On this page

A breakpoint answers “where to stop,” a watchpoint answers “when memory changes,” and .eh_frame answers “where to return once the frame is already torn down.”

The five micro-bugs gave us symptoms, exit codes, and dumps for manual inspection. Here that same investigation becomes systematic: VS Code launch configuration, hardware traps on memory writes, call-frame unwind tables, and CPU performance counters instead of wall-clock seconds.

Mental Model: Address, Write, Frame

Intuition What the testbed shows
A debugger can only break on an instruction address A watchpoint triggers on a memory write, even when the address is computed indirectly
bt can always reconstruct the stack Without .cfi_*, the unwinder reads the wrong slot and terminates the chain at ??
perf stat measures time Hardware counters report cycles, instructions, and branches, whereas wall-clock seconds vary with core frequency
VS Code config is just repository boilerplate miDebuggerArgs: -nx prevents ~/.gdbinit from breaking reproducibility

Launching from VS Code: Configuration as Part of the Testbed

The C/C++ extension does not ship its own debugger: it spawns gdb in MI mode and passes it the binary path. As a result, what the “Debug” button does is governed by two JSON files under .vscode/.

.vscode/tasks.json
{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "build-lesson",
      "type": "shell",
      "command": "make",
      "args": ["build"],
      "options": {
        "cwd": "${workspaceFolder}"
      },
      "group": {
        "kind": "build",
        "isDefault": true
      },
      "problemMatcher": []
    }
  ]
}
.vscode/launch.json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug watch.asm",
      "type": "cppdbg",
      "request": "launch",
      "program": "${workspaceFolder}/build/watch",
      "args": [],
      "stopAtEntry": false,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": false,
      "MIMode": "gdb",
      "miDebuggerPath": "/usr/bin/gdb",
      "miDebuggerArgs": "-nx",
      "preLaunchTask": "build-lesson",
      "setupCommands": [
        {
          "description": "Intel syntax in the disassembly view",
          "text": "set disassembly-flavor intel",
          "ignoreFailures": true
        }
      ]
    },
    {
      "name": "Debug cfi_demo without CFI",
      "type": "cppdbg",
      "request": "launch",
      "program": "${workspaceFolder}/build/cfi_demo",
      "args": ["without"],
      "stopAtEntry": false,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": false,
      "MIMode": "gdb",
      "miDebuggerPath": "/usr/bin/gdb",
      "miDebuggerArgs": "-nx",
      "preLaunchTask": "build-lesson",
      "setupCommands": [
        {
          "description": "Intel syntax in the disassembly view",
          "text": "set disassembly-flavor intel",
          "ignoreFailures": true
        }
      ]
    }
  ]
}

Fields that control reproducibility:

  • program — path to the already-built ELF binary; the extension does not build the project on its own.
  • preLaunchTask — label of the task from tasks.json to run before launching.
  • stopAtEntry — when false, the process runs to the first breakpoint instead of stopping at _start.
  • miDebuggerArgs — flags passed to GDB; -nx skips ~/.gdbinit so a user’s personal init file cannot alter behavior.
  • setupCommands — commands sent to GDB right after startup; here we enable Intel disassembly syntax.

/usr/bin/gdb is not a guess—it is the output of command -v gdb on the testbed. On another machine, substitute your own path.

Watchpoint: Stopping on a Write

break sets a breakpoint on an instruction address. watch sets a watchpoint. There are four debug registers (DR0–DR3), so at most four hardware watchpoints can be active simultaneously.

watch.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0

; watch.asm — loop incrementing a global counter: target for watchpoint and perf stat.

default rel

%define SYS_EXIT 60
%define ITERATIONS 200000000

section .data
    align 8
    counter: dq 0

section .text
    global _start

_start:
    mov rcx, ITERATIONS

.loop:
    inc qword [counter]
    dec rcx
    jnz .loop

    ; syscall: exit(0)
    mov eax, SYS_EXIT
    xor edi, edi
    syscall

section .note.GNU-stack noalloc noexec nowrite progbits

Because counter is declared in NASM without a DWARF type, GDB does not know its width. You must specify the address and type explicitly:

$ gdb -q --nx -batch ./build/watch \
    -ex starti \
    -ex 'watch *(long long *)&counter' \
    -ex continue \
    -ex 'x/gd &counter'
Program stopped.
_start () at watch.asm:18
18	    mov rcx, ITERATIONS
Hardware watchpoint 1: *(long long *)&counter

Old value = 0
New value = 1
_start.loop () at watch.asm:22
22	    dec rcx
0x402000 <counter>:	1

Reading the dump line by line:

  • Hardware watchpoint 1 — GDB claimed a hardware debug slot; software emulation would print just Watchpoint 1.
  • Old value = 0 and New value = 1 — the inc qword [counter] write fired on the first iteration.
  • _start.loop () at watch.asm:22 — execution stopped on the next instruction, dec rcx, immediately after the write completed.
  • 0x402000 <counter>: 1 — the address in .data of this non-PIE binary and the updated value read back with x/gd.
  • starti in the launch arguments stops the program on its very first instruction (before the loop begins) so the hardware watchpoint can be armed immediately.

You can observe the difference between hardware and software watchpoints directly: with set can-use-hw-watchpoints 0, GDB prints Watchpoint 1: *(long long *)&counter and single-steps to check memory after every instruction instead of matching in a debug register.

perf stat: Counters Instead of Wall-Clock Seconds

Hardware performance counters are read by the perf profiler. On the testbed, perf_event_paranoid = 2, so only :u events are permitted—these count instructions executed in user mode.

$ perf stat -r 5 -e cycles:u,instructions:u,branches:u ./build/watch
 Performance counter stats for './build/watch' (5 runs):

     1,170,323,659      cycles:u                    ( +-  4.02% )
       600,000,772      instructions:u              ( +-  0.00% )
       200,000,769      branches:u                  ( +-  0.00% )

       0.352141211 +- 0.024143843 seconds time elapsed  ( +-  6.86% )

Columns and numbers:

  • cycles:u — CPU cycles spent in user space; +- 4.02% is the relative standard deviation across five runs.
  • instructions:u — exactly three instructions per iteration (inc, dec, jnz), so 200 million iterations yield roughly 600 million instructions.
  • branches:u — one branch per iteration (jnz), matching the iteration count.
  • seconds time elapsed — wall-clock time; this fluctuates with CPU frequency scaling and the OS scheduler, which is why hardware counters are used to compare algorithms.

The cycles-per-instruction ratio is about 1.95: the loop is not bottlenecked by branch prediction, but by the loop-carried dependency on inc qword [counter], where each iteration must wait for the previous memory write to complete.

DWARF CFI: How the Unwinder Finds a Frame

GDB’s backtrace and profiler stack unwinding do not require source code: they read the .eh_frame table generated from .cfi_* directives. CFI defines the unwinding rules, and every function bracketed with .cfi_startproc gets an FDE.

All offsets in an FDE are relative to the CFA, so a single FDE remains accurate throughout the prologue and even after dynamic stack realignment.

cfi_demo.S is written for the GNU Assembler (GAS) in AT&T syntax (push %rbx: source on the left, % prefix on registers). This is necessary because NASM lacks built-in CFI generation directives (.cfi_*), whereas GAS lowers them directly into .eh_frame.

cfi_demo.S
/* SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 */

/* cfi_demo.S — identical frame body twice: with .cfi_* directives and without them. */

    .text
    .globl asm_with_cfi
    .type asm_with_cfi, @function
asm_with_cfi:
    .cfi_startproc
    push %rbx
    .cfi_def_cfa_offset 16
    .cfi_offset %rbx, -16

    push %rbp
    .cfi_def_cfa_offset 24
    .cfi_offset %rbp, -24

    xor %ebp, %ebp
    mov %rsp, %rbx
    .cfi_def_cfa_register %rbx
    and $-16, %rsp

    call asm_fault

    mov %rbx, %rsp
    pop %rbp
    .cfi_def_cfa %rsp, 16
    pop %rbx
    .cfi_def_cfa %rsp, 8

    ret
    .cfi_endproc
    .size asm_with_cfi, .-asm_with_cfi

    .globl asm_without_cfi
    .type asm_without_cfi, @function
asm_without_cfi:
    push %rbx
    push %rbp

    xor %ebp, %ebp
    mov %rsp, %rbx
    and $-16, %rsp

    call asm_fault

    mov %rbx, %rsp
    pop %rbp
    pop %rbx

    ret
    .size asm_without_cfi, .-asm_without_cfi

    .section .note.GNU-stack,"",@progbits

Both functions do the exact same work: save rbx and rbp, zero rbp, stash the old rsp in rbx, 16-byte-align the stack before call, and invoke the C function asm_fault, which writes to the null page. The only difference is the .cfi_* directives: the second function has no unwind table entry.

xor %ebp, %ebp zeroes rbp in both functions, so without CFI the debugger’s frame-pointer heuristic cannot walk the chain back to main.

$ gdb -q --nx -batch -ex run -ex bt --args ./build/cfi_demo with
Program received signal SIGSEGV, Segmentation fault.
0x0000000000401146 in asm_fault () at cfi_demo.c:15
15	    *null_page = 1;
#0  0x0000000000401146 in asm_fault () at cfi_demo.c:15
#1  0x00000000004011a5 in asm_with_cfi () at cfi_demo.S:23
#2  0x0000000000401187 in main (argc=2, argv=0x7fffffffd7e8) at cfi_demo.c:21

$ gdb -q --nx -batch -ex run -ex bt --args ./build/cfi_demo without
Program received signal SIGSEGV, Segmentation fault.
0x0000000000401146 in asm_fault () at cfi_demo.c:15
15	    *null_page = 1;
#0  0x0000000000401146 in asm_fault () at cfi_demo.c:15
#1  0x00000000004011bb in asm_without_cfi () at cfi_demo.S:45
#2  0x0000000000000000 in ?? ()

In the first run, the backtrace reaches main. In the second, GDB recovers asm_without_cfi via heuristic unwinding of the prologue, but then reads the next caller from the wrong stack slot and lands on a null address: #2 0x0000000000000000 in ?? (). That is not a GDB bug—it is missing unwind metadata.

The root cause is visible in .eh_frame. asm_with_cfi has an FDE covering 0x401195..0x4011ab, whereas the neighboring function 0x4011ab..0x4011bb has no entry at all:

$ nm -n build/cfi_demo | grep ' T asm_with'
0000000000401195 T asm_with_cfi
00000000004011ab T asm_without_cfi

$ readelf -wf build/cfi_demo | sed -n '/pc=0000000000401195/,/^$/p'
000000c0 0000000000000024 000000c4 FDE cie=00000000 pc=0000000000401195..00000000004011ab
  DW_CFA_advance_loc: 1 to 0000000000401196
  DW_CFA_def_cfa_offset: 16
  DW_CFA_offset: r3 (rbx) at cfa-16
  DW_CFA_advance_loc: 1 to 0000000000401197
  DW_CFA_def_cfa_offset: 24
  DW_CFA_offset: r6 (rbp) at cfa-24
  DW_CFA_advance_loc: 5 to 000000000040119c
  DW_CFA_def_cfa_register: r3 (rbx)
  DW_CFA_advance_loc: 13 to 00000000004011a9
  DW_CFA_def_cfa: r7 (rsp) ofs 16
  DW_CFA_advance_loc: 1 to 00000000004011aa
  DW_CFA_def_cfa: r7 (rsp) ofs 8
  DW_CFA_nop
  DW_CFA_nop

Each line in the FDE encodes a rule transition as execution advances through the function:

  • DW_CFA_def_cfa_offset: 16 after push %rbx — right after call, the CIE sets CFA to rsp + 8 (the top of stack before call, 8 bytes above the return address), so the first 8-byte push shifts the offset to 16.
Higher addresses:  CFA ──────► (rsp before call)
                   CFA - 8     [ ret addr  ]  (function entry:  rsp = CFA - 8)
                   CFA - 16    [ saved rbx ]  (after push rbx:  rsp = CFA - 16)
                   CFA - 24    [ saved rbp ]  ◄── rbx = rsp after push rbp (before alignment)
                   ...         [ alignment and new frame for asm_fault ]
  • DW_CFA_offset: r3 (rbx) at cfa-16 — the saved rbx sits at CFA - 16.
  • DW_CFA_def_cfa_register: r3 (rbx) — after mov %rsp, %rbx, CFA is tracked relative to rbx because rsp is about to be aligned and will no longer be a fixed reference.
  • DW_CFA_def_cfa: r7 (rsp) ofs 16, then ofs 8 — in the epilogue, rsp becomes the base register again, and the offset shrinks after each pop.
  • DW_CFA_nop — padding byte for table alignment, not an action.

The CIE defines the baseline rule: DW_CFA_def_cfa: r7 (rsp) ofs 8 and DW_CFA_offset: r16 (rip) at cfa-8. That is where “the return address sits at CFA - 8” comes from.

Common Failures

  1. "watch counter should work just like watch on a C variable."
    Fact: GDB refuses to set the watchpoint:

    text
    'counter' has unknown type; cast it to its declared type

    Cause: A NASM symbol appears in the symbol table, but it has no DWARF type, so GDB does not know the size of the object to monitor.
    Fix: Cast the address explicitly: watch *(long long *)&counter.

  2. “If bt printed the frame, then CFI isn’t needed.”
    Fact: For asm_without_cfi, GDB prints #1 ... in asm_without_cfi, but the caller frame collapses to #2 0x0000000000000000 in ?? ().
    Cause: Without an FDE, the debugger only recovers what it can guess from the prologue heuristic; beyond that, it dereferences the wrong stack slot.
    Fix: Add .cfi_startproc, .cfi_def_cfa_offset, and .cfi_offset to assembly routines that call other code, or place those routines in a .S file where CFI directives are supported.

  3. "perf stat -e cycles counts all cycles of the process."
    Fact: On the testbed, the command outputs cycles:u instead of cycles.
    Cause: With perf_event_paranoid = 2, the kernel only permits user-space events, so perf automatically appends :u.
    Fix: Specify :u explicitly for user-space counters and do not expect kernel-mode counts without root privileges.

  4. “A breakpoint in VS Code behaves identically to the terminal.”
    Fact: When miDebuggerArgs is empty, the launch reads ~/.gdbinit, so an unexpected set pagination off or user hook alters the output.
    Cause: The extension passes GDB only the arguments listed in launch.json; user init files are not disabled by default.
    Fix: Set "miDebuggerArgs": "-nx" and keep the debug configuration in the repository rather than relying on a personal profile.

Lab

Goal. Add a third function asm_patched to cfi_demo.S: an exact copy of asm_without_cfi equipped with proper CFI directives. Stack unwinding must recover main, and the perf stat counters must remain reproducible.

Contract and constraints.

  • asm_patched is called from main when passed the argument patched and triggers the same SIGSEGV inside asm_fault.
  • The function body and instruction order remain untouched; only CFI directives are added.
  • make build and make test pass, and readelf -wf shows an FDE covering the address range of asm_patched.
  • The numbers from perf stat -r 5 -e cycles:u,instructions:u,branches:u ./build/watch remain on the same order of magnitude: roughly 600 million instructions and 200 million branches.

Verification criteria.

  1. gdb -q --nx -batch -ex run -ex bt --args ./build/cfi_demo patched prints both asm_patched and main.
  2. The address of asm_patched from nm -n build/cfi_demo falls inside the pc=... range of an FDE printed by readelf -wf build/cfi_demo.
  3. perf stat stays within the same order of magnitude as the lesson run.
Hints, Expected Output, and Walkthrough

The FDE for the third function differs from asm_with_cfi only in its addresses: the def_cfa_offset, offset, and def_cfa_register rules follow the exact same sequence. You can check coverage with a pair of commands:

$ nm -n build/cfi_demo | grep ' T asm_patched'
$ readelf -wf build/cfi_demo | grep 'pc=0000000000401'

If readelf shows an FDE but bt still breaks, .cfi_startproc is not at the start of the function or .cfi_endproc is missing. If the FDE is present yet main still does not appear, verify that .cfi_offset for rbx and rbp specifies cfa-16 and cfa-24 rather than positive offsets.

The expected bt for patched matches the shape of with: three frames, ending at main. Raw perf stat numbers will differ on another machine—what matters is the cycles-per-instruction ratio and the branch count per iteration, not the absolute cycle count.

Testbed sources, Makefile, and automated tests for this lesson: lessons/27-advanced-debugging.

Summary

  1. VS Code debugging configuration consists of two JSON files that pass the binary path and launch flags to GDB.
  2. miDebuggerArgs: -nx ignores ~/.gdbinit and keeps launches reproducible.
  3. A watchpoint stops execution on a memory write; there are only four hardware debug slots (DR0–DR3).
  4. A NASM symbol without a DWARF type requires an explicit cast when passed to watch.
  5. perf stat reports cycles, instructions, and branches; at perf_event_paranoid = 2, only :u user-space events are available.
  6. .cfi_* directives compile into .eh_frame, and without an FDE, stack unwinding terminates at ??.
Bridge to the Next Lesson
Debugging tools only work when the build environment itself is sound. In the final lesson 28, I break down environment diagnostics: Makefile tab indentation, CRLF line endings in shebangs, strip, .gitattributes, and editor settings.