1 /* addr2line.c -- convert addresses to line number and function name
2    Copyright (C) 1997-2020 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 
41 static bfd_boolean unwind_inlines;	/* -i, unwind inlined functions. */
42 static bfd_boolean with_addresses;	/* -a, show addresses.  */
43 static bfd_boolean with_functions;	/* -f, show function names.  */
44 static bfd_boolean do_demangle;		/* -C, demangle names.  */
45 static bfd_boolean pretty_print;	/* -p, print on one line.  */
46 static bfd_boolean base_names;		/* -s, strip directory names.  */
47 
48 /* Flags passed to the name demangler.  */
49 static int demangle_flags = DMGL_PARAMS | DMGL_ANSI;
50 
51 static int naddr;		/* Number of addresses to process.  */
52 static char **addr;		/* Hex addresses to process.  */
53 
54 static asymbol **syms;		/* Symbol table.  */
55 
56 static struct option long_options[] =
57 {
58   {"addresses", no_argument, NULL, 'a'},
59   {"basenames", no_argument, NULL, 's'},
60   {"demangle", optional_argument, NULL, 'C'},
61   {"exe", required_argument, NULL, 'e'},
62   {"functions", no_argument, NULL, 'f'},
63   {"inlines", no_argument, NULL, 'i'},
64   {"pretty-print", no_argument, NULL, 'p'},
65   {"recurse-limit", no_argument, NULL, 'R'},
66   {"recursion-limit", no_argument, NULL, 'R'},
67   {"no-recurse-limit", no_argument, NULL, 'r'},
68   {"no-recursion-limit", no_argument, NULL, 'r'},
69   {"section", required_argument, NULL, 'j'},
70   {"target", required_argument, NULL, 'b'},
71   {"help", no_argument, NULL, 'H'},
72   {"version", no_argument, NULL, 'V'},
73   {0, no_argument, 0, 0}
74 };
75 
76 static void usage (FILE *, int);
77 static void slurp_symtab (bfd *);
78 static void find_address_in_section (bfd *, asection *, void *);
79 static void find_offset_in_section (bfd *, asection *);
80 static void translate_addresses (bfd *, asection *);
81 
82 /* Print a usage message to STREAM and exit with STATUS.  */
83 
84 static void
usage(FILE * stream,int status)85 usage (FILE *stream, int status)
86 {
87   fprintf (stream, _("Usage: %s [option(s)] [addr(s)]\n"), program_name);
88   fprintf (stream, _(" Convert addresses into line number/file name pairs.\n"));
89   fprintf (stream, _(" If no addresses are specified on the command line, they will be read from stdin\n"));
90   fprintf (stream, _(" The options are:\n\
91   @<file>                Read options from <file>\n\
92   -a --addresses         Show addresses\n\
93   -b --target=<bfdname>  Set the binary file format\n\
94   -e --exe=<executable>  Set the input file name (default is a.out)\n\
95   -i --inlines           Unwind inlined functions\n\
96   -j --section=<name>    Read section-relative offsets instead of addresses\n\
97   -p --pretty-print      Make the output easier to read for humans\n\
98   -s --basenames         Strip directory names\n\
99   -f --functions         Show function names\n\
100   -C --demangle[=style]  Demangle function names\n\
101   -R --recurse-limit     Enable a limit on recursion whilst demangling.  [Default]\n\
102   -r --no-recurse-limit  Disable a limit on recursion whilst demangling\n\
103   -h --help              Display this information\n\
104   -v --version           Display the program's version\n\
105 \n"));
106 
107   list_supported_targets (program_name, stream);
108   if (REPORT_BUGS_TO[0] && status == 0)
109     fprintf (stream, _("Report bugs to %s\n"), REPORT_BUGS_TO);
110   exit (status);
111 }
112 
113 /* Read in the symbol table.  */
114 
115 static void
slurp_symtab(bfd * abfd)116 slurp_symtab (bfd *abfd)
117 {
118   long storage;
119   long symcount;
120   bfd_boolean dynamic = FALSE;
121 
122   if ((bfd_get_file_flags (abfd) & HAS_SYMS) == 0)
123     return;
124 
125   storage = bfd_get_symtab_upper_bound (abfd);
126   if (storage == 0)
127     {
128       storage = bfd_get_dynamic_symtab_upper_bound (abfd);
129       dynamic = TRUE;
130     }
131   if (storage < 0)
132     bfd_fatal (bfd_get_filename (abfd));
133 
134   syms = (asymbol **) xmalloc (storage);
135   if (dynamic)
136     symcount = bfd_canonicalize_dynamic_symtab (abfd, syms);
137   else
138     symcount = bfd_canonicalize_symtab (abfd, syms);
139   if (symcount < 0)
140     bfd_fatal (bfd_get_filename (abfd));
141 
142   /* If there are no symbols left after canonicalization and
143      we have not tried the dynamic symbols then give them a go.  */
144   if (symcount == 0
145       && ! dynamic
146       && (storage = bfd_get_dynamic_symtab_upper_bound (abfd)) > 0)
147     {
148       free (syms);
149       syms = xmalloc (storage);
150       symcount = bfd_canonicalize_dynamic_symtab (abfd, syms);
151     }
152 
153   /* PR 17512: file: 2a1d3b5b.
154      Do not pretend that we have some symbols when we don't.  */
155   if (symcount <= 0)
156     {
157       free (syms);
158       syms = NULL;
159     }
160 }
161 
162 /* These global variables are used to pass information between
163    translate_addresses and find_address_in_section.  */
164 
165 static bfd_vma pc;
166 static const char *filename;
167 static const char *functionname;
168 static unsigned int line;
169 static unsigned int discriminator;
170 static bfd_boolean found;
171 
172 /* Look for an address in a section.  This is called via
173    bfd_map_over_sections.  */
174 
175 static void
find_address_in_section(bfd * abfd,asection * section,void * data ATTRIBUTE_UNUSED)176 find_address_in_section (bfd *abfd, asection *section,
177 			 void *data ATTRIBUTE_UNUSED)
178 {
179   bfd_vma vma;
180   bfd_size_type size;
181 
182   if (found)
183     return;
184 
185   if ((bfd_section_flags (section) & SEC_ALLOC) == 0)
186     return;
187 
188   vma = bfd_section_vma (section);
189   if (pc < vma)
190     return;
191 
192   size = bfd_section_size (section);
193   if (pc >= vma + size)
194     return;
195 
196   found = bfd_find_nearest_line_discriminator (abfd, section, syms, pc - vma,
197                                                &filename, &functionname,
198                                                &line, &discriminator);
199 }
200 
201 /* Look for an offset in a section.  This is directly called.  */
202 
203 static void
find_offset_in_section(bfd * abfd,asection * section)204 find_offset_in_section (bfd *abfd, asection *section)
205 {
206   bfd_size_type size;
207 
208   if (found)
209     return;
210 
211   if ((bfd_section_flags (section) & SEC_ALLOC) == 0)
212     return;
213 
214   size = bfd_section_size (section);
215   if (pc >= size)
216     return;
217 
218   found = bfd_find_nearest_line_discriminator (abfd, section, syms, pc,
219                                                &filename, &functionname,
220                                                &line, &discriminator);
221 }
222 
223 /* Read hexadecimal addresses from stdin, translate into
224    file_name:line_number and optionally function name.  */
225 
226 static void
translate_addresses(bfd * abfd,asection * section)227 translate_addresses (bfd *abfd, asection *section)
228 {
229   int read_stdin = (naddr == 0);
230 
231   for (;;)
232     {
233       if (read_stdin)
234 	{
235 	  char addr_hex[100];
236 
237 	  if (fgets (addr_hex, sizeof addr_hex, stdin) == NULL)
238 	    break;
239 	  pc = bfd_scan_vma (addr_hex, NULL, 16);
240 	}
241       else
242 	{
243 	  if (naddr <= 0)
244 	    break;
245 	  --naddr;
246 	  pc = bfd_scan_vma (*addr++, NULL, 16);
247 	}
248 
249       if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
250 	{
251 	  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
252 	  bfd_vma sign = (bfd_vma) 1 << (bed->s->arch_size - 1);
253 
254 	  pc &= (sign << 1) - 1;
255 	  if (bed->sign_extend_vma)
256 	    pc = (pc ^ sign) - sign;
257 	}
258 
259       if (with_addresses)
260         {
261           printf ("0x");
262           bfd_printf_vma (abfd, pc);
263 
264           if (pretty_print)
265             printf (": ");
266           else
267             printf ("\n");
268         }
269 
270       found = FALSE;
271       if (section)
272 	find_offset_in_section (abfd, section);
273       else
274 	bfd_map_over_sections (abfd, find_address_in_section, NULL);
275 
276       if (! found)
277 	{
278 	  if (with_functions)
279 	    {
280 	      if (pretty_print)
281 		printf ("?? ");
282 	      else
283 		printf ("??\n");
284 	    }
285 	  printf ("??:0\n");
286 	}
287       else
288 	{
289 	  while (1)
290             {
291               if (with_functions)
292                 {
293                   const char *name;
294                   char *alloc = NULL;
295 
296                   name = functionname;
297                   if (name == NULL || *name == '\0')
298                     name = "??";
299                   else if (do_demangle)
300                     {
301                       alloc = bfd_demangle (abfd, name, demangle_flags);
302                       if (alloc != NULL)
303                         name = alloc;
304                     }
305 
306                   printf ("%s", name);
307                   if (pretty_print)
308 		    /* Note for translators:  This printf is used to join the
309 		       function name just printed above to the line number/
310 		       file name pair that is about to be printed below.  Eg:
311 
312 		         foo at 123:bar.c  */
313                     printf (_(" at "));
314                   else
315                     printf ("\n");
316 
317 		  free (alloc);
318                 }
319 
320               if (base_names && filename != NULL)
321                 {
322                   char *h;
323 
324                   h = strrchr (filename, '/');
325                   if (h != NULL)
326                     filename = h + 1;
327                 }
328 
329               printf ("%s:", filename ? filename : "??");
330 	      if (line != 0)
331                 {
332                   if (discriminator != 0)
333                     printf ("%u (discriminator %u)\n", line, discriminator);
334                   else
335                     printf ("%u\n", line);
336                 }
337 	      else
338 		printf ("?\n");
339               if (!unwind_inlines)
340                 found = FALSE;
341               else
342                 found = bfd_find_inliner_info (abfd, &filename, &functionname,
343 					       &line);
344               if (! found)
345                 break;
346               if (pretty_print)
347 		/* Note for translators: This printf is used to join the
348 		   line number/file name pair that has just been printed with
349 		   the line number/file name pair that is going to be printed
350 		   by the next iteration of the while loop.  Eg:
351 
352 		     123:bar.c (inlined by) 456:main.c  */
353                 printf (_(" (inlined by) "));
354             }
355 	}
356 
357       /* fflush() is essential for using this command as a server
358          child process that reads addresses from a pipe and responds
359          with line number information, processing one address at a
360          time.  */
361       fflush (stdout);
362     }
363 }
364 
365 /* Process a file.  Returns an exit value for main().  */
366 
367 static int
process_file(const char * file_name,const char * section_name,const char * target)368 process_file (const char *file_name, const char *section_name,
369 	      const char *target)
370 {
371   bfd *abfd;
372   asection *section;
373   char **matching;
374 
375   if (get_file_size (file_name) < 1)
376     return 1;
377 
378   abfd = bfd_openr (file_name, target);
379   if (abfd == NULL)
380     bfd_fatal (file_name);
381 
382   /* Decompress sections.  */
383   abfd->flags |= BFD_DECOMPRESS;
384 
385   if (bfd_check_format (abfd, bfd_archive))
386     fatal (_("%s: cannot get addresses from archive"), file_name);
387 
388   if (! bfd_check_format_matches (abfd, bfd_object, &matching))
389     {
390       bfd_nonfatal (bfd_get_filename (abfd));
391       if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
392 	{
393 	  list_matching_formats (matching);
394 	  free (matching);
395 	}
396       xexit (1);
397     }
398 
399   if (section_name != NULL)
400     {
401       section = bfd_get_section_by_name (abfd, section_name);
402       if (section == NULL)
403 	fatal (_("%s: cannot find section %s"), file_name, section_name);
404     }
405   else
406     section = NULL;
407 
408   slurp_symtab (abfd);
409 
410   translate_addresses (abfd, section);
411 
412   free (syms);
413   syms = NULL;
414 
415   bfd_close (abfd);
416 
417   return 0;
418 }
419 
420 int
main(int argc,char ** argv)421 main (int argc, char **argv)
422 {
423   const char *file_name;
424   const char *section_name;
425   char *target;
426   int c;
427 
428 #if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
429   setlocale (LC_MESSAGES, "");
430 #endif
431 #if defined (HAVE_SETLOCALE)
432   setlocale (LC_CTYPE, "");
433 #endif
434   bindtextdomain (PACKAGE, LOCALEDIR);
435   textdomain (PACKAGE);
436 
437   program_name = *argv;
438   xmalloc_set_program_name (program_name);
439   bfd_set_error_program_name (program_name);
440 
441   expandargv (&argc, &argv);
442 
443   if (bfd_init () != BFD_INIT_MAGIC)
444     fatal (_("fatal error: libbfd ABI mismatch"));
445   set_default_bfd_target ();
446 
447   file_name = NULL;
448   section_name = NULL;
449   target = NULL;
450   while ((c = getopt_long (argc, argv, "ab:Ce:rRsfHhij:pVv", long_options, (int *) 0))
451 	 != EOF)
452     {
453       switch (c)
454 	{
455 	case 0:
456 	  break;		/* We've been given a long option.  */
457 	case 'a':
458 	  with_addresses = TRUE;
459 	  break;
460 	case 'b':
461 	  target = optarg;
462 	  break;
463 	case 'C':
464 	  do_demangle = TRUE;
465 	  if (optarg != NULL)
466 	    {
467 	      enum demangling_styles style;
468 
469 	      style = cplus_demangle_name_to_style (optarg);
470 	      if (style == unknown_demangling)
471 		fatal (_("unknown demangling style `%s'"),
472 		       optarg);
473 
474 	      cplus_demangle_set_style (style);
475 	    }
476 	  break;
477 	case 'r':
478 	  demangle_flags |= DMGL_NO_RECURSE_LIMIT;
479 	  break;
480 	case 'R':
481 	  demangle_flags &= ~ DMGL_NO_RECURSE_LIMIT;
482 	  break;
483 	case 'e':
484 	  file_name = optarg;
485 	  break;
486 	case 's':
487 	  base_names = TRUE;
488 	  break;
489 	case 'f':
490 	  with_functions = TRUE;
491 	  break;
492         case 'p':
493           pretty_print = TRUE;
494           break;
495 	case 'v':
496 	case 'V':
497 	  print_version ("addr2line");
498 	  break;
499 	case 'h':
500 	case 'H':
501 	  usage (stdout, 0);
502 	  break;
503 	case 'i':
504 	  unwind_inlines = TRUE;
505 	  break;
506 	case 'j':
507 	  section_name = optarg;
508 	  break;
509 	default:
510 	  usage (stderr, 1);
511 	  break;
512 	}
513     }
514 
515   if (file_name == NULL)
516     file_name = "a.out";
517 
518   addr = argv + optind;
519   naddr = argc - optind;
520 
521   return process_file (file_name, section_name, target);
522 }
523