Skip to content

Commit

Permalink
Fix error message in BPFMap.Update (#29)
Browse files Browse the repository at this point in the history
When trying to obtain an unsafe pointer to the value type, upon failure
the code was incorrectly returning an error message which contained the
type of the key, not the value. This patch fixes it so that the correct
type is returned for the value in the error message.

Additionally this commit contains a small refactor which uses a type
switch rather than if-else statements for readability.
  • Loading branch information
derekparker authored Jul 7, 2021
1 parent 2245dce commit 8ce3840
Showing 1 changed file with 11 additions and 10 deletions.
21 changes: 11 additions & 10 deletions libbpfgo.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,8 +195,8 @@ import "C"

import (
"fmt"
"path/filepath"
"net"
"path/filepath"
"strings"
"sync"
"syscall"
Expand Down Expand Up @@ -442,21 +442,22 @@ func (b *BPFMap) GetMaxEntries() uint32 {

func GetUnsafePointer(data interface{}) (unsafe.Pointer, error) {
var dataPtr unsafe.Pointer
if k, isType := data.(int8); isType {
switch k := data.(type) {
case int8:
dataPtr = unsafe.Pointer(&k)
} else if k, isType := data.(uint8); isType {
case uint8:
dataPtr = unsafe.Pointer(&k)
} else if k, isType := data.(int32); isType {
case int32:
dataPtr = unsafe.Pointer(&k)
} else if k, isType := data.(uint32); isType {
case uint32:
dataPtr = unsafe.Pointer(&k)
} else if k, isType := data.(int64); isType {
case int64:
dataPtr = unsafe.Pointer(&k)
} else if k, isType := data.(uint64); isType {
case uint64:
dataPtr = unsafe.Pointer(&k)
} else if k, isType := data.([]byte); isType {
case []byte:
dataPtr = unsafe.Pointer(&k[0])
} else {
default:
return nil, fmt.Errorf("unknown data type %T", data)
}

Expand Down Expand Up @@ -507,7 +508,7 @@ func (b *BPFMap) Update(key, value interface{}) error {
}
valuePtr, err := GetUnsafePointer(value)
if err != nil {
return fmt.Errorf("failed to update map %s: unknown value type %T", b.name, key)
return fmt.Errorf("failed to update map %s: unknown value type %T", b.name, value)
}

errC := C.bpf_map_update_elem(b.fd, keyPtr, valuePtr, C.BPF_ANY)
Expand Down

0 comments on commit 8ce3840

Please sign in to comment.