Skip to content

Commit

Permalink
Fix possible MatProfile race by ordering remove before free.
Browse files Browse the repository at this point in the history
When building with `-tags matprofile` set, gocv will occasionally panic due to a
duplicate pointer added to the pprof Profile:
#851 (comment)

The pointer added comes directly from new (via Mat_New). Assuming correct memory
allocator behavior, that means that we must be inserting a pointer which was
previously deleted.

Since the pointer is currently removed from the Profile *after* it is freed,
there's a possible data race in multithreaded applications where `new` gives us
back a deleted pointer immediately and we insert it before we have a chance to
remove it from the profile, triggering this condition.

I'm not completely certain this resolves the issue since the race is extremely
difficult to reproduce.
  • Loading branch information
jheidel authored and deadprogram committed Jun 11, 2021
1 parent 71be5aa commit 4c86e5f
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion mat_profile.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,10 @@ func newMat(p C.Mat) Mat {

// Close the Mat object.
func (m *Mat) Close() error {
C.Mat_Close(m.p)
// NOTE: The pointer must be removed from the profile before it is deleted to
// avoid a data race.
MatProfile.Remove(m.p)
C.Mat_Close(m.p)
m.p = nil
m.d = nil
return nil
Expand Down

0 comments on commit 4c86e5f

Please sign in to comment.