Lesson 26 of 26 · 12 min read
Systems debugging (gdb, valgrind) and mixed OS traces
Inspect crashes and leaks cleanly using gcc, gdb, valgrind, and strace, then run through all four cold operating-system traces from memory.

Course syllabus · lesson 26 of 26
In this lesson
A debugger can show where a thread stopped, a system-call trace can show what it asked the kernel to do, and a paper trace can explain how the system reached that state. Use all three on the same failure to connect a symptom to the transition that caused it.
The crux of the problem is how to combine practical systems inspection tools (gcc, gdb, valgrind, strace) with disciplined active-recall tracing across every layer of an operating system.
Diagnose a stalled write across OS layers
Step 1 of 4
Check the process state
A system call trace shows a worker still in fsync(). If the scheduler shows the worker blocked on I/O, increasing its CPU share will not complete the device request.
Part 1: Practical systems tooling (gcc, gdb, valgrind, strace)
Before writing multi-threaded servers or kernel extensions (see the lab, systems, and xv6 project appendices in OSTEP), keep a tight, reproducible terminal inspection workflow ready:
- Compile with symbols and strict warnings (
gcc): Always pass-Wall -Wextra -g(plus-pthreadwhen linkingpthreads) during development. Warnings catch missing prototypes or format bugs at compile time;-gembeds source line tables so debuggers resolve variable names instead of raw hex offsets. - Trace system calls (
straceon Linux /dtruss): Runstrace -f ./myprogto watch every kernel boundary crossing live —execve,brk,mmap,openat,read,write,futex, andwait4(TIP: USE STRACE). Checking real syscalls proves immediately whetherprintf()buffered in user space or wrote to FD1! - Interactive inspection (
gdb): Attach to binaries or core dumps to catch segfaults and thread states:gcc -Wall -g -pthread race_demo.c -o race_demo gdb ./race_demo # Inside gdb: # break worker -> pause at function entry # run -> start process under ptrace # backtrace (bt) -> print call stack on crash # info threads -> list all live OS threads # thread apply all bt -> dump stacks of deadlocked threads # watch counter -> hardware watchpoint stops when the value changes - Memory & concurrency checkers (
valgrind):valgrind --leak-check=full --track-origins=yes ./progcatches out-of-bounds reads/writes, uses of uninitialized values that affect observable behavior, double frees, and unreachable memory leaks (Memcheck).valgrind --tool=helgrind ./race_demoflags lock-order inversions (potential deadlocks!) and unprotected shared writes across threads (Helgrind).
Follow one buffer from allocation to syscall
Use this small Linux exercise to connect debugger frames, heap ownership, and a kernel return value. The program writes a three-byte message but exits without releasing its staging buffer.
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static ssize_t emit(void)
{
char *buffer = malloc(3);
if (buffer == NULL)
return -1;
memcpy(buffer, "ok\n", 3);
return write(STDOUT_FILENO, buffer, 3);
}
int main(void)
{
return emit() == 3 ? EXIT_SUCCESS : EXIT_FAILURE;
}
Save it as emit.c and build a debug binary with optimizations disabled for this session.
gcc -g -O0 -Wall -Wextra emit.c -o emit
gdb -ex 'break emit' -ex run ./emit
strace -f -e trace=write,exit_group -o emit.trace ./emit
valgrind --leak-check=full --track-origins=yes ./emit
Inside GDB, use bt at the breakpoint to find the caller. Step over the allocation and copy with next, then inspect the initialized bytes with x/3cb buffer. Use finish to execute the write and return from emit. The displayed return value should be 3 when the write succeeds. After returning, the local pointer has gone out of scope. GDB confirms when ownership was lost but does not need to follow every allocation. Memcheck reports three bytes definitely lost and gives the allocation stack. The kernel trace in emit.trace still shows a successful write(1, "ok\n", 3) = 3 in this run. A correct write can coexist with a leak.
Repair the lifetime by storing the return value from write, freeing the buffer, and then returning the saved result. Rerun both traces. The write and its successful result should remain the same while the leak disappears. The sample treats a short write as failure. A production writer that promises to send every byte would need to advance the pointer by the returned count and retry the unsent suffix, handling interruption and other errors explicitly.
A different run may show write(1, "ok\n", 3) = -1 EBADF if standard output is closed. On Linux, try strace -o emit.trace -e trace=write,exit_group ./emit 1>&- with the repaired binary. Here the allocation and copy still succeed. The kernel rejects the descriptor, and the program deliberately exits with failure. Inspect the return value before reading errno. The error number only explains the call when it reported failure. Closing a descriptor is also a way to test this branch without editing the program. One run therefore exercises two independent claims about the repair. Heap ownership is correct on the error path, and the process reports the failed write.
Pick a trace for a blocked thread
If a threaded program hangs, capture thread apply all bt and identify what each thread is waiting for. Suppose worker A holds the queue mutex and is waiting for the log mutex while worker B holds the log mutex and waits for the queue mutex. Write both ownership edges alongside the call stacks. Together they form a cycle. The syscall trace may show two threads in futex waits without naming either user-space mutex. An uncontended mutex acquisition may complete entirely in user space and leave no syscall line.
Helgrind can report conflicting shared accesses along with the two access stacks. It can also report an inconsistent lock order in a run that happens to finish. Instrumentation and breakpoints perturb scheduling, so record the input, thread count, and observed order when trying to reproduce a race. For a condition-variable wait, inspect the predicate and queue state while reasoning about ownership of the associated mutex. The thread may be correctly asleep because nobody has produced work.
Part 2: The four cold traces (No notes!)
Trace each prompt on paper before reading its answer. For each transition, write the state before the event, which component changes it, and the first observable result.
Cold Trace 1 — CPU scheduling (A = 6 ticks, B = 2 ticks, C = 2 ticks arriving at t = 0)
-
Compare FIFO (
A, B, C) against Round Robin (q = 1, orderA, B, C). -
Check your numbers:
- FIFO:
A (0..6), B (6..8), C (8..10). Turnarounds =6, 8, 10(mean8.00). Responses =0, 6, 8(mean4.67). - Round Robin (
q = 1):A(0), B(1), C(2), A(3), B(4 done at 5!), C(5 done at 6!), A(6..10). Turnarounds:A=10, B=5, C=6-> mean7.00. Responses:A=0, B=1, C=2-> mean1.00!
- FIFO:
-
Change one input: What if
Carrives att = 2instead oft = 0? Under STCF, B (2) still finishes0..2, C (2) runs2..4before A runs from 4 to 10. Turnarounds areA=10, B=2, C=2for a mean of14/3 = 4.67ticks. To isolate the scheduling policy from the changed arrival, run FIFO with the same arrivals. Its turnarounds are 6, 8, and 8, averaging 7.33 ticks. -
Connect to an I/O wait. Repeat round robin with all three tasks arriving at zero, but make A block after its first tick until time 4. B and C run at 1, 2, and 3 in the order B, C, B. At time 4, C is already waiting and A rejoins the tail. C finishes at 5, then A runs its five remaining ticks and finishes at 10. B finishes at 4. A's response remains zero because it started immediately, even though it spends three ticks blocked.
Cold Trace 2 — Address translation (4 KiB pages, VA = 0x35AB)
-
Split
0x35ABintoVPNandOffset. GivenVPN 3 -> PFN 7(Valid=1, Present=1), compute the physical address and trace what changes ifPresent = 0. -
Check your numbers:
4 KiB = 12-bit offset-> low 3 hex digitsOffset = 0x5AB(stays unchanged!), upper nibbleVPN = 3. Physical address =(7 << 12) + 0x5AB = 0x75AB. -
Change one input: If
PTE[3]hasValid = 1andPresent = 0, hardware traps a page fault into the kernel: the OS picks a replacement frame (via Clock sweep, writing back ifDirty=1), blocks the process while fetching from swap, setsPresent=1, PFN=frame, and retries the instruction. If the OS selects frame0xB, the retried physical address is0xB5AB. The offset is the same. While the page is being fetched, the faulting thread is blocked and the scheduler can run another ready thread. -
Connect to copy-on-write. Instead set the original mapping present and read-only for both parent and child after
fork(). A child store triggers a protection fault. If the mapping is marked copy-on-write, the kernel allocates a new frame, copies frame 7, updates the child's PTE, and invalidates its stale translation. The child retries the store to the new frame. The parent continues to read frame 7. A read-only mapping without copy-on-write permission has a different outcome: the kernel reports an illegal access.
Cold Trace 3 — Thread race + Mesa condition check
-
Two threads share
counter = 0(counter++) and later wait on a bounded queue of capacity1with two consumersC1, C2. -
Check your trace: Without a mutex protecting
load -> add -> store,C1andC2or two incrementers interleaveload 0before either stores, leavingcounter = 1in a simplified load/add/store trace. In C, a data race on an ordinary shared integer has undefined behavior, so this interleaving illustrates the lost update without limiting the possible outcomes. On the bounded queue,C1wakes frompthread_cond_signalonly to findC2already stole the sole item (count = 0) — proving whypthread_cond_waitmust live insidewhile (count == 0)under Mesa semantics, so the consumer tests the predicate again after reacquiring the mutex. -
Write the queue transitions. C1 waits with the mutex released. A producer locks the mutex, changes count from 0 to 1, signals C1, and unlocks. C2 obtains the mutex first, dequeues, and changes count back to 0. When C1 runs and obtains the mutex, it sees 0 and waits again. The signal made it eligible to run but reserved no item. To connect this to deadlock, add a separate log mutex and give both code paths the order queue then log whenever both locks are needed. This removes the cycle where each path holds one lock while waiting for the other.
Cold Trace 4 — Crash consistency (Redo Journal)
-
Draw an ordered metadata journal write:
Db -> TxB + I[v2] + B[v2] -> TxE -> Checkpoint. -
Check your trace:
- Power cut before
TxE: Recovery finds no commit blockTxE, skips the incomplete transaction, and mounts the cleanv1filesystem. BecauseDbwrote directly to an unreferenced block,v1files remain intact with zero dangling pointers. - Power cut after
TxE, before checkpoint: Recovery detectsTxE, replaysI[v2]andB[v2]idempotently to home blocks, and preserves the appended data becauseDbreached durable storage before the commit. Its write may overlap writing the journal body.
- Power cut before
-
Connect recovery to RPC. A server accepts upload request 91, durably commits the append and its deduplication record in one transaction, then loses power before sending the reply. On restart, redo completes any missing home writes. The retry of request 91 uses the recorded result and appends nothing. If the same crash occurred before a durable commit, recovery skips the transaction, and the retry can perform the append for the first time. The client sees a timeout in both cases and can recover the result by retrying with the same identity.
Where to go next
For another pass, change the order of a wakeup, the fault type, or the last durable write and predict which result changes.
Return to the full Operating Systems syllabus anytime to re-test cold traces whenever you switch one input, or explore all standalone systems writing.
Before you move on
Try it in your workspace
Debug a multi-threaded C trace fixture with `gdb` breakpoints/watchpoints and `valgrind --tool=memcheck`, then complete all four cold traces (scheduling, address translation, thread race, redo journal) without notes.
Keep a short note of what you tried, what passed, and what you still need to check.
0 of 3 checked.
Saved in this browser when storage is available. Uncheck any item to revisit it. This is your own record, not an assessment.