Wednesday, February 24, 2010

Strace

Strace

strace is a tool for tracing system calls and signals. It intercepts and records the system calls made by a running process. strace can print a record of each system call, its arguments, and its return value. You can use strace on programs for which you do not have the source since using strace does not require recompilation. It is often useful in instances where a program freezes or otherwise fails to work and offers few clues as to the problem. It is also a great for instructional purposes.

Basics

It is easiest to explain with an example. The simplest example is perhaps
bash$ strace -o strace-echo-output.txt echo "Hello there"
Hello World
bash$ 
This example traced the execution of echo "Hello there", and printed the resulting trace to strace-echo-output.txt. As you can see, the program runs normally, the only difference is that it runs a little slower under strace and at the end you have a trace file. Trace files tend to be fairly large. Even for this simple example,
strace-echo-output.txt was 48 lines long for me. The file contains lines such as

open("/opt/gnome2/lib/libc.so.6", O_RDONLY) = -1 ENOENT (No such file or directory)
stat64("/opt/gnome2/lib", {st_mode=S_IFDIR|0755, st_size=20480, ...}) = 0
open("/etc/ld.so.cache", O_RDONLY)      = 3
fstat64(3, {st_mode=S_IFREG|0644, st_size=65928, ...}) = 0
old_mmap(NULL, 65928, PROT_READ, MAP_PRIVATE, 3, 0) = 0xbf596000
close(3)                                = 0
open("/lib/tls/libc.so.6", O_RDONLY)    = 3
read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0`ht\000"..., 512) = 512
 

That may look a little intimidating at first, but it is not so scary once you learn the basic format and realize that these files are usually meant to be searched, not read. Each line starts with a system call name, is followed by its arguments in parenthesis and then has the return value at the end of the line. Errors (which typically have a return value of -1) have the symbolic error name (such as ENOENT in the first line in the example above) as well as a more informative error string appended.

 Thanks to :
http://people.gnome.org/~newren/tutorials/developing-with-gnome/html/ch03s02.html

No comments:

Post a Comment