Print source on breakpoint hit

This commit is contained in:
kamkow1
2025-03-12 20:31:27 +01:00
parent 19d6185ffb
commit 14b5368e7c

View File

@@ -9,6 +9,7 @@
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
@@ -22,6 +23,27 @@
#include "da.h"
#include "libelfin_wrap.h"
// They took my usleep() away >;( fuck u POSIX
int msleep(long msec)
{
struct timespec ts;
int res;
if (msec < 0) {
errno = EINVAL;
return -1;
}
ts.tv_sec = msec/1000;
ts.tv_nsec = (msec%1000) * 1000000;
do {
res = nanosleep(&ts, &ts);
} while(res && errno == EINTR);
return res;
}
#define LOG_ERR(fmt, ...) fprintf(stderr, "Error: " fmt, ##__VA_ARGS__)
#define LOG_INF(fmt, ...) fprintf(stdout, "Info: " fmt, ##__VA_ARGS__)
@@ -197,6 +219,46 @@ void dbg_handle_sigsegv(Dbg *dbg, siginfo_t info)
}
}
void print_source(const char *file, size_t line)
{
FILE *src = fopen(file, "r");
if (src == NULL) {
LOG_ERR("No source file found\n");
return;
}
fseek(src, 0L, SEEK_END);
long sz = ftell(src);
rewind(src);
char *srcbuf = malloc(sz+1);
fread(srcbuf, sz, 1, src);
srcbuf[sz] = '\0';
char *p = srcbuf;
size_t i = 0;
while (p) {
char *next = strchr(p, '\n');
if (next) {
*next = '\0';
}
if (i == line) {
LOG_INF("Source:\n");
printf("%6zu %s\n", line, p);
}
if (next) {
*next = '\n';
}
p = next ? (next + 1) : NULL;
i++;
}
free(srcbuf);
fclose(src);
}
void dbg_handle_sigtrap(Dbg *dbg, siginfo_t info)
{
void dbg_set_rip(Dbg *dbg, uint64_t v);
@@ -211,6 +273,7 @@ void dbg_handle_sigtrap(Dbg *dbg, siginfo_t info)
ai = libelfin_wrap_info_from_rip(dbg->plibelfin, dbg_get_rip(dbg) - (uint64_t)dbg->program_load_offset);
if (ai != NULL) {
LOG_INF("Hit breakpoint at 0x%"PRIxPTR", %s:%zu\n", dbg_get_rip(dbg), ai->file, (size_t)ai->line);
print_source(ai->file, (size_t)ai->line);
libelfin_wrap_free_info(ai);
} else {
LOG_INF("Hit breakpoint at 0x%"PRIxPTR"\n", dbg_get_rip(dbg));
@@ -593,6 +656,10 @@ void dbg_init_js(Dbg *dbg)
void dbg_init_load_offset(Dbg *dbg)
{
msleep(500); // We need to sleep for a bit, because we need to ensure that our debuggee
// program has already been loaded into memory. This is technically a bad
// practice since we're sleeping for 500ms and praying that it's enough
// time to ensure that debuggee has been loaded, but if it works, it works.
procmaps_iterator maps_iter = {0};
procmaps_error_t parser_err = PROCMAPS_SUCCESS;