From d80392aacf3c642e39daff2cb8d77e3269accf55 Mon Sep 17 00:00:00 2001 From: Lorenz Bauer Date: Thu, 22 Feb 2024 15:27:50 +0000 Subject: [PATCH] btf: fix race in mutableTypes.copy 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 --- btf/btf.go | 4 ++++ btf/btf_test.go | 8 ++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/btf/btf.go b/btf/btf.go index 1268a4135..74a17a9e1 100644 --- a/btf/btf.go +++ b/btf/btf.go @@ -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 diff --git a/btf/btf_test.go b/btf/btf_test.go index 02e6b5fad..d2a043e46 100644 --- a/btf/btf_test.go +++ b/btf/btf_test.go @@ -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.