CSE Roadmap

Core tier · about 3 hours · 7 parts

Part 3 of 7 · 2 min read

Tracing a program

Think of a stage play seen from backstage: before the first word the crew moves scenery, plugs in lights and checks the sound. The words are a small part of the work. The analogy stops in one place: the crew is a separate team, and here the dynamic loader and the C library are part of the same program.

In plain words: The program below prints one line.

#include <stdio.h>

int main(void) {
    puts("hello");
    return 0;
}

Under strace it makes 34 system calls, and one of them is the write of the line. The rest fall into groups.

Group Calls (examples) Purpose
Start execve, brk, arch_prctl, set_tid_address, rseq The kernel starts the program; the C library sets up its thread data
Find libraries access("/etc/ld.so.preload"), openat("/etc/ld.so.cache"), fstat, close The dynamic loader looks for libraries
Map the library openat("libc.so.6"), read, pread64, mmap (four times), close Map the C library into memory (Level 7)
Protect mprotect (three times) Make read-only parts read-only (Level 10)
Prepare output fstat(1), getrandom, brk (twice) Check what standard output is; set up the heap for the output buffer
Work write(1, "hello\n", 6) The only call that the source code asked for
End exit_group(0) End the process

A worked example. The first line is execve("./hello", ["./hello"], ... ) = 0, the kernel starting the program (Level 1). The access call on /etc/ld.so.preload returns ENOENT: the loader looks for an optional preload list and finds none, which accounts for the one error among the 34 calls. The four mmap calls on the C library map its code (PROT_READ|PROT_EXEC), its read-only data and its writable data into the address space, as Level 7 described. The call write(1, "hello\n", 6) = 6 writes 6 bytes to descriptor 1 (standard output). Only that one line corresponds to the source code. The rest is the cost of starting a dynamically linked program.

The key lines. puts did not call write at once: when output goes to a pipe or a file, the C library buffers it and flushes at exit (to a terminal it flushes at each new line). A program that prints with many small printf calls and a terminal output can make many write calls, and strace shows how many.

File descriptor 1

File descriptor 1 is standard output: the descriptor that every process has open at start, by convention, for normal output. Descriptor 0 is standard input and descriptor 2 is standard error.

Example: write(1, "hello\n", 6) sends six bytes to standard output.

Check yourself: 1. How many system calls did the hello program make? 2. Which call corresponds to the puts in the source? 3. Why does one call end with an error?