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.
12 // A VM is an emulated BPF virtual machine.
17 // NewVM returns a new VM using the input BPF program.
18 func NewVM(filter []Instruction) (*VM, error) {
20 return nil, errors.New("one or more Instructions must be specified")
23 for i, ins := range filter {
24 check := len(filter) - (i + 1)
25 switch ins := ins.(type) {
26 // Check for out-of-bounds jumps in instructions
28 if check <= int(ins.Skip) {
29 return nil, fmt.Errorf("cannot jump %d instructions; jumping past program bounds", ins.Skip)
32 if check <= int(ins.SkipTrue) {
33 return nil, fmt.Errorf("cannot jump %d instructions in true case; jumping past program bounds", ins.SkipTrue)
35 if check <= int(ins.SkipFalse) {
36 return nil, fmt.Errorf("cannot jump %d instructions in false case; jumping past program bounds", ins.SkipFalse)
38 // Check for division or modulus by zero
45 case ALUOpDiv, ALUOpMod:
46 return nil, errors.New("cannot divide by zero using ALUOpConstant")
48 // Check for unknown extensions
53 return nil, fmt.Errorf("extension %d not implemented", ins.Num)
58 // Make sure last instruction is a return instruction
59 switch filter[len(filter)-1].(type) {
60 case RetA, RetConstant:
62 return nil, errors.New("BPF program must end with RetA or RetConstant")
65 // Though our VM works using disassembled instructions, we
66 // attempt to assemble the input filter anyway to ensure it is compatible
67 // with an operating system VM.
68 _, err := Assemble(filter)
75 // Run runs the VM's BPF program against the input bytes.
76 // Run returns the number of bytes accepted by the BPF program, and any errors
77 // which occurred while processing the program.
78 func (v *VM) Run(in []byte) (int, error) {
80 // Registers of the virtual machine
85 // OK is true if the program should continue processing the next
86 // instruction, or false if not, causing the loop to break
90 // TODO(mdlayher): implement:
92 // - would require a change from uint32 registers to int32
95 // TODO(mdlayher): add interop tests that check signedness of ALU
96 // operations against kernel implementation, and make sure Go
97 // implementation matches behavior
99 for i := 0; i < len(v.filter) && ok; i++ {
102 switch ins := ins.(type) {
104 regA = aluOpConstant(ins, regA)
106 regA, ok = aluOpX(ins, regA, regX)
110 jump := jumpIf(ins, regA)
113 regA, ok = loadAbsolute(ins, in)
115 regA, regX = loadConstant(ins, regA, regX)
117 regA = loadExtension(ins, in)
119 regA, ok = loadIndirect(ins, in, regX)
121 regX, ok = loadMemShift(ins, in)
123 regA, regX = loadScratch(ins, regScratch, regA, regX)
125 return int(regA), nil
127 return int(ins.Val), nil
129 regScratch = storeScratch(ins, regScratch, regA, regX)
135 return 0, fmt.Errorf("unknown Instruction at index %d: %T", i, ins)