Skip to content

Instantly share code, notes, and snippets.

@inaz2
Last active September 25, 2016 23:55
Show Gist options
  • Save inaz2/be8ac037301ccce9311dc36e5a57ba79 to your computer and use it in GitHub Desktop.
Save inaz2/be8ac037301ccce9311dc36e5a57ba79 to your computer and use it in GitHub Desktop.
basic usage of ptrace(2)
$ gcc itrace.c -o itrace
$ ./itrace /bin/ls | head
7f86ae81d2d0
7f86ae81d2d3
7f86ae820a70
7f86ae820a71
7f86ae820a74
7f86ae820a76
7f86ae820a78
7f86ae820a7a
7f86ae820a7c
7f86ae820a7d
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ptrace.h>
#include <sys/user.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
pid_t pid;
int status;
struct user_regs_struct regs;
if (argc < 2) {
fprintf(stderr, "Usage: %s PROG [ARGS]\n", argv[0]);
exit(1);
}
pid = fork();
if (pid == -1) {
fprintf(stderr, "fork failed\n");
exit(1);
} else if (pid == 0) {
ptrace(PTRACE_TRACEME, 0, NULL, NULL);
execvp(argv[1], argv+1);
perror(argv[0]);
exit(1);
} else {
while (1) {
waitpid(pid, &status, 0);
if (WIFEXITED(status) || WIFSIGNALED(status)) {
break;
}
ptrace(PTRACE_GETREGS, pid, NULL, &regs);
printf("%llx\n", regs.rip);
ptrace(PTRACE_SINGLESTEP, pid, NULL, NULL);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment