1 /* Print symbol information from ELF file in human-readable form.
2 Copyright (C) 2000-2008, 2009, 2011, 2012 Red Hat, Inc.
3 This file is part of elfutils.
4 Written by Ulrich Drepper <drepper@redhat.com>, 2000.
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.
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.
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/>. */
41 #include <stdio_ext.h>
45 #include <sys/param.h>
48 #include "../libebl/libeblP.h"
51 /* Name and version of program. */
52 static void print_version (FILE *stream, struct argp_state *state);
53 ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
55 /* Bug report address. */
56 ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
59 /* Values for the parameters which have no short form. */
60 #define OPT_DEFINED 0x100
61 #define OPT_MARK_SPECIAL 0x101
63 /* Definitions of arguments for argp functions. */
64 static const struct argp_option options[] =
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"),
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 },
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'"),
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 },
91 { NULL, 0, NULL, 0, N_("Output options:"), 0 },
92 { "numeric-sort", 'n', NULL, 0, N_("Sort symbols numerically by address"),
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 },
97 { "demangle", 'C', NULL, 0,
98 N_("Decode low-level symbol names into source code names"), 0 },
100 { NULL, 0, NULL, 0, N_("Miscellaneous:"), 0 },
101 { NULL, 0, NULL, 0, NULL, 0 }
104 /* Short description of program. */
105 static const char doc[] = N_("List symbols from FILEs (a.out by default).");
107 /* Strings for arguments in help texts. */
108 static const char args_doc[] = N_("[FILE...]");
110 /* Prototype for option handler. */
111 static error_t parse_opt (int key, char *arg, struct argp_state *state);
113 /* Parser children. */
114 static struct argp_child argp_children[] =
116 { &color_argp, 0, N_("Output formatting"), 2 },
120 /* Data structure to communicate with argp functions. */
121 static struct argp argp =
123 options, parse_opt, args_doc, doc, argp_children, NULL, NULL
127 /* Print symbols in file named FNAME. */
128 static int process_file (const char *fname, bool more_than_one);
130 /* Handle content of archive. */
131 static int handle_ar (int fd, Elf *elf, const char *prefix, const char *fname,
134 /* Handle ELF file. */
135 static int handle_elf (Elf *elf, const char *prefix, const char *fname,
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))
144 /* Internal representation of symbols. */
145 typedef struct GElf_SymX
153 /* User-selectable options. */
155 /* The selected output format. */
163 /* Print defined, undefined, or both? */
164 static bool hide_undefined;
165 static bool hide_defined;
167 /* Print local symbols also? */
168 static bool hide_local;
170 /* Nonzero if full filename should precede every symbol. */
171 static bool print_file_name;
173 /* If true print size of defined symbols in BSD format. */
174 static bool print_size;
176 /* If true print archive index. */
177 static bool print_armap;
179 /* If true reverse sorting. */
180 static bool reverse_sort;
183 /* If true demangle symbols. */
184 static bool demangle;
187 /* Type of the section we are printing. */
188 static GElf_Word symsec_type = SHT_SYMTAB;
190 /* Sorting selection. */
198 /* Radix for printed numbers. */
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. */
211 static bool mark_special;
215 main (int argc, char *argv[])
220 /* Make memory leak detection possible. */
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);
229 (void) setlocale (LC_ALL, "");
231 /* Make sure the message catalog can be found. */
232 (void) bindtextdomain (PACKAGE_TARNAME, LOCALEDIR);
234 /* Initialize the message catalog. */
235 (void) textdomain (PACKAGE_TARNAME);
237 /* Parse and process arguments. */
238 (void) argp_parse (&argp, argc, argv, 0, &remaining, NULL);
240 /* Tell the library which version we are expecting. */
241 (void) elf_version (EV_CURRENT);
243 if (remaining == argc)
244 /* The user didn't specify a name so we use a.out. */
245 result = process_file ("a.out", false);
248 /* Process all the remaining files. */
249 const bool more_than_one = remaining + 1 < argc;
252 result |= process_file (argv[remaining], more_than_one);
253 while (++remaining < argc);
260 /* Print the version information. */
262 print_version (FILE *stream, struct argp_state *state __attribute__ ((unused)))
264 fprintf (stream, "nm (%s) %s\n", PACKAGE_NAME, PACKAGE_VERSION);
265 fprintf (stream, gettext ("\
266 Copyright (C) %s Red Hat, Inc.\n\
267 This is free software; see the source for copying conditions. There is NO\n\
268 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
270 fprintf (stream, gettext ("Written by %s.\n"), "Ulrich Drepper");
274 /* Handle program arguments. */
276 parse_opt (int key, char *arg,
277 struct argp_state *state __attribute__ ((unused)))
292 if (strcmp (arg, "bsd") == 0)
294 else if (strcmp (arg, "posix") == 0)
295 format = format_posix;
297 /* Be bug compatible. The BFD implementation also defaulted to
298 using the SysV format if nothing else matches. */
299 format = format_sysv;
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)
324 hide_undefined = false;
330 print_file_name = true;
338 symsec_type = SHT_DYNSYM;
342 format = format_posix;
346 hide_undefined = true;
347 hide_defined = false;
350 case OPT_MARK_SPECIAL:
367 return ARGP_ERR_UNKNOWN;
373 /* Open the file and determine the type. */
375 process_file (const char *fname, bool more_than_one)
378 int fd = open (fname, O_RDONLY);
381 error (0, errno, gettext ("cannot open '%s'"), fname);
385 /* Now get the ELF descriptor. */
386 Elf *elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
389 if (elf_kind (elf) == ELF_K_ELF)
391 int result = handle_elf (elf, more_than_one ? "" : NULL,
394 if (elf_end (elf) != 0)
395 INTERNAL_ERROR (fname);
398 error (EXIT_FAILURE, errno, gettext ("while closing '%s'"), fname);
402 else if (elf_kind (elf) == ELF_K_AR)
404 int result = handle_ar (fd, elf, NULL, fname, NULL);
406 if (elf_end (elf) != 0)
407 INTERNAL_ERROR (fname);
410 error (EXIT_FAILURE, errno, gettext ("while closing '%s'"), fname);
415 /* We cannot handle this type. Close the descriptor anyway. */
416 if (elf_end (elf) != 0)
417 INTERNAL_ERROR (fname);
420 error (0, 0, gettext ("%s: File format not recognized"), fname);
427 handle_ar (int fd, Elf *elf, const char *prefix, const char *fname,
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];
436 Elf_Cmd cmd = ELF_C_READ_MMAP;
439 char *cp = new_prefix;
441 cp = stpcpy (cp, prefix);
442 cp = stpcpy (cp, fname);
447 cp = stpcpy (cp, suffix);
450 /* First print the archive index if this is wanted. */
453 Elf_Arsym *arsym = elf_getarsym (elf, NULL);
457 Elf_Arhdr *arhdr = NULL;
458 size_t arhdr_off = 0; /* Note: 0 is no valid offset. */
460 fputs_unlocked (gettext("\nArchive index:\n"), stdout);
462 while (arsym->as_off != 0)
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))
469 error (0, 0, gettext ("invalid offset %zu for symbol %s"),
470 arsym->as_off, arsym->as_name);
474 printf (gettext ("%s in %s\n"), arsym->as_name, arhdr->ar_name);
479 if (elf_rand (elf, SARMAG) != SARMAG)
482 gettext ("cannot reset archive offset to beginning"));
488 /* Process all the files contained in the archive. */
489 while ((subelf = elf_begin (fd, cmd, elf)) != NULL)
491 /* The the header for this element. */
492 Elf_Arhdr *arhdr = elf_getarhdr (subelf);
494 /* Skip over the index entries. */
495 if (strcmp (arhdr->ar_name, "/") != 0
496 && strcmp (arhdr->ar_name, "//") != 0)
498 if (elf_kind (subelf) == ELF_K_ELF)
499 result |= handle_elf (subelf, new_prefix, arhdr->ar_name,
501 else if (elf_kind (subelf) == ELF_K_AR)
502 result |= handle_ar (fd, subelf, new_prefix, arhdr->ar_name,
506 error (0, 0, gettext ("%s%s%s: file format not recognized"),
507 new_prefix, arhdr->ar_name, new_suffix);
512 /* Get next archive element. */
513 cmd = elf_next (subelf);
514 if (elf_end (subelf) != 0)
515 INTERNAL_ERROR (fname);
522 /* Mapping of radix and binary class to length. */
523 static const int length_map[2][3] =
528 [radix_decimal] = 10,
534 [radix_decimal] = 20,
541 global_compare (const void *p1, const void *p2)
543 const Dwarf_Global *g1 = (const Dwarf_Global *) p1;
544 const Dwarf_Global *g2 = (const Dwarf_Global *) p2;
546 return strcmp (g1->name, g2->name);
550 static void *global_root;
554 get_global (Dwarf *dbg __attribute__ ((unused)), Dwarf_Global *global,
555 void *arg __attribute__ ((unused)))
557 tsearch (memcpy (xmalloc (sizeof (Dwarf_Global)), global,
558 sizeof (Dwarf_Global)),
559 &global_root, global_compare);
576 local_compare (const void *p1, const void *p2)
578 struct local_name *g1 = (struct local_name *) p1;
579 struct local_name *g2 = (struct local_name *) p2;
582 result = strcmp (g1->name, g2->name);
585 if (g1->lowpc <= g2->lowpc && g1->highpc >= g2->highpc)
587 /* g2 is contained in g1. Update the data. */
588 g2->lowpc = g1->lowpc;
589 g2->highpc = g1->highpc;
592 else if (g2->lowpc <= g1->lowpc && g2->highpc >= g1->highpc)
594 /* g1 is contained in g2. Update the data. */
595 g1->lowpc = g2->lowpc;
596 g1->highpc = g2->highpc;
600 result = g1->lowpc < g2->lowpc ? -1 : 1;
608 get_var_range (Dwarf_Die *die, Dwarf_Word *lowpc, Dwarf_Word *highpc)
610 Dwarf_Attribute locattr_mem;
611 Dwarf_Attribute *locattr = dwarf_attr (die, DW_AT_location, &locattr_mem);
617 if (dwarf_getlocation (locattr, &loc, &nloc) != 0)
620 /* Interpret the location expressions. */
621 // XXX For now just the simple one:
622 if (nloc == 1 && loc[0].atom == DW_OP_addr)
624 *lowpc = *highpc = loc[0].number;
633 static void *local_root;
637 get_local_names (Dwarf *dbg)
639 Dwarf_Off offset = 0;
640 Dwarf_Off old_offset;
643 while (dwarf_nextcu (dbg, old_offset = offset, &offset, &hsize, NULL, NULL,
647 Dwarf_Die *cudie = dwarf_offdie (dbg, old_offset + hsize, &cudie_mem);
649 /* If we cannot get the CU DIE there is no need to go on with
653 /* This better be a CU DIE. */
654 if (dwarf_tag (cudie) != DW_TAG_compile_unit)
657 /* Get the line information. */
660 if (dwarf_getsrcfiles (cudie, &files, &nfiles) != 0)
664 Dwarf_Die *die = &die_mem;
665 if (dwarf_child (cudie, die) == 0)
666 /* Iterate over all immediate children of the CU DIE. */
669 int tag = dwarf_tag (die);
670 if (tag != DW_TAG_subprogram && tag != DW_TAG_variable)
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);
682 attr = dwarf_attr (die, DW_AT_decl_file, &attr_mem);
683 if (dwarf_formudata (attr, &fileidx) != 0 || fileidx >= nfiles)
687 attr = dwarf_attr (die, DW_AT_decl_line, &attr_mem);
688 if (dwarf_formudata (attr, &lineno) != 0 || lineno == 0)
693 if (tag == DW_TAG_subprogram)
695 if (dwarf_lowpc (die, &lowpc) != 0
696 || dwarf_highpc (die, &highpc) != 0)
701 if (get_var_range (die, &lowpc, &highpc) != 0)
705 /* We have all the information. Create a record. */
706 struct local_name *newp
707 = (struct local_name *) xmalloc (sizeof (*newp));
709 newp->file = dwarf_filesrc (files, fileidx, NULL, NULL);
710 newp->lineno = lineno;
712 newp->highpc = highpc;
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"));
720 while (dwarf_siblingof (die, die) == 0);
724 /* Do elf_strptr, but return a backup string and never NULL. */
726 sym_name (Elf *elf, GElf_Word strndx, GElf_Word st_name, char buf[], size_t n)
728 const char *symstr = elf_strptr (elf, strndx, st_name);
731 snprintf (buf, n, "[invalid st_name %#" PRIx32 "]", st_name);
737 /* Show symbols in SysV format. */
739 show_symbols_sysv (Ebl *ebl, GElf_Word strndx, const char *fullname,
740 GElf_SymX *syms, size_t nsyms, int longest_name,
744 if (elf_getshdrnum (ebl->elf, &shnum) < 0)
745 INTERNAL_ERROR (fullname);
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);
752 scnnames = (const char **) alloca (sizeof (const char *) * shnum);
753 /* Get the section header string table index. */
755 if (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0)
756 error (EXIT_FAILURE, 0,
757 gettext ("cannot get section header string table index"));
759 /* Cache the section names. */
762 while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
766 assert (elf_ndxscn (scn) == cnt++);
768 char *name = elf_strptr (ebl->elf, shstrndx,
769 gelf_getshdr (scn, &shdr_mem)->sh_name);
770 if (unlikely (name == NULL))
772 name = alloca (sizeof "[invalid sh_name 0x12345678]");
773 snprintf (name, sizeof name, "[invalid sh_name %#" PRIx32 "]",
774 gelf_getshdr (scn, &shdr_mem)->sh_name);
776 scnnames[elf_ndxscn (scn)] = name;
779 int digits = length_map[gelf_getclass (ebl->elf) - 1][radix];
781 /* We always print this prolog. */
782 printf (gettext ("\n\nSymbols from %s:\n\n"), fullname);
784 /* The header line. */
785 printf (gettext ("%*s%-*s %-*s Class Type %-*s %*s Section\n\n"),
786 print_file_name ? (int) strlen (fullname) + 1: 0, "",
787 longest_name, sgettext ("sysv|Name"),
788 /* TRANS: the "sysv|" parts makes the string unique. */
789 digits, sgettext ("sysv|Value"),
790 /* TRANS: the "sysv|" parts makes the string unique. */
791 digits, sgettext ("sysv|Size"),
792 /* TRANS: the "sysv|" parts makes the string unique. */
793 longest_where, sgettext ("sysv|Line"));
795 /* Which format string to use (different radix for numbers). */
796 const char *number_fmtstr;
797 if (radix == radix_hex)
798 number_fmtstr = "%0*" PRIx64;
799 else if (radix == radix_decimal)
800 number_fmtstr = "%0*" PRId64;
802 number_fmtstr = "%0*" PRIo64;
805 size_t demangle_buffer_len = 0;
806 char *demangle_buffer = NULL;
809 /* Iterate over all symbols. */
810 for (cnt = 1; cnt < nsyms; ++cnt)
812 /* In this format SECTION entries are not printed. */
813 if (GELF_ST_TYPE (syms[cnt].sym.st_info) == STT_SECTION)
817 const char *symstr = sym_name (ebl->elf, strndx, syms[cnt].sym.st_name,
818 symstrbuf, sizeof symstrbuf);
821 /* Demangle if necessary. */
825 char *dmsymstr = __cxa_demangle (symstr, demangle_buffer,
826 &demangle_buffer_len, &status);
835 char secnamebuf[1024];
836 char addressbuf[(64 + 2) / 3 + 1];
837 char sizebuf[(64 + 2) / 3 + 1];
839 /* If we have to precede the line with the file name. */
842 fputs_unlocked (fullname, stdout);
843 putchar_unlocked (':');
846 /* Covert the address. */
847 if (syms[cnt].sym.st_shndx == SHN_UNDEF)
848 addressbuf[0] = sizebuf[0] = '\0';
851 snprintf (addressbuf, sizeof (addressbuf), number_fmtstr,
852 digits, syms[cnt].sym.st_value);
853 snprintf (sizebuf, sizeof (sizebuf), number_fmtstr,
854 digits, syms[cnt].sym.st_size);
857 /* Print the actual string. */
858 printf ("%-*s|%s|%-6s|%-8s|%s|%*s|%s\n",
859 longest_name, symstr, addressbuf,
860 ebl_symbol_binding_name (ebl,
861 GELF_ST_BIND (syms[cnt].sym.st_info),
862 symbindbuf, sizeof (symbindbuf)),
863 ebl_symbol_type_name (ebl, GELF_ST_TYPE (syms[cnt].sym.st_info),
864 symtypebuf, sizeof (symtypebuf)),
865 sizebuf, longest_where, syms[cnt].where,
866 ebl_section_name (ebl, syms[cnt].sym.st_shndx, syms[cnt].xndx,
867 secnamebuf, sizeof (secnamebuf), scnnames,
872 free (demangle_buffer);
875 if (scnnames_malloced)
881 class_type_char (Elf *elf, const GElf_Ehdr *ehdr, GElf_Sym *sym)
883 int local_p = GELF_ST_BIND (sym->st_info) == STB_LOCAL;
885 /* XXX Add support for architecture specific types and classes. */
886 if (sym->st_shndx == SHN_ABS)
887 return local_p ? 'a' : 'A';
889 if (sym->st_shndx == SHN_UNDEF)
890 /* Undefined symbols must be global. */
893 char result = "NDTSFBD "[GELF_ST_TYPE (sym->st_info)];
897 /* Special handling: unique data symbols. */
898 if (ehdr->e_ident[EI_OSABI] == ELFOSABI_LINUX
899 && GELF_ST_BIND (sym->st_info) == STB_GNU_UNIQUE)
904 GElf_Shdr *shdr = gelf_getshdr (elf_getscn (elf, sym->st_shndx),
908 if ((shdr->sh_flags & SHF_WRITE) == 0)
910 else if (shdr->sh_type == SHT_NOBITS)
916 return local_p ? tolower (result) : result;
921 show_symbols_bsd (Elf *elf, const GElf_Ehdr *ehdr, GElf_Word strndx,
922 const char *prefix, const char *fname, const char *fullname,
923 GElf_SymX *syms, size_t nsyms)
925 int digits = length_map[gelf_getclass (elf) - 1][radix];
927 if (prefix != NULL && ! print_file_name)
928 printf ("\n%s:\n", fname);
930 static const char *const fmtstrs[] =
932 [radix_hex] = "%6$s%2$0*1$" PRIx64 "%8$s %7$s%3$c%4$s %5$s",
933 [radix_decimal] = "%6$s%*" PRId64 "%8$s %7$s%3$c%4$s %5$s",
934 [radix_octal] = "%6$s%2$0*1$" PRIo64 "%8$s %7$s%3$c%4$s %5$s"
936 static const char *const sfmtstrs[] =
938 [radix_hex] = "%6$s%2$0*1$" PRIx64 "%8$s %10$0*9$" PRIx64 " %7$s%3$c%4$s %5$s",
939 [radix_decimal] = "%6$s%2$*1$" PRId64 "%8$s %10$*9$" PRId64 " %7$s%3$c%4$s %5$s",
940 [radix_octal] = "%6$s%2$0*1$" PRIo64 "%8$s %10$0*9$" PRIo64 " %7$s%3$c%4$s %5$s"
944 size_t demangle_buffer_len = 0;
945 char *demangle_buffer = NULL;
948 /* Iterate over all symbols. */
949 for (size_t cnt = 0; cnt < nsyms; ++cnt)
952 const char *symstr = sym_name (elf, strndx, syms[cnt].sym.st_name,
953 symstrbuf, sizeof symstrbuf);
955 /* Printing entries with a zero-length name makes the output
956 not very well parseable. Since these entries don't carry
957 much information we leave them out. */
958 if (symstr[0] == '\0')
961 /* We do not print the entries for files. */
962 if (GELF_ST_TYPE (syms[cnt].sym.st_info) == STT_FILE)
966 /* Demangle if necessary. */
970 char *dmsymstr = __cxa_demangle (symstr, demangle_buffer,
971 &demangle_buffer_len, &status);
978 /* If we have to precede the line with the file name. */
981 fputs_unlocked (fullname, stdout);
982 putchar_unlocked (':');
985 bool is_tls = GELF_ST_TYPE (syms[cnt].sym.st_info) == STT_TLS;
986 bool is_weak = GELF_ST_BIND (syms[cnt].sym.st_info) == STB_WEAK;
987 const char *marker = (mark_special
988 ? (is_tls ? "@" : (is_weak ? "*" : " ")) : "");
990 if (syms[cnt].sym.st_shndx == SHN_UNDEF)
992 const char *color = "";
996 color = color_undef_tls;
998 color = color_undef_weak;
1000 color = color_undef;
1003 printf ("%*s %sU%s %s", digits, "", color, marker, symstr);
1007 const char *color = "";
1015 color = color_symbol;
1018 printf (print_size && syms[cnt].sym.st_size != 0
1019 ? sfmtstrs[radix] : fmtstrs[radix],
1020 digits, syms[cnt].sym.st_value,
1021 class_type_char (elf, ehdr, &syms[cnt].sym), marker,
1023 color_mode ? color_address : "",
1025 color_mode ? color_off : "",
1026 digits, (uint64_t) syms[cnt].sym.st_size);
1030 fputs_unlocked (color_off, stdout);
1031 putchar_unlocked ('\n');
1035 free (demangle_buffer);
1041 show_symbols_posix (Elf *elf, const GElf_Ehdr *ehdr, GElf_Word strndx,
1042 const char *prefix, const char *fullname, GElf_SymX *syms,
1045 if (prefix != NULL && ! print_file_name)
1046 printf ("%s:\n", fullname);
1049 if (radix == radix_hex)
1050 fmtstr = "%s %c%s %0*" PRIx64 " %0*" PRIx64 "\n";
1051 else if (radix == radix_decimal)
1052 fmtstr = "%s %c%s %*" PRId64 " %*" PRId64 "\n";
1054 fmtstr = "%s %c%s %0*" PRIo64 " %0*" PRIo64 "\n";
1056 int digits = length_map[gelf_getclass (elf) - 1][radix];
1059 size_t demangle_buffer_len = 0;
1060 char *demangle_buffer = NULL;
1063 /* Iterate over all symbols. */
1064 for (size_t cnt = 0; cnt < nsyms; ++cnt)
1067 const char *symstr = sym_name (elf, strndx, syms[cnt].sym.st_name,
1068 symstrbuf, sizeof symstrbuf);
1070 /* Printing entries with a zero-length name makes the output
1071 not very well parseable. Since these entries don't carry
1072 much information we leave them out. */
1073 if (symstr[0] == '\0')
1077 /* Demangle if necessary. */
1081 char *dmsymstr = __cxa_demangle (symstr, demangle_buffer,
1082 &demangle_buffer_len, &status);
1089 /* If we have to precede the line with the file name. */
1090 if (print_file_name)
1092 fputs_unlocked (fullname, stdout);
1093 putchar_unlocked (':');
1094 putchar_unlocked (' ');
1099 class_type_char (elf, ehdr, &syms[cnt].sym),
1101 ? (GELF_ST_TYPE (syms[cnt].sym.st_info) == STT_TLS
1103 : (GELF_ST_BIND (syms[cnt].sym.st_info) == STB_WEAK
1106 digits, syms[cnt].sym.st_value,
1107 digits, syms[cnt].sym.st_size);
1111 free (demangle_buffer);
1116 /* Maximum size of memory we allocate on the stack. */
1117 #define MAX_STACK_ALLOC 65536
1120 sort_by_address (const void *p1, const void *p2)
1122 GElf_SymX *s1 = (GElf_SymX *) p1;
1123 GElf_SymX *s2 = (GElf_SymX *) p2;
1125 int result = (s1->sym.st_value < s2->sym.st_value
1126 ? -1 : (s1->sym.st_value == s2->sym.st_value ? 0 : 1));
1128 return reverse_sort ? -result : result;
1131 static Elf_Data *sort_by_name_strtab;
1134 sort_by_name (const void *p1, const void *p2)
1136 GElf_SymX *s1 = (GElf_SymX *) p1;
1137 GElf_SymX *s2 = (GElf_SymX *) p2;
1139 const char *n1 = sort_by_name_strtab->d_buf + s1->sym.st_name;
1140 const char *n2 = sort_by_name_strtab->d_buf + s2->sym.st_name;
1142 int result = strcmp (n1, n2);
1144 return reverse_sort ? -result : result;
1148 show_symbols (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn, Elf_Scn *xndxscn,
1149 GElf_Shdr *shdr, const char *prefix, const char *fname,
1150 const char *fullname)
1152 /* Get the section header string table index. */
1154 if (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0)
1155 error (EXIT_FAILURE, 0,
1156 gettext ("cannot get section header string table index"));
1158 /* The section is that large. */
1159 size_t size = shdr->sh_size;
1160 /* One entry is this large. */
1161 size_t entsize = shdr->sh_entsize;
1163 /* Consistency checks. */
1164 if (entsize != gelf_fsize (ebl->elf, ELF_T_SYM, 1, ehdr->e_version))
1166 gettext ("%s: entry size in section `%s' is not what we expect"),
1167 fullname, elf_strptr (ebl->elf, shstrndx, shdr->sh_name));
1168 else if (size % entsize != 0)
1170 gettext ("%s: size of section `%s' is not multiple of entry size"),
1171 fullname, elf_strptr (ebl->elf, shstrndx, shdr->sh_name));
1173 /* Compute number of entries. Handle buggy entsize values. */
1174 size_t nentries = size / (entsize ?: 1);
1177 #define obstack_chunk_alloc xmalloc
1178 #define obstack_chunk_free free
1179 struct obstack whereob;
1180 obstack_init (&whereob);
1182 /* Get a DWARF debugging descriptor. It's no problem if this isn't
1183 possible. We just won't print any line number information. */
1185 if (format == format_sysv)
1187 dbg = dwarf_begin_elf (ebl->elf, DWARF_C_READ, NULL);
1190 (void) dwarf_getpubnames (dbg, get_global, NULL, 0);
1192 get_local_names (dbg);
1196 /* Allocate the memory.
1198 XXX We can use a dirty trick here. Since GElf_Sym == Elf64_Sym we
1199 can use the data memory instead of copying again if what we read
1200 is a 64 bit file. */
1202 if (nentries * sizeof (GElf_SymX) < MAX_STACK_ALLOC)
1203 sym_mem = (GElf_SymX *) alloca (nentries * sizeof (GElf_SymX));
1205 sym_mem = (GElf_SymX *) xmalloc (nentries * sizeof (GElf_SymX));
1207 /* Get the data of the section. */
1208 Elf_Data *data = elf_getdata (scn, NULL);
1209 Elf_Data *xndxdata = elf_getdata (xndxscn, NULL);
1210 if (data == NULL || (xndxscn != NULL && xndxdata == NULL))
1211 INTERNAL_ERROR (fullname);
1213 /* Iterate over all symbols. */
1215 size_t demangle_buffer_len = 0;
1216 char *demangle_buffer = NULL;
1218 int longest_name = 4;
1219 int longest_where = 4;
1220 size_t nentries_used = 0;
1221 for (size_t cnt = 0; cnt < nentries; ++cnt)
1223 GElf_Sym *sym = gelf_getsymshndx (data, xndxdata, cnt,
1224 &sym_mem[nentries_used].sym,
1225 &sym_mem[nentries_used].xndx);
1227 INTERNAL_ERROR (fullname);
1229 /* Filter out administrative symbols without a name and those
1230 deselected by the user with command line options. */
1231 if ((hide_undefined && sym->st_shndx == SHN_UNDEF)
1232 || (hide_defined && sym->st_shndx != SHN_UNDEF)
1233 || (hide_local && GELF_ST_BIND (sym->st_info) == STB_LOCAL))
1236 sym_mem[nentries_used].where = "";
1237 if (format == format_sysv)
1239 const char *symstr = elf_strptr (ebl->elf, shdr->sh_link,
1245 /* Demangle if necessary. */
1249 char *dmsymstr = __cxa_demangle (symstr, demangle_buffer,
1250 &demangle_buffer_len, &status);
1257 longest_name = MAX ((size_t) longest_name, strlen (symstr));
1259 if (sym->st_shndx != SHN_UNDEF
1260 && GELF_ST_BIND (sym->st_info) != STB_LOCAL
1261 && global_root != NULL)
1263 Dwarf_Global fake = { .name = symstr };
1264 Dwarf_Global **found = tfind (&fake, &global_root,
1269 Dwarf_Die *die = dwarf_offdie (dbg, (*found)->die_offset,
1272 Dwarf_Die cudie_mem;
1273 Dwarf_Die *cudie = NULL;
1278 && dwarf_lowpc (die, &lowpc) == 0
1279 && lowpc <= sym->st_value
1280 && dwarf_highpc (die, &highpc) == 0
1281 && highpc > sym->st_value)
1282 cudie = dwarf_offdie (dbg, (*found)->cu_offset,
1286 Dwarf_Line *line = dwarf_getsrc_die (cudie,
1290 /* We found the line. */
1292 (void) dwarf_lineno (line, &lineno);
1294 n = obstack_printf (&whereob, "%s:%d%c",
1295 basename (dwarf_linesrc (line,
1299 sym_mem[nentries_used].where
1300 = obstack_finish (&whereob);
1302 /* The return value of obstack_print included the
1303 NUL byte, so subtract one. */
1304 if (--n > (int) longest_where)
1305 longest_where = (size_t) n;
1311 /* Try to find the symbol among the local symbols. */
1312 if (sym_mem[nentries_used].where[0] == '\0')
1314 struct local_name fake =
1317 .lowpc = sym->st_value,
1318 .highpc = sym->st_value,
1320 struct local_name **found = tfind (&fake, &local_root,
1324 /* We found the line. */
1325 int n = obstack_printf (&whereob, "%s:%" PRIu64 "%c",
1326 basename ((*found)->file),
1329 sym_mem[nentries_used].where = obstack_finish (&whereob);
1331 /* The return value of obstack_print included the
1332 NUL byte, so subtract one. */
1333 if (--n > (int) longest_where)
1334 longest_where = (size_t) n;
1339 /* We use this entry. */
1343 free (demangle_buffer);
1345 /* Now we know the exact number. */
1346 nentries = nentries_used;
1348 /* Sort the entries according to the users wishes. */
1349 if (sort == sort_name)
1351 sort_by_name_strtab = elf_getdata (elf_getscn (ebl->elf, shdr->sh_link),
1353 qsort (sym_mem, nentries, sizeof (GElf_SymX), sort_by_name);
1355 else if (sort == sort_numeric)
1356 qsort (sym_mem, nentries, sizeof (GElf_SymX), sort_by_address);
1358 /* Finally print according to the users selection. */
1362 show_symbols_sysv (ebl, shdr->sh_link, fullname, sym_mem, nentries,
1363 longest_name, longest_where);
1367 show_symbols_bsd (ebl->elf, ehdr, shdr->sh_link, prefix, fname, fullname,
1373 assert (format == format_posix);
1374 show_symbols_posix (ebl->elf, ehdr, shdr->sh_link, prefix, fullname,
1379 /* Free all memory. */
1380 if (nentries * sizeof (GElf_Sym) >= MAX_STACK_ALLOC)
1383 obstack_free (&whereob, NULL);
1387 tdestroy (global_root, free);
1390 tdestroy (local_root, free);
1393 (void) dwarf_end (dbg);
1399 handle_elf (Elf *elf, const char *prefix, const char *fname,
1402 size_t prefix_len = prefix == NULL ? 0 : strlen (prefix);
1403 size_t suffix_len = suffix == NULL ? 0 : strlen (suffix);
1404 size_t fname_len = strlen (fname) + 1;
1405 char fullname[prefix_len + 1 + fname_len + suffix_len];
1406 char *cp = fullname;
1407 Elf_Scn *scn = NULL;
1414 /* Get the backend for this object file type. */
1415 ebl = ebl_openbackend (elf);
1417 /* We need the ELF header in a few places. */
1418 ehdr = gelf_getehdr (elf, &ehdr_mem);
1420 INTERNAL_ERROR (fullname);
1422 /* If we are asked to print the dynamic symbol table and this is
1423 executable or dynamic executable, fail. */
1424 if (symsec_type == SHT_DYNSYM
1425 && ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN)
1427 /* XXX Add machine specific object file types. */
1428 error (0, 0, gettext ("%s%s%s%s: Invalid operation"),
1429 prefix ?: "", prefix ? "(" : "", fname, prefix ? ")" : "");
1434 /* Create the full name of the file. */
1436 cp = mempcpy (cp, prefix, prefix_len);
1437 cp = mempcpy (cp, fname, fname_len);
1439 memcpy (cp - 1, suffix, suffix_len + 1);
1441 /* Find the symbol table.
1443 XXX Can there be more than one? Do we print all? Currently we do. */
1444 while ((scn = elf_nextscn (elf, scn)) != NULL)
1447 GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1450 INTERNAL_ERROR (fullname);
1452 if (shdr->sh_type == symsec_type)
1454 Elf_Scn *xndxscn = NULL;
1456 /* We have a symbol table. First make sure we remember this. */
1459 /* Look for an extended section index table for this section. */
1460 if (symsec_type == SHT_SYMTAB)
1462 size_t scnndx = elf_ndxscn (scn);
1464 while ((xndxscn = elf_nextscn (elf, xndxscn)) != NULL)
1466 GElf_Shdr xndxshdr_mem;
1467 GElf_Shdr *xndxshdr = gelf_getshdr (xndxscn, &xndxshdr_mem);
1469 if (xndxshdr == NULL)
1470 INTERNAL_ERROR (fullname);
1472 if (xndxshdr->sh_type == SHT_SYMTAB_SHNDX
1473 && xndxshdr->sh_link == scnndx)
1478 show_symbols (ebl, ehdr, scn, xndxscn, shdr, prefix, fname,
1485 error (0, 0, gettext ("%s%s%s: no symbols"),
1486 prefix ?: "", prefix ? ":" : "", fname);
1491 /* Close the ELF backend library descriptor. */
1492 ebl_closebackend (ebl);
1498 #include "debugpred.h"