qmonnet / rbpf

Rust virtual machine and JIT compiler for eBPF programs
Apache License 2.0
922 stars 235 forks source link

src/jit.rs: Fix offset when skipping insns for handling divisions by 0 #89

Closed qmonnet closed 1 year ago

qmonnet commented 1 year ago

When dividing by the content of a register, we have a specific case to handle divisions by zero. When the denominator is not 0, we skip the related instructions by emitted a near jump with the relevant offset.

However, this offset was incorrect. We accounted for two instructions: a 2-byte long XOR of the destination register with itself to set it to 0, and a 5-byte long jump. The former may in fact emit 3 bytes under certain condition, depending on the destination in use. For example, when dividing from r7, we emit 3 bytes, and the fixed offset of 7 bytes we used is incorrect, and triggers a segfault.

To fix this, let's add a check to determine the offset value we should use. We also add related tests to make sure we don't regress on this in the future.

Closes: https://github.com/qmonnet/rbpf/issues/88