Skip to content
systemcoding.dev
Debugging

The Complete Guide to Tracing Programs With strace and ltrace

Learn to trace programs on Linux with strace 6.8 and ltrace 0.7.3: read every line, filter, time, follow children, find config bugs and know the limits.

26 min read
Summarize in AI
Flat illustration of a debugger stopped at a breakpoint beside the register values, with the Linux, LLVM and GNU logos.

Most programs fail in a boring way. They cannot find a file, they are not allowed to open one, they wait forever for a network peer, or they ask the operating system for something it refuses to give. The error message the program prints is often a summary of that boring failure with the useful part removed: cannot read configuration, connection failed, permission denied with no path. A tracer shows the missing part. It prints every request a program makes to the operating system, with the arguments it passed and the answer it received, and from that record the cause of most everyday failures is visible within a minute. This guide teaches that skill from the start. It covers strace, which traces the system calls a program makes to the Linux kernel, and ltrace, which traces the calls a program makes into shared libraries. It uses strace 6.8 and ltrace 0.7.3 on Ubuntu 24.04 with glibc 2.39 and a 6.8 kernel, and every command and output block in it can be reproduced on a similar system, with the caveat that process IDs, addresses, timings and some library details will differ.

You do not need to know how the kernel works to follow this guide. You need a Linux machine, a terminal and a program that misbehaves. Each idea is introduced when you need it, in the order a real investigation uses it, and the guide ends with a set of worked cases and a reference you can keep next to the terminal.

Why tracing works

A program running on Linux cannot touch the world directly. It cannot read a file, open a network connection, start another program, allocate a large block of memory or even print a character to the screen by itself. All of those actions belong to the kernel, and the program has to ask. Each request goes through a numbered entry point called a system call. Opening a file is openat, reading from it is read, writing is write, making a network connection is connect, creating a process is clone, and replacing the running program with another is execve. There are a few hundred of them, and every program on the system, whatever language it is written in, makes its requests through them.

That fact is what makes a tracer possible and useful. Because every interaction with the outside world passes through the same narrow door, a tool that watches the door sees everything the program does to the outside world, without knowing anything about the program. It does not matter whether the program is written in C, Python, Go or Java, whether you have the source, or whether the binary was built last week or in 2009. The system calls are the same.

Linux provides the mechanism through a system call of its own, ptrace. A tracer attaches to a program, the kernel stops the program at each system call entry and exit, and the tracer reads the arguments and result from the stopped program and prints them. strace is that tracer, packaged as a command. Its output is a faithful record of the conversation between the program and the kernel, one line per call.

ltrace works one level up. Most programs do not call the kernel directly. They call functions in shared libraries such as the C library, which in turn make the system calls. A program that calls printf ends up making a write system call, but the printf call carries information the write does not: the format string and the values. ltrace stops the program at calls into shared libraries and prints those, so it shows the program's own view of the world, such as malloc(32), strcpy(dst, "hello") and getenv("HOME"). The two tools complement each other, and a good investigation often uses both.

What a trace cannot tell you

Be clear about the limit before you start. A tracer shows what a program asked the system, not why it asked, and not what the program computed internally. It does not show a loop that burns CPU without making system calls, an arithmetic error, or a logic bug that never reaches the kernel. For those problems a debugger is the right tool. What a tracer is exceptionally good at is every question of the form: what files, what network addresses, what processes, what signals, what permissions, what waits. Most real failures in deployed software are of that form, which is why strace is on the short list of tools worth learning first.

Your first trace

Start with the smallest possible program that does something visible. The command true does nothing and exits, and tracing it shows what even nothing costs:

Shell
strace true
Text
execve("/usr/bin/true", ["true"], 0x7ffd5f3a2d10 /* 38 vars */) = 0
brk(NULL)                               = 0x55c5e1b3c000
arch_prctl(0x3001 /* ARCH_??? */, 0x7ffd1a9e3b40) = -1 EINVAL (Invalid argument)
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f2a64d7e000
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
newfstatat(3, "", {st_mode=S_IFREG|0644, st_size=61253, ...}, AT_EMPTY_PATH) = 0
mmap(NULL, 61253, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f2a64d6f000
close(3)                                = 0
openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220\243\2\0\0\0\0\0"..., 832) = 832
close(3)                                = 0
mprotect(0x7f2a64d5a000, 16384, PROT_READ) = 0
munmap(0x7f2a64d6f000, 61253)           = 0
exit_group(0)                           = ?
+++ exited with 0 +++

The trace is trimmed and its numbers will differ on your machine, but the shape is always the same, and it is worth reading once slowly, because the same pattern opens every dynamically linked program on the system.

The first line is execve, the call that started the program. It shows the program's path, its argument list, a pointer to the environment, and the comment that the environment holds 38 variables. The result after the equals sign is zero: success. Next come a few calls that set up memory, brk and mmap, which you can ignore for now. Then the dynamic loader goes looking for libraries. It checks for a preload file with access, which fails with ENOENT, "no such file", and that is normal because almost no system has one. It opens the library cache /etc/ld.so.cache and maps it into memory, finds the C library from the cache, opens /lib/x86_64-linux-gnu/libc.so.6, reads its first 832 bytes, which start with the ELF header you can see as \177ELF, and maps it. Finally the program has nothing to do and calls exit_group(0), which ends the process with status 0. The question mark after it means the call never returned, because the process was gone, and the last line is strace's own note that the process exited with status zero.

Everything else you will do with strace is a variation on reading lines like these. Learn the anatomy of one.

Reading a single line

Every line has the same parts:

Text
openat(AT_FDCWD, "/etc/hostname", O_RDONLY) = 3

The word before the opening parenthesis is the system call name: openat. The arguments follow, in the order the kernel expects them. Here the first, AT_FDCWD, means "resolve the path relative to the current directory", the second is the path as a string, and the third is the flag O_RDONLY, open for reading only. strace decodes flag bits into their symbolic names, which is much of its value, since the kernel itself only sees numbers. After the closing parenthesis comes an equals sign and the result. For openat, a successful result is a file descriptor, a small integer that names the open file in later calls. Here it is 3. The numbers 0, 1 and 2 are always standard input, output and error, so the first file a program opens by itself is usually 3.

A failure looks different:

Text
openat(AT_FDCWD, "/etc/nothere", O_RDONLY) = -1 ENOENT (No such file or directory)

The result is -1, which is how system calls signal an error in the C interface, followed by the name of the error code, ENOENT, and its description in parentheses. The error name is the useful part. The same few appear again and again, and reading them quickly is most of the skill:

ErrorMeaningTypical cause
ENOENTno such file or directorywrong path, missing file, wrong working directory
EACCESpermission deniedfile mode, directory permissions or a security module
EPERMoperation not permittedneeds root or a capability
EEXISTfile existscreating something that is already there
ENOTDIRnot a directorya path component is a file
EISDIRis a directoryopening a directory for writing
EINVALinvalid argumenta bad value passed to the call
EAGAINtry againa non-blocking call that has nothing yet
EINTRinterrupteda signal arrived during the call
ECONNREFUSEDconnection refusednothing listening on that address and port
ETIMEDOUTconnection timed outpeer or firewall not answering
ENOSPCno space left on devicedisk is full
EMFILEtoo many open filesper-process descriptor limit reached

The full list is in the errno manual page, section 3 (man 3 errno), and you can read the possible errors for any one system call in its own page, section 2, such as man 2 openat. Make that a habit. The manual page for the call lists what each error means for that particular call, and it is the primary reference for every line you will read.

Some lines do not have a result yet. If the program is blocked inside a call, strace prints the call's name and arguments as soon as it starts and finishes the line when the call returns. A line that ends in the middle, with no equals sign, is a program waiting inside that call. This is the single most useful thing to know when diagnosing a hang, and the guide returns to it later.

Strings, buffers and structures

strace shows data, not only numbers. A read or write call includes the buffer, as a quoted string with the usual escapes:

Text
write(1, "hello\n", 6)                  = 6

By default, strace prints at most 32 bytes of any string and adds three dots when it cuts one off. Use -s to raise the limit:

Shell
strace -s 200 ./myprogram

Binary data is printed with escapes such as \177 and \0. When you want the raw hexadecimal, -x prints non-printable bytes as hex and -xx prints every byte as hex. Structures, such as the one newfstatat fills with file information, are printed in braces with the interesting fields, and the ... inside them is strace shortening the structure. To see all fields, use -v, the verbose option, which turns off the abbreviation.

File descriptors appear as bare numbers, and keeping track of which number names which file is tedious. The -y option annotates each descriptor with the path it refers to:

Shell
strace -y cat /etc/hostname
Text
openat(AT_FDCWD, "/etc/hostname", O_RDONLY) = 3</etc/hostname>
read(3</etc/hostname>, "buildhost\n", 131072) = 10
write(1</dev/pts/0>, "buildhost\n", 10) = 10

The text in angle brackets after each descriptor is the file, or the terminal, or for a network socket the addresses at each end when you use -yy. This option turns many traces from puzzles into readable stories.

Tracing a command, and a process that is already running

There are two ways to start tracing, and you will use both.

The first is to run the program under strace, by putting strace in front of the command. The program starts as strace's child, and the trace begins at its first instruction. This is right for a program that fails quickly, or one you can start yourself. It captures start-up, which is where configuration and library problems appear.

The second is to attach to a process that is already running, with -p and its process ID:

Shell
sudo strace -p 2310
Text
strace: Process 2310 attached
read(0,

Attaching shows what the process is doing now, not what it did before, which suits a program that has been running for days and has just started to misbehave. The last line in the example is cut off after read(0, because the process is blocked in that call. The program is waiting to read from file descriptor 0, and it will stay there until data arrives. Press Ctrl-C and strace detaches, leaving the process running.

Attaching to a process you do not own needs privilege. On a typical distribution you can attach to your own processes only if the Yama security setting allows it, and to anyone else's only as root. The kernel setting kernel.yama.ptrace_scope controls it: 0 allows tracing any process of the same user, 1 allows only descendants, 2 allows only administrators, and 3 allows nothing. On Ubuntu the default is 1, which is why strace -p on a sibling process says Operation not permitted until you use sudo.

Saving the trace and reading it later

A busy program prints more than a terminal can show. Write the trace to a file with -o:

Shell
strace -o /tmp/job.strace ./myprogram --flag value

Writing to a file does three useful things. It keeps strace's output apart from the program's own output, which would otherwise be mixed into the same stream. It lets you search with the usual tools. And it lets you share the evidence: a trace file attached to a bug report is worth a paragraph of description. The commands grep, less and awk work on it as on any text.

Shell
grep -n ENOENT /tmp/job.strace | head
Text
12:access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
41:openat(AT_FDCWD, "/home/dev/.config/myprogram/config.toml", O_RDONLY) = -1 ENOENT (No such file or directory)
42:openat(AT_FDCWD, "/etc/myprogram/config.toml", O_RDONLY) = -1 ENOENT (No such file or directory)

The second and third lines are a program looking for its configuration in two places and finding it in neither, which is an answer that no error message from the program was giving.

Cutting the noise with filters

A trace of anything substantial runs to thousands of lines, and most of them are not the ones you need. The first discipline of tracing is to ask a question before you read, then filter to match it.

The -e trace= option selects system calls by name, with a comma-separated list:

Shell
strace -e trace=openat,read cat /etc/hostname
Text
openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220\243\2\0\0\0\0\0"..., 832) = 832
openat(AT_FDCWD, "/etc/hostname", O_RDONLY) = 3
read(3, "buildhost\n", 131072)          = 10
read(3, "", 131072)                     = 0

Names are the kernel's names. On current systems the open call is openat, because glibc implements open() through it, so asking for open shows nothing and raises no error, which is a common reason for an empty trace. For groups of related calls, strace has named sets that start with a percent sign: %file for calls that take a file name, %desc for calls on descriptors, %network for sockets, %process for process lifecycle, %memory for memory mapping and %signal for signals. The set %file is the one to reach for when the question is about files:

Shell
strace -e trace=%file ./myprogram

The ! character negates a list, which is useful for removing one noisy call and keeping everything else. A multi-threaded program spends most of its trace in futex, so -e 'trace=!futex' clears that out. Quote the expression, because most shells treat the exclamation mark specially.

Filtering by outcome is as important as filtering by name. The -e status=failed option, or -Z, shows only calls that returned an error:

Shell
strace -Z ./myprogram

Failures are where most investigations end, because the question "what went wrong" is usually answered by the one call that returned an error. A word of caution that experienced users learn quickly: not every failure is a problem. Programs probe for optional files by design, and the loader's check for /etc/ld.so.preload fails on nearly every system. Read each failure in context, and ask whether the program could carry on without the thing it failed to get.

Filters reduce what is printed, not the cost of tracing. strace still stops the program at every system call, so a filter makes the output shorter without making the program faster. There is one exception worth knowing: with -f and the --seccomp-bpf option, strace asks the kernel to stop the program only for the calls selected by the filter, which reduces the overhead of tracing a few calls in a busy program.

Timing: when, how long and how often

A trace tells you what happened. Timing options tell you when, and the combination answers questions about slowness.

The -t family adds a timestamp to each line. -t shows the wall-clock time to the second, -tt adds microseconds, and -ttt shows seconds since the Unix epoch, which is easier for scripts. The -r option shows the time since the previous call, which makes gaps visible without arithmetic. The -T option appends the time spent inside each call, in angle brackets:

Shell
strace -T -e trace=openat,connect,read ./myprogram
Text
openat(AT_FDCWD, "/etc/hosts", O_RDONLY|O_CLOEXEC) = 3 <0.000032>
connect(4, {sa_family=AF_INET, sin_port=htons(443), sin_addr=inet_addr("203.0.113.7")}, 16) = 0 <0.482911>
read(4, "HTTP/1.1 200 OK\r\n"..., 4096) = 312 <0.001205>

The durations are an example, and you should treat them with care: strace's own overhead is inside them, so they overstate the cost of fast calls. They are good for finding a call that takes orders of magnitude longer than its neighbors, such as the connect that took nearly half a second in the example. That one line says where the program's start-up time went, and it names the address it waited for.

For a count of how much time each kind of call used, -c summarizes the whole run instead of printing every call:

Shell
strace -c ./myprogram
Text
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
 61.40    0.019800        1980        10           connect
 24.10    0.007770          14       554           read
 10.20    0.003290          10       321           openat
  4.30    0.001380           3       412         9 newfstatat
------ ----------- ----------- --------- --------- ----------------
100.00    0.032240                  1297         9 total

The table lists each call with the share of time, the total seconds, the average per call, the number of calls, and the number of errors. A program that makes 554 read calls is a candidate for a larger buffer. A program with many openat errors is probing for files. A program dominated by a single call is waiting on it. A counting run adds little output, so it is a fine first look at an unfamiliar program before you decide what to trace in detail. The -w option, available in current versions, summarizes wall-clock time in place of system time, which is the right choice when the program spends its time blocked.

Following children and threads

Run strace on a shell script and the trace is nearly empty, because the script's work happens in other programs the shell starts, and strace only follows the process it launched. The -f option makes it follow every new process and thread:

Shell
strace -f -e trace=execve sh -c 'ls | wc -l'
Text
execve("/usr/bin/sh", ["sh", "-c", "ls | wc -l"], 0x7ffe3a1d4c58 /* 38 vars */) = 0
strace: Process 3102 attached
strace: Process 3103 attached
[pid  3102] execve("/usr/bin/ls", ["ls"], 0x55b7f1a3f6b0 /* 38 vars */) = 0
[pid  3103] execve("/usr/bin/wc", ["wc", "-l"], 0x55b7f1a3f6b0 /* 38 vars */) = 0
[pid  3103] +++ exited with 0 +++
[pid  3102] +++ exited with 0 +++
+++ exited with 0 +++

Once more than one process is traced, each line carries a process ID in brackets. Combining -f with -e trace=execve is a quick way to list every command a script or a build runs, with its arguments. For a large tree of processes, the lines of different processes interleave and become hard to read, and -ff together with -o writes one file per process, named with the process ID, so each file reads like an ordinary single-process trace.

Threads are created with the same underlying call as processes, so -f covers them. Attaching with -p to a multi-threaded server traces only the one thread you named unless you add -f, and the thread that does the work is often a different one.

Signals and exits

strace prints signals the program receives, in lines that begin with three dashes:

Text
--- SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_MAPERR, si_addr=0x8} ---
+++ killed by SIGSEGV (core dumped) +++

This is how a crash looks to a tracer: the signal, the kind of fault, and the address that was accessed. A segmentation fault at address 0x8 is almost always a null pointer plus a small field offset, and seeing it names the type of bug, though not the line. The line before the signal shows the last system call the program made, which often points at the code region. For the line itself, you need a debugger or a core file, but the trace has already told you the program crashed in its own code and not in a library failure.

A program that exits with a failure code shows it on the last line:

Text
+++ exited with 1 +++

The status is the program's choice. Look at the calls just before it, usually a failed openat or connect, and a write of an error message to descriptor 2, standard error, such as write(2, "cannot read configuration\n", 26). The call that failed immediately before the message is the cause the message hid.

Network calls

For networking problems the %network set and the -yy option are the tools. A connection attempt shows the destination address and port:

Shell
strace -f -yy -e trace=%network ./myclient
Text
socket(AF_INET, SOCK_STREAM|SOCK_CLOEXEC, IPPROTO_IP) = 3<TCP:[44211]>
connect(3<TCP:[44211]>, {sa_family=AF_INET, sin_port=htons(5432), sin_addr=inet_addr("10.0.0.7")}, 16) = -1 ECONNREFUSED (Connection refused)

That answers a question the program's own error message probably left vague. It tried to reach 10.0.0.7 on port 5432, and the connection was refused, which means the host answered and nothing was listening on that port. A different result would mean something else. ETIMEDOUT after a long wait means packets were being dropped, typically by a firewall. ENETUNREACH means there is no route. EINPROGRESS on a non-blocking socket is normal and is followed by a poll or select call that waits for the result. A program that never connects but sits in connect for a long time is waiting for a timeout, and -T shows how long.

Name resolution leaves its own trail. Before connect, the program often opens /etc/resolv.conf and /etc/hosts, sends a UDP packet to the resolver, and reads the answer. If a program is slow to start talking to a server, the gap is frequently in the DNS lookup, and -tt on those lines shows it.

Data in and out

When you want to see the contents of the data a program reads or writes, not only the first bytes, strace can dump a descriptor in full as a hexadecimal and text listing, with -e read= or -e write= naming the descriptor:

Shell
strace -e trace=write -e write=1 echo hi
Text
write(1, "hi\n", 3)                     = 3
 | 00000  68 69 0a                                          hi.             |

The dump line shows the offset, the bytes in hexadecimal and the printable form. This is how you read a binary protocol, or a long message that -s would cut off. For a tool talking to a server over a socket, dump the socket descriptor to see the exact request bytes.

Seeing where in the code a call came from

By default a trace says what the program asked and not which line of code asked. If strace was built with stack-unwinding support, which is common in distribution packages, the -k option prints a stack trace after each call:

Shell
strace -k -e trace=openat ./myprogram
Text
openat(AT_FDCWD, "/etc/myprogram.conf", O_RDONLY) = -1 ENOENT (No such file or directory)
 > /lib/x86_64-linux-gnu/libc.so.6(__open64+0x4a) [0x11b2fa]
 > /usr/local/bin/myprogram(load_config+0x32) [0x1a52]
 > /usr/local/bin/myprogram(main+0x18) [0x1b30]

Now the failed open has a caller: load_config, called from main. Function names appear when the binary has symbols, and plain offsets when it was stripped. The option works best on a build with debug information, and it is the quickest bridge from a trace to the source line when you have the source. If your strace says the option is not supported, the package was built without it.

Changing what the program sees

A trace can also change behavior, which is what makes it useful for testing error handling. The -e inject= option makes a chosen call fail on purpose:

Shell
strace -e trace=openat -e inject=openat:error=ENOSPC:when=3 ./myprogram

This makes the third openat return ENOSPC, "no space left on device", without filling any disk. It is a cheap way to check what a program does when a rare error occurs, such as whether it reports the failure or crashes. The delay_enter and delay_exit forms add delay to simulate a slow disk or network. Use these on a test copy, never on a system you cannot afford to disturb.

Library calls with ltrace

System calls are one layer of what a program does. The other is its use of shared libraries, and ltrace shows it:

Shell
ltrace ./greet world
Text
malloc(32)                                       = 0x5581e3a2f2a0
strcpy(0x5581e3a2f2a0, "world")                  = 0x5581e3a2f2a0
strlen("world")                                  = 5
printf("%s has %zu bytes\n", "world", 5world has 5 bytes
)         = 18
free(0x5581e3a2f2a0)                             = <void>
+++ exited (status 0) +++

Each line is a call into a shared library, with the arguments and the return value. This is the view a developer has of the program, and it shows things a system call trace never will: the strings passed to strcpy, the size passed to malloc, the variable names passed to getenv. The program's own output, world has 5 bytes, appears in the middle of the printf line, because ltrace prints the call after it returns, and the program wrote its output during the call.

Most strace options have equivalents. -f follows children, -o writes to a file, -p attaches to a running process and -s sets the string length. Filtering uses -e with function names joined by a plus sign:

Shell
ltrace -e 'malloc+free' ./greet world
Text
greet->malloc(32)                                = 0x5581e3a2f2a0
greet->free(0x5581e3a2f2a0)                      = <void>
+++ exited (status 0) +++

The -S option shows system calls in the same stream, so you see a library call and the kernel calls it caused side by side. And -c summarizes calls and time like strace's -c.

Know ltrace's limits. It sees only calls that go through the dynamic linker's procedure linkage table, so it shows nothing for a statically linked program. It cannot see a call the compiler inlined, and with optimization on, a call to printf may be turned into puts. Programs written in Go and Rust often bypass the C library for much of their work, so ltrace shows little for them. The latest ltrace release, 0.7.3, is from 2013, and some modern position-independent executables on hardened systems confuse it. When ltrace fails on a binary, a dynamic-tracing tool such as bpftrace with uprobes, or a breakpoint in a debugger, reaches the same information with more setup.

Worked case one: the setting that has no effect

A tool ignores a change you made to its configuration file. The question is which file it actually reads.

Shell
strace -f -e trace=%file -e status=failed -o /tmp/tool.strace ./tool --serve
grep -v ld.so /tmp/tool.strace
Text
openat(AT_FDCWD, "/home/dev/.config/tool/tool.conf", O_RDONLY) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/etc/tool/override.conf", O_RDONLY) = -1 ENOENT (No such file or directory)

The two failures are the places the tool looked before it found a file. Now repeat without the failure filter and find the first successful open of a configuration file:

Shell
grep -E 'openat.*\.conf' /tmp/tool.strace
Text
openat(AT_FDCWD, "/var/lib/tool/tool.conf", O_RDONLY) = 3

There it is. The tool reads a copy in /var/lib/tool, not the file in /etc. Edits to the one in /etc never mattered, because a different file shadows it. The fix is to change the right file, and the proof that it worked is the same trace showing the intended path on its successful open.

Worked case two: the program that hangs

A program starts and then does nothing. Attach to it:

Shell
sudo strace -f -p 4021
Text
strace: Process 4021 attached with 3 threads
[pid  4023] futex(0x7f9c40000b60, FUTEX_WAIT_BITSET_PRIVATE|FUTEX_CLOCK_REALTIME, 0, NULL, FUTEX_BITSET_MATCH_ANY <unfinished ...>
[pid  4022] read(5<socket:[88213]>, 
[pid  4021] futex(0x7f9c4a1b9a90, FUTEX_WAIT_BITSET_PRIVATE|FUTEX_CLOCK_REALTIME, 0, NULL, FUTEX_BITSET_MATCH_ANY

Three threads, three unfinished calls. Two are waiting on a futex, a lock or a condition variable, and one is reading from a socket whose number is shown, 88213. The thread that reads from the socket is waiting for the peer to send something. The others wait for that thread, or for each other. Look up the socket with ls -l /proc/4021/fd/5 and ss -tp to see which remote address it is connected to. The picture is a program waiting for a server that has not answered, and the next question is about that server, not this program.

The reading skill is the same every time: an unfinished call is where a thread lives, and its arguments say what it is waiting for.

Worked case three: slow start-up

A tool takes eight seconds to start and you do not know why. Use timestamps and look for a gap:

Shell
strace -f -tt -o /tmp/slow.strace ./tool --version
awk '{print $1}' /tmp/slow.strace | head -3

Open the file and scan the left column of times for a jump. A jump of several seconds between two adjacent lines puts the cause in the call before the gap, which is where the program blocked:

Text
14:20:03.100412 connect(4<TCP:[44211]>, {sa_family=AF_INET, sin_port=htons(53), sin_addr=inet_addr("10.0.0.2")}, 16) = 0
14:20:03.100588 sendto(4, "\x1c\xd2\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03api\x07example\x03com\x00\x00\x01\x00\x01", 33, MSG_NOSIGNAL, NULL, 0) = 33
14:20:08.101103 poll([{fd=4, events=POLLIN}], 1, 5000) = 0 (Timeout)

The program sent a DNS query, waited five seconds, and got a timeout. The resolver address 10.0.0.2 is not answering, which explains the delay without any need to look at the program. The remedy lies in resolver configuration, and the trace showed that in a minute.

Worked case four: permission denied with no path

A program prints permission denied and nothing else.

Shell
strace -f -e trace=%file -e status=failed ./deploy.sh
Text
openat(AT_FDCWD, "/var/log/app/deploy.log", O_WRONLY|O_CREAT|O_APPEND, 0666) = -1 EACCES (Permission denied)

The path is in the line, and so is the operation: opening for append with creation. Check the directory's owner and mode and the user the script runs as. If the file's mode looks right, a mandatory access control module, such as SELinux or AppArmor, may be denying the call even though the ordinary permissions allow it, and the kernel log has the denial message.

Worked case five: a program that works as root and fails as a user

A common report is that a command works under sudo and fails without it, with an unhelpful message. Trace both runs to files and compare the first failure in each:

Shell
strace -f -o /tmp/user.strace ./tool --sync
sudo strace -f -o /tmp/root.strace ./tool --sync
grep -n -m1 -E 'EACCES|EPERM' /tmp/user.strace
Text
212:openat(AT_FDCWD, "/var/lib/tool/state.db", O_RDWR) = -1 EACCES (Permission denied)

The failing call names the file and the access the program wanted, read and write. In the root trace the same line shows a successful descriptor, which confirms the difference is permission and not a different code path. The fix is to give the user's group access to that file or to run the tool as the owning account, not to run everything as root. The comparison method, tracing the working and the failing case and diffing the first divergence, applies to any "works on my machine" problem: the point where the two traces first differ is where the environment differs, whether that is a file, a variable, a limit or a user.

A related check uses diff directly on filtered traces. Strip addresses and process IDs first, since they differ on every run, and compare what remains:

Shell
sed -E 's/0x[0-9a-f]+/ADDR/g; s/\[pid +[0-9]+\] //' /tmp/user.strace > /tmp/user.clean
sed -E 's/0x[0-9a-f]+/ADDR/g; s/\[pid +[0-9]+\] //' /tmp/root.strace > /tmp/root.clean
diff /tmp/user.clean /tmp/root.clean | head

The first differing lines name the call where the two runs parted ways. It will not always be the cause, but it is where to start reading.

Overhead, containers and what to use instead

A tracer stops the program twice for each traced call, so a program that makes many system calls slows down a great deal, sometimes by an order of magnitude. This does not matter for a program that is stuck or broken, which is the usual reason to trace. It does matter for a production service under real traffic, and for questions about performance, since the timings include the tracer's own cost. On a busy server, attach for a few seconds, write to a file with -o, and detach, or use a kernel-based tracer that does not stop the program: perf trace and bpftrace read the same events through the kernel's tracing facilities with far less disturbance.

In a container, ptrace is often blocked by default. Starting the container with the SYS_PTRACE capability, or tracing the container's processes from the host by their host process IDs, are the usual ways around it. Both are covered in a separate post in this series.

Two more practical limits. A program that uses ptrace on itself, a debugger or an anti-debugging check, cannot be traced by a second tracer at the same time, because the kernel allows only one tracer per process. And a setuid program run under strace by a normal user does not gain its extra privileges, so it may behave differently, because the kernel refuses to grant them to a traced process.

A habit for every investigation

The guide's lesson is a loop you can repeat. State the question: which file, which address, which process, which wait. Choose the cheapest trace that can answer it: a counting run to see the shape, a filtered trace for the call family, or an attach for a live process. Read failures and the last unfinished call first. Check each suspect line against the manual page for that call. Fix the cause, and trace again to confirm the line now says what you intended. The answer is usually one line in a few hundred, and the filters in this guide are how you find it quickly.

Quick reference

GoalCommand
Trace a commandstrace ./prog args
Attach to a running processsudo strace -p PID
Save to a filestrace -o out.txt ./prog
Follow children and threadsstrace -f ./prog
One file per processstrace -ff -o out ./prog
Only file callsstrace -e trace=%file ./prog
Only failuresstrace -Z ./prog
Longer stringsstrace -s 256 ./prog
Show paths for descriptorsstrace -y ./prog
Timestamps and call timestrace -tt -T ./prog
Summary tablestrace -c ./prog
Stack trace per callstrace -k ./prog
Library callsltrace ./prog
Library and system callsltrace -S ./prog
Filter library callsltrace -e 'malloc+free' ./prog
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.