aboutsummaryrefslogtreecommitdiffstats
path: root/save_backtrace.c
blob: e366abfbab1792e990273df29b5ac310a73c0449 (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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* See LICENSE file for copyright and license details. */
#include "internal.h"

#define UNW_LOCAL_ONLY
#include <libunwind.h>


struct partial {
	uintptr_t rips[8];
	struct partial *next;
};


int
liberror_save_backtrace(struct liberror_error *error)
{
	struct liberror_backtrace *backtrace = NULL;
	unw_word_t rip;
	unw_cursor_t cursor;
	unw_context_t context;
	size_t i = 0;
	struct partial *current, head;
	int saved_errno = errno;
	int ret = -1;

	if (unw_getcontext(&context))
		goto out;
	if (unw_init_local(&cursor, &context))
		goto out;

	current = &head;

	for (; unw_step(&cursor) > 0; i++) {
		if (!(i & 7))
			current = current->next = alloca(sizeof(*current));
		if (unw_get_reg(&cursor, UNW_REG_IP, &rip))
			goto out;
		current->rips[i & 7] = (uintptr_t)rip;
	}

	backtrace = malloc(offsetof(struct liberror_backtrace, rips) + i * sizeof(*backtrace->rips));
	if (!backtrace)
		goto out;
	backtrace->refcount = 1;

	backtrace->n = i;
	current = &head;
	for (i = 0; i < backtrace->n; i++) {
		if (!(i & 7))
			current = current->next;
		backtrace->rips[i] = current->rips[i & 7];
	}

	ret = 0;
out:
	if (error->backtrace && !--error->backtrace->refcount)
		free(error->backtrace);
	error->backtrace = backtrace;
	errno = saved_errno;
	return ret;
}