diff --git a/libbpfgo.go b/libbpfgo.go index 2aa77585..afff64a8 100644 --- a/libbpfgo.go +++ b/libbpfgo.go @@ -394,8 +394,14 @@ func bpfMapCreateOptsToC(createOpts *BPFMapCreateOpts) *C.struct_bpf_map_create_ return &opts } -// CreateMap returns file descriptor of newly created map -func (m *Module) CreateMap(mapType MapType, mapName string, keySize, valueSize, maxEntries int, opts *BPFMapCreateOpts) (*BPFMap, error) { +// CreateMap creates a BPF map from userspace. This can be used for populating +// BPF array of maps or hash of maps. However, this function uses a low-level +// libbpf API; maps created in this way do not conform to libbpf map formats, +// and therefore do not have access to libbpf high level bpf_map__* APIS +// which causes different behavior from maps created in the kernel side code +// +// See usage of `bpf_map_create()` in kernel selftests for more info +func CreateMap(mapType MapType, mapName string, keySize, valueSize, maxEntries int, opts *BPFMapCreateOpts) (*BPFMap, error) { cs := C.CString(mapName) fdOrError := C.bpf_map_create(uint32(mapType), cs, C.uint(keySize), C.uint(valueSize), C.uint(maxEntries), bpfMapCreateOptsToC(opts)) C.free(unsafe.Pointer(cs)) @@ -405,9 +411,9 @@ func (m *Module) CreateMap(mapType MapType, mapName string, keySize, valueSize, return &BPFMap{ name: mapName, - bpfMap: nil, //FIXME: find by name? fd: fdOrError, - module: m, + module: nil, + bpfMap: nil, }, nil } diff --git a/selftest/create-map/main.go b/selftest/create-map/main.go index 4ff6dc3f..74ae1bdc 100644 --- a/selftest/create-map/main.go +++ b/selftest/create-map/main.go @@ -6,16 +6,12 @@ import ( "fmt" "log" "os" - "time" + "unsafe" "github.com/aquasecurity/libbpfgo" bpf "github.com/aquasecurity/libbpfgo" ) -func getSupposedPinPath(m *bpf.BPFMap) string { - return "/sys/fs/bpf/" + m.GetName() -} - func main() { bpfModule, err := bpf.NewModuleFromFile("main.bpf.o") if err != nil { @@ -25,13 +21,20 @@ func main() { defer bpfModule.Close() bpfModule.BPFLoadObject() + opts := bpf.BPFMapCreateOpts{} + opts.Size = uint64(unsafe.Sizeof(opts)) - m, err := bpfModule.CreateMap(libbpfgo.MapTypeArray, "foobar", 1, 1, 1, nil) + m, err := libbpfgo.CreateMap(libbpfgo.MapTypeHash, "foobar", 4, 4, 420, nil) if err != nil { - log.Fatal(m, err) + log.Fatal(err) } - fmt.Println(m) - - time.Sleep(time.Second * 30) + key1 := uint32(1) + value1 := uint32(55) + key1Unsafe := unsafe.Pointer(&key1) + value1Unsafe := unsafe.Pointer(&value1) + err = m.Update(key1Unsafe, value1Unsafe) + if err != nil { + log.Fatal(err) + } }