asm.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package bpf
  5. import "fmt"
  6. // Assemble converts insts into raw instructions suitable for loading
  7. // into a BPF virtual machine.
  8. //
  9. // Currently, no optimization is attempted, the assembled program flow
  10. // is exactly as provided.
  11. func Assemble(insts []Instruction) ([]RawInstruction, error) {
  12. ret := make([]RawInstruction, len(insts))
  13. var err error
  14. for i, inst := range insts {
  15. ret[i], err = inst.Assemble()
  16. if err != nil {
  17. return nil, fmt.Errorf("assembling instruction %d: %s", i+1, err)
  18. }
  19. }
  20. return ret, nil
  21. }
  22. // Disassemble attempts to parse raw back into
  23. // Instructions. Unrecognized RawInstructions are assumed to be an
  24. // extension not implemented by this package, and are passed through
  25. // unchanged to the output. The allDecoded value reports whether insts
  26. // contains no RawInstructions.
  27. func Disassemble(raw []RawInstruction) (insts []Instruction, allDecoded bool) {
  28. insts = make([]Instruction, len(raw))
  29. allDecoded = true
  30. for i, r := range raw {
  31. insts[i] = r.Disassemble()
  32. if _, ok := insts[i].(RawInstruction); ok {
  33. allDecoded = false
  34. }
  35. }
  36. return insts, allDecoded
  37. }