1/* Print symbol information from ELF file in human-readable form.
2   Copyright (C) 2000-2008, 2009, 2011, 2012, 2014 Red Hat, Inc.
3   This file is part of elfutils.
4   Written by Ulrich Drepper <drepper@redhat.com>, 2000.
5
6   This file 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   elfutils is distributed in the hope that it will be useful, but
12   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, see <http://www.gnu.org/licenses/>.  */
18
19#ifdef HAVE_CONFIG_H
20# include <config.h>
21#endif
22
23#include <ar.h>
24#include <argp.h>
25#include <assert.h>
26#include <ctype.h>
27#include <dwarf.h>
28#include <errno.h>
29#include <error.h>
30#include <fcntl.h>
31#include <gelf.h>
32#include <inttypes.h>
33#include <libdw.h>
34#include <libintl.h>
35#include <locale.h>
36#include <mcheck.h>
37#include <obstack.h>
38#include <search.h>
39#include <stdbool.h>
40#include <stdio.h>
41#include <stdio_ext.h>
42#include <stdlib.h>
43#include <string.h>
44#include <unistd.h>
45#include <sys/param.h>
46
47#include <system.h>
48#include "../libebl/libeblP.h"
49
50
51/* Name and version of program.  */
52static void print_version (FILE *stream, struct argp_state *state);
53ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
54
55/* Bug report address.  */
56ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
57
58
59/* Values for the parameters which have no short form.  */
60#define OPT_DEFINED		0x100
61#define OPT_MARK_SPECIAL	0x101
62
63/* Definitions of arguments for argp functions.  */
64static const struct argp_option options[] =
65{
66  { NULL, 0, NULL, 0, N_("Output selection:"), 0 },
67  { "debug-syms", 'a', NULL, 0, N_("Display debugger-only symbols"), 0 },
68  { "defined-only", OPT_DEFINED, NULL, 0, N_("Display only defined symbols"),
69    0 },
70  { "dynamic", 'D', NULL, 0,
71    N_("Display dynamic symbols instead of normal symbols"), 0 },
72  { "extern-only", 'g', NULL, 0, N_("Display only external symbols"), 0 },
73  { "undefined-only", 'u', NULL, 0, N_("Display only undefined symbols"), 0 },
74  { "print-armap", 's', NULL, 0,
75    N_("Include index for symbols from archive members"), 0 },
76
77  { NULL, 0, NULL, 0, N_("Output format:"), 0 },
78  { "print-file-name", 'A', NULL, 0,
79    N_("Print name of the input file before every symbol"), 0 },
80  { NULL, 'o', NULL, OPTION_HIDDEN, "Same as -A", 0 },
81  { "format", 'f', "FORMAT", 0,
82    N_("Use the output format FORMAT.  FORMAT can be `bsd', `sysv' or `posix'.  The default is `sysv'"),
83    0 },
84  { NULL, 'B', NULL, 0, N_("Same as --format=bsd"), 0 },
85  { "portability", 'P', NULL, 0, N_("Same as --format=posix"), 0 },
86  { "radix", 't', "RADIX", 0, N_("Use RADIX for printing symbol values"), 0 },
87  { "mark-special", OPT_MARK_SPECIAL, NULL, 0, N_("Mark special symbols"), 0 },
88  { "mark-weak", OPT_MARK_SPECIAL, NULL, OPTION_HIDDEN, "", 0 },
89  { "print-size", 'S', NULL, 0, N_("Print size of defined symbols"), 0 },
90
91  { NULL, 0, NULL, 0, N_("Output options:"), 0 },
92  { "numeric-sort", 'n', NULL, 0, N_("Sort symbols numerically by address"),
93    0 },
94  { "no-sort", 'p', NULL, 0, N_("Do not sort the symbols"), 0 },
95  { "reverse-sort", 'r', NULL, 0, N_("Reverse the sense of the sort"), 0 },
96#ifdef USE_DEMANGLE
97  { "demangle", 'C', NULL, 0,
98    N_("Decode low-level symbol names into source code names"), 0 },
99#endif
100  { NULL, 0, NULL, 0, N_("Miscellaneous:"), 0 },
101  { NULL, 0, NULL, 0, NULL, 0 }
102};
103
104/* Short description of program.  */
105static const char doc[] = N_("List symbols from FILEs (a.out by default).");
106
107/* Strings for arguments in help texts.  */
108static const char args_doc[] = N_("[FILE...]");
109
110/* Prototype for option handler.  */
111static error_t parse_opt (int key, char *arg, struct argp_state *state);
112
113/* Parser children.  */
114static struct argp_child argp_children[] =
115  {
116    { &color_argp, 0, N_("Output formatting"), 2 },
117    { NULL, 0, NULL, 0}
118  };
119
120/* Data structure to communicate with argp functions.  */
121static struct argp argp =
122{
123  options, parse_opt, args_doc, doc, argp_children, NULL, NULL
124};
125
126
127/* Print symbols in file named FNAME.  */
128static int process_file (const char *fname, bool more_than_one);
129
130/* Handle content of archive.  */
131static int handle_ar (int fd, Elf *elf, const char *prefix, const char *fname,
132		      const char *suffix);
133
134/* Handle ELF file.  */
135static int handle_elf (Elf *elf, const char *prefix, const char *fname,
136		       const char *suffix);
137
138
139#define INTERNAL_ERROR(fname) \
140  error (EXIT_FAILURE, 0, gettext ("%s: INTERNAL ERROR %d (%s-%s): %s"),      \
141	 fname, __LINE__, PACKAGE_VERSION, __DATE__, elf_errmsg (-1))
142
143
144/* Internal representation of symbols.  */
145typedef struct GElf_SymX
146{
147  GElf_Sym sym;
148  Elf32_Word xndx;
149  char *where;
150} GElf_SymX;
151
152
153/* User-selectable options.  */
154
155/* The selected output format.  */
156static enum
157{
158  format_sysv = 0,
159  format_bsd,
160  format_posix
161} format;
162
163/* Print defined, undefined, or both?  */
164static bool hide_undefined;
165static bool hide_defined;
166
167/* Print local symbols also?  */
168static bool hide_local;
169
170/* Nonzero if full filename should precede every symbol.  */
171static bool print_file_name;
172
173/* If true print size of defined symbols in BSD format.  */
174static bool print_size;
175
176/* If true print archive index.  */
177static bool print_armap;
178
179/* If true reverse sorting.  */
180static bool reverse_sort;
181
182#ifdef USE_DEMANGLE
183/* If true demangle symbols.  */
184static bool demangle;
185#endif
186
187/* Type of the section we are printing.  */
188static GElf_Word symsec_type = SHT_SYMTAB;
189
190/* Sorting selection.  */
191static enum
192{
193  sort_name = 0,
194  sort_numeric,
195  sort_nosort
196} sort;
197
198/* Radix for printed numbers.  */
199static enum
200{
201  radix_hex = 0,
202  radix_decimal,
203  radix_octal
204} radix;
205
206/* If nonzero mark special symbols:
207   - weak symbols are distinguished from global symbols by adding
208     a `*' after the identifying letter for the symbol class and type.
209   - TLS symbols are distinguished from normal symbols by adding
210     a '@' after the identifying letter for the symbol class and type.  */
211static bool mark_special;
212
213
214int
215main (int argc, char *argv[])
216{
217  int remaining;
218  int result = 0;
219
220  /* Make memory leak detection possible.  */
221  mtrace ();
222
223  /* We use no threads here which can interfere with handling a stream.  */
224  (void) __fsetlocking (stdin, FSETLOCKING_BYCALLER);
225  (void) __fsetlocking (stdout, FSETLOCKING_BYCALLER);
226  (void) __fsetlocking (stderr, FSETLOCKING_BYCALLER);
227
228  /* Set locale.  */
229  (void) setlocale (LC_ALL, "");
230
231  /* Make sure the message catalog can be found.  */
232  (void) bindtextdomain (PACKAGE_TARNAME, LOCALEDIR);
233
234  /* Initialize the message catalog.  */
235  (void) textdomain (PACKAGE_TARNAME);
236
237  /* Parse and process arguments.  */
238  (void) argp_parse (&argp, argc, argv, 0, &remaining, NULL);
239
240  /* Tell the library which version we are expecting.  */
241  (void) elf_version (EV_CURRENT);
242
243  if (remaining == argc)
244    /* The user didn't specify a name so we use a.out.  */
245    result = process_file ("a.out", false);
246  else
247    {
248      /* Process all the remaining files.  */
249      const bool more_than_one = remaining + 1 < argc;
250
251      do
252	result |= process_file (argv[remaining], more_than_one);
253      while (++remaining < argc);
254    }
255
256  return result;
257}
258
259
260/* Print the version information.  */
261static void
262print_version (FILE *stream, struct argp_state *state __attribute__ ((unused)))
263{
264  fprintf (stream, "nm (%s) %s\n", PACKAGE_NAME, PACKAGE_VERSION);
265  fprintf (stream, gettext ("\
266Copyright (C) %s Red Hat, Inc.\n\
267This is free software; see the source for copying conditions.  There is NO\n\
268warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
269"), "2012");
270  fprintf (stream, gettext ("Written by %s.\n"), "Ulrich Drepper");
271}
272
273
274/* Handle program arguments.  */
275static error_t
276parse_opt (int key, char *arg,
277	   struct argp_state *state __attribute__ ((unused)))
278{
279  switch (key)
280    {
281    case 'a':
282      /* XXX */
283      break;
284
285#ifdef USE_DEMANGLE
286    case 'C':
287      demangle = true;
288      break;
289#endif
290
291    case 'f':
292      if (strcmp (arg, "bsd") == 0)
293	format = format_bsd;
294      else if (strcmp (arg, "posix") == 0)
295	format = format_posix;
296      else
297	/* Be bug compatible.  The BFD implementation also defaulted to
298	   using the SysV format if nothing else matches.  */
299	format = format_sysv;
300      break;
301
302    case 'g':
303      hide_local = true;
304      break;
305
306    case 'n':
307      sort = sort_numeric;
308      break;
309
310    case 'p':
311      sort = sort_nosort;
312      break;
313
314    case 't':
315      if (strcmp (arg, "10") == 0 || strcmp (arg, "d") == 0)
316	radix = radix_decimal;
317      else if (strcmp (arg, "8") == 0 || strcmp (arg, "o") == 0)
318	radix = radix_octal;
319      else
320	radix = radix_hex;
321      break;
322
323    case 'u':
324      hide_undefined = false;
325      hide_defined = true;
326      break;
327
328    case 'A':
329    case 'o':
330      print_file_name = true;
331      break;
332
333    case 'B':
334      format = format_bsd;
335      break;
336
337    case 'D':
338      symsec_type = SHT_DYNSYM;
339      break;
340
341    case 'P':
342      format = format_posix;
343      break;
344
345    case OPT_DEFINED:
346      hide_undefined = true;
347      hide_defined = false;
348      break;
349
350    case OPT_MARK_SPECIAL:
351      mark_special = true;
352      break;
353
354    case 'S':
355      print_size = true;
356      break;
357
358    case 's':
359      print_armap = true;
360      break;
361
362    case 'r':
363      reverse_sort = true;
364      break;
365
366    default:
367      return ARGP_ERR_UNKNOWN;
368    }
369  return 0;
370}
371
372
373/* Open the file and determine the type.  */
374static int
375process_file (const char *fname, bool more_than_one)
376{
377  /* Open the file.  */
378  int fd = open (fname, O_RDONLY);
379  if (fd == -1)
380    {
381      error (0, errno, gettext ("cannot open '%s'"), fname);
382      return 1;
383    }
384
385  /* Now get the ELF descriptor.  */
386  Elf *elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
387  if (elf != NULL)
388    {
389      if (elf_kind (elf) == ELF_K_ELF)
390	{
391	  int result = handle_elf (elf, more_than_one ? "" : NULL,
392				   fname, NULL);
393
394	  if (elf_end (elf) != 0)
395	    INTERNAL_ERROR (fname);
396
397	  if (close (fd) != 0)
398	    error (EXIT_FAILURE, errno, gettext ("while closing '%s'"), fname);
399
400	  return result;
401	}
402      else if (elf_kind (elf) == ELF_K_AR)
403	{
404	  int result = handle_ar (fd, elf, NULL, fname, NULL);
405
406	  if (elf_end (elf) != 0)
407	    INTERNAL_ERROR (fname);
408
409	  if (close (fd) != 0)
410	    error (EXIT_FAILURE, errno, gettext ("while closing '%s'"), fname);
411
412	  return result;
413	}
414
415      /* We cannot handle this type.  Close the descriptor anyway.  */
416      if (elf_end (elf) != 0)
417	INTERNAL_ERROR (fname);
418    }
419
420  error (0, 0, gettext ("%s: File format not recognized"), fname);
421
422  return 1;
423}
424
425
426static int
427handle_ar (int fd, Elf *elf, const char *prefix, const char *fname,
428	   const char *suffix)
429{
430  size_t fname_len = strlen (fname) + 1;
431  size_t prefix_len = prefix != NULL ? strlen (prefix) : 0;
432  char new_prefix[prefix_len + fname_len + 2];
433  size_t suffix_len = suffix != NULL ? strlen (suffix) : 0;
434  char new_suffix[suffix_len + 2];
435  Elf *subelf;
436  Elf_Cmd cmd = ELF_C_READ_MMAP;
437  int result = 0;
438
439  char *cp = new_prefix;
440  if (prefix != NULL)
441    cp = stpcpy (cp, prefix);
442  cp = stpcpy (cp, fname);
443  stpcpy (cp, "[");
444
445  cp = new_suffix;
446  if (suffix != NULL)
447    cp = stpcpy (cp, suffix);
448  stpcpy (cp, "]");
449
450  /* First print the archive index if this is wanted.  */
451  if (print_armap)
452    {
453      Elf_Arsym *arsym = elf_getarsym (elf, NULL);
454
455      if (arsym != NULL)
456	{
457	  Elf_Arhdr *arhdr = NULL;
458	  size_t arhdr_off = 0;	/* Note: 0 is no valid offset.  */
459
460	  fputs_unlocked (gettext("\nArchive index:\n"), stdout);
461
462	  while (arsym->as_off != 0)
463	    {
464	      if (arhdr_off != arsym->as_off
465		  && (elf_rand (elf, arsym->as_off) != arsym->as_off
466		      || (subelf = elf_begin (fd, cmd, elf)) == NULL
467		      || (arhdr = elf_getarhdr (subelf)) == NULL))
468		{
469		  error (0, 0, gettext ("invalid offset %zu for symbol %s"),
470			 arsym->as_off, arsym->as_name);
471		  continue;
472		}
473
474	      printf (gettext ("%s in %s\n"), arsym->as_name, arhdr->ar_name);
475
476	      ++arsym;
477	    }
478
479	  if (elf_rand (elf, SARMAG) != SARMAG)
480	    {
481	      error (0, 0,
482		     gettext ("cannot reset archive offset to beginning"));
483	      return 1;
484	    }
485	}
486    }
487
488  /* Process all the files contained in the archive.  */
489  while ((subelf = elf_begin (fd, cmd, elf)) != NULL)
490    {
491      /* The the header for this element.  */
492      Elf_Arhdr *arhdr = elf_getarhdr (subelf);
493
494      /* Skip over the index entries.  */
495      if (strcmp (arhdr->ar_name, "/") != 0
496	  && strcmp (arhdr->ar_name, "//") != 0)
497	{
498	  if (elf_kind (subelf) == ELF_K_ELF)
499	    result |= handle_elf (subelf, new_prefix, arhdr->ar_name,
500				  new_suffix);
501	  else if (elf_kind (subelf) == ELF_K_AR)
502	    result |= handle_ar (fd, subelf, new_prefix, arhdr->ar_name,
503				 new_suffix);
504	  else
505	    {
506	      error (0, 0, gettext ("%s%s%s: file format not recognized"),
507		     new_prefix, arhdr->ar_name, new_suffix);
508	      result = 1;
509	    }
510	}
511
512      /* Get next archive element.  */
513      cmd = elf_next (subelf);
514      if (elf_end (subelf) != 0)
515	INTERNAL_ERROR (fname);
516    }
517
518  return result;
519}
520
521
522/* Mapping of radix and binary class to length.  */
523static const int length_map[2][3] =
524{
525  [ELFCLASS32 - 1] =
526  {
527    [radix_hex] = 8,
528    [radix_decimal] = 10,
529    [radix_octal] = 11
530  },
531  [ELFCLASS64 - 1] =
532  {
533    [radix_hex] = 16,
534    [radix_decimal] = 20,
535    [radix_octal] = 22
536  }
537};
538
539
540static int
541global_compare (const void *p1, const void *p2)
542{
543  const Dwarf_Global *g1 = (const Dwarf_Global *) p1;
544  const Dwarf_Global *g2 = (const Dwarf_Global *) p2;
545
546  return strcmp (g1->name, g2->name);
547}
548
549
550static void *global_root;
551
552
553static int
554get_global (Dwarf *dbg __attribute__ ((unused)), Dwarf_Global *global,
555	    void *arg __attribute__ ((unused)))
556{
557  tsearch (memcpy (xmalloc (sizeof (Dwarf_Global)), global,
558		   sizeof (Dwarf_Global)),
559	   &global_root, global_compare);
560
561  return DWARF_CB_OK;
562}
563
564
565struct local_name
566{
567  const char *name;
568  const char *file;
569  Dwarf_Word lineno;
570  Dwarf_Addr lowpc;
571  Dwarf_Addr highpc;
572};
573
574
575static int
576local_compare (const void *p1, const void *p2)
577{
578  struct local_name *g1 = (struct local_name *) p1;
579  struct local_name *g2 = (struct local_name *) p2;
580  int result;
581
582  result = strcmp (g1->name, g2->name);
583  if (result == 0)
584    {
585      if (g1->lowpc <= g2->lowpc && g1->highpc >= g2->highpc)
586	{
587	  /* g2 is contained in g1.  Update the data.  */
588	  g2->lowpc = g1->lowpc;
589	  g2->highpc = g1->highpc;
590	  result = 0;
591	}
592      else if (g2->lowpc <= g1->lowpc && g2->highpc >= g1->highpc)
593	{
594	  /* g1 is contained in g2.  Update the data.  */
595	  g1->lowpc = g2->lowpc;
596	  g1->highpc = g2->highpc;
597	  result = 0;
598	}
599      else
600	result = g1->lowpc < g2->lowpc ? -1 : 1;
601    }
602
603  return result;
604}
605
606
607static int
608get_var_range (Dwarf_Die *die, Dwarf_Word *lowpc, Dwarf_Word *highpc)
609{
610  Dwarf_Attribute locattr_mem;
611  Dwarf_Attribute *locattr = dwarf_attr (die, DW_AT_location, &locattr_mem);
612  if  (locattr == NULL)
613    return 1;
614
615  Dwarf_Op *loc;
616  size_t nloc;
617  if (dwarf_getlocation (locattr, &loc, &nloc) != 0)
618    return 1;
619
620  /* Interpret the location expressions.  */
621  // XXX For now just the simple one:
622  if (nloc == 1 && loc[0].atom == DW_OP_addr)
623    {
624      *lowpc = *highpc = loc[0].number;
625      return 0;
626    }
627
628  return 1;
629}
630
631
632
633static void *local_root;
634
635
636static void
637get_local_names (Dwarf *dbg)
638{
639  Dwarf_Off offset = 0;
640  Dwarf_Off old_offset;
641  size_t hsize;
642
643  while (dwarf_nextcu (dbg, old_offset = offset, &offset, &hsize, NULL, NULL,
644		       NULL) == 0)
645    {
646      Dwarf_Die cudie_mem;
647      Dwarf_Die *cudie = dwarf_offdie (dbg, old_offset + hsize, &cudie_mem);
648
649      /* If we cannot get the CU DIE there is no need to go on with
650	 this CU.  */
651      if (cudie == NULL)
652	continue;
653      /* This better be a CU DIE.  */
654      if (dwarf_tag (cudie) != DW_TAG_compile_unit)
655	continue;
656
657      /* Get the line information.  */
658      Dwarf_Files *files;
659      size_t nfiles;
660      if (dwarf_getsrcfiles (cudie, &files, &nfiles) != 0)
661	continue;
662
663      Dwarf_Die die_mem;
664      Dwarf_Die *die = &die_mem;
665      if (dwarf_child (cudie, die) == 0)
666	/* Iterate over all immediate children of the CU DIE.  */
667	do
668	  {
669	    int tag = dwarf_tag (die);
670	    if (tag != DW_TAG_subprogram && tag != DW_TAG_variable)
671	      continue;
672
673	    /* We are interested in five attributes: name, decl_file,
674	       decl_line, low_pc, and high_pc.  */
675	    Dwarf_Attribute attr_mem;
676	    Dwarf_Attribute *attr = dwarf_attr (die, DW_AT_name, &attr_mem);
677	    const char *name = dwarf_formstring (attr);
678	    if (name == NULL)
679	      continue;
680
681	    Dwarf_Word fileidx;
682	    attr = dwarf_attr (die, DW_AT_decl_file, &attr_mem);
683	    if (dwarf_formudata (attr, &fileidx) != 0 || fileidx >= nfiles)
684	      continue;
685
686	    Dwarf_Word lineno;
687	    attr = dwarf_attr (die, DW_AT_decl_line, &attr_mem);
688	    if (dwarf_formudata (attr, &lineno) != 0 || lineno == 0)
689	      continue;
690
691	    Dwarf_Addr lowpc;
692	    Dwarf_Addr highpc;
693	    if (tag == DW_TAG_subprogram)
694	      {
695		if (dwarf_lowpc (die, &lowpc) != 0
696		    || dwarf_highpc (die, &highpc) != 0)
697		  continue;
698	      }
699	    else
700	      {
701		if (get_var_range (die, &lowpc, &highpc) != 0)
702		  continue;
703	      }
704
705	    /* We have all the information.  Create a record.  */
706	    struct local_name *newp
707	      = (struct local_name *) xmalloc (sizeof (*newp));
708	    newp->name = name;
709	    newp->file = dwarf_filesrc (files, fileidx, NULL, NULL);
710	    newp->lineno = lineno;
711	    newp->lowpc = lowpc;
712	    newp->highpc = highpc;
713
714	    /* Since we cannot deallocate individual memory we do not test
715	       for duplicates in the tree.  This should not happen anyway.  */
716	    if (tsearch (newp, &local_root, local_compare) == NULL)
717	      error (EXIT_FAILURE, errno,
718		     gettext ("cannot create search tree"));
719	  }
720	while (dwarf_siblingof (die, die) == 0);
721    }
722}
723
724/* Do elf_strptr, but return a backup string and never NULL.  */
725static const char *
726sym_name (Elf *elf, GElf_Word strndx, GElf_Word st_name, char buf[], size_t n)
727{
728  const char *symstr = elf_strptr (elf, strndx, st_name);
729  if (symstr == NULL)
730    {
731      snprintf (buf, n, "[invalid st_name %#" PRIx32 "]", st_name);
732      symstr = buf;
733    }
734  return symstr;
735}
736
737/* Show symbols in SysV format.  */
738static void
739show_symbols_sysv (Ebl *ebl, GElf_Word strndx, const char *fullname,
740		   GElf_SymX *syms, size_t nsyms, int longest_name,
741		   int longest_where)
742{
743  size_t shnum;
744  if (elf_getshdrnum (ebl->elf, &shnum) < 0)
745    INTERNAL_ERROR (fullname);
746
747  bool scnnames_malloced = shnum * sizeof (const char *) > 128 * 1024;
748  const char **scnnames;
749  if (scnnames_malloced)
750    scnnames = (const char **) xmalloc (sizeof (const char *) * shnum);
751  else
752    scnnames = (const char **) alloca (sizeof (const char *) * shnum);
753  /* Get the section header string table index.  */
754  size_t shstrndx;
755  if (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0)
756    error (EXIT_FAILURE, 0,
757	   gettext ("cannot get section header string table index"));
758
759  /* Cache the section names.  */
760  Elf_Scn *scn = NULL;
761  size_t cnt = 1;
762  while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
763    {
764      GElf_Shdr shdr_mem;
765
766      assert (elf_ndxscn (scn) == cnt);
767      cnt++;
768
769      char *name = elf_strptr (ebl->elf, shstrndx,
770			       gelf_getshdr (scn, &shdr_mem)->sh_name);
771      if (unlikely (name == NULL))
772	{
773	  const size_t bufsz = sizeof "[invalid sh_name 0x12345678]";
774	  name = alloca (bufsz);
775	  snprintf (name, bufsz, "[invalid sh_name %#" PRIx32 "]",
776		    gelf_getshdr (scn, &shdr_mem)->sh_name);
777	}
778      scnnames[elf_ndxscn (scn)] = name;
779    }
780
781  int digits = length_map[gelf_getclass (ebl->elf) - 1][radix];
782
783  /* We always print this prolog.  */
784  printf (gettext ("\n\nSymbols from %s:\n\n"), fullname);
785
786  /* The header line.  */
787  printf (gettext ("%*s%-*s %-*s Class  Type     %-*s %*s Section\n\n"),
788	  print_file_name ? (int) strlen (fullname) + 1: 0, "",
789	  longest_name, sgettext ("sysv|Name"),
790	  /* TRANS: the "sysv|" parts makes the string unique.  */
791	  digits, sgettext ("sysv|Value"),
792	  /* TRANS: the "sysv|" parts makes the string unique.  */
793	  digits, sgettext ("sysv|Size"),
794	  /* TRANS: the "sysv|" parts makes the string unique.  */
795	  longest_where, sgettext ("sysv|Line"));
796
797#ifdef USE_DEMANGLE
798  size_t demangle_buffer_len = 0;
799  char *demangle_buffer = NULL;
800#endif
801
802  /* Iterate over all symbols.  */
803  for (cnt = 1; cnt < nsyms; ++cnt)
804    {
805      /* In this format SECTION entries are not printed.  */
806      if (GELF_ST_TYPE (syms[cnt].sym.st_info) == STT_SECTION)
807	continue;
808
809      char symstrbuf[50];
810      const char *symstr = sym_name (ebl->elf, strndx, syms[cnt].sym.st_name,
811				     symstrbuf, sizeof symstrbuf);
812
813#ifdef USE_DEMANGLE
814      /* Demangle if necessary.  Require GNU v3 ABI by the "_Z" prefix.  */
815      if (demangle && symstr[0] == '_' && symstr[1] == 'Z')
816	{
817	  int status = -1;
818	  char *dmsymstr = __cxa_demangle (symstr, demangle_buffer,
819					   &demangle_buffer_len, &status);
820
821	  if (status == 0)
822	    symstr = dmsymstr;
823	}
824#endif
825
826      char symbindbuf[50];
827      char symtypebuf[50];
828      char secnamebuf[1024];
829      char addressbuf[(64 + 2) / 3 + 1];
830      char sizebuf[(64 + 2) / 3 + 1];
831
832      /* If we have to precede the line with the file name.  */
833      if (print_file_name)
834	{
835	  fputs_unlocked (fullname, stdout);
836	  putchar_unlocked (':');
837	}
838
839      /* Covert the address.  */
840      if (syms[cnt].sym.st_shndx == SHN_UNDEF)
841	addressbuf[0] = sizebuf[0] = '\0';
842      else
843	{
844	  snprintf (addressbuf, sizeof (addressbuf),
845		    (radix == radix_hex ? "%0*" PRIx64
846		     : (radix == radix_decimal ? "%0*" PRId64
847			: "%0*" PRIo64)),
848		    digits, syms[cnt].sym.st_value);
849	  snprintf (sizebuf, sizeof (sizebuf),
850		    (radix == radix_hex ? "%0*" PRIx64
851		     : (radix == radix_decimal ? "%0*" PRId64
852			: "%0*" PRIo64)),
853		    digits, syms[cnt].sym.st_size);
854	}
855
856      /* Print the actual string.  */
857      printf ("%-*s|%s|%-6s|%-8s|%s|%*s|%s\n",
858	      longest_name, symstr, addressbuf,
859	      ebl_symbol_binding_name (ebl,
860				       GELF_ST_BIND (syms[cnt].sym.st_info),
861				       symbindbuf, sizeof (symbindbuf)),
862	      ebl_symbol_type_name (ebl, GELF_ST_TYPE (syms[cnt].sym.st_info),
863				    symtypebuf, sizeof (symtypebuf)),
864	      sizebuf, longest_where, syms[cnt].where,
865	      ebl_section_name (ebl, syms[cnt].sym.st_shndx, syms[cnt].xndx,
866				secnamebuf, sizeof (secnamebuf), scnnames,
867				shnum));
868    }
869
870#ifdef USE_DEMANGLE
871  free (demangle_buffer);
872#endif
873
874  if (scnnames_malloced)
875    free (scnnames);
876}
877
878
879static char
880class_type_char (Elf *elf, const GElf_Ehdr *ehdr, GElf_Sym *sym)
881{
882  int local_p = GELF_ST_BIND (sym->st_info) == STB_LOCAL;
883
884  /* XXX Add support for architecture specific types and classes.  */
885  if (sym->st_shndx == SHN_ABS)
886    return local_p ? 'a' : 'A';
887
888  if (sym->st_shndx == SHN_UNDEF)
889    /* Undefined symbols must be global.  */
890    return 'U';
891
892  char result = "NDTSFBD         "[GELF_ST_TYPE (sym->st_info)];
893
894  if (result == 'D')
895    {
896      /* Special handling: unique data symbols.  */
897      if (ehdr->e_ident[EI_OSABI] == ELFOSABI_LINUX
898	  && GELF_ST_BIND (sym->st_info) == STB_GNU_UNIQUE)
899	result = 'u';
900      else
901	{
902	  GElf_Shdr shdr_mem;
903	  GElf_Shdr *shdr = gelf_getshdr (elf_getscn (elf, sym->st_shndx),
904					  &shdr_mem);
905	  if (shdr != NULL)
906	    {
907	      if ((shdr->sh_flags & SHF_WRITE) == 0)
908		result = 'R';
909	      else if (shdr->sh_type == SHT_NOBITS)
910		result = 'B';
911	    }
912	}
913    }
914
915  return local_p ? tolower (result) : result;
916}
917
918
919static void
920show_symbols_bsd (Elf *elf, const GElf_Ehdr *ehdr, GElf_Word strndx,
921		  const char *prefix, const char *fname, const char *fullname,
922		  GElf_SymX *syms, size_t nsyms)
923{
924  int digits = length_map[gelf_getclass (elf) - 1][radix];
925
926  if (prefix != NULL && ! print_file_name)
927    printf ("\n%s:\n", fname);
928
929#ifdef USE_DEMANGLE
930  size_t demangle_buffer_len = 0;
931  char *demangle_buffer = NULL;
932#endif
933
934  /* Iterate over all symbols.  */
935  for (size_t cnt = 0; cnt < nsyms; ++cnt)
936    {
937      char symstrbuf[50];
938      const char *symstr = sym_name (elf, strndx, syms[cnt].sym.st_name,
939				     symstrbuf, sizeof symstrbuf);
940
941      /* Printing entries with a zero-length name makes the output
942	 not very well parseable.  Since these entries don't carry
943	 much information we leave them out.  */
944      if (symstr[0] == '\0')
945	continue;
946
947      /* We do not print the entries for files.  */
948      if (GELF_ST_TYPE (syms[cnt].sym.st_info) == STT_FILE)
949	continue;
950
951#ifdef USE_DEMANGLE
952      /* Demangle if necessary.  Require GNU v3 ABI by the "_Z" prefix.  */
953      if (demangle && symstr[0] == '_' && symstr[1] == 'Z')
954	{
955	  int status = -1;
956	  char *dmsymstr = __cxa_demangle (symstr, demangle_buffer,
957					   &demangle_buffer_len, &status);
958
959	  if (status == 0)
960	    symstr = dmsymstr;
961	}
962#endif
963
964      /* If we have to precede the line with the file name.  */
965      if (print_file_name)
966	{
967	  fputs_unlocked (fullname, stdout);
968	  putchar_unlocked (':');
969	}
970
971      bool is_tls = GELF_ST_TYPE (syms[cnt].sym.st_info) == STT_TLS;
972      bool is_weak = GELF_ST_BIND (syms[cnt].sym.st_info) == STB_WEAK;
973      const char *marker = (mark_special
974			    ? (is_tls ? "@" : (is_weak ? "*" : " ")) : "");
975
976      if (syms[cnt].sym.st_shndx == SHN_UNDEF)
977	{
978	  const char *color = "";
979	  if (color_mode)
980	    {
981	      if (is_tls)
982		color = color_undef_tls;
983	      else if (is_weak)
984		color = color_undef_weak;
985	      else
986		color = color_undef;
987	    }
988
989	  printf ("%*s %sU%s %s", digits, "", color, marker, symstr);
990	}
991      else
992	{
993	  const char *color = "";
994	  if (color_mode)
995	    {
996	      if (is_tls)
997		color = color_tls;
998	      else if (is_weak)
999		color = color_weak;
1000	      else
1001		color = color_symbol;
1002	    }
1003	  if (print_size && syms[cnt].sym.st_size != 0)
1004	    {
1005#define HEXFMT "%6$s%2$0*1$" PRIx64 "%8$s %10$0*9$" PRIx64 " %7$s%3$c%4$s %5$s"
1006#define DECFMT "%6$s%2$*1$" PRId64 "%8$s %10$*9$" PRId64 " %7$s%3$c%4$s %5$s"
1007#define OCTFMT "%6$s%2$0*1$" PRIo64 "%8$s %10$0*9$" PRIo64 " %7$s%3$c%4$s %5$s"
1008	      printf ((radix == radix_hex ? HEXFMT
1009		       : (radix == radix_decimal ? DECFMT : OCTFMT)),
1010		      digits, syms[cnt].sym.st_value,
1011		      class_type_char (elf, ehdr, &syms[cnt].sym), marker,
1012		      symstr,
1013		      color_mode ? color_address : "",
1014		      color,
1015		      color_mode ? color_off : "",
1016		      digits, (uint64_t) syms[cnt].sym.st_size);
1017#undef HEXFMT
1018#undef DECFMT
1019#undef OCTFMT
1020	    }
1021	  else
1022	    {
1023#define HEXFMT "%6$s%2$0*1$" PRIx64 "%8$s %7$s%3$c%4$s %5$s"
1024#define DECFMT "%6$s%2$*1$" PRId64 "%8$s %7$s%3$c%4$s %5$s"
1025#define OCTFMT "%6$s%2$0*1$" PRIo64 "%8$s %7$s%3$c%4$s %5$s"
1026	      printf ((radix == radix_hex ? HEXFMT
1027		       : (radix == radix_decimal ? DECFMT : OCTFMT)),
1028		      digits, syms[cnt].sym.st_value,
1029		      class_type_char (elf, ehdr, &syms[cnt].sym), marker,
1030		      symstr,
1031		      color_mode ? color_address : "",
1032		      color,
1033		      color_mode ? color_off : "");
1034#undef HEXFMT
1035#undef DECFMT
1036#undef OCTFMT
1037	    }
1038	}
1039
1040      if (color_mode)
1041	fputs_unlocked (color_off, stdout);
1042      putchar_unlocked ('\n');
1043    }
1044
1045#ifdef USE_DEMANGLE
1046  free (demangle_buffer);
1047#endif
1048}
1049
1050
1051static void
1052show_symbols_posix (Elf *elf, const GElf_Ehdr *ehdr, GElf_Word strndx,
1053		    const char *prefix, const char *fullname, GElf_SymX *syms,
1054		    size_t nsyms)
1055{
1056  if (prefix != NULL && ! print_file_name)
1057    printf ("%s:\n", fullname);
1058
1059  int digits = length_map[gelf_getclass (elf) - 1][radix];
1060
1061#ifdef USE_DEMANGLE
1062  size_t demangle_buffer_len = 0;
1063  char *demangle_buffer = NULL;
1064#endif
1065
1066  /* Iterate over all symbols.  */
1067  for (size_t cnt = 0; cnt < nsyms; ++cnt)
1068    {
1069      char symstrbuf[50];
1070      const char *symstr = sym_name (elf, strndx, syms[cnt].sym.st_name,
1071				     symstrbuf, sizeof symstrbuf);
1072
1073      /* Printing entries with a zero-length name makes the output
1074	 not very well parseable.  Since these entries don't carry
1075	 much information we leave them out.  */
1076      if (symstr[0] == '\0')
1077	continue;
1078
1079#ifdef USE_DEMANGLE
1080      /* Demangle if necessary.  Require GNU v3 ABI by the "_Z" prefix.  */
1081      if (demangle && symstr[0] == '_' && symstr[1] == 'Z')
1082	{
1083	  int status = -1;
1084	  char *dmsymstr = __cxa_demangle (symstr, demangle_buffer,
1085					   &demangle_buffer_len, &status);
1086
1087	  if (status == 0)
1088	    symstr = dmsymstr;
1089	}
1090#endif
1091
1092      /* If we have to precede the line with the file name.  */
1093      if (print_file_name)
1094	{
1095	  fputs_unlocked (fullname, stdout);
1096	  putchar_unlocked (':');
1097	  putchar_unlocked (' ');
1098	}
1099
1100      printf ((radix == radix_hex
1101	       ? "%s %c%s %0*" PRIx64 " %0*" PRIx64 "\n"
1102	       : (radix == radix_decimal
1103		  ? "%s %c%s %*" PRId64 " %*" PRId64 "\n"
1104		  : "%s %c%s %0*" PRIo64 " %0*" PRIo64 "\n")),
1105	      symstr,
1106	      class_type_char (elf, ehdr, &syms[cnt].sym),
1107	      mark_special
1108	      ? (GELF_ST_TYPE (syms[cnt].sym.st_info) == STT_TLS
1109		 ? "@"
1110		 : (GELF_ST_BIND (syms[cnt].sym.st_info) == STB_WEAK
1111		    ? "*" : " "))
1112	      : "",
1113	      digits, syms[cnt].sym.st_value,
1114	      digits, syms[cnt].sym.st_size);
1115    }
1116
1117#ifdef USE_DEMANGLE
1118  free (demangle_buffer);
1119#endif
1120}
1121
1122
1123/* Maximum size of memory we allocate on the stack.  */
1124#define MAX_STACK_ALLOC	65536
1125
1126static int
1127sort_by_address (const void *p1, const void *p2)
1128{
1129  GElf_SymX *s1 = (GElf_SymX *) p1;
1130  GElf_SymX *s2 = (GElf_SymX *) p2;
1131
1132  int result = (s1->sym.st_value < s2->sym.st_value
1133		? -1 : (s1->sym.st_value == s2->sym.st_value ? 0 : 1));
1134
1135  return reverse_sort ? -result : result;
1136}
1137
1138static Elf_Data *sort_by_name_strtab;
1139
1140static int
1141sort_by_name (const void *p1, const void *p2)
1142{
1143  GElf_SymX *s1 = (GElf_SymX *) p1;
1144  GElf_SymX *s2 = (GElf_SymX *) p2;
1145
1146  const char *n1 = sort_by_name_strtab->d_buf + s1->sym.st_name;
1147  const char *n2 = sort_by_name_strtab->d_buf + s2->sym.st_name;
1148
1149  int result = strcmp (n1, n2);
1150
1151  return reverse_sort ? -result : result;
1152}
1153
1154static void
1155show_symbols (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn, Elf_Scn *xndxscn,
1156	      GElf_Shdr *shdr, const char *prefix, const char *fname,
1157	      const char *fullname)
1158{
1159  /* Get the section header string table index.  */
1160  size_t shstrndx;
1161  if (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0)
1162    error (EXIT_FAILURE, 0,
1163	   gettext ("cannot get section header string table index"));
1164
1165  /* The section is that large.  */
1166  size_t size = shdr->sh_size;
1167  /* One entry is this large.  */
1168  size_t entsize = shdr->sh_entsize;
1169
1170  /* Consistency checks.  */
1171  if (entsize != gelf_fsize (ebl->elf, ELF_T_SYM, 1, ehdr->e_version))
1172    error (0, 0,
1173	   gettext ("%s: entry size in section `%s' is not what we expect"),
1174	   fullname, elf_strptr (ebl->elf, shstrndx, shdr->sh_name));
1175  else if (size % entsize != 0)
1176    error (0, 0,
1177	   gettext ("%s: size of section `%s' is not multiple of entry size"),
1178	   fullname, elf_strptr (ebl->elf, shstrndx, shdr->sh_name));
1179
1180  /* Compute number of entries.  Handle buggy entsize values.  */
1181  size_t nentries = size / (entsize ?: 1);
1182
1183
1184#define obstack_chunk_alloc xmalloc
1185#define obstack_chunk_free free
1186  struct obstack whereob;
1187  obstack_init (&whereob);
1188
1189  /* Get a DWARF debugging descriptor.  It's no problem if this isn't
1190     possible.  We just won't print any line number information.  */
1191  Dwarf *dbg = NULL;
1192  if (format == format_sysv)
1193    {
1194      dbg = dwarf_begin_elf (ebl->elf, DWARF_C_READ, NULL);
1195      if (dbg != NULL)
1196	{
1197	  (void) dwarf_getpubnames (dbg, get_global, NULL, 0);
1198
1199	  get_local_names (dbg);
1200	}
1201    }
1202
1203  /* Allocate the memory.
1204
1205     XXX We can use a dirty trick here.  Since GElf_Sym == Elf64_Sym we
1206     can use the data memory instead of copying again if what we read
1207     is a 64 bit file.  */
1208  GElf_SymX *sym_mem;
1209  if (nentries * sizeof (GElf_SymX) < MAX_STACK_ALLOC)
1210    sym_mem = (GElf_SymX *) alloca (nentries * sizeof (GElf_SymX));
1211  else
1212    sym_mem = (GElf_SymX *) xmalloc (nentries * sizeof (GElf_SymX));
1213
1214  /* Get the data of the section.  */
1215  Elf_Data *data = elf_getdata (scn, NULL);
1216  Elf_Data *xndxdata = elf_getdata (xndxscn, NULL);
1217  if (data == NULL || (xndxscn != NULL && xndxdata == NULL))
1218    INTERNAL_ERROR (fullname);
1219
1220  /* Iterate over all symbols.  */
1221#ifdef USE_DEMANGLE
1222  size_t demangle_buffer_len = 0;
1223  char *demangle_buffer = NULL;
1224#endif
1225  int longest_name = 4;
1226  int longest_where = 4;
1227  size_t nentries_used = 0;
1228  for (size_t cnt = 0; cnt < nentries; ++cnt)
1229    {
1230      GElf_Sym *sym = gelf_getsymshndx (data, xndxdata, cnt,
1231					&sym_mem[nentries_used].sym,
1232					&sym_mem[nentries_used].xndx);
1233      if (sym == NULL)
1234	INTERNAL_ERROR (fullname);
1235
1236      /* Filter out administrative symbols without a name and those
1237	 deselected by the user with command line options.  */
1238      if ((hide_undefined && sym->st_shndx == SHN_UNDEF)
1239	  || (hide_defined && sym->st_shndx != SHN_UNDEF)
1240	  || (hide_local && GELF_ST_BIND (sym->st_info) == STB_LOCAL))
1241	continue;
1242
1243      sym_mem[nentries_used].where = "";
1244      if (format == format_sysv)
1245	{
1246	  const char *symstr = elf_strptr (ebl->elf, shdr->sh_link,
1247					   sym->st_name);
1248	  if (symstr == NULL)
1249	    continue;
1250
1251#ifdef USE_DEMANGLE
1252	  /* Demangle if necessary.  Require GNU v3 ABI by the "_Z" prefix.  */
1253	  if (demangle && symstr[0] == '_' && symstr[1] == 'Z')
1254	    {
1255	      int status = -1;
1256	      char *dmsymstr = __cxa_demangle (symstr, demangle_buffer,
1257					       &demangle_buffer_len, &status);
1258
1259	      if (status == 0)
1260		symstr = dmsymstr;
1261	    }
1262#endif
1263
1264	  longest_name = MAX ((size_t) longest_name, strlen (symstr));
1265
1266	  if (sym->st_shndx != SHN_UNDEF
1267	      && GELF_ST_BIND (sym->st_info) != STB_LOCAL
1268	      && global_root != NULL)
1269	    {
1270	      Dwarf_Global fake = { .name = symstr };
1271	      Dwarf_Global **found = tfind (&fake, &global_root,
1272					    global_compare);
1273	      if (found != NULL)
1274		{
1275		  Dwarf_Die die_mem;
1276		  Dwarf_Die *die = dwarf_offdie (dbg, (*found)->die_offset,
1277						 &die_mem);
1278
1279		  Dwarf_Die cudie_mem;
1280		  Dwarf_Die *cudie = NULL;
1281
1282		  Dwarf_Addr lowpc;
1283		  Dwarf_Addr highpc;
1284		  if (die != NULL
1285		      && dwarf_lowpc (die, &lowpc) == 0
1286		      && lowpc <= sym->st_value
1287		      && dwarf_highpc (die, &highpc) == 0
1288		      && highpc > sym->st_value)
1289		    cudie = dwarf_offdie (dbg, (*found)->cu_offset,
1290					  &cudie_mem);
1291		  if (cudie != NULL)
1292		    {
1293		      Dwarf_Line *line = dwarf_getsrc_die (cudie,
1294							   sym->st_value);
1295		      if (line != NULL)
1296			{
1297			  /* We found the line.  */
1298			  int lineno;
1299			  (void) dwarf_lineno (line, &lineno);
1300			  int n;
1301			  n = obstack_printf (&whereob, "%s:%d%c",
1302					      basename (dwarf_linesrc (line,
1303								       NULL,
1304								       NULL)),
1305					      lineno, '\0');
1306			  sym_mem[nentries_used].where
1307			    = obstack_finish (&whereob);
1308
1309			  /* The return value of obstack_print included the
1310			     NUL byte, so subtract one.  */
1311			  if (--n > (int) longest_where)
1312			    longest_where = (size_t) n;
1313			}
1314		    }
1315		}
1316	    }
1317
1318	  /* Try to find the symbol among the local symbols.  */
1319	  if (sym_mem[nentries_used].where[0] == '\0')
1320	    {
1321	      struct local_name fake =
1322		{
1323		  .name = symstr,
1324		  .lowpc = sym->st_value,
1325		  .highpc = sym->st_value,
1326		};
1327	      struct local_name **found = tfind (&fake, &local_root,
1328						 local_compare);
1329	      if (found != NULL)
1330		{
1331		  /* We found the line.  */
1332		  int n = obstack_printf (&whereob, "%s:%" PRIu64 "%c",
1333					  basename ((*found)->file),
1334					  (*found)->lineno,
1335					  '\0');
1336		  sym_mem[nentries_used].where = obstack_finish (&whereob);
1337
1338		  /* The return value of obstack_print included the
1339		     NUL byte, so subtract one.  */
1340		  if (--n > (int) longest_where)
1341		    longest_where = (size_t) n;
1342		}
1343	    }
1344	}
1345
1346      /* We use this entry.  */
1347      ++nentries_used;
1348    }
1349#ifdef USE_DEMANGLE
1350  free (demangle_buffer);
1351#endif
1352  /* Now we know the exact number.  */
1353  nentries = nentries_used;
1354
1355  /* Sort the entries according to the users wishes.  */
1356  if (sort == sort_name)
1357    {
1358      sort_by_name_strtab = elf_getdata (elf_getscn (ebl->elf, shdr->sh_link),
1359					 NULL);
1360      qsort (sym_mem, nentries, sizeof (GElf_SymX), sort_by_name);
1361    }
1362  else if (sort == sort_numeric)
1363    qsort (sym_mem, nentries, sizeof (GElf_SymX), sort_by_address);
1364
1365  /* Finally print according to the users selection.  */
1366  switch (format)
1367    {
1368    case format_sysv:
1369      show_symbols_sysv (ebl, shdr->sh_link, fullname, sym_mem, nentries,
1370			 longest_name, longest_where);
1371      break;
1372
1373    case format_bsd:
1374      show_symbols_bsd (ebl->elf, ehdr, shdr->sh_link, prefix, fname, fullname,
1375			sym_mem, nentries);
1376      break;
1377
1378    case format_posix:
1379    default:
1380      assert (format == format_posix);
1381      show_symbols_posix (ebl->elf, ehdr, shdr->sh_link, prefix, fullname,
1382			  sym_mem, nentries);
1383      break;
1384    }
1385
1386  /* Free all memory.  */
1387  if (nentries * sizeof (GElf_Sym) >= MAX_STACK_ALLOC)
1388    free (sym_mem);
1389
1390  obstack_free (&whereob, NULL);
1391
1392  if (dbg != NULL)
1393    {
1394      tdestroy (global_root, free);
1395      global_root = NULL;
1396
1397      tdestroy (local_root, free);
1398      local_root = NULL;
1399
1400      (void) dwarf_end (dbg);
1401    }
1402}
1403
1404
1405static int
1406handle_elf (Elf *elf, const char *prefix, const char *fname,
1407	    const char *suffix)
1408{
1409  size_t prefix_len = prefix == NULL ? 0 : strlen (prefix);
1410  size_t suffix_len = suffix == NULL ? 0 : strlen (suffix);
1411  size_t fname_len = strlen (fname) + 1;
1412  char fullname[prefix_len + 1 + fname_len + suffix_len];
1413  char *cp = fullname;
1414  Elf_Scn *scn = NULL;
1415  int any = 0;
1416  int result = 0;
1417  GElf_Ehdr ehdr_mem;
1418  GElf_Ehdr *ehdr;
1419  Ebl *ebl;
1420
1421  /* Get the backend for this object file type.  */
1422  ebl = ebl_openbackend (elf);
1423
1424  /* We need the ELF header in a few places.  */
1425  ehdr = gelf_getehdr (elf, &ehdr_mem);
1426  if (ehdr == NULL)
1427    INTERNAL_ERROR (fullname);
1428
1429  /* If we are asked to print the dynamic symbol table and this is
1430     executable or dynamic executable, fail.  */
1431  if (symsec_type == SHT_DYNSYM
1432      && ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN)
1433    {
1434      /* XXX Add machine specific object file types.  */
1435      error (0, 0, gettext ("%s%s%s%s: Invalid operation"),
1436	     prefix ?: "", prefix ? "(" : "", fname, prefix ? ")" : "");
1437      result = 1;
1438      goto out;
1439    }
1440
1441  /* Create the full name of the file.  */
1442  if (prefix != NULL)
1443    cp = mempcpy (cp, prefix, prefix_len);
1444  cp = mempcpy (cp, fname, fname_len);
1445  if (suffix != NULL)
1446    memcpy (cp - 1, suffix, suffix_len + 1);
1447
1448  /* Find the symbol table.
1449
1450     XXX Can there be more than one?  Do we print all?  Currently we do.  */
1451  while ((scn = elf_nextscn (elf, scn)) != NULL)
1452    {
1453      GElf_Shdr shdr_mem;
1454      GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1455
1456      if (shdr == NULL)
1457	INTERNAL_ERROR (fullname);
1458
1459      if (shdr->sh_type == symsec_type)
1460	{
1461	  Elf_Scn *xndxscn = NULL;
1462
1463	  /* We have a symbol table.  First make sure we remember this.  */
1464	  any = 1;
1465
1466	  /* Look for an extended section index table for this section.  */
1467	  if (symsec_type == SHT_SYMTAB)
1468	    {
1469	      size_t scnndx = elf_ndxscn (scn);
1470
1471	      while ((xndxscn = elf_nextscn (elf, xndxscn)) != NULL)
1472		{
1473		  GElf_Shdr xndxshdr_mem;
1474		  GElf_Shdr *xndxshdr = gelf_getshdr (xndxscn, &xndxshdr_mem);
1475
1476		  if (xndxshdr == NULL)
1477		    INTERNAL_ERROR (fullname);
1478
1479		  if (xndxshdr->sh_type == SHT_SYMTAB_SHNDX
1480		      && xndxshdr->sh_link == scnndx)
1481		    break;
1482		}
1483	    }
1484
1485	  show_symbols (ebl, ehdr, scn, xndxscn, shdr, prefix, fname,
1486			fullname);
1487	}
1488    }
1489
1490  if (! any)
1491    {
1492      error (0, 0, gettext ("%s%s%s: no symbols"),
1493	     prefix ?: "", prefix ? ":" : "", fname);
1494      result = 1;
1495    }
1496
1497 out:
1498  /* Close the ELF backend library descriptor.  */
1499  ebl_closebackend (ebl);
1500
1501  return result;
1502}
1503
1504
1505#include "debugpred.h"
1506