1 /*
2   A hacky replacement for backtrace_symbols in glibc
3 
4   backtrace_symbols in glibc looks up symbols using dladdr which is limited in
5   the symbols that it sees. libbacktracesymbols opens the executable and shared
6   libraries using libbfd and will look up backtrace information using the symbol
7   table and the dwarf line information.
8 
9   It may make more sense for this program to use libelf instead of libbfd.
10   However, I have not investigated that yet.
11 
12   Derived from addr2line.c from GNU Binutils by Jeff Muizelaar
13 
14   Copyright 2007 Jeff Muizelaar
15 */
16 
17 /* addr2line.c -- convert addresses to line number and function name
18    Copyright 1997, 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
19    Contributed by Ulrich Lauther <Ulrich.Lauther@mchp.siemens.de>
20 
21    This file was part of GNU Binutils.
22 
23    This program is free software; you can redistribute it and/or modify
24    it under the terms of the GNU General Public License as published by
25    the Free Software Foundation; either version 2, or (at your option)
26    any later version.
27 
28    This program is distributed in the hope that it will be useful,
29    but WITHOUT ANY WARRANTY; without even the implied warranty of
30    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
31    GNU General Public License for more details.
32 
33    You should have received a copy of the GNU General Public License
34    along with this program; if not, write to the Free Software
35    Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.  */
36 
37 #define fatal(a, b) exit(1)
38 #define bfd_fatal(a) exit(1)
39 #define bfd_nonfatal(a) exit(1)
40 #define list_matching_formats(a) exit(1)
41 
42 /* 2 characters for each byte, plus 1 each for 0, x, and NULL */
43 #define PTRSTR_LEN (sizeof(void *) * 2 + 3)
44 #define true 1
45 #define false 0
46 
47 #define _GNU_SOURCE
48 #include <string.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <execinfo.h>
52 #include <bfd.h>
53 #include <libiberty.h>
54 #include <dlfcn.h>
55 #include <link.h>
56 #if 0
57 
58 void (*dbfd_init)(void);
59 bfd_vma (*dbfd_scan_vma)(const char *string, const char **end, int base);
60 bfd* (*dbfd_openr)(const char *filename, const char *target);
61 bfd_boolean (*dbfd_check_format)(bfd *abfd, bfd_format format);
62 bfd_boolean (*dbfd_check_format_matches)(bfd *abfd, bfd_format format, char ***matching);
63 bfd_boolean (*dbfd_close)(bfd *abfd);
64 bfd_boolean (*dbfd_map_over_sections)(bfd *abfd, void (*func)(bfd *abfd, asection *sect, void *obj),
65 		void *obj);
66 #define bfd_init dbfd_init
67 
68 static void load_funcs(void)
69 {
70 	void * handle = dlopen("libbfd.so", RTLD_NOW);
71 	dbfd_init = dlsym(handle, "bfd_init");
72 	dbfd_scan_vma = dlsym(handle, "bfd_scan_vma");
73 	dbfd_openr = dlsym(handle, "bfd_openr");
74 	dbfd_check_format = dlsym(handle, "bfd_check_format");
75 	dbfd_check_format_matches = dlsym(handle, "bfd_check_format_matches");
76 	dbfd_close = dlsym(handle, "bfd_close");
77 	dbfd_map_over_sections = dlsym(handle, "bfd_map_over_sections");
78 }
79 
80 #endif
81 
82 
83 static asymbol **syms;		/* Symbol table.  */
84 
85 /* 150 isn't special; it's just an arbitrary non-ASCII char value.  */
86 #define OPTION_DEMANGLER	(150)
87 
88 static void slurp_symtab(bfd * abfd);
89 static void find_address_in_section(bfd *abfd, asection *section, void *data);
90 
91 /* Read in the symbol table.  */
92 
slurp_symtab(bfd * abfd)93 static void slurp_symtab(bfd * abfd)
94 {
95 	long symcount;
96 	unsigned int size;
97 
98 	if ((bfd_get_file_flags(abfd) & HAS_SYMS) == 0)
99 		return;
100 
101 	symcount = bfd_read_minisymbols(abfd, false, (PTR) & syms, &size);
102 	if (symcount == 0)
103 		symcount = bfd_read_minisymbols(abfd, true /* dynamic */ ,
104 						(PTR) & syms, &size);
105 
106 	if (symcount < 0)
107 		bfd_fatal(bfd_get_filename(abfd));
108 }
109 
110 /* These global variables are used to pass information between
111    translate_addresses and find_address_in_section.  */
112 
113 static bfd_vma pc;
114 static const char *filename;
115 static const char *functionname;
116 static unsigned int line;
117 static int found;
118 
119 /* Look for an address in a section.  This is called via
120    bfd_map_over_sections.  */
121 
find_address_in_section(bfd * abfd,asection * section,void * data)122 static void find_address_in_section(bfd *abfd, asection *section, void *data __attribute__ ((__unused__)) )
123 {
124 	bfd_vma vma;
125 	bfd_size_type size;
126 
127 	if (found)
128 		return;
129 
130 	if ((bfd_get_section_flags(abfd, section) & SEC_ALLOC) == 0)
131 		return;
132 
133 	vma = bfd_get_section_vma(abfd, section);
134 	if (pc < vma)
135 		return;
136 
137 	size = bfd_section_size(abfd, section);
138 	if (pc >= vma + size)
139 		return;
140 
141 	found = bfd_find_nearest_line(abfd, section, syms, pc - vma,
142 				      &filename, &functionname, &line);
143 }
144 
145 /* Read hexadecimal addresses from stdin, translate into
146    file_name:line_number and optionally function name.  */
147 #if 0
148 static void translate_addresses(bfd * abfd, char (*addr)[PTRSTR_LEN], int naddr)
149 {
150 	while (naddr) {
151 		pc = bfd_scan_vma(addr[naddr-1], NULL, 16);
152 
153 		found = false;
154 		bfd_map_over_sections(abfd, find_address_in_section,
155 		(PTR) NULL);
156 
157 		if (!found) {
158 			printf("[%s] \?\?() \?\?:0\n",addr[naddr-1]);
159 		} else {
160 			const char *name;
161 
162 			name = functionname;
163 			if (name == NULL || *name == '\0')
164 				name = "??";
165 			if (filename != NULL) {
166 				char *h;
167 
168 				h = strrchr(filename, '/');
169 				if (h != NULL)
170 					filename = h + 1;
171 			}
172 
173 			printf("\t%s:%u\t", filename ? filename : "??",
174 			       line);
175 
176 			printf("%s()\n", name);
177 
178 		}
179 
180 		/* fflush() is essential for using this command as a server
181 		   child process that reads addresses from a pipe and responds
182 		   with line number information, processing one address at a
183 		   time.  */
184 		fflush(stdout);
185 		naddr--;
186 	}
187 }
188 #endif
189 
translate_addresses_buf(bfd * abfd,bfd_vma * addr,int naddr)190 static char** translate_addresses_buf(bfd * abfd, bfd_vma *addr, int naddr)
191 {
192 	int naddr_orig = naddr;
193 	char b;
194 	int total  = 0;
195 	enum { Count, Print } state;
196 	char *buf = &b;
197 	int len = 0;
198 	char **ret_buf = NULL;
199 	/* iterate over the formatting twice.
200 	 * the first time we count how much space we need
201 	 * the second time we do the actual printing */
202 	for (state=Count; state<=Print; state++) {
203 	if (state == Print) {
204 		ret_buf = malloc(total + sizeof(char*)*naddr);
205 		buf = (char*)(ret_buf + naddr);
206 		len = total;
207 	}
208 	while (naddr) {
209 		if (state == Print)
210 			ret_buf[naddr-1] = buf;
211 		pc = addr[naddr-1];
212 
213 		found = false;
214 		bfd_map_over_sections(abfd, find_address_in_section,
215 		(PTR) NULL);
216 
217 		if (!found) {
218 			total += snprintf(buf, len, "[0x%llx] \?\?() \?\?:0",(long long unsigned int) addr[naddr-1]) + 1;
219 		} else {
220 			const char *name;
221 
222 			name = functionname;
223 			if (name == NULL || *name == '\0')
224 				name = "??";
225 			if (filename != NULL) {
226 				char *h;
227 
228 				h = strrchr(filename, '/');
229 				if (h != NULL)
230 					filename = h + 1;
231 			}
232 			total += snprintf(buf, len, "%s:%u\t%s()", filename ? filename : "??",
233 			       line, name) + 1;
234 
235 		}
236 		if (state == Print) {
237 			/* set buf just past the end of string */
238 			buf = buf + total + 1;
239 		}
240 		naddr--;
241 	}
242 	naddr = naddr_orig;
243 	}
244 	return ret_buf;
245 }
246 /* Process a file.  */
247 
process_file(const char * file_name,bfd_vma * addr,int naddr)248 static char **process_file(const char *file_name, bfd_vma *addr, int naddr)
249 {
250 	bfd *abfd;
251 	char **matching;
252 	char **ret_buf;
253 
254 	abfd = bfd_openr(file_name, NULL);
255 
256 	if (abfd == NULL)
257 		bfd_fatal(file_name);
258 
259 	if (bfd_check_format(abfd, bfd_archive))
260 		fatal("%s: can not get addresses from archive", file_name);
261 
262 	if (!bfd_check_format_matches(abfd, bfd_object, &matching)) {
263 		bfd_nonfatal(bfd_get_filename(abfd));
264 		if (bfd_get_error() ==
265 		    bfd_error_file_ambiguously_recognized) {
266 			list_matching_formats(matching);
267 			free(matching);
268 		}
269 		xexit(1);
270 	}
271 
272 	slurp_symtab(abfd);
273 
274 	ret_buf = translate_addresses_buf(abfd, addr, naddr);
275 
276 	free (syms);
277 	syms = NULL;
278 
279 	bfd_close(abfd);
280 	return ret_buf;
281 }
282 
283 #define MAX_DEPTH 16
284 
285 struct file_match {
286 	const char *file;
287 	void *address;
288 	void *base;
289 	void *hdr;
290 };
291 
find_matching_file(struct dl_phdr_info * info,size_t size,void * data)292 static int find_matching_file(struct dl_phdr_info *info,
293 		size_t size, void *data)
294 {
295 	struct file_match *match = data;
296 	/* This code is modeled from Gfind_proc_info-lsb.c:callback() from libunwind */
297 	long n;
298 	const ElfW(Phdr) *phdr;
299 	ElfW(Addr) load_base = info->dlpi_addr;
300 	phdr = info->dlpi_phdr;
301 	for (n = info->dlpi_phnum; --n >= 0; phdr++) {
302 		if (phdr->p_type == PT_LOAD) {
303 			ElfW(Addr) vaddr = phdr->p_vaddr + load_base;
304 			if (match->address >= vaddr && match->address < vaddr + phdr->p_memsz) {
305 				/* we found a match */
306 				match->file = info->dlpi_name;
307 				match->base = info->dlpi_addr;
308 			}
309 		}
310 	}
311 	return 0;
312 }
313 
backtrace_symbols(void * const * buffer,int size)314 char **backtrace_symbols(void *const *buffer, int size)
315 {
316 	int stack_depth = size - 1;
317 	int x,y;
318 	/* discard calling function */
319 	int total = 0;
320 
321 	char ***locations;
322 	char **final;
323 	char *f_strings;
324 
325 	locations = malloc(sizeof(char**) * (stack_depth+1));
326 
327 	bfd_init();
328 	for(x=stack_depth, y=0; x>=0; x--, y++){
329 		struct file_match match = { .address = buffer[x] };
330 		char **ret_buf;
331 		bfd_vma addr;
332 		dl_iterate_phdr(find_matching_file, &match);
333 		addr = buffer[x] - match.base;
334 		if (match.file && strlen(match.file))
335 			ret_buf = process_file(match.file, &addr, 1);
336 		else
337 			ret_buf = process_file("/proc/self/exe", &addr, 1);
338 		locations[x] = ret_buf;
339 		total += strlen(ret_buf[0]) + 1;
340 	}
341 
342 	/* allocate the array of char* we are going to return and extra space for
343 	 * all of the strings */
344 	final = malloc(total + (stack_depth + 1) * sizeof(char*));
345 	/* get a pointer to the extra space */
346 	f_strings = (char*)(final + stack_depth + 1);
347 
348 	/* fill in all of strings and pointers */
349 	for(x=stack_depth; x>=0; x--){
350 		strcpy(f_strings, locations[x][0]);
351 		free(locations[x]);
352 		final[x] = f_strings;
353 		f_strings += strlen(f_strings) + 1;
354 	}
355 
356 	free(locations);
357 
358 	return final;
359 }
360 
361 void
backtrace_symbols_fd(void * const * buffer,int size,int fd)362 backtrace_symbols_fd(void *const *buffer, int size, int fd)
363 {
364         int j;
365         char **strings;
366 
367         strings = backtrace_symbols(buffer, size);
368         if (strings == NULL) {
369 		perror("backtrace_symbols");
370 		exit(EXIT_FAILURE);
371         }
372 
373         for (j = 0; j < size; j++)
374 		printf("%s\n", strings[j]);
375 
376         free(strings);
377 }
378