|
| 1 | +package main |
| 2 | + |
| 3 | +import "C" |
| 4 | + |
| 5 | +import ( |
| 6 | + "log" |
| 7 | + "syscall" |
| 8 | + "unsafe" |
| 9 | + |
| 10 | + bpf "github.com/aquasecurity/libbpfgo" |
| 11 | +) |
| 12 | + |
| 13 | +const ( |
| 14 | + BPFMapNameToNotFind = "not_found" |
| 15 | + // The following properties are used to identify the map |
| 16 | + BPFMapNameToFind = "test_name" |
| 17 | + BPFMapTypeToFind = bpf.MapTypeArray |
| 18 | + BPFMapMaxEntriesToFind = 1 |
| 19 | + BPFMapKeySizeToFind = 4 |
| 20 | + BPFMapValSizeToFind = 4 |
| 21 | +) |
| 22 | + |
| 23 | +func main() { |
| 24 | + bpfModule, err := bpf.NewModuleFromFile("main.bpf.o") |
| 25 | + if err != nil { |
| 26 | + log.Fatal(err) |
| 27 | + } |
| 28 | + defer bpfModule.Close() |
| 29 | + |
| 30 | + bpfModule.BPFLoadObject() |
| 31 | + |
| 32 | + notFoundMapsIDs, err := bpf.GetMapsIDsByName(BPFMapNameToNotFind) |
| 33 | + if len(notFoundMapsIDs) != 0 { |
| 34 | + log.Fatalf("the %s map should not be found, but it was found with ids: %v", BPFMapNameToNotFind, notFoundMapsIDs) |
| 35 | + } |
| 36 | + |
| 37 | + mapsIDs, err := bpf.GetMapsIDsByName(BPFMapNameToFind) |
| 38 | + if err != nil { |
| 39 | + log.Fatal(err) |
| 40 | + } |
| 41 | + if len(mapsIDs) == 0 { |
| 42 | + log.Fatalf("the %s map was not found", BPFMapNameToFind) |
| 43 | + } |
| 44 | + |
| 45 | + // try to identify the map by its properties |
| 46 | + similarMaps := []*bpf.BPFMapLow{} |
| 47 | + for _, id := range mapsIDs { |
| 48 | + bpfMap, err := bpf.GetMapByID(id) |
| 49 | + if err != nil { |
| 50 | + log.Fatalf("the %s map with %d id was not found: %v", BPFMapNameToFind, id, err) |
| 51 | + } |
| 52 | + |
| 53 | + if bpfMap.Type() == BPFMapTypeToFind && |
| 54 | + bpfMap.MaxEntries() == BPFMapMaxEntriesToFind && |
| 55 | + bpfMap.KeySize() == BPFMapKeySizeToFind && |
| 56 | + bpfMap.ValueSize() == BPFMapValSizeToFind { |
| 57 | + // found a map with the same properties |
| 58 | + similarMaps = append(similarMaps, bpfMap) |
| 59 | + } else { |
| 60 | + if err := syscall.Close(bpfMap.FileDescriptor()); err != nil { |
| 61 | + log.Fatalf("failed to close the file descriptor of the %s map with %d id: %v", BPFMapNameToFind, id, err) |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + if len(similarMaps) == 0 { |
| 67 | + log.Fatalf("no %s maps with the same properties found", BPFMapNameToFind) |
| 68 | + } |
| 69 | + if len(similarMaps) > 1 { |
| 70 | + // This is a conundrum for the user, as they cannot decide which map to use |
| 71 | + // automatically. Perhaps they should change the name of the map to make it |
| 72 | + // unique. |
| 73 | + _ = 0 |
| 74 | + } |
| 75 | + |
| 76 | + // use the first map of the similar ones |
| 77 | + bpfMap := similarMaps[0] |
| 78 | + |
| 79 | + key1 := uint32(0) |
| 80 | + value1 := uint32(55) |
| 81 | + if err := bpfMap.Update(unsafe.Pointer(&key1), unsafe.Pointer(&value1)); err != nil { |
| 82 | + log.Fatal(err) |
| 83 | + } |
| 84 | +} |
0 commit comments