summaryrefslogtreecommitdiff
path: root/src/arch/amd64/backtrace.c
blob: c882fa0e6dc711ab5df0bb4c3a6b38b4e3ed94a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <backtrace.h>
#include <lib.h>
#include "serial.h"

struct stackframe {
	struct stackframe *rbp;
	void *rip;
};

size_t backtrace(void **dst, size_t len) {
	struct stackframe *rbp;
	__asm__ volatile ("mov %%rbp, %0" : "=r"(rbp));
	return backtrace_ex(dst, len, rbp->rip, rbp->rbp);
}

size_t backtrace_ex(void **dst, size_t len, void *ip, void *bp) {
	struct stackframe *frame = bp;
	__asm__ volatile ("mov %%rbp, %0" : "=r"(frame));
	if(len > 0) {
		dst[0] = ip;
	}
	size_t i;
	for(i = 1; frame && i < len; i++) {
		dst[i] = frame->rip;
		frame = frame->rbp;
	}
	return i;
}

void log_backtrace() {
	struct stackframe *rbp;
	__asm__ volatile ("mov %%rbp, %0" : "=r"(rbp));
	log_backtrace_ex(rbp->rip, rbp->rbp);
}


void log_backtrace_ex(void *ip, void *bp) {
	struct stackframe *frame = bp;
	char buf[20];
	serial_out_str("Stack trace:\n");
	ultoa((size_t)ip, buf, 16);
	serial_out_str("  0x");
	serial_out_str(buf);
	serial_out_str("\n");
	while(frame) {
		ultoa((size_t)frame->rip, buf, 16);
		serial_out_str("  0x");
		serial_out_str(buf);
		serial_out_str("\n");
		frame = frame->rbp;
	}

}