Eleven Registers and a 512-Byte Stack

Contents
Part 1’s counter reached the kernel as 216 bytes: 27 slots of eight bytes each, which clang made out of about thirty lines of C. The kernel kept 29 slots, 232 bytes, and handed 141 bytes of x86-64 machine code to the processor. Every one of those bytes has a reason, and this post finds it: what each field of each instruction means, why the program keeps its key’s address in one register and the number 1 in another, how a call into the kernel ends up as a single machine instruction, and which line of the program each of the 141 bytes came from.
Nothing here needs a debugger or a patched kernel. The tools that ship with Ubuntu 22.04 show almost all of it, and the one thing they refuse to show takes a short build to get at.
This is Part 2 of a series on eBPF, written for C programmers who know what a process, a system
call and a socket are, and nothing about kernel internals. Everything here was run on Ubuntu 22.04
as it shipped in April: kernel 5.15.0-25-generic, clang 14, libbpf 0.5 and the bpftool from
linux-tools-5.15.0-25-generic, plus one bpftool built from the 5.15 source for the job the
packaged one can’t do. The output is pasted from those runs, not reconstructed. The note at the end
says exactly where and how.
Three copies of one program
Part 1 built a tool that counts execve() calls by
process name. Its kernel half, unchanged, is this:
// execcount.bpf.c — runs in the kernel, once per execve()
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#define TASK_COMM_LEN 16
struct comm_key {
char comm[TASK_COMM_LEN];
};
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 1024);
__type(key, struct comm_key);
__type(value, __u64);
} counts SEC(".maps");
SEC("tracepoint/syscalls/sys_enter_execve")
int count_execve(void *ctx)
{
struct comm_key key = {};
__u64 one = 1, *val;
bpf_get_current_comm(&key.comm, sizeof(key.comm));
val = bpf_map_lookup_elem(&counts, &key);
if (val)
__sync_fetch_and_add(val, 1);
else
bpf_map_update_elem(&counts, &key, &one, BPF_NOEXIST);
return 0;
}
char LICENSE[] SEC("license") = "GPL";
By the time it runs, three copies of this program have existed, and each is a translation of the one before:
- The object file. clang’s BPF backend writes the instructions into an ELF section named after the hook. This copy has holes in it: it refers to a map that doesn’t exist yet and to helpers by number.
- The verified program. The kernel copies the instructions in, proves them safe, fills the holes
and rewrites a few instructions into faster ones. This is what
bpftool prog dump xlatedshows, and what the kernel keeps. - The machine code. The JIT compiler translates the verified program into x86-64, one BPF
instruction at a time. This is what the processor executes on every
execve().
Part 1 looked at the second copy from a distance. This post reads all three, starting at the bottom: the format of a single instruction.
A machine with eleven registers
BPF programs are written for a virtual machine that exists only on paper. It is a small, ordinary register machine, much closer to a real CPU than to the stack-based virtual machines of Java or WebAssembly:
- Eleven 64-bit registers,
r0tor10. Each has a 32-bit lower half, writtenw0tow10when an instruction works on 32 bits only. Writing awregister zeroes the upper half, as it does on x86-64 and arm64. - A stack of 512 bytes, addressed downwards from
r10, the frame pointer.r10is read-only. - Memory access only through load and store instructions, each a base register plus a signed 16-bit offset. Arithmetic works on registers and constants, never directly on memory.
- No heap, and no memory that outlives one run except maps. Anything a program wants to remember between runs goes into a map.
The registers have fixed jobs, and the jobs are the calling convention:
| register | job |
|---|---|
r0 | return value from a call, and the program’s own return value |
r1–r5 | arguments to a call; destroyed by the call |
r6–r9 | callee-saved: a call leaves them alone |
r10 | read-only frame pointer; the stack is below it |
On entry, r1 holds the program’s one argument, a pointer to its context: for a tracepoint
program, the record of the tracepoint’s arguments, and r10 points at the top of the stack. The
other nine registers start out unreadable.
Why these numbers, and why this convention? Because a BPF program’s main job, besides arithmetic, is calling helpers, and helpers are ordinary C functions inside the kernel. The kernel’s own documentation, in the 5.15 tree, gives the reasoning:
Thus, all eBPF registers map one to one to HW registers on x86_64, aarch64, etc, and eBPF calling convention maps directly to ABIs used by the kernel on 64-bit architectures.
On x86-64, a C function receives its first arguments in rdi, rsi, rdx, rcx and r8, returns
its result in rax, and must preserve rbx, rbp and r12–r15. If BPF’s r1–r5 are
rdi…r8, and r0 is rax, then a BPF call to a helper needs no shuffling at all: the arguments
are already where the C function expects them, and the call is one call instruction. That is the
whole design in one sentence, and the last third of this post shows the JIT doing exactly that.
The limit of five arguments follows from the same idea. x86-64 passes six arguments in registers; BPF uses five, so every helper can be called without touching the stack. The 512-byte stack, for its part, is small because BPF programs run inside the kernel, often on a stack the kernel itself is using, and the kernel’s own stacks are only a few pages.
Eight bytes per instruction
Every BPF instruction is one of these, defined in include/uapi/linux/bpf.h:
struct bpf_insn {
__u8 code; /* opcode */
__u8 dst_reg:4; /* dest register */
__u8 src_reg:4; /* source register */
__s16 off; /* signed offset */
__s32 imm; /* signed immediate constant */
};
Eight bytes, five fields: an opcode, a destination register and a source register packed into one byte, a 16-bit signed offset, and a 32-bit signed constant. Every instruction has all five, and most leave some of them zero. Take the second instruction of our program, as clang wrote it:
7b 1a f8 ff 00 00 00 00
Read it left to right, remembering that x86-64 is little-endian, so multi-byte fields read backwards:
7bis the opcode. We’ll take it apart in a moment; it means “store a 64-bit register to memory”.1aholds both registers. The destination is the low four bits,a, sor10. The source is the high four bits,1, sor1.f8 ffis the offset:0xfff8, which as a signed 16-bit number is −8.00 00 00 00is the immediate, unused here.
Together: store r1, all 64 bits of it, at address r10 − 8. llvm-objdump prints it as
*(u64 *)(r10 - 8) = r1. It is the first half of struct comm_key key = {}.
The opcode byte is itself three fields, and which three depends on its lowest three bits, the class:
| class | value | what it does | in our program |
|---|---|---|---|
BPF_LD | 0 | special loads; in practice the 64-bit constant load | r1 = map |
BPF_LDX | 1 | load from memory into a register | — |
BPF_ST | 2 | store a constant to memory | — |
BPF_STX | 3 | store a register to memory, and atomic operations | the key, the 1, the atomic add |
BPF_ALU | 4 | 32-bit arithmetic | — |
BPF_JMP | 5 | 64-bit compares and jumps, calls, exit | the if, the goto, three calls, exit |
BPF_JMP32 | 6 | 32-bit compares and jumps (5.1) | — |
BPF_ALU64 | 7 | 64-bit arithmetic and moves | everything else |
The numbers are classic BPF’s: the 1992 design used the same three bits, and eBPF kept the classes
that still made sense. Classic class 6 was BPF_RET and class 7 BPF_MISC; eBPF reused 7 for
64-bit arithmetic from the start, and 6 became BPF_JMP32 in 5.1.
For the four memory classes, the upper five bits are a size (two bits: 4, 2, 1 or 8 bytes) and a
mode (three bits: how the address is formed). For the four arithmetic and jump classes they are an
operation (four bits: add, subtract, move, jump-if-equal, call, …) and a source bit that says
whether the second operand is src_reg or the immediate. So:
7b=0110 1011: mode011(0x60,BPF_MEM, register plus offset), size01(0x18 overall,BPF_DW, 8 bytes), class011(BPF_STX).b7=1011 0111: operation1011(0xb0,BPF_MOV), source0(the immediate), class111(BPF_ALU64). That isr1 = 0.bf=1011 1111: the same move, but source1, so from a register:r6 = r10.
The figure decodes any instruction of the program, in either of the two copies we can see.
Eight bytes, five fields
Pick an instruction from the counter. The bytes are as clang wrote them, or as the kernel holds them after verifying.
0: b7 01 00 00 00 00 00 00 r1 = 0 1: 7b 1a f8 ff 00 00 00 00 *(u64 *)(r10 - 8) = r1 2: 7b 1a f0 ff 00 00 00 00 *(u64 *)(r10 - 16) = r1 3: b7 07 00 00 01 00 00 00 r7 = 1 4: 7b 7a e8 ff 00 00 00 00 *(u64 *)(r10 - 24) = r7 5: bf a6 00 00 00 00 00 00 r6 = r10 6: 07 06 00 00 f0 ff ff ff r6 += -16 7: bf 61 00 00 00 00 00 00 r1 = r6 8: b7 02 00 00 10 00 00 00 r2 = 16 9: 85 00 00 00 10 00 00 00 call 16 10: 18 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 r1 = 0 ll 12: bf 62 00 00 00 00 00 00 r2 = r6 13: 85 00 00 00 01 00 00 00 call 1 14: 15 00 02 00 00 00 00 00 if r0 == 0 goto +2 <LBB0_2> 15: db 70 00 00 00 00 00 00 lock *(u64 *)(r0 + 0) += r7 16: 05 00 08 00 00 00 00 00 goto +8 <LBB0_3> 17: bf a2 00 00 00 00 00 00 r2 = r10 18: 07 02 00 00 f0 ff ff ff r2 += -16 19: bf a3 00 00 00 00 00 00 r3 = r10 20: 07 03 00 00 e8 ff ff ff r3 += -24 21: 18 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 r1 = 0 ll 23: b7 04 00 00 01 00 00 00 r4 = 1 24: 85 00 00 00 02 00 00 00 call 2 25: b7 00 00 00 00 00 00 00 r0 = 0 26: 95 00 00 00 00 00 00 00 exit
Bytes are little-endian: the 16-bit offset and 32-bit immediate read right to left, and the register byte holds the destination in its low four bits. A 16-byte ld_imm64 carries the low half of its constant in the first immediate and the high half in the second. Slots marked in copper differ between the two copies.
Reading the object file
llvm-objdump, from Ubuntu’s llvm package, disassembles the object file. With -r it also
prints the relocations, the holes clang left for the loader to fill:
$ llvm-objdump -d -r execcount.bpf.o
execcount.bpf.o: file format elf64-bpf
Disassembly of section tracepoint/syscalls/sys_enter_execve:
0000000000000000 <count_execve>:
0: b7 01 00 00 00 00 00 00 r1 = 0
1: 7b 1a f8 ff 00 00 00 00 *(u64 *)(r10 - 8) = r1
2: 7b 1a f0 ff 00 00 00 00 *(u64 *)(r10 - 16) = r1
3: b7 07 00 00 01 00 00 00 r7 = 1
4: 7b 7a e8 ff 00 00 00 00 *(u64 *)(r10 - 24) = r7
5: bf a6 00 00 00 00 00 00 r6 = r10
6: 07 06 00 00 f0 ff ff ff r6 += -16
7: bf 61 00 00 00 00 00 00 r1 = r6
8: b7 02 00 00 10 00 00 00 r2 = 16
9: 85 00 00 00 10 00 00 00 call 16
10: 18 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 r1 = 0 ll
0000000000000050: R_BPF_64_64 counts
12: bf 62 00 00 00 00 00 00 r2 = r6
13: 85 00 00 00 01 00 00 00 call 1
14: 15 00 02 00 00 00 00 00 if r0 == 0 goto +2 <LBB0_2>
15: db 70 00 00 00 00 00 00 lock *(u64 *)(r0 + 0) += r7
16: 05 00 08 00 00 00 00 00 goto +8 <LBB0_3>
0000000000000088 <LBB0_2>:
17: bf a2 00 00 00 00 00 00 r2 = r10
18: 07 02 00 00 f0 ff ff ff r2 += -16
19: bf a3 00 00 00 00 00 00 r3 = r10
20: 07 03 00 00 e8 ff ff ff r3 += -24
21: 18 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 r1 = 0 ll
00000000000000a8: R_BPF_64_64 counts
23: b7 04 00 00 01 00 00 00 r4 = 1
24: 85 00 00 00 02 00 00 00 call 2
00000000000000c8 <LBB0_3>:
25: b7 00 00 00 00 00 00 00 r0 = 0
26: 95 00 00 00 00 00 00 00 exit
The numbers down the left count eight-byte slots, not instructions. There are 25 instructions in
27 slots, because two of them, at 10 and 21, take two slots each. The section is 0xd8 = 216 bytes,
and the insn_cnt=27 that Part 1 saw in strace was this count of slots. Here is the program, in
the order it runs:
0–4: the locals. r1 = 0 (b7, a 64-bit move of the immediate 0), then two 8-byte stores of
r1 at r10 − 8 and r10 − 16. That is struct comm_key key = {}: sixteen zero bytes at the top
of the stack. Then r7 = 1 and a store of r7 at r10 − 24, which is __u64 one = 1. The
variable has to live in memory because its address will be passed to the update helper, and a
register has no address.
5–8: the arguments to the first call. r6 = r10; r6 += -16 computes the address of key into
r6. Then r1 = r6 and r2 = 16 load the two arguments of bpf_get_current_comm(&key.comm, 16).
Notice that clang computed the address into r6 first and only then copied it to r1. That is the
calling convention at work: r1 will be destroyed by the call, and the address is needed again
afterwards, so it is kept in a callee-saved register. The 1 is in r7 for the same reason.
9: call 16. Opcode 85 is class BPF_JMP, operation BPF_CALL (0x80). The immediate is the
helper’s number: 16 is bpf_get_current_comm. Helpers are called by number, not by address, and
a later section follows how the number becomes an address.
10–11: r1 = 0 ll. Opcode 18 is class BPF_LD, size BPF_DW, mode BPF_IMM: load a 64-bit
constant. A 64-bit constant doesn’t fit in a 32-bit immediate, so this instruction is two slots
long. And the constant here is a placeholder, 0, with a relocation underneath it, R_BPF_64_64 counts: “the loader must put the map counts here”. The next section is about this instruction.
12–13: r2 = r6; call 1. r2 gets the key’s address back from r6, which the call did not
touch, and helper 1 is bpf_map_lookup_elem(map, &key). Its result comes back in r0.
14: if r0 == 0 goto +2. Opcode 15 is BPF_JMP | BPF_JEQ | BPF_K: compare dst_reg (r0)
with the immediate (0), and if equal jump by off, here 2. Jump offsets count slots and are relative
to the next instruction, so +2 from 14 lands on 17, the label clang called LBB0_2.
15: the atomic add. db is class BPF_STX, size BPF_DW, mode 0xc0, which 5.12 renamed from
BPF_XADD to BPF_ATOMIC. The immediate picks the operation, and 0 is BPF_ADD. So this is
*(u64 *)(r0 + 0) += r7 done atomically: __sync_fetch_and_add(val, 1) with the 1 from r7.
Before 5.12 add was the only atomic BPF had; since then the same mode also does and, or, xor,
exchange and compare-and-exchange, chosen by the immediate.
16: goto +8. Opcode 05 is BPF_JMP | BPF_JA, an unconditional jump, to 25.
17–24: the insert path. r2 = &key, r3 = &one (computed afresh from r10, not copied from
r6: clang’s choice, equally valid), r1 = the map again, r4 = 1 (BPF_NOEXIST), and helper 2,
bpf_map_update_elem(map, &key, &one, BPF_NOEXIST).
25–26: r0 = 0; exit. The return value goes in r0, and 95 is BPF_JMP | BPF_EXIT.
The 16-byte instruction
Slot 10 is the only instruction in the program whose meaning changes on the way into the kernel.
A BPF_LD | BPF_IMM | BPF_DW instruction, usually called ld_imm64, is two slots. The first slot
is a normal instruction whose immediate holds the low 32 bits of the constant; the second slot has
an opcode of 0 and holds the high 32 bits in its immediate. It is the only way to put a full 64-bit
value in a register, and the only BPF instruction longer than eight bytes.
clang left it as zero because, at compile time, the map didn’t exist. libbpf’s debug output, which
bpftool -d turns on, shows the loader finding the holes and filling them:
$ sudo bpftool -d prog load execcount.bpf.o /sys/fs/bpf/ec
...
libbpf: sec '.reltracepoint/syscalls/sys_enter_execve': relo #0: insn #10 against 'counts'
libbpf: prog 'count_execve': found map 0 (counts, sec 5, off 0) for insn #10
libbpf: sec '.reltracepoint/syscalls/sys_enter_execve': relo #1: insn #21 against 'counts'
libbpf: prog 'count_execve': found map 0 (counts, sec 5, off 0) for insn #21
libbpf: map 'counts': created successfully, fd=4
...
Two relocations, for slots 10 and 21, both against counts. libbpf creates the map, gets file
descriptor 4 back, and patches both instructions: the immediate becomes 4, and the src_reg field,
otherwise unused by ld_imm64, becomes 1, which is BPF_PSEUDO_MAP_FD. The instruction now says
“load the map whose file descriptor is 4 in my process”. (In libbpf 0.5 this is
bpf_object__relocate_data(), two assignments.) Programs have referred to maps this way since the
bpf() system call arrived in 3.18.
The kernel then resolves the descriptor. Early in verification, before it looks at a single path,
it looks up file descriptor 4 in the loading process, takes a reference on the map, and writes the
map’s kernel address into the two immediates. The verifier log shows the result: where clang wrote
r1 = 0 ll, the kernel now has
10: (18) r1 = 0xffff941b402ca800
That is a pointer into kernel memory, the struct bpf_map itself. When bpftool later asks for the
program back, the kernel doesn’t hand out that address. It swaps it for the map’s ID, and puts the
pseudo-register value back in src_reg, which is why the dump reads map[id:1]:
$ sudo bpftool prog dump xlated id 4 opcodes
...
10: (18) r1 = map[id:1]
18 11 00 00 01 00 00 00 00 00 00 00 00 00 00 00
...
11: destination r1, source 1 (BPF_PSEUDO_MAP_FD); immediate 1, the map ID. Map file
descriptors aren’t the only thing src_reg can mark in an ld_imm64. Value 2,
BPF_PSEUDO_MAP_VALUE, means “the address of a value inside a map”, and it is how global variables
work since 5.2: libbpf puts a program’s .data, .rodata and .bss into array maps and points
instructions at them. The 5.15 header defines a few more, for newer features that later parts reach.
Who may touch which register
Back to the calling convention, because the verifier enforces it, and you can watch it do so. bpftool -d prog load asks for the most detailed verifier log there is, which prints the verifier’s knowledge
of every register and stack slot after each instruction. Here are the lines around the first call:
8: R1_w=fp-16 R6_w=fp-16 R7_w=inv1 R10=fp0 fp-8_w=00000000 fp-16_w=00000000 fp-24_w=inv1
8: (b7) r2 = 16
9: R1_w=fp-16 R2_w=inv16 R6_w=fp-16 R7_w=inv1 R10=fp0 fp-8_w=00000000 fp-16_w=00000000 fp-24_w=inv1
9: (85) call bpf_get_current_comm#16
last_idx 9 first_idx 0
regs=4 stack=0 before 8: (b7) r2 = 16
10: R0_w=inv(id=0) R6_w=fp-16 R7_w=inv1 R10=fp0 fp-8_w=mmmmmmmm fp-16_w=mmmmmmmm fp-24_w=inv1
Each state line lists only the registers the verifier considers readable. Before the call: r1 is
fp-16, a pointer 16 bytes below the frame pointer; r2 is inv16, a scalar known to be exactly
16; r6 is the same pointer as r1; r7 is the scalar 1. (inv is the 5.15 verifier’s word for a
plain number, as opposed to a pointer; _w is liveness bookkeeping, marking a register this state
has written.) After
the call, r1 and r2 are gone. The verifier has marked r1–r5 unreadable, and any instruction
that reads one before writing it is rejected. r0 is inv(id=0), an unknown scalar: the helper’s
return value. r6, r7 and r10 are unchanged.
The stack changed too. Before the call, both halves of the key were 00000000, known zero bytes.
After it, they are mmmmmmmm, “miscellaneous” data: the verifier knows the helper wrote them, but not
what. That’s also where the type information comes in. bpf_get_current_comm is described to the
verifier by a struct bpf_func_proto:
const struct bpf_func_proto bpf_get_current_comm_proto = {
.func = bpf_get_current_comm,
.gpl_only = false,
.ret_type = RET_INTEGER,
.arg1_type = ARG_PTR_TO_UNINIT_MEM,
.arg2_type = ARG_CONST_SIZE,
};
The first argument must be a pointer to memory the program owns, which may be uninitialised because
the helper only writes it. The second must be a constant size. The verifier checks that r1 points
into the stack, that r2 is a known constant, and that the 16 bytes from fp-16 are within the
stack: all of which the state line above shows it knew. If r2 had been a value the verifier couldn’t
pin down, the call would have been rejected, however correct the program was at run time.
Two more rules complete the picture. r10 can be read and copied, as instruction 5 does, but an
instruction that writes it is refused with “frame pointer is read only”. And the stack is 512 bytes,
which clang enforces before the kernel gets the chance. Here is a program that wants 600:
// big.bpf.c — one buffer too many for a 512-byte stack
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
SEC("tracepoint/syscalls/sys_enter_execve")
int too_big(void *ctx)
{
char buf[600] = {};
bpf_get_current_comm(buf, sizeof(buf));
return buf[599];
}
char LICENSE[] SEC("license") = "GPL";
$ clang -g -O2 -target bpf -D__TARGET_ARCH_x86 -c big.bpf.c -o big.bpf.o
big.bpf.c:8:7: error: Looks like the BPF stack limit of 512 bytes is exceeded. Please move large on stack variables into BPF per-cpu array map.
char buf[600] = {};
^
...
13 errors generated.
The advice in the message is the standard answer: a per-CPU array map with one entry is, in effect, a
private scratch buffer of any size for each CPU. Our counter uses 24 bytes of its 512, which the
verifier reports at the end of its log as stack depth 24.
The figure walks the 29 instructions the kernel kept, on both paths through them, with the verifier’s
view of each register and the actual bytes on the stack when the process calling execve() is sh.
What the verifier knew, instruction by instruction
The 29 instructions the kernel keeps, on either path through them. Registers show the type the verifier proved; the stack shows the bytes when the process is sh.
Registers
Stack (below r10)
“—” means the verifier considers the register unreadable: never written, or wiped by a call. fp−16 is “r10 minus 16”, a pointer into this program's stack. Slots 14 and 15 are the two the kernel added after it had verified the program.
Helpers are called by number
In the object file, the three calls are call 16, call 1 and call 2. Those are positions in an
enumeration in include/uapi/linux/bpf.h, which on this kernel begins:
FN(unspec), \
FN(map_lookup_elem), \
FN(map_update_elem), \
FN(map_delete_elem), \
FN(probe_read), \
FN(ktime_get_ns), \
FN(trace_printk), \
FN(get_prandom_u32), \
FN(get_smp_processor_id), \
FN(skb_store_bytes), \
FN(l3_csum_replace), \
FN(l4_csum_replace), \
FN(tail_call), \
FN(clone_redirect), \
FN(get_current_pid_tgid), \
FN(get_current_uid_gid), \
FN(get_current_comm), \
and continues to 175. New helpers are only ever appended, so a program compiled against an old header still means the same thing on a new kernel. That is the whole ABI of a helper call: a number, five registers in, one register out.
The verifier turns the number into a function in two steps. First, while checking the call, it asks
the program type for the helper’s prototype, get_func_proto(16). A tracepoint program gets
bpf_get_current_comm_proto, the structure above. A socket filter or an XDP program asking for
helper 16 gets nothing back, and its load fails. This is where “which helpers a program may call depends on
its type” is decided. Second, after checking, a pass called do_misc_fixups rewrites each call’s
immediate:
insn->imm = fn->func - __bpf_call_base;
The immediate stops being a helper number and becomes the distance, in bytes, from a fixed function
in the kernel, __bpf_call_base, to the helper’s code. The xlated dump shows the new immediates, and
/proc/kallsyms shows where everything is:
$ sudo bpftool prog dump xlated id 4 opcodes
...
9: (85) call bpf_get_current_comm#160480
85 00 00 00 e0 72 02 00
...
$ sudo grep -w -e __bpf_call_base -e bpf_get_current_comm \
-e __htab_map_lookup_elem -e htab_map_update_elem /proc/kallsyms
ffffffffa36287b0 T __bpf_call_base
ffffffffa364fa90 T bpf_get_current_comm
ffffffffa3653a60 t __htab_map_lookup_elem
ffffffffa3656a60 t htab_map_update_elem
e0 72 02 00 is 0x000272e0, which is 160,480. And 0xffffffffa364fa90 − 0xffffffffa36287b0 =
0x272e0. The other two calls check out the same way: 0x2b2b0 = 176,816 for __htab_map_lookup_elem
and 0x2e2b0 = 189,104 for htab_map_update_elem. These are exactly the numbers in Part 1’s listing,
from a different boot, although every absolute address above is different, because the kernel loads
its code at a random base on each boot. Offsets within the kernel image don’t move. A 32-bit offset
is enough because the whole kernel image fits within two gigabytes, and an offset rather than a full
address is what lets a 64-bit target fit in a 32-bit field.
Two of the three calls no longer go to the helper the program asked for. call 1 was
bpf_map_lookup_elem, a generic function that looks at the map’s type and dispatches to the right
implementation. But the verifier knows, at load time, exactly which map instruction 10 loads, so it
skips the dispatch. For the update, it calls the hash table’s htab_map_update_elem directly. For
the lookup it goes further: since 4.12, the hash map supplies a short replacement sequence,
htab_map_gen_lookup() in kernel/bpf/hashtab.c:
*insn++ = BPF_EMIT_CALL(BPF_CAST_CALL(__htab_map_lookup_elem));
*insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 1);
*insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
offsetof(struct htab_elem, key) +
round_up(map->key_size, 8));
Call the internal lookup, which returns the hash table element or NULL; if it isn’t NULL, add the
size of the element’s header plus the key, rounded up to eight, to reach the value. On this kernel
that is 48 + 16 = 64, the r0 += 64 we saw in Part 1. One instruction became three: that is the
first half of 27 becoming 29.
Calls that stay inside BPF, and one that never returns
Helpers aren’t the only thing a call instruction can reach. Two other kinds of call change how
programs are structured, and both are easy to see in a program of a few lines:
// calls.bpf.c — one BPF-to-BPF call and one tail call
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
struct {
__uint(type, BPF_MAP_TYPE_PROG_ARRAY);
__uint(max_entries, 1);
__uint(key_size, sizeof(__u32));
__uint(value_size, sizeof(__u32));
} next SEC(".maps");
static __attribute__((noinline)) int twice(int x)
{
return x * 2;
}
SEC("xdp/first")
int first(struct xdp_md *ctx)
{
bpf_tail_call(ctx, &next, 0);
return twice(1); /* reached only if the tail call fails */
}
SEC("xdp/second")
int second(struct xdp_md *ctx)
{
return twice(21);
}
char LICENSE[] SEC("license") = "GPL";
Two XDP programs, so that bpftool prog run can execute them on a made-up packet without attaching
them to anything. Both call twice(), a real function, kept out of line by noinline. And first
tries a tail call: it asks the kernel to replace the running program with whatever program sits
at index 0 of the next map, a BPF_MAP_TYPE_PROG_ARRAY.
$ llvm-objdump -d -r calls.bpf.o
...
0000000000000000 <twice>:
0: bf 10 00 00 00 00 00 00 r0 = r1
1: 67 00 00 00 01 00 00 00 r0 <<= 1
2: 95 00 00 00 00 00 00 00 exit
...
0000000000000000 <first>:
0: 18 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 r2 = 0 ll
0000000000000000: R_BPF_64_64 next
2: b7 03 00 00 00 00 00 00 r3 = 0
3: 85 00 00 00 0c 00 00 00 call 12
4: b7 01 00 00 01 00 00 00 r1 = 1
5: 85 10 00 00 ff ff ff ff call -1
0000000000000028: R_BPF_64_32 .text
6: 95 00 00 00 00 00 00 00 exit
...
twice compiled to a shift: 67 is BPF_ALU64 | BPF_LSH | BPF_K, so r0 <<= 1. The two calls in
first are different in kind:
call 12is a helper call like the others: helper 12 isbpf_tail_call(ctx, map, index).r1still holds the context it held on entry,r2the map,r3the index.call -1hassrc_reg1 (85 10), which for a call meansBPF_PSEUDO_CALL: not a helper, but another BPF function in the same program, at a distance in slots given by the immediate. clang can’t know the distance, since libbpf decides wheretwicegoes, so it writes −1 and a relocation against.text. libbpf appends a copy oftwiceto every program that calls it and fixes the offset.
BPF-to-BPF calls arrived in 4.16. Before that every function had to be inlined, and large
programs paid for it in size. A called function gets its own stack frame, so r10 in twice is a
different frame pointer from r10 in first, and the same calling convention applies: arguments in
r1–r5, result in r0, r6–r9 preserved. The verifier allows up to eight frames, and the 512
bytes of stack are a limit on the sum of the frames on the deepest call chain, not on each one.
Tail calls are older, from 4.2, and stranger. A tail call doesn’t return. If it succeeds, the current program is finished and the target program runs in its place, on the same stack frame, returning its result to whoever ran the first. If it fails (an empty slot, an index out of range), execution simply continues with the next instruction. They exist to chain programs together, for example one per protocol in a packet parser, and to swap pieces of a running pipeline by updating a map instead of reloading anything. To stop a chain of them from running forever, the kernel counts them: before each tail call the 5.15 code checks the count against 32 and then adds one, so a chain can be 33 tail calls long, and the 34th fails as if the slot were empty.
All of that is visible from bpftool. Load both programs, pin them, and run first:
$ clang -g -O2 -target bpf -c calls.bpf.c -o calls.bpf.o
$ sudo bpftool prog loadall calls.bpf.o /sys/fs/bpf/calls pinmaps /sys/fs/bpf/calls_maps
$ head -c 64 /dev/zero > pkt.bin
$ sudo bpftool prog run pinned /sys/fs/bpf/calls/xdp_first data_in pkt.bin
Return value: 2, duration: ...
2: the slot is empty, the tail call fell through, and twice(1) ran. Now put second in the slot
and run first again:
$ sudo bpftool map update pinned /sys/fs/bpf/calls_maps/next key 0 0 0 0 \
value pinned /sys/fs/bpf/calls/xdp_second
$ sudo bpftool prog run pinned /sys/fs/bpf/calls/xdp_first data_in pkt.bin
Return value: 42, duration: ...
42: first was replaced by second, which returned twice(21). Nothing was reloaded; one map entry
changed. The kernel’s copy of first shows the two calls as it resolved them:
$ sudo bpftool prog dump xlated pinned /sys/fs/bpf/calls/xdp_first
int first(struct xdp_md * ctx):
; bpf_tail_call(ctx, &next, 0);
0: (18) r2 = map[id:3]
2: (b7) r3 = 0
3: (85) call bpf_tail_call#12
; return twice(1); /* reached only if the tail call fails */
4: (b7) r1 = 1
5: (85) call pc+1#bpf_prog_6aadb6445c8badae_F
; return twice(1); /* reached only if the tail call fails */
6: (95) exit
int twice(int x):
; static __attribute__((noinline)) int twice(int x)
7: (bf) r0 = r1
; return x * 2;
8: (67) r0 <<= 1
; return x * 2;
9: (95) exit
The call to twice is now pc+1: one slot past the next instruction, which is where libbpf put
the copy of twice, at 7. The kernel compiles each BPF function separately, and
bpf_prog_6aadb6445c8badae_F is the name the compiled twice got.
What the tail call becomes in machine code is the most surprising thing in this post, and it needs the JIT, so it comes at the end.
From 27 to 29
We can now line up the object file against what the kernel kept, slot by slot. Everything that changed:
| object file | kept by the kernel | who changed it |
|---|---|---|
9: call 16 | 9: call bpf_get_current_comm#160480 | verifier: helper number → offset from __bpf_call_base |
10: r1 = 0 ll | 10: r1 = map[id:1] | libbpf: placeholder → fd 4; verifier: fd → map address |
13: call 1 | 13: call __htab_map_lookup_elem#176816 | verifier: inlined hash lookup … |
| — | 14: if r0 == 0x0 goto pc+1 | … plus the NULL check … |
| — | 15: r0 += 64 | … and the step to the value |
21: r1 = 0 ll | 23: r1 = map[id:1] | as slot 10 |
24: call 2 | 26: call htab_map_update_elem#189104 | verifier: direct call to the hash map’s update |
Every other slot is byte-for-byte what clang wrote, including the jumps: if r0 == 0 goto +2 at
object slot 14 is if r0 == 0x0 goto pc+2 at kernel slot 16, and goto +8 still says 8, because both
jumps start after the insertion point and land after it. When the kernel inserts instructions it
walks the program and fixes every jump that crosses the insertion, so none of these needed to.
The order of events inside the one BPF_PROG_LOAD call matters, and bpf_check() in
kernel/bpf/verifier.c lays it out: first resolve the map references (and compute the program’s tag,
the hash bpftool prints, with the map immediates blanked so that the same object always gets the same
tag: 2ef1c7a420d19e5e, as in Part 1); then walk every path; only then the fixups. So the verifier
proved the 27-slot program, not the 29-slot one. The two instructions it added afterwards are the
kernel’s own, and the kernel trusts itself. The verifier’s summary line says how much walking it did:
verification time 167 usec
stack depth 24
processed 27 insns (limit 1000000) max_states_per_insn 0 total_states 2 peak_states 2 mark_read 1
“Processed 27 insns” is a coincidence worth defusing. It doesn’t count slots; it counts instruction visits. The verifier walked the path where the lookup succeeds (slots 0 to 16, then 25 and 26: 18 instructions, counting the two-slot load once) and then the path where it fails (17 to 26: nine more), and 18 + 9 happens to be 27. A program with more branches processes far more instructions than it has, which is what the million in the limit is about.
Getting the 141 bytes out
The last copy of the program is the machine code. Part 1 stopped here:
$ sudo bpftool prog dump jited id 4
Error: No libbfd support
bpftool disassembles JIT output with libbfd, the GNU binutils library that objdump is built on.
Ubuntu builds its bpftool without it, so the command gives up before it asks the kernel for anything.
The bytes themselves are available to any root process: the bpf() system call’s
BPF_OBJ_GET_INFO_BY_FD command copies a program’s JIT image into a buffer the caller supplies. There
are two period-correct ways to use that, and I did both.
Build bpftool with libbfd. bpftool lives in the kernel tree, so the 5.15 release tarball from
kernel.org has the same tool Ubuntu packages, and binutils-dev, in the 22.04 archive, provides
libbfd. bpftool’s makefile detects it on its own:
sudo apt install binutils-dev
tar -xf linux-5.15.tar.xz
make -C linux-5.15/tools/bpf/bpftool
linux-5.15/tools/bpf/bpftool/bpftool version
...
... libbfd: [ on ]
... disassembler-four-args: [ on ]
...
linux-5.15/tools/bpf/bpftool/bpftool v5.15.0
features: libbfd, skeletons
This builds bpftool and its own copy of libbpf from the tree, and nothing is installed: the binary
runs from where it was built. It prints v5.15.0 where Ubuntu’s prints v5.15.30, because Ubuntu
builds from its own kernel tree, which carries the 5.15 stable updates.
Copy the bytes out yourself. Twenty lines of C with libbpf, which call BPF_OBJ_GET_INFO_BY_FD
twice: once to learn the size, once with a buffer of that size.
// jitdump.c — copy a loaded program's JIT image out of the kernel, raw
#include <stdio.h>
#include <stdlib.h>
#include <bpf/bpf.h>
int main(int argc, char **argv)
{
struct bpf_prog_info info = {};
__u32 len = sizeof(info);
unsigned char *image;
int fd;
if (argc != 2) {
fprintf(stderr, "usage: %s PROG_ID > image.bin\n", argv[0]);
return 1;
}
fd = bpf_prog_get_fd_by_id(atoi(argv[1]));
if (fd < 0 || bpf_obj_get_info_by_fd(fd, &info, &len)) {
perror("bpf");
return 1;
}
/* second call: now that we know the size, ask for the bytes */
image = malloc(info.jited_prog_len);
struct bpf_prog_info again = {
.jited_prog_len = info.jited_prog_len,
.jited_prog_insns = (__u64)(unsigned long)image,
};
len = sizeof(again);
if (bpf_obj_get_info_by_fd(fd, &again, &len)) {
perror("bpf");
return 1;
}
fwrite(image, 1, again.jited_prog_len, stdout);
fprintf(stderr, "%u bytes\n", again.jited_prog_len);
return 0;
}
The raw bytes go to ordinary objdump, which can disassemble a file with no headers at all if told
the architecture. Giving it the program’s address from /proc/kallsyms as the starting address makes
the call targets come out as real kernel addresses:
cc -g -O2 -Wall jitdump.c -lbpf -lelf -lz -o jitdump
sudo ./jitdump 4 > image.bin
A=$(sudo awk '/_count_execve/ {print $1}' /proc/kallsyms)
objdump -D -b binary -m i386:x86-64 --adjust-vma=0x$A image.bin
141 bytes
image.bin: file format binary
Disassembly of section .data:
ffffffffc008f9e8 <.data>:
ffffffffc008f9e8: 0f 1f 44 00 00 nopl 0x0(%rax,%rax,1)
ffffffffc008f9ed: 66 90 xchg %ax,%ax
ffffffffc008f9ef: 55 push %rbp
ffffffffc008f9f0: 48 89 e5 mov %rsp,%rbp
ffffffffc008f9f3: 48 81 ec 18 00 00 00 sub $0x18,%rsp
ffffffffc008f9fa: 53 push %rbx
ffffffffc008f9fb: 41 55 push %r13
ffffffffc008f9fd: 31 ff xor %edi,%edi
ffffffffc008f9ff: 48 89 7d f8 mov %rdi,-0x8(%rbp)
ffffffffc008fa03: 48 89 7d f0 mov %rdi,-0x10(%rbp)
ffffffffc008fa07: 41 bd 01 00 00 00 mov $0x1,%r13d
ffffffffc008fa0d: 4c 89 6d e8 mov %r13,-0x18(%rbp)
ffffffffc008fa11: 48 89 eb mov %rbp,%rbx
ffffffffc008fa14: 48 83 c3 f0 add $0xfffffffffffffff0,%rbx
ffffffffc008fa18: 48 89 df mov %rbx,%rdi
ffffffffc008fa1b: be 10 00 00 00 mov $0x10,%esi
ffffffffc008fa20: e8 6b 00 5c e3 call 0xffffffffa364fa90
ffffffffc008fa25: 48 bf 00 64 e4 40 1b movabs $0xffff941b40e46400,%rdi
ffffffffc008fa2c: 94 ff ff
ffffffffc008fa2f: 48 89 de mov %rbx,%rsi
ffffffffc008fa32: e8 29 40 5c e3 call 0xffffffffa3653a60
ffffffffc008fa37: 48 85 c0 test %rax,%rax
ffffffffc008fa3a: 74 04 je 0xffffffffc008fa40
ffffffffc008fa3c: 48 83 c0 40 add $0x40,%rax
ffffffffc008fa40: 48 85 c0 test %rax,%rax
ffffffffc008fa43: 74 07 je 0xffffffffc008fa4c
ffffffffc008fa45: f0 4c 01 68 00 lock add %r13,0x0(%rax)
ffffffffc008fa4a: eb 22 jmp 0xffffffffc008fa6e
ffffffffc008fa4c: 48 89 ee mov %rbp,%rsi
ffffffffc008fa4f: 48 83 c6 f0 add $0xfffffffffffffff0,%rsi
ffffffffc008fa53: 48 89 ea mov %rbp,%rdx
ffffffffc008fa56: 48 83 c2 e8 add $0xffffffffffffffe8,%rdx
ffffffffc008fa5a: 48 bf 00 64 e4 40 1b movabs $0xffff941b40e46400,%rdi
ffffffffc008fa61: 94 ff ff
ffffffffc008fa64: b9 01 00 00 00 mov $0x1,%ecx
ffffffffc008fa69: e8 f2 6f 5c e3 call 0xffffffffa3656a60
ffffffffc008fa6e: 31 c0 xor %eax,%eax
ffffffffc008fa70: 41 5d pop %r13
ffffffffc008fa72: 5b pop %rbx
ffffffffc008fa73: c9 leave
ffffffffc008fa74: c3 ret
The three call targets are the three addresses /proc/kallsyms gave earlier:
bpf_get_current_comm, __htab_map_lookup_elem and htab_map_update_elem. The rebuilt bpftool
produces the same listing with C source lines between the instructions, but prints call targets
relative to address 0, so they come out as meaningless numbers. Asked to write the image to a file
instead, it wrote one identical to jitdump’s:
$ sudo linux-5.15/tools/bpf/bpftool/bpftool prog dump jited id 4 file image2.bin
$ cmp image.bin image2.bin && echo "cmp: identical"
cmp: identical
Why both? The rebuilt bpftool is what a 22.04 user would reach for, and it ties each instruction to its line of C. The raw dump doesn’t depend on bpftool or libbfd at all, so it is an independent check of the bytes, and it resolves every call to a kernel symbol. They agree, so from here on “the 141 bytes” means those.
How each instruction became x86-64
The JIT is arch/x86/net/bpf_jit_comp.c, and its core, do_jit(), is a loop over the BPF
instructions with a switch on the opcode, emitting a few bytes of x86-64 for each. Beyond
picking the shortest encoding for each instruction, there is no optimiser, no register allocator,
no instruction scheduling. Each BPF instruction becomes a fixed,
short sequence of machine instructions, in order. That simplicity is a design choice: the verifier
has already proved the program, and a translation this direct is easy to trust.
The registers are fixed by a table, reg2hex[]:
| BPF | x86-64 | as a C function sees it |
|---|---|---|
r0 | rax | return value |
r1–r5 | rdi, rsi, rdx, rcx, r8 | arguments 1 to 5 |
r6–r9 | rbx, r13, r14, r15 | callee-saved |
r10 | rbp | frame pointer |
This is the System V calling convention that the kernel’s C code follows, register for register. A
comment in the table explains the one gap: r12 is callee-saved too, but using it as a base address
costs an extra byte in every instruction that does, so the JIT keeps it for nothing.
The prologue, 21 bytes, comes first:
nopl 0x0(%rax,%rax,1) 0f 1f 44 00 00
xchg %ax,%ax 66 90
push %rbp 55
mov %rsp,%rbp 48 89 e5
sub $0x18,%rsp 48 81 ec 18 00 00 00
push %rbx 53
push %r13 41 55
The first seven bytes do nothing, on purpose. The five-byte nopl is a patch site: since 5.5, the
kernel can attach a trampoline to a BPF program by rewriting those five bytes into a call, the
same trick it uses for kernel functions. The two-byte xchg %ax,%ax (a two-byte no-op) is a slot
that becomes xor %eax,%eax in programs that make tail calls, where rax carries the tail-call
count. Then a normal C function prologue: save the caller’s frame pointer, make our own, and reserve
0x18 = 24 bytes of stack, the stack depth 24 the verifier computed, rounded up to eight. Finally
it saves the callee-saved registers the program uses. detect_reg_usage() found r6 and r7, so
rbx and r13 are pushed, and r14 and r15 are not.
The body. Each BPF instruction, in order:
r1 = 0→xor %edi,%edi, two bytes. A move of the constant 0 is emitted as an exclusive-or of the register with itself, the shortest way on x86-64 to zero a register. Writing the 32-bitediclears all ofrdi.*(u64 *)(r10 -8) = r1→mov %rdi,-0x8(%rbp), four bytes: a REX prefix (48, 64-bit operand), the opcode for a register-to-memory move (89), a ModRM byte (7d) namingrdiandrbp-plus-a-byte, and the byte,f8, which is −8. The BPF offset went through unchanged.r7 = 1→mov $0x1,%r13d, six bytes. A positive constant is loaded with a 32-bit move, which zeroes the upper half and is shorter than the 64-bit form.r6 = r10; r6 += -16→mov %rbp,%rbx; add $-16,%rbx(objdump prints the constant as a 64-bit two’s complement number). The add uses the short form with a sign-extended byte,f0.call bpf_get_current_comm→callwith a 32-bit displacement, five bytes. The arguments are already inrdiandrsi, because that’s wherer1andr2live. The JIT computes the target as__bpf_call_baseplus the instruction’s immediate, which is how the offset the verifier wrote becomes an address, and then encodes it relative to the end of thecall.r1 = map[id:1]→movabs $0xffff941b40e46400,%rdi, ten bytes: the map’s address as a 64-bit constant, put there by the verifier. It is the longest instruction in the image.call __htab_map_lookup_elem, then the inserted pair →call, thentest %rax,%rax; jeandadd $0x40,%rax. A compare with 0 is emitted astestof the register with itself, a byte shorter thancmp.if r0 == 0x0 goto pc+2→test %rax,%rax; je +7.lock *(u64 *)(r0 +0) += r7→lock add %r13,0x0(%rax), five bytes: thelockprefix (f0), REX (4c, 64-bit, andr13needs the extra register bit),add(01), ModRM, and a zero displacement byte the JIT always emits, as a comment explains, rather than special-casing the registers that need one.goto pc+8→jmpwith a one-byte offset,eb 22.- the insert path → the same patterns:
mov %rbp,%rsi; add $-16,%rsifor&key, the same for&oneintordx, the map’s address intordi,mov $0x1,%ecxforBPF_NOEXIST, and acalltohtab_map_update_elem. Four arguments, already in the four argument registers. r0 = 0→xor %eax,%eax.
The epilogue is the code for the first exit: restore the callee-saved registers in reverse,
then leave (undo the frame) and ret. Five bytes. A program with several exits would get jumps
to this one copy.
Prologue 21, body 115, epilogue 5: 141. The figure colours every byte by the BPF instruction that produced it.
Where each of the 141 bytes came from
The JIT image of the counter, sixteen bytes to a row. Pick a byte, or a row of the table, to see the BPF instruction that produced it.
| BPF | off | bytes | x86-64 |
|---|---|---|---|
| prologue | 0 | 0f 1f 44 00 00 | nopl 0x0(%rax,%rax,1) |
| 5 | 66 90 | xchg %ax,%ax | |
| 7 | 55 | push %rbp | |
| 8 | 48 89 e5 | mov %rsp,%rbp | |
| b | 48 81 ec 18 00 00 00 | sub $0x18,%rsp | |
| 12 | 53 | push %rbx | |
| 13 | 41 55 | push %r13 | |
| 0: r1 = 0 | 15 | 31 ff | xor %edi,%edi |
| 1: *(u64 *)(r10 -8) = r1 | 17 | 48 89 7d f8 | mov %rdi,-0x8(%rbp) |
| 2: *(u64 *)(r10 -16) = r1 | 1b | 48 89 7d f0 | mov %rdi,-0x10(%rbp) |
| 3: r7 = 1 | 1f | 41 bd 01 00 00 00 | mov $0x1,%r13d |
| 4: *(u64 *)(r10 -24) = r7 | 25 | 4c 89 6d e8 | mov %r13,-0x18(%rbp) |
| 5: r6 = r10 | 29 | 48 89 eb | mov %rbp,%rbx |
| 6: r6 += -16 | 2c | 48 83 c3 f0 | add $0xfffffffffffffff0,%rbx |
| 7: r1 = r6 | 30 | 48 89 df | mov %rbx,%rdi |
| 8: r2 = 16 | 33 | be 10 00 00 00 | mov $0x10,%esi |
| 9: call bpf_get_current_comm#160480 | 38 | e8 6b 00 5c e3 | call 0xffffffffe35c00a8 |
| 10: r1 = map[id:1] | 3d | 48 bf 00 64 e4 40 1b 94 ff ff | movabs $0xffff941b40e46400,%rdi |
| 12: r2 = r6 | 47 | 48 89 de | mov %rbx,%rsi |
| 13: call __htab_map_lookup_elem#176816 | 4a | e8 29 40 5c e3 | call 0xffffffffe35c4078 |
| 14: if r0 == 0x0 goto pc+1 | 4f | 48 85 c0 | test %rax,%rax |
| 52 | 74 04 | je 0x0000000000000058 | |
| 15: r0 += 64 | 54 | 48 83 c0 40 | add $0x40,%rax |
| 16: if r0 == 0x0 goto pc+2 | 58 | 48 85 c0 | test %rax,%rax |
| 5b | 74 07 | je 0x0000000000000064 | |
| 17: lock *(u64 *)(r0 +0) += r7 | 5d | f0 4c 01 68 00 | lock add %r13,0x0(%rax) |
| 18: goto pc+8 | 62 | eb 22 | jmp 0x0000000000000086 |
| 19: r2 = r10 | 64 | 48 89 ee | mov %rbp,%rsi |
| 20: r2 += -16 | 67 | 48 83 c6 f0 | add $0xfffffffffffffff0,%rsi |
| 21: r3 = r10 | 6b | 48 89 ea | mov %rbp,%rdx |
| 22: r3 += -24 | 6e | 48 83 c2 e8 | add $0xffffffffffffffe8,%rdx |
| 23: r1 = map[id:1] | 72 | 48 bf 00 64 e4 40 1b 94 ff ff | movabs $0xffff941b40e46400,%rdi |
| 25: r4 = 1 | 7c | b9 01 00 00 00 | mov $0x1,%ecx |
| 26: call htab_map_update_elem#189104 | 81 | e8 f2 6f 5c e3 | call 0xffffffffe35c7078 |
| 27: r0 = 0 | 86 | 31 c0 | xor %eax,%eax |
| 28: exit | 88 | 41 5d | pop %r13 |
| 8a | 5b | pop %rbx | |
| 8b | c9 | leave | |
| 8c | c3 | ret |
The prologue is the same shape for every program on this kernel; what varies is the stack size it reserves and which callee-saved registers it pushes. The exit row includes the epilogue. Call targets are shown as bpftool prints them, relative to address 0; the post resolves them against /proc/kallsyms.
There is one thing the table can’t show: the jump offsets. To emit je +4 the JIT has to know how
far away the target is, which depends on the size of the code in between, which depends on whether
its jumps fit in one byte. do_jit() breaks the circle by running repeatedly. The first pass
assumes every instruction takes 64 bytes; each pass recomputes the sizes with the offsets from the
one before; when two passes in a row produce the same total, the offsets are right and the final pass
writes the image. bpf_int_jit_compile() allows up to twenty passes.
And there is one thing the table doesn’t contain: any checking. No bounds checks on the stack
accesses, no NULL checks the program didn’t write itself, no limit on how long it runs. The 141
bytes are exactly what a C compiler might have produced for the same function, because everything
that would make them unsafe was ruled out before the JIT ran. (One option would change that: with the
net.core.bpf_jit_harden sysctl turned on, the JIT disguises constants such as the map address by
emitting them XORed with a random value, so that an attacker can’t use them to plant chosen bytes in
executable memory. It is 0 on this machine.)
What the tail call compiled to
Now the surprise promised earlier. Here is the JIT output for first, from the calls.bpf.c example,
before second was put in the program array, from the rebuilt bpftool, trimmed to the tail call:
$ sudo linux-5.15/tools/bpf/bpftool/bpftool prog dump jited pinned /sys/fs/bpf/calls/xdp_first opcodes
int first(struct xdp_md * ctx):
bpf_prog_d6dab0aa9a6fd1c5_first:
; bpf_tail_call(ctx, &next, 0);
0: nopl 0x0(%rax,%rax,1)
0f 1f 44 00 00
5: xor %eax,%eax
31 c0
7: push %rbp
55
8: mov %rsp,%rbp
48 89 e5
b: push %rax
50
c: movabs $0xffff941b40ac9800,%rsi
48 be 00 98 ac 40 1b 94 ff ff
16: xor %edx,%edx
31 d2
18: mov -0x4(%rbp),%eax
8b 85 fc ff ff ff
1e: cmp $0x20,%eax
83 f8 20
21: ja 0x0000000000000037
77 14
23: add $0x1,%eax
83 c0 01
26: mov %eax,-0x4(%rbp)
89 85 fc ff ff ff
2c: jmp 0x0000000000000037
e9 06 00 00 00
31: pop %rax
58
32: nopl 0x0(%rax,%rax,1)
0f 1f 44 00 00
; return twice(1); /* reached only if the tail call fails */
37: mov $0x1,%edi
bf 01 00 00 00
...
The prologue’s two-byte slot is xor %eax,%eax now, and push %rax saves the tail-call count of
zero on the stack. Then the call to bpf_tail_call is gone. In its place: load the count, compare
with 0x20 = 32 (MAX_TAIL_CALL_CNT in 5.15), give up if it’s above, otherwise add one and store it
back.
Then jmp 0x37, straight past the tail call to the fall-through code, followed by a five-byte
nopl that nothing jumps to.
Here is the same stretch after bpftool map update put second in slot 0:
2c: nopl 0x0(%rax,%rax,1)
0f 1f 44 00 00
31: pop %rax
58
32: jmp 0x000000000000460f
e9 d8 45 00 00
The kernel rewrote the machine code of a running program. The jmp 0x37 that skipped the tail
call became a nopl, and the nopl became a jmp to second. Because the index, 0, is a constant,
the verifier could tell, at load time, which slot of which map this call would always use, and since
5.5 the x86-64 JIT turns such a tail call into a direct jump that is patched whenever the slot
changes, instead of a lookup in the map on every run. The target checks out: /proc/kallsyms had
first at 0xffffffffc008f4d8 and second at 0xffffffffc0093adc, and 0xffffffffc008f4d8 + 0x460f =
0xffffffffc0093ae7, which is second plus 11.
Eleven is the length of the prologue up to the end of mov %rsp,%rbp: the five-byte nopl, the
two-byte slot, push %rbp and mov %rsp,%rbp. A tail call jumps into its target’s prologue, past
the part that would set up a new frame, so the target runs on the caller’s stack frame, and the
count in rax carries over. Before jumping, the caller undoes everything its prologue did after
mov %rsp,%rbp, popping the count back into rax on the way, so the target starts with the stack
exactly as it would be just after its own mov %rsp,%rbp. So the two seemingly idle slots at the top of every BPF program on
this kernel, the five-byte and the two-byte, are there so that the kernel can redirect into the
program and out of it, without stopping it.
The call to twice at 0x43, a little further down, is an ordinary call with a 32-bit
displacement to bpf_prog_6aadb6445c8badae_F, preceded by mov -0x8(%rbp),%rax, which reloads the
tail-call count so that twice would inherit it. Since 5.10 the x86-64 JIT allows tail calls from
inside BPF-to-BPF functions, and that is the bookkeeping it costs.
What we covered
- A BPF instruction is eight bytes: an opcode, two four-bit register numbers, a 16-bit offset and a 32-bit immediate. The opcode’s low three bits are the class; the rest is size and mode for memory instructions, operation and source for arithmetic and jumps.
ld_imm64is the one 16-byte instruction. clang leaves map references in it as zeros with relocations; libbpf writes the map’s file descriptor andBPF_PSEUDO_MAP_FD; the verifier replaces the descriptor with the map’s address.- Eleven registers with fixed roles:
r0result,r1–r5arguments destroyed by calls,r6–r9preserved,r10a read-only frame pointer over a 512-byte stack. The verifier enforces the convention by makingr1–r5unreadable after every call, and clang keeps anything needed across a call inr6–r9. - Helpers are called by number. The verifier checks each call against the helper’s prototype for the
program type, then rewrites the number into the helper’s offset from
__bpf_call_base; for maps, it calls the map type’s own functions directly, and inlines the hash lookup as three instructions, which is how 27 slots became 29. - BPF-to-BPF calls (4.16) are real calls with their own frames; tail calls (4.2) replace the running program and never return, at most 33 in a chain on this kernel.
- The x86-64 JIT maps the registers one to one onto the System V calling convention, so a helper call
is one
call. The 141 bytes are a 21-byte prologue, 115 bytes of body and a 5-byte epilogue, with every BPF instruction in its own short run of machine code, and no checks of any kind. - A tail call with a constant index is a patched direct jump: updating the program array rewrites the caller’s machine code.
Part 3 steps back up to user space: the same tool written with bpftrace, BCC and libbpf, compared,
and what the bpf() system call, file descriptors, pinning and links mean for how long a program
lives.
A note on the evidence
What I ran, and where. Every listing in this post is pasted from a real run. The machine was a KVM
virtual machine with 4 virtual CPUs and 4 GiB of memory, booting Ubuntu 22.04’s release kernel,
5.15.0-25-generic #25-Ubuntu SMP Wed Mar 30 15:54:22 UTC 2022, on a minimal 22.04 userland built
from the release archive only, so every package is at its release-day version: clang and LLVM
14.0.0-1ubuntu1 (which provides llvm-objdump), GNU binutils 2.38 (objdump), libbpf-dev 0.5.0-1,
and bpftool v5.15.30 from linux-tools-5.15.0-25-generic. For the JIT listings I added
binutils-dev 2.38-3ubuntu1, from the same release archive, and built bpftool from the kernel.org
5.15 tarball exactly as shown; it reported v5.15.0 and features: libbfd, skeletons. The C files
in this post (execcount.bpf.c, identical to Part 1’s, big.bpf.c, calls.bpf.c, jitdump.c) and
the two command blocks were extracted from the page and run as shown. Part 1’s user-space half and
build script were extracted from Part 1’s page.
One load, mostly. The object file listing, bpftool prog show, the xlated dumps, the kallsyms
lines and both JIT listings come from one boot and one load of the counter, program 4 with map 1. The
verifier log comes from a second load of the same object in the same boot, by bpftool -d prog load,
which created its own map. That is why the map address in the log, 0xffff941b402ca800, differs from
the one in the JIT image. The calls.bpf.c listings come from the same boot, programs 13 and 14.
Kernel addresses change on every boot; the offsets from __bpf_call_base were the same as in Part
1’s run, from a different boot.
What I trimmed. Lines marked ... are cut: the loaded_at timestamp of bpftool prog show and
duration of bpftool prog run (a single run’s timing, meaningless at this scale), the rest of the
libbpf debug output and of the verifier log around the parts quoted, the twelve repeats of clang’s
stack-limit error (it reports the same error for each use of the buffer, 13 in all), the rest of
llvm-objdump’s output for calls.bpf.o, and the tail of the tail-call JIT listing. The make
output is cut to the feature detection and the final line. Nothing inside a quoted line was changed.
What I worked out rather than read. Which x86-64 instructions belong to which BPF instruction is
not something either tool prints. I assigned them by following do_jit() in the 5.15 source, which
emits one BPF instruction’s code at a time, in order, and checked that the assignment uses up exactly
the 141 bytes; it is also the only assignment consistent with the jump targets in the listing. The
stack bytes in the stepper figure (“sh” followed by zeros) follow from the instructions, not from
reading a running program’s stack. The JIT’s pass count for this program is not something I measured.
What I cited rather than ran. The kernel versions in which each piece arrived (JMP32 in 5.1,
BPF_ATOMIC in 5.12, the inlined hash lookup in 4.12, BPF-to-BPF calls in 4.16, tail calls in 4.2,
direct tail calls in 5.5, tail calls from subprograms in 5.10) are the first release tags containing
the commits that introduced them. The quoted kernel code, the helper enumeration, the calling
convention table, MAX_TAIL_CALL_CNT, the eight-frame limit and the order of passes in bpf_check()
are from the 5.15 tarball. libbpf’s relocation and pin-naming behaviour is from libbpf 0.5.0’s source.
What I’d still change. The reading of each x86-64 instruction’s bytes is by hand, against the JIT’s own comments and objdump’s decoding, and I’d rather have had a tool print the BPF-to-x86 mapping than reconstruct it. And this is one small program on one architecture: the arm64 JIT maps the same eleven registers onto different hardware, and a program with loops, packet access or BTF-typed pointers would exercise parts of the JIT this one never touches.
Eleven Registers and a 512-Byte Stack