Skip to content

Commit 0eb9d19

Browse files
dthalerborkmann
authored andcommitted
bpf, docs: Fix modulo zero, division by zero, overflow, and underflow
Fix modulo zero, division by zero, overflow, and underflow. Also clarify how a negative immediate value is used in unsigned division. Signed-off-by: Dave Thaler <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Link: https://lore.kernel.org/bpf/[email protected]
1 parent ea403bb commit 0eb9d19

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

Documentation/bpf/instruction-set.rst

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,19 +99,26 @@ code value description
9999
BPF_ADD 0x00 dst += src
100100
BPF_SUB 0x10 dst -= src
101101
BPF_MUL 0x20 dst \*= src
102-
BPF_DIV 0x30 dst /= src
102+
BPF_DIV 0x30 dst = (src != 0) ? (dst / src) : 0
103103
BPF_OR 0x40 dst \|= src
104104
BPF_AND 0x50 dst &= src
105105
BPF_LSH 0x60 dst <<= src
106106
BPF_RSH 0x70 dst >>= src
107107
BPF_NEG 0x80 dst = ~src
108-
BPF_MOD 0x90 dst %= src
108+
BPF_MOD 0x90 dst = (src != 0) ? (dst % src) : dst
109109
BPF_XOR 0xa0 dst ^= src
110110
BPF_MOV 0xb0 dst = src
111111
BPF_ARSH 0xc0 sign extending shift right
112112
BPF_END 0xd0 byte swap operations (see `Byte swap instructions`_ below)
113113
======== ===== ==========================================================
114114

115+
Underflow and overflow are allowed during arithmetic operations, meaning
116+
the 64-bit or 32-bit value will wrap. If eBPF program execution would
117+
result in division by zero, the destination register is instead set to zero.
118+
If execution would result in modulo by zero, for ``BPF_ALU64`` the value of
119+
the destination register is unchanged whereas for ``BPF_ALU`` the upper
120+
32 bits of the destination register are zeroed.
121+
115122
``BPF_ADD | BPF_X | BPF_ALU`` means::
116123

117124
dst_reg = (u32) dst_reg + (u32) src_reg;
@@ -128,6 +135,11 @@ BPF_END 0xd0 byte swap operations (see `Byte swap instructions`_ below)
128135

129136
dst_reg = dst_reg ^ imm32
130137

138+
Also note that the division and modulo operations are unsigned. Thus, for
139+
``BPF_ALU``, 'imm' is first interpreted as an unsigned 32-bit value, whereas
140+
for ``BPF_ALU64``, 'imm' is first sign extended to 64 bits and the result
141+
interpreted as an unsigned 64-bit value. There are no instructions for
142+
signed division or modulo.
131143

132144
Byte swap instructions
133145
~~~~~~~~~~~~~~~~~~~~~~

0 commit comments

Comments
 (0)