Skip to content

Commit

Permalink
feat: GetMapsIdsByName
Browse files Browse the repository at this point in the history
Allow a user to get a list of maps Ids filtered by map name.
  • Loading branch information
aymericDD committed Sep 13, 2023
1 parent 585cbd5 commit 6c53f03
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 11 deletions.
17 changes: 11 additions & 6 deletions libbpfgo.go
Original file line number Diff line number Diff line change
Expand Up @@ -393,31 +393,36 @@ 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)

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)
}
}

Expand Down
19 changes: 14 additions & 5 deletions selftest/map-get-maps-by-name/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
}
Expand Down

0 comments on commit 6c53f03

Please sign in to comment.