xref: /netbsd-src/external/gpl3/binutils.old/dist/binutils/addr2line.c (revision e992f068c547fd6e84b3f104dc2340adcc955732)
1 /* addr2line.c -- convert addresses to line number and function name
2    Copyright (C) 1997-2022 Free Software Foundation, Inc.
3    Contributed by Ulrich Lauther <Ulrich.Lauther@mchp.siemens.de>
4 
5    This file is part of GNU Binutils.
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3, or (at your option)
10    any later version.
11 
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, 51 Franklin Street - Fifth Floor, Boston,
20    MA 02110-1301, USA.  */
21 
22 
23 /* Derived from objdump.c and nm.c by Ulrich.Lauther@mchp.siemens.de
24 
25    Usage:
26    addr2line [options] addr addr ...
27    or
28    addr2line [options]
29 
30    both forms write results to stdout, the second form reads addresses
31    to be converted from stdin.  */
32 
33 #include "sysdep.h"
34 #include "bfd.h"
35 #include "getopt.h"
36 #include "libiberty.h"
37 #include "demangle.h"
38 #include "bucomm.h"
39 #include "elf-bfd.h"
40 #include "safe-ctype.h"
41 
42 static bool unwind_inlines;	/* -i, unwind inlined functions. */
43 static bool with_addresses;	/* -a, show addresses.  */
44 static bool with_functions;	/* -f, show function names.  */
45 static bool do_demangle;	/* -C, demangle names.  */
46 static bool pretty_print;	/* -p, print on one line.  */
47 static bool base_names;		/* -s, strip directory names.  */
48 
49 /* Flags passed to the name demangler.  */
50 static int demangle_flags = DMGL_PARAMS | DMGL_ANSI;
51 
52 static int naddr;		/* Number of addresses to process.  */
53 static char **addr;		/* Hex addresses to process.  */
54 
55 static long symcount;
56 static asymbol **syms;		/* Symbol table.  */
57 
58 static struct option long_options[] =
59 {
60   {"addresses", no_argument, NULL, 'a'},
61   {"basenames", no_argument, NULL, 's'},
62   {"demangle", optional_argument, NULL, 'C'},
63   {"exe", required_argument, NULL, 'e'},
64   {"functions", no_argument, NULL, 'f'},
65   {"inlines", no_argument, NULL, 'i'},
66   {"pretty-print", no_argument, NULL, 'p'},
67   {"recurse-limit", no_argument, NULL, 'R'},
68   {"recursion-limit", no_argument, NULL, 'R'},
69   {"no-recurse-limit", no_argument, NULL, 'r'},
70   {"no-recursion-limit", no_argument, NULL, 'r'},
71   {"section", required_argument, NULL, 'j'},
72   {"target", required_argument, NULL, 'b'},
73   {"help", no_argument, NULL, 'H'},
74   {"version", no_argument, NULL, 'V'},
75   {0, no_argument, 0, 0}
76 };
77 
78 static void usage (FILE *, int);
79 static void slurp_symtab (bfd *);
80 static void find_address_in_section (bfd *, asection *, void *);
81 static void find_offset_in_section (bfd *, asection *);
82 static void translate_addresses (bfd *, asection *);
83 
84 /* Print a usage message to STREAM and exit with STATUS.  */
85 
86 static void
usage(FILE * stream,int status)87 usage (FILE *stream, int status)
88 {
89   fprintf (stream, _("Usage: %s [option(s)] [addr(s)]\n"), program_name);
90   fprintf (stream, _(" Convert addresses into line number/file name pairs.\n"));
91   fprintf (stream, _(" If no addresses are specified on the command line, they will be read from stdin\n"));
92   fprintf (stream, _(" The options are:\n\
93   @<file>                Read options from <file>\n\
94   -a --addresses         Show addresses\n\
95   -b --target=<bfdname>  Set the binary file format\n\
96   -e --exe=<executable>  Set the input file name (default is a.out)\n\
97   -i --inlines           Unwind inlined functions\n\
98   -j --section=<name>    Read section-relative offsets instead of addresses\n\
99   -p --pretty-print      Make the output easier to read for humans\n\
100   -s --basenames         Strip directory names\n\
101   -f --functions         Show function names\n\
102   -C --demangle[=style]  Demangle function names\n\
103   -R --recurse-limit     Enable a limit on recursion whilst demangling.  [Default]\n\
104   -r --no-recurse-limit  Disable a limit on recursion whilst demangling\n\
105   -h --help              Display this information\n\
106   -v --version           Display the program's version\n\
107 \n"));
108 
109   list_supported_targets (program_name, stream);
110   if (REPORT_BUGS_TO[0] && status == 0)
111     fprintf (stream, _("Report bugs to %s\n"), REPORT_BUGS_TO);
112   exit (status);
113 }
114 
115 /* Read in the symbol table.  */
116 
117 static void
slurp_symtab(bfd * abfd)118 slurp_symtab (bfd *abfd)
119 {
120   long storage;
121   bool dynamic = false;
122 
123   if ((bfd_get_file_flags (abfd) & HAS_SYMS) == 0)
124     return;
125 
126   storage = bfd_get_symtab_upper_bound (abfd);
127   if (storage == 0)
128     {
129       storage = bfd_get_dynamic_symtab_upper_bound (abfd);
130       dynamic = true;
131     }
132   if (storage < 0)
133     bfd_fatal (bfd_get_filename (abfd));
134 
135   syms = (asymbol **) xmalloc (storage);
136   if (dynamic)
137     symcount = bfd_canonicalize_dynamic_symtab (abfd, syms);
138   else
139     symcount = bfd_canonicalize_symtab (abfd, syms);
140   if (symcount < 0)
141     bfd_fatal (bfd_get_filename (abfd));
142 
143   /* If there are no symbols left after canonicalization and
144      we have not tried the dynamic symbols then give them a go.  */
145   if (symcount == 0
146       && ! dynamic
147       && (storage = bfd_get_dynamic_symtab_upper_bound (abfd)) > 0)
148     {
149       free (syms);
150       syms = xmalloc (storage);
151       symcount = bfd_canonicalize_dynamic_symtab (abfd, syms);
152     }
153 
154   /* PR 17512: file: 2a1d3b5b.
155      Do not pretend that we have some symbols when we don't.  */
156   if (symcount <= 0)
157     {
158       free (syms);
159       syms = NULL;
160     }
161 }
162 
163 /* These global variables are used to pass information between
164    translate_addresses and find_address_in_section.  */
165 
166 static bfd_vma pc;
167 static const char *filename;
168 static const char *functionname;
169 static unsigned int line;
170 static unsigned int discriminator;
171 static bool found;
172 
173 /* Look for an address in a section.  This is called via
174    bfd_map_over_sections.  */
175 
176 static void
find_address_in_section(bfd * abfd,asection * section,void * data ATTRIBUTE_UNUSED)177 find_address_in_section (bfd *abfd, asection *section,
178 			 void *data ATTRIBUTE_UNUSED)
179 {
180   bfd_vma vma;
181   bfd_size_type size;
182 
183   if (found)
184     return;
185 
186   if ((bfd_section_flags (section) & SEC_ALLOC) == 0)
187     return;
188 
189   vma = bfd_section_vma (section);
190   if (pc < vma)
191     return;
192 
193   size = bfd_section_size (section);
194   if (pc >= vma + size)
195     return;
196 
197   found = bfd_find_nearest_line_discriminator (abfd, section, syms, pc - vma,
198                                                &filename, &functionname,
199                                                &line, &discriminator);
200 }
201 
202 /* Look for an offset in a section.  This is directly called.  */
203 
204 static void
find_offset_in_section(bfd * abfd,asection * section)205 find_offset_in_section (bfd *abfd, asection *section)
206 {
207   bfd_size_type size;
208 
209   if (found)
210     return;
211 
212   if ((bfd_section_flags (section) & SEC_ALLOC) == 0)
213     return;
214 
215   size = bfd_section_size (section);
216   if (pc >= size)
217     return;
218 
219   found = bfd_find_nearest_line_discriminator (abfd, section, syms, pc,
220                                                &filename, &functionname,
221                                                &line, &discriminator);
222 }
223 
224 /* Lookup a symbol with offset in symbol table.  */
225 
226 static bfd_vma
lookup_symbol(bfd * abfd,char * sym,size_t offset)227 lookup_symbol (bfd *abfd, char *sym, size_t offset)
228 {
229   long i;
230 
231   for (i = 0; i < symcount; i++)
232     {
233       if (!strcmp (syms[i]->name, sym))
234 	return syms[i]->value + offset + bfd_asymbol_section (syms[i])->vma;
235     }
236   /* Try again mangled */
237   for (i = 0; i < symcount; i++)
238     {
239       char *d = bfd_demangle (abfd, syms[i]->name, demangle_flags);
240       bool match = d && !strcmp (d, sym);
241       free (d);
242 
243       if (match)
244 	return syms[i]->value + offset + bfd_asymbol_section (syms[i])->vma;
245     }
246   return 0;
247 }
248 
249 /* Split an symbol+offset expression. adr is modified.  */
250 
251 static bool
is_symbol(char * adr,char ** symp,size_t * offset)252 is_symbol (char *adr, char **symp, size_t *offset)
253 {
254   char *end;
255 
256   while (ISSPACE (*adr))
257     adr++;
258   if (ISDIGIT (*adr) || *adr == 0)
259     return false;
260   /* Could be either symbol or hex number. Check if it has +.  */
261   if (TOUPPER(*adr) >= 'A' && TOUPPER(*adr) <= 'F' && !strchr (adr, '+'))
262     return false;
263 
264   *symp = adr;
265   while (*adr && !ISSPACE (*adr) && *adr != '+')
266     adr++;
267   end = adr;
268   while (ISSPACE (*adr))
269     adr++;
270   *offset = 0;
271   if (*adr == '+')
272     {
273       adr++;
274       *offset = strtoul(adr, NULL, 0);
275     }
276   *end = 0;
277   return true;
278 }
279 
280 /* Read hexadecimal or symbolic with offset addresses from stdin, translate into
281    file_name:line_number and optionally function name.  */
282 
283 static void
translate_addresses(bfd * abfd,asection * section)284 translate_addresses (bfd *abfd, asection *section)
285 {
286   int read_stdin = (naddr == 0);
287   char *adr;
288   char addr_hex[100];
289   char *symp;
290   size_t offset;
291 
292   for (;;)
293     {
294       if (read_stdin)
295 	{
296 	  if (fgets (addr_hex, sizeof addr_hex, stdin) == NULL)
297 	    break;
298 	  adr = addr_hex;
299 	}
300       else
301 	{
302 	  if (naddr <= 0)
303 	    break;
304 	  --naddr;
305 	  adr = *addr++;
306 	}
307 
308       if (is_symbol (adr, &symp, &offset))
309         pc = lookup_symbol (abfd, symp, offset);
310       else
311         pc = bfd_scan_vma (adr, NULL, 16);
312       if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
313 	{
314 	  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
315 	  bfd_vma sign = (bfd_vma) 1 << (bed->s->arch_size - 1);
316 
317 	  pc &= (sign << 1) - 1;
318 	  if (bed->sign_extend_vma)
319 	    pc = (pc ^ sign) - sign;
320 	}
321 
322       if (with_addresses)
323         {
324           printf ("0x");
325           bfd_printf_vma (abfd, pc);
326 
327           if (pretty_print)
328             printf (": ");
329           else
330             printf ("\n");
331         }
332 
333       found = false;
334       if (section)
335 	find_offset_in_section (abfd, section);
336       else
337 	bfd_map_over_sections (abfd, find_address_in_section, NULL);
338 
339       if (! found)
340 	{
341 	  if (with_functions)
342 	    {
343 	      if (pretty_print)
344 		printf ("?? ");
345 	      else
346 		printf ("??\n");
347 	    }
348 	  printf ("??:0\n");
349 	}
350       else
351 	{
352 	  while (1)
353             {
354               if (with_functions)
355                 {
356                   const char *name;
357                   char *alloc = NULL;
358 
359                   name = functionname;
360                   if (name == NULL || *name == '\0')
361                     name = "??";
362                   else if (do_demangle)
363                     {
364                       alloc = bfd_demangle (abfd, name, demangle_flags);
365                       if (alloc != NULL)
366                         name = alloc;
367                     }
368 
369                   printf ("%s", name);
370                   if (pretty_print)
371 		    /* Note for translators:  This printf is used to join the
372 		       function name just printed above to the line number/
373 		       file name pair that is about to be printed below.  Eg:
374 
375 		         foo at 123:bar.c  */
376                     printf (_(" at "));
377                   else
378                     printf ("\n");
379 
380 		  free (alloc);
381                 }
382 
383               if (base_names && filename != NULL)
384                 {
385                   char *h;
386 
387                   h = strrchr (filename, '/');
388                   if (h != NULL)
389                     filename = h + 1;
390                 }
391 
392               printf ("%s:", filename ? filename : "??");
393 	      if (line != 0)
394                 {
395                   if (discriminator != 0)
396                     printf ("%u (discriminator %u)\n", line, discriminator);
397                   else
398                     printf ("%u\n", line);
399                 }
400 	      else
401 		printf ("?\n");
402               if (!unwind_inlines)
403                 found = false;
404               else
405                 found = bfd_find_inliner_info (abfd, &filename, &functionname,
406 					       &line);
407               if (! found)
408                 break;
409               if (pretty_print)
410 		/* Note for translators: This printf is used to join the
411 		   line number/file name pair that has just been printed with
412 		   the line number/file name pair that is going to be printed
413 		   by the next iteration of the while loop.  Eg:
414 
415 		     123:bar.c (inlined by) 456:main.c  */
416                 printf (_(" (inlined by) "));
417             }
418 	}
419 
420       /* fflush() is essential for using this command as a server
421          child process that reads addresses from a pipe and responds
422          with line number information, processing one address at a
423          time.  */
424       fflush (stdout);
425     }
426 }
427 
428 /* Process a file.  Returns an exit value for main().  */
429 
430 static int
process_file(const char * file_name,const char * section_name,const char * target)431 process_file (const char *file_name, const char *section_name,
432 	      const char *target)
433 {
434   bfd *abfd;
435   asection *section;
436   char **matching;
437 
438   if (get_file_size (file_name) < 1)
439     return 1;
440 
441   abfd = bfd_openr (file_name, target);
442   if (abfd == NULL)
443     bfd_fatal (file_name);
444 
445   /* Decompress sections.  */
446   abfd->flags |= BFD_DECOMPRESS;
447 
448   if (bfd_check_format (abfd, bfd_archive))
449     fatal (_("%s: cannot get addresses from archive"), file_name);
450 
451   if (! bfd_check_format_matches (abfd, bfd_object, &matching))
452     {
453       bfd_nonfatal (bfd_get_filename (abfd));
454       if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
455 	list_matching_formats (matching);
456       xexit (1);
457     }
458 
459   if (section_name != NULL)
460     {
461       section = bfd_get_section_by_name (abfd, section_name);
462       if (section == NULL)
463 	fatal (_("%s: cannot find section %s"), file_name, section_name);
464     }
465   else
466     section = NULL;
467 
468   slurp_symtab (abfd);
469 
470   translate_addresses (abfd, section);
471 
472   free (syms);
473   syms = NULL;
474 
475   bfd_close (abfd);
476 
477   return 0;
478 }
479 
480 int
main(int argc,char ** argv)481 main (int argc, char **argv)
482 {
483   const char *file_name;
484   const char *section_name;
485   char *target;
486   int c;
487 
488 #ifdef HAVE_LC_MESSAGES
489   setlocale (LC_MESSAGES, "");
490 #endif
491   setlocale (LC_CTYPE, "");
492   bindtextdomain (PACKAGE, LOCALEDIR);
493   textdomain (PACKAGE);
494 
495   program_name = *argv;
496   xmalloc_set_program_name (program_name);
497   bfd_set_error_program_name (program_name);
498 
499   expandargv (&argc, &argv);
500 
501   if (bfd_init () != BFD_INIT_MAGIC)
502     fatal (_("fatal error: libbfd ABI mismatch"));
503   set_default_bfd_target ();
504 
505   file_name = NULL;
506   section_name = NULL;
507   target = NULL;
508   while ((c = getopt_long (argc, argv, "ab:Ce:rRsfHhij:pVv", long_options, (int *) 0))
509 	 != EOF)
510     {
511       switch (c)
512 	{
513 	case 0:
514 	  break;		/* We've been given a long option.  */
515 	case 'a':
516 	  with_addresses = true;
517 	  break;
518 	case 'b':
519 	  target = optarg;
520 	  break;
521 	case 'C':
522 	  do_demangle = true;
523 	  if (optarg != NULL)
524 	    {
525 	      enum demangling_styles style;
526 
527 	      style = cplus_demangle_name_to_style (optarg);
528 	      if (style == unknown_demangling)
529 		fatal (_("unknown demangling style `%s'"),
530 		       optarg);
531 
532 	      cplus_demangle_set_style (style);
533 	    }
534 	  break;
535 	case 'r':
536 	  demangle_flags |= DMGL_NO_RECURSE_LIMIT;
537 	  break;
538 	case 'R':
539 	  demangle_flags &= ~ DMGL_NO_RECURSE_LIMIT;
540 	  break;
541 	case 'e':
542 	  file_name = optarg;
543 	  break;
544 	case 's':
545 	  base_names = true;
546 	  break;
547 	case 'f':
548 	  with_functions = true;
549 	  break;
550         case 'p':
551           pretty_print = true;
552           break;
553 	case 'v':
554 	case 'V':
555 	  print_version ("addr2line");
556 	  break;
557 	case 'h':
558 	case 'H':
559 	  usage (stdout, 0);
560 	  break;
561 	case 'i':
562 	  unwind_inlines = true;
563 	  break;
564 	case 'j':
565 	  section_name = optarg;
566 	  break;
567 	default:
568 	  usage (stderr, 1);
569 	  break;
570 	}
571     }
572 
573   if (file_name == NULL)
574     file_name = "a.out";
575 
576   addr = argv + optind;
577   naddr = argc - optind;
578 
579   return process_file (file_name, section_name, target);
580 }
581