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