Skip to content

Instantly share code, notes, and snippets.

@pablogsal
Last active January 17, 2023 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablogsal/0f955279819fb113d40d7dc26caba7d4 to your computer and use it in GitHub Desktop.
Save pablogsal/0f955279819fb113d40d7dc26caba7d4 to your computer and use it in GitHub Desktop.
#include <elfutils/libdwfl.h>
#include <elfutils/libdw.h>
#include <sys/ptrace.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/user.h>
#include <syscall.h>
#include <cstring>
static char *debuginfo_path = NULL;
static const Dwfl_Callbacks proc_callbacks =
{
.find_elf = dwfl_linux_proc_find_elf,
.find_debuginfo = dwfl_standard_find_debuginfo,
.debuginfo_path = &debuginfo_path,
};
int main(int argc, char **argv) {
if (argc < 2) {
printf("Usage: %s pid\n", argv[0]);
return 1;
}
pid_t pid = atoi(argv[1]);
Dwfl *dwfl = dwfl_begin(&proc_callbacks);
if (!dwfl) {
printf("dwfl_begin failed\n");
return 1;
}
if (ptrace(PTRACE_ATTACH, pid, NULL, NULL) < 0) {
printf("ptrace attach failed\n");
return 1;
}
waitpid(pid, NULL, 0);
dwfl_linux_proc_report(dwfl, pid);
if (dwfl_linux_proc_attach(dwfl, pid, true) != 0) {
printf("dwfl_linux_proc_attach failed\n");
return 1;
}
Dwarf_Addr pc;
Dwarf_Addr bias;
Dwarf_Addr prev_pc = 0;
Dwarf_Addr prev_bias = 0;
const char *prev_name = NULL;
struct user_regs_struct regs;
while (true) {
ptrace(PTRACE_SINGLESTEP, pid, NULL, NULL);
waitpid(pid, NULL, 0);
if (ptrace(PTRACE_GETREGS, pid, NULL, &regs) < 0) {
printf("ptrace getregs failed\n");
continue;
}
pc = regs.rip;
Dwfl_Module *mod = dwfl_addrmodule(dwfl, pc);
if (!mod) {
printf("dwfl_addrmodule failed\n");
continue;
}
GElf_Sym sym;
const char *name = dwfl_module_addrsym(mod, pc, &sym, NULL);
if (name && (pc != prev_pc) && (!prev_name || strcmp(prev_name, name) != 0 )) {
printf("Symbol: ");
printf("%s\n", name);
prev_pc = pc;
prev_name = name;
}
}
dwfl_end(dwfl);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment