Skip to content

Commit

Permalink
btf: fix race in mutableTypes.copy
Browse files Browse the repository at this point in the history
We reference mt.copiedTypeIDs during copy to be able to figure out
the correct ID for a copied type. This access can currently race
with mutableTypes.add since we don't protect mt.copiedTypeIDs.

Take a read lock to prevent modification.

Signed-off-by: Lorenz Bauer <lmb@isovalent.com>
  • Loading branch information
lmb committed Feb 22, 2024
1 parent 26065e7 commit d80392a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
4 changes: 4 additions & 0 deletions btf/btf.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,10 @@ func (mt *mutableTypes) copy() mutableTypes {
make(map[Type]TypeID, len(mt.copiedTypeIDs)),
}

// Prevent concurrent modification of mt.copiedTypeIDs.
mt.mu.RLock()
defer mt.mu.RUnlock()

copies := make(map[Type]Type, len(mt.copies))
for orig, copy := range mt.copies {
// NB: We make a copy of copy, not orig, so that changes to mutable types
Expand Down
8 changes: 6 additions & 2 deletions btf/btf_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -542,12 +542,16 @@ func TestSpecConcurrentAccess(t *testing.T) {
go func() {
defer wg.Done()

cond.Add(1)
n := cond.Add(1)
for cond.Load() != int64(maxprocs) {
// Spin to increase the chances of a race.
}

_, _ = spec.AnyTypeByName("gov_update_cpu_data")
if n%2 == 0 {
_, _ = spec.AnyTypeByName("gov_update_cpu_data")
} else {
_ = spec.Copy()
}
}()

// Try to get the Goroutines scheduled and spinning.
Expand Down

0 comments on commit d80392a

Please sign in to comment.