Files
golang.net/bpf/asm.go
David Anderson 3c208088b6 bpf: new package to assemble and disassemble Berkeley Packet Filter programs.
The package currently implements the operations defined by
https://www.kernel.org/doc/Documentation/networking/filter.txt , which
comprises the base BPF virtual machine plus the Linux kernel's extension
opcodes.

Updates golang/go#14982

Change-Id: Iafb43d80e067040e60465a9bfb7d5f2ca90cc2ae
Reviewed-on: https://go-review.googlesource.com/21212
Reviewed-by: Mikio Hara <mikioh.mikioh@gmail.com>
2016-03-28 06:22:12 +00:00

42 lines
1.2 KiB
Go

// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bpf
import "fmt"
// Assemble converts insts into raw instructions suitable for loading
// into a BPF virtual machine.
//
// Currently, no optimization is attempted, the assembled program flow
// is exactly as provided.
func Assemble(insts []Instruction) ([]RawInstruction, error) {
ret := make([]RawInstruction, len(insts))
var err error
for i, inst := range insts {
ret[i], err = inst.Assemble()
if err != nil {
return nil, fmt.Errorf("assembling instruction %d: %s", i+1, err)
}
}
return ret, nil
}
// Disassemble attempts to parse raw back into
// Instructions. Unrecognized RawInstructions are assumed to be an
// extension not implemented by this package, and are passed through
// unchanged to the output. The allDecoded value reports whether insts
// contains no RawInstructions.
func Disassemble(raw []RawInstruction) (insts []Instruction, allDecoded bool) {
insts = make([]Instruction, len(raw))
allDecoded = true
for i, r := range raw {
insts[i] = r.Disassemble()
if _, ok := insts[i].(RawInstruction); ok {
allDecoded = false
}
}
return insts, allDecoded
}