Skip to content

Commit

Permalink
prog, map: add nil checks in value marshalers
Browse files Browse the repository at this point in the history
In case of programs or maps as map value types, the value marshaling
results in a panic in case of a nil pointer. For other types this is not a
problem since sysenc.Marshal does a nil check.

This commit adds a nil check to the internal helper for marshaling
programs and maps.

Signed-off-by: Tobias Böhm <[email protected]>
  • Loading branch information
aibor authored and ti-mo committed Nov 12, 2024
1 parent 9894d25 commit e521b5b
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 0 deletions.
4 changes: 4 additions & 0 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -1589,6 +1589,10 @@ func unmarshalMap(buf sysenc.Buffer) (*Map, error) {

// marshalMap marshals the fd of a map into a buffer in host endianness.
func marshalMap(m *Map, length int) ([]byte, error) {
if m == nil {
return nil, errors.New("can't marshal a nil Map")
}

if length != 4 {
return nil, fmt.Errorf("can't marshal map to %d bytes", length)
}
Expand Down
4 changes: 4 additions & 0 deletions map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,10 @@ func TestMapInMap(t *testing.T) {
t.Fatal("Can't put inner map:", err)
}

if err := outer.Put(uint32(0), (*Map)(nil)); err == nil {
t.Fatal("Put accepted a nil Map")
}

var inner2 *Map
if err := outer.Lookup(uint32(0), &inner2); err != nil {
t.Fatal("Can't lookup 0:", err)
Expand Down
4 changes: 4 additions & 0 deletions prog.go
Original file line number Diff line number Diff line change
Expand Up @@ -893,6 +893,10 @@ func unmarshalProgram(buf sysenc.Buffer) (*Program, error) {
}

func marshalProgram(p *Program, length int) ([]byte, error) {
if p == nil {
return nil, errors.New("can't marshal a nil Program")
}

if length != 4 {
return nil, fmt.Errorf("can't marshal program to %d bytes", length)
}
Expand Down
4 changes: 4 additions & 0 deletions prog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,10 @@ func TestProgramMarshaling(t *testing.T) {
arr := createProgramArray(t)
defer arr.Close()

if err := arr.Put(idx, (*Program)(nil)); err == nil {
t.Fatal("Put accepted a nil Program")
}

prog := mustSocketFilter(t)

if err := arr.Put(idx, prog); err != nil {
Expand Down

0 comments on commit e521b5b

Please sign in to comment.