Files
sakurac/tools/profile/sampler.c
T

69 lines
2.1 KiB
C
Raw Permalink Normal View History

2026-10-26 10:14:11 -05:00
// Samples a program's instruction pointer and its chain of return addresses with
// ptrace, which needs no kernel profiling support.
//
// cc -O2 -o sampler sampler.c
// sampler OUT INTERVAL_US PROGRAM ARGS...
//
// Writes one line per sample to OUT: the instruction pointer, then each return
// address the `rbp` chain gives, in hex. The program's output is discarded.
#define _GNU_SOURCE
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ptrace.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char **argv) {
FILE *out = fopen(argv[1], "w");
long interval = atol(argv[2]);
pid_t pid = fork();
if (pid == 0) {
int null = open("/dev/null", O_WRONLY); dup2(null, 1);
ptrace(PTRACE_TRACEME, 0, 0, 0);
raise(SIGSTOP);
execv(argv[3], argv + 3);
_exit(127);
}
int status;
waitpid(pid, &status, 0);
ptrace(PTRACE_SETOPTIONS, pid, 0, PTRACE_O_EXITKILL);
ptrace(PTRACE_CONT, pid, 0, 0);
// Wait for the exec stop.
waitpid(pid, &status, 0);
ptrace(PTRACE_CONT, pid, 0, 0);
long samples = 0;
for (;;) {
struct timespec ts = { 0, interval * 1000 };
nanosleep(&ts, 0);
if (kill(pid, SIGSTOP) != 0) break;
if (waitpid(pid, &status, 0) < 0) break;
if (WIFEXITED(status) || WIFSIGNALED(status)) break;
int sig = WSTOPSIG(status);
if (sig != SIGSTOP) { ptrace(PTRACE_CONT, pid, 0, sig); continue; }
struct user_regs_struct r;
if (ptrace(PTRACE_GETREGS, pid, 0, &r) == 0) {
fprintf(out, "%llx", r.rip);
unsigned long bp = r.rbp;
for (int i = 0; i < 400 && bp; i++) {
errno = 0;
long ret = ptrace(PTRACE_PEEKDATA, pid, bp + 8, 0);
long next = ptrace(PTRACE_PEEKDATA, pid, bp, 0);
if (errno) break;
fprintf(out, " %lx", ret);
if ((unsigned long)next <= bp) break;
bp = next;
}
fputc('\n', out);
samples++;
}
ptrace(PTRACE_CONT, pid, 0, 0);
}
fclose(out);
fprintf(stderr, "%ld samples\n", samples);
return 0;
}