# Debugging — how to find out why `mini_serv` misbehaves
Debugging is **bisecting your assumptions**: test one layer at a time, make each layer prove
itself with your own eyes. This file gives you the toolkit, the symptom table, and a triage
checklist. On this machine: `nc`, `ss`, `gdb`, `valgrind`, `lsof` are available (`strace`
isn't; everything still works without it).
---
## 1. The golden rules
1. **Compile strict, always**: `cc -Wall -Wextra -Werror -g mini_serv.c -o mini_serv`.
`-g` = debug symbols for gdb/valgrind. The exam runner compiles for you, but your own
compile is your fast feedback loop.
2. **Keep a last-known-good copy** before every edit: `cp mini_serv.c mini_serv.ok.c`.
If things get weird: `cp mini_serv.ok.c mini_serv.c`.
3. **Build in layers and test each layer** (that's exactly what your checkpoints in
`drills/typing-script.md` are). Never write 150 lines and *then* run it for the first time.
4. **One change at a time.** Two changes at once = you learn nothing from the result.
5. **Write down what you expect before you test.** If expectation ≠ observation, you have a
clue, not a mystery. The `sandbox/traceback` file from the grader is exactly this: their
expectation vs your output.
## 2. Your three terminals
- **T1**: the server. Watch its stderr.
- **T2**: `nc 127.0.0.1 PORT` — client A (the "listener", like the grader's).
- **T3**: scripted sender (repeatable, race-free):
```bash
send() { exec 3<>/dev/tcp/127.0.0.1/"$1"; cat >&3; exec 3>&-; }
printf 'hello\n' | send 8081 # connects, sends, disconnects
{ printf 'par'; sleep 1; printf 'tial\n'; } | send 8081 # split line
printf 'abc' | send 8081 # no newline, then EOF
```
T3 is how you reproduce anything deterministically. T2 is how you *observe*.
```mermaid
flowchart LR
T1["T1: the server
./mini_serv PORT — watch stderr"]
T2["T2: the observer
nc 127.0.0.1 PORT (like the grader)"]
T3["T3: the scripted sender
send() helper — repeatable"]
T2 <-->|"chat traffic"| T1
T3 -->|"connect / send / disappear"| T1
```
## 3. Trace prints (poor man's debugger)
Add temporary prints in the server. Two flavors:
```c
write(2, "accepted\n", 9); /* exam-safe */
fprintf(stderr, "recv fd=%d id=%d n=%zd buf=%s\n",
fd, clients[fd].id, n, clients[fd].msg); /* local-only */
```
Rules:
- print to **stderr** (fd 2) so it interleaves with the client traffic in T1 without messing
with anything else;
- useful things to print: which fd `select` reported ready, `max_fd`, the `recv` return
value, the buffer after appending, the string you're about to relay;
- **before submitting, delete every trace line** (`grep -n 'fprintf\|printf' mini_serv.c`) —
`printf` is not in the allowed-function list.
```mermaid
flowchart TD
A["select() returned"] --> B{"listen fd ready?"}
B -->|"yes"| C["accept() — print: new fd + client id"]
B -->|"no"| D["recv() — print: return value n"]
D --> E{"n <= 0 ?"}
E -->|"yes"| F["print: disconnecting fd + id"]
E -->|"no"| G["after str_join — print the whole buffer"]
G --> H["inside the extract loop — print each line before send"]
```
## 4. Fast signals from the outside
| Observation | What it already tells you |
|---|---|
| `./mini_serv; echo $?` → `1` + stderr text | your argc guard + `exit` path work, or the strings are wrong |
| `nc` prints **Connection refused** | nothing is listening on that port: server not running / died / wrong port |
| `nc` connects but nothing ever arrives | listen works, but accept/broadcast never happens (or `select` misses the fd) |
| `nc` can't connect until server starts, then works | bind+listen fine |
| `top` shows 100% CPU with no clients | `select` returns instantly forever: set not rebuilt / readiness not consumed |
| server silently dies after a client disconnects | `echo $?` → `141` = killed by SIGPIPE; `139` = segfault (see §6) |
| everything works for 1 client, breaks at 2 | `max_fd` not updated on accept, or set rebuilt from a stale copy |
| message appears only when the sender sends MORE bytes | you flush on `recv` instead of extracting full lines |
## 5. Symptom → cause table (the one to tape to your monitor)
| Symptom | Most likely cause | Confirm with | Fix |
|---|---|---|---|
| `Wrong number of arguments` even with a port | `argc` test wrong (`< 2`, `<= 2`…) | `./mini_serv 8081; echo $?` | `if (argc != 2)` |
| immediate `Fatal error`, port free | bind hit a stale/TIME_WAIT port; or bad addr | `ss -tan \| grep PORT` | try another port; check `htonl(2130706433)` |
| nc connects, nothing happens | accept branch never runs: fd not in set, `max_fd` wrong, or you check readiness against the wrong set (`active_fds` instead of the copy) | print every fd `select` reports; print `max_fd` | rebuild/copy sets each loop; `FD_SET` new fds into the *master*; pass `max_fd + 1` |
| 100% CPU, no clients | `select` never blocks — e.g. `FD_SET(0,…)`/junk bits, or you `continue`d past a ready fd | `top`, trace prints | `FD_ZERO` + set only real fds; always consume readiness |
| 1 client fine, 2nd client ignored | `max_fd` not raised on accept | trace `max_fd` after accept | `if (fd > max_fd) max_fd = fd;` |
| extra answer: newcomer gets its own arrival line | broadcast includes the new fd | two nc | exclude the new fd (or broadcast before `FD_SET`-ing it — the pre-accept set copy naturally excludes it) |
| recipient gets text only after ANOTHER packet arrives | you only extract one line per `recv`, or you wait for `\n` to appear before treating the chunk | send `a\nb\n` in one shot | `while (extract_message(...) == 1)` after every append |
| prefix missing / duplicated | prefix built once per `recv` instead of per line | same test | build `"client N: " + line` *inside* the extract loop |
| sender sees its own message | broadcast doesn't exclude `fd` | 2 nc, one sends | skip the sender |
| ids restart or equal fds | `id` derived from fd/count | connect → leave → connect | dedicated `id = next_id++` |
| no `just left` on Ctrl-D | `recv <= 0` branch missing, or you `exit()` there | Ctrl-C an nc | broadcast left, `FD_CLR`, `close`, `free` |
| leftover partial text is flushed on disconnect | you broadcast the buffer at EOF | `printf 'abc' \| send PORT` | drop it: free, don't send |
| segfault after churn | fd used after close, index out of bounds, `strlen(NULL)` | `gdb`, `valgrind` (§6) | see §6 output |
| `select: Bad file descriptor` | closed fd still in the set, or `max_fd` smaller than a watched fd | trace prints | `FD_CLR` **before** `close(fd)`; keep `max_fd` honest |
| killed when a client leaves (exit 141) | SIGPIPE: you `send` to a socket that got a reset | `echo $?` = 141 | official test doesn't hit this; if you want armor: `signal(SIGPIPE, SIG_IGN)` (check your subject's allowed list) |
| valgrind `definitely lost` | forgot `free(msg)` after relay; forgot `free(clients[fd].msg)` on disconnect; leaked remainder buffers | valgrind recipe §6 | free every `char *` the two helpers hand you |
| works, but the 364 KB test never delivers | fixed-size buffers + no append, or single-line extract only | `bash tester/check.sh`, read `sandbox/traceback` | heap-append the chunk; extract when `\n` shows up |
## 6. The tools in practice
### gdb — freeze it and look inside
```bash
gdb --args ./mini_serv 8081
(gdb) run
# ... reproduce the misbehaviour in T2/T3 ...
# if it hangs: press Ctrl-C in gdb
(gdb) bt # where is it stuck?
(gdb) info locals # variables at that frame
(gdb) p fd
(gdb) p clients[fd].id
```
Segfault case: run, reproduce, then `bt`, `frame `, `info locals`, `p *buf`.
The frame where the crash happened plus the variables is usually the whole story.
(When `bt` shows `recv` or `select` waiting — that's not a crash, that's *blocking*:
go up a frame or two to find whose loop forgot to check readiness.)
### valgrind — memory and fd audit
```bash
cc -Wall -Wextra -Werror -g mini_serv.c -o mini_serv
valgrind --leak-check=full --track-fds=yes ./mini_serv 8099
# in another terminal: reproduce a full session (connect, chat, Ctrl-C, replay)
# then Ctrl-C the server and read the summary
```
What to look for:
- `definitely lost: N bytes` → a `malloc` nobody freed (see table above);
- `FILE DESCRIPTORS: N open at exit` → an fd never `close`d;
- `Invalid read/write` → out-of-bounds (classic: `clients[fd]` indexing, `buf[n]` off-by-one).
### ss / lsof — see what the kernel sees
```bash
ss -tlnp | grep 8081 # is anything LISTENing?
ss -tnp | grep 8081 # who is CONNECTED (and how many are queued)
lsof -p $(pgrep mini_serv) # the process's open files/fds
ls -l /proc/$(pgrep mini_serv)/fd # same, without lsof
```
### The gym's graders
```bash
bash tester/check.sh # the full mill
python3 tester/mini_serv_tester.py sandbox/mini_serv --quick # fast loop
sed -n '1,60p' sandbox/traceback # grader's expected-vs-you diff
```
`traceback` is not an error message — it's a **difference report**. Read the first
difference and work backwards; don't read the whole thing.
## 7. 60-second triage checklist
```mermaid
flowchart TD
P["server misbehaves"] --> C{"compiles?"}
C -->|"no"| C1["fix the FIRST error only, recompile"]
C -->|"yes"| R{"process alive? check echo $?"}
R -->|"141 = SIGPIPE, 139 = segv, 1 = exit(1)"| R1["read stderr; gdb / valgrind; see §5 table"]
R -->|"alive"| L{"ss -tlnp shows LISTEN on the port?"}
L -->|"no"| L1["bind failed, wrong port, or Fatal error already printed"]
L -->|"yes"| N{"nc connects?"}
N -->|"refused"| L1
N -->|"connected but silent"| T["trace prints: is accept() reached? is the fd in the set?"]
N -->|"chat flows"| M{"messages exactly right?"}
M -->|"flushed early / lines missing"| M1["buffer + extract logic — cheatsheet trap 6"]
M -->|"only the first client works"| M2["max_fd and the set rebuild — traps 1 and 2"]
M -->|"yes"| G["bash tester/check.sh — let the grader speak"]
```
1. `cc -Wall -Wextra -Werror -g` — does it even compile?
2. `./mini_serv 8081; echo $?` — argument path sane?
3. `ss -tlnp | grep 8081` — is it listening?
4. `nc` connect works; arrival message correct on the *other* client?
5. One scripted line `printf 'a\nb\n' | send PORT` — both lines relayed, prefix per line?
6. Split line test — one message, no early flush?
7. EOF test — `left` broadcast, no partial flush?
8. `bash tester/check.sh` — the whole thing.
Fix the **first** red step, not the last one. Everything downstream is usually a
consequence.
## 8. Exam-day debugging budget
Plan for ~30 minutes of debugging even on a good run. Order of attack:
1. `nc` two windows — behavior first, code second.
2. Trace prints at: `select` result → accept → recv return value → buffer after append →
what you relay. That's 5 prints that locate almost every bug.
3. If it dies: `echo $?` (141 SIGPIPE / 139 segv), then `bt` in gdb if installed.
4. Last resort, not first: simplify — comment out the relay, make it echo to the sender
only, confirm the pipeline, then re-enable.