diff --git a/libbpfgo.go b/libbpfgo.go index beffa54d..9e0c3e39 100644 --- a/libbpfgo.go +++ b/libbpfgo.go @@ -393,9 +393,10 @@ func (m *Module) InitGlobalVariable(name string, value interface{}) error { return err } -// GetMapsByName retrieves BPF maps with the specified name. -func GetMapsByName(name string) []*BPFMapLow { - bpfMaps := []*BPFMapLow{} +// GetMapsIdsByName searches for maps with a given name. +// It returns a slice of unsigned 32-bit integers representing the IDs of matching maps. +func GetMapsIdsByName(name string) []uint32 { + bpfMapsIds := []uint32{} startId := C.uint(0) nextId := C.uint(0) @@ -403,21 +404,25 @@ func GetMapsByName(name string) []*BPFMapLow { for { err := C.bpf_map_get_next_id(startId, &nextId) if err != 0 { - return bpfMaps + return bpfMapsIds } startId = nextId + 1 bpfMapLow, errMap := GetMapByID(uint32(nextId)) if errMap != nil { - return bpfMaps + return bpfMapsIds + } + + if err := syscall.Close(bpfMapLow.FileDescriptor()); err != nil { + return bpfMapsIds } if bpfMapLow.Name() != name { continue } - bpfMaps = append(bpfMaps, bpfMapLow) + bpfMapsIds = append(bpfMapsIds, bpfMapLow.info.ID) } } diff --git a/selftest/map-get-maps-by-name/main.go b/selftest/map-get-maps-by-name/main.go index afd90bae..9308d1ab 100644 --- a/selftest/map-get-maps-by-name/main.go +++ b/selftest/map-get-maps-by-name/main.go @@ -10,6 +10,8 @@ import ( bpf "github.com/aquasecurity/libbpfgo" ) +const BPFMapName = "test" + func main() { bpfModule, err := bpf.NewModuleFromFile("main.bpf.o") if err != nil { @@ -20,16 +22,23 @@ func main() { bpfModule.BPFLoadObject() - testMaps := bpf.GetMapsByName("test") - if len(testMaps) == 0 { - fmt.Fprintln(os.Stderr, fmt.Errorf("no maps found")) + mapsIdS := bpf.GetMapsIdsByName(BPFMapName) + if len(mapsIdS) == 0 { + fmt.Fprintln(os.Stderr, fmt.Errorf("no maps found for the %s map", BPFMapName)) + os.Exit(-1) + } + + bpfMapId := mapsIdS[0] + + bpfMap, err := bpf.GetMapByID(bpfMapId) + if err != nil { + fmt.Fprintln(os.Stderr, fmt.Errorf("the %s map with %d id not found: %w", BPFMapName, bpfMapId, err)) os.Exit(-1) } - testMap := testMaps[0] key1 := uint32(0) value1 := uint32(55) - if err := testMap.Update(unsafe.Pointer(&key1), unsafe.Pointer(&value1)); err != nil { + if err := bpfMap.Update(unsafe.Pointer(&key1), unsafe.Pointer(&value1)); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(-1) }