Assembly and Low-Level Language Fundamentals Questions
Programming and debugging at the instruction level. Covers reading and writing assembly for x86-64 and ARM (A32, Thumb, AArch64), including small hand-written routines, vector (SIMD) code and exclusive load/store atomics, registers, the stack and frame layout, prologues and epilogues, calling conventions and ABIs (System V, Microsoft x64, AAPCS), variadic calls, inline assembly and its constraints and clobbers, Cortex-M exception entry and context-switch code written in assembly, and how compilers translate and optimize source into machine code (optimization flags, inlining, tail calls, LTO, aliasing, strength reduction, virtual dispatch, memcpy lowering, stack spills). Also covers object files and linking as they affect generated code (ELF, PE/COFF and Mach-O, relocations, GOT and PLT, position-independent code, static linking, stack unwinding), the compiler backend ideas behind it (SSA, register allocation, instruction selection, peephole passes) and emitting machine code from a minimal JIT. On the debugging side: reading disassembly, using gdb and lldb for registers, frames, breakpoints and watchpoints, analyzing core dumps and stripped binaries with addr2line and build IDs, and diagnosing crashes from instruction-level state such as corrupted returns, stack smashing, ABI mismatches and optimizer-induced bugs. Debugging method in general, hardware probe tooling, malware analysis and exploit-mitigation design are covered elsewhere.
A hardened Linux binary uses dynamic linking, and you need to understand how a function call resolves at runtime. How would you use readelf to inspect relocations, PLT/GOT entries, and symbol tables, and why does that matter when debugging a crash or a suspected hook/injection issue?
Sample Answer
Direct answer
In a dynamically linked program, a call to a library function goes to a small stub in the PLT (procedure linkage table) in the executable, which jumps through an address stored in a slot of the GOT (global offset table, an array of addresses the dynamic linker fills in). The dynamic linker (also called the loader, ld.so) is the program that maps the shared libraries at startup and fills in those slots. With lazy binding a slot is filled at the first call of that function; with immediate binding, at startup. One call, greet(), is followed through every section below: the bl in main, the stub, the slot, and the slot's contents before and after the first call. readelf shows the static layout of that machinery, and gdb shows what the slots hold at runtime. The ordered inspection is: dynamic section (what libraries, what flags), program headers (RELRO), relocation table (which slots exist and their types), dynamic symbols (which names are imported), then the stubs themselves and the slot contents in a live process. It matters for crashes and hooks because a corrupted or redirected slot makes the br in the stub jump to the wrong address, and because the binding mode (lazy or immediate) and RELRO decide whether the slots can be changed at all.
Test program
The listings are AArch64 (Arm 64-bit). On x86-64 the same machinery appears with R_X86_64_JUMP_SLOT and R_X86_64_GLOB_DAT relocation names, and a PLT stub is an indirect jump through the slot (jmp *slot(%rip)) instead of the adrp/ldr/br sequence. The readelf steps are identical.
#include <stdio.h>
void greet(void) { puts("hello from libgreet"); }
#include <stdio.h>
void greet(void);
int main(void) {
greet();
greet();
puts("done");
return 0;
}
Built in a gcc:14 container (GCC 14.4.0, aarch64, native), once with lazy binding and no RELRO and once with immediate binding and full RELRO:
gcc -shared -fPIC libgreet.c -o libgreet.so
gcc -O1 -fPIE -pie main.c -L. -lgreet -Wl,-rpath,'$ORIGIN' -Wl,-z,lazy -Wl,-z,norelro -o app_lazy
gcc -O1 -fPIE -pie main.c -L. -lgreet -Wl,-rpath,'$ORIGIN' -Wl,-z,relro -Wl,-z,now -o app_full
PIE (position-independent executable) means the executable itself can be loaded at any address, and ASLR (address space layout randomization) is the kernel feature that picks a different random load address each run. RELRO ("relocation read-only") means the loader makes the GOT read-only after it has filled it in; -z now asks the loader to resolve every symbol at startup instead of at first call.
1. The dynamic section: libraries and binding flags
readelf -d app_full | grep -E "NEEDED|RUNPATH|BIND_NOW|FLAGS":
0x0000000000000001 (NEEDED) Shared library: [libgreet.so]
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
0x000000000000001d (RUNPATH) Library runpath: [$ORIGIN]
0x000000000000001e (FLAGS) BIND_NOW
0x000000006ffffffb (FLAGS_1) Flags: NOW PIE
The dynamic section is the table the loader reads first. NEEDED lists the libraries that will be loaded, RUNPATH lists directories the loader searches for the executable's direct dependencies, after LD_LIBRARY_PATH and before the system library cache and default directories (a writable directory here would let someone substitute a library), and BIND_NOW records immediate binding. In app_lazy, the same command shows no BIND_NOW and only Flags: PIE.
2. Program headers: is there RELRO?
readelf -lW app_full | grep RELRO prints a GNU_RELRO segment (offset 0x00fd68, size 0x298); the same command on app_lazy prints nothing for RELRO. In a running app_full (info proc mappings in gdb) the page holding the GOT is r--p (read-only) after startup; the page after it is rw-p. In app_lazy, the page with .got and .got.plt is rw-p for the whole run.
3. Relocations: which slots exist
readelf -rW app_full | grep -E "JUMP_SLOT|GLOB_DAT" prints ten lines (four R_AARCH64_GLOB_DAT and six R_AARCH64_JUMP_SLOT, the latter including __libc_start_main, __cxa_finalize, __gmon_start__ and abort). Only the two JUMP_SLOT lines for greet and puts are shown here; the other eight lines are omitted and the two shown are as printed:
000000000001ffb0 0000000600000402 R_AARCH64_JUMP_SLOT 0000000000000000 greet + 0
000000000001ffc8 0000000900000402 R_AARCH64_JUMP_SLOT 0000000000000000 puts@GLIBC_2.17 + 0
A symbol table is the list of names a file defines or needs; --dyn-syms shows the part the loader uses. Each relocation line says: at address 0x1ffb0 in the image, the dynamic linker must store the address of greet. In the AArch64 ELF specification, R_AARCH64_JUMP_SLOT (code 1026, matching the 0x402 at the end of the info column) is the relocation for PLT entries, and R_AARCH64_GLOB_DAT (code 1025, 0x401) fills a GOT entry with a resolved symbol address; in this binary the GLOB_DAT entries are for __cxa_finalize, __gmon_start__ and the _ITM_ transactional-memory symbols, not for greet or puts. readelf --dyn-syms -W app_full | grep -E "greet|puts" shows both as UND (undefined in this file, to be supplied by another library at load time), while readelf --dyn-syms -W libgreet.so shows greet defined (FUNC GLOBAL DEFAULT 10) and puts undefined there too.
4. The stubs and the slots, lazy binding in action
objdump -d app_lazy shows main calling the stub, and the stub loading the slot. The listing is trimmed: the raw-bytes column, the file format header, the Disassembly of section header lines, the <main>: label line, the instructions of main before 76c and after 770, the // ... comment objdump prints after some instructions of main, and every other function and stub are omitted. The blank line stands for everything objdump prints between main and the stub, which it prints elsewhere in .plt. The two bl lines and the four stub instructions are otherwise as printed:
76c: bl 5f0 <greet@plt>
770: bl 5f0 <greet@plt>
00000000000005f0 <greet@plt>:
5f0: adrp x16, 10000 <__abi_tag+0xf75c>
5f4: ldr x17, [x16, #2864]
5f8: add x16, x16, #0xb30
5fc: br x17
The stub computes the slot address: adrp x16, 10000 puts the 4 KiB page address 0x10000 in x16, and the ldr adds the byte offset 2864 (0x10b30 - 0x10000 = 0xb30 = 2864), matching the JUMP_SLOT offset for greet in app_lazy's relocation table (readelf -rW app_lazy lists 0000000000010b30 ... R_AARCH64_JUMP_SLOT ... greet). It loads the pointer from the slot into x17 and jumps with br x17. Two kinds of stub exist in .plt: the first entry (PLT0, at 0x5b0, the start of .plt per readelf -SW) is the shared lookup stub that calls into the dynamic linker's resolver, and each later entry such as greet@plt at 0x5f0 is a small per-function stub like the one above. The two constants in the script below come from the files: 0x764 is the address of main in app_lazy (nm app_lazy | grep ' main'), so &main - 0x764 is the address where the whole executable was loaded (the load base, which ASLR would otherwise change on every run), and 0x10b30 is the slot's address from the relocation table, so base + 0x10b30 is the slot in the running process. x/gx ADDR in gdb examines one 8-byte word, and info symbol names the function containing an address. The break *($base + 0x770) stops at the second bl, that is after the first greet() call has returned. This gdb script (lazy.gdb), run with gdb -q -batch -x lazy.gdb ./app_lazy, reads the slot before and after the first call (gdb turns address-space randomization off, so these addresses repeat; a normal run shifts them):
set pagination off
break main
run
set $base = (long)&main - 0x764
printf "load base of app_lazy: %#lx\n", $base
printf "GOT slot for greet (file offset 0x10b30) at %#lx\n", $base + 0x10b30
printf "before first call: slot holds %#lx = ", *(long*)($base + 0x10b30)
info symbol *(long*)($base + 0x10b30)
break *($base + 0x770)
continue
printf "after first call: slot holds %#lx = ", *(long*)($base + 0x10b30)
info symbol *(long*)($base + 0x10b30)
info proc mappings
Output of one run (gdb 16.3, aarch64, working directory /w) in which gdb was allowed to disable randomization, filtered to the four lines the script prints with printf (the before and after lines each join the printf text and the info symbol answer). Removed: gdb's Breakpoint 1 at ... and Breakpoint 2 at ... lines, the Breakpoint 1, ... in main () stop lines, the thread-debugging messages, the process N line and the whole info proc mappings table. A container that cannot disable randomization prints different addresses, so only the offsets (0x5b0, 0x584, 0x10b30) are reproducible:
load base of app_lazy: 0xaaaaaaaa0000
GOT slot for greet (file offset 0x10b30) at 0xaaaaaaab0b30
before first call: slot holds 0xaaaaaaaa05b0 = No symbol matches *(long*)($base + 0x10b30).
after first call: slot holds 0xfffff7f90584 = greet in section .text of libgreet.so
With the working directory set to the directory holding the files, as here, gdb prints the library as libgreet.so in the info symbol answer; started from another directory (cd /; gdb ... /w/app_lazy) it prints /w/libgreet.so. The load base is the same on every run only where gdb is allowed to disable address randomization (its default, set disable-randomization on). In a container that forbids the personality system call gdb warns about it and the base changes from run to run; the offsets, such as base + 0x5b0, stay the same. The address inside libgreet.so also depends on where the C library is mapped.
No symbol matches is gdb's answer from info symbol when no symbol covers the address. info symbol finds no symbol at base + 0x5b0, the start of the shared lookup stub (PLT0), which has no name of its own; the per-function stubs are named (info symbol $base + 0x5f0 prints greet@plt in section .plt of /w/app_lazy). So the message only says that the slot does not hold the address of a named function in a shared library. Before the first call, the slot holds base + 0x5b0, the address of the first entry in .plt (the lookup stub in the executable, whose .plt section begins at 0x5b0 per readelf -SW). The first call goes into the dynamic linker's resolver, which finds greet in libgreet.so, writes its address into the slot, and jumps there. After that first call, the slot holds the real address, so the second bl goes straight through. In app_full (BIND_NOW) the slot already holds the final address at main. The same script with set $base = (long)&main - 0x7a4 (the offset of main in app_full, from nm), the slot offset 0x1ffb0 and the second breakpoint at $base + 0x7b0 (the second bl in app_full's main) prints before first call: slot holds 0xfffff7f90584 = greet in section .text of libgreet.so, and the same value after the first call.
5. Why it matters for crashes and hooks
- A crash whose
pcis a wild address, reached straight from a PLT stub'sbr x17, points to a corrupted slot: inspectx/gxof the slot address from the relocation table and runinfo symbolon its value. A healthy slot is either the PLT lookup address (not yet bound) or inside the right library. - Hooking by preloading a library leaves the file unchanged, so check runtime state. The dynamic linker can show who a symbol was bound to:
LD_DEBUG=bindings ./app_lazyincludesbinding file ./app_lazy [0] to /w/libgreet.so [0]: normal symbol `greet', and with a preloaded library that definesputs,LD_PRELOAD=./hook.so LD_DEBUG=bindings ./app_fullprintsbinding file ./app_full [0] to ./hook.so [0]: normal symbol `puts' [GLIBC_2.17]and the same for/w/libgreet.so. - The preloaded library, built with
gcc -shared -fPIC hook.c -o hook.soand used asLD_PRELOAD=./hook.so ./app_full:
#include <string.h>
#include <unistd.h>
int puts(const char *s) {
write(1, "[hooked] ", 9);
write(1, s, strlen(s));
write(1, "\n", 1);
return 0;
}
[hooked] hello from libgreet
[hooked] hello from libgreet
[hooked] done
Both the executable's puts and the library's puts were bound to the hook, with no change to either file. readelf on the files cannot show this; the environment (LD_PRELOAD), LD_DEBUG, /proc/PID/maps and slot contents can.
- With full RELRO plus
BIND_NOW, the slots are final and read-only frommainonward, so a later write through an ordinary memory-corruption bug into the GOT faults instead of redirecting calls. Without RELRO and with lazy binding the slots are writable for the whole run. That is the cost of the lazy design: its first call per function is slower (resolver work) but startup is faster;BIND_NOWshifts all that work to startup. - A debugger or tracer (ptrace, the Linux system call debuggers use to inspect and modify another process) can still write to read-only pages, so RELRO protects against in-process bugs and exploits, not against a debugger-level attacker.
How does a call to a shared-library function such as printf actually get resolved at runtime on x86-64 Linux? Walk through what the dynamic linker does, what the call site looks like, and how lazy binding differs from immediate binding.
Sample Answer
Direct answer
The executable cannot contain the address of printf or puts, because the C library is loaded at an address chosen at run time. So the call site calls a small stub in the executable, the PLT (procedure linkage table). The stub jumps through a pointer stored in the GOT (global offset table, a writable array of addresses the dynamic linker fills in). With lazy binding the pointer initially points back into the stub, which hands control to the dynamic linker (ld.so, the program that loads shared libraries and resolves symbols); the linker looks the symbol up, writes the real address into the GOT slot and jumps there. Every later call goes through the same stub but lands directly in libc. With immediate binding (LD_BIND_NOW or the -z now link flag) the linker fills in every slot before main starts, so no call ever takes the slow path.
The artifacts on x86-64 Linux
The program (greet.c):
#include <stdio.h>
int main(void)
{
puts("first call");
puts("second call");
return 0;
}
Built with gcc -O1 -o greet greet.c (GCC 14.4 in a linux/amd64 container, emulated; this toolchain produced a non-PIE executable with lazy binding, and readelf -d shows no BIND_NOW flag). The main function from objdump -d --no-show-raw-insn greet (the flag drops the column of machine-code bytes):
0000000000401126 <main>:
401126: sub $0x8,%rsp
40112a: mov $0x402004,%edi
40112f: call 401030 <puts@plt>
401134: mov $0x40200f,%edi
401139: call 401030 <puts@plt>
40113e: mov $0x0,%eax
401143: add $0x8,%rsp
401147: ret
A relocation is a record that tells the loader "patch this address with the real address of that symbol". The linker emitted one of type R_X86_64_JUMP_SLOT, which tells ld.so which GOT slot belongs to puts. It is in the .rela.plt section of the readelf -rW greet output (the .rela.dyn section that readelf prints before it is omitted here). In the Info column, the high 32 bits (00000002) are the symbol-table index of puts and the low 32 bits (00000007) are the relocation type, 7 = R_X86_64_JUMP_SLOT:
Relocation section '.rela.plt' at offset 0x468 contains 1 entry:
Offset Info Type Symbol's Value Symbol's Name + Addend
0000000000404000 0000000200000007 R_X86_64_JUMP_SLOT 0000000000000000 puts@GLIBC_2.2.5 + 0
The PLT (objdump -d --no-show-raw-insn -j .plt greet, with its file-header lines (greet: file format elf64-x86-64, Disassembly of section .plt:) and the blank lines around them omitted). The first entry, puts@plt-0x10, is PLT0, the shared resolver stub, and puts@plt is the stub for puts. This listing is in AT&T syntax, so the source operand comes first and the destination last, $ marks an immediate value, * marks an indirect jump through memory, and 0x2fca(%rip) is a memory operand at the address of the next instruction plus 0x2fca; the # 403ff0 <...> text is objdump's annotation with the address that operand works out to. nopl is a multi-byte no-operation used as padding, and psABI below means the processor-specific ABI supplement, the document that fixes these rules for x86-64:
0000000000401020 <puts@plt-0x10>:
401020: push 0x2fca(%rip) # 403ff0 <_GLOBAL_OFFSET_TABLE_+0x8>
401026: jmp *0x2fcc(%rip) # 403ff8 <_GLOBAL_OFFSET_TABLE_+0x10>
40102c: nopl 0x0(%rax)
0000000000401030 <puts@plt>:
401030: jmp *0x2fca(%rip) # 404000 <puts@GLIBC_2.2.5>
401036: push $0x0
40103b: jmp 401020 <_init+0x20>
The push $0x0 at 0x401036 pushes relocation index 0. The GOT as stored in the file (objdump -s -j .got.plt greet, with its file-header lines and blank lines omitted) holds 8-byte little-endian entries starting at 0x403fe8, and the right-hand column is objdump's ASCII rendering of the bytes:
Contents of section .got.plt:
403fe8 083e4000 00000000 00000000 00000000 .>@.............
403ff8 00000000 00000000 36104000 00000000 ........6.@.....
Each 8-byte entry is stored with its least significant byte first, so the bytes 08 3e 40 00 00 00 00 00 are reversed to 0x0000000000403e08, and 36 10 40 00 00 00 00 00 to 0x0000000000401036. That reads: slot 0 = 0x403e08 (the address of the _DYNAMIC section), slots 1 and 2 = 0, slot 3 (0x404000, the slot for puts) = 0x401036, the address of the push $0 instruction right after the jmp in the puts stub.
The first call, step by step
The System V x86-64 psABI (the ABI document) describes this sequence:
maincallsputs@plt(0x401030).- The first instruction jumps to the address in the GOT entry for
puts. Initially that entry "holds the address of the followingpushqinstruction, not the real address" of the function, so the jump falls straight through to the next instruction. push $0pushes the relocation index (the position ofputs's relocation in.rela.plt), then the stub jumps to PLT0.- PLT0 pushes the second GOT entry (GOT+8, which the psABI describes as one word of identifying information for the dynamic linker, set when the program image is created) and jumps through the third GOT entry (GOT+16), which the dynamic linker set to its own resolver. The psABI says that on x86-64 GOT entries one and two are reserved for this purpose.
- The resolver uses the relocation index to find the
R_X86_64_JUMP_SLOTentry (the relocation record shown above), looks the symbol up in the loaded libraries, stores the real address in the GOT slot (0x404000), and jumps toputs. - On the second call, step 2's jump goes directly to
putsin libc; the dynamic linker is never entered again for this symbol.
The last call returns to main normally: the resolver's work is invisible except for the first call being slower.
Observing the GOT slot change
This program reads slot 3 of the GOT before and after the first call (non-PIE, so _GLOBAL_OFFSET_TABLE_ is the start of .got.plt, and puts is the first PLT function referenced):
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
/* Linker-defined symbol: the start of .got.plt. Slots 0-2 are reserved for the
dynamic loader; the first PLT function (here puts) owns slot 3. */
extern void *_GLOBAL_OFFSET_TABLE_[];
int main(void)
{
void *before = _GLOBAL_OFFSET_TABLE_[3];
puts("hello"); /* first call goes through the PLT */
void *after = _GLOBAL_OFFSET_TABLE_[3];
void *real = dlsym(RTLD_DEFAULT, "puts");
printf("slot changed by first call: %s\n", before != after ? "yes" : "no");
printf("slot now equals libc puts: %s\n", after == real ? "yes" : "no");
return 0;
}
Built as gcc -O1 -no-pie -Wl,-z,lazy -o got_peek got_peek.c and as -Wl,-z,now, on linux/amd64 (emulated). Output (the two -- heading lines name the build that was run and were printed by a shell echo; the rest is the program's own output):
-- lazy:
hello
slot changed by first call: yes
slot now equals libc puts: yes
-- -z now:
hello
slot changed by first call: no
slot now equals libc puts: yes
With lazy binding the slot changes on the first call; with -z now it already held the final address before the call.
LD_DEBUG=bindings shows the same moment from the loader's side. With lazy binding, the symbol is bound after transferring control (when main is already running); with LD_BIND_NOW=1 it is bound before. Run as LD_DEBUG=bindings ./greet 2>&1 | grep -E 'puts|first|second|calling init|transferring' (and the same with LD_BIND_NOW=1 in front), with the process-id prefix and leading whitespace of each line removed and the lazy: and LD_BIND_NOW=1: headings added by hand; every other line the filter drops is omitted. Read the lines as follows: calling init lines show the loader running each library's start-up code; transferring control: ./greet is the point where the loader hands over to the program's own entry point, so everything after it is the program running; binding file ./greet ... to .../libc.so.6 ...: normal symbol puts'is the loader resolving the reference fromgreettoputsin libc, and the version tag[GLIBC_2.2.5]is the symbol version it matched (the bracketed[0]numbers can be ignored here).first callandsecond callare the program's own output. Because the pipe makesputsbuffer its output until the program exits, these two lines print last in both modes, so they do not mark when each call happened; thetransferring controlline is the marker for when the program's own code starts running, and the binding line shows whetherputs` was resolved before or after it:
lazy:
calling init: /lib64/ld-linux-x86-64.so.2
calling init: /lib/x86_64-linux-gnu/libc.so.6
transferring control: ./greet
binding file ./greet [0] to /lib/x86_64-linux-gnu/libc.so.6 [0]: normal symbol `puts' [GLIBC_2.2.5]
first call
second call
LD_BIND_NOW=1:
binding file ./greet [0] to /lib/x86_64-linux-gnu/libc.so.6 [0]: normal symbol `puts' [GLIBC_2.2.5]
calling init: /lib64/ld-linux-x86-64.so.2
calling init: /lib/x86_64-linux-gnu/libc.so.6
transferring control: ./greet
first call
second call
Lazy versus immediate binding
| Lazy | Immediate (-z now, LD_BIND_NOW) | |
|---|---|---|
| When symbols resolve | on first call of each function | all, before main |
| Startup cost | low | higher: every imported function is looked up |
| First-call cost | one trip through the resolver | none |
| Failure mode | an unresolvable function fails when first called, possibly late | fails at startup |
| GOT writability | .got.plt slots must stay writable at run time | GOT can be made read-only after relocation |
RELRO (relocation read-only: the loader makes parts of the GOT read-only once it is done) shows the last row. Linking greet.c three ways (gcc -O1 -o greet greet.c with -Wl,-z,norelro, -Wl,-z,relro,-z,lazy and -Wl,-z,relro,-z,now) and reading readelf -lW and -SW gives the table below, which is a hand-built summary of those two outputs (the GNU_RELRO segment is the address range the loader write-protects after relocation; the address and size columns of the program header were combined into a start-to-end range):
| Link flags | GNU_RELRO range | Where the puts slot is | Is it write-protected? |
|---|---|---|---|
-z norelro | no such segment | .got.plt | no |
-z relro -z lazy | 0x403df8 to 0x404000 | 0x404000, the first byte after the range | no, so lazy binding can still write it |
-z relro -z now | 0x403dd0 to 0x404000 | inside .got (0x403fd0 to 0x404000), which is covered | yes |
With lazy binding the protected range still includes .got (0x403fd8) and the reserved first three slots of .got.plt (0x403fe8 to 0x404000), but the lazily filled slot at 0x404000 sits just past the end and stays writable. With -z now there is no lazy slot, so the function slots move into .got and the whole table is protected. For a penetration tester this is the practical difference: overwriting a function's GOT slot to redirect a later call requires the slot to be writable at run time, which lazy binding requires and "full RELRO" (relro plus now) removes.
Pitfalls
LD_DEBUGandLD_BIND_NOWare environment variables read byld.so; they are useful for diagnosis, not for deployment.
You suspect a pointer arithmetic bug in a crypto routine, but you need to prove it without permanently modifying the code. In GDB or LLDB, how would you inspect and, if safe, temporarily modify registers or memory to confirm your hypothesis while avoiding side effects that could hide the bug?
Sample Answer
Direct answer
State the hypothesis as a number you can read off, observe it with commands that only read, and only then change state, once, at one named point, on the running process and never in the file. For a pointer-arithmetic bug the number is usually a stride or an offset: "block i should start 16 bytes after block i-1, but the pointer moves 64". Reading registers and memory (info registers, x, print) does not change the program. Changing one value in the live process and watching the result move to the known-good answer confirms the hypothesis without touching the binary or the source.
The bug and the evidence
A stand-in for the routine: it should XOR the first word of each 16-byte block (4 words of 32 bits) of a key. The pointer type is uint32_t *, so adding i * 16 moves 16 words (64 bytes), not 16 bytes:
#include <stdint.h>
#include <stdio.h>
/* XOR the first word of each 16-byte (4-word) block of the key. */
uint32_t fold_blocks(const uint32_t *key, size_t nblocks) {
uint32_t acc = 0;
for (size_t i = 0; i < nblocks; i++) {
const uint32_t *blk = key + i * 16;
acc ^= blk[0];
}
return acc;
}
int main(void) {
uint32_t key[16];
for (int i = 0; i < 16; i++)
key[i] = 0x9e3779b9u * (uint32_t)(i + 1);
printf("acc=0x%08x\n", fold_blocks(key, 4));
return 0;
}
The expected value is key[0] ^ key[4] ^ key[8] ^ key[12] = 0x0e0070c0 (computed separately). Built with gcc -O0 -g -fno-stack-protector (GCC 14.4, AArch64, gdb 16.3 in an AArch64 Linux container), the program prints a different wrong value on nearly every run, because it reads past key into whatever sits on the stack. That run-to-run change is itself a clue: the code reads memory it does not own.
Inspecting without changing anything
Commands run at the breakpoint on line 9 (acc ^= blk[0];), then continue to reach the second iteration (gdb -batch session). The same p, x and info registers commands were also run at the first stop, where blk equals key and the history numbers $1 to $3 were used; the transcript below starts at the second stop and omits the Breakpoint 1, fold_blocks (...) stop lines and the source line gdb prints with them. Command syntax: p EXPR prints a C expression; the $4, $5 labels are gdb's value history numbers, which can be reused in later expressions; x/2wx ADDR examines memory (x), 2 units, each a w word (4 bytes), printed in hexadecimal (x); info registers x0 x1 pc prints those registers; set var blk = ... assigns to a program variable in the live process.
(gdb) p i
$4 = 1
(gdb) p (char*)blk - (char*)key
$5 = 64
(gdb) p blk - key
$6 = 16
(gdb) x/2wx blk
0xfffff3fae238: 0x00000000 0x00000010
(gdb) x/2wx key+4
0xfffff3fae208: 0x1715609d 0xb54cda56
(gdb) info registers x0 x1 pc
x0 0xfffff3fae238 281474775048760
x1 0xfffff3fae1f8 281474775048696
pc 0x400670 0x400670 <fold_blocks+44>
Explanation of the numbers: at i = 1 the distance between blk and key is 64 bytes (16 elements of 4 bytes each), where the intent was 16 bytes (4 elements). x/2wx blk shows the word the code actually reads (unrelated stack data), while x/2wx key+4 shows the word it should read, 0x1715609d, which is key[4]. On AArch64 x0 holds blk, the pointer just computed, and x1 holds key; their difference is 0x40, the 64-byte stride. (AArch64 x0 to x30 are the 64-bit general registers, the counterpart of rax, rdi and so on.) At -O0 variables normally live on the stack, so x0 and x1 hold these values only because the instructions just before the breakpoint computed them: lsl x0, x0, #6 (shift left 6, multiply by 64, which is i * 16 words times 4 bytes), ldr x1, [sp, #8] (load key from the stack), add x0, x1, x0 (key plus offset), then str x0, [sp, #24] stores blk into its stack slot. The breakpoint line then reloads blk from [sp, #24], which is why set var blk (which writes that slot) takes effect, with no register edit needed. Reading was all that was needed to establish the claim: these commands do not write to the process or the file.
Confirming the fix by changing live state once
At the breakpoint, set the pointer to the intended value:
(gdb) set var blk = key + i * 4
(gdb) p (char*)blk - (char*)key
$7 = 16
(gdb) p/x blk[0]
$8 = 0x1715609d
The stride is now 16 bytes and blk[0] is the correct word. To confirm the whole routine, apply the same assignment at every iteration with a breakpoint commands block in a gdb script (break 9, commands 1, silent, set var blk = key + i * 4, continue, end, run). commands 1 attaches the lines that follow, up to end, to breakpoint 1, so gdb runs them each time it stops there; silent suppresses the stop message. The program then printed acc=0x0e0070c0, the expected value, and md5sum of the executable printed the same digest before and after the session (the digest depends on the build, so it is not quoted here), because gdb edits the process's memory and registers, not the file.
Avoiding side effects that hide the bug
- Do not
set write onor patch the file. Keep every change in the live process. Changes to the process disappear when it exits, so nothing persists. - Keep the scope small. Change one value at a named instruction, then compare against a known-good test vector, not real key material. Assigning a register that holds a pointer used later changes every later use; say which uses you expect to change.
- Remember what the debugger itself changes. gdb disables address-space randomization by default (ASLR, which randomizes where the stack and heap start), and runs the program under ptrace (the Linux system call a debugger uses to control and inspect another process), so an overflow that depends on layout or timing can vanish.
set disable-randomization offkeeps the normal layout (in the container used here, gdb printedError disabling address space randomization: Operation not permitted, so check what your own session actually did). Software breakpoints temporarily replace an instruction with a trap (an instruction that deliberately transfers control to the debugger), so single-stepping through a race changes its timing. - Prefer a hardware watchpoint to a breakpoint inside a hot loop.
watch accprintedHardware watchpoint 2: acc; hardware watchpoints use the CPU's debug registers (a few special registers that hold addresses the CPU watches and traps on), so the program runs at full speed between writes to the watched address, whereas a software watchpoint single-steps the program and checks the value after every instruction. - Do not call functions from the debugger that have side effects (
call,print f()), such as ones that advance a cipher state or free memory. - In optimized builds the variable may live only in a register;
info registersandset $x2 = ...operate on that register, and the same change can affect every later use, so confirm with the disassembly where the register is read next.
LLDB equivalents
The same session in LLDB 19.1.7 (AArch64 container; settings set target.disable-aslr false was needed because run failed with personality set failed: Operation not permitted). The transcript is the second stop of the session (after run and continue); the stop reports with their source listings and the first stop's output are omitted, and addresses and $ numbers vary from run to run:
(lldb) settings set target.disable-aslr false
(lldb) breakpoint set -l 9
Breakpoint 1: where = fold`fold_blocks + 44 at fold.c:9:19, address = 0x0000000000400670
(lldb) run
(lldb) continue
(lldb) frame variable i blk
(size_t) i = 1
(const uint32_t *) blk = 0x0000fffff3d863b8
(lldb) register read x0 x1 pc
x0 = 0x0000fffff3d863b8
x1 = 0x0000fffff3d86378
pc = 0x0000000000400670 fold`fold_blocks + 44 at fold.c:9:19
(lldb) memory read -f x -s 4 -c 2 blk
0xfffff3d863b8: 0x00000000 0x00000010
(lldb) expression -- (long)blk - (long)key
(long) $3 = 64
(lldb) expression -- blk = key + i * 4
(const uint32_t *) $4 = 0x0000fffff3d86388
(lldb) expression -- (long)blk - (long)key
(long) $5 = 16
In LLDB, breakpoint set -l 9 sets a breakpoint at line 9, frame variable prints locals, register read and memory read -f x -s 4 -c 2 blk read registers and memory (-f x hex format, -s 4 four-byte units, -c 2 count 2, the counterpart of x/2wx), and expression evaluates C in the frame and can assign. The same session accepted register write x2 0x5 (followed by register read x2, which showed 0x5), memory write -s 4 blk 0x11111111 (read back as 0x11111111) and watchpoint set variable acc, which stopped when acc was first written (old value: 0, new value: 2654435769). Use watchpoint set variable for a variable: watchpoint set expression -- acc is accepted too, but it evaluates acc and watches the memory at the address equal to that value (it reported addr = 0x9e3779b9, the value acc held at that moment), so it watches the wrong thing.
A stack buffer overflow is suspected in a service, but the crash is intermittent. How would you use the debugger to catch the exact instruction that corrupts the stack, and how would you tell whether the overwrite happened before or after the function's return address was last used?
Sample Answer
Direct answer
Find the memory slot that holds the return address (the saved copy of the address the CPU jumps back to when the function finishes), then ask the CPU to stop the instant anything writes to it. That is a hardware watchpoint: gdb programs the processor's debug registers so the write traps right after the offending instruction completes. The stop shows you the exact instruction (and its caller chain). To decide "before or after the return address was last used", note that the address is used once, by the ret at the end of the function that owns the slot: if the watchpoint fires while that function (or its callees) is still on the backtrace, the overwrite came first and ret then jumps to the corrupted value; if the write only shows up after that ret ran, the slot belongs to a dead frame and the stack was reused, which is a different bug (a stale pointer into a returned frame), not a smashed return address.
Where the return address lives (it differs by architecture)
A stack frame is the stack space one function call owns: its saved registers, its locals and its saved return address. On x86-64, call pushes the return address, so it sits above the callee's locals. For the program below, GCC 14.4 at -O0 puts name at [rbp-16], the saved rbp at [rbp] and the return address at [rbp+8], so the bytes from name upward are: offsets 0 to 15 are name itself, 16 to 23 are the saved rbp, and 24 to 31 are the return address. A copy that writes 25 or more bytes (counting the terminating NUL that strcpy adds) reaches the return address; exactly 24 bytes stops after the saved rbp. (That -O0 layout is what the x86-64 compiler's assembly output (-S) shows for this program.) On AArch64 the return address arrives in register x30 (the link register, which bl fills in instead of pushing onto the stack) and a non-leaf function saves it with stp x29, x30, [sp, #-48]! at the bottom of its frame, with locals above it. There, the same overflow runs upward out of parse into the caller's frame and corrupts main's saved x30, not parse's. Read the layout from the debugger, not from a diagram.
The program
#include <stdio.h>
#include <string.h>
static void parse(const char *input) {
char name[16];
strcpy(name, input); /* no length check */
printf("hello %s\n", name);
}
int main(void) {
parse("short");
parse("this input is much longer than sixteen bytes");
return 0;
}
Built with gcc -O0 -g -fno-stack-protector -no-pie -o overflow overflow.c (GCC 14.4, aarch64 Linux). The stack protector is off so that nothing stops the overflow before gdb sees it.
The ordered procedure
- Reproduce under the debugger and stop in a state where the slot exists. Break at the entry of the suspect function. A breakpoint condition such as
$_streq(input, "...")(gdb's built-in string-equals function) stops only for the bad input; when no input distinguishes the bad call,ignore N countskips the first N hits instead. Attach withgdb -p <pid>for a running service. - Locate the return-address slot.
info framefor the frame that owns it prints "saved registers" with the stack address of the saved return register (x30 at 0x...on AArch64,rip at 0x...on x86-64). - Set a hardware watchpoint on that address, using
watch -l(location: evaluate the expression once, take its address, and watch that fixed memory) so it stays attached to the memory even when the frame changes, and run. The expression*(unsigned long *)0xfffffffff978means "treat this number as the address of an 8-byte unsigned integer". - At the stop, read the evidence. Hardware watchpoints report after the writing instruction has completed, so the culprit is the instruction before
$pc, the program counter ($pcis the address of the next instruction to run).x/2i $pc-4means "examine 2 instructions starting at$pcminus 4": on fixed-width AArch64 (every instruction is 4 bytes) the first line is the instruction that just executed and wrote the slot, and the second line, marked=>, is the one about to run. On x86-64 instructions vary in length, so a start address a few bytes back can land inside an instruction and decode as nonsense (x/3i $pc-8did exactly that in the x86-64 session described below); usedisassembleon the function that gdb names, or on a range that starts at a known instruction boundary, and read the instruction just above the=>marker, or usebtand the function it names.btshows who called it, the old and new values show what was written (ASCII-looking bytes mean text from a string copy), andx/son the buffer shows the source. - Place a breakpoint on the
retof the function whose slot you watch. If the watchpoint fires first, the overwrite was before the return address was used.info breakpointsalso records hit counts. - Confirm and fix. Continue to see the jump to the bad address, then replace the unbounded copy with a bounded one, and rerun the same session to see the watchpoint stay silent.
A real transcript (AArch64, gdb 16.3)
The transcript omits the two libthread_db lines (gdb loading its thread-debugging helper library), the Breakpoint 1 at 0x400690: file overflow.c, line 6. and Breakpoint 2 at 0x4006e4: file overflow.c, line 14. lines that the two break commands print, the blank line that run prints before the first stop line, any Starting program and Continuing. progress lines, the program's own hello short line (printed by the first call to parse, between run and the first stop, because stdout is line-buffered on a terminal), and the source-line echo that gdb prints after each stop and after up (for example 6 strcpy(name, input);). In the info frame output, the ... line stands for the lines above Saved registers: (the frame address, pc and saved pc, the caller frame, the source language, and the argument and locals addresses with the previous sp). The stack addresses are from one run and differ on other runs. main's ret is at 0x4006e4 (from disassemble main).
(gdb) break parse if $_streq(input, "this input is much longer than sixteen bytes")
(gdb) break *0x4006e4
(gdb) run
Breakpoint 1, parse (input=0x400720 "this input is much longer than sixteen bytes") at overflow.c:6
(gdb) up
#1 0x00000000004006dc in main () at overflow.c:12
(gdb) info frame
...
Saved registers:
x29 at 0xfffffffff970, x30 at 0xfffffffff978
(gdb) watch -l *(unsigned long *)0xfffffffff978
Hardware watchpoint 3: -location *(unsigned long *)0xfffffffff978
(gdb) continue
Hardware watchpoint 3: -location *(unsigned long *)0xfffffffff978
Old value = 281474840470108
New value = 8295751878259777650
0x0000fffff7e8eb14 in strcpy () from /lib/aarch64-linux-gnu/libc.so.6
(gdb) bt
#0 0x0000fffff7e8eb14 in strcpy () from /lib/aarch64-linux-gnu/libc.so.6
#1 0x000000000040069c in parse (input=0x400720 "this input is much longer than sixteen bytes") at overflow.c:6
#2 0x00000000004006dc in main () at overflow.c:12
(gdb) x/2i $pc-4
0xfffff7e8eb10 <strcpy+208>: str q0, [x3], #32
=> 0xfffff7e8eb14 <strcpy+212>: ldr q0, [x2, #16]
(gdb) continue
Breakpoint 2, 0x00000000004006e4 in main () at overflow.c:14
(gdb) p/x $x30
$1 = 0x73206e6168742072
(gdb) stepi
0x00206e6168742072 in ?? ()
Reading it: the slot at 0xfffffffff978 is main's saved x30. The old value, 281474840470108, is 0xfffff7e1225c in hex: a valid libc address (the point in main's caller where main should return), which is what a healthy return address looks like. The write came from a 16-byte vector store (str q0, [x3], #32) inside strcpy, called from parse at line 6. The new value, 8295751878259777650, is 0x73206e6168742072: the bytes 72 20 74 68 61 6e 20 73, which are the ASCII characters "r than s" from the input string. main was still on the backtrace and its own ret had not yet executed: the breakpoint on ret fires after the watchpoint, and by then the ldp x29, x30, [sp], #16 just before that ret has loaded the corrupted word into x30, which is why p/x $x30 prints 0x73206e6168742072. So the overwrite came before the return address was used, and ret jumps to garbage (the next stepi lands at 0x00206e6168742072: in this session the program counter holds the target without the 0x73 top byte that x30 still shows, and the fault address the kernel reports in siginfo has the same form, so this is not just gdb's formatting; running freely instead of stepping ends in SIGBUS, a bus-error signal, and the garbage target here is not a multiple of 4 while AArch64 instruction addresses must be). On x86-64 the overflow reaches the return address of parse itself, so no up is needed: info frame at the breakpoint in parse reads rip at 0x..., watch -l on that slot stops inside strcpy with an old value that is a valid code address in main and a new value made of the same ASCII bytes, and the ret to break on is parse's own. That x86-64 session was run in qemu-x86_64 user mode with gdb-multiarch; QEMU's debug stub could not insert a hardware watchpoint: gdb printed Hardware watchpoint 2 when the watch was set, then continue failed with Could not insert hardware watchpoint 2. After set can-use-hw-watchpoints 0, gdb set a software watchpoint (printed as Watchpoint N, without the word Hardware) and the stop inside strcpy described above followed. The transcript above is the native AArch64 session.
What goes wrong, and limits of the method
- The processor has only a few debug registers, each covering a small aligned region, so watch only the slot or a few bytes, not the whole buffer. If hardware watchpoints are unavailable, gdb falls back to single-stepping (
set can-use-hw-watchpoints 0forces this) and the program runs far slower. - A watchpoint written as
watch name(a local) is dropped when its frame exits; use-lwith an address. - Without a debugger available in production: compile with
-fstack-protector-strong, whose canary (a guard value placed between locals and the return address and checked at function exit) aborts with "stack smashing detected", or build with AddressSanitizer, which reports the overflow at the writing instruction. Both tell you the function and line, but only the watchpoint gives the exact instruction and the order relative toret. - Intermittent crashes: enable core dumps (
ulimit -c unlimited) so a crash leaves a file, then use the watchpoint on a deterministic replay if you can reconstruct the triggering input.
When you open a disassembly listing from objdump or GDB for a small x86-64 function, what are the main clues you use to map instructions back to the original C source, identify branches or loops, and infer the function's purpose?
Sample Answer
Work from a concrete listing
Source, compiled with gcc -O1 -g -no-pie -fcf-protection=none -fno-asynchronous-unwind-tables (-g adds debug line information, -no-pie gives fixed addresses so the listing is stable, -fcf-protection=none makes sure there are no endbr64 marker instructions at function entries, which some distributions' GCC builds emit by default and the GCC 14.4 build used here does not, and the last flag omits the unwind tables that GCC emits by default on x86-64 Linux, which do not appear in this listing either way) (GCC 14.4, x86-64, run in a linux/amd64 container under emulation) and disassembled with objdump -d -M intel -S --no-show-raw-insn (the -S option interleaves source lines, which only works because -g put line information in the file). The listing below is an excerpt of that output: the file format header, the .init, .plt and .fini sections, the Disassembly of section .text: heading and the start-up functions that come before count_char (_start, frame_dummy and others) are omitted. count_char and main are exactly as objdump printed them, with no instruction or source line removed or edited:
#include <stdio.h>
int count_char(const char *s, char c)
{
int n = 0;
for (; *s; s++)
if (*s == c)
n++;
return n;
}
int main(int argc, char **argv)
{
if (argc < 2)
return 1;
printf("%d\n", count_char(argv[1], 'a'));
return 0;
}
0000000000401140 <count_char>:
#include <stdio.h>
int count_char(const char *s, char c)
{
int n = 0;
for (; *s; s++)
401140: movzx eax,BYTE PTR [rdi]
401143: test al,al
401145: je 401179 <count_char+0x39>
int n = 0;
401147: mov edx,0x0
40114c: data16 cs nop WORD PTR [rax+rax*1+0x0]
401157: nop WORD PTR [rax+rax*1+0x0]
if (*s == c)
n++;
401160: cmp sil,al
401163: sete al
401166: movzx eax,al
401169: add edx,eax
for (; *s; s++)
40116b: add rdi,0x1
40116f: movzx eax,BYTE PTR [rdi]
401172: test al,al
401174: jne 401160 <count_char+0x20>
return n;
}
401176: mov eax,edx
401178: ret
int n = 0;
401179: mov edx,0x0
return n;
40117e: jmp 401176 <count_char+0x36>
0000000000401180 <main>:
int main(int argc, char **argv)
{
if (argc < 2)
return 1;
401180: mov eax,0x1
if (argc < 2)
401185: cmp edi,0x1
401188: jle 4011b7 <main+0x37>
{
40118a: sub rsp,0x8
printf("%d\n", count_char(argv[1], 'a'));
40118e: mov rdi,QWORD PTR [rsi+0x8]
401192: mov esi,0x61
401197: call 401140 <count_char>
40119c: mov esi,eax
40119e: mov edi,0x402004
4011a3: mov eax,0x0
4011a8: call 401030 <printf@plt>
return 0;
4011ad: mov eax,0x0
}
4011b2: add rsp,0x8
4011b6: ret
4011b7: ret
The unindented lines are the source lines that -S interleaves: each group of source text applies to the instructions that follow it, up to the next source line. Two things show in this output that a plain listing hides. The compiler has put n++ and if (*s == c) together at 401160, and it has placed for (; *s; s++) both before the loop (the first test, at 401140) and after the body (the step and test, at 40116b), which is how a for loop is laid out when the test is at the bottom. The clues, in the order they are usually useful:
1. Function boundaries and names
A symbol such as <count_char>: marks the start (it comes from the symbol table, the list of function and variable names the linker keeps in the file), and the name is already a hint. In a stripped binary (symbol table removed with strip) those names are gone: nm on the stripped copy reports no symbols, and you recover boundaries from call targets and from ret instructions instead. Calls into shared libraries still carry names (printf@plt in main), and those are the best purpose clues left. @plt refers to the procedure linkage table: a small stub in the executable that jumps to the real printf in the C library (a shared library), whose address is filled in by the dynamic loader; seeing call <name>@plt means "this function calls a library function with that name".
2. Source mapping
With debug info, objdump -S or -l (file and line numbers) gives the interleave directly. Without it, map by structure: loops, calls, constants and the order of side effects. Expect optimized code to interleave source lines out of order and to repeat one line in two places (here int n = 0; appears twice, at 401147 and at 401179, because the compiler duplicated the initialization onto both sides of the first test: once on the path that enters the loop and once on the path that skips the loop for an empty string).
3. Arguments, return value, and registers
Under System V AMD64 the first integer or pointer arguments are in rdi, rsi, rdx, rcx, r8, r9 and the result is in rax. In count_char the first instruction dereferences rdi (a pointer) and later code compares sil (the low byte of rsi) against that byte: so a char * and a char. The last thing written before ret is mov eax, edx, so edx is the return value, an int.
4. Loops and branches
A conditional jump whose target address is lower than the jump itself is a backward branch, and that is a loop. Here jne 401160 at address 401174 jumps back up, so 401160 to 401174 is the loop body. A forward conditional jump (je 401179 at the top) is a guard or early exit, and the compare or test just before it (here test al,al at 401143) is what sets the flags it reads. The instruction before the branch tells you the condition: test al, al before je/jne means "is this value zero", which on a byte loaded from a pointer is the C idiom for "end of string".
5. Instruction idioms
movzx eax, BYTE PTR [rdi](move with zero-extend) is a one-byte load widened to 32 bits: acharread.add rdi, 0x1is a pointer step of one byte:s++on achar *.cmp sil, althensete al,movzx eax, al,add edx, eaxisn += (*s == c)computed without a branch:cmpsets the flags,sete(set if equal) writes 1 intoalwhen they were equal and 0 otherwise,movzxwidens it, and the 0 or 1 is added.mov edx, 0x0isn = 0(compilers also usexor edx, edx).
6. Constants, strings and calls
In main, mov esi,0x61 loads the constant 97, which is 'a' in ASCII, and mov edi,0x402004 loads an address in .rodata (the section that holds read-only data such as string literals). objdump -s -j .rodata dumps it (the file format line, the Contents of section .rodata: heading and the trailing ASCII column ....%d.. are omitted here) as 402000 01000200 25640a00: the line starts at address 402000, so the first four bytes (01 00 02 00) are at 402000 to 402003 and the next four, 25 64 0a 00, start at 402004. Decoded as ASCII (the standard byte-to-character table), 25 is %, 64 is d, 0a is the newline and 00 is the terminator that ends a C string, so the bytes spell "%d\n", the format string for printf. Before each call the argument registers are set up, and after it the returned eax is moved into the next argument register (mov esi, eax feeds printf). Running the binary with the argument banana prints 3, matching the reading.
7. Noise to skip
data16 cs nop WORD PTR [...] and nop WORD PTR [...] are multi-byte no-ops the compiler inserts so the loop at 401160 starts on a 16-byte boundary (0x401160 is 16 times 0x40116, so its last hex digit is 0). They do nothing. Unreachable bytes after a ret or jmp are usually padding or another function.
8. Syntax flavour
objdump and gdb default to AT&T syntax (source first, % on registers); -M intel in objdump, or set disassembly-flavor intel in gdb, gives the Intel order used above (destination first). Mixing the two up reverses every operand.
Summary of the inference here
String loop that reads bytes until zero, compares each against a second char argument, counts matches, returns the count: a character-counting function.
Unlock Full Question Bank
Get access to all 18 Assembly and Low-Level Language Fundamentals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.