Berkeley Packet Filter (BPF) assembler.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.2KB

  1. package bpf_test
  2. import (
  3. "testing"
  4. gobpf "golang.org/x/net/bpf"
  5. "maze.io/x/bpf"
  6. )
  7. // udpHeaderLen is the length of a UDP header.
  8. const udpHeaderLen = 8
  9. type testVirtualMachine struct {
  10. *bpf.VM
  11. }
  12. func (vm *testVirtualMachine) Run(in []byte) (uint32, error) {
  13. out, err := vm.VM.Run(in)
  14. // All tests have a UDP header as part of input, because the OS VM
  15. // packets always will. For the Go VM, this output is trimmed before
  16. // being sent back to tests.
  17. if out >= udpHeaderLen {
  18. out -= udpHeaderLen
  19. }
  20. // If Go output is larger than the size of the packet, packet filtering
  21. // interop tests must trim the output bytes to the length of the packet.
  22. // The BPF VM should not do this on its own, as other uses of it do
  23. // not trim the output byte count.
  24. trim := uint32(len(in) - udpHeaderLen)
  25. if out > trim {
  26. out = trim
  27. }
  28. return out, err
  29. }
  30. func testVM(t *testing.T, instructions []gobpf.Instruction) (*testVirtualMachine, error) {
  31. t.Helper()
  32. v := bpf.NewVM(instructions)
  33. if err := v.Verify(); err != nil {
  34. return nil, err
  35. }
  36. return &testVirtualMachine{v}, nil
  37. }
  38. // errStr returns the string representation of an error, or
  39. // "<nil>" if it is nil.
  40. func errStr(err error) string {
  41. if err == nil {
  42. return "<nil>"
  43. }
  44. return err.Error()
  45. }