Skip to content

Commit

Permalink
asm: refuse marshaling unknown extended opcodes
Browse files Browse the repository at this point in the history
We currently rely on the low byte of OpCode to be a valid BPF opcode.
Make this clearer by adding a method to OpCode. This allows us to
reject invalid extended opcodes during marshaling.

Signed-off-by: Lorenz Bauer <[email protected]>
  • Loading branch information
lmb committed Nov 8, 2023
1 parent c34b971 commit bc2ae59
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
7 changes: 6 additions & 1 deletion asm/instruction.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,13 @@ func (ins Instruction) Marshal(w io.Writer, bo binary.ByteOrder) (uint64, error)
ins.Offset = newOffset
}

op, err := ins.OpCode.bpfOpCode()
if err != nil {
return 0, err
}

data := make([]byte, InstructionSize)
data[0] = byte(ins.OpCode)
data[0] = op
data[1] = byte(regs)
bo.PutUint16(data[2:4], uint16(ins.Offset))
bo.PutUint32(data[4:8], uint32(cons))
Expand Down
11 changes: 11 additions & 0 deletions asm/opcode.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,17 @@ type OpCode uint16
// InvalidOpCode is returned by setters on OpCode
const InvalidOpCode OpCode = 0xffff

// bpfOpCode returns the actual BPF opcode.
func (op OpCode) bpfOpCode() (byte, error) {
const opCodeMask = 0xff

if !valid(op, opCodeMask) {
return 0, fmt.Errorf("invalid opcode %x", op)
}

return byte(op & opCodeMask), nil
}

// rawInstructions returns the number of BPF instructions required
// to encode this opcode.
func (op OpCode) rawInstructions() int {
Expand Down

0 comments on commit bc2ae59

Please sign in to comment.