Technique:Recognizing compiler-generated code/Switch jump tables
Appearance
Topic page of Technique:Recognizing compiler-generated code.
How compilers lower a dense C switch to an unsigned bounds check followed by an indirect jump through a table, and how the table entries are encoded on x86, x64 (image-relative 32-bit) and AArch64 (byte, halfword or word offsets from a label).
A dense switch becomes: subtract the lowest case value, unsigned-compare with the case count, branch to the default case when above, then an indirect jump through a table of code addresses. The table is data in .rdata / .rodata that disassemblers often fail to follow.
Shapes
- x86 (absolute):
lea eax, [ecx-1]; cmp eax, 6; ja default; jmp dword ptr [table + eax*4]; table entries are absolute addresses (they have base relocations in a PE). - x64 MSVC (relative):
cmp eax, 6; ja default; lea rdx, __ImageBase; mov ecx, [rdx+rax*4+table_rva]; add rcx, rdx; jmp rcx: entries are 32-bit RVAs from the image base. Some MSVC tables are split by an additional byte-index table (movzx eax, byte ptr [index+rax]) when several cases share targets (two-level: byte table selects an entry of the dword table). Unverified: from memory of MSVC output. - x64 GCC/Clang, PIC:
lea rdx, table(%rip); movslq (%rdx,%rax,4), %rax; add %rdx, %rax; jmp *%rax: entries are signed 32-bit offsets relative to the table start (.long .L5-.L4). Non-PIC code can use absolutejmp *table(,%rax,8). Unverified: from memory of GCC output. - AArch64 (LLVM): the JumpTableDest8/16/32 pseudo lowers to
adr x, <label>; ldrb|ldrh|ldrsw w/x, [table, index, ...]; add x, x, w, sxtw #2; br x. Entries are 1, 2 or 4 bytes; for the 1- and 2-byte forms they count instructions (4-byte steps) from theadrbase label, so the offset islabel + entry*4(ldrbwith no scaling,ldrhscaled by 2,ldrswscaled by 4). The 4-byte form is a signed word. (Read inAArch64AsmPrinter::LowerJumpTableDest: the finaladduses shift 0 for 4-byte entries and shift 2 for the compressed forms.)
Recovery
- Find the bounds check: the
ja/b.hitarget is the default case; the immediate is the number of entries minus one. - Read the table at the address in the instruction, N entries of the stride the code uses, decode them as above, and label the targets as cases.
- Case values are index plus the constant subtracted before the compare. Sparse switches use a binary search of compares instead, or a hash/lookup table; cases sharing a handler repeat the same target.
- Ghidra and IDA recover most tables; when they miss (indirect jump shown as
jmp rax), define the table manually and set the switch override.
Evidence & references
- llvm-project
llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp(LowerJumpTableDest). - x86/x64 shapes: Unverified, not read in a source for this page.