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.

vm_test.go 1.5KB

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