Skip to content

Commit

Permalink
sharedlibraries: Replace sync.Once with sync.Mutex
Browse files Browse the repository at this point in the history
Preliminary change to replace the sync.Once with a mutex, to better handle access to the
EBPF program singleton
  • Loading branch information
guyarb committed Dec 4, 2024
1 parent a89384b commit be68b4d
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions pkg/network/usm/sharedlibraries/ebpf.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,12 @@ const (
openat2SysCall = "openat2"
)

var traceTypes = []string{"enter", "exit"}
var (
singletonMutex = sync.Mutex{}
progSingleton *EbpfProgram

var progSingletonOnce sync.Once
var progSingleton *EbpfProgram
traceTypes = []string{"enter", "exit"}
)

// LibraryCallback defines the type of the callback function that will be called when a shared library event is detected
type LibraryCallback func(LibPath)
Expand Down Expand Up @@ -127,7 +129,10 @@ func IsSupported(cfg *ddebpf.Config) bool {

// GetEBPFProgram returns an instance of the shared libraries eBPF program singleton
func GetEBPFProgram(cfg *ddebpf.Config) *EbpfProgram {
progSingletonOnce.Do(func() {
singletonMutex.Lock()
defer singletonMutex.Unlock()

if progSingleton == nil {
progSingleton = &EbpfProgram{
cfg: cfg,
libsets: make(map[Libset]*libsetHandler),
Expand All @@ -140,7 +145,8 @@ func GetEBPFProgram(cfg *ddebpf.Config) *EbpfProgram {
callbacks: make(map[*LibraryCallback]struct{}),
}
}
})
}

progSingleton.refcount.Inc()

return progSingleton
Expand Down Expand Up @@ -438,6 +444,9 @@ func (e *EbpfProgram) Subscribe(callback LibraryCallback, libsets ...Libset) (fu

// Stop stops the eBPF program if the refcount reaches 0
func (e *EbpfProgram) Stop() {
singletonMutex.Lock()
defer singletonMutex.Unlock()

if e.refcount.Dec() != 0 {
if e.refcount.Load() < 0 {
e.refcount.Swap(0)
Expand All @@ -451,8 +460,6 @@ func (e *EbpfProgram) Stop() {

e.stopImpl()

// Reset the program singleton in case it's used again (e.g. in tests)
progSingletonOnce = sync.Once{}
progSingleton = nil
}

Expand Down

0 comments on commit be68b4d

Please sign in to comment.