1 /* nm.c -- Describe symbol table of a rel file.
2    Copyright (C) 1991-2021 Free Software Foundation, Inc.
3 
4    This file is part of GNU Binutils.
5 
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10 
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15 
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
19    02110-1301, USA.  */
20 
21 #include "sysdep.h"
22 #include "bfd.h"
23 #include "progress.h"
24 #include "getopt.h"
25 #include "aout/stab_gnu.h"
26 #include "aout/ranlib.h"
27 #include "demangle.h"
28 #include "libiberty.h"
29 #include "elf-bfd.h"
30 #include "elf/common.h"
31 #define DO_NOT_DEFINE_AOUTHDR
32 #define DO_NOT_DEFINE_FILHDR
33 #define DO_NOT_DEFINE_LINENO
34 #define DO_NOT_DEFINE_SCNHDR
35 #include "coff/external.h"
36 #include "coff/internal.h"
37 #include "libcoff.h"
38 #include "bucomm.h"
39 #include "plugin-api.h"
40 #include "plugin.h"
41 
42 /* When sorting by size, we use this structure to hold the size and a
43    pointer to the minisymbol.  */
44 
45 struct size_sym
46 {
47   const void *minisym;
48   bfd_vma size;
49 };
50 
51 /* When fetching relocs, we use this structure to pass information to
52    get_relocs.  */
53 
54 struct get_relocs_info
55 {
56   asection **secs;
57   arelent ***relocs;
58   long *relcount;
59   asymbol **syms;
60 };
61 
62 struct extended_symbol_info
63 {
64   symbol_info *sinfo;
65   bfd_vma ssize;
66   elf_symbol_type *elfinfo;
67   coff_symbol_type *coffinfo;
68   /* FIXME: We should add more fields for Type, Line, Section.  */
69 };
70 #define SYM_VALUE(sym)       (sym->sinfo->value)
71 #define SYM_TYPE(sym)        (sym->sinfo->type)
72 #define SYM_STAB_NAME(sym)   (sym->sinfo->stab_name)
73 #define SYM_STAB_DESC(sym)   (sym->sinfo->stab_desc)
74 #define SYM_STAB_OTHER(sym)  (sym->sinfo->stab_other)
75 #define SYM_SIZE(sym) \
76   (sym->elfinfo ? sym->elfinfo->internal_elf_sym.st_size: sym->ssize)
77 
78 /* The output formatting functions.  */
79 static void print_object_filename_bsd (const char *);
80 static void print_object_filename_sysv (const char *);
81 static void print_object_filename_posix (const char *);
82 static void do_not_print_object_filename (const char *);
83 
84 static void print_archive_filename_bsd (const char *);
85 static void print_archive_filename_sysv (const char *);
86 static void print_archive_filename_posix (const char *);
87 static void do_not_print_archive_filename (const char *);
88 
89 static void print_archive_member_bsd (const char *, const char *);
90 static void print_archive_member_sysv (const char *, const char *);
91 static void print_archive_member_posix (const char *, const char *);
92 static void do_not_print_archive_member (const char *, const char *);
93 
94 static void print_symbol_filename_bsd (bfd *, bfd *);
95 static void print_symbol_filename_sysv (bfd *, bfd *);
96 static void print_symbol_filename_posix (bfd *, bfd *);
97 static void do_not_print_symbol_filename (bfd *, bfd *);
98 
99 static void print_symbol_info_bsd (struct extended_symbol_info *, bfd *);
100 static void print_symbol_info_sysv (struct extended_symbol_info *, bfd *);
101 static void print_symbol_info_posix (struct extended_symbol_info *, bfd *);
102 static void just_print_symbol_name (struct extended_symbol_info *, bfd *);
103 
104 static void print_value (bfd *, bfd_vma);
105 
106 /* Support for different output formats.  */
107 struct output_fns
108 {
109   /* Print the name of an object file given on the command line.  */
110   void (*print_object_filename) (const char *);
111 
112   /* Print the name of an archive file given on the command line.  */
113   void (*print_archive_filename) (const char *);
114 
115   /* Print the name of an archive member file.  */
116   void (*print_archive_member) (const char *, const char *);
117 
118   /* Print the name of the file (and archive, if there is one)
119      containing a symbol.  */
120   void (*print_symbol_filename) (bfd *, bfd *);
121 
122   /* Print a line of information about a symbol.  */
123   void (*print_symbol_info) (struct extended_symbol_info *, bfd *);
124 };
125 
126 /* Indices in `formats'.  */
127 enum formats
128 {
129   FORMAT_BSD = 0,
130   FORMAT_SYSV,
131   FORMAT_POSIX,
132   FORMAT_JUST_SYMBOLS,
133   FORMAT_MAX
134 };
135 
136 #define FORMAT_DEFAULT FORMAT_BSD
137 
138 static struct output_fns formats[FORMAT_MAX] =
139 {
140   {print_object_filename_bsd,
141    print_archive_filename_bsd,
142    print_archive_member_bsd,
143    print_symbol_filename_bsd,
144    print_symbol_info_bsd},
145   {print_object_filename_sysv,
146    print_archive_filename_sysv,
147    print_archive_member_sysv,
148    print_symbol_filename_sysv,
149    print_symbol_info_sysv},
150   {print_object_filename_posix,
151    print_archive_filename_posix,
152    print_archive_member_posix,
153    print_symbol_filename_posix,
154    print_symbol_info_posix},
155   {do_not_print_object_filename,
156    do_not_print_archive_filename,
157    do_not_print_archive_member,
158    do_not_print_symbol_filename,
159    just_print_symbol_name}
160 };
161 
162 
163 /* The output format to use.  */
164 static struct output_fns *format = &formats[FORMAT_DEFAULT];
165 static unsigned int print_format = FORMAT_DEFAULT;
166 static const char *print_format_string = NULL;
167 
168 /* Command options.  */
169 
170 static int do_demangle = 0;	/* Pretty print C++ symbol names.  */
171 static int external_only = 0;	/* Print external symbols only.  */
172 static int defined_only = 0;	/* Print defined symbols only.  */
173 static int no_sort = 0;		/* Don't sort; print syms in order found.  */
174 static int print_debug_syms = 0;/* Print debugger-only symbols too.  */
175 static int print_armap = 0;	/* Describe __.SYMDEF data in archive files.  */
176 static int print_size = 0;	/* Print size of defined symbols.  */
177 static int reverse_sort = 0;	/* Sort in downward(alpha or numeric) order.  */
178 static int sort_numerically = 0;/* Sort in numeric rather than alpha order.  */
179 static int sort_by_size = 0;	/* Sort by size of symbol.  */
180 static int undefined_only = 0;	/* Print undefined symbols only.  */
181 static int dynamic = 0;		/* Print dynamic symbols.  */
182 static int show_version = 0;	/* Show the version number.  */
183 static int show_synthetic = 0;	/* Display synthesized symbols too.  */
184 static int line_numbers = 0;	/* Print line numbers for symbols.  */
185 static int allow_special_symbols = 0;  /* Allow special symbols.  */
186 static int with_symbol_versions = -1; /* Output symbol version information.  */
187 static int quiet = 0;		/* Suppress "no symbols" diagnostic.  */
188 
189 /* The characters to use for global and local ifunc symbols.  */
190 #if DEFAULT_F_FOR_IFUNC_SYMBOLS
191 static const char * ifunc_type_chars = "Ff";
192 #else
193 static const char * ifunc_type_chars = NULL;
194 #endif
195 
196 static int demangle_flags = DMGL_ANSI | DMGL_PARAMS;
197 
198 /* When to print the names of files.  Not mutually exclusive in SYSV format.  */
199 static int filename_per_file = 0;	/* Once per file, on its own line.  */
200 static int filename_per_symbol = 0;	/* Once per symbol, at start of line.  */
201 
202 static int print_width = 0;
203 static int print_radix = 16;
204 /* Print formats for printing stab info.  */
205 static char other_format[] = "%02x";
206 static char desc_format[] = "%04x";
207 
208 static char *target = NULL;
209 #if BFD_SUPPORTS_PLUGINS
210 static const char *plugin_target = "plugin";
211 #else
212 static const char *plugin_target = NULL;
213 #endif
214 
215 /* Used to cache the line numbers for a BFD.  */
216 static bfd *lineno_cache_bfd;
217 static bfd *lineno_cache_rel_bfd;
218 
219 enum long_option_values
220 {
221   OPTION_TARGET = 200,
222   OPTION_PLUGIN,
223   OPTION_SIZE_SORT,
224   OPTION_RECURSE_LIMIT,
225   OPTION_NO_RECURSE_LIMIT,
226   OPTION_IFUNC_CHARS,
227   OPTION_QUIET
228 };
229 
230 static struct option long_options[] =
231 {
232   {"debug-syms", no_argument, &print_debug_syms, 1},
233   {"demangle", optional_argument, 0, 'C'},
234   {"dynamic", no_argument, &dynamic, 1},
235   {"extern-only", no_argument, &external_only, 1},
236   {"format", required_argument, 0, 'f'},
237   {"help", no_argument, 0, 'h'},
238   {"ifunc-chars", required_argument, 0, OPTION_IFUNC_CHARS},
239   {"just-symbols", no_argument, 0, 'j'},
240   {"line-numbers", no_argument, 0, 'l'},
241   {"no-cplus", no_argument, &do_demangle, 0},  /* Linux compatibility.  */
242   {"no-demangle", no_argument, &do_demangle, 0},
243   {"no-recurse-limit", no_argument, NULL, OPTION_NO_RECURSE_LIMIT},
244   {"no-recursion-limit", no_argument, NULL, OPTION_NO_RECURSE_LIMIT},
245   {"no-sort", no_argument, 0, 'p'},
246   {"numeric-sort", no_argument, 0, 'n'},
247   {"plugin", required_argument, 0, OPTION_PLUGIN},
248   {"portability", no_argument, 0, 'P'},
249   {"print-armap", no_argument, &print_armap, 1},
250   {"print-file-name", no_argument, 0, 'o'},
251   {"print-size", no_argument, 0, 'S'},
252   {"quiet", no_argument, 0, OPTION_QUIET},
253   {"radix", required_argument, 0, 't'},
254   {"recurse-limit", no_argument, NULL, OPTION_RECURSE_LIMIT},
255   {"recursion-limit", no_argument, NULL, OPTION_RECURSE_LIMIT},
256   {"reverse-sort", no_argument, &reverse_sort, 1},
257   {"size-sort", no_argument, 0, OPTION_SIZE_SORT},
258   {"special-syms", no_argument, &allow_special_symbols, 1},
259   {"synthetic", no_argument, &show_synthetic, 1},
260   {"target", required_argument, 0, OPTION_TARGET},
261   {"defined-only", no_argument, &defined_only, 1},
262   {"undefined-only", no_argument, &undefined_only, 1},
263   {"version", no_argument, &show_version, 1},
264   {"with-symbol-versions", no_argument, &with_symbol_versions, 1},
265   {"without-symbol-versions", no_argument, &with_symbol_versions, 0},
266   {0, no_argument, 0, 0}
267 };
268 
269 /* Some error-reporting functions.  */
270 
271 ATTRIBUTE_NORETURN static void
usage(FILE * stream,int status)272 usage (FILE *stream, int status)
273 {
274   fprintf (stream, _("Usage: %s [option(s)] [file(s)]\n"), program_name);
275   fprintf (stream, _(" List symbols in [file(s)] (a.out by default).\n"));
276   fprintf (stream, _(" The options are:\n\
277   -a, --debug-syms       Display debugger-only symbols\n\
278   -A, --print-file-name  Print name of the input file before every symbol\n\
279   -B                     Same as --format=bsd\n\
280   -C, --demangle[=STYLE] Decode low-level symbol names into user-level names\n\
281                           The STYLE, if specified, can be `auto' (the default),\n\
282                           `gnu', `lucid', `arm', `hp', `edg', `gnu-v3', `java'\n\
283                           or `gnat'\n\
284       --no-demangle      Do not demangle low-level symbol names\n\
285       --recurse-limit    Enable a demangling recursion limit.  This is the default.\n\
286       --no-recurse-limit Disable a demangling recursion limit.\n\
287   -D, --dynamic          Display dynamic symbols instead of normal symbols\n\
288       --defined-only     Display only defined symbols\n\
289   -e                     (ignored)\n\
290   -f, --format=FORMAT    Use the output format FORMAT.  FORMAT can be `bsd',\n\
291                            `sysv', `posix' or 'just-symbols'.  The default is `bsd'\n\
292   -g, --extern-only      Display only external symbols\n\
293     --ifunc-chars=CHARS  Characters to use when displaying ifunc symbols\n\
294   -j, --just-symbols     Same as --format=just-symbols\n\
295   -l, --line-numbers     Use debugging information to find a filename and\n\
296                            line number for each symbol\n\
297   -n, --numeric-sort     Sort symbols numerically by address\n\
298   -o                     Same as -A\n\
299   -p, --no-sort          Do not sort the symbols\n\
300   -P, --portability      Same as --format=posix\n\
301   -r, --reverse-sort     Reverse the sense of the sort\n"));
302 #if BFD_SUPPORTS_PLUGINS
303   fprintf (stream, _("\
304       --plugin NAME      Load the specified plugin\n"));
305 #endif
306   fprintf (stream, _("\
307   -S, --print-size       Print size of defined symbols\n\
308   -s, --print-armap      Include index for symbols from archive members\n\
309       --quiet            Suppress \"no symbols\" diagnostic\n\
310       --size-sort        Sort symbols by size\n\
311       --special-syms     Include special symbols in the output\n\
312       --synthetic        Display synthetic symbols as well\n\
313   -t, --radix=RADIX      Use RADIX for printing symbol values\n\
314       --target=BFDNAME   Specify the target object format as BFDNAME\n\
315   -u, --undefined-only   Display only undefined symbols\n\
316       --with-symbol-versions  Display version strings after symbol names\n\
317   -X 32_64               (ignored)\n\
318   @FILE                  Read options from FILE\n\
319   -h, --help             Display this information\n\
320   -V, --version          Display this program's version number\n\
321 \n"));
322   list_supported_targets (program_name, stream);
323   if (REPORT_BUGS_TO[0] && status == 0)
324     fprintf (stream, _("Report bugs to %s.\n"), REPORT_BUGS_TO);
325   exit (status);
326 }
327 
328 /* Set the radix for the symbol value and size according to RADIX.  */
329 
330 static void
set_print_radix(char * radix)331 set_print_radix (char *radix)
332 {
333   switch (*radix)
334     {
335     case 'x': print_radix = 16; break;
336     case 'd': print_radix = 10; break;
337     case 'o': print_radix =  8; break;
338 
339     default:
340       fatal (_("%s: invalid radix"), radix);
341     }
342 
343   other_format[3] = desc_format[3] = *radix;
344 }
345 
346 static void
set_output_format(char * f)347 set_output_format (char *f)
348 {
349   int i;
350 
351   switch (*f)
352     {
353     case 'b':
354     case 'B':
355       i = FORMAT_BSD;
356       break;
357     case 'p':
358     case 'P':
359       i = FORMAT_POSIX;
360       break;
361     case 's':
362     case 'S':
363       i = FORMAT_SYSV;
364       break;
365     case 'j':
366     case 'J':
367       i = FORMAT_JUST_SYMBOLS;
368       break;
369     default:
370       fatal (_("%s: invalid output format"), f);
371     }
372   format = &formats[i];
373   print_format = i;
374 }
375 
376 static const char *
get_elf_symbol_type(unsigned int type)377 get_elf_symbol_type (unsigned int type)
378 {
379   static char *bufp;
380   int n;
381 
382   switch (type)
383     {
384     case STT_NOTYPE:   return "NOTYPE";
385     case STT_OBJECT:   return "OBJECT";
386     case STT_FUNC:     return "FUNC";
387     case STT_SECTION:  return "SECTION";
388     case STT_FILE:     return "FILE";
389     case STT_COMMON:   return "COMMON";
390     case STT_TLS:      return "TLS";
391     }
392 
393   free (bufp);
394   if (type >= STT_LOPROC && type <= STT_HIPROC)
395     n = asprintf (&bufp, _("<processor specific>: %d"), type);
396   else if (type >= STT_LOOS && type <= STT_HIOS)
397     n = asprintf (&bufp, _("<OS specific>: %d"), type);
398   else
399     n = asprintf (&bufp, _("<unknown>: %d"), type);
400   if (n < 0)
401     fatal ("%s", xstrerror (errno));
402   return bufp;
403 }
404 
405 static const char *
get_coff_symbol_type(const struct internal_syment * sym)406 get_coff_symbol_type (const struct internal_syment *sym)
407 {
408   static char *bufp;
409   int n;
410 
411   switch (sym->n_sclass)
412     {
413     case C_BLOCK: return "Block";
414     case C_FILE:  return "File";
415     case C_LINE:  return "Line";
416     }
417 
418   if (!sym->n_type)
419     return "None";
420 
421   switch (DTYPE(sym->n_type))
422     {
423     case DT_FCN: return "Function";
424     case DT_PTR: return "Pointer";
425     case DT_ARY: return "Array";
426     }
427 
428   free (bufp);
429   n = asprintf (&bufp, _("<unknown>: %d/%d"), sym->n_sclass, sym->n_type);
430   if (n < 0)
431     fatal ("%s", xstrerror (errno));
432   return bufp;
433 }
434 
435 /* Print symbol name NAME, read from ABFD, with printf format FORM,
436    demangling it if requested.  */
437 
438 static void
print_symname(const char * form,struct extended_symbol_info * info,const char * name,bfd * abfd)439 print_symname (const char *form, struct extended_symbol_info *info,
440 	       const char *name, bfd *abfd)
441 {
442   char *alloc = NULL;
443   char *atver = NULL;
444 
445   if (name == NULL)
446     name = info->sinfo->name;
447   if (!with_symbol_versions
448       && bfd_get_flavour (abfd) == bfd_target_elf_flavour)
449     {
450       atver = strchr (name, '@');
451       if (atver)
452 	*atver = 0;
453     }
454   if (do_demangle && *name)
455     {
456       alloc = bfd_demangle (abfd, name, demangle_flags);
457       if (alloc != NULL)
458 	name = alloc;
459     }
460 
461   if (info != NULL && info->elfinfo && with_symbol_versions)
462     {
463       const char *version_string;
464       bool hidden;
465 
466       version_string
467 	= bfd_get_symbol_version_string (abfd, &info->elfinfo->symbol,
468 					 false, &hidden);
469       if (version_string && version_string[0])
470 	{
471 	  const char *at = "@@";
472 	  if (hidden || bfd_is_und_section (info->elfinfo->symbol.section))
473 	    at = "@";
474 	  alloc = reconcat (alloc, name, at, version_string, NULL);
475 	  if (alloc != NULL)
476 	    name = alloc;
477 	}
478     }
479   printf (form, name);
480   if (atver)
481     *atver = '@';
482   free (alloc);
483 }
484 
485 static void
print_symdef_entry(bfd * abfd)486 print_symdef_entry (bfd *abfd)
487 {
488   symindex idx = BFD_NO_MORE_SYMBOLS;
489   carsym *thesym;
490   bool everprinted = false;
491 
492   for (idx = bfd_get_next_mapent (abfd, idx, &thesym);
493        idx != BFD_NO_MORE_SYMBOLS;
494        idx = bfd_get_next_mapent (abfd, idx, &thesym))
495     {
496       bfd *elt;
497       if (!everprinted)
498 	{
499 	  printf (_("\nArchive index:\n"));
500 	  everprinted = true;
501 	}
502       elt = bfd_get_elt_at_index (abfd, idx);
503       if (elt == NULL)
504 	bfd_fatal ("bfd_get_elt_at_index");
505       if (thesym->name != (char *) NULL)
506 	{
507 	  print_symname ("%s", NULL, thesym->name, abfd);
508 	  printf (" in %s\n", bfd_get_filename (elt));
509 	}
510     }
511 }
512 
513 
514 /* True when we can report missing plugin error.  */
515 bool report_plugin_err = true;
516 
517 /* Choose which symbol entries to print;
518    compact them downward to get rid of the rest.
519    Return the number of symbols to be printed.  */
520 
521 static long
filter_symbols(bfd * abfd,bool is_dynamic,void * minisyms,long symcount,unsigned int size)522 filter_symbols (bfd *abfd, bool is_dynamic, void *minisyms,
523 		long symcount, unsigned int size)
524 {
525   bfd_byte *from, *fromend, *to;
526   asymbol *store;
527 
528   store = bfd_make_empty_symbol (abfd);
529   if (store == NULL)
530     bfd_fatal (bfd_get_filename (abfd));
531 
532   from = (bfd_byte *) minisyms;
533   fromend = from + symcount * size;
534   to = (bfd_byte *) minisyms;
535 
536   for (; from < fromend; from += size)
537     {
538       int keep = 0;
539       asymbol *sym;
540 
541       PROGRESS (1);
542 
543       sym = bfd_minisymbol_to_symbol (abfd, is_dynamic, (const void *) from, store);
544       if (sym == NULL)
545 	bfd_fatal (bfd_get_filename (abfd));
546 
547       if (sym->name[0] == '_'
548 	  && sym->name[1] == '_'
549 	  && strcmp (sym->name + (sym->name[2] == '_'), "__gnu_lto_slim") == 0
550 	  && report_plugin_err)
551 	{
552 	  report_plugin_err = false;
553 	  non_fatal (_("%s: plugin needed to handle lto object"),
554 		     bfd_get_filename (abfd));
555 	}
556 
557       if (undefined_only)
558 	keep = bfd_is_und_section (sym->section);
559       else if (external_only)
560 	/* PR binutls/12753: Unique symbols are global too.  */
561 	keep = ((sym->flags & (BSF_GLOBAL
562 			       | BSF_WEAK
563 			       | BSF_GNU_UNIQUE)) != 0
564 		|| bfd_is_und_section (sym->section)
565 		|| bfd_is_com_section (sym->section));
566       else
567 	keep = 1;
568 
569       if (keep
570 	  && ! print_debug_syms
571 	  && (sym->flags & BSF_DEBUGGING) != 0)
572 	keep = 0;
573 
574       if (keep
575 	  && sort_by_size
576 	  && (bfd_is_abs_section (sym->section)
577 	      || bfd_is_und_section (sym->section)))
578 	keep = 0;
579 
580       if (keep
581 	  && defined_only)
582 	{
583 	  if (bfd_is_und_section (sym->section))
584 	    keep = 0;
585 	}
586 
587       if (keep
588 	  && bfd_is_target_special_symbol (abfd, sym)
589 	  && ! allow_special_symbols)
590 	keep = 0;
591 
592       if (keep)
593 	{
594 	  if (to != from)
595 	    memcpy (to, from, size);
596 	  to += size;
597 	}
598     }
599 
600   return (to - (bfd_byte *) minisyms) / size;
601 }
602 
603 /* These globals are used to pass information into the sorting
604    routines.  */
605 static bfd *sort_bfd;
606 static bool sort_dynamic;
607 static asymbol *sort_x;
608 static asymbol *sort_y;
609 
610 /* Symbol-sorting predicates */
611 #define valueof(x) ((x)->section->vma + (x)->value)
612 
613 /* Numeric sorts.  Undefined symbols are always considered "less than"
614    defined symbols with zero values.  Common symbols are not treated
615    specially -- i.e., their sizes are used as their "values".  */
616 
617 static int
non_numeric_forward(const void * P_x,const void * P_y)618 non_numeric_forward (const void *P_x, const void *P_y)
619 {
620   asymbol *x, *y;
621   const char *xn, *yn;
622 
623   x = bfd_minisymbol_to_symbol (sort_bfd, sort_dynamic, P_x, sort_x);
624   y = bfd_minisymbol_to_symbol (sort_bfd, sort_dynamic, P_y, sort_y);
625   if (x == NULL || y == NULL)
626     bfd_fatal (bfd_get_filename (sort_bfd));
627 
628   xn = bfd_asymbol_name (x);
629   yn = bfd_asymbol_name (y);
630 
631   if (yn == NULL)
632     return xn != NULL;
633   if (xn == NULL)
634     return -1;
635 
636   /* Solaris 2.5 has a bug in strcoll.
637      strcoll returns invalid values when confronted with empty strings.  */
638   if (*yn == '\0')
639     return *xn != '\0';
640   if (*xn == '\0')
641     return -1;
642 
643   return strcoll (xn, yn);
644 }
645 
646 static int
non_numeric_reverse(const void * x,const void * y)647 non_numeric_reverse (const void *x, const void *y)
648 {
649   return - non_numeric_forward (x, y);
650 }
651 
652 static int
numeric_forward(const void * P_x,const void * P_y)653 numeric_forward (const void *P_x, const void *P_y)
654 {
655   asymbol *x, *y;
656   asection *xs, *ys;
657 
658   x = bfd_minisymbol_to_symbol (sort_bfd, sort_dynamic, P_x, sort_x);
659   y =  bfd_minisymbol_to_symbol (sort_bfd, sort_dynamic, P_y, sort_y);
660   if (x == NULL || y == NULL)
661     bfd_fatal (bfd_get_filename (sort_bfd));
662 
663   xs = bfd_asymbol_section (x);
664   ys = bfd_asymbol_section (y);
665 
666   if (bfd_is_und_section (xs))
667     {
668       if (! bfd_is_und_section (ys))
669 	return -1;
670     }
671   else if (bfd_is_und_section (ys))
672     return 1;
673   else if (valueof (x) != valueof (y))
674     return valueof (x) < valueof (y) ? -1 : 1;
675 
676   return non_numeric_forward (P_x, P_y);
677 }
678 
679 static int
numeric_reverse(const void * x,const void * y)680 numeric_reverse (const void *x, const void *y)
681 {
682   return - numeric_forward (x, y);
683 }
684 
685 static int (*(sorters[2][2])) (const void *, const void *) =
686 {
687   { non_numeric_forward, non_numeric_reverse },
688   { numeric_forward, numeric_reverse }
689 };
690 
691 /* This sort routine is used by sort_symbols_by_size.  It is similar
692    to numeric_forward, but when symbols have the same value it sorts
693    by section VMA.  This simplifies the sort_symbols_by_size code
694    which handles symbols at the end of sections.  Also, this routine
695    tries to sort file names before other symbols with the same value.
696    That will make the file name have a zero size, which will make
697    sort_symbols_by_size choose the non file name symbol, leading to
698    more meaningful output.  For similar reasons, this code sorts
699    gnu_compiled_* and gcc2_compiled before other symbols with the same
700    value.  */
701 
702 static int
size_forward1(const void * P_x,const void * P_y)703 size_forward1 (const void *P_x, const void *P_y)
704 {
705   asymbol *x, *y;
706   asection *xs, *ys;
707   const char *xn, *yn;
708   size_t xnl, ynl;
709   int xf, yf;
710 
711   x = bfd_minisymbol_to_symbol (sort_bfd, sort_dynamic, P_x, sort_x);
712   y = bfd_minisymbol_to_symbol (sort_bfd, sort_dynamic, P_y, sort_y);
713   if (x == NULL || y == NULL)
714     bfd_fatal (bfd_get_filename (sort_bfd));
715 
716   xs = bfd_asymbol_section (x);
717   ys = bfd_asymbol_section (y);
718 
719   if (bfd_is_und_section (xs))
720     abort ();
721   if (bfd_is_und_section (ys))
722     abort ();
723 
724   if (valueof (x) != valueof (y))
725     return valueof (x) < valueof (y) ? -1 : 1;
726 
727   if (xs->vma != ys->vma)
728     return xs->vma < ys->vma ? -1 : 1;
729 
730   xn = bfd_asymbol_name (x);
731   yn = bfd_asymbol_name (y);
732   xnl = strlen (xn);
733   ynl = strlen (yn);
734 
735   /* The symbols gnu_compiled and gcc2_compiled convey even less
736      information than the file name, so sort them out first.  */
737 
738   xf = (strstr (xn, "gnu_compiled") != NULL
739 	|| strstr (xn, "gcc2_compiled") != NULL);
740   yf = (strstr (yn, "gnu_compiled") != NULL
741 	|| strstr (yn, "gcc2_compiled") != NULL);
742 
743   if (xf && ! yf)
744     return -1;
745   if (! xf && yf)
746     return 1;
747 
748   /* We use a heuristic for the file name.  It may not work on non
749      Unix systems, but it doesn't really matter; the only difference
750      is precisely which symbol names get printed.  */
751 
752 #define file_symbol(s, sn, snl)			\
753   (((s)->flags & BSF_FILE) != 0			\
754    || ((snl) > 2				\
755        && (sn)[(snl) - 2] == '.'		\
756        && ((sn)[(snl) - 1] == 'o'		\
757 	   || (sn)[(snl) - 1] == 'a')))
758 
759   xf = file_symbol (x, xn, xnl);
760   yf = file_symbol (y, yn, ynl);
761 
762   if (xf && ! yf)
763     return -1;
764   if (! xf && yf)
765     return 1;
766 
767   return non_numeric_forward (P_x, P_y);
768 }
769 
770 /* This sort routine is used by sort_symbols_by_size.  It is sorting
771    an array of size_sym structures into size order.  */
772 
773 static int
size_forward2(const void * P_x,const void * P_y)774 size_forward2 (const void *P_x, const void *P_y)
775 {
776   const struct size_sym *x = (const struct size_sym *) P_x;
777   const struct size_sym *y = (const struct size_sym *) P_y;
778 
779   if (x->size < y->size)
780     return reverse_sort ? 1 : -1;
781   else if (x->size > y->size)
782     return reverse_sort ? -1 : 1;
783   else
784     return sorters[0][reverse_sort] (x->minisym, y->minisym);
785 }
786 
787 /* Sort the symbols by size.  ELF provides a size but for other formats
788    we have to make a guess by assuming that the difference between the
789    address of a symbol and the address of the next higher symbol is the
790    size.  */
791 
792 static long
sort_symbols_by_size(bfd * abfd,bool is_dynamic,void * minisyms,long symcount,unsigned int size,struct size_sym ** symsizesp)793 sort_symbols_by_size (bfd *abfd, bool is_dynamic, void *minisyms,
794 		      long symcount, unsigned int size,
795 		      struct size_sym **symsizesp)
796 {
797   struct size_sym *symsizes;
798   bfd_byte *from, *fromend;
799   asymbol *sym = NULL;
800   asymbol *store_sym, *store_next;
801 
802   qsort (minisyms, symcount, size, size_forward1);
803 
804   /* We are going to return a special set of symbols and sizes to
805      print.  */
806   symsizes = (struct size_sym *) xmalloc (symcount * sizeof (struct size_sym));
807   *symsizesp = symsizes;
808 
809   /* Note that filter_symbols has already removed all absolute and
810      undefined symbols.  Here we remove all symbols whose size winds
811      up as zero.  */
812   from = (bfd_byte *) minisyms;
813   fromend = from + symcount * size;
814 
815   store_sym = sort_x;
816   store_next = sort_y;
817 
818   if (from < fromend)
819     {
820       sym = bfd_minisymbol_to_symbol (abfd, is_dynamic, (const void *) from,
821 				      store_sym);
822       if (sym == NULL)
823 	bfd_fatal (bfd_get_filename (abfd));
824     }
825 
826   for (; from < fromend; from += size)
827     {
828       asymbol *next;
829       asection *sec;
830       bfd_vma sz;
831       asymbol *temp;
832 
833       if (from + size < fromend)
834 	{
835 	  next = bfd_minisymbol_to_symbol (abfd,
836 					   is_dynamic,
837 					   (const void *) (from + size),
838 					   store_next);
839 	  if (next == NULL)
840 	    bfd_fatal (bfd_get_filename (abfd));
841 	}
842       else
843 	next = NULL;
844 
845       sec = bfd_asymbol_section (sym);
846 
847       /* Synthetic symbols don't have a full type set of data available, thus
848 	 we can't rely on that information for the symbol size.  Ditto for
849 	 bfd/section.c:global_syms like *ABS*.  */
850       if ((sym->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) == 0
851 	  && bfd_get_flavour (abfd) == bfd_target_elf_flavour)
852 	sz = ((elf_symbol_type *) sym)->internal_elf_sym.st_size;
853       else if ((sym->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) == 0
854 	       && bfd_is_com_section (sec))
855 	sz = sym->value;
856       else
857 	{
858 	  if (from + size < fromend
859 	      && sec == bfd_asymbol_section (next))
860 	    sz = valueof (next) - valueof (sym);
861 	  else
862 	    sz = (bfd_section_vma (sec)
863 		  + bfd_section_size (sec)
864 		  - valueof (sym));
865 	}
866 
867       if (sz != 0)
868 	{
869 	  symsizes->minisym = (const void *) from;
870 	  symsizes->size = sz;
871 	  ++symsizes;
872 	}
873 
874       sym = next;
875 
876       temp = store_sym;
877       store_sym = store_next;
878       store_next = temp;
879     }
880 
881   symcount = symsizes - *symsizesp;
882 
883   /* We must now sort again by size.  */
884   qsort ((void *) *symsizesp, symcount, sizeof (struct size_sym), size_forward2);
885 
886   return symcount;
887 }
888 
889 /* This function is used to get the relocs for a particular section.
890    It is called via bfd_map_over_sections.  */
891 
892 static void
get_relocs(bfd * abfd,asection * sec,void * dataarg)893 get_relocs (bfd *abfd, asection *sec, void *dataarg)
894 {
895   struct get_relocs_info *data = (struct get_relocs_info *) dataarg;
896 
897   *data->secs = sec;
898 
899   if ((sec->flags & SEC_RELOC) == 0)
900     {
901       *data->relocs = NULL;
902       *data->relcount = 0;
903     }
904   else
905     {
906       long relsize;
907 
908       relsize = bfd_get_reloc_upper_bound (abfd, sec);
909       if (relsize < 0)
910 	bfd_fatal (bfd_get_filename (abfd));
911 
912       *data->relocs = (arelent **) xmalloc (relsize);
913       *data->relcount = bfd_canonicalize_reloc (abfd, sec, *data->relocs,
914 						data->syms);
915       if (*data->relcount < 0)
916 	bfd_fatal (bfd_get_filename (abfd));
917     }
918 
919   ++data->secs;
920   ++data->relocs;
921   ++data->relcount;
922 }
923 
924 /* Print a single symbol.  */
925 
926 static void
print_symbol(bfd * abfd,asymbol * sym,bfd_vma ssize,bfd * archive_bfd)927 print_symbol (bfd *        abfd,
928 	      asymbol *    sym,
929 	      bfd_vma      ssize,
930 	      bfd *        archive_bfd)
931 {
932   symbol_info syminfo;
933   struct extended_symbol_info info;
934 
935   PROGRESS (1);
936 
937   format->print_symbol_filename (archive_bfd, abfd);
938 
939   bfd_get_symbol_info (abfd, sym, &syminfo);
940 
941   /* PR 22967 - Distinguish between local and global ifunc symbols.  */
942   if (syminfo.type == 'i'
943       && sym->flags & BSF_GNU_INDIRECT_FUNCTION)
944     {
945       if (ifunc_type_chars == NULL || ifunc_type_chars[0] == 0)
946 	; /* Change nothing.  */
947       else if (sym->flags & BSF_GLOBAL)
948 	syminfo.type = ifunc_type_chars[0];
949       else if (ifunc_type_chars[1] != 0)
950 	syminfo.type = ifunc_type_chars[1];
951     }
952 
953   info.sinfo = &syminfo;
954   info.ssize = ssize;
955   /* Synthetic symbols do not have a full symbol type set of data available.
956      Nor do bfd/section.c:global_syms like *ABS*.  */
957   if ((sym->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) != 0)
958     {
959       info.elfinfo = NULL;
960       info.coffinfo = NULL;
961     }
962   else
963     {
964       info.elfinfo = elf_symbol_from (sym);
965       info.coffinfo = coff_symbol_from (sym);
966     }
967 
968   format->print_symbol_info (&info, abfd);
969 
970   if (line_numbers)
971     {
972       static asymbol **syms;
973       static long symcount;
974       const char *filename, *functionname;
975       unsigned int lineno;
976 
977       /* We need to get the canonical symbols in order to call
978          bfd_find_nearest_line.  This is inefficient, but, then, you
979          don't have to use --line-numbers.  */
980       if (abfd != lineno_cache_bfd && syms != NULL)
981 	{
982 	  free (syms);
983 	  syms = NULL;
984 	}
985       if (syms == NULL)
986 	{
987 	  long symsize;
988 
989 	  symsize = bfd_get_symtab_upper_bound (abfd);
990 	  if (symsize < 0)
991 	    bfd_fatal (bfd_get_filename (abfd));
992 	  syms = (asymbol **) xmalloc (symsize);
993 	  symcount = bfd_canonicalize_symtab (abfd, syms);
994 	  if (symcount < 0)
995 	    bfd_fatal (bfd_get_filename (abfd));
996 	  lineno_cache_bfd = abfd;
997 	}
998 
999       if (bfd_is_und_section (bfd_asymbol_section (sym)))
1000 	{
1001 	  static asection **secs;
1002 	  static arelent ***relocs;
1003 	  static long *relcount;
1004 	  static unsigned int seccount;
1005 	  unsigned int i;
1006 	  const char *symname;
1007 
1008 	  /* For an undefined symbol, we try to find a reloc for the
1009              symbol, and print the line number of the reloc.  */
1010 	  if (abfd != lineno_cache_rel_bfd && relocs != NULL)
1011 	    {
1012 	      for (i = 0; i < seccount; i++)
1013 		if (relocs[i] != NULL)
1014 		  free (relocs[i]);
1015 	      free (secs);
1016 	      free (relocs);
1017 	      free (relcount);
1018 	      secs = NULL;
1019 	      relocs = NULL;
1020 	      relcount = NULL;
1021 	    }
1022 
1023 	  if (relocs == NULL)
1024 	    {
1025 	      struct get_relocs_info rinfo;
1026 
1027 	      seccount = bfd_count_sections (abfd);
1028 
1029 	      secs = (asection **) xmalloc (seccount * sizeof *secs);
1030 	      relocs = (arelent ***) xmalloc (seccount * sizeof *relocs);
1031 	      relcount = (long *) xmalloc (seccount * sizeof *relcount);
1032 
1033 	      rinfo.secs = secs;
1034 	      rinfo.relocs = relocs;
1035 	      rinfo.relcount = relcount;
1036 	      rinfo.syms = syms;
1037 	      bfd_map_over_sections (abfd, get_relocs, (void *) &rinfo);
1038 	      lineno_cache_rel_bfd = abfd;
1039 	    }
1040 
1041 	  symname = bfd_asymbol_name (sym);
1042 	  for (i = 0; i < seccount; i++)
1043 	    {
1044 	      long j;
1045 
1046 	      for (j = 0; j < relcount[i]; j++)
1047 		{
1048 		  arelent *r;
1049 
1050 		  r = relocs[i][j];
1051 		  if (r->sym_ptr_ptr != NULL
1052 		      && (*r->sym_ptr_ptr)->section == sym->section
1053 		      && (*r->sym_ptr_ptr)->value == sym->value
1054 		      && strcmp (symname,
1055 				 bfd_asymbol_name (*r->sym_ptr_ptr)) == 0
1056 		      && bfd_find_nearest_line (abfd, secs[i], syms,
1057 						r->address, &filename,
1058 						&functionname, &lineno)
1059 		      && filename != NULL)
1060 		    {
1061 		      /* We only print the first one we find.  */
1062 		      printf ("\t%s:%u", filename, lineno);
1063 		      i = seccount;
1064 		      break;
1065 		    }
1066 		}
1067 	    }
1068 	}
1069       else if (bfd_asymbol_section (sym)->owner == abfd)
1070 	{
1071 	  if ((bfd_find_line (abfd, syms, sym, &filename, &lineno)
1072 	       || bfd_find_nearest_line (abfd, bfd_asymbol_section (sym),
1073 					 syms, sym->value, &filename,
1074 					 &functionname, &lineno))
1075 	      && filename != NULL
1076 	      && lineno != 0)
1077 	    printf ("\t%s:%u", filename, lineno);
1078 	}
1079     }
1080 
1081   putchar ('\n');
1082 }
1083 
1084 /* Print the symbols when sorting by size.  */
1085 
1086 static void
print_size_symbols(bfd * abfd,bool is_dynamic,struct size_sym * symsizes,long symcount,bfd * archive_bfd)1087 print_size_symbols (bfd *abfd,
1088 		    bool is_dynamic,
1089 		    struct size_sym *symsizes,
1090 		    long symcount,
1091 		    bfd *archive_bfd)
1092 {
1093   asymbol *store;
1094   struct size_sym *from;
1095   struct size_sym *fromend;
1096 
1097   store = bfd_make_empty_symbol (abfd);
1098   if (store == NULL)
1099     bfd_fatal (bfd_get_filename (abfd));
1100 
1101   from = symsizes;
1102   fromend = from + symcount;
1103 
1104   for (; from < fromend; from++)
1105     {
1106       asymbol *sym;
1107 
1108       sym = bfd_minisymbol_to_symbol (abfd, is_dynamic, from->minisym, store);
1109       if (sym == NULL)
1110 	bfd_fatal (bfd_get_filename (abfd));
1111 
1112       print_symbol (abfd, sym, from->size, archive_bfd);
1113     }
1114 }
1115 
1116 
1117 /* Print the symbols of ABFD that are held in MINISYMS.
1118 
1119    If ARCHIVE_BFD is non-NULL, it is the archive containing ABFD.
1120 
1121    SYMCOUNT is the number of symbols in MINISYMS.
1122 
1123    SIZE is the size of a symbol in MINISYMS.  */
1124 
1125 static void
print_symbols(bfd * abfd,bool is_dynamic,void * minisyms,long symcount,unsigned int size,bfd * archive_bfd)1126 print_symbols (bfd *abfd,
1127 	       bool is_dynamic,
1128 	       void *minisyms,
1129 	       long symcount,
1130 	       unsigned int size,
1131 	       bfd *archive_bfd)
1132 {
1133   asymbol *store;
1134   bfd_byte *from;
1135   bfd_byte *fromend;
1136 
1137   store = bfd_make_empty_symbol (abfd);
1138   if (store == NULL)
1139     bfd_fatal (bfd_get_filename (abfd));
1140 
1141   from = (bfd_byte *) minisyms;
1142   fromend = from + symcount * size;
1143 
1144   for (; from < fromend; from += size)
1145     {
1146       asymbol *sym;
1147 
1148       sym = bfd_minisymbol_to_symbol (abfd, is_dynamic, from, store);
1149       if (sym == NULL)
1150 	bfd_fatal (bfd_get_filename (abfd));
1151 
1152       print_symbol (abfd, sym, (bfd_vma) 0, archive_bfd);
1153     }
1154 }
1155 
1156 /* If ARCHIVE_BFD is non-NULL, it is the archive containing ABFD.  */
1157 
1158 static void
display_rel_file(bfd * abfd,bfd * archive_bfd)1159 display_rel_file (bfd *abfd, bfd *archive_bfd)
1160 {
1161   long symcount;
1162   void *minisyms;
1163   unsigned int size;
1164   struct size_sym *symsizes;
1165   asymbol *synthsyms = NULL;
1166 
1167   if (! dynamic)
1168     {
1169       if (!(bfd_get_file_flags (abfd) & HAS_SYMS))
1170 	{
1171 	  if (!quiet)
1172 	    non_fatal (_("%s: no symbols"), bfd_get_filename (abfd));
1173 	  return;
1174 	}
1175     }
1176 
1177   symcount = bfd_read_minisymbols (abfd, dynamic, &minisyms, &size);
1178   if (symcount < 0)
1179     {
1180       if (dynamic && bfd_get_error () == bfd_error_no_symbols)
1181 	{
1182 	  if (!quiet)
1183 	    non_fatal (_("%s: no symbols"), bfd_get_filename (abfd));
1184 	  return;
1185 	}
1186 
1187       bfd_fatal (bfd_get_filename (abfd));
1188     }
1189 
1190   if (symcount == 0)
1191     {
1192       if (!quiet)
1193 	non_fatal (_("%s: no symbols"), bfd_get_filename (abfd));
1194       return;
1195     }
1196 
1197   if (show_synthetic && size == sizeof (asymbol *))
1198     {
1199       asymbol **static_syms = NULL;
1200       asymbol **dyn_syms = NULL;
1201       long static_count = 0;
1202       long dyn_count = 0;
1203       long synth_count;
1204 
1205       if (dynamic)
1206 	{
1207 	  dyn_count = symcount;
1208 	  dyn_syms = (asymbol **) minisyms;
1209 	}
1210       else
1211 	{
1212 	  long storage = bfd_get_dynamic_symtab_upper_bound (abfd);
1213 
1214 	  static_count = symcount;
1215 	  static_syms = (asymbol **) minisyms;
1216 
1217 	  if (storage > 0)
1218 	    {
1219 	      dyn_syms = (asymbol **) xmalloc (storage);
1220 	      dyn_count = bfd_canonicalize_dynamic_symtab (abfd, dyn_syms);
1221 	      if (dyn_count < 0)
1222 		bfd_fatal (bfd_get_filename (abfd));
1223 	    }
1224 	}
1225 
1226       synth_count = bfd_get_synthetic_symtab (abfd, static_count, static_syms,
1227 					      dyn_count, dyn_syms, &synthsyms);
1228       if (synth_count > 0)
1229 	{
1230 	  asymbol **symp;
1231 	  long i;
1232 
1233 	  minisyms = xrealloc (minisyms,
1234 			       (symcount + synth_count + 1) * sizeof (*symp));
1235 	  symp = (asymbol **) minisyms + symcount;
1236 	  for (i = 0; i < synth_count; i++)
1237 	    *symp++ = synthsyms + i;
1238 	  *symp = 0;
1239 	  symcount += synth_count;
1240 	}
1241       if (!dynamic && dyn_syms != NULL)
1242 	free (dyn_syms);
1243     }
1244 
1245   /* lto_slim_object is set to false when a bfd is loaded with a compiler
1246      LTO plugin.  */
1247   if (abfd->lto_slim_object)
1248     {
1249       report_plugin_err = false;
1250       non_fatal (_("%s: plugin needed to handle lto object"),
1251 		 bfd_get_filename (abfd));
1252     }
1253 
1254   /* Discard the symbols we don't want to print.
1255      It's OK to do this in place; we'll free the storage anyway
1256      (after printing).  */
1257 
1258   symcount = filter_symbols (abfd, dynamic, minisyms, symcount, size);
1259 
1260   symsizes = NULL;
1261   if (! no_sort)
1262     {
1263       sort_bfd = abfd;
1264       sort_dynamic = dynamic;
1265       sort_x = bfd_make_empty_symbol (abfd);
1266       sort_y = bfd_make_empty_symbol (abfd);
1267       if (sort_x == NULL || sort_y == NULL)
1268 	bfd_fatal (bfd_get_filename (abfd));
1269 
1270       if (! sort_by_size)
1271 	qsort (minisyms, symcount, size,
1272 	       sorters[sort_numerically][reverse_sort]);
1273       else
1274 	symcount = sort_symbols_by_size (abfd, dynamic, minisyms, symcount,
1275 					 size, &symsizes);
1276     }
1277 
1278   if (! sort_by_size)
1279     print_symbols (abfd, dynamic, minisyms, symcount, size, archive_bfd);
1280   else
1281     print_size_symbols (abfd, dynamic, symsizes, symcount, archive_bfd);
1282 
1283   if (synthsyms)
1284     free (synthsyms);
1285   free (minisyms);
1286   free (symsizes);
1287 }
1288 
1289 /* Construct a formatting string for printing symbol values.  */
1290 
1291 static const char *
get_print_format(void)1292 get_print_format (void)
1293 {
1294   const char * padding;
1295   if (print_format == FORMAT_POSIX || print_format == FORMAT_JUST_SYMBOLS)
1296     {
1297       /* POSIX compatible output does not have any padding.  */
1298       padding = "";
1299     }
1300   else if (print_width == 32)
1301     {
1302       padding ="08";
1303     }
1304   else /* print_width == 64 */
1305     {
1306       padding = "016";
1307     }
1308 
1309   const char * length = "l";
1310   if (print_width == 64)
1311     {
1312 #if BFD_HOST_64BIT_LONG
1313       ;
1314 #elif BFD_HOST_64BIT_LONG_LONG
1315 #ifndef __MSVCRT__
1316       length = "ll";
1317 #else
1318       length = "I64";
1319 #endif
1320 #endif
1321     }
1322 
1323   const char * radix = NULL;
1324   switch (print_radix)
1325     {
1326     case 8:  radix = "o"; break;
1327     case 10: radix = "d"; break;
1328     case 16: radix = "x"; break;
1329     }
1330 
1331   return concat ("%", padding, length, radix, NULL);
1332 }
1333 
1334 static void
set_print_width(bfd * file)1335 set_print_width (bfd *file)
1336 {
1337   print_width = bfd_get_arch_size (file);
1338 
1339   if (print_width == -1)
1340     {
1341       /* PR binutils/4292
1342 	 Guess the target's bitsize based on its name.
1343 	 We assume here than any 64-bit format will include
1344 	 "64" somewhere in its name.  The only known exception
1345 	 is the MMO object file format.  */
1346       if (strstr (bfd_get_target (file), "64") != NULL
1347 	  || strcmp (bfd_get_target (file), "mmo") == 0)
1348 	print_width = 64;
1349       else
1350 	print_width = 32;
1351     }
1352   free ((char *) print_format_string);
1353   print_format_string = get_print_format ();
1354 }
1355 
1356 static void
display_archive(bfd * file)1357 display_archive (bfd *file)
1358 {
1359   bfd *arfile = NULL;
1360   bfd *last_arfile = NULL;
1361   char **matching;
1362 
1363   format->print_archive_filename (bfd_get_filename (file));
1364 
1365   if (print_armap)
1366     print_symdef_entry (file);
1367 
1368   for (;;)
1369     {
1370       PROGRESS (1);
1371 
1372       arfile = bfd_openr_next_archived_file (file, arfile);
1373 
1374       if (arfile == NULL)
1375 	{
1376 	  if (bfd_get_error () != bfd_error_no_more_archived_files)
1377 	    bfd_fatal (bfd_get_filename (file));
1378 	  break;
1379 	}
1380 
1381       if (bfd_check_format_matches (arfile, bfd_object, &matching))
1382 	{
1383 	  set_print_width (arfile);
1384 	  format->print_archive_member (bfd_get_filename (file),
1385 					bfd_get_filename (arfile));
1386 	  display_rel_file (arfile, file);
1387 	}
1388       else
1389 	{
1390 	  bfd_nonfatal (bfd_get_filename (arfile));
1391 	  if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
1392 	    {
1393 	      list_matching_formats (matching);
1394 	      free (matching);
1395 	    }
1396 	}
1397 
1398       if (last_arfile != NULL)
1399 	{
1400 	  bfd_close (last_arfile);
1401 	  lineno_cache_bfd = NULL;
1402 	  lineno_cache_rel_bfd = NULL;
1403 	  if (arfile == last_arfile)
1404 	    return;
1405 	}
1406       last_arfile = arfile;
1407     }
1408 
1409   if (last_arfile != NULL)
1410     {
1411       bfd_close (last_arfile);
1412       lineno_cache_bfd = NULL;
1413       lineno_cache_rel_bfd = NULL;
1414     }
1415 }
1416 
1417 static bool
display_file(char * filename)1418 display_file (char *filename)
1419 {
1420   bool retval = true;
1421   bfd *file;
1422   char **matching;
1423 
1424   if (get_file_size (filename) < 1)
1425     return false;
1426 
1427   file = bfd_openr (filename, target ? target : plugin_target);
1428   if (file == NULL)
1429     {
1430       bfd_nonfatal (filename);
1431       return false;
1432     }
1433 
1434   /* If printing line numbers, decompress the debug sections.  */
1435   if (line_numbers)
1436     file->flags |= BFD_DECOMPRESS;
1437 
1438   if (bfd_check_format (file, bfd_archive))
1439     {
1440       display_archive (file);
1441     }
1442   else if (bfd_check_format_matches (file, bfd_object, &matching))
1443     {
1444       set_print_width (file);
1445       format->print_object_filename (filename);
1446       display_rel_file (file, NULL);
1447     }
1448   else
1449     {
1450       bfd_nonfatal (filename);
1451       if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
1452 	{
1453 	  list_matching_formats (matching);
1454 	  free (matching);
1455 	}
1456       retval = false;
1457     }
1458 
1459   if (!bfd_close (file))
1460     bfd_fatal (filename);
1461 
1462   lineno_cache_bfd = NULL;
1463   lineno_cache_rel_bfd = NULL;
1464 
1465   return retval;
1466 }
1467 
1468 /* The following 3 groups of functions are called unconditionally,
1469    once at the start of processing each file of the appropriate type.
1470    They should check `filename_per_file' and `filename_per_symbol',
1471    as appropriate for their output format, to determine whether to
1472    print anything.  */
1473 
1474 /* Print the name of an object file given on the command line.  */
1475 
1476 static void
print_object_filename_bsd(const char * filename)1477 print_object_filename_bsd (const char *filename)
1478 {
1479   if (filename_per_file && !filename_per_symbol)
1480     printf ("\n%s:\n", filename);
1481 }
1482 
1483 static void
print_object_filename_sysv(const char * filename)1484 print_object_filename_sysv (const char *filename)
1485 {
1486   if (undefined_only)
1487     printf (_("\n\nUndefined symbols from %s:\n\n"), filename);
1488   else
1489     printf (_("\n\nSymbols from %s:\n\n"), filename);
1490   if (print_width == 32)
1491     printf (_("\
1492 Name                  Value   Class        Type         Size     Line  Section\n\n"));
1493   else
1494     printf (_("\
1495 Name                  Value           Class        Type         Size             Line  Section\n\n"));
1496 }
1497 
1498 static void
print_object_filename_posix(const char * filename)1499 print_object_filename_posix (const char *filename)
1500 {
1501   if (filename_per_file && !filename_per_symbol)
1502     printf ("%s:\n", filename);
1503 }
1504 
1505 static void
do_not_print_object_filename(const char * filename ATTRIBUTE_UNUSED)1506 do_not_print_object_filename (const char *filename ATTRIBUTE_UNUSED)
1507 {
1508 }
1509 
1510 /* Print the name of an archive file given on the command line.  */
1511 
1512 static void
print_archive_filename_bsd(const char * filename)1513 print_archive_filename_bsd (const char *filename)
1514 {
1515   if (filename_per_file)
1516     printf ("\n%s:\n", filename);
1517 }
1518 
1519 static void
print_archive_filename_sysv(const char * filename ATTRIBUTE_UNUSED)1520 print_archive_filename_sysv (const char *filename ATTRIBUTE_UNUSED)
1521 {
1522 }
1523 
1524 static void
print_archive_filename_posix(const char * filename ATTRIBUTE_UNUSED)1525 print_archive_filename_posix (const char *filename ATTRIBUTE_UNUSED)
1526 {
1527 }
1528 
1529 static void
do_not_print_archive_filename(const char * filename ATTRIBUTE_UNUSED)1530 do_not_print_archive_filename (const char *filename ATTRIBUTE_UNUSED)
1531 {
1532 }
1533 
1534 /* Print the name of an archive member file.  */
1535 
1536 static void
print_archive_member_bsd(const char * archive ATTRIBUTE_UNUSED,const char * filename)1537 print_archive_member_bsd (const char *archive ATTRIBUTE_UNUSED,
1538 			  const char *filename)
1539 {
1540   if (!filename_per_symbol)
1541     printf ("\n%s:\n", filename);
1542 }
1543 
1544 static void
print_archive_member_sysv(const char * archive,const char * filename)1545 print_archive_member_sysv (const char *archive, const char *filename)
1546 {
1547   if (undefined_only)
1548     printf (_("\n\nUndefined symbols from %s[%s]:\n\n"), archive, filename);
1549   else
1550     printf (_("\n\nSymbols from %s[%s]:\n\n"), archive, filename);
1551   if (print_width == 32)
1552     printf (_("\
1553 Name                  Value   Class        Type         Size     Line  Section\n\n"));
1554   else
1555     printf (_("\
1556 Name                  Value           Class        Type         Size             Line  Section\n\n"));
1557 }
1558 
1559 static void
print_archive_member_posix(const char * archive,const char * filename)1560 print_archive_member_posix (const char *archive, const char *filename)
1561 {
1562   if (!filename_per_symbol)
1563     printf ("%s[%s]:\n", archive, filename);
1564 }
1565 
1566 static void
do_not_print_archive_member(const char * archive ATTRIBUTE_UNUSED,const char * filename ATTRIBUTE_UNUSED)1567 do_not_print_archive_member (const char *archive ATTRIBUTE_UNUSED,
1568 			     const char *filename ATTRIBUTE_UNUSED)
1569 {
1570 }
1571 
1572 
1573 /* Print the name of the file (and archive, if there is one)
1574    containing a symbol.  */
1575 
1576 static void
print_symbol_filename_bsd(bfd * archive_bfd,bfd * abfd)1577 print_symbol_filename_bsd (bfd *archive_bfd, bfd *abfd)
1578 {
1579   if (filename_per_symbol)
1580     {
1581       if (archive_bfd)
1582 	printf ("%s:", bfd_get_filename (archive_bfd));
1583       printf ("%s:", bfd_get_filename (abfd));
1584     }
1585 }
1586 
1587 static void
print_symbol_filename_sysv(bfd * archive_bfd,bfd * abfd)1588 print_symbol_filename_sysv (bfd *archive_bfd, bfd *abfd)
1589 {
1590   if (filename_per_symbol)
1591     {
1592       if (archive_bfd)
1593 	printf ("%s:", bfd_get_filename (archive_bfd));
1594       printf ("%s:", bfd_get_filename (abfd));
1595     }
1596 }
1597 
1598 static void
print_symbol_filename_posix(bfd * archive_bfd,bfd * abfd)1599 print_symbol_filename_posix (bfd *archive_bfd, bfd *abfd)
1600 {
1601   if (filename_per_symbol)
1602     {
1603       if (archive_bfd)
1604 	printf ("%s[%s]: ", bfd_get_filename (archive_bfd),
1605 		bfd_get_filename (abfd));
1606       else
1607 	printf ("%s: ", bfd_get_filename (abfd));
1608     }
1609 }
1610 
1611 static void
do_not_print_symbol_filename(bfd * archive_bfd ATTRIBUTE_UNUSED,bfd * abfd ATTRIBUTE_UNUSED)1612 do_not_print_symbol_filename (bfd *archive_bfd ATTRIBUTE_UNUSED,
1613 			      bfd *abfd ATTRIBUTE_UNUSED)
1614 {
1615 }
1616 
1617 
1618 /* Print a symbol value.  */
1619 
1620 static void
print_value(bfd * abfd ATTRIBUTE_UNUSED,bfd_vma val)1621 print_value (bfd *abfd ATTRIBUTE_UNUSED, bfd_vma val)
1622 {
1623   switch (print_width)
1624     {
1625     case 32:
1626       printf (print_format_string, (unsigned long) val);
1627       break;
1628 
1629     case 64:
1630 #if BFD_HOST_64BIT_LONG || BFD_HOST_64BIT_LONG_LONG
1631       printf (print_format_string, val);
1632 #else
1633       /* We have a 64 bit value to print, but the host is only 32 bit.  */
1634       if (print_radix == 16)
1635 	bfd_fprintf_vma (abfd, stdout, val);
1636       else
1637 	{
1638 	  char buf[30];
1639 	  char *s;
1640 
1641 	  s = buf + sizeof buf;
1642 	  *--s = '\0';
1643 	  while (val > 0)
1644 	    {
1645 	      *--s = (val % print_radix) + '0';
1646 	      val /= print_radix;
1647 	    }
1648 	  while ((buf + sizeof buf - 1) - s < 16)
1649 	    *--s = '0';
1650 	  printf ("%s", s);
1651 	}
1652 #endif
1653       break;
1654 
1655     default:
1656       fatal (_("Print width has not been initialized (%d)"), print_width);
1657       break;
1658     }
1659 }
1660 
1661 /* Print a line of information about a symbol.  */
1662 
1663 static void
print_symbol_info_bsd(struct extended_symbol_info * info,bfd * abfd)1664 print_symbol_info_bsd (struct extended_symbol_info *info, bfd *abfd)
1665 {
1666   if (bfd_is_undefined_symclass (SYM_TYPE (info)))
1667     {
1668       if (print_width == 64)
1669 	printf ("        ");
1670       printf ("        ");
1671     }
1672   else
1673     {
1674       /* Normally we print the value of the symbol.  If we are printing the
1675 	 size or sorting by size then we print its size, except for the
1676 	 (weird) special case where both flags are defined, in which case we
1677 	 print both values.  This conforms to documented behaviour.  */
1678       if (sort_by_size && !print_size)
1679 	print_value (abfd, SYM_SIZE (info));
1680       else
1681 	print_value (abfd, SYM_VALUE (info));
1682       if (print_size && SYM_SIZE (info))
1683 	{
1684 	  printf (" ");
1685 	  print_value (abfd, SYM_SIZE (info));
1686 	}
1687     }
1688 
1689   printf (" %c", SYM_TYPE (info));
1690 
1691   if (SYM_TYPE (info) == '-')
1692     {
1693       /* A stab.  */
1694       printf (" ");
1695       printf (other_format, SYM_STAB_OTHER (info));
1696       printf (" ");
1697       printf (desc_format, SYM_STAB_DESC (info));
1698       printf (" %5s", SYM_STAB_NAME (info));
1699     }
1700   print_symname (" %s", info, NULL, abfd);
1701 }
1702 
1703 static void
print_symbol_info_sysv(struct extended_symbol_info * info,bfd * abfd)1704 print_symbol_info_sysv (struct extended_symbol_info *info, bfd *abfd)
1705 {
1706   print_symname ("%-20s|", info, NULL, abfd);
1707 
1708   if (bfd_is_undefined_symclass (SYM_TYPE (info)))
1709     {
1710       if (print_width == 32)
1711 	printf ("        ");
1712       else
1713 	printf ("                ");
1714     }
1715   else
1716     print_value (abfd, SYM_VALUE (info));
1717 
1718   printf ("|   %c  |", SYM_TYPE (info));
1719 
1720   if (SYM_TYPE (info) == '-')
1721     {
1722       /* A stab.  */
1723       printf ("%18s|  ", SYM_STAB_NAME (info));		/* (C) Type.  */
1724       printf (desc_format, SYM_STAB_DESC (info));	/* Size.  */
1725       printf ("|     |");				/* Line, Section.  */
1726     }
1727   else
1728     {
1729       /* Type, Size, Line, Section */
1730       if (info->elfinfo)
1731 	printf ("%18s|",
1732 		get_elf_symbol_type (ELF_ST_TYPE (info->elfinfo->internal_elf_sym.st_info)));
1733       else if (info->coffinfo)
1734 	printf ("%18s|",
1735 		get_coff_symbol_type (&info->coffinfo->native->u.syment));
1736       else
1737 	printf ("                  |");
1738 
1739       if (SYM_SIZE (info))
1740 	print_value (abfd, SYM_SIZE (info));
1741       else
1742 	{
1743 	  if (print_width == 32)
1744 	    printf ("        ");
1745 	  else
1746 	    printf ("                ");
1747 	}
1748 
1749       if (info->elfinfo)
1750 	printf("|     |%s", info->elfinfo->symbol.section->name);
1751       else if (info->coffinfo)
1752 	printf("|     |%s", info->coffinfo->symbol.section->name);
1753       else
1754 	printf("|     |");
1755     }
1756 }
1757 
1758 static void
print_symbol_info_posix(struct extended_symbol_info * info,bfd * abfd)1759 print_symbol_info_posix (struct extended_symbol_info *info, bfd *abfd)
1760 {
1761   print_symname ("%s ", info, NULL, abfd);
1762   printf ("%c ", SYM_TYPE (info));
1763 
1764   if (bfd_is_undefined_symclass (SYM_TYPE (info)))
1765     printf ("        ");
1766   else
1767     {
1768       print_value (abfd, SYM_VALUE (info));
1769       printf (" ");
1770       if (SYM_SIZE (info))
1771 	print_value (abfd, SYM_SIZE (info));
1772     }
1773 }
1774 
1775 static void
just_print_symbol_name(struct extended_symbol_info * info,bfd * abfd)1776 just_print_symbol_name (struct extended_symbol_info *info, bfd *abfd)
1777 {
1778   print_symname ("%s", info, NULL, abfd);
1779 }
1780 
1781 int
main(int argc,char ** argv)1782 main (int argc, char **argv)
1783 {
1784   int c;
1785   int retval;
1786 
1787 #ifdef HAVE_LC_MESSAGES
1788   setlocale (LC_MESSAGES, "");
1789 #endif
1790   setlocale (LC_CTYPE, "");
1791   setlocale (LC_COLLATE, "");
1792   bindtextdomain (PACKAGE, LOCALEDIR);
1793   textdomain (PACKAGE);
1794 
1795   program_name = *argv;
1796   xmalloc_set_program_name (program_name);
1797   bfd_set_error_program_name (program_name);
1798 #if BFD_SUPPORTS_PLUGINS
1799   bfd_plugin_set_program_name (program_name);
1800 #endif
1801 
1802   START_PROGRESS (program_name, 0);
1803 
1804   expandargv (&argc, &argv);
1805 
1806   if (bfd_init () != BFD_INIT_MAGIC)
1807     fatal (_("fatal error: libbfd ABI mismatch"));
1808   set_default_bfd_target ();
1809 
1810   while ((c = getopt_long (argc, argv, "aABCDef:gHhjJlnopPrSst:uvVvX:",
1811 			   long_options, (int *) 0)) != EOF)
1812     {
1813       switch (c)
1814 	{
1815 	case 'a':
1816 	  print_debug_syms = 1;
1817 	  break;
1818 	case 'A':
1819 	case 'o':
1820 	  filename_per_symbol = 1;
1821 	  break;
1822 	case 'B':		/* For MIPS compatibility.  */
1823 	  set_output_format ("bsd");
1824 	  break;
1825 	case 'C':
1826 	  do_demangle = 1;
1827 	  if (optarg != NULL)
1828 	    {
1829 	      enum demangling_styles style;
1830 
1831 	      style = cplus_demangle_name_to_style (optarg);
1832 	      if (style == unknown_demangling)
1833 		fatal (_("unknown demangling style `%s'"),
1834 		       optarg);
1835 
1836 	      cplus_demangle_set_style (style);
1837 	    }
1838 	  break;
1839 	case OPTION_RECURSE_LIMIT:
1840 	  demangle_flags &= ~ DMGL_NO_RECURSE_LIMIT;
1841 	  break;
1842 	case OPTION_NO_RECURSE_LIMIT:
1843 	  demangle_flags |= DMGL_NO_RECURSE_LIMIT;
1844 	  break;
1845 	case OPTION_QUIET:
1846 	  quiet = 1;
1847 	  break;
1848 	case 'D':
1849 	  dynamic = 1;
1850 	  break;
1851 	case 'e':
1852 	  /* Ignored for HP/UX compatibility.  */
1853 	  break;
1854 	case 'f':
1855 	  set_output_format (optarg);
1856 	  break;
1857 	case 'g':
1858 	  external_only = 1;
1859 	  break;
1860 	case 'H':
1861 	case 'h':
1862 	  usage (stdout, 0);
1863 	case 'l':
1864 	  line_numbers = 1;
1865 	  break;
1866 	case 'n':
1867 	case 'v':
1868 	  no_sort = 0;
1869 	  sort_numerically = 1;
1870 	  sort_by_size = 0;
1871 	  break;
1872 	case 'p':
1873 	  no_sort = 1;
1874 	  sort_numerically = 0;
1875 	  sort_by_size = 0;
1876 	  break;
1877 	case OPTION_SIZE_SORT:
1878 	  no_sort = 0;
1879 	  sort_numerically = 0;
1880 	  sort_by_size = 1;
1881 	  break;
1882 	case 'P':
1883 	  set_output_format ("posix");
1884 	  break;
1885 	case 'j':
1886 	  set_output_format ("just-symbols");
1887 	  break;
1888 	case 'r':
1889 	  reverse_sort = 1;
1890 	  break;
1891 	case 's':
1892 	  print_armap = 1;
1893 	  break;
1894 	case 'S':
1895 	  print_size = 1;
1896 	  break;
1897 	case 't':
1898 	  set_print_radix (optarg);
1899 	  break;
1900 	case 'u':
1901 	  undefined_only = 1;
1902 	  break;
1903 	case 'V':
1904 	  show_version = 1;
1905 	  break;
1906 	case 'X':
1907 	  /* Ignored for (partial) AIX compatibility.  On AIX, the
1908 	     argument has values 32, 64, or 32_64, and specifies that
1909 	     only 32-bit, only 64-bit, or both kinds of objects should
1910 	     be examined.  The default is 32.  So plain AIX nm on a
1911 	     library archive with both kinds of objects will ignore
1912 	     the 64-bit ones.  For GNU nm, the default is and always
1913 	     has been -X 32_64, and other options are not supported.  */
1914 	  if (strcmp (optarg, "32_64") != 0)
1915 	    fatal (_("Only -X 32_64 is supported"));
1916 	  break;
1917 
1918 	case OPTION_TARGET:	/* --target */
1919 	  target = optarg;
1920 	  break;
1921 
1922 	case OPTION_PLUGIN:	/* --plugin */
1923 #if BFD_SUPPORTS_PLUGINS
1924 	  bfd_plugin_set_plugin (optarg);
1925 #else
1926 	  fatal (_("sorry - this program has been built without plugin support\n"));
1927 #endif
1928 	  break;
1929 
1930 	case OPTION_IFUNC_CHARS:
1931 	  ifunc_type_chars = optarg;
1932 	  break;
1933 
1934 	case 0:		/* A long option that just sets a flag.  */
1935 	  break;
1936 
1937 	default:
1938 	  usage (stderr, 1);
1939 	}
1940     }
1941 
1942   if (show_version)
1943     print_version ("nm");
1944 
1945   if (sort_by_size && undefined_only)
1946     {
1947       non_fatal (_("Using the --size-sort and --undefined-only options together"));
1948       non_fatal (_("will produce no output, since undefined symbols have no size."));
1949       return 0;
1950     }
1951 
1952   /* OK, all options now parsed.  If no filename specified, do a.out.  */
1953   if (optind == argc)
1954     return !display_file ("a.out");
1955 
1956   retval = 0;
1957 
1958   if (argc - optind > 1)
1959     filename_per_file = 1;
1960 
1961   /* We were given several filenames to do.  */
1962   while (optind < argc)
1963     {
1964       PROGRESS (1);
1965       if (!display_file (argv[optind++]))
1966 	retval++;
1967     }
1968 
1969   END_PROGRESS (program_name);
1970 
1971   exit (retval);
1972   return retval;
1973 }
1974