After discovering strace, I've started to wonder, how does strace work ?. Let's dig into it !
I had no idea how strace worked, and I'm way too lazy to dig into its source code !
If only I had a tool to monitor strace
without looking at its source code ...
Wait... Can strace track its own syscalls ?
YES IT CAN !
The things is : strace has to strace some process to run correctly, let's write the simplest one that doesn't use much syscall, to keep a "clean" strace output :
int main(void){
// This useless infinite loop should keep this program busy
while(1) {
continue;
}
return 0;
}
Then run it:
$ gcc busy.c -o busy
$ ./busy
As expected, it loops forever. Now let's strace it !
$ strace ./busy
This output a bunch of lines that i don't understand :
execve("./busy", ["./busy"], [/* 26 vars */]) = 0 brk(0)
= 0x1cea000 access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory) mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f74e9b0c000 access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory) open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3 fstat(3, [...]
But, now we know what stracing busy
outputs, let's compare that with a strace
tracing output :
$ strace strace ./busy
[...] ptrace(PTRACE_SETOPTIONS, 5275, 0, PTRACE_O_TRACESYSGOOD|PTRACE_O_TRACEEXEC) = 0 ptrace(PTRACE_SYSCALL, 5275, 0, SIG_0) = 0 [...]
Sostrace
uses a syscall called ptrace ?! let's RTFM:
$ man ptrace
The ptrace() system call provides a means by which one process (the "tracer") may observe and control the execution of another process (the "tracee"), and examine and change the tracee's memory and registers.
BINGO !
Now, we know how strace
manages to log each syscall used by a program, it simply ask the kernel to do it !
How does strace
trace programs ? It ask the kernel to do it.
I might seem obvious for you, but not for me, I guess I'm still a newbie... :)
Now that I know that, I would like to play with the ptrace syscall myself.
To be continued...