Skip to content
systemcoding.dev
Debugging

Trace Shared Library Calls With ltrace

Use ltrace 0.7.3 on Linux to print the shared library calls a program makes, such as malloc and strcpy, with arguments and return values, and filter with -e.

6 min read
Summarize in AI
Flat illustration of a magnifier over lines of a log, with the Rust, C and C++ logos.

strace shows what a program asks the kernel to do. It does not show the library functions a program calls on the way: malloc, strcpy, printf, fopen. That layer is where many bugs start, a wrong length passed to strcpy, a free of the wrong pointer, a getenv for a variable that is not set. ltrace traces calls into dynamic shared libraries, prints the arguments and return values, and needs no recompilation. This post uses ltrace 0.7.3 on Debian and Ubuntu with glibc 2.39, and a small C program built with GCC 14. It assumes you have used strace or at least read the post on tracing system calls with strace.

A program to trace

greet.cc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv)
{
    if (argc < 2)
        return 1;

    char *buf = malloc(32);
    strcpy(buf, argv[1]);
    printf("%s has %zu bytes\n", buf, strlen(buf));
    free(buf);
    return 0;
}

Build it without optimization so the compiler leaves the library calls visible:

Shell
gcc -O0 -o greet greet.c

The program copies its first argument into a heap buffer, prints it with its length, and frees the buffer. Run it normally first:

Shell
./greet world
Text
world has 5 bytes

Trace 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) +++

Read it line by line. Each line is a call, with its arguments in parentheses and the return value after the equals sign. The pointer values differ on every run because of address space randomization. strcpy returns its destination, so the same address appears twice. printf returns 18, the number of characters it wrote, and you can see the program's own output interleaved into the printf line, because ltrace prints the call after it returns while the program wrote its output during the call. free returns nothing, which ltrace shows as <void>.

This is the useful view when you do not have the source, or do not trust it. A binary that crashes can be run under ltrace to see the last library call before the failure.

Filter with -e

Real programs make thousands of library calls. The -e option selects which ones to show. A plus sign joins several names:

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

With a filter active, ltrace prefixes each call with the name of the module that made it, here the program greet. A leading ! inverts the filter, so -e '!malloc' shows everything except malloc. You can also restrict by library with -l, as in -l libssl.so.3, which shows only calls into that library.

Add the system calls

-S makes ltrace print system calls as well, so one stream shows the library call and the kernel call it caused. A printf or puts then appears next to the write it eventually produces, which explains stdio buffering: the library call happens when the program calls it, and the system call only when the buffer flushes. Use -S when you need to see that boundary. For the kernel side alone, strace gives the more complete view.

Count calls with -c

When you want totals rather than a transcript, -c summarizes:

Shell
ltrace -c ./greet world
Text
world has 5 bytes
% time     seconds  usecs/call     calls      function
------ ----------- ----------- --------- --------------------
 31.20    0.000121         121         1 printf
 24.40    0.000095          95         1 strcpy
 19.10    0.000074          74         1 malloc
 15.60    0.000061          61         1 free
  9.70    0.000038          38         1 strlen
------ ----------- ----------- --------- --------------------
100.00    0.000389                     5 total

The times are tracing overhead as much as real cost, and they differ on every run, so use the call counts and treat the times as a rough ranking only.

Find a real bug with it

The value of ltrace is that the arguments are visible. Change the program to a version with a classic mistake, copying a string into a buffer that is too small:

bad.cc
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv)
{
    if (argc < 2)
        return 1;

    char *buf = malloc(8);
    strcpy(buf, argv[1]);
    free(buf);
    return 0;
}

Running ltrace ./bad "a string that is far too long" shows the problem without any debugger:

Text
malloc(8)                                        = 0x55d1c8a7c2a0
strcpy(0x55d1c8a7c2a0, "a string that is far too long")  = 0x55d1c8a7c2a0
free(0x55d1c8a7c2a0)                             = <void>
+++ exited (status 0) +++

The trace makes the mismatch plain: the buffer was allocated with 8 bytes and the copied string is 29 characters plus the terminator. Nothing crashed here, because glibc usually has slack after small chunks, which is exactly why this kind of bug survives testing. The trace turns a silent corruption into a visible mismatch between two numbers. A sanitizer would catch it at the faulting instruction, and ltrace is the quick look you use first when you cannot rebuild the program.

Check what a program reads from its environment

Another everyday use is finding which environment variables and files a program consults, without reading its source. Filter to the calls that matter:

home.cc
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    const char *home = getenv("HOME");
    const char *editor = getenv("EDITOR");
    printf("%s %s\n", home ? home : "none", editor ? editor : "none");
    return 0;
}
Shell
ltrace -e getenv ./home
Text
home->getenv("HOME")                             = "/home/dev"
home->getenv("EDITOR")                           = nil
/home/dev none
+++ exited (status 0) +++

Each getenv("NAME") line shows a variable the program looks up, and its return value shows what it found, or nil when the variable is unset. This answers questions like which variable controls a hidden behavior far faster than searching documentation. The same filter on fopen and open lists the files a program opens through the library, though strace on openat is the more complete answer for files, since it also catches code that bypasses stdio.

Reading pointer arguments

ltrace prints a pointer to a string as the string, but for an arbitrary pointer it prints the hex address, and the contents are not decoded. Pointer values only mean something when compared: if malloc returns 0x5581e3a2f2a0 and free later gets the same value, the pair is correct. A free with an address that no earlier malloc returned is a double free or a free of a stack pointer, and the trace shows it immediately. Keep a short list of the returned addresses beside the trace when a program makes dozens of allocations.

Other useful options

OptionWhat it does
-ffollow forked children
-o FILEwrite the trace to a file instead of stderr
-Cdemangle C++ symbol names
-s Nprint up to N characters of string arguments (default 32)
-Salso show system calls
-p PIDattach to a running process
-n 2indent nested calls by two spaces

-s matters often: the default hides most of a long string, and the argument you need is usually the one that gets cut.

When ltrace does not work

ltrace has real limits, and knowing them saves time.

  • It only sees calls that go through the dynamic linker's procedure linkage table. A statically linked program has no such calls to intercept, so ltrace prints nothing useful.

  • A function the compiler inlined or replaced with a builtin is not a library call at all. With optimization on, GCC may turn printf("hi\n") into puts("hi"), so the trace shows puts, not what the source says. Build with -fno-builtin while you investigate.

  • Programs that call syscalls directly, as many Go programs do, bypass the C library entirely.

  • The 0.7.3 release dates from 2013, and some modern binaries, particularly position-independent executables built with newer toolchains and hardened distributions, trip it. If ltrace aborts with a message about breakpoints, fall back to strace and gdb.

If ltrace fails for your binary, a uprobe-based tool or gdb with a breakpoint on the library function reaches the same information, with more setup.

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.