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