Handle signals

This commit is contained in:
2025-03-10 14:10:49 +01:00
parent 00c6625a28
commit 17207421d3
2 changed files with 40 additions and 4 deletions

View File

@@ -8,7 +8,7 @@ DEPS=$(patsubst %.c,%.d,$(SRCS))
all: debugus test all: debugus test
test: test.o test: test.o
$(CC) -o $@ $^ $(CC) -gdwarf -o $@ $^
debugus: $(OBJS) ./mujs/build/debug/libmujs.o debugus: $(OBJS) ./mujs/build/debug/libmujs.o
$(CC) -o $@ $^ $(LDFLAGS) $(CC) -o $@ $^ $(LDFLAGS)

View File

@@ -1,3 +1,4 @@
#define _XOPEN_SOURCE 600
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <stddef.h> #include <stddef.h>
@@ -9,6 +10,7 @@
#include <errno.h> #include <errno.h>
#include <libelf.h> #include <libelf.h>
#include <gelf.h> #include <gelf.h>
#include <signal.h>
#include <sys/types.h> #include <sys/types.h>
#include <sys/wait.h> #include <sys/wait.h>
#include <sys/ptrace.h> #include <sys/ptrace.h>
@@ -164,10 +166,46 @@ typedef struct {
HashTable js_descs; HashTable js_descs;
} Dbg; } Dbg;
siginfo_t dbg_get_siginfo(Dbg *dbg)
{
siginfo_t i;
ptrace(PTRACE_GETSIGINFO, dbg->pid, NULL, &i);
return i;
}
void dbg_handle_sigsegv(Dbg *dbg, siginfo_t info)
{
unused(dbg);
LOG_ERR("Caught a segfault %d. SKILL ISSUE BRO\n", info.si_code);
}
void dbg_handle_sigtrap(Dbg *dbg, siginfo_t info)
{
void dbg_set_rip(Dbg *dbg, uint64_t v);
uint64_t dbg_get_rip(Dbg *dbg);
switch (info.si_code) {
case SI_KERNEL:
case TRAP_BRKPT:
dbg_set_rip(dbg, dbg_get_rip(dbg) - 1);
LOG_INF("Hit breakpoint at 0x%"PRIxPTR"\n", dbg_get_rip(dbg));
return;
case TRAP_TRACE:
return;
}
}
void dbg_wait(Dbg *dbg) void dbg_wait(Dbg *dbg)
{ {
int status, options = 0; int status, options = 0;
waitpid(dbg->pid, &status, options); waitpid(dbg->pid, &status, options);
siginfo_t info = dbg_get_siginfo(dbg);
switch (info.si_signo) {
case SIGTRAP: dbg_handle_sigtrap(dbg, info); break;
case SIGSEGV: dbg_handle_sigsegv(dbg, info); break;
default: LOG_INF("Signal %d\n!!", info.si_signo); break;
}
} }
// Memory // Memory
@@ -238,13 +276,11 @@ void dbg_set_rip(Dbg *dbg, uint64_t v)
void dbg_step_brk(Dbg *dbg) void dbg_step_brk(Dbg *dbg)
{ {
uint64_t loc = dbg_get_rip(dbg) - 1; uint64_t loc = dbg_get_rip(dbg);
char key[20]; char key[20];
snprintf(key, sizeof(key), "0x%"PRIxPTR, (uintptr_t)loc); snprintf(key, sizeof(key), "0x%"PRIxPTR, (uintptr_t)loc);
Brk *brk = hashtable_get(&dbg->brks, key); Brk *brk = hashtable_get(&dbg->brks, key);
if ((brk != NULL && brk->enabled)) { if ((brk != NULL && brk->enabled)) {
uint64_t prev_instr = loc;
dbg_set_rip(dbg, prev_instr);
brk_disable(brk); brk_disable(brk);
ptrace(PTRACE_SINGLESTEP, brk->pid, NULL, NULL); ptrace(PTRACE_SINGLESTEP, brk->pid, NULL, NULL);
dbg_wait(dbg); dbg_wait(dbg);