Home | History | Annotate | Line # | Download | only in libexecinfo
      1 /*	$NetBSD: backtrace.c,v 1.9 2025/01/23 12:08:12 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.9 2025/01/23 12:08:12 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 "symbol.h"
     49 #include "symtab.h"
     50 
     51 #ifdef __linux__
     52 #define SELF	"/proc/self/exe"
     53 #else
     54 #include <sys/sysctl.h>
     55 #define SELF	"/proc/curproc/file"
     56 #endif
     57 
     58 static int self_fd = -1;
     59 
     60 static int
     61 open_self(int flags)
     62 {
     63 	const char *pathname = SELF;
     64 #ifdef KERN_PROC_PATHNAME
     65 	static const int name[] = {
     66 		CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME,
     67 	};
     68 	char path[MAXPATHLEN];
     69 	size_t len;
     70 
     71 	len = sizeof(path);
     72 	if (sysctl(name, __arraycount(name), path, &len, NULL, 0) != -1)
     73 		pathname = path;
     74 #endif
     75 	return open(pathname, flags);
     76 }
     77 
     78 int
     79 backtrace_sandbox_init(void)
     80 {
     81 
     82 	if (self_fd == -1)
     83 		self_fd = open_self(O_RDONLY);
     84 	return self_fd >= 0 ? 0 : -1;
     85 }
     86 
     87 void
     88 backtrace_sandbox_fini(void)
     89 {
     90 	assert(self_fd >= 0);
     91 
     92 	close(self_fd);
     93 	self_fd = -1;
     94 }
     95 
     96 static int __printflike(4, 5)
     97 rasprintf(char **buf, size_t *bufsiz, size_t offs, const char *fmt, ...)
     98 {
     99 	for (;;) {
    100 		size_t nbufsiz;
    101 		char *nbuf;
    102 
    103 		if (*buf && offs < *bufsiz) {
    104 			va_list ap;
    105 			int len;
    106 
    107 			va_start(ap, fmt);
    108 			len = vsnprintf(*buf + offs, *bufsiz - offs, fmt, ap);
    109 			va_end(ap);
    110 
    111 			if (len < 0 || (size_t)len + 1 < *bufsiz - offs)
    112 				return len;
    113 			nbufsiz = MAX(*bufsiz + 512, (size_t)len + 1);
    114 		} else
    115 			nbufsiz = MAX(offs, *bufsiz) + 512;
    116 
    117 		nbuf = realloc(*buf, nbufsiz);
    118 		if (nbuf == NULL)
    119 			return -1;
    120 		*buf = nbuf;
    121 		*bufsiz = nbufsiz;
    122 	}
    123 }
    124 
    125 /*
    126  * format specifiers:
    127  *	%a	= address
    128  *	%n	= symbol_name
    129  *	%d	= symbol_address - address
    130  *	%D	= if symbol_address == address "" else +%d
    131  *	%f	= filename
    132  */
    133 static ssize_t
    134 format_string(char **buf, size_t *bufsiz, size_t offs, const char *fmt,
    135     Dl_info *dli, const void *addr)
    136 {
    137 	const uintptr_t symaddr = SYMBOL_CANONICALIZE(dli->dli_saddr);
    138 	ptrdiff_t diff = (const char *)addr - (const char *)symaddr;
    139 	size_t o = offs;
    140 	int len;
    141 
    142 	for (; *fmt; fmt++) {
    143 		if (*fmt != '%')
    144 			goto printone;
    145 		switch (*++fmt) {
    146 		case 'a':
    147 			len = rasprintf(buf, bufsiz, o, "%p", addr);
    148 			break;
    149 		case 'n':
    150 			len = rasprintf(buf, bufsiz, o, "%s", dli->dli_sname);
    151 			break;
    152 		case 'D':
    153 			if (diff)
    154 				len = rasprintf(buf, bufsiz, o, "+0x%tx", diff);
    155 			else
    156 				len = 0;
    157 			break;
    158 		case 'd':
    159 			len = rasprintf(buf, bufsiz, o, "0x%tx", diff);
    160 			break;
    161 		case 'f':
    162 			len = rasprintf(buf, bufsiz, o, "%s", dli->dli_fname);
    163 			break;
    164 		default:
    165 		printone:
    166 			len = rasprintf(buf, bufsiz, o, "%c", *fmt);
    167 			break;
    168 		}
    169 		if (len == -1)
    170 			return -1;
    171 		o += len;
    172 	}
    173 	return o - offs;
    174 }
    175 
    176 static ssize_t
    177 format_address(symtab_t *st, char **buf, size_t *bufsiz, size_t offs,
    178     const char *fmt, const void *addr)
    179 {
    180 	Dl_info dli;
    181 
    182 	memset(&dli, 0, sizeof(dli));
    183 	(void)dladdr(addr, &dli);
    184 	if (st)
    185 		symtab_find(st, addr, &dli);
    186 
    187 	if (dli.dli_sname == NULL)
    188 		dli.dli_sname = "???";
    189 	if (dli.dli_fname == NULL)
    190 		dli.dli_fname = "???";
    191 	if (dli.dli_saddr == NULL)
    192 		dli.dli_saddr = (void *)(intptr_t)addr;
    193 
    194 	return format_string(buf, bufsiz, offs, fmt, &dli, addr);
    195 }
    196 
    197 char **
    198 backtrace_symbols_fmt(void *const *trace, size_t len, const char *fmt)
    199 {
    200 
    201 	static const size_t slen = sizeof(char *) + 64;	/* estimate */
    202 	char *ptr;
    203 	symtab_t *st;
    204 	int fd = self_fd;
    205 
    206 	if (fd != -1 || (fd = open_self(O_RDONLY)) != -1)
    207 		st = symtab_create(fd, -1, STT_FUNC);
    208 	else
    209 		st = NULL;
    210 
    211 	if ((ptr = calloc(len, slen)) == NULL)
    212 		goto out;
    213 
    214 	size_t psize = len * slen;
    215 	size_t offs = len * sizeof(char *);
    216 
    217 	/* We store only offsets in the first pass because of realloc */
    218 	for (size_t i = 0; i < len; i++) {
    219 		ssize_t x;
    220 		((char **)(void *)ptr)[i] = (void *)offs;
    221 		x = format_address(st, &ptr, &psize, offs, fmt, trace[i]);
    222 		if (x == -1) {
    223 			free(ptr);
    224 			ptr = NULL;
    225 			goto out;
    226 		}
    227 		offs += x;
    228 		ptr[offs++] = '\0';
    229 		assert(offs < psize);
    230 	}
    231 
    232 	/* Change offsets to pointers */
    233 	for (size_t j = 0; j < len; j++)
    234 		((char **)(void *)ptr)[j] += (intptr_t)ptr;
    235 
    236 out:
    237 	symtab_destroy(st);
    238 	if (fd != -1 && fd != self_fd)
    239 		(void)close(fd);
    240 
    241 	return (void *)ptr;
    242 }
    243 
    244 int
    245 backtrace_symbols_fd_fmt(void *const *trace, size_t len, int fd,
    246     const char *fmt)
    247 {
    248 	char **s = backtrace_symbols_fmt(trace, len, fmt);
    249 	if (s == NULL)
    250 		return -1;
    251 	for (size_t i = 0; i < len; i++)
    252 		if (dprintf(fd, "%s\n", s[i]) < 0)
    253 			break;
    254 	free(s);
    255 	return 0;
    256 }
    257 
    258 static const char fmt[] = "%a <%n%D> at %f";
    259 
    260 char **
    261 backtrace_symbols(void *const *trace, size_t len)
    262 {
    263 	return backtrace_symbols_fmt(trace, len, fmt);
    264 }
    265 
    266 int
    267 backtrace_symbols_fd(void *const *trace, size_t len, int fd)
    268 {
    269 	return backtrace_symbols_fd_fmt(trace, len, fd, fmt);
    270 }
    271