| 1 |
package cbpfc |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"strings" |
| 6 |
"testing" |
| 7 |
|
| 8 |
"github.com/cilium/ebpf" |
| 9 |
"golang.org/x/net/bpf" |
| 10 |
) |
| 11 |
|
| 12 |
func TestFunctionName(t *testing.T) { |
| 13 |
checkName := func(t *testing.T, name string, valid bool) { |
| 14 |
t.Helper() |
| 15 |
|
| 16 |
_, err := ToC([]bpf.Instruction{bpf.RetA{}}, COpts{ |
| 17 |
FunctionName: name, |
| 18 |
}) |
| 19 |
if valid && err != nil { |
| 20 |
t.Fatalf("valid function name %s rejected: %v", name, err) |
| 21 |
} |
| 22 |
if !valid { |
| 23 |
requireError(t, err, "invalid FunctionName") |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
checkName(t, "", false) |
| 28 |
checkName(t, "0foo", false) |
| 29 |
checkName(t, "0foo\nfoo", false) |
| 30 |
checkName(t, "foo_bar2", true) |
| 31 |
checkName(t, "a2", true) |
| 32 |
} |
| 33 |
|
| 34 |
func TestToCNoInline(t *testing.T) { |
| 35 |
elf, err := ToC([]bpf.Instruction{ |
| 36 |
bpf.RetConstant{Val: 1}, |
| 37 |
}, COpts{ |
| 38 |
FunctionName: "filter", |
| 39 |
NoInline: true, |
| 40 |
}) |
| 41 |
if err != nil { |
| 42 |
t.Fatal(err) |
| 43 |
} |
| 44 |
|
| 45 |
if strings.Contains(elf, "__always_inline__") { |
| 46 |
t.Fatal("generated C source should not contain __always_inline__ when NoInline is true") |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
func TestNoInline(t *testing.T) { |
| 51 |
elf, err := buildC([]bpf.Instruction{ |
| 52 |
bpf.RetConstant{Val: 1}, |
| 53 |
}, entryPoint, COpts{ |
| 54 |
FunctionName: "filter", |
| 55 |
NoInline: true, |
| 56 |
}) |
| 57 |
if err != nil { |
| 58 |
t.Fatal(err) |
| 59 |
} |
| 60 |
|
| 61 |
spec, err := ebpf.LoadCollectionSpecFromReader(bytes.NewReader(elf)) |
| 62 |
if err != nil { |
| 63 |
t.Fatal(err) |
| 64 |
} |
| 65 |
|
| 66 |
in := make([]byte, 14) |
| 67 |
if res := testProg(t, spec.Programs[entryPoint], in); res != match { |
| 68 |
t.Fatalf("expected match, got %v", res) |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
const entryPoint = "xdp_filter" |
| 73 |
|
| 74 |
|
| 75 |
func cBackend(tb testing.TB, insns []bpf.Instruction, in []byte, opts backendOpts) result { |
| 76 |
elf, err := buildC(insns, entryPoint, COpts{FunctionName: "filter", PacketStartMaxOffset: opts.offset}) |
| 77 |
if err != nil { |
| 78 |
tb.Fatal(err) |
| 79 |
} |
| 80 |
|
| 81 |
|
| 82 |
spec, err := ebpf.LoadCollectionSpecFromReader(bytes.NewReader(elf)) |
| 83 |
if err != nil { |
| 84 |
tb.Fatal(err) |
| 85 |
} |
| 86 |
|
| 87 |
return testProg(tb, spec.Programs[entryPoint], in) |
| 88 |
} |