“My program segfaulted” is a symptom, not a diagnosis: exit code 139 only tells you which signal hit;
$rip,$rsp, and the faulting instruction tell you why.
The previous two lessons gave us reference tables for registers, the ABI, and ISA capabilities. Now we look at the flip side: code that assembles, links, runs, and crashes. Below are five self-contained bugs—each reproducible with a single command—and the exact GDB dump that pinpoints which invariant broke.
Mental Model: Signal, Exit Code, and Root Cause
| Intuition | What the testbed shows |
|---|---|
| A segfault always means a C99 pointer bug | SIGSEGV fires just as easily from a clobbered return slot or an unaligned movaps |
| Exit code 139 was returned by the program | The shell encodes fatal signals as 128 + signal (128 + 11); the binary never returned 139 |
| GDB names the root cause automatically | GDB prints the faulting instruction and registers; you deduce the broken invariant from the dump |
core dumped guarantees a core file on disk |
With ulimit -c 0, the kernel writes no core dump file |
#DE also raises SIGSEGV |
Integer divide-by-zero raises SIGFPE, exit code 136 |
Signals and Exit Codes
SIGSEGV does not distinguish among these causes on its own: the signal only tells you a memory or protection fault occurred.
SIGFPE comes from the #DE hardware exception, not a floating-point format error.
| Signal | Number | Shell Exit Code | Typical Cause |
|---|---|---|---|
SIGSEGV |
11 | 139 | lost return address, unaligned movaps, writing to an unmapped/read-only page |
SIGFPE |
8 | 136 | divide-by-zero, div/idiv quotient overflow |
SIGILL |
4 | 132 | illegal/disabled opcode, e.g., AVX without XCR0 enabled |
SIGBUS |
7 | 135 | accessing past EOF in an mmap-backed file or unaligned bus access |
A C99 harness distinguishes normal exits from fatal signals via WIFSIGNALED and WTERMSIG. The 128 + signal convention belongs to the shell, not the ABI: inside a parent process, waitpid returns a status word from which the signal number is extracted separately.
Quick triage by exit code:
139 (SIGSEGV) ──► $rip == 0 (ret slot) | movaps ($rsp % 16 == 8) | guard page
136 (SIGFPE) ──► div/idiv at $rip (divisor == 0 or dirty rdx)
132 (SIGILL) ──► unsupported/disabled opcode (check CPUID / XCR0)
1..125 ──► normal exit(-errno) or logic failure (check strace)Five Reproducible Bugs
Each source file lives in lessons/26-common-errors/, builds cleanly with nasm and ld, and runs without libc. In all shell snippets below, echo $? prints the shell’s exit code.
1. Lost Return Address: bug_ret.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; bug_ret.asm — function reserves a stack slot without restoring rsp; ret pops zero.
default rel
%define SYS_EXIT 60
section .text
global _start
_start:
call asm_bad_ret
; syscall: exit(0)
mov eax, SYS_EXIT
xor edi, edi
syscall
; ------------------------------------------------------------------------------
; asm_bad_ret: sub rsp, 8 without matching add; ret pops 0 instead of return address.
; Input: none
; Output: does not return
; Clobbers: rsp, rip, flags
; ------------------------------------------------------------------------------
asm_bad_ret:
sub rsp, 8
mov qword [rsp], 0
ret
section .note.GNU-stack noalloc noexec nowrite progbits$ ./build/bug_ret >/dev/null 2>&1; echo $?
139GDB stops on the signal and reveals where $rip jumped:
$ gdb -q --nx -batch -ex 'set pagination off' -ex run \
-ex 'info registers rip rsp' -ex 'x/2gx $rsp' ./build/bug_ret
Program received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ?? ()
rip 0x0 0x0
rsp 0x7fffffffd7f8 0x7fffffffd7f8
0x7fffffffd7f8: 0x0000000000401005 0x0000000000000001$rip = 0—retpopped zero off the stack and jumped to address0x0.[rsp] = 0x401005— the real return address, still sitting untouched on the stack.[rsp + 8] = 1—argcfrom the initial process stack.
The function executed sub rsp, 8, zeroed the new slot, and hit ret. The actual return address sat 8 bytes higher and was never popped. Fix: restore rsp before ret, or don’t subtract from rsp at all.
bug_ret: $rsp ──► [ 0x0000000000000000 ] ◄── ret pops this and jumps to 0x0!
+8 [ 0x0000000000401005 ] (real return address left above)
bug_align: $rsp % 16 == 0 ──► sub rsp, 8 ──► $rsp % 16 == 8 ──► movaps [rsp] (#GP)2. Unaligned movaps: bug_align.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; bug_align.asm — movaps requires a 16-byte aligned address, broken by sub rsp, 8.
default rel
%define SYS_EXIT 60
section .text
global _start
_start:
sub rsp, 8
movaps [rsp], xmm0
; syscall: exit(0)
mov eax, SYS_EXIT
xor edi, edi
syscall
section .note.GNU-stack noalloc noexec nowrite progbits$ ./build/bug_align >/dev/null 2>&1; echo $?
139$ gdb -q --nx -batch -ex 'set debuginfod enabled off' \
-ex 'set pagination off' -ex 'set disassembly-flavor intel' -ex run \
-ex 'info registers rip rsp' -ex 'x/i $rip' ./build/bug_align
Program received signal SIGSEGV, Segmentation fault.
_start () at bug_align.asm:14
14 movaps [rsp], xmm0
rip 0x401004 0x401004 <_start+4>
rsp 0x7fffffffd848 0x7fffffffd848
=> 0x401004 <_start+4>: movaps XMMWORD PTR [rsp],xmm0Upon entering _start, the stack pointer is 16-byte aligned. sub rsp, 8 shifts it to an 8-mod-16 address (...8), while movaps requires 16-byte alignment. The CPU raises #GP, the kernel delivers SIGSEGV, and GDB points straight at the unaligned memory operand.
3. Fourth Syscall Argument in rcx: bug_rcx.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; bug_rcx.asm — fourth syscall argument goes in r10, not rcx.
default rel
%define SYS_MMAP 9
%define SYS_EXIT 60
%define PAGE_SIZE 4096
%define PROT_RW 3
%define MAP_FLAGS 0x22
section .text
global _start
_start:
xor r10d, r10d
; syscall: mmap(NULL, PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0)
mov eax, SYS_MMAP
xor edi, edi
mov esi, PAGE_SIZE
mov edx, PROT_RW
mov rcx, MAP_FLAGS
mov r8, -1
xor r9d, r9d
syscall
cmp rax, -4095
jae .err
; syscall: exit(0)
mov eax, SYS_EXIT
xor edi, edi
syscall
.err:
neg rax
mov edi, eax
; syscall: exit(errno)
mov eax, SYS_EXIT
syscall
section .note.GNU-stack noalloc noexec nowrite progbits$ ./build/bug_rcx >/dev/null 2>&1; echo $?
9strace reveals what arguments the kernel actually received:
$ strace -e trace=mmap ./build/bug_rcx
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_FILE, -1, 0) = -1 EBADF (Bad file descriptor)
+++ exited with 9 +++Breaking at syscall in GDB shows both registers side by side:
$ gdb -q --nx -batch -ex 'set pagination off' -ex 'break *0x401023' \
-ex run -ex 'print/x $rcx' -ex 'print/x $r10' \
-ex nexti -ex 'print/d $rax' ./build/bug_rcx
Breakpoint 1, _start () at bug_rcx.asm:27
27 syscall
$1 = 0x22
$2 = 0x0
29 cmp rax, -4095
$3 = -9$rcx = 0x22— theMAP_PRIVATE|MAP_ANONYMOUSflags were placed in the wrong register.$r10 = 0— the kernel reads the fourth syscall argument fromr10, seeingMAP_FILE(0) instead.$rax = -9—-EBADF: withoutMAP_ANONYMOUS, the kernel tries to map file descriptor-1.- Address
0x401023is thesyscallinstruction located viaobjdump. - Fix: use
mov r10, MAP_FLAGSinstead ofmov rcx, MAP_FLAGS. - Whatever was in
rcxwould be clobbered anyway:syscalloverwritesrcxandr11with the return RIP and RFLAGS.
4. Division by Zero: bug_div.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; bug_div.asm — division by zero triggers #DE and SIGFPE rather than a silent zero.
default rel
%define SYS_EXIT 60
section .text
global _start
_start:
xor edx, edx
xor ecx, ecx
mov rax, 7
div rcx
; syscall: exit(0)
mov eax, SYS_EXIT
xor edi, edi
syscall
section .note.GNU-stack noalloc noexec nowrite progbits$ ./build/bug_div >/dev/null 2>&1; echo $?
136$ gdb -q --nx -batch -ex 'set debuginfod enabled off' \
-ex 'set pagination off' -ex 'set disassembly-flavor intel' -ex run \
-ex 'info registers rip rax rcx rdx' -ex 'x/i $rip' ./build/bug_div
Program received signal SIGFPE, Arithmetic exception.
_start () at bug_div.asm:17
17 div rcx
rip 0x401009 0x401009 <_start+9>
rax 0x7 7
rcx 0x0 0
rdx 0x0 0
=> 0x401009 <_start+9>: div rcxrdx:rax = 0:7, divisor rcx = 0, and div raises #DE. The kernel maps #DE to SIGFPE, and the shell reports 128 + 8 = 136. The second way to trigger #DE is quotient overflow when the quotient doesn’t fit in 64 bits: for unsigned div, whenever rdx >= rcx, and for signed idiv, also on the edge case INT64_MIN / -1 (see lesson 15). Guarding the divisor and overflow bounds before dividing eliminates both faults.
5. Implicit Operand Size in NASM 3: bug_size.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; bug_size.asm — NASM 3 encodes mov [value], 1 as a single-byte write.
default rel
%define SYS_EXIT 60
section .data
align 8
value: dq 0x1122334455667788
section .text
global _start
_start:
mov [value], 1 ; lint:allow-ambiguous-size — intentional lesson bug
mov rax, [value]
shr rax, 8
and eax, 0xFF
mov edi, eax
; syscall: exit((value >> 8) & 0xFF)
mov eax, SYS_EXIT
syscall
section .note.GNU-stack noalloc noexec nowrite progbitsThe lint:allow-ambiguous-size comment is a course linter annotation acknowledging that this line breaks the explicit-size rule intentionally.
$ ./build/bug_size >/dev/null 2>&1; echo $?
119GDB breaks before the store and inspects memory right after a single step:
$ gdb -q --nx -batch -ex 'set pagination off' -ex 'break _start' \
-ex run -ex stepi -ex 'x/8bx &value' -ex 'x/gx &value' ./build/bug_size
Breakpoint 1, _start () at bug_size.asm:17
17 mov [value], 1 ; lint:allow-ambiguous-size — intentional lesson bug
19 mov rax, [value]
0x402000 <value>: 0x01 0x77 0x66 0x55 0x44 0x33 0x22 0x11
0x402000 <value>: 0x1122334455667701objdump explains why only the lowest byte changed:
$ objdump -d -M intel -j .text build/bug_size | sed -n '/<_start>:/,+1p'
0000000000401000 <_start>:
401000: c6 05 f9 0f 00 00 01 mov BYTE PTR [rip+0xff9],0x1 # 402000 <value>- Opcode
c6ismov r/m8, imm8—an 8-bit store. - NASM 3 picks the narrowest encoding when operand size is omitted; NASM 2.15 rejected the same line with
operation size not specified. valuestarted as0x1122334455667788, became0x1122334455667701, and(value >> 8) & 0xFFequals0x77, or119.- Fix: write
mov qword [value], 1.
Terminal Verification
$ make test
26-common-errors: signals and exit codes OK
$ cat build/triage.out
build/bug_ret: signal 11
build/bug_align: signal 11
build/bug_rcx: exit 9
build/bug_div: signal 8
build/bug_size: exit 119
triage: okbug_triage.c spawns each binary via fork and exec, waits with waitpid, and separates WIFSIGNALED from WIFEXITED. Before executing the child, it sets RLIMIT_CORE to zero so crashes don’t scatter core.* files into the working directory.
On NASM 2.x, mov [value], 1 fails to assemble: make test checks for the expected operation size not specified diagnostic, and build/triage.out records build/bug_size: skipped in place of build/bug_size: exit 119.
Common Failure Modes
-
Believing exit code 139 was returned by the program itself.
Symptom:echo $?prints139afterSIGSEGV, even though the program never calledexit(139).
Cause: The shell encodes fatal signals as128 + signal, whereaswaitpidreturns a separate status word.
Fix: CheckWIFSIGNALEDvs.WIFEXITEDin C, and extract the signal number viaWTERMSIG. -
Assuming GDB prints the root cause on its own.
Symptom: GDB prints$rip,$rsp, and the faulting instruction, without saying thatretpopped the wrong slot orrspwas misaligned by 8.
Cause: The debugger shows machine state, not programmer intent.
Fix: Inspect the instruction at$rip, check its operands, and verify$rspalignment against the ABI. -
Expecting
core dumpedto guarantee a core file on disk.
Symptom: Withulimit -c 0, no core dump is created even though the shell prints a crash message.
Cause: Core dump size is capped by the process’s resource limit.
Fix: Checkulimit -c, or run directly under GDB rather than relying on post-mortem core files. -
Confusing
#DEwithSIGSEGV.
Symptom:bug_divraisesSIGFPE(exit code 136), notSIGSEGV(139).
Cause: Divide-by-zero raises#DE, which the kernel translates toSIGFPE.
Fix: Match exit codes against the signal table so you inspect the divisor rather than hunting for a memory error. -
Thinking
mov [mem], 1writes a 64-bit value likemov rax, [mem].
Symptom:objdumpshowsBYTE PTR, leaving the upper seven bytes ofvalueuntouched.
Cause: NASM 3 defaults to the narrowest immediate-to-memory encoding when no size specifier is given.
Fix: Always writemov qword [value], 1and verify store width inobjdump.
Lab
Goal. Write a script triage.sh that takes any of the five binaries and prints its signal or exit code, $rip, $rsp, and the instruction at $rip.
Contract.
- Input: path to a binary, e.g.,
./triage.sh build/bug_div. - Output: one line with the signal or exit code, followed by
rip,rsp, andx/i $ripfrom GDB. - For
bug_ret, the output must showrip = 0. - For
bug_align, it must showrsp % 16 = 8. - For
bug_div, it must showrcx = 0. - For
bug_rcx, it must showrax = -9. - The script must never leave
core.*files behind and must work regardless of the current working directory.
Acceptance criteria.
./triage.sh build/bug_retprintsSIGSEGVandrip = 0../triage.sh build/bug_divprintsSIGFPEandrcx = 0../triage.sh build/bug_rcxprints exit code9andrax = -9.git statusshows no untrackedcore.*files.
Hints, expected output, and walkthrough
Run GDB in batch mode like this:
$ gdb -q --nx -batch -ex 'set pagination off' -ex run \
-ex 'info registers rip rsp' -ex 'x/i $rip' ./build/bug_retbug_rcx receives no signal: it exits cleanly with status 9, so run reaches exited with code 09.
To observe rax = -9, you need a breakpoint right after syscall or at _start.err.
A triage.sh script that doesn’t hardcode file labels can pause via catch syscall mmap: GDB stops twice—on entry to mmap (rax = 9) and on exit (rax = -9)—without stopping again on the subsequent exit syscall.
That way, the script captures both the mmap failure and its -EBADF return value without relying on hardcoded binary addresses.
If your script prints rip = 0x401000 for bug_ret, GDB stopped at the entry point rather than running to the signal.
Testbed sources, Makefile, and automated tests for this lesson: lessons/26-common-errors.
Summary
- Shell exit code 139 is
128 + SIGSEGV, not a value returned by the program. - A lost return address shows up as
$rip = 0while the real return address remains sitting at[rsp]. movapsrequires a 16-byte aligned address, so a precedingsub rsp, 8breaks alignment.- The fourth syscall argument goes in
r10, whilercxandr11are clobbered bysyscall. - Integer divide-by-zero raises
#DE, delivered asSIGFPE(exit code 136). - NASM 3 picks the narrowest store size when an operand size is omitted, so always specify memory sizes explicitly.
perf.