ltrace Command

The ltrace command traces library function calls made by a program. It intercepts and records dynamic library calls and signals received by a process, making it invaluable for debugging and understanding program behavior.

Syntax

ltrace [OPTIONS] [COMMAND [ARGS...]] ltrace [OPTIONS] -p PID

Description

The ltrace command traces library function calls made by a program. It shows which functions from shared libraries are called, their arguments, and return values.

Key features:

  • Trace library function calls
  • Show function arguments and return values
  • Monitor signal delivery
  • Attach to running processes
  • Filter specific functions or libraries
  • Generate detailed execution reports
Note: ltrace requires ptrace permissions and may need to be run with appropriate privileges depending on the target process.

Common Options

Option Description
-p PID Attach to process with specified PID
-f Trace child processes (follow forks)
-e expr Modify which events to trace (functions, signals)
-l library Trace calls to functions in specified library
-o file Write output to file instead of stderr
-c Count calls and report summary
-C Demangle C++ function names
-n num Show at most num characters of strings
-s num Show at most num characters of string arguments
-S Also trace system calls (like strace)
-t Prefix each line with time of day
-tt Include microseconds in timestamps
-T Show time spent in each call
-u user Run command as specified user

Examples

Trace a new process

ltrace ls

Trace library calls made by the ls command

Attach to running process

ltrace -p 1234

Attach to and trace process with PID 1234

Trace with child processes

ltrace -f ./myprogram

Trace program and all child processes it creates

Filter specific functions

ltrace -e malloc,free ./myprogram

Trace only malloc and free function calls

Trace specific library

ltrace -l libc.so.6 ./myprogram

Trace calls to functions in libc library only

Save output to file

ltrace -o trace.log ./myprogram

Save trace output to a file

Count function calls

ltrace -c ./myprogram

Show summary count of function calls

Include timestamps

ltrace -tt ./myprogram

Include precise timestamps with each call

Understanding ltrace Output

Basic Output Format

$ ltrace ls __libc_start_main(0x404b60, 1, 0x7fff5c9b5c88, 0x40a2a0 strrchr("ls", '/') = nil setlocale(LC_ALL, "") = "en_US.UTF-8" bindtextdomain("coreutils", "/usr/share/locale") = "coreutils" textdomain("coreutils") = "coreutils" __cxa_atexit(0x4056a0, 0, 0, 0x736c6974756572) = 0 isatty(1) = 1 getenv("QUOTING_STYLE") = nil getenv("COLUMNS") = nil ioctl(1, 21523, 0x7fff5c9b5b90) = 0 malloc(16) = 0x1c3f010 opendir(".") = 0x1c3f030 readdir(0x1c3f030) = 0x1c3f048 strlen(".") = 1 malloc(24) = 0x1c3f070 strcpy(0x1c3f070, ".") = 0x1c3f070 readdir(0x1c3f030) = 0x1c3f048 strlen("..") = 2 malloc(24) = 0x1c3f090 strcpy(0x1c3f090, "..") = 0x1c3f090 +++ exited (status 0) +++

Example ltrace output showing library function calls

Output Components

Component Description
Function Name Name of the library function being called
Arguments Parameters passed to the function
Return Value Value returned by the function (after =)
unfinished Function call that hasn't completed yet
resumed Continuation of an unfinished call
+++ Process events (signals, exit status)

Summary Output (-c option)

$ ltrace -c ls % time seconds usecs/call calls function ------ ----------- ----------- --------- -------------------- 28.57 0.000020 4 5 malloc 21.43 0.000015 3 5 strlen 14.29 0.000010 2 5 strcpy 14.29 0.000010 10 1 opendir 7.14 0.000005 1 5 readdir 7.14 0.000005 5 1 closedir 7.14 0.000005 5 1 free ------ ----------- ----------- --------- -------------------- 100.00 0.000070 23 total

Summary showing function call statistics

Filtering and Selection

Function Filtering

Trace specific functions

# Single function ltrace -e malloc ./myprogram # Multiple functions ltrace -e malloc,free,calloc ./myprogram # Function patterns ltrace -e 'str*' ./myprogram

Filter to show only specific functions or patterns

Exclude functions

# Exclude specific functions ltrace -e '!printf' ./myprogram # Exclude multiple functions ltrace -e '!printf,!puts' ./myprogram

Exclude specific functions from tracing

Library Filtering

Trace specific libraries

# Standard C library ltrace -l libc.so.6 ./myprogram # Math library ltrace -l libm.so.6 ./myprogram # Multiple libraries ltrace -l libc.so.6 -l libm.so.6 ./myprogram

Limit tracing to specific shared libraries

Signal Tracing

Include signals

# Trace signals along with function calls ltrace -e signal ./myprogram # Trace specific signals ltrace -e signal=SIGTERM,SIGINT ./myprogram

Include signal delivery in the trace

Advanced Usage

Multi-Process Tracing

Follow forks and threads

# Follow child processes ltrace -f ./parent_process # Trace with process IDs ltrace -f -o trace_%p.log ./parent_process

Trace parent and child processes

Attach to process tree

# Attach to process and its children ltrace -f -p 1234 # Trace all processes in a group ltrace -f -p $(pgrep -g process_group)

Trace entire process hierarchies

Performance Analysis

Timing information

# Show time spent in each call ltrace -T ./myprogram # Include absolute timestamps ltrace -tt -T ./myprogram # Relative timestamps ltrace -r ./myprogram

Analyze performance and timing of function calls

Memory allocation tracking

# Track memory functions ltrace -e malloc,free,calloc,realloc ./myprogram # Count memory operations ltrace -c -e malloc,free,calloc,realloc ./myprogram

Monitor memory allocation patterns

Debugging Techniques

String handling analysis

# Show full string arguments ltrace -s 200 ./myprogram # Track string functions ltrace -e 'str*' ./myprogram # Monitor string operations ltrace -e strcpy,strcat,strlen,strcmp ./myprogram

Analyze string manipulation and handling

File I/O monitoring

# Track file operations ltrace -e fopen,fclose,fread,fwrite ./myprogram # Monitor file descriptors ltrace -e open,close,read,write -S ./myprogram

Monitor file and I/O operations

Practical Use Cases

Application Debugging

Debug library loading issues

# Check library loading ltrace -e dlopen,dlsym,dlclose ./myprogram # Monitor initialization ltrace -e '__*' ./myprogram

Debug dynamic library loading and initialization

Memory leak detection

# Track all memory operations ltrace -e malloc,free,calloc,realloc -c ./myprogram # Detailed memory tracing ltrace -e malloc,free,calloc,realloc -o memory.log ./myprogram

Identify potential memory leaks and allocation patterns

Performance Analysis

Function call profiling

# Profile function calls ltrace -c -T ./myprogram # Focus on expensive functions ltrace -T -e 'expensive_func*' ./myprogram

Profile application performance at the library level

I/O performance analysis

# Monitor I/O functions ltrace -T -e fread,fwrite,read,write -S ./myprogram # Track file operations timing ltrace -tt -T -e fopen,fclose ./myprogram

Analyze I/O performance and bottlenecks

Security Analysis

Monitor security-related functions

# Track authentication functions ltrace -e getpwnam,getgrnam,crypt ./myprogram # Monitor privilege changes ltrace -e setuid,setgid,seteuid,setegid ./myprogram # Track network security ltrace -e SSL_*,TLS_* ./myprogram

Monitor security-related library function calls

Analyze cryptographic operations

# OpenSSL functions ltrace -e 'SSL_*,EVP_*' ./myprogram # Crypto library functions ltrace -l libcrypto.so ./myprogram

Trace cryptographic library usage

Comparison with Other Tools

ltrace vs strace

Aspect ltrace strace
Purpose Traces library function calls Traces system calls
Level User space (library level) Kernel space (system call level)
Functions malloc, printf, strcpy, etc. open, read, write, fork, etc.
Use Case Debug library usage, memory leaks Debug system interactions, I/O

Combined Usage

# Use both tools together ltrace -S ./myprogram # ltrace with system calls # Or run separately ltrace ./myprogram & strace -p $!

Combine ltrace and strace for comprehensive analysis

Troubleshooting

Common Issues

Permission denied

# Run with appropriate privileges sudo ltrace -p 1234 # Check ptrace permissions echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope # For containers, may need --cap-add=SYS_PTRACE

Handle permission and ptrace issues

No symbols or stripped binaries

# ltrace may show limited info for stripped binaries ltrace -C ./stripped_program # Try C++ demangling # Use with debug symbols when available ltrace ./program_with_symbols # Check if symbols are available nm -D ./program | head

Work with stripped or optimized binaries

High volume output

# Filter to reduce noise ltrace -e '!printf,!puts' ./chatty_program # Use summary mode ltrace -c ./program # Limit string output ltrace -s 50 ./program

Manage large amounts of trace output

Performance Impact

Minimize overhead

# Trace specific functions only ltrace -e malloc,free ./program # Use summary mode for less overhead ltrace -c ./program # Avoid following all children ltrace ./program # Don't use -f unless needed

Reduce performance impact of tracing

Scripting and Automation

Automated Analysis Scripts

Memory leak detector

#!/bin/bash PROGRAM="$1" if [ -z "$PROGRAM" ]; then echo "Usage: $0 " exit 1 fi echo "=== Memory Allocation Analysis ===" ltrace -c -e malloc,free,calloc,realloc "$PROGRAM" 2>&1 | \ awk '/malloc|calloc/ {alloc+=$4} /free/ {freed+=$4} END {print "Allocated:", alloc, "Freed:", freed, "Difference:", alloc-freed}'

Automated memory leak detection script

Function call profiler

#!/bin/bash PROGRAM="$1" OUTPUT="profile_$(date +%Y%m%d_%H%M%S).log" echo "Profiling $PROGRAM..." ltrace -c -T -o "$OUTPUT" "$PROGRAM" echo "Top 10 most called functions:" grep -v "^%" "$OUTPUT" | sort -k4 -nr | head -10 echo "Top 10 most time-consuming functions:" grep -v "^%" "$OUTPUT" | sort -k2 -nr | head -10

Automated function call profiling

Log Analysis

Parse ltrace output

# Extract function names ltrace ./program 2>&1 | grep -o '^[a-zA-Z_][a-zA-Z0-9_]*' | sort | uniq -c # Find memory allocations ltrace ./program 2>&1 | grep 'malloc\|calloc' | awk '{print $1, $2}' # Track return values ltrace ./program 2>&1 | grep '= ' | awk -F'= ' '{print $2}' | sort | uniq -c

Parse and analyze ltrace output

Generate reports

#!/bin/bash LOGFILE="$1" echo "=== ltrace Analysis Report ===" echo "Total function calls: $(grep -c '^[a-zA-Z]' "$LOGFILE")" echo "Unique functions: $(grep -o '^[a-zA-Z_][a-zA-Z0-9_]*' "$LOGFILE" | sort -u | wc -l)" echo "Memory allocations: $(grep -c 'malloc\|calloc' "$LOGFILE")" echo "Memory deallocations: $(grep -c 'free' "$LOGFILE")" echo echo "Most called functions:" grep -o '^[a-zA-Z_][a-zA-Z0-9_]*' "$LOGFILE" | sort | uniq -c | sort -nr | head -5

Generate comprehensive analysis reports

Best Practices

ltrace Best Practices
  • Start Specific - Use filters to focus on relevant functions
  • Combine Tools - Use with strace, gdb, and valgrind for comprehensive analysis
  • Save Output - Always save traces to files for later analysis
  • Use Summary Mode - Use -c for overview before detailed tracing
  • Consider Performance - Be aware of tracing overhead on production systems
  • Filter Noise - Exclude verbose functions that aren't relevant

See also