Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions c.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,11 @@ func insnToC(insn instruction, blk *block) ([]string, error) {
case bpf.ALUOpConstant:
return stat("a %s= %d;", aluToCOp[i.Op], i.Val)
case bpf.ALUOpX:
// Shifts >=32 are undefined behavior in C.
// https://elixir.bootlin.com/linux/v7.2/source/kernel/bpf/core.c#L1899
if i.Op == bpf.ALUOpShiftLeft || i.Op == bpf.ALUOpShiftRight {
return stat("a %s= (x & 31);", aluToCOp[i.Op])
}
return stat("a %s= x;", aluToCOp[i.Op])
case bpf.NegateA:
return stat("a = -a;")
Expand Down
9 changes: 8 additions & 1 deletion insn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -526,10 +526,15 @@ func checkAlu(t *testing.T, op bpf.ALUOp, a, b, res uint32) {
}

checkBackends(t, constFilter, []byte{}, match)
checkAluX(t, op, a, b, res)
}

func checkAluX(t *testing.T, op bpf.ALUOp, a, x, res uint32) {
t.Helper()

xFilter := []bpf.Instruction{
bpf.LoadConstant{Dst: bpf.RegA, Val: a},
bpf.LoadConstant{Dst: bpf.RegX, Val: b},
bpf.LoadConstant{Dst: bpf.RegX, Val: x},

bpf.ALUOpX{Op: op},

Expand Down Expand Up @@ -623,6 +628,7 @@ func TestALUShiftLeft(t *testing.T) {
checkAlu(t, bpf.ALUOpShiftLeft, 1, 0, 1)
checkAlu(t, bpf.ALUOpShiftLeft, 1, 4, 0x10)
checkAlu(t, bpf.ALUOpShiftLeft, 1, 31, 0x80000000)
checkAluX(t, bpf.ALUOpShiftLeft, 1, 32, 1)
}

func TestALUShiftRight(t *testing.T) {
Expand All @@ -631,6 +637,7 @@ func TestALUShiftRight(t *testing.T) {
checkAlu(t, bpf.ALUOpShiftRight, 0xF0, 4, 0x0F)
checkAlu(t, bpf.ALUOpShiftRight, 0xF0, 8, 0)
checkAlu(t, bpf.ALUOpShiftRight, 0x80000000, 31, 1)
checkAluX(t, bpf.ALUOpShiftRight, 0x80000000, 32, 0x80000000)
}

func TestALUMod(t *testing.T) {
Expand Down
Loading