Monday, May 25, 2015

How do I start with 'strace'


Here in this post you gonna find a few tips about 'How do I start with strace' I've just gather some basics ideas/information.

So, First of all find the list of Linux system calls, "man 2 syscalls" or sites like (http://syscalls.kernelgrok.com/)
 

manpage way:
Read the manual page of a system call to learn the calling convention and expected behaviour and returns, "man 2 open" or "man 3p open".
You can search manual page names and descriptions with "man -k" and "man -k open" for example.

Write a basic C program to exercise:


# vi /tmp/demo-strace-open.c
================================================
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char *argv[]) {
    int fd = open("/etc/hosts", O_RDONLY);

    if (fd < 0)
        /* see RETURN VALUE in "man 2 open" to understand why and when fd will be negative */
        /* bonus points if you can make this break and print an error why it broke, see man errno */
        return 1;

    close (fd);
    return 0;
}

================================================

Compile your program and run through to the strace:


# cd /tmp

# gcc -o demo-strace-open demo-strace-open.c
# strace -fvttTo strace.log -s 1024 ./demo-strace-open

 
Read strace.log There will be a lot of stuff at the start as the program sets up to run.
For a simple thing like this, start at the end of the file and work your way up. Look for where your program starts.

For the above code example, these are the lines you're interested in:

17153 19:45:46.866711 open("/etc/hosts", O_RDONLY) = 3 <0.000009>
17153 19:45:46.866735 close(3)          = 0 <0.000007>

 

If you compile with debugging symbols (gcc -g) you can also load the program into gdb, add a breakpoint at main, and use "step" to step through each line of code.
For example, compare the strace of "/bin/ls" and "ls -l". To look at some basic socket calls you could use "nc" (netcat).

References:

- http://jvns.ca/blog/categories/strace/
- http://syscalls.kernelgrok.com/

No comments:

Post a Comment