Skip to content

Commit

Permalink
Add godoc comment
Browse files Browse the repository at this point in the history
Signed-off-by: grantseltzer <grantseltzer@gmail.com>
  • Loading branch information
grantseltzer committed Mar 15, 2022
1 parent cb1f55a commit 2f2b397
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 14 deletions.
14 changes: 10 additions & 4 deletions libbpfgo.go
Expand Up @@ -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))
Expand All @@ -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
}

Expand Down
23 changes: 13 additions & 10 deletions selftest/create-map/main.go
Expand Up @@ -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 {
Expand All @@ -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)
}
}

0 comments on commit 2f2b397

Please sign in to comment.