1/*	$NetBSD: backtrace.c,v 1.3 2013/08/29 14:58:56 christos Exp $	*/
2
3/*-
4 * Copyright (c) 2012 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Christos Zoulas.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31#include <sys/cdefs.h>
32__RCSID("$NetBSD: backtrace.c,v 1.3 2013/08/29 14:58:56 christos Exp $");
33
34#include <sys/param.h>
35#include <assert.h>
36#include <stdio.h>
37#include <string.h>
38#include <stdlib.h>
39#include <stdarg.h>
40#include <stdint.h>
41#include <stddef.h>
42#include <unistd.h>
43#include <fcntl.h>
44#include <dlfcn.h>
45#include <elf.h>
46
47#include "execinfo.h"
48#include "symtab.h"
49
50#ifdef __linux__
51#define SELF	"/proc/self/exe"
52#else
53#include <sys/sysctl.h>
54#define SELF	"/proc/curproc/file"
55#endif
56
57static int
58open_self(int flags)
59{
60	const char *pathname = SELF;
61#ifdef KERN_PROC_PATHNAME
62	static const int name[] = {
63		CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1,
64	};
65	char path[MAXPATHLEN];
66	size_t len;
67
68	len = sizeof(path);
69	if (sysctl(name, 4, path, &len, NULL, 0) != -1)
70		pathname = path;
71#endif
72	return open(pathname, flags);
73}
74
75
76static int __printflike(4, 5)
77rasprintf(char **buf, size_t *bufsiz, size_t offs, const char *fmt, ...)
78{
79	for (;;) {
80		size_t nbufsiz;
81		char *nbuf;
82
83		if (*buf && offs < *bufsiz) {
84			va_list ap;
85			int len;
86
87			va_start(ap, fmt);
88			len = vsnprintf(*buf + offs, *bufsiz - offs, fmt, ap);
89			va_end(ap);
90
91			if (len < 0 || (size_t)len + 1 < *bufsiz - offs)
92				return len;
93			nbufsiz = MAX(*bufsiz + 512, (size_t)len + 1);
94		} else
95			nbufsiz = MAX(offs, *bufsiz) + 512;
96
97		nbuf = realloc(*buf, nbufsiz);
98		if (nbuf == NULL)
99			return -1;
100		*buf = nbuf;
101		*bufsiz = nbufsiz;
102	}
103}
104
105/*
106 * format specifiers:
107 *	%a	= address
108 *	%n	= symbol_name
109 *	%d	= symbol_address - address
110 *	%D	= if symbol_address == address "" else +%d
111 *	%f	= filename
112 */
113static ssize_t
114format_string(char **buf, size_t *bufsiz, size_t offs, const char *fmt,
115    Dl_info *dli, const void *addr)
116{
117	ptrdiff_t diff = (const char *)addr - (const char *)dli->dli_saddr;
118	size_t o = offs;
119	int len;
120
121	for (; *fmt; fmt++) {
122		if (*fmt != '%')
123			goto printone;
124		switch (*++fmt) {
125		case 'a':
126			len = rasprintf(buf, bufsiz, o, "%p", addr);
127			break;
128		case 'n':
129			len = rasprintf(buf, bufsiz, o, "%s", dli->dli_sname);
130			break;
131		case 'D':
132			if (diff)
133				len = rasprintf(buf, bufsiz, o, "+0x%tx", diff);
134			else
135				len = 0;
136			break;
137		case 'd':
138			len = rasprintf(buf, bufsiz, o, "0x%tx", diff);
139			break;
140		case 'f':
141			len = rasprintf(buf, bufsiz, o, "%s", dli->dli_fname);
142			break;
143		default:
144		printone:
145			len = rasprintf(buf, bufsiz, o, "%c", *fmt);
146			break;
147		}
148		if (len == -1)
149			return -1;
150		o += len;
151	}
152	return o - offs;
153}
154
155static ssize_t
156format_address(symtab_t *st, char **buf, size_t *bufsiz, size_t offs,
157    const char *fmt, const void *addr)
158{
159	Dl_info dli;
160
161	memset(&dli, 0, sizeof(dli));
162	(void)dladdr(addr, &dli);
163	if (st)
164		symtab_find(st, addr, &dli);
165
166	if (dli.dli_sname == NULL)
167		dli.dli_sname = "???";
168	if (dli.dli_fname == NULL)
169		dli.dli_fname = "???";
170	if (dli.dli_saddr == NULL)
171		dli.dli_saddr = (void *)(intptr_t)addr;
172
173	return format_string(buf, bufsiz, offs, fmt, &dli, addr);
174}
175
176char **
177backtrace_symbols_fmt(void *const *trace, size_t len, const char *fmt)
178{
179
180	static const size_t slen = sizeof(char *) + 64;	/* estimate */
181	char *ptr;
182	symtab_t *st;
183	int fd;
184
185	if ((fd = open_self(O_RDONLY)) != -1)
186		st = symtab_create(fd, -1, STT_FUNC);
187	else
188		st = NULL;
189
190	if ((ptr = calloc(len, slen)) == NULL)
191		goto out;
192
193	size_t psize = len * slen;
194	size_t offs = len * sizeof(char *);
195
196	/* We store only offsets in the first pass because of realloc */
197	for (size_t i = 0; i < len; i++) {
198		ssize_t x;
199		((char **)(void *)ptr)[i] = (void *)offs;
200		x = format_address(st, &ptr, &psize, offs, fmt, trace[i]);
201		if (x == -1) {
202			free(ptr);
203			ptr = NULL;
204			goto out;
205		}
206		offs += x;
207		ptr[offs++] = '\0';
208		assert(offs < psize);
209	}
210
211	/* Change offsets to pointers */
212	for (size_t j = 0; j < len; j++)
213		((char **)(void *)ptr)[j] += (intptr_t)ptr;
214
215out:
216	symtab_destroy(st);
217	if (fd != -1)
218		(void)close(fd);
219
220	return (void *)ptr;
221}
222
223int
224backtrace_symbols_fd_fmt(void *const *trace, size_t len, int fd,
225    const char *fmt)
226{
227	char **s = backtrace_symbols_fmt(trace, len, fmt);
228	if (s == NULL)
229		return -1;
230	for (size_t i = 0; i < len; i++)
231		if (dprintf(fd, "%s\n", s[i]) < 0)
232			break;
233	free(s);
234	return 0;
235}
236
237static const char fmt[] = "%a <%n%D> at %f";
238
239char **
240backtrace_symbols(void *const *trace, size_t len)
241{
242	return backtrace_symbols_fmt(trace, len, fmt);
243}
244
245int
246backtrace_symbols_fd(void *const *trace, size_t len, int fd)
247{
248	return backtrace_symbols_fd_fmt(trace, len, fd, fmt);
249}
250