summaryrefslogtreecommitdiff
path: root/libgcompat/backtrace.c
blob: 2ceb334e81a7a31a6a7fda87697868e9a1cea397 (plain) (blame)
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
#include <dlfcn.h>
#include <stddef.h>
#include <stdlib.h>

#define _frame_level(addr_buf, curr, frame, size) \
	if(__builtin_frame_address(frame) != NULL && (curr = __builtin_return_address(frame)) > 0x1000 && frame <= size) addr_buf[frame] = curr; \
	else return size;

int backtrace(void **addr_buf, int size)
{
	void *curr;
	_frame_level(addr_buf, curr, 0, size)
	_frame_level(addr_buf, curr, 1, size)
	_frame_level(addr_buf, curr, 2, size)
	_frame_level(addr_buf, curr, 3, size)
	_frame_level(addr_buf, curr, 4, size)
	_frame_level(addr_buf, curr, 5, size)
	_frame_level(addr_buf, curr, 6, size)
	_frame_level(addr_buf, curr, 7, size)
	_frame_level(addr_buf, curr, 8, size)
	_frame_level(addr_buf, curr, 9, size)
	return 9;
}

char **backtrace_symbols(void * const *addr_buf, int size)
{
	char **result = calloc(sizeof(char *), size);
	if(result == NULL) return result;

	for(int next = 0; next < size; next++)
	{
		Dl_info info;
		int err = dladdr(addr_buf[next], &info);

		if(err != 0)
		{
			result[next] = "??:0";
		} else {
			result[next] = info.dli_sname;
		}
	}

	return result;
}