David K. Bainbridge | 215e024 | 2017-09-05 23:18:24 -0700 | [diff] [blame] | 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 | |
| 5 | package bpf |
| 6 | |
| 7 | import "fmt" |
| 8 | |
| 9 | // Assemble converts insts into raw instructions suitable for loading |
| 10 | // into a BPF virtual machine. |
| 11 | // |
| 12 | // Currently, no optimization is attempted, the assembled program flow |
| 13 | // is exactly as provided. |
| 14 | func Assemble(insts []Instruction) ([]RawInstruction, error) { |
| 15 | ret := make([]RawInstruction, len(insts)) |
| 16 | var err error |
| 17 | for i, inst := range insts { |
| 18 | ret[i], err = inst.Assemble() |
| 19 | if err != nil { |
| 20 | return nil, fmt.Errorf("assembling instruction %d: %s", i+1, err) |
| 21 | } |
| 22 | } |
| 23 | return ret, nil |
| 24 | } |
| 25 | |
| 26 | // Disassemble attempts to parse raw back into |
| 27 | // Instructions. Unrecognized RawInstructions are assumed to be an |
| 28 | // extension not implemented by this package, and are passed through |
| 29 | // unchanged to the output. The allDecoded value reports whether insts |
| 30 | // contains no RawInstructions. |
| 31 | func Disassemble(raw []RawInstruction) (insts []Instruction, allDecoded bool) { |
| 32 | insts = make([]Instruction, len(raw)) |
| 33 | allDecoded = true |
| 34 | for i, r := range raw { |
| 35 | insts[i] = r.Disassemble() |
| 36 | if _, ok := insts[i].(RawInstruction); ok { |
| 37 | allDecoded = false |
| 38 | } |
| 39 | } |
| 40 | return insts, allDecoded |
| 41 | } |