readelf,libdw: Correct .debug_line overflow check for unit_length.
[platform/upstream/elfutils.git] / src / readelf.c
1 /* Print information from ELF file in human-readable form.
2    Copyright (C) 1999-2014 Red Hat, Inc.
3    This file is part of elfutils.
4    Written by Ulrich Drepper <drepper@redhat.com>, 1999.
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 <argp.h>
24 #include <assert.h>
25 #include <ctype.h>
26 #include <dwarf.h>
27 #include <errno.h>
28 #include <error.h>
29 #include <fcntl.h>
30 #include <gelf.h>
31 #include <inttypes.h>
32 #include <langinfo.h>
33 #include <libdw.h>
34 #include <libdwfl.h>
35 #include <libintl.h>
36 #include <locale.h>
37 #include <stdarg.h>
38 #include <stdbool.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <time.h>
42 #include <unistd.h>
43 #include <sys/param.h>
44 #include <sys/stat.h>
45 #include <signal.h>
46
47 #include <system.h>
48 #include "../libelf/libelfP.h"
49 #include "../libelf/common.h"
50 #include "../libebl/libeblP.h"
51 #include "../libdw/libdwP.h"
52 #include "../libdwfl/libdwflP.h"
53 #include "../libdw/memory-access.h"
54
55 #include "../libdw/known-dwarf.h"
56
57
58 /* Name and version of program.  */
59 static void print_version (FILE *stream, struct argp_state *state);
60 ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
61
62 /* Bug report address.  */
63 ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
64
65 /* argp key value for --elf-section, non-ascii.  */
66 #define ELF_INPUT_SECTION 256
67
68 /* Definitions of arguments for argp functions.  */
69 static const struct argp_option options[] =
70 {
71   { NULL, 0, NULL, 0, N_("ELF input selection:"), 0 },
72   { "elf-section", ELF_INPUT_SECTION, "SECTION", OPTION_ARG_OPTIONAL,
73     N_("Use the named SECTION (default .gnu_debugdata) as (compressed) ELF "
74        "input data"), 0 },
75   { NULL, 0, NULL, 0, N_("ELF output selection:"), 0 },
76   { "all", 'a', NULL, 0,
77     N_("All these plus -p .strtab -p .dynstr -p .comment"), 0 },
78   { "dynamic", 'd', NULL, 0, N_("Display the dynamic segment"), 0 },
79   { "file-header", 'h', NULL, 0, N_("Display the ELF file header"), 0 },
80   { "histogram", 'I', NULL, 0,
81     N_("Display histogram of bucket list lengths"), 0 },
82   { "program-headers", 'l', NULL, 0, N_("Display the program headers"), 0 },
83   { "segments", 'l', NULL, OPTION_ALIAS | OPTION_HIDDEN, NULL, 0 },
84   { "relocs", 'r', NULL, 0, N_("Display relocations"), 0 },
85   { "section-headers", 'S', NULL, 0, N_("Display the sections' headers"), 0 },
86   { "sections", 'S', NULL, OPTION_ALIAS | OPTION_HIDDEN, NULL, 0 },
87   { "symbols", 's', NULL, 0, N_("Display the symbol table"), 0 },
88   { "version-info", 'V', NULL, 0, N_("Display versioning information"), 0 },
89   { "notes", 'n', NULL, 0, N_("Display the ELF notes"), 0 },
90   { "arch-specific", 'A', NULL, 0,
91     N_("Display architecture specific information, if any"), 0 },
92   { "exception", 'e', NULL, 0,
93     N_("Display sections for exception handling"), 0 },
94
95   { NULL, 0, NULL, 0, N_("Additional output selection:"), 0 },
96   { "debug-dump", 'w', "SECTION", OPTION_ARG_OPTIONAL,
97     N_("Display DWARF section content.  SECTION can be one of abbrev, "
98        "aranges, decodedaranges, frame, gdb_index, info, loc, line, "
99        "decodedline, ranges, pubnames, str, macinfo, macro or exception"), 0 },
100   { "hex-dump", 'x', "SECTION", 0,
101     N_("Dump the uninterpreted contents of SECTION, by number or name"), 0 },
102   { "strings", 'p', "SECTION", OPTION_ARG_OPTIONAL,
103     N_("Print string contents of sections"), 0 },
104   { "string-dump", 'p', NULL, OPTION_ALIAS | OPTION_HIDDEN, NULL, 0 },
105   { "archive-index", 'c', NULL, 0,
106     N_("Display the symbol index of an archive"), 0 },
107
108   { NULL, 0, NULL, 0, N_("Output control:"), 0 },
109   { "numeric-addresses", 'N', NULL, 0,
110     N_("Do not find symbol names for addresses in DWARF data"), 0 },
111   { "unresolved-address-offsets", 'U', NULL, 0,
112     N_("Display just offsets instead of resolving values to addresses in DWARF data"), 0 },
113   { "wide", 'W', NULL, 0,
114     N_("Ignored for compatibility (lines always wide)"), 0 },
115   { NULL, 0, NULL, 0, NULL, 0 }
116 };
117
118 /* Short description of program.  */
119 static const char doc[] = N_("\
120 Print information from ELF file in human-readable form.");
121
122 /* Strings for arguments in help texts.  */
123 static const char args_doc[] = N_("FILE...");
124
125 /* Prototype for option handler.  */
126 static error_t parse_opt (int key, char *arg, struct argp_state *state);
127
128 /* Data structure to communicate with argp functions.  */
129 static struct argp argp =
130 {
131   options, parse_opt, args_doc, doc, NULL, NULL, NULL
132 };
133
134 /* If non-null, the section from which we should read to (compressed) ELF.  */
135 static const char *elf_input_section = NULL;
136
137 /* Flags set by the option controlling the output.  */
138
139 /* True if dynamic segment should be printed.  */
140 static bool print_dynamic_table;
141
142 /* True if the file header should be printed.  */
143 static bool print_file_header;
144
145 /* True if the program headers should be printed.  */
146 static bool print_program_header;
147
148 /* True if relocations should be printed.  */
149 static bool print_relocations;
150
151 /* True if the section headers should be printed.  */
152 static bool print_section_header;
153
154 /* True if the symbol table should be printed.  */
155 static bool print_symbol_table;
156
157 /* True if the version information should be printed.  */
158 static bool print_version_info;
159
160 /* True if section groups should be printed.  */
161 static bool print_section_groups;
162
163 /* True if bucket list length histogram should be printed.  */
164 static bool print_histogram;
165
166 /* True if the architecture specific data should be printed.  */
167 static bool print_arch;
168
169 /* True if note section content should be printed.  */
170 static bool print_notes;
171
172 /* True if SHF_STRINGS section content should be printed.  */
173 static bool print_string_sections;
174
175 /* True if archive index should be printed.  */
176 static bool print_archive_index;
177
178 /* True if any of the control options except print_archive_index is set.  */
179 static bool any_control_option;
180
181 /* True if we should print addresses from DWARF in symbolic form.  */
182 static bool print_address_names = true;
183
184 /* True if we should print raw values instead of relativized addresses.  */
185 static bool print_unresolved_addresses = false;
186
187 /* True if we should print the .debug_aranges section using libdw.  */
188 static bool decodedaranges = false;
189
190 /* True if we should print the .debug_aranges section using libdw.  */
191 static bool decodedline = false;
192
193 /* Select printing of debugging sections.  */
194 static enum section_e
195 {
196   section_abbrev = 1,           /* .debug_abbrev  */
197   section_aranges = 2,          /* .debug_aranges  */
198   section_frame = 4,            /* .debug_frame or .eh_frame & al.  */
199   section_info = 8,             /* .debug_info, .debug_types  */
200   section_types = section_info,
201   section_line = 16,            /* .debug_line  */
202   section_loc = 32,             /* .debug_loc  */
203   section_pubnames = 64,        /* .debug_pubnames  */
204   section_str = 128,            /* .debug_str  */
205   section_macinfo = 256,        /* .debug_macinfo  */
206   section_ranges = 512,         /* .debug_ranges  */
207   section_exception = 1024,     /* .eh_frame & al.  */
208   section_gdb_index = 2048,     /* .gdb_index  */
209   section_macro = 4096,         /* .debug_macro  */
210   section_all = (section_abbrev | section_aranges | section_frame
211                  | section_info | section_line | section_loc
212                  | section_pubnames | section_str | section_macinfo
213                  | section_ranges | section_exception | section_gdb_index
214                  | section_macro)
215 } print_debug_sections, implicit_debug_sections;
216
217 /* Select hex dumping of sections.  */
218 static struct section_argument *dump_data_sections;
219 static struct section_argument **dump_data_sections_tail = &dump_data_sections;
220
221 /* Select string dumping of sections.  */
222 static struct section_argument *string_sections;
223 static struct section_argument **string_sections_tail = &string_sections;
224
225 struct section_argument
226 {
227   struct section_argument *next;
228   const char *arg;
229   bool implicit;
230 };
231
232 /* Numbers of sections and program headers in the file.  */
233 static size_t shnum;
234 static size_t phnum;
235
236
237 /* Declarations of local functions.  */
238 static void process_file (int fd, const char *fname, bool only_one);
239 static void process_elf_file (Dwfl_Module *dwflmod, int fd);
240 static void print_ehdr (Ebl *ebl, GElf_Ehdr *ehdr);
241 static void print_shdr (Ebl *ebl, GElf_Ehdr *ehdr);
242 static void print_phdr (Ebl *ebl, GElf_Ehdr *ehdr);
243 static void print_scngrp (Ebl *ebl);
244 static void print_dynamic (Ebl *ebl);
245 static void print_relocs (Ebl *ebl, GElf_Ehdr *ehdr);
246 static void handle_relocs_rel (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn,
247                                GElf_Shdr *shdr);
248 static void handle_relocs_rela (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn,
249                                 GElf_Shdr *shdr);
250 static void print_symtab (Ebl *ebl, int type);
251 static void handle_symtab (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr);
252 static void print_verinfo (Ebl *ebl);
253 static void handle_verneed (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr);
254 static void handle_verdef (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr);
255 static void handle_versym (Ebl *ebl, Elf_Scn *scn,
256                            GElf_Shdr *shdr);
257 static void print_debug (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr);
258 static void handle_hash (Ebl *ebl);
259 static void handle_notes (Ebl *ebl, GElf_Ehdr *ehdr);
260 static void print_liblist (Ebl *ebl);
261 static void print_attributes (Ebl *ebl, const GElf_Ehdr *ehdr);
262 static void dump_data (Ebl *ebl);
263 static void dump_strings (Ebl *ebl);
264 static void print_strings (Ebl *ebl);
265 static void dump_archive_index (Elf *, const char *);
266
267
268 int
269 main (int argc, char *argv[])
270 {
271   /* Set locale.  */
272   setlocale (LC_ALL, "");
273
274   /* Initialize the message catalog.  */
275   textdomain (PACKAGE_TARNAME);
276
277   /* Parse and process arguments.  */
278   int remaining;
279   argp_parse (&argp, argc, argv, 0, &remaining, NULL);
280
281   /* Before we start tell the ELF library which version we are using.  */
282   elf_version (EV_CURRENT);
283
284   /* Now process all the files given at the command line.  */
285   bool only_one = remaining + 1 == argc;
286   do
287     {
288       /* Open the file.  */
289       int fd = open (argv[remaining], O_RDONLY);
290       if (fd == -1)
291         {
292           error (0, errno, gettext ("cannot open input file"));
293           continue;
294         }
295
296       process_file (fd, argv[remaining], only_one);
297
298       close (fd);
299     }
300   while (++remaining < argc);
301
302   return error_message_count != 0;
303 }
304
305
306 /* Handle program arguments.  */
307 static error_t
308 parse_opt (int key, char *arg,
309            struct argp_state *state __attribute__ ((unused)))
310 {
311   void add_dump_section (const char *name, bool implicit)
312   {
313     struct section_argument *a = xmalloc (sizeof *a);
314     a->arg = name;
315     a->next = NULL;
316     a->implicit = implicit;
317     struct section_argument ***tailp
318       = key == 'x' ? &dump_data_sections_tail : &string_sections_tail;
319     **tailp = a;
320     *tailp = &a->next;
321   }
322
323   switch (key)
324     {
325     case 'a':
326       print_file_header = true;
327       print_program_header = true;
328       print_relocations = true;
329       print_section_header = true;
330       print_symbol_table = true;
331       print_version_info = true;
332       print_dynamic_table = true;
333       print_section_groups = true;
334       print_histogram = true;
335       print_arch = true;
336       print_notes = true;
337       implicit_debug_sections |= section_exception;
338       add_dump_section (".strtab", true);
339       add_dump_section (".dynstr", true);
340       add_dump_section (".comment", true);
341       any_control_option = true;
342       break;
343     case 'A':
344       print_arch = true;
345       any_control_option = true;
346       break;
347     case 'd':
348       print_dynamic_table = true;
349       any_control_option = true;
350       break;
351     case 'e':
352       print_debug_sections |= section_exception;
353       any_control_option = true;
354       break;
355     case 'g':
356       print_section_groups = true;
357       any_control_option = true;
358       break;
359     case 'h':
360       print_file_header = true;
361       any_control_option = true;
362       break;
363     case 'I':
364       print_histogram = true;
365       any_control_option = true;
366       break;
367     case 'l':
368       print_program_header = true;
369       any_control_option = true;
370       break;
371     case 'n':
372       print_notes = true;
373       any_control_option = true;
374       break;
375     case 'r':
376       print_relocations = true;
377       any_control_option = true;
378      break;
379     case 'S':
380       print_section_header = true;
381       any_control_option = true;
382       break;
383     case 's':
384       print_symbol_table = true;
385       any_control_option = true;
386       break;
387     case 'V':
388       print_version_info = true;
389       any_control_option = true;
390       break;
391     case 'c':
392       print_archive_index = true;
393       break;
394     case 'w':
395       if (arg == NULL)
396         print_debug_sections = section_all;
397       else if (strcmp (arg, "abbrev") == 0)
398         print_debug_sections |= section_abbrev;
399       else if (strcmp (arg, "aranges") == 0)
400         print_debug_sections |= section_aranges;
401       else if (strcmp (arg, "decodedaranges") == 0)
402         {
403           print_debug_sections |= section_aranges;
404           decodedaranges = true;
405         }
406       else if (strcmp (arg, "ranges") == 0)
407         {
408           print_debug_sections |= section_ranges;
409           implicit_debug_sections |= section_info;
410         }
411       else if (strcmp (arg, "frame") == 0 || strcmp (arg, "frames") == 0)
412         print_debug_sections |= section_frame;
413       else if (strcmp (arg, "info") == 0)
414         print_debug_sections |= section_info;
415       else if (strcmp (arg, "loc") == 0)
416         {
417           print_debug_sections |= section_loc;
418           implicit_debug_sections |= section_info;
419         }
420       else if (strcmp (arg, "line") == 0)
421         print_debug_sections |= section_line;
422       else if (strcmp (arg, "decodedline") == 0)
423         {
424           print_debug_sections |= section_line;
425           decodedline = true;
426         }
427       else if (strcmp (arg, "pubnames") == 0)
428         print_debug_sections |= section_pubnames;
429       else if (strcmp (arg, "str") == 0)
430         print_debug_sections |= section_str;
431       else if (strcmp (arg, "macinfo") == 0)
432         print_debug_sections |= section_macinfo;
433       else if (strcmp (arg, "macro") == 0)
434         print_debug_sections |= section_macro;
435       else if (strcmp (arg, "exception") == 0)
436         print_debug_sections |= section_exception;
437       else if (strcmp (arg, "gdb_index") == 0)
438         print_debug_sections |= section_gdb_index;
439       else
440         {
441           fprintf (stderr, gettext ("Unknown DWARF debug section `%s'.\n"),
442                    arg);
443           argp_help (&argp, stderr, ARGP_HELP_SEE,
444                      program_invocation_short_name);
445           exit (1);
446         }
447       any_control_option = true;
448       break;
449     case 'p':
450       any_control_option = true;
451       if (arg == NULL)
452         {
453           print_string_sections = true;
454           break;
455         }
456       /* Fall through.  */
457     case 'x':
458       add_dump_section (arg, false);
459       any_control_option = true;
460       break;
461     case 'N':
462       print_address_names = false;
463       break;
464     case 'U':
465       print_unresolved_addresses = true;
466       break;
467     case ARGP_KEY_NO_ARGS:
468       fputs (gettext ("Missing file name.\n"), stderr);
469       goto do_argp_help;
470     case ARGP_KEY_FINI:
471       if (! any_control_option && ! print_archive_index)
472         {
473           fputs (gettext ("No operation specified.\n"), stderr);
474         do_argp_help:
475           argp_help (&argp, stderr, ARGP_HELP_SEE,
476                      program_invocation_short_name);
477           exit (EXIT_FAILURE);
478         }
479       break;
480     case 'W':                   /* Ignored.  */
481       break;
482     case ELF_INPUT_SECTION:
483       if (arg == NULL)
484         elf_input_section = ".gnu_debugdata";
485       else
486         elf_input_section = arg;
487       break;
488     default:
489       return ARGP_ERR_UNKNOWN;
490     }
491   return 0;
492 }
493
494
495 /* Print the version information.  */
496 static void
497 print_version (FILE *stream, struct argp_state *state __attribute__ ((unused)))
498 {
499   fprintf (stream, "readelf (%s) %s\n", PACKAGE_NAME, PACKAGE_VERSION);
500   fprintf (stream, gettext ("\
501 Copyright (C) %s Red Hat, Inc.\n\
502 This is free software; see the source for copying conditions.  There is NO\n\
503 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
504 "), "2012");
505   fprintf (stream, gettext ("Written by %s.\n"), "Ulrich Drepper");
506 }
507
508
509 /* Create a file descriptor to read the data from the
510    elf_input_section given a file descriptor to an ELF file.  */
511 static int
512 open_input_section (int fd)
513 {
514   size_t shnums;
515   size_t cnt;
516   size_t shstrndx;
517   Elf *elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
518   if (elf == NULL)
519     {
520       error (0, 0, gettext ("cannot generate Elf descriptor: %s"),
521              elf_errmsg (-1));
522       return -1;
523     }
524
525   if (elf_getshdrnum (elf, &shnums) < 0)
526     {
527       error (0, 0, gettext ("cannot determine number of sections: %s"),
528              elf_errmsg (-1));
529     open_error:
530       elf_end (elf);
531       return -1;
532     }
533
534   if (elf_getshdrstrndx (elf, &shstrndx) < 0)
535     {
536       error (0, 0, gettext ("cannot get section header string table index"));
537       goto open_error;
538     }
539
540   for (cnt = 0; cnt < shnums; ++cnt)
541     {
542       Elf_Scn *scn = elf_getscn (elf, cnt);
543       if (scn == NULL)
544         {
545           error (0, 0, gettext ("cannot get section: %s"),
546                  elf_errmsg (-1));
547           goto open_error;
548         }
549
550       GElf_Shdr shdr_mem;
551       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
552       if (unlikely (shdr == NULL))
553         {
554           error (0, 0, gettext ("cannot get section header: %s"),
555                  elf_errmsg (-1));
556           goto open_error;
557         }
558
559       const char *sname = elf_strptr (elf, shstrndx, shdr->sh_name);
560       if (sname == NULL)
561         {
562           error (0, 0, gettext ("cannot get section name"));
563           goto open_error;
564         }
565
566       if (strcmp (sname, elf_input_section) == 0)
567         {
568           Elf_Data *data = elf_rawdata (scn, NULL);
569           if (data == NULL)
570             {
571               error (0, 0, gettext ("cannot get %s content: %s"),
572                      sname, elf_errmsg (-1));
573               goto open_error;
574             }
575
576           /* Create (and immediately unlink) a temporary file to store
577              section data in to create a file descriptor for it.  */
578           const char *tmpdir = getenv ("TMPDIR") ?: P_tmpdir;
579           static const char suffix[] = "/readelfXXXXXX";
580           int tmplen = strlen (tmpdir) + sizeof (suffix);
581           char *tempname = alloca (tmplen);
582           sprintf (tempname, "%s%s", tmpdir, suffix);
583
584           int sfd = mkstemp (tempname);
585           if (sfd == -1)
586             {
587               error (0, 0, gettext ("cannot create temp file '%s'"),
588                      tempname);
589               goto open_error;
590             }
591           unlink (tempname);
592
593           ssize_t size = data->d_size;
594           if (write_retry (sfd, data->d_buf, size) != size)
595             {
596               error (0, 0, gettext ("cannot write section data"));
597               goto open_error;
598             }
599
600           if (elf_end (elf) != 0)
601             {
602               error (0, 0, gettext ("error while closing Elf descriptor: %s"),
603                      elf_errmsg (-1));
604               return -1;
605             }
606
607           if (lseek (sfd, 0, SEEK_SET) == -1)
608             {
609               error (0, 0, gettext ("error while rewinding file descriptor"));
610               return -1;
611             }
612
613           return sfd;
614         }
615     }
616
617   /* Named section not found.  */
618   if (elf_end (elf) != 0)
619     error (0, 0, gettext ("error while closing Elf descriptor: %s"),
620            elf_errmsg (-1));
621   return -1;
622 }
623
624 /* Check if the file is an archive, and if so dump its index.  */
625 static void
626 check_archive_index (int fd, const char *fname, bool only_one)
627 {
628   /* Create an `Elf' descriptor.  */
629   Elf *elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
630   if (elf == NULL)
631     error (0, 0, gettext ("cannot generate Elf descriptor: %s"),
632            elf_errmsg (-1));
633   else
634     {
635       if (elf_kind (elf) == ELF_K_AR)
636         {
637           if (!only_one)
638             printf ("\n%s:\n\n", fname);
639           dump_archive_index (elf, fname);
640         }
641       else
642         error (0, 0,
643                gettext ("'%s' is not an archive, cannot print archive index"),
644                fname);
645
646       /* Now we can close the descriptor.  */
647       if (elf_end (elf) != 0)
648         error (0, 0, gettext ("error while closing Elf descriptor: %s"),
649                elf_errmsg (-1));
650     }
651 }
652
653 /* Trivial callback used for checking if we opened an archive.  */
654 static int
655 count_dwflmod (Dwfl_Module *dwflmod __attribute__ ((unused)),
656                void **userdata __attribute__ ((unused)),
657                const char *name __attribute__ ((unused)),
658                Dwarf_Addr base __attribute__ ((unused)),
659                void *arg)
660 {
661   if (*(bool *) arg)
662     return DWARF_CB_ABORT;
663   *(bool *) arg = true;
664   return DWARF_CB_OK;
665 }
666
667 struct process_dwflmod_args
668 {
669   int fd;
670   bool only_one;
671 };
672
673 static int
674 process_dwflmod (Dwfl_Module *dwflmod,
675                  void **userdata __attribute__ ((unused)),
676                  const char *name __attribute__ ((unused)),
677                  Dwarf_Addr base __attribute__ ((unused)),
678                  void *arg)
679 {
680   const struct process_dwflmod_args *a = arg;
681
682   /* Print the file name.  */
683   if (!a->only_one)
684     {
685       const char *fname;
686       dwfl_module_info (dwflmod, NULL, NULL, NULL, NULL, NULL, &fname, NULL);
687
688       printf ("\n%s:\n\n", fname);
689     }
690
691   process_elf_file (dwflmod, a->fd);
692
693   return DWARF_CB_OK;
694 }
695
696 /* Stub libdwfl callback, only the ELF handle already open is ever used.
697    Only used for finding the alternate debug file if the Dwarf comes from
698    the main file.  We are not interested in separate debuginfo.  */
699 static int
700 find_no_debuginfo (Dwfl_Module *mod,
701                    void **userdata,
702                    const char *modname,
703                    Dwarf_Addr base,
704                    const char *file_name,
705                    const char *debuglink_file,
706                    GElf_Word debuglink_crc,
707                    char **debuginfo_file_name)
708 {
709   Dwarf_Addr dwbias;
710   dwfl_module_info (mod, NULL, NULL, NULL, &dwbias, NULL, NULL, NULL);
711
712   /* We are only interested if the Dwarf has been setup on the main
713      elf file but is only missing the alternate debug link.  If dwbias
714      hasn't even been setup, this is searching for separate debuginfo
715      for the main elf.  We don't care in that case.  */
716   if (dwbias == (Dwarf_Addr) -1)
717     return -1;
718
719   return dwfl_standard_find_debuginfo (mod, userdata, modname, base,
720                                        file_name, debuglink_file,
721                                        debuglink_crc, debuginfo_file_name);
722 }
723
724 /* Process one input file.  */
725 static void
726 process_file (int fd, const char *fname, bool only_one)
727 {
728   if (print_archive_index)
729     check_archive_index (fd, fname, only_one);
730
731   if (!any_control_option)
732     return;
733
734   if (elf_input_section != NULL)
735     {
736       /* Replace fname and fd with section content. */
737       char *fnname = alloca (strlen (fname) + strlen (elf_input_section) + 2);
738       sprintf (fnname, "%s:%s", fname, elf_input_section);
739       fd = open_input_section (fd);
740       if (fd == -1)
741         {
742           error (0, 0, gettext ("No such section '%s' in '%s'"),
743                  elf_input_section, fname);
744           return;
745         }
746       fname = fnname;
747     }
748
749   /* Duplicate an fd for dwfl_report_offline to swallow.  */
750   int dwfl_fd = dup (fd);
751   if (unlikely (dwfl_fd < 0))
752     error (EXIT_FAILURE, errno, "dup");
753
754   /* Use libdwfl in a trivial way to open the libdw handle for us.
755      This takes care of applying relocations to DWARF data in ET_REL files.  */
756   static const Dwfl_Callbacks callbacks =
757     {
758       .section_address = dwfl_offline_section_address,
759       .find_debuginfo = find_no_debuginfo
760     };
761   Dwfl *dwfl = dwfl_begin (&callbacks);
762   if (likely (dwfl != NULL))
763     /* Let 0 be the logical address of the file (or first in archive).  */
764     dwfl->offline_next_address = 0;
765   if (dwfl_report_offline (dwfl, fname, fname, dwfl_fd) == NULL)
766     {
767       struct stat64 st;
768       if (fstat64 (dwfl_fd, &st) != 0)
769         error (0, errno, gettext ("cannot stat input file"));
770       else if (unlikely (st.st_size == 0))
771         error (0, 0, gettext ("input file is empty"));
772       else
773         error (0, 0, gettext ("failed reading '%s': %s"),
774                fname, dwfl_errmsg (-1));
775       close (dwfl_fd);          /* Consumed on success, not on failure.  */
776     }
777   else
778     {
779       dwfl_report_end (dwfl, NULL, NULL);
780
781       if (only_one)
782         {
783           /* Clear ONLY_ONE if we have multiple modules, from an archive.  */
784           bool seen = false;
785           only_one = dwfl_getmodules (dwfl, &count_dwflmod, &seen, 0) == 0;
786         }
787
788       /* Process the one or more modules gleaned from this file.  */
789       struct process_dwflmod_args a = { .fd = fd, .only_one = only_one };
790       dwfl_getmodules (dwfl, &process_dwflmod, &a, 0);
791     }
792   dwfl_end (dwfl);
793
794   /* Need to close the replaced fd if we created it.  Caller takes
795      care of original.  */
796   if (elf_input_section != NULL)
797     close (fd);
798 }
799
800
801 /* Process one ELF file.  */
802 static void
803 process_elf_file (Dwfl_Module *dwflmod, int fd)
804 {
805   GElf_Addr dwflbias;
806   Elf *elf = dwfl_module_getelf (dwflmod, &dwflbias);
807
808   GElf_Ehdr ehdr_mem;
809   GElf_Ehdr *ehdr = gelf_getehdr (elf, &ehdr_mem);
810
811   if (ehdr == NULL)
812     {
813     elf_error:
814       error (0, 0, gettext ("cannot read ELF header: %s"), elf_errmsg (-1));
815       return;
816     }
817
818   Ebl *ebl = ebl_openbackend (elf);
819   if (unlikely (ebl == NULL))
820     {
821     ebl_error:
822       error (0, errno, gettext ("cannot create EBL handle"));
823       return;
824     }
825
826   /* Determine the number of sections.  */
827   if (unlikely (elf_getshdrnum (ebl->elf, &shnum) < 0))
828     error (EXIT_FAILURE, 0,
829            gettext ("cannot determine number of sections: %s"),
830            elf_errmsg (-1));
831
832   /* Determine the number of phdrs.  */
833   if (unlikely (elf_getphdrnum (ebl->elf, &phnum) < 0))
834     error (EXIT_FAILURE, 0,
835            gettext ("cannot determine number of program headers: %s"),
836            elf_errmsg (-1));
837
838   /* For an ET_REL file, libdwfl has adjusted the in-core shdrs
839      and may have applied relocation to some sections.
840      So we need to get a fresh Elf handle on the file to display those.  */
841   bool print_unrelocated = (print_section_header
842                             || print_relocations
843                             || dump_data_sections != NULL
844                             || print_notes);
845
846   Elf *pure_elf = NULL;
847   Ebl *pure_ebl = ebl;
848   if (ehdr->e_type == ET_REL && print_unrelocated)
849     {
850       /* Read the file afresh.  */
851       off64_t aroff = elf_getaroff (elf);
852       pure_elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
853       if (aroff > 0)
854         {
855           /* Archive member.  */
856           (void) elf_rand (pure_elf, aroff);
857           Elf *armem = elf_begin (-1, ELF_C_READ_MMAP, pure_elf);
858           elf_end (pure_elf);
859           pure_elf = armem;
860         }
861       if (pure_elf == NULL)
862         goto elf_error;
863       pure_ebl = ebl_openbackend (pure_elf);
864       if (pure_ebl == NULL)
865         goto ebl_error;
866     }
867
868   if (print_file_header)
869     print_ehdr (ebl, ehdr);
870   if (print_section_header)
871     print_shdr (pure_ebl, ehdr);
872   if (print_program_header)
873     print_phdr (ebl, ehdr);
874   if (print_section_groups)
875     print_scngrp (ebl);
876   if (print_dynamic_table)
877     print_dynamic (ebl);
878   if (print_relocations)
879     print_relocs (pure_ebl, ehdr);
880   if (print_histogram)
881     handle_hash (ebl);
882   if (print_symbol_table)
883     print_symtab (ebl, SHT_DYNSYM);
884   if (print_version_info)
885     print_verinfo (ebl);
886   if (print_symbol_table)
887     print_symtab (ebl, SHT_SYMTAB);
888   if (print_arch)
889     print_liblist (ebl);
890   if (print_arch)
891     print_attributes (ebl, ehdr);
892   if (dump_data_sections != NULL)
893     dump_data (pure_ebl);
894   if (string_sections != NULL)
895     dump_strings (ebl);
896   if ((print_debug_sections | implicit_debug_sections) != 0)
897     print_debug (dwflmod, ebl, ehdr);
898   if (print_notes)
899     handle_notes (pure_ebl, ehdr);
900   if (print_string_sections)
901     print_strings (ebl);
902
903   ebl_closebackend (ebl);
904
905   if (pure_ebl != ebl)
906     {
907       ebl_closebackend (pure_ebl);
908       elf_end (pure_elf);
909     }
910 }
911
912
913 /* Print file type.  */
914 static void
915 print_file_type (unsigned short int e_type)
916 {
917   if (likely (e_type <= ET_CORE))
918     {
919       static const char *const knowntypes[] =
920       {
921         N_("NONE (None)"),
922         N_("REL (Relocatable file)"),
923         N_("EXEC (Executable file)"),
924         N_("DYN (Shared object file)"),
925         N_("CORE (Core file)")
926       };
927       puts (gettext (knowntypes[e_type]));
928     }
929   else if (e_type >= ET_LOOS && e_type <= ET_HIOS)
930     printf (gettext ("OS Specific: (%x)\n"),  e_type);
931   else if (e_type >= ET_LOPROC /* && e_type <= ET_HIPROC always true */)
932     printf (gettext ("Processor Specific: (%x)\n"),  e_type);
933   else
934     puts ("???");
935 }
936
937
938 /* Print ELF header.  */
939 static void
940 print_ehdr (Ebl *ebl, GElf_Ehdr *ehdr)
941 {
942   fputs_unlocked (gettext ("ELF Header:\n  Magic:  "), stdout);
943   for (size_t cnt = 0; cnt < EI_NIDENT; ++cnt)
944     printf (" %02hhx", ehdr->e_ident[cnt]);
945
946   printf (gettext ("\n  Class:                             %s\n"),
947           ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? "ELF32"
948           : ehdr->e_ident[EI_CLASS] == ELFCLASS64 ? "ELF64"
949           : "\?\?\?");
950
951   printf (gettext ("  Data:                              %s\n"),
952           ehdr->e_ident[EI_DATA] == ELFDATA2LSB
953           ? "2's complement, little endian"
954           : ehdr->e_ident[EI_DATA] == ELFDATA2MSB
955           ? "2's complement, big endian" : "\?\?\?");
956
957   printf (gettext ("  Ident Version:                     %hhd %s\n"),
958           ehdr->e_ident[EI_VERSION],
959           ehdr->e_ident[EI_VERSION] == EV_CURRENT ? gettext ("(current)")
960           : "(\?\?\?)");
961
962   char buf[512];
963   printf (gettext ("  OS/ABI:                            %s\n"),
964           ebl_osabi_name (ebl, ehdr->e_ident[EI_OSABI], buf, sizeof (buf)));
965
966   printf (gettext ("  ABI Version:                       %hhd\n"),
967           ehdr->e_ident[EI_ABIVERSION]);
968
969   fputs_unlocked (gettext ("  Type:                              "), stdout);
970   print_file_type (ehdr->e_type);
971
972   printf (gettext ("  Machine:                           %s\n"), ebl->name);
973
974   printf (gettext ("  Version:                           %d %s\n"),
975           ehdr->e_version,
976           ehdr->e_version  == EV_CURRENT ? gettext ("(current)") : "(\?\?\?)");
977
978   printf (gettext ("  Entry point address:               %#" PRIx64 "\n"),
979           ehdr->e_entry);
980
981   printf (gettext ("  Start of program headers:          %" PRId64 " %s\n"),
982           ehdr->e_phoff, gettext ("(bytes into file)"));
983
984   printf (gettext ("  Start of section headers:          %" PRId64 " %s\n"),
985           ehdr->e_shoff, gettext ("(bytes into file)"));
986
987   printf (gettext ("  Flags:                             %s\n"),
988           ebl_machine_flag_name (ebl, ehdr->e_flags, buf, sizeof (buf)));
989
990   printf (gettext ("  Size of this header:               %" PRId16 " %s\n"),
991           ehdr->e_ehsize, gettext ("(bytes)"));
992
993   printf (gettext ("  Size of program header entries:    %" PRId16 " %s\n"),
994           ehdr->e_phentsize, gettext ("(bytes)"));
995
996   printf (gettext ("  Number of program headers entries: %" PRId16),
997           ehdr->e_phnum);
998   if (ehdr->e_phnum == PN_XNUM)
999     {
1000       GElf_Shdr shdr_mem;
1001       GElf_Shdr *shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
1002       if (shdr != NULL)
1003         printf (gettext (" (%" PRIu32 " in [0].sh_info)"),
1004                 (uint32_t) shdr->sh_info);
1005       else
1006         fputs_unlocked (gettext (" ([0] not available)"), stdout);
1007     }
1008   fputc_unlocked ('\n', stdout);
1009
1010   printf (gettext ("  Size of section header entries:    %" PRId16 " %s\n"),
1011           ehdr->e_shentsize, gettext ("(bytes)"));
1012
1013   printf (gettext ("  Number of section headers entries: %" PRId16),
1014           ehdr->e_shnum);
1015   if (ehdr->e_shnum == 0)
1016     {
1017       GElf_Shdr shdr_mem;
1018       GElf_Shdr *shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
1019       if (shdr != NULL)
1020         printf (gettext (" (%" PRIu32 " in [0].sh_size)"),
1021                 (uint32_t) shdr->sh_size);
1022       else
1023         fputs_unlocked (gettext (" ([0] not available)"), stdout);
1024     }
1025   fputc_unlocked ('\n', stdout);
1026
1027   if (unlikely (ehdr->e_shstrndx == SHN_XINDEX))
1028     {
1029       GElf_Shdr shdr_mem;
1030       GElf_Shdr *shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
1031       if (shdr != NULL)
1032         /* We managed to get the zeroth section.  */
1033         snprintf (buf, sizeof (buf), gettext (" (%" PRIu32 " in [0].sh_link)"),
1034                   (uint32_t) shdr->sh_link);
1035       else
1036         {
1037           strncpy (buf, gettext (" ([0] not available)"), sizeof (buf));
1038           buf[sizeof (buf) - 1] = '\0';
1039         }
1040
1041       printf (gettext ("  Section header string table index: XINDEX%s\n\n"),
1042               buf);
1043     }
1044   else
1045     printf (gettext ("  Section header string table index: %" PRId16 "\n\n"),
1046             ehdr->e_shstrndx);
1047 }
1048
1049
1050 static const char *
1051 get_visibility_type (int value)
1052 {
1053   switch (value)
1054     {
1055     case STV_DEFAULT:
1056       return "DEFAULT";
1057     case STV_INTERNAL:
1058       return "INTERNAL";
1059     case STV_HIDDEN:
1060       return "HIDDEN";
1061     case STV_PROTECTED:
1062       return "PROTECTED";
1063     default:
1064       return "???";
1065     }
1066 }
1067
1068
1069 /* Print the section headers.  */
1070 static void
1071 print_shdr (Ebl *ebl, GElf_Ehdr *ehdr)
1072 {
1073   size_t cnt;
1074   size_t shstrndx;
1075
1076   if (! print_file_header)
1077     printf (gettext ("\
1078 There are %d section headers, starting at offset %#" PRIx64 ":\n\
1079 \n"),
1080             ehdr->e_shnum, ehdr->e_shoff);
1081
1082   /* Get the section header string table index.  */
1083   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1084     error (EXIT_FAILURE, 0,
1085            gettext ("cannot get section header string table index"));
1086
1087   puts (gettext ("Section Headers:"));
1088
1089   if (ehdr->e_ident[EI_CLASS] == ELFCLASS32)
1090     puts (gettext ("[Nr] Name                 Type         Addr     Off    Size   ES Flags Lk Inf Al"));
1091   else
1092     puts (gettext ("[Nr] Name                 Type         Addr             Off      Size     ES Flags Lk Inf Al"));
1093
1094   for (cnt = 0; cnt < shnum; ++cnt)
1095     {
1096       Elf_Scn *scn = elf_getscn (ebl->elf, cnt);
1097
1098       if (unlikely (scn == NULL))
1099         error (EXIT_FAILURE, 0, gettext ("cannot get section: %s"),
1100                elf_errmsg (-1));
1101
1102       /* Get the section header.  */
1103       GElf_Shdr shdr_mem;
1104       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1105       if (unlikely (shdr == NULL))
1106         error (EXIT_FAILURE, 0, gettext ("cannot get section header: %s"),
1107                elf_errmsg (-1));
1108
1109       char flagbuf[20];
1110       char *cp = flagbuf;
1111       if (shdr->sh_flags & SHF_WRITE)
1112         *cp++ = 'W';
1113       if (shdr->sh_flags & SHF_ALLOC)
1114         *cp++ = 'A';
1115       if (shdr->sh_flags & SHF_EXECINSTR)
1116         *cp++ = 'X';
1117       if (shdr->sh_flags & SHF_MERGE)
1118         *cp++ = 'M';
1119       if (shdr->sh_flags & SHF_STRINGS)
1120         *cp++ = 'S';
1121       if (shdr->sh_flags & SHF_INFO_LINK)
1122         *cp++ = 'I';
1123       if (shdr->sh_flags & SHF_LINK_ORDER)
1124         *cp++ = 'L';
1125       if (shdr->sh_flags & SHF_OS_NONCONFORMING)
1126         *cp++ = 'N';
1127       if (shdr->sh_flags & SHF_GROUP)
1128         *cp++ = 'G';
1129       if (shdr->sh_flags & SHF_TLS)
1130         *cp++ = 'T';
1131       if (shdr->sh_flags & SHF_ORDERED)
1132         *cp++ = 'O';
1133       if (shdr->sh_flags & SHF_EXCLUDE)
1134         *cp++ = 'E';
1135       *cp = '\0';
1136
1137       char buf[128];
1138       printf ("[%2zu] %-20s %-12s %0*" PRIx64 " %0*" PRIx64 " %0*" PRIx64
1139               " %2" PRId64 " %-5s %2" PRId32 " %3" PRId32
1140               " %2" PRId64 "\n",
1141               cnt,
1142               elf_strptr (ebl->elf, shstrndx, shdr->sh_name)
1143               ?: "<corrupt>",
1144               ebl_section_type_name (ebl, shdr->sh_type, buf, sizeof (buf)),
1145               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 8 : 16, shdr->sh_addr,
1146               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 6 : 8, shdr->sh_offset,
1147               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 6 : 8, shdr->sh_size,
1148               shdr->sh_entsize, flagbuf, shdr->sh_link, shdr->sh_info,
1149               shdr->sh_addralign);
1150     }
1151
1152   fputc_unlocked ('\n', stdout);
1153 }
1154
1155
1156 /* Print the program header.  */
1157 static void
1158 print_phdr (Ebl *ebl, GElf_Ehdr *ehdr)
1159 {
1160   if (phnum == 0)
1161     /* No program header, this is OK in relocatable objects.  */
1162     return;
1163
1164   puts (gettext ("Program Headers:"));
1165   if (ehdr->e_ident[EI_CLASS] == ELFCLASS32)
1166     puts (gettext ("\
1167   Type           Offset   VirtAddr   PhysAddr   FileSiz  MemSiz   Flg Align"));
1168   else
1169     puts (gettext ("\
1170   Type           Offset   VirtAddr           PhysAddr           FileSiz  MemSiz   Flg Align"));
1171
1172   /* Process all program headers.  */
1173   bool has_relro = false;
1174   GElf_Addr relro_from = 0;
1175   GElf_Addr relro_to = 0;
1176   for (size_t cnt = 0; cnt < phnum; ++cnt)
1177     {
1178       char buf[128];
1179       GElf_Phdr mem;
1180       GElf_Phdr *phdr = gelf_getphdr (ebl->elf, cnt, &mem);
1181
1182       /* If for some reason the header cannot be returned show this.  */
1183       if (unlikely (phdr == NULL))
1184         {
1185           puts ("  ???");
1186           continue;
1187         }
1188
1189       printf ("  %-14s 0x%06" PRIx64 " 0x%0*" PRIx64 " 0x%0*" PRIx64
1190               " 0x%06" PRIx64 " 0x%06" PRIx64 " %c%c%c 0x%" PRIx64 "\n",
1191               ebl_segment_type_name (ebl, phdr->p_type, buf, sizeof (buf)),
1192               phdr->p_offset,
1193               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 8 : 16, phdr->p_vaddr,
1194               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 8 : 16, phdr->p_paddr,
1195               phdr->p_filesz,
1196               phdr->p_memsz,
1197               phdr->p_flags & PF_R ? 'R' : ' ',
1198               phdr->p_flags & PF_W ? 'W' : ' ',
1199               phdr->p_flags & PF_X ? 'E' : ' ',
1200               phdr->p_align);
1201
1202       if (phdr->p_type == PT_INTERP)
1203         {
1204           /* If we are sure the file offset is valid then we can show
1205              the user the name of the interpreter.  We check whether
1206              there is a section at the file offset.  Normally there
1207              would be a section called ".interp".  But in separate
1208              .debug files it is a NOBITS section (and so doesn't match
1209              with gelf_offscn).  Which probably means the offset is
1210              not valid another reason could be because the ELF file
1211              just doesn't contain any section headers, in that case
1212              just play it safe and don't display anything.  */
1213
1214           Elf_Scn *scn = gelf_offscn (ebl->elf, phdr->p_offset);
1215           GElf_Shdr shdr_mem;
1216           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1217
1218           size_t maxsize;
1219           char *filedata = elf_rawfile (ebl->elf, &maxsize);
1220
1221           if (shdr != NULL && shdr->sh_type == SHT_PROGBITS
1222               && filedata != NULL && phdr->p_offset < maxsize
1223               && phdr->p_filesz <= maxsize - phdr->p_offset
1224               && memchr (filedata + phdr->p_offset, '\0',
1225                          phdr->p_filesz) != NULL)
1226             printf (gettext ("\t[Requesting program interpreter: %s]\n"),
1227                     filedata + phdr->p_offset);
1228         }
1229       else if (phdr->p_type == PT_GNU_RELRO)
1230         {
1231           has_relro = true;
1232           relro_from = phdr->p_vaddr;
1233           relro_to = relro_from + phdr->p_memsz;
1234         }
1235     }
1236
1237   if (ehdr->e_shnum == 0)
1238     /* No sections in the file.  Punt.  */
1239     return;
1240
1241   /* Get the section header string table index.  */
1242   size_t shstrndx;
1243   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1244     error (EXIT_FAILURE, 0,
1245            gettext ("cannot get section header string table index"));
1246
1247   puts (gettext ("\n Section to Segment mapping:\n  Segment Sections..."));
1248
1249   for (size_t cnt = 0; cnt < phnum; ++cnt)
1250     {
1251       /* Print the segment number.  */
1252       printf ("   %2.2zu     ", cnt);
1253
1254       GElf_Phdr phdr_mem;
1255       GElf_Phdr *phdr = gelf_getphdr (ebl->elf, cnt, &phdr_mem);
1256       /* This must not happen.  */
1257       if (unlikely (phdr == NULL))
1258         error (EXIT_FAILURE, 0, gettext ("cannot get program header: %s"),
1259                elf_errmsg (-1));
1260
1261       /* Iterate over the sections.  */
1262       bool in_relro = false;
1263       bool in_ro = false;
1264       for (size_t inner = 1; inner < shnum; ++inner)
1265         {
1266           Elf_Scn *scn = elf_getscn (ebl->elf, inner);
1267           /* This should not happen.  */
1268           if (unlikely (scn == NULL))
1269             error (EXIT_FAILURE, 0, gettext ("cannot get section: %s"),
1270                    elf_errmsg (-1));
1271
1272           /* Get the section header.  */
1273           GElf_Shdr shdr_mem;
1274           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1275           if (unlikely (shdr == NULL))
1276             error (EXIT_FAILURE, 0,
1277                    gettext ("cannot get section header: %s"),
1278                    elf_errmsg (-1));
1279
1280           if (shdr->sh_size > 0
1281               /* Compare allocated sections by VMA, unallocated
1282                  sections by file offset.  */
1283               && (shdr->sh_flags & SHF_ALLOC
1284                   ? (shdr->sh_addr >= phdr->p_vaddr
1285                      && (shdr->sh_addr + shdr->sh_size
1286                          <= phdr->p_vaddr + phdr->p_memsz))
1287                   : (shdr->sh_offset >= phdr->p_offset
1288                      && (shdr->sh_offset + shdr->sh_size
1289                          <= phdr->p_offset + phdr->p_filesz))))
1290             {
1291               if (has_relro && !in_relro
1292                   && shdr->sh_addr >= relro_from
1293                   && shdr->sh_addr + shdr->sh_size <= relro_to)
1294                 {
1295                   fputs_unlocked (" [RELRO:", stdout);
1296                   in_relro = true;
1297                 }
1298               else if (has_relro && in_relro && shdr->sh_addr >= relro_to)
1299                 {
1300                   fputs_unlocked ("]", stdout);
1301                   in_relro =  false;
1302                 }
1303               else if (has_relro && in_relro
1304                        && shdr->sh_addr + shdr->sh_size > relro_to)
1305                 fputs_unlocked ("] <RELRO:", stdout);
1306               else if (phdr->p_type == PT_LOAD && (phdr->p_flags & PF_W) == 0)
1307                 {
1308                   if (!in_ro)
1309                     {
1310                       fputs_unlocked (" [RO:", stdout);
1311                       in_ro = true;
1312                     }
1313                 }
1314               else
1315                 {
1316                   /* Determine the segment this section is part of.  */
1317                   size_t cnt2;
1318                   GElf_Phdr *phdr2 = NULL;
1319                   for (cnt2 = 0; cnt2 < phnum; ++cnt2)
1320                     {
1321                       GElf_Phdr phdr2_mem;
1322                       phdr2 = gelf_getphdr (ebl->elf, cnt2, &phdr2_mem);
1323
1324                       if (phdr2 != NULL && phdr2->p_type == PT_LOAD
1325                           && shdr->sh_addr >= phdr2->p_vaddr
1326                           && (shdr->sh_addr + shdr->sh_size
1327                               <= phdr2->p_vaddr + phdr2->p_memsz))
1328                         break;
1329                     }
1330
1331                   if (cnt2 < phnum)
1332                     {
1333                       if ((phdr2->p_flags & PF_W) == 0 && !in_ro)
1334                         {
1335                           fputs_unlocked (" [RO:", stdout);
1336                           in_ro = true;
1337                         }
1338                       else if ((phdr2->p_flags & PF_W) != 0 && in_ro)
1339                         {
1340                           fputs_unlocked ("]", stdout);
1341                           in_ro = false;
1342                         }
1343                     }
1344                 }
1345
1346               printf (" %s",
1347                       elf_strptr (ebl->elf, shstrndx, shdr->sh_name));
1348
1349               /* Signal that this sectin is only partially covered.  */
1350               if (has_relro && in_relro
1351                        && shdr->sh_addr + shdr->sh_size > relro_to)
1352                 {
1353                   fputs_unlocked (">", stdout);
1354                   in_relro =  false;
1355                 }
1356             }
1357         }
1358       if (in_relro || in_ro)
1359         fputs_unlocked ("]", stdout);
1360
1361       /* Finish the line.  */
1362       fputc_unlocked ('\n', stdout);
1363     }
1364 }
1365
1366
1367 static const char *
1368 section_name (Ebl *ebl, GElf_Ehdr *ehdr, GElf_Shdr *shdr)
1369 {
1370   return elf_strptr (ebl->elf, ehdr->e_shstrndx, shdr->sh_name) ?: "???";
1371 }
1372
1373
1374 static void
1375 handle_scngrp (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
1376 {
1377   /* Get the data of the section.  */
1378   Elf_Data *data = elf_getdata (scn, NULL);
1379
1380   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
1381   GElf_Shdr symshdr_mem;
1382   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
1383   Elf_Data *symdata = elf_getdata (symscn, NULL);
1384
1385   if (data == NULL || data->d_size < sizeof (Elf32_Word) || symshdr == NULL
1386       || symdata == NULL)
1387     return;
1388
1389   /* Get the section header string table index.  */
1390   size_t shstrndx;
1391   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1392     error (EXIT_FAILURE, 0,
1393            gettext ("cannot get section header string table index"));
1394
1395   Elf32_Word *grpref = (Elf32_Word *) data->d_buf;
1396
1397   GElf_Sym sym_mem;
1398   GElf_Sym *sym = gelf_getsym (symdata, shdr->sh_info, &sym_mem);
1399
1400   printf ((grpref[0] & GRP_COMDAT)
1401           ? ngettext ("\
1402 \nCOMDAT section group [%2zu] '%s' with signature '%s' contains %zu entry:\n",
1403                       "\
1404 \nCOMDAT section group [%2zu] '%s' with signature '%s' contains %zu entries:\n",
1405                       data->d_size / sizeof (Elf32_Word) - 1)
1406           : ngettext ("\
1407 \nSection group [%2zu] '%s' with signature '%s' contains %zu entry:\n", "\
1408 \nSection group [%2zu] '%s' with signature '%s' contains %zu entries:\n",
1409                       data->d_size / sizeof (Elf32_Word) - 1),
1410           elf_ndxscn (scn),
1411           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
1412           (sym == NULL ? NULL
1413            : elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name))
1414           ?: gettext ("<INVALID SYMBOL>"),
1415           data->d_size / sizeof (Elf32_Word) - 1);
1416
1417   for (size_t cnt = 1; cnt < data->d_size / sizeof (Elf32_Word); ++cnt)
1418     {
1419       GElf_Shdr grpshdr_mem;
1420       GElf_Shdr *grpshdr = gelf_getshdr (elf_getscn (ebl->elf, grpref[cnt]),
1421                                          &grpshdr_mem);
1422
1423       const char *str;
1424       printf ("  [%2u] %s\n",
1425               grpref[cnt],
1426               grpshdr != NULL
1427               && (str = elf_strptr (ebl->elf, shstrndx, grpshdr->sh_name))
1428               ? str : gettext ("<INVALID SECTION>"));
1429     }
1430 }
1431
1432
1433 static void
1434 print_scngrp (Ebl *ebl)
1435 {
1436   /* Find all relocation sections and handle them.  */
1437   Elf_Scn *scn = NULL;
1438
1439   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
1440     {
1441        /* Handle the section if it is a symbol table.  */
1442       GElf_Shdr shdr_mem;
1443       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1444
1445       if (shdr != NULL && shdr->sh_type == SHT_GROUP)
1446         handle_scngrp (ebl, scn, shdr);
1447     }
1448 }
1449
1450
1451 static const struct flags
1452 {
1453   int mask;
1454   const char *str;
1455 } dt_flags[] =
1456   {
1457     { DF_ORIGIN, "ORIGIN" },
1458     { DF_SYMBOLIC, "SYMBOLIC" },
1459     { DF_TEXTREL, "TEXTREL" },
1460     { DF_BIND_NOW, "BIND_NOW" },
1461     { DF_STATIC_TLS, "STATIC_TLS" }
1462   };
1463 static const int ndt_flags = sizeof (dt_flags) / sizeof (dt_flags[0]);
1464
1465 static const struct flags dt_flags_1[] =
1466   {
1467     { DF_1_NOW, "NOW" },
1468     { DF_1_GLOBAL, "GLOBAL" },
1469     { DF_1_GROUP, "GROUP" },
1470     { DF_1_NODELETE, "NODELETE" },
1471     { DF_1_LOADFLTR, "LOADFLTR" },
1472     { DF_1_INITFIRST, "INITFIRST" },
1473     { DF_1_NOOPEN, "NOOPEN" },
1474     { DF_1_ORIGIN, "ORIGIN" },
1475     { DF_1_DIRECT, "DIRECT" },
1476     { DF_1_TRANS, "TRANS" },
1477     { DF_1_INTERPOSE, "INTERPOSE" },
1478     { DF_1_NODEFLIB, "NODEFLIB" },
1479     { DF_1_NODUMP, "NODUMP" },
1480     { DF_1_CONFALT, "CONFALT" },
1481     { DF_1_ENDFILTEE, "ENDFILTEE" },
1482     { DF_1_DISPRELDNE, "DISPRELDNE" },
1483     { DF_1_DISPRELPND, "DISPRELPND" },
1484   };
1485 static const int ndt_flags_1 = sizeof (dt_flags_1) / sizeof (dt_flags_1[0]);
1486
1487 static const struct flags dt_feature_1[] =
1488   {
1489     { DTF_1_PARINIT, "PARINIT" },
1490     { DTF_1_CONFEXP, "CONFEXP" }
1491   };
1492 static const int ndt_feature_1 = (sizeof (dt_feature_1)
1493                                   / sizeof (dt_feature_1[0]));
1494
1495 static const struct flags dt_posflag_1[] =
1496   {
1497     { DF_P1_LAZYLOAD, "LAZYLOAD" },
1498     { DF_P1_GROUPPERM, "GROUPPERM" }
1499   };
1500 static const int ndt_posflag_1 = (sizeof (dt_posflag_1)
1501                                   / sizeof (dt_posflag_1[0]));
1502
1503
1504 static void
1505 print_flags (int class, GElf_Xword d_val, const struct flags *flags,
1506                 int nflags)
1507 {
1508   bool first = true;
1509   int cnt;
1510
1511   for (cnt = 0; cnt < nflags; ++cnt)
1512     if (d_val & flags[cnt].mask)
1513       {
1514         if (!first)
1515           putchar_unlocked (' ');
1516         fputs_unlocked (flags[cnt].str, stdout);
1517         d_val &= ~flags[cnt].mask;
1518         first = false;
1519       }
1520
1521   if (d_val != 0)
1522     {
1523       if (!first)
1524         putchar_unlocked (' ');
1525       printf ("%#0*" PRIx64, class == ELFCLASS32 ? 10 : 18, d_val);
1526     }
1527
1528   putchar_unlocked ('\n');
1529 }
1530
1531
1532 static void
1533 print_dt_flags (int class, GElf_Xword d_val)
1534 {
1535   print_flags (class, d_val, dt_flags, ndt_flags);
1536 }
1537
1538
1539 static void
1540 print_dt_flags_1 (int class, GElf_Xword d_val)
1541 {
1542   print_flags (class, d_val, dt_flags_1, ndt_flags_1);
1543 }
1544
1545
1546 static void
1547 print_dt_feature_1 (int class, GElf_Xword d_val)
1548 {
1549   print_flags (class, d_val, dt_feature_1, ndt_feature_1);
1550 }
1551
1552
1553 static void
1554 print_dt_posflag_1 (int class, GElf_Xword d_val)
1555 {
1556   print_flags (class, d_val, dt_posflag_1, ndt_posflag_1);
1557 }
1558
1559
1560 static void
1561 handle_dynamic (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
1562 {
1563   int class = gelf_getclass (ebl->elf);
1564   GElf_Shdr glink_mem;
1565   GElf_Shdr *glink;
1566   Elf_Data *data;
1567   size_t cnt;
1568   size_t shstrndx;
1569   size_t sh_entsize;
1570
1571   /* Get the data of the section.  */
1572   data = elf_getdata (scn, NULL);
1573   if (data == NULL)
1574     return;
1575
1576   /* Get the section header string table index.  */
1577   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1578     error (EXIT_FAILURE, 0,
1579            gettext ("cannot get section header string table index"));
1580
1581   sh_entsize = gelf_fsize (ebl->elf, ELF_T_DYN, 1, EV_CURRENT);
1582
1583   glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link), &glink_mem);
1584   if (glink == NULL)
1585     error (EXIT_FAILURE, 0, gettext ("invalid sh_link value in section %Zu"),
1586            elf_ndxscn (scn));
1587
1588   printf (ngettext ("\
1589 \nDynamic segment contains %lu entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
1590                     "\
1591 \nDynamic segment contains %lu entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
1592                     shdr->sh_size / sh_entsize),
1593           (unsigned long int) (shdr->sh_size / sh_entsize),
1594           class == ELFCLASS32 ? 10 : 18, shdr->sh_addr,
1595           shdr->sh_offset,
1596           (int) shdr->sh_link,
1597           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
1598   fputs_unlocked (gettext ("  Type              Value\n"), stdout);
1599
1600   for (cnt = 0; cnt < shdr->sh_size / sh_entsize; ++cnt)
1601     {
1602       GElf_Dyn dynmem;
1603       GElf_Dyn *dyn = gelf_getdyn (data, cnt, &dynmem);
1604       if (dyn == NULL)
1605         break;
1606
1607       char buf[64];
1608       printf ("  %-17s ",
1609               ebl_dynamic_tag_name (ebl, dyn->d_tag, buf, sizeof (buf)));
1610
1611       switch (dyn->d_tag)
1612         {
1613         case DT_NULL:
1614         case DT_DEBUG:
1615         case DT_BIND_NOW:
1616         case DT_TEXTREL:
1617           /* No further output.  */
1618           fputc_unlocked ('\n', stdout);
1619           break;
1620
1621         case DT_NEEDED:
1622           printf (gettext ("Shared library: [%s]\n"),
1623                   elf_strptr (ebl->elf, shdr->sh_link, dyn->d_un.d_val));
1624           break;
1625
1626         case DT_SONAME:
1627           printf (gettext ("Library soname: [%s]\n"),
1628                   elf_strptr (ebl->elf, shdr->sh_link, dyn->d_un.d_val));
1629           break;
1630
1631         case DT_RPATH:
1632           printf (gettext ("Library rpath: [%s]\n"),
1633                   elf_strptr (ebl->elf, shdr->sh_link, dyn->d_un.d_val));
1634           break;
1635
1636         case DT_RUNPATH:
1637           printf (gettext ("Library runpath: [%s]\n"),
1638                   elf_strptr (ebl->elf, shdr->sh_link, dyn->d_un.d_val));
1639           break;
1640
1641         case DT_PLTRELSZ:
1642         case DT_RELASZ:
1643         case DT_STRSZ:
1644         case DT_RELSZ:
1645         case DT_RELAENT:
1646         case DT_SYMENT:
1647         case DT_RELENT:
1648         case DT_PLTPADSZ:
1649         case DT_MOVEENT:
1650         case DT_MOVESZ:
1651         case DT_INIT_ARRAYSZ:
1652         case DT_FINI_ARRAYSZ:
1653         case DT_SYMINSZ:
1654         case DT_SYMINENT:
1655         case DT_GNU_CONFLICTSZ:
1656         case DT_GNU_LIBLISTSZ:
1657           printf (gettext ("%" PRId64 " (bytes)\n"), dyn->d_un.d_val);
1658           break;
1659
1660         case DT_VERDEFNUM:
1661         case DT_VERNEEDNUM:
1662         case DT_RELACOUNT:
1663         case DT_RELCOUNT:
1664           printf ("%" PRId64 "\n", dyn->d_un.d_val);
1665           break;
1666
1667         case DT_PLTREL:;
1668           const char *tagname = ebl_dynamic_tag_name (ebl, dyn->d_un.d_val,
1669                                                       NULL, 0);
1670           puts (tagname ?: "???");
1671           break;
1672
1673         case DT_FLAGS:
1674           print_dt_flags (class, dyn->d_un.d_val);
1675           break;
1676
1677         case DT_FLAGS_1:
1678           print_dt_flags_1 (class, dyn->d_un.d_val);
1679           break;
1680
1681         case DT_FEATURE_1:
1682           print_dt_feature_1 (class, dyn->d_un.d_val);
1683           break;
1684
1685         case DT_POSFLAG_1:
1686           print_dt_posflag_1 (class, dyn->d_un.d_val);
1687           break;
1688
1689         default:
1690           printf ("%#0*" PRIx64 "\n",
1691                   class == ELFCLASS32 ? 10 : 18, dyn->d_un.d_val);
1692           break;
1693         }
1694     }
1695 }
1696
1697
1698 /* Print the dynamic segment.  */
1699 static void
1700 print_dynamic (Ebl *ebl)
1701 {
1702   for (size_t i = 0; i < phnum; ++i)
1703     {
1704       GElf_Phdr phdr_mem;
1705       GElf_Phdr *phdr = gelf_getphdr (ebl->elf, i, &phdr_mem);
1706
1707       if (phdr != NULL && phdr->p_type == PT_DYNAMIC)
1708         {
1709           Elf_Scn *scn = gelf_offscn (ebl->elf, phdr->p_offset);
1710           GElf_Shdr shdr_mem;
1711           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1712           if (shdr != NULL && shdr->sh_type == SHT_DYNAMIC)
1713             handle_dynamic (ebl, scn, shdr);
1714           break;
1715         }
1716     }
1717 }
1718
1719
1720 /* Print relocations.  */
1721 static void
1722 print_relocs (Ebl *ebl, GElf_Ehdr *ehdr)
1723 {
1724   /* Find all relocation sections and handle them.  */
1725   Elf_Scn *scn = NULL;
1726
1727   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
1728     {
1729        /* Handle the section if it is a symbol table.  */
1730       GElf_Shdr shdr_mem;
1731       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1732
1733       if (likely (shdr != NULL))
1734         {
1735           if (shdr->sh_type == SHT_REL)
1736             handle_relocs_rel (ebl, ehdr, scn, shdr);
1737           else if (shdr->sh_type == SHT_RELA)
1738             handle_relocs_rela (ebl, ehdr, scn, shdr);
1739         }
1740     }
1741 }
1742
1743
1744 /* Handle a relocation section.  */
1745 static void
1746 handle_relocs_rel (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn, GElf_Shdr *shdr)
1747 {
1748   int class = gelf_getclass (ebl->elf);
1749   size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_REL, 1, EV_CURRENT);
1750   int nentries = shdr->sh_size / sh_entsize;
1751
1752   /* Get the data of the section.  */
1753   Elf_Data *data = elf_getdata (scn, NULL);
1754   if (data == NULL)
1755     return;
1756
1757   /* Get the symbol table information.  */
1758   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
1759   GElf_Shdr symshdr_mem;
1760   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
1761   Elf_Data *symdata = elf_getdata (symscn, NULL);
1762
1763   /* Get the section header of the section the relocations are for.  */
1764   GElf_Shdr destshdr_mem;
1765   GElf_Shdr *destshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_info),
1766                                       &destshdr_mem);
1767
1768   if (unlikely (symshdr == NULL || symdata == NULL || destshdr == NULL))
1769     {
1770       printf (gettext ("\nInvalid symbol table at offset %#0" PRIx64 "\n"),
1771               shdr->sh_offset);
1772       return;
1773     }
1774
1775   /* Search for the optional extended section index table.  */
1776   Elf_Data *xndxdata = NULL;
1777   int xndxscnidx = elf_scnshndx (scn);
1778   if (unlikely (xndxscnidx > 0))
1779     xndxdata = elf_getdata (elf_getscn (ebl->elf, xndxscnidx), NULL);
1780
1781   /* Get the section header string table index.  */
1782   size_t shstrndx;
1783   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1784     error (EXIT_FAILURE, 0,
1785            gettext ("cannot get section header string table index"));
1786
1787   if (shdr->sh_info != 0)
1788     printf (ngettext ("\
1789 \nRelocation section [%2zu] '%s' for section [%2u] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
1790                     "\
1791 \nRelocation section [%2zu] '%s' for section [%2u] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
1792                       nentries),
1793             elf_ndxscn (scn),
1794             elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
1795             (unsigned int) shdr->sh_info,
1796             elf_strptr (ebl->elf, shstrndx, destshdr->sh_name),
1797             shdr->sh_offset,
1798             nentries);
1799   else
1800     /* The .rel.dyn section does not refer to a specific section but
1801        instead of section index zero.  Do not try to print a section
1802        name.  */
1803     printf (ngettext ("\
1804 \nRelocation section [%2u] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
1805                     "\
1806 \nRelocation section [%2u] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
1807                       nentries),
1808             (unsigned int) elf_ndxscn (scn),
1809             elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
1810             shdr->sh_offset,
1811             nentries);
1812   fputs_unlocked (class == ELFCLASS32
1813                   ? gettext ("\
1814   Offset      Type                 Value       Name\n")
1815                   : gettext ("\
1816   Offset              Type                 Value               Name\n"),
1817          stdout);
1818
1819   int is_statically_linked = 0;
1820   for (int cnt = 0; cnt < nentries; ++cnt)
1821     {
1822       GElf_Rel relmem;
1823       GElf_Rel *rel = gelf_getrel (data, cnt, &relmem);
1824       if (likely (rel != NULL))
1825         {
1826           char buf[128];
1827           GElf_Sym symmem;
1828           Elf32_Word xndx;
1829           GElf_Sym *sym = gelf_getsymshndx (symdata, xndxdata,
1830                                             GELF_R_SYM (rel->r_info),
1831                                             &symmem, &xndx);
1832           if (unlikely (sym == NULL))
1833             {
1834               /* As a special case we have to handle relocations in static
1835                  executables.  This only happens for IRELATIVE relocations
1836                  (so far).  There is no symbol table.  */
1837               if (is_statically_linked == 0)
1838                 {
1839                   /* Find the program header and look for a PT_INTERP entry. */
1840                   is_statically_linked = -1;
1841                   if (ehdr->e_type == ET_EXEC)
1842                     {
1843                       is_statically_linked = 1;
1844
1845                       for (size_t inner = 0; inner < phnum; ++inner)
1846                         {
1847                           GElf_Phdr phdr_mem;
1848                           GElf_Phdr *phdr = gelf_getphdr (ebl->elf, inner,
1849                                                           &phdr_mem);
1850                           if (phdr != NULL && phdr->p_type == PT_INTERP)
1851                             {
1852                               is_statically_linked = -1;
1853                               break;
1854                             }
1855                         }
1856                     }
1857                 }
1858
1859               if (is_statically_linked > 0 && shdr->sh_link == 0)
1860                 printf ("\
1861   %#0*" PRIx64 "  %-20s %*s  %s\n",
1862                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
1863                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
1864                         /* Avoid the leading R_ which isn't carrying any
1865                            information.  */
1866                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
1867                                                buf, sizeof (buf)) + 2
1868                         : gettext ("<INVALID RELOC>"),
1869                         class == ELFCLASS32 ? 10 : 18, "",
1870                         elf_strptr (ebl->elf, shstrndx, destshdr->sh_name));
1871               else
1872                 printf ("  %#0*" PRIx64 "  %-20s <%s %ld>\n",
1873                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
1874                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
1875                         /* Avoid the leading R_ which isn't carrying any
1876                            information.  */
1877                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
1878                                                buf, sizeof (buf)) + 2
1879                         : gettext ("<INVALID RELOC>"),
1880                         gettext ("INVALID SYMBOL"),
1881                         (long int) GELF_R_SYM (rel->r_info));
1882             }
1883           else if (GELF_ST_TYPE (sym->st_info) != STT_SECTION)
1884             printf ("  %#0*" PRIx64 "  %-20s %#0*" PRIx64 "  %s\n",
1885                     class == ELFCLASS32 ? 10 : 18, rel->r_offset,
1886                     likely (ebl_reloc_type_check (ebl,
1887                                                   GELF_R_TYPE (rel->r_info)))
1888                     /* Avoid the leading R_ which isn't carrying any
1889                        information.  */
1890                     ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
1891                                            buf, sizeof (buf)) + 2
1892                     : gettext ("<INVALID RELOC>"),
1893                     class == ELFCLASS32 ? 10 : 18, sym->st_value,
1894                     elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name));
1895           else
1896             {
1897               /* This is a relocation against a STT_SECTION symbol.  */
1898               GElf_Shdr secshdr_mem;
1899               GElf_Shdr *secshdr;
1900               secshdr = gelf_getshdr (elf_getscn (ebl->elf,
1901                                                   sym->st_shndx == SHN_XINDEX
1902                                                   ? xndx : sym->st_shndx),
1903                                       &secshdr_mem);
1904
1905               if (unlikely (secshdr == NULL))
1906                 printf ("  %#0*" PRIx64 "  %-20s <%s %ld>\n",
1907                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
1908                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
1909                         /* Avoid the leading R_ which isn't carrying any
1910                            information.  */
1911                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
1912                                                buf, sizeof (buf)) + 2
1913                         : gettext ("<INVALID RELOC>"),
1914                         gettext ("INVALID SECTION"),
1915                         (long int) (sym->st_shndx == SHN_XINDEX
1916                                     ? xndx : sym->st_shndx));
1917               else
1918                 printf ("  %#0*" PRIx64 "  %-20s %#0*" PRIx64 "  %s\n",
1919                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
1920                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
1921                         /* Avoid the leading R_ which isn't carrying any
1922                            information.  */
1923                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
1924                                                buf, sizeof (buf)) + 2
1925                         : gettext ("<INVALID RELOC>"),
1926                         class == ELFCLASS32 ? 10 : 18, sym->st_value,
1927                         elf_strptr (ebl->elf, shstrndx, secshdr->sh_name));
1928             }
1929         }
1930     }
1931 }
1932
1933
1934 /* Handle a relocation section.  */
1935 static void
1936 handle_relocs_rela (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn, GElf_Shdr *shdr)
1937 {
1938   int class = gelf_getclass (ebl->elf);
1939   size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_RELA, 1, EV_CURRENT);
1940   int nentries = shdr->sh_size / sh_entsize;
1941
1942   /* Get the data of the section.  */
1943   Elf_Data *data = elf_getdata (scn, NULL);
1944   if (data == NULL)
1945     return;
1946
1947   /* Get the symbol table information.  */
1948   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
1949   GElf_Shdr symshdr_mem;
1950   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
1951   Elf_Data *symdata = elf_getdata (symscn, NULL);
1952
1953   /* Get the section header of the section the relocations are for.  */
1954   GElf_Shdr destshdr_mem;
1955   GElf_Shdr *destshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_info),
1956                                       &destshdr_mem);
1957
1958   if (unlikely (symshdr == NULL || symdata == NULL || destshdr == NULL))
1959     {
1960       printf (gettext ("\nInvalid symbol table at offset %#0" PRIx64 "\n"),
1961               shdr->sh_offset);
1962       return;
1963     }
1964
1965   /* Search for the optional extended section index table.  */
1966   Elf_Data *xndxdata = NULL;
1967   int xndxscnidx = elf_scnshndx (scn);
1968   if (unlikely (xndxscnidx > 0))
1969     xndxdata = elf_getdata (elf_getscn (ebl->elf, xndxscnidx), NULL);
1970
1971   /* Get the section header string table index.  */
1972   size_t shstrndx;
1973   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1974     error (EXIT_FAILURE, 0,
1975            gettext ("cannot get section header string table index"));
1976
1977   if (shdr->sh_info != 0)
1978     printf (ngettext ("\
1979 \nRelocation section [%2zu] '%s' for section [%2u] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
1980                     "\
1981 \nRelocation section [%2zu] '%s' for section [%2u] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
1982                     nentries),
1983           elf_ndxscn (scn),
1984           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
1985           (unsigned int) shdr->sh_info,
1986           elf_strptr (ebl->elf, shstrndx, destshdr->sh_name),
1987           shdr->sh_offset,
1988           nentries);
1989   else
1990     /* The .rela.dyn section does not refer to a specific section but
1991        instead of section index zero.  Do not try to print a section
1992        name.  */
1993     printf (ngettext ("\
1994 \nRelocation section [%2u] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
1995                     "\
1996 \nRelocation section [%2u] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
1997                       nentries),
1998             (unsigned int) elf_ndxscn (scn),
1999             elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2000             shdr->sh_offset,
2001             nentries);
2002   fputs_unlocked (class == ELFCLASS32
2003                   ? gettext ("\
2004   Offset      Type            Value       Addend Name\n")
2005                   : gettext ("\
2006   Offset              Type            Value               Addend Name\n"),
2007                   stdout);
2008
2009   int is_statically_linked = 0;
2010   for (int cnt = 0; cnt < nentries; ++cnt)
2011     {
2012       GElf_Rela relmem;
2013       GElf_Rela *rel = gelf_getrela (data, cnt, &relmem);
2014       if (likely (rel != NULL))
2015         {
2016           char buf[64];
2017           GElf_Sym symmem;
2018           Elf32_Word xndx;
2019           GElf_Sym *sym = gelf_getsymshndx (symdata, xndxdata,
2020                                             GELF_R_SYM (rel->r_info),
2021                                             &symmem, &xndx);
2022
2023           if (unlikely (sym == NULL))
2024             {
2025               /* As a special case we have to handle relocations in static
2026                  executables.  This only happens for IRELATIVE relocations
2027                  (so far).  There is no symbol table.  */
2028               if (is_statically_linked == 0)
2029                 {
2030                   /* Find the program header and look for a PT_INTERP entry. */
2031                   is_statically_linked = -1;
2032                   if (ehdr->e_type == ET_EXEC)
2033                     {
2034                       is_statically_linked = 1;
2035
2036                       for (size_t inner = 0; inner < phnum; ++inner)
2037                         {
2038                           GElf_Phdr phdr_mem;
2039                           GElf_Phdr *phdr = gelf_getphdr (ebl->elf, inner,
2040                                                           &phdr_mem);
2041                           if (phdr != NULL && phdr->p_type == PT_INTERP)
2042                             {
2043                               is_statically_linked = -1;
2044                               break;
2045                             }
2046                         }
2047                     }
2048                 }
2049
2050               if (is_statically_linked > 0 && shdr->sh_link == 0)
2051                 printf ("\
2052   %#0*" PRIx64 "  %-15s %*s  %#6" PRIx64 " %s\n",
2053                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2054                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2055                         /* Avoid the leading R_ which isn't carrying any
2056                            information.  */
2057                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2058                                                buf, sizeof (buf)) + 2
2059                         : gettext ("<INVALID RELOC>"),
2060                         class == ELFCLASS32 ? 10 : 18, "",
2061                         rel->r_addend,
2062                         elf_strptr (ebl->elf, shstrndx, destshdr->sh_name));
2063               else
2064                 printf ("  %#0*" PRIx64 "  %-15s <%s %ld>\n",
2065                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2066                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2067                         /* Avoid the leading R_ which isn't carrying any
2068                            information.  */
2069                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2070                                                buf, sizeof (buf)) + 2
2071                         : gettext ("<INVALID RELOC>"),
2072                         gettext ("INVALID SYMBOL"),
2073                         (long int) GELF_R_SYM (rel->r_info));
2074             }
2075           else if (GELF_ST_TYPE (sym->st_info) != STT_SECTION)
2076             printf ("\
2077   %#0*" PRIx64 "  %-15s %#0*" PRIx64 "  %+6" PRId64 " %s\n",
2078                     class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2079                     likely (ebl_reloc_type_check (ebl,
2080                                                   GELF_R_TYPE (rel->r_info)))
2081                     /* Avoid the leading R_ which isn't carrying any
2082                        information.  */
2083                     ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2084                                            buf, sizeof (buf)) + 2
2085                     : gettext ("<INVALID RELOC>"),
2086                     class == ELFCLASS32 ? 10 : 18, sym->st_value,
2087                     rel->r_addend,
2088                     elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name));
2089           else
2090             {
2091               /* This is a relocation against a STT_SECTION symbol.  */
2092               GElf_Shdr secshdr_mem;
2093               GElf_Shdr *secshdr;
2094               secshdr = gelf_getshdr (elf_getscn (ebl->elf,
2095                                                   sym->st_shndx == SHN_XINDEX
2096                                                   ? xndx : sym->st_shndx),
2097                                       &secshdr_mem);
2098
2099               if (unlikely (secshdr == NULL))
2100                 printf ("  %#0*" PRIx64 "  %-15s <%s %ld>\n",
2101                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2102                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2103                         /* Avoid the leading R_ which isn't carrying any
2104                            information.  */
2105                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2106                                                buf, sizeof (buf)) + 2
2107                         : gettext ("<INVALID RELOC>"),
2108                         gettext ("INVALID SECTION"),
2109                         (long int) (sym->st_shndx == SHN_XINDEX
2110                                     ? xndx : sym->st_shndx));
2111               else
2112                 printf ("\
2113   %#0*" PRIx64 "  %-15s %#0*" PRIx64 "  %+6" PRId64 " %s\n",
2114                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2115                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2116                         /* Avoid the leading R_ which isn't carrying any
2117                            information.  */
2118                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2119                                                buf, sizeof (buf)) + 2
2120                         : gettext ("<INVALID RELOC>"),
2121                         class == ELFCLASS32 ? 10 : 18, sym->st_value,
2122                         rel->r_addend,
2123                         elf_strptr (ebl->elf, shstrndx, secshdr->sh_name));
2124             }
2125         }
2126     }
2127 }
2128
2129
2130 /* Print the program header.  */
2131 static void
2132 print_symtab (Ebl *ebl, int type)
2133 {
2134   /* Find the symbol table(s).  For this we have to search through the
2135      section table.  */
2136   Elf_Scn *scn = NULL;
2137
2138   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
2139     {
2140       /* Handle the section if it is a symbol table.  */
2141       GElf_Shdr shdr_mem;
2142       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
2143
2144       if (shdr != NULL && shdr->sh_type == (GElf_Word) type)
2145         handle_symtab (ebl, scn, shdr);
2146     }
2147 }
2148
2149
2150 static void
2151 handle_symtab (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
2152 {
2153   Elf_Data *versym_data = NULL;
2154   Elf_Data *verneed_data = NULL;
2155   Elf_Data *verdef_data = NULL;
2156   Elf_Data *xndx_data = NULL;
2157   int class = gelf_getclass (ebl->elf);
2158   Elf32_Word verneed_stridx = 0;
2159   Elf32_Word verdef_stridx = 0;
2160
2161   /* Get the data of the section.  */
2162   Elf_Data *data = elf_getdata (scn, NULL);
2163   if (data == NULL)
2164     return;
2165
2166   /* Find out whether we have other sections we might need.  */
2167   Elf_Scn *runscn = NULL;
2168   while ((runscn = elf_nextscn (ebl->elf, runscn)) != NULL)
2169     {
2170       GElf_Shdr runshdr_mem;
2171       GElf_Shdr *runshdr = gelf_getshdr (runscn, &runshdr_mem);
2172
2173       if (likely (runshdr != NULL))
2174         {
2175           if (runshdr->sh_type == SHT_GNU_versym
2176               && runshdr->sh_link == elf_ndxscn (scn))
2177             /* Bingo, found the version information.  Now get the data.  */
2178             versym_data = elf_getdata (runscn, NULL);
2179           else if (runshdr->sh_type == SHT_GNU_verneed)
2180             {
2181               /* This is the information about the needed versions.  */
2182               verneed_data = elf_getdata (runscn, NULL);
2183               verneed_stridx = runshdr->sh_link;
2184             }
2185           else if (runshdr->sh_type == SHT_GNU_verdef)
2186             {
2187               /* This is the information about the defined versions.  */
2188               verdef_data = elf_getdata (runscn, NULL);
2189               verdef_stridx = runshdr->sh_link;
2190             }
2191           else if (runshdr->sh_type == SHT_SYMTAB_SHNDX
2192               && runshdr->sh_link == elf_ndxscn (scn))
2193             /* Extended section index.  */
2194             xndx_data = elf_getdata (runscn, NULL);
2195         }
2196     }
2197
2198   /* Get the section header string table index.  */
2199   size_t shstrndx;
2200   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2201     error (EXIT_FAILURE, 0,
2202            gettext ("cannot get section header string table index"));
2203
2204   GElf_Shdr glink_mem;
2205   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
2206                                    &glink_mem);
2207   if (glink == NULL)
2208     error (EXIT_FAILURE, 0, gettext ("invalid sh_link value in section %Zu"),
2209            elf_ndxscn (scn));
2210
2211   /* Now we can compute the number of entries in the section.  */
2212   unsigned int nsyms = data->d_size / (class == ELFCLASS32
2213                                        ? sizeof (Elf32_Sym)
2214                                        : sizeof (Elf64_Sym));
2215
2216   printf (ngettext ("\nSymbol table [%2u] '%s' contains %u entry:\n",
2217                     "\nSymbol table [%2u] '%s' contains %u entries:\n",
2218                     nsyms),
2219           (unsigned int) elf_ndxscn (scn),
2220           elf_strptr (ebl->elf, shstrndx, shdr->sh_name), nsyms);
2221   printf (ngettext (" %lu local symbol  String table: [%2u] '%s'\n",
2222                     " %lu local symbols  String table: [%2u] '%s'\n",
2223                     shdr->sh_info),
2224           (unsigned long int) shdr->sh_info,
2225           (unsigned int) shdr->sh_link,
2226           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
2227
2228   fputs_unlocked (class == ELFCLASS32
2229                   ? gettext ("\
2230   Num:    Value   Size Type    Bind   Vis          Ndx Name\n")
2231                   : gettext ("\
2232   Num:            Value   Size Type    Bind   Vis          Ndx Name\n"),
2233                   stdout);
2234
2235   for (unsigned int cnt = 0; cnt < nsyms; ++cnt)
2236     {
2237       char typebuf[64];
2238       char bindbuf[64];
2239       char scnbuf[64];
2240       Elf32_Word xndx;
2241       GElf_Sym sym_mem;
2242       GElf_Sym *sym = gelf_getsymshndx (data, xndx_data, cnt, &sym_mem, &xndx);
2243
2244       if (unlikely (sym == NULL))
2245         continue;
2246
2247       /* Determine the real section index.  */
2248       if (likely (sym->st_shndx != SHN_XINDEX))
2249         xndx = sym->st_shndx;
2250
2251       printf (gettext ("\
2252 %5u: %0*" PRIx64 " %6" PRId64 " %-7s %-6s %-9s %6s %s"),
2253               cnt,
2254               class == ELFCLASS32 ? 8 : 16,
2255               sym->st_value,
2256               sym->st_size,
2257               ebl_symbol_type_name (ebl, GELF_ST_TYPE (sym->st_info),
2258                                     typebuf, sizeof (typebuf)),
2259               ebl_symbol_binding_name (ebl, GELF_ST_BIND (sym->st_info),
2260                                        bindbuf, sizeof (bindbuf)),
2261               get_visibility_type (GELF_ST_VISIBILITY (sym->st_other)),
2262               ebl_section_name (ebl, sym->st_shndx, xndx, scnbuf,
2263                                 sizeof (scnbuf), NULL, shnum),
2264               elf_strptr (ebl->elf, shdr->sh_link, sym->st_name));
2265
2266       if (versym_data != NULL)
2267         {
2268           /* Get the version information.  */
2269           GElf_Versym versym_mem;
2270           GElf_Versym *versym = gelf_getversym (versym_data, cnt, &versym_mem);
2271
2272           if (versym != NULL && ((*versym & 0x8000) != 0 || *versym > 1))
2273             {
2274               bool is_nobits = false;
2275               bool check_def = xndx != SHN_UNDEF;
2276
2277               if (xndx < SHN_LORESERVE || sym->st_shndx == SHN_XINDEX)
2278                 {
2279                   GElf_Shdr symshdr_mem;
2280                   GElf_Shdr *symshdr =
2281                     gelf_getshdr (elf_getscn (ebl->elf, xndx), &symshdr_mem);
2282
2283                   is_nobits = (symshdr != NULL
2284                                && symshdr->sh_type == SHT_NOBITS);
2285                 }
2286
2287               if (is_nobits || ! check_def)
2288                 {
2289                   /* We must test both.  */
2290                   GElf_Vernaux vernaux_mem;
2291                   GElf_Vernaux *vernaux = NULL;
2292                   size_t vn_offset = 0;
2293
2294                   GElf_Verneed verneed_mem;
2295                   GElf_Verneed *verneed = gelf_getverneed (verneed_data, 0,
2296                                                            &verneed_mem);
2297                   while (verneed != NULL)
2298                     {
2299                       size_t vna_offset = vn_offset;
2300
2301                       vernaux = gelf_getvernaux (verneed_data,
2302                                                  vna_offset += verneed->vn_aux,
2303                                                  &vernaux_mem);
2304                       while (vernaux != NULL
2305                              && vernaux->vna_other != *versym
2306                              && vernaux->vna_next != 0)
2307                         {
2308                           /* Update the offset.  */
2309                           vna_offset += vernaux->vna_next;
2310
2311                           vernaux = (vernaux->vna_next == 0
2312                                      ? NULL
2313                                      : gelf_getvernaux (verneed_data,
2314                                                         vna_offset,
2315                                                         &vernaux_mem));
2316                         }
2317
2318                       /* Check whether we found the version.  */
2319                       if (vernaux != NULL && vernaux->vna_other == *versym)
2320                         /* Found it.  */
2321                         break;
2322
2323                       vn_offset += verneed->vn_next;
2324                       verneed = (verneed->vn_next == 0
2325                                  ? NULL
2326                                  : gelf_getverneed (verneed_data, vn_offset,
2327                                                     &verneed_mem));
2328                     }
2329
2330                   if (vernaux != NULL && vernaux->vna_other == *versym)
2331                     {
2332                       printf ("@%s (%u)",
2333                               elf_strptr (ebl->elf, verneed_stridx,
2334                                           vernaux->vna_name),
2335                               (unsigned int) vernaux->vna_other);
2336                       check_def = 0;
2337                     }
2338                   else if (unlikely (! is_nobits))
2339                     error (0, 0, gettext ("bad dynamic symbol"));
2340                   else
2341                     check_def = 1;
2342                 }
2343
2344               if (check_def && *versym != 0x8001)
2345                 {
2346                   /* We must test both.  */
2347                   size_t vd_offset = 0;
2348
2349                   GElf_Verdef verdef_mem;
2350                   GElf_Verdef *verdef = gelf_getverdef (verdef_data, 0,
2351                                                         &verdef_mem);
2352                   while (verdef != NULL)
2353                     {
2354                       if (verdef->vd_ndx == (*versym & 0x7fff))
2355                         /* Found the definition.  */
2356                         break;
2357
2358                       vd_offset += verdef->vd_next;
2359                       verdef = (verdef->vd_next == 0
2360                                 ? NULL
2361                                 : gelf_getverdef (verdef_data, vd_offset,
2362                                                   &verdef_mem));
2363                     }
2364
2365                   if (verdef != NULL)
2366                     {
2367                       GElf_Verdaux verdaux_mem;
2368                       GElf_Verdaux *verdaux
2369                         = gelf_getverdaux (verdef_data,
2370                                            vd_offset + verdef->vd_aux,
2371                                            &verdaux_mem);
2372
2373                       if (verdaux != NULL)
2374                         printf ((*versym & 0x8000) ? "@%s" : "@@%s",
2375                                 elf_strptr (ebl->elf, verdef_stridx,
2376                                             verdaux->vda_name));
2377                     }
2378                 }
2379             }
2380         }
2381
2382       putchar_unlocked ('\n');
2383     }
2384 }
2385
2386
2387 /* Print version information.  */
2388 static void
2389 print_verinfo (Ebl *ebl)
2390 {
2391   /* Find the version information sections.  For this we have to
2392      search through the section table.  */
2393   Elf_Scn *scn = NULL;
2394
2395   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
2396     {
2397       /* Handle the section if it is part of the versioning handling.  */
2398       GElf_Shdr shdr_mem;
2399       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
2400
2401       if (likely (shdr != NULL))
2402         {
2403           if (shdr->sh_type == SHT_GNU_verneed)
2404             handle_verneed (ebl, scn, shdr);
2405           else if (shdr->sh_type == SHT_GNU_verdef)
2406             handle_verdef (ebl, scn, shdr);
2407           else if (shdr->sh_type == SHT_GNU_versym)
2408             handle_versym (ebl, scn, shdr);
2409         }
2410     }
2411 }
2412
2413
2414 static const char *
2415 get_ver_flags (unsigned int flags)
2416 {
2417   static char buf[32];
2418   char *endp;
2419
2420   if (flags == 0)
2421     return gettext ("none");
2422
2423   if (flags & VER_FLG_BASE)
2424     endp = stpcpy (buf, "BASE ");
2425   else
2426     endp = buf;
2427
2428   if (flags & VER_FLG_WEAK)
2429     {
2430       if (endp != buf)
2431         endp = stpcpy (endp, "| ");
2432
2433       endp = stpcpy (endp, "WEAK ");
2434     }
2435
2436   if (unlikely (flags & ~(VER_FLG_BASE | VER_FLG_WEAK)))
2437     {
2438       strncpy (endp, gettext ("| <unknown>"), buf + sizeof (buf) - endp);
2439       buf[sizeof (buf) - 1] = '\0';
2440     }
2441
2442   return buf;
2443 }
2444
2445
2446 static void
2447 handle_verneed (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
2448 {
2449   int class = gelf_getclass (ebl->elf);
2450
2451   /* Get the data of the section.  */
2452   Elf_Data *data = elf_getdata (scn, NULL);
2453   if (data == NULL)
2454     return;
2455
2456   /* Get the section header string table index.  */
2457   size_t shstrndx;
2458   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2459     error (EXIT_FAILURE, 0,
2460            gettext ("cannot get section header string table index"));
2461
2462   GElf_Shdr glink_mem;
2463   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
2464                                    &glink_mem);
2465   if (glink == NULL)
2466     error (EXIT_FAILURE, 0, gettext ("invalid sh_link value in section %Zu"),
2467            elf_ndxscn (scn));
2468
2469   printf (ngettext ("\
2470 \nVersion needs section [%2u] '%s' contains %d entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2471                     "\
2472 \nVersion needs section [%2u] '%s' contains %d entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2473                     shdr->sh_info),
2474           (unsigned int) elf_ndxscn (scn),
2475           elf_strptr (ebl->elf, shstrndx, shdr->sh_name), shdr->sh_info,
2476           class == ELFCLASS32 ? 10 : 18, shdr->sh_addr,
2477           shdr->sh_offset,
2478           (unsigned int) shdr->sh_link,
2479           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
2480
2481   unsigned int offset = 0;
2482   for (int cnt = shdr->sh_info; --cnt >= 0; )
2483     {
2484       /* Get the data at the next offset.  */
2485       GElf_Verneed needmem;
2486       GElf_Verneed *need = gelf_getverneed (data, offset, &needmem);
2487       if (unlikely (need == NULL))
2488         break;
2489
2490       printf (gettext ("  %#06x: Version: %hu  File: %s  Cnt: %hu\n"),
2491               offset, (unsigned short int) need->vn_version,
2492               elf_strptr (ebl->elf, shdr->sh_link, need->vn_file),
2493               (unsigned short int) need->vn_cnt);
2494
2495       unsigned int auxoffset = offset + need->vn_aux;
2496       for (int cnt2 = need->vn_cnt; --cnt2 >= 0; )
2497         {
2498           GElf_Vernaux auxmem;
2499           GElf_Vernaux *aux = gelf_getvernaux (data, auxoffset, &auxmem);
2500           if (unlikely (aux == NULL))
2501             break;
2502
2503           printf (gettext ("  %#06x: Name: %s  Flags: %s  Version: %hu\n"),
2504                   auxoffset,
2505                   elf_strptr (ebl->elf, shdr->sh_link, aux->vna_name),
2506                   get_ver_flags (aux->vna_flags),
2507                   (unsigned short int) aux->vna_other);
2508
2509           if (aux->vna_next == 0)
2510             break;
2511
2512           auxoffset += aux->vna_next;
2513         }
2514
2515       /* Find the next offset.  */
2516       if (need->vn_next == 0)
2517         break;
2518
2519       offset += need->vn_next;
2520     }
2521 }
2522
2523
2524 static void
2525 handle_verdef (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
2526 {
2527   /* Get the data of the section.  */
2528   Elf_Data *data = elf_getdata (scn, NULL);
2529   if (data == NULL)
2530     return;
2531
2532   /* Get the section header string table index.  */
2533   size_t shstrndx;
2534   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2535     error (EXIT_FAILURE, 0,
2536            gettext ("cannot get section header string table index"));
2537
2538   GElf_Shdr glink_mem;
2539   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
2540                                    &glink_mem);
2541   if (glink == NULL)
2542     error (EXIT_FAILURE, 0, gettext ("invalid sh_link value in section %Zu"),
2543            elf_ndxscn (scn));
2544
2545   int class = gelf_getclass (ebl->elf);
2546   printf (ngettext ("\
2547 \nVersion definition section [%2u] '%s' contains %d entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2548                     "\
2549 \nVersion definition section [%2u] '%s' contains %d entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2550                     shdr->sh_info),
2551           (unsigned int) elf_ndxscn (scn),
2552           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2553           shdr->sh_info,
2554           class == ELFCLASS32 ? 10 : 18, shdr->sh_addr,
2555           shdr->sh_offset,
2556           (unsigned int) shdr->sh_link,
2557           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
2558
2559   unsigned int offset = 0;
2560   for (int cnt = shdr->sh_info; --cnt >= 0; )
2561     {
2562       /* Get the data at the next offset.  */
2563       GElf_Verdef defmem;
2564       GElf_Verdef *def = gelf_getverdef (data, offset, &defmem);
2565       if (unlikely (def == NULL))
2566         break;
2567
2568       unsigned int auxoffset = offset + def->vd_aux;
2569       GElf_Verdaux auxmem;
2570       GElf_Verdaux *aux = gelf_getverdaux (data, auxoffset, &auxmem);
2571       if (unlikely (aux == NULL))
2572         break;
2573
2574       printf (gettext ("\
2575   %#06x: Version: %hd  Flags: %s  Index: %hd  Cnt: %hd  Name: %s\n"),
2576               offset, def->vd_version,
2577               get_ver_flags (def->vd_flags),
2578               def->vd_ndx,
2579               def->vd_cnt,
2580               elf_strptr (ebl->elf, shdr->sh_link, aux->vda_name));
2581
2582       auxoffset += aux->vda_next;
2583       for (int cnt2 = 1; cnt2 < def->vd_cnt; ++cnt2)
2584         {
2585           aux = gelf_getverdaux (data, auxoffset, &auxmem);
2586           if (unlikely (aux == NULL))
2587             break;
2588
2589           printf (gettext ("  %#06x: Parent %d: %s\n"),
2590                   auxoffset, cnt2,
2591                   elf_strptr (ebl->elf, shdr->sh_link, aux->vda_name));
2592
2593           if (aux->vda_next == 0)
2594             break;
2595
2596           auxoffset += aux->vda_next;
2597         }
2598
2599       /* Find the next offset.  */
2600       if (def->vd_next == 0)
2601         break;
2602       offset += def->vd_next;
2603     }
2604 }
2605
2606
2607 static void
2608 handle_versym (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
2609 {
2610   int class = gelf_getclass (ebl->elf);
2611   const char **vername;
2612   const char **filename;
2613
2614   /* Get the data of the section.  */
2615   Elf_Data *data = elf_getdata (scn, NULL);
2616   if (data == NULL)
2617     return;
2618
2619   /* Get the section header string table index.  */
2620   size_t shstrndx;
2621   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2622     error (EXIT_FAILURE, 0,
2623            gettext ("cannot get section header string table index"));
2624
2625   /* We have to find the version definition section and extract the
2626      version names.  */
2627   Elf_Scn *defscn = NULL;
2628   Elf_Scn *needscn = NULL;
2629
2630   Elf_Scn *verscn = NULL;
2631   while ((verscn = elf_nextscn (ebl->elf, verscn)) != NULL)
2632     {
2633       GElf_Shdr vershdr_mem;
2634       GElf_Shdr *vershdr = gelf_getshdr (verscn, &vershdr_mem);
2635
2636       if (likely (vershdr != NULL))
2637         {
2638           if (vershdr->sh_type == SHT_GNU_verdef)
2639             defscn = verscn;
2640           else if (vershdr->sh_type == SHT_GNU_verneed)
2641             needscn = verscn;
2642         }
2643     }
2644
2645   size_t nvername;
2646   if (defscn != NULL || needscn != NULL)
2647     {
2648       /* We have a version information (better should have).  Now get
2649          the version names.  First find the maximum version number.  */
2650       nvername = 0;
2651       if (defscn != NULL)
2652         {
2653           /* Run through the version definitions and find the highest
2654              index.  */
2655           unsigned int offset = 0;
2656           Elf_Data *defdata;
2657           GElf_Shdr defshdrmem;
2658           GElf_Shdr *defshdr;
2659
2660           defdata = elf_getdata (defscn, NULL);
2661           if (unlikely (defdata == NULL))
2662             return;
2663
2664           defshdr = gelf_getshdr (defscn, &defshdrmem);
2665           if (unlikely (defshdr == NULL))
2666             return;
2667
2668           for (unsigned int cnt = 0; cnt < defshdr->sh_info; ++cnt)
2669             {
2670               GElf_Verdef defmem;
2671               GElf_Verdef *def;
2672
2673               /* Get the data at the next offset.  */
2674               def = gelf_getverdef (defdata, offset, &defmem);
2675               if (unlikely (def == NULL))
2676                 break;
2677
2678               nvername = MAX (nvername, (size_t) (def->vd_ndx & 0x7fff));
2679
2680               if (def->vd_next == 0)
2681                 break;
2682               offset += def->vd_next;
2683             }
2684         }
2685       if (needscn != NULL)
2686         {
2687           unsigned int offset = 0;
2688           Elf_Data *needdata;
2689           GElf_Shdr needshdrmem;
2690           GElf_Shdr *needshdr;
2691
2692           needdata = elf_getdata (needscn, NULL);
2693           if (unlikely (needdata == NULL))
2694             return;
2695
2696           needshdr = gelf_getshdr (needscn, &needshdrmem);
2697           if (unlikely (needshdr == NULL))
2698             return;
2699
2700           for (unsigned int cnt = 0; cnt < needshdr->sh_info; ++cnt)
2701             {
2702               GElf_Verneed needmem;
2703               GElf_Verneed *need;
2704               unsigned int auxoffset;
2705               int cnt2;
2706
2707               /* Get the data at the next offset.  */
2708               need = gelf_getverneed (needdata, offset, &needmem);
2709               if (unlikely (need == NULL))
2710                 break;
2711
2712               /* Run through the auxiliary entries.  */
2713               auxoffset = offset + need->vn_aux;
2714               for (cnt2 = need->vn_cnt; --cnt2 >= 0; )
2715                 {
2716                   GElf_Vernaux auxmem;
2717                   GElf_Vernaux *aux;
2718
2719                   aux = gelf_getvernaux (needdata, auxoffset, &auxmem);
2720                   if (unlikely (aux == NULL))
2721                     break;
2722
2723                   nvername = MAX (nvername,
2724                                   (size_t) (aux->vna_other & 0x7fff));
2725
2726                   if (aux->vna_next == 0)
2727                     break;
2728                   auxoffset += aux->vna_next;
2729                 }
2730
2731               if (need->vn_next == 0)
2732                 break;
2733               offset += need->vn_next;
2734             }
2735         }
2736
2737       /* This is the number of versions we know about.  */
2738       ++nvername;
2739
2740       /* Allocate the array.  */
2741       vername = (const char **) alloca (nvername * sizeof (const char *));
2742       memset(vername, 0, nvername * sizeof (const char *));
2743       filename = (const char **) alloca (nvername * sizeof (const char *));
2744       memset(filename, 0, nvername * sizeof (const char *));
2745
2746       /* Run through the data structures again and collect the strings.  */
2747       if (defscn != NULL)
2748         {
2749           /* Run through the version definitions and find the highest
2750              index.  */
2751           unsigned int offset = 0;
2752           Elf_Data *defdata;
2753           GElf_Shdr defshdrmem;
2754           GElf_Shdr *defshdr;
2755
2756           defdata = elf_getdata (defscn, NULL);
2757           if (unlikely (defdata == NULL))
2758             return;
2759
2760           defshdr = gelf_getshdr (defscn, &defshdrmem);
2761           if (unlikely (defshdr == NULL))
2762             return;
2763
2764           for (unsigned int cnt = 0; cnt < defshdr->sh_info; ++cnt)
2765             {
2766
2767               /* Get the data at the next offset.  */
2768               GElf_Verdef defmem;
2769               GElf_Verdef *def = gelf_getverdef (defdata, offset, &defmem);
2770               if (unlikely (def == NULL))
2771                 break;
2772
2773               GElf_Verdaux auxmem;
2774               GElf_Verdaux *aux = gelf_getverdaux (defdata,
2775                                                    offset + def->vd_aux,
2776                                                    &auxmem);
2777               if (unlikely (aux == NULL))
2778                 break;
2779
2780               vername[def->vd_ndx & 0x7fff]
2781                 = elf_strptr (ebl->elf, defshdr->sh_link, aux->vda_name);
2782               filename[def->vd_ndx & 0x7fff] = NULL;
2783
2784               if (def->vd_next == 0)
2785                 break;
2786               offset += def->vd_next;
2787             }
2788         }
2789       if (needscn != NULL)
2790         {
2791           unsigned int offset = 0;
2792
2793           Elf_Data *needdata = elf_getdata (needscn, NULL);
2794           GElf_Shdr needshdrmem;
2795           GElf_Shdr *needshdr = gelf_getshdr (needscn, &needshdrmem);
2796           if (unlikely (needdata == NULL || needshdr == NULL))
2797             return;
2798
2799           for (unsigned int cnt = 0; cnt < needshdr->sh_info; ++cnt)
2800             {
2801               /* Get the data at the next offset.  */
2802               GElf_Verneed needmem;
2803               GElf_Verneed *need = gelf_getverneed (needdata, offset,
2804                                                     &needmem);
2805               if (unlikely (need == NULL))
2806                 break;
2807
2808               /* Run through the auxiliary entries.  */
2809               unsigned int auxoffset = offset + need->vn_aux;
2810               for (int cnt2 = need->vn_cnt; --cnt2 >= 0; )
2811                 {
2812                   GElf_Vernaux auxmem;
2813                   GElf_Vernaux *aux = gelf_getvernaux (needdata, auxoffset,
2814                                                        &auxmem);
2815                   if (unlikely (aux == NULL))
2816                     break;
2817
2818                   vername[aux->vna_other & 0x7fff]
2819                     = elf_strptr (ebl->elf, needshdr->sh_link, aux->vna_name);
2820                   filename[aux->vna_other & 0x7fff]
2821                     = elf_strptr (ebl->elf, needshdr->sh_link, need->vn_file);
2822
2823                   if (aux->vna_next == 0)
2824                     break;
2825                   auxoffset += aux->vna_next;
2826                 }
2827
2828               if (need->vn_next == 0)
2829                 break;
2830               offset += need->vn_next;
2831             }
2832         }
2833     }
2834   else
2835     {
2836       vername = NULL;
2837       nvername = 1;
2838       filename = NULL;
2839     }
2840
2841   GElf_Shdr glink_mem;
2842   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
2843                                    &glink_mem);
2844   size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_HALF, 1, EV_CURRENT);
2845   if (glink == NULL)
2846     error (EXIT_FAILURE, 0, gettext ("invalid sh_link value in section %Zu"),
2847            elf_ndxscn (scn));
2848
2849   /* Print the header.  */
2850   printf (ngettext ("\
2851 \nVersion symbols section [%2u] '%s' contains %d entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'",
2852                     "\
2853 \nVersion symbols section [%2u] '%s' contains %d entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'",
2854                     shdr->sh_size / sh_entsize),
2855           (unsigned int) elf_ndxscn (scn),
2856           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2857           (int) (shdr->sh_size / sh_entsize),
2858           class == ELFCLASS32 ? 10 : 18, shdr->sh_addr,
2859           shdr->sh_offset,
2860           (unsigned int) shdr->sh_link,
2861           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
2862
2863   /* Now we can finally look at the actual contents of this section.  */
2864   for (unsigned int cnt = 0; cnt < shdr->sh_size / sh_entsize; ++cnt)
2865     {
2866       if (cnt % 2 == 0)
2867         printf ("\n %4d:", cnt);
2868
2869       GElf_Versym symmem;
2870       GElf_Versym *sym = gelf_getversym (data, cnt, &symmem);
2871       if (sym == NULL)
2872         break;
2873
2874       switch (*sym)
2875         {
2876           ssize_t n;
2877         case 0:
2878           fputs_unlocked (gettext ("   0 *local*                     "),
2879                           stdout);
2880           break;
2881
2882         case 1:
2883           fputs_unlocked (gettext ("   1 *global*                    "),
2884                           stdout);
2885           break;
2886
2887         default:
2888           n = printf ("%4d%c%s",
2889                       *sym & 0x7fff, *sym & 0x8000 ? 'h' : ' ',
2890                       (vername != NULL
2891                        && (unsigned int) (*sym & 0x7fff) < nvername)
2892                       ? vername[*sym & 0x7fff] : "???");
2893           if ((unsigned int) (*sym & 0x7fff) < nvername
2894               && filename != NULL && filename[*sym & 0x7fff] != NULL)
2895             n += printf ("(%s)", filename[*sym & 0x7fff]);
2896           printf ("%*s", MAX (0, 33 - (int) n), " ");
2897           break;
2898         }
2899     }
2900   putchar_unlocked ('\n');
2901 }
2902
2903
2904 static void
2905 print_hash_info (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, size_t shstrndx,
2906                  uint_fast32_t maxlength, Elf32_Word nbucket,
2907                  uint_fast32_t nsyms, uint32_t *lengths, const char *extrastr)
2908 {
2909   uint32_t *counts = (uint32_t *) xcalloc (maxlength + 1, sizeof (uint32_t));
2910
2911   for (Elf32_Word cnt = 0; cnt < nbucket; ++cnt)
2912     ++counts[lengths[cnt]];
2913
2914   GElf_Shdr glink_mem;
2915   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf,
2916                                                shdr->sh_link),
2917                                    &glink_mem);
2918   if (glink == NULL)
2919     {
2920       error (0, 0, gettext ("invalid sh_link value in section %Zu"),
2921              elf_ndxscn (scn));
2922       return;
2923     }
2924
2925   printf (ngettext ("\
2926 \nHistogram for bucket list length in section [%2u] '%s' (total of %d bucket):\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2927                     "\
2928 \nHistogram for bucket list length in section [%2u] '%s' (total of %d buckets):\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2929                     nbucket),
2930           (unsigned int) elf_ndxscn (scn),
2931           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2932           (int) nbucket,
2933           gelf_getclass (ebl->elf) == ELFCLASS32 ? 10 : 18,
2934           shdr->sh_addr,
2935           shdr->sh_offset,
2936           (unsigned int) shdr->sh_link,
2937           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
2938
2939   if (extrastr != NULL)
2940     fputs (extrastr, stdout);
2941
2942   if (likely (nbucket > 0))
2943     {
2944       uint64_t success = 0;
2945
2946       /* xgettext:no-c-format */
2947       fputs_unlocked (gettext ("\
2948  Length  Number  % of total  Coverage\n"), stdout);
2949       printf (gettext ("      0  %6" PRIu32 "      %5.1f%%\n"),
2950               counts[0], (counts[0] * 100.0) / nbucket);
2951
2952       uint64_t nzero_counts = 0;
2953       for (Elf32_Word cnt = 1; cnt <= maxlength; ++cnt)
2954         {
2955           nzero_counts += counts[cnt] * cnt;
2956           printf (gettext ("\
2957 %7d  %6" PRIu32 "      %5.1f%%    %5.1f%%\n"),
2958                   (int) cnt, counts[cnt], (counts[cnt] * 100.0) / nbucket,
2959                   (nzero_counts * 100.0) / nsyms);
2960         }
2961
2962       Elf32_Word acc = 0;
2963       for (Elf32_Word cnt = 1; cnt <= maxlength; ++cnt)
2964         {
2965           acc += cnt;
2966           success += counts[cnt] * acc;
2967         }
2968
2969       printf (gettext ("\
2970  Average number of tests:   successful lookup: %f\n\
2971                           unsuccessful lookup: %f\n"),
2972               (double) success / (double) nzero_counts,
2973               (double) nzero_counts / (double) nbucket);
2974     }
2975
2976   free (counts);
2977 }
2978
2979
2980 /* This function handles the traditional System V-style hash table format.  */
2981 static void
2982 handle_sysv_hash (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, size_t shstrndx)
2983 {
2984   Elf_Data *data = elf_getdata (scn, NULL);
2985   if (unlikely (data == NULL))
2986     {
2987       error (0, 0, gettext ("cannot get data for section %d: %s"),
2988              (int) elf_ndxscn (scn), elf_errmsg (-1));
2989       return;
2990     }
2991
2992   if (unlikely (data->d_size < 2 * sizeof (Elf32_Word)))
2993     {
2994     invalid_data:
2995       error (0, 0, gettext ("invalid data in sysv.hash section %d"),
2996              (int) elf_ndxscn (scn));
2997       return;
2998     }
2999
3000   Elf32_Word nbucket = ((Elf32_Word *) data->d_buf)[0];
3001   Elf32_Word nchain = ((Elf32_Word *) data->d_buf)[1];
3002
3003   uint64_t used_buf = (2ULL + nchain + nbucket) * sizeof (Elf32_Word);
3004   if (used_buf > data->d_size)
3005     goto invalid_data;
3006
3007   Elf32_Word *bucket = &((Elf32_Word *) data->d_buf)[2];
3008   Elf32_Word *chain = &((Elf32_Word *) data->d_buf)[2 + nbucket];
3009
3010   uint32_t *lengths = (uint32_t *) xcalloc (nbucket, sizeof (uint32_t));
3011
3012   uint_fast32_t maxlength = 0;
3013   uint_fast32_t nsyms = 0;
3014   for (Elf32_Word cnt = 0; cnt < nbucket; ++cnt)
3015     {
3016       Elf32_Word inner = bucket[cnt];
3017       while (inner > 0 && inner < nchain)
3018         {
3019           ++nsyms;
3020           if (maxlength < ++lengths[cnt])
3021             ++maxlength;
3022
3023           inner = chain[inner];
3024         }
3025     }
3026
3027   print_hash_info (ebl, scn, shdr, shstrndx, maxlength, nbucket, nsyms,
3028                    lengths, NULL);
3029
3030   free (lengths);
3031 }
3032
3033
3034 /* This function handles the incorrect, System V-style hash table
3035    format some 64-bit architectures use.  */
3036 static void
3037 handle_sysv_hash64 (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, size_t shstrndx)
3038 {
3039   Elf_Data *data = elf_getdata (scn, NULL);
3040   if (unlikely (data == NULL))
3041     {
3042       error (0, 0, gettext ("cannot get data for section %d: %s"),
3043              (int) elf_ndxscn (scn), elf_errmsg (-1));
3044       return;
3045     }
3046
3047   if (unlikely (data->d_size < 2 * sizeof (Elf64_Xword)))
3048     {
3049     invalid_data:
3050       error (0, 0, gettext ("invalid data in sysv.hash64 section %d"),
3051              (int) elf_ndxscn (scn));
3052       return;
3053     }
3054
3055   Elf64_Xword nbucket = ((Elf64_Xword *) data->d_buf)[0];
3056   Elf64_Xword nchain = ((Elf64_Xword *) data->d_buf)[1];
3057
3058   uint64_t maxwords = data->d_size / sizeof (Elf64_Xword);
3059   if (maxwords < 2
3060       || maxwords - 2 < nbucket
3061       || maxwords - 2 - nbucket < nchain)
3062     goto invalid_data;
3063
3064   Elf64_Xword *bucket = &((Elf64_Xword *) data->d_buf)[2];
3065   Elf64_Xword *chain = &((Elf64_Xword *) data->d_buf)[2 + nbucket];
3066
3067   uint32_t *lengths = (uint32_t *) xcalloc (nbucket, sizeof (uint32_t));
3068
3069   uint_fast32_t maxlength = 0;
3070   uint_fast32_t nsyms = 0;
3071   for (Elf64_Xword cnt = 0; cnt < nbucket; ++cnt)
3072     {
3073       Elf64_Xword inner = bucket[cnt];
3074       while (inner > 0 && inner < nchain)
3075         {
3076           ++nsyms;
3077           if (maxlength < ++lengths[cnt])
3078             ++maxlength;
3079
3080           inner = chain[inner];
3081         }
3082     }
3083
3084   print_hash_info (ebl, scn, shdr, shstrndx, maxlength, nbucket, nsyms,
3085                    lengths, NULL);
3086
3087   free (lengths);
3088 }
3089
3090
3091 /* This function handles the GNU-style hash table format.  */
3092 static void
3093 handle_gnu_hash (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, size_t shstrndx)
3094 {
3095   Elf_Data *data = elf_getdata (scn, NULL);
3096   if (unlikely (data == NULL))
3097     {
3098       error (0, 0, gettext ("cannot get data for section %d: %s"),
3099              (int) elf_ndxscn (scn), elf_errmsg (-1));
3100       return;
3101     }
3102
3103   if (unlikely (data->d_size < 4 * sizeof (Elf32_Word)))
3104     {
3105     invalid_data:
3106       error (0, 0, gettext ("invalid data in gnu.hash section %d"),
3107              (int) elf_ndxscn (scn));
3108       return;
3109     }
3110
3111   Elf32_Word nbucket = ((Elf32_Word *) data->d_buf)[0];
3112   Elf32_Word symbias = ((Elf32_Word *) data->d_buf)[1];
3113
3114   /* Next comes the size of the bitmap.  It's measured in words for
3115      the architecture.  It's 32 bits for 32 bit archs, and 64 bits for
3116      64 bit archs.  There is always a bloom filter present, so zero is
3117      an invalid value.  */
3118   Elf32_Word bitmask_words = ((Elf32_Word *) data->d_buf)[2];
3119   if (gelf_getclass (ebl->elf) == ELFCLASS64)
3120     bitmask_words *= 2;
3121
3122   if (bitmask_words == 0)
3123     goto invalid_data;
3124
3125   Elf32_Word shift = ((Elf32_Word *) data->d_buf)[3];
3126
3127   /* Is there still room for the sym chain?
3128      Use uint64_t calculation to prevent 32bit overlow.  */
3129   uint64_t used_buf = (4ULL + bitmask_words + nbucket) * sizeof (Elf32_Word);
3130   uint32_t max_nsyms = (data->d_size - used_buf) / sizeof (Elf32_Word);
3131   if (used_buf > data->d_size)
3132     goto invalid_data;
3133
3134   uint32_t *lengths = (uint32_t *) xcalloc (nbucket, sizeof (uint32_t));
3135
3136   Elf32_Word *bitmask = &((Elf32_Word *) data->d_buf)[4];
3137   Elf32_Word *bucket = &((Elf32_Word *) data->d_buf)[4 + bitmask_words];
3138   Elf32_Word *chain = &((Elf32_Word *) data->d_buf)[4 + bitmask_words
3139                                                     + nbucket];
3140
3141   /* Compute distribution of chain lengths.  */
3142   uint_fast32_t maxlength = 0;
3143   uint_fast32_t nsyms = 0;
3144   for (Elf32_Word cnt = 0; cnt < nbucket; ++cnt)
3145     if (bucket[cnt] != 0)
3146       {
3147         Elf32_Word inner = bucket[cnt] - symbias;
3148         do
3149           {
3150             ++nsyms;
3151             if (maxlength < ++lengths[cnt])
3152               ++maxlength;
3153             if (inner > max_nsyms)
3154               goto invalid_data;
3155           }
3156         while ((chain[inner++] & 1) == 0);
3157       }
3158
3159   /* Count bits in bitmask.  */
3160   uint_fast32_t nbits = 0;
3161   for (Elf32_Word cnt = 0; cnt < bitmask_words; ++cnt)
3162     {
3163       uint_fast32_t word = bitmask[cnt];
3164
3165       word = (word & 0x55555555) + ((word >> 1) & 0x55555555);
3166       word = (word & 0x33333333) + ((word >> 2) & 0x33333333);
3167       word = (word & 0x0f0f0f0f) + ((word >> 4) & 0x0f0f0f0f);
3168       word = (word & 0x00ff00ff) + ((word >> 8) & 0x00ff00ff);
3169       nbits += (word & 0x0000ffff) + ((word >> 16) & 0x0000ffff);
3170     }
3171
3172   char *str;
3173   if (unlikely (asprintf (&str, gettext ("\
3174  Symbol Bias: %u\n\
3175  Bitmask Size: %zu bytes  %" PRIuFAST32 "%% bits set  2nd hash shift: %u\n"),
3176                           (unsigned int) symbias,
3177                           bitmask_words * sizeof (Elf32_Word),
3178                           ((nbits * 100 + 50)
3179                            / (uint_fast32_t) (bitmask_words
3180                                               * sizeof (Elf32_Word) * 8)),
3181                           (unsigned int) shift) == -1))
3182     error (EXIT_FAILURE, 0, gettext ("memory exhausted"));
3183
3184   print_hash_info (ebl, scn, shdr, shstrndx, maxlength, nbucket, nsyms,
3185                    lengths, str);
3186
3187   free (str);
3188   free (lengths);
3189 }
3190
3191
3192 /* Find the symbol table(s).  For this we have to search through the
3193    section table.  */
3194 static void
3195 handle_hash (Ebl *ebl)
3196 {
3197   /* Get the section header string table index.  */
3198   size_t shstrndx;
3199   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
3200     error (EXIT_FAILURE, 0,
3201            gettext ("cannot get section header string table index"));
3202
3203   Elf_Scn *scn = NULL;
3204   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
3205     {
3206       /* Handle the section if it is a symbol table.  */
3207       GElf_Shdr shdr_mem;
3208       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
3209
3210       if (likely (shdr != NULL))
3211         {
3212           if (shdr->sh_type == SHT_HASH)
3213             {
3214               if (ebl_sysvhash_entrysize (ebl) == sizeof (Elf64_Xword))
3215                 handle_sysv_hash64 (ebl, scn, shdr, shstrndx);
3216               else
3217                 handle_sysv_hash (ebl, scn, shdr, shstrndx);
3218             }
3219           else if (shdr->sh_type == SHT_GNU_HASH)
3220             handle_gnu_hash (ebl, scn, shdr, shstrndx);
3221         }
3222     }
3223 }
3224
3225
3226 static void
3227 print_liblist (Ebl *ebl)
3228 {
3229   /* Find the library list sections.  For this we have to search
3230      through the section table.  */
3231   Elf_Scn *scn = NULL;
3232
3233   /* Get the section header string table index.  */
3234   size_t shstrndx;
3235   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
3236     error (EXIT_FAILURE, 0,
3237            gettext ("cannot get section header string table index"));
3238
3239   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
3240     {
3241       GElf_Shdr shdr_mem;
3242       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
3243
3244       if (shdr != NULL && shdr->sh_type == SHT_GNU_LIBLIST)
3245         {
3246           size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_LIB, 1, EV_CURRENT);
3247           int nentries = shdr->sh_size / sh_entsize;
3248           printf (ngettext ("\
3249 \nLibrary list section [%2zu] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
3250                             "\
3251 \nLibrary list section [%2zu] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
3252                             nentries),
3253                   elf_ndxscn (scn),
3254                   elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
3255                   shdr->sh_offset,
3256                   nentries);
3257
3258           Elf_Data *data = elf_getdata (scn, NULL);
3259           if (data == NULL)
3260             return;
3261
3262           puts (gettext ("\
3263        Library                       Time Stamp          Checksum Version Flags"));
3264
3265           for (int cnt = 0; cnt < nentries; ++cnt)
3266             {
3267               GElf_Lib lib_mem;
3268               GElf_Lib *lib = gelf_getlib (data, cnt, &lib_mem);
3269               if (unlikely (lib == NULL))
3270                 continue;
3271
3272               time_t t = (time_t) lib->l_time_stamp;
3273               struct tm *tm = gmtime (&t);
3274               if (unlikely (tm == NULL))
3275                 continue;
3276
3277               printf ("  [%2d] %-29s %04u-%02u-%02uT%02u:%02u:%02u %08x %-7u %u\n",
3278                       cnt, elf_strptr (ebl->elf, shdr->sh_link, lib->l_name),
3279                       tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
3280                       tm->tm_hour, tm->tm_min, tm->tm_sec,
3281                       (unsigned int) lib->l_checksum,
3282                       (unsigned int) lib->l_version,
3283                       (unsigned int) lib->l_flags);
3284             }
3285         }
3286     }
3287 }
3288
3289 static void
3290 print_attributes (Ebl *ebl, const GElf_Ehdr *ehdr)
3291 {
3292   /* Find the object attributes sections.  For this we have to search
3293      through the section table.  */
3294   Elf_Scn *scn = NULL;
3295
3296   /* Get the section header string table index.  */
3297   size_t shstrndx;
3298   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
3299     error (EXIT_FAILURE, 0,
3300            gettext ("cannot get section header string table index"));
3301
3302   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
3303     {
3304       GElf_Shdr shdr_mem;
3305       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
3306
3307       if (shdr == NULL || (shdr->sh_type != SHT_GNU_ATTRIBUTES
3308                            && (shdr->sh_type != SHT_ARM_ATTRIBUTES
3309                                || ehdr->e_machine != EM_ARM)))
3310         continue;
3311
3312       printf (gettext ("\
3313 \nObject attributes section [%2zu] '%s' of %" PRIu64
3314                        " bytes at offset %#0" PRIx64 ":\n"),
3315               elf_ndxscn (scn),
3316               elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
3317               shdr->sh_size, shdr->sh_offset);
3318
3319       Elf_Data *data = elf_rawdata (scn, NULL);
3320       if (unlikely (data == NULL || data->d_size == 0))
3321         return;
3322
3323       const unsigned char *p = data->d_buf;
3324
3325       /* There is only one 'version', A.  */
3326       if (unlikely (*p++ != 'A'))
3327         return;
3328
3329       fputs_unlocked (gettext ("  Owner          Size\n"), stdout);
3330
3331       inline size_t left (void)
3332       {
3333         return (const unsigned char *) data->d_buf + data->d_size - p;
3334       }
3335
3336       /* Loop over the sections.  */
3337       while (left () >= 4)
3338         {
3339           /* Section length.  */
3340           uint32_t len;
3341           memcpy (&len, p, sizeof len);
3342
3343           if (MY_ELFDATA != ehdr->e_ident[EI_DATA])
3344             CONVERT (len);
3345
3346           if (unlikely (len > left ()))
3347             break;
3348
3349           /* Section vendor name.  */
3350           const unsigned char *name = p + sizeof len;
3351           p += len;
3352
3353           unsigned const char *q = memchr (name, '\0', len);
3354           if (unlikely (q == NULL))
3355             break;
3356           ++q;
3357
3358           printf (gettext ("  %-13s  %4" PRIu32 "\n"), name, len);
3359
3360           bool gnu_vendor = (q - name == sizeof "gnu"
3361                              && !memcmp (name, "gnu", sizeof "gnu"));
3362
3363           /* Loop over subsections.  */
3364           if (shdr->sh_type != SHT_GNU_ATTRIBUTES
3365               || gnu_vendor)
3366             while (q < p)
3367               {
3368                 const unsigned char *const sub = q;
3369
3370                 unsigned int subsection_tag;
3371                 get_uleb128 (subsection_tag, q, p);
3372                 if (unlikely (q >= p))
3373                   break;
3374
3375                 uint32_t subsection_len;
3376                 if (unlikely (p - sub < (ptrdiff_t) sizeof subsection_len))
3377                   break;
3378
3379                 memcpy (&subsection_len, q, sizeof subsection_len);
3380
3381                 if (MY_ELFDATA != ehdr->e_ident[EI_DATA])
3382                   CONVERT (subsection_len);
3383
3384                 /* Don't overflow, ptrdiff_t might be 32bits, but signed.  */
3385                 if (unlikely (subsection_len == 0
3386                               || subsection_len >= (uint32_t) PTRDIFF_MAX
3387                               || p - sub < (ptrdiff_t) subsection_len))
3388                   break;
3389
3390                 const unsigned char *r = q + sizeof subsection_len;
3391                 q = sub + subsection_len;
3392
3393                 switch (subsection_tag)
3394                   {
3395                   default:
3396                     /* Unknown subsection, print and skip.  */
3397                     printf (gettext ("    %-4u %12" PRIu32 "\n"),
3398                             subsection_tag, subsection_len);
3399                     break;
3400
3401                   case 1:       /* Tag_File */
3402                     printf (gettext ("    File: %11" PRIu32 "\n"),
3403                             subsection_len);
3404
3405                     while (r < q)
3406                       {
3407                         unsigned int tag;
3408                         get_uleb128 (tag, r, q);
3409                         if (unlikely (r >= q))
3410                           break;
3411
3412                         /* GNU style tags have either a uleb128 value,
3413                            when lowest bit is not set, or a string
3414                            when the lowest bit is set.
3415                            "compatibility" (32) is special.  It has
3416                            both a string and a uleb128 value.  For
3417                            non-gnu we assume 6 till 31 only take ints.
3418                            XXX see arm backend, do we need a separate
3419                            hook?  */
3420                         uint64_t value = 0;
3421                         const char *string = NULL;
3422                         if (tag == 32 || (tag & 1) == 0
3423                             || (! gnu_vendor && (tag > 5 && tag < 32)))
3424                           {
3425                             get_uleb128 (value, r, q);
3426                             if (r > q)
3427                               break;
3428                           }
3429                         if (tag == 32
3430                             || ((tag & 1) != 0
3431                                 && (gnu_vendor
3432                                     || (! gnu_vendor && tag > 32)))
3433                             || (! gnu_vendor && tag > 3 && tag < 6))
3434                           {
3435                             string = (const char *) r;
3436                             r = memchr (r, '\0', q - r);
3437                             if (r == NULL)
3438                               break;
3439                             ++r;
3440                           }
3441
3442                         const char *tag_name = NULL;
3443                         const char *value_name = NULL;
3444                         ebl_check_object_attribute (ebl, (const char *) name,
3445                                                     tag, value,
3446                                                     &tag_name, &value_name);
3447
3448                         if (tag_name != NULL)
3449                           {
3450                             if (tag == 32)
3451                               printf (gettext ("      %s: %" PRId64 ", %s\n"),
3452                                       tag_name, value, string);
3453                             else if (string == NULL && value_name == NULL)
3454                               printf (gettext ("      %s: %" PRId64 "\n"),
3455                                       tag_name, value);
3456                             else
3457                               printf (gettext ("      %s: %s\n"),
3458                                       tag_name, string ?: value_name);
3459                           }
3460                         else
3461                           {
3462                             /* For "gnu" vendor 32 "compatibility" has
3463                                already been handled above.  */
3464                             assert (tag != 32
3465                                     || strcmp ((const char *) name, "gnu"));
3466                             if (string == NULL)
3467                               printf (gettext ("      %u: %" PRId64 "\n"),
3468                                       tag, value);
3469                             else
3470                               printf (gettext ("      %u: %s\n"),
3471                                       tag, string);
3472                           }
3473                       }
3474                   }
3475               }
3476         }
3477     }
3478 }
3479
3480
3481 static char *
3482 format_dwarf_addr (Dwfl_Module *dwflmod,
3483                    int address_size, Dwarf_Addr address, Dwarf_Addr raw)
3484 {
3485   /* See if there is a name we can give for this address.  */
3486   GElf_Sym sym;
3487   GElf_Off off = 0;
3488   const char *name = (print_address_names && ! print_unresolved_addresses)
3489     ? dwfl_module_addrinfo (dwflmod, address, &off, &sym, NULL, NULL, NULL)
3490     : NULL;
3491
3492   const char *scn;
3493   if (print_unresolved_addresses)
3494     {
3495       address = raw;
3496       scn = NULL;
3497     }
3498   else
3499     {
3500       /* Relativize the address.  */
3501       int n = dwfl_module_relocations (dwflmod);
3502       int i = n < 1 ? -1 : dwfl_module_relocate_address (dwflmod, &address);
3503
3504       /* In an ET_REL file there is a section name to refer to.  */
3505       scn = (i < 0 ? NULL
3506              : dwfl_module_relocation_info (dwflmod, i, NULL));
3507     }
3508
3509   char *result;
3510   if ((name != NULL
3511        ? (off != 0
3512           ? (scn != NULL
3513              ? (address_size == 0
3514                 ? asprintf (&result,
3515                             gettext ("%s+%#" PRIx64 " <%s+%#" PRIx64 ">"),
3516                             scn, address, name, off)
3517                 : asprintf (&result,
3518                             gettext ("%s+%#0*" PRIx64 " <%s+%#" PRIx64 ">"),
3519                             scn, 2 + address_size * 2, address,
3520                             name, off))
3521              : (address_size == 0
3522                 ? asprintf (&result,
3523                             gettext ("%#" PRIx64 " <%s+%#" PRIx64 ">"),
3524                             address, name, off)
3525                 : asprintf (&result,
3526                             gettext ("%#0*" PRIx64 " <%s+%#" PRIx64 ">"),
3527                             2 + address_size * 2, address,
3528                             name, off)))
3529           : (scn != NULL
3530              ? (address_size == 0
3531                 ? asprintf (&result,
3532                             gettext ("%s+%#" PRIx64 " <%s>"),
3533                             scn, address, name)
3534                 : asprintf (&result,
3535                             gettext ("%s+%#0*" PRIx64 " <%s>"),
3536                             scn, 2 + address_size * 2, address, name))
3537              : (address_size == 0
3538                 ? asprintf (&result,
3539                             gettext ("%#" PRIx64 " <%s>"),
3540                             address, name)
3541                 : asprintf (&result,
3542                             gettext ("%#0*" PRIx64 " <%s>"),
3543                             2 + address_size * 2, address, name))))
3544        : (scn != NULL
3545           ? (address_size == 0
3546              ? asprintf (&result,
3547                          gettext ("%s+%#" PRIx64),
3548                          scn, address)
3549              : asprintf (&result,
3550                          gettext ("%s+%#0*" PRIx64),
3551                          scn, 2 + address_size * 2, address))
3552           : (address_size == 0
3553              ? asprintf (&result,
3554                          "%#" PRIx64,
3555                          address)
3556              : asprintf (&result,
3557                          "%#0*" PRIx64,
3558                          2 + address_size * 2, address)))) < 0)
3559     error (EXIT_FAILURE, 0, _("memory exhausted"));
3560
3561   return result;
3562 }
3563
3564 static const char *
3565 dwarf_tag_string (unsigned int tag)
3566 {
3567   switch (tag)
3568     {
3569 #define ONE_KNOWN_DW_TAG(NAME, CODE) case CODE: return #NAME;
3570       ALL_KNOWN_DW_TAG
3571 #undef ONE_KNOWN_DW_TAG
3572     default:
3573       return NULL;
3574     }
3575 }
3576
3577
3578 static const char *
3579 dwarf_attr_string (unsigned int attrnum)
3580 {
3581   switch (attrnum)
3582     {
3583 #define ONE_KNOWN_DW_AT(NAME, CODE) case CODE: return #NAME;
3584       ALL_KNOWN_DW_AT
3585 #undef ONE_KNOWN_DW_AT
3586     default:
3587       return NULL;
3588     }
3589 }
3590
3591
3592 static const char *
3593 dwarf_form_string (unsigned int form)
3594 {
3595   switch (form)
3596     {
3597 #define ONE_KNOWN_DW_FORM_DESC(NAME, CODE, DESC) ONE_KNOWN_DW_FORM (NAME, CODE)
3598 #define ONE_KNOWN_DW_FORM(NAME, CODE) case CODE: return #NAME;
3599       ALL_KNOWN_DW_FORM
3600 #undef ONE_KNOWN_DW_FORM
3601 #undef ONE_KNOWN_DW_FORM_DESC
3602     default:
3603       return NULL;
3604     }
3605 }
3606
3607
3608 static const char *
3609 dwarf_lang_string (unsigned int lang)
3610 {
3611   switch (lang)
3612     {
3613 #define ONE_KNOWN_DW_LANG_DESC(NAME, CODE, DESC) case CODE: return #NAME;
3614       ALL_KNOWN_DW_LANG
3615 #undef ONE_KNOWN_DW_LANG_DESC
3616     default:
3617       return NULL;
3618     }
3619 }
3620
3621
3622 static const char *
3623 dwarf_inline_string (unsigned int code)
3624 {
3625   static const char *const known[] =
3626     {
3627 #define ONE_KNOWN_DW_INL(NAME, CODE) [CODE] = #NAME,
3628       ALL_KNOWN_DW_INL
3629 #undef ONE_KNOWN_DW_INL
3630     };
3631
3632   if (likely (code < sizeof (known) / sizeof (known[0])))
3633     return known[code];
3634
3635   return NULL;
3636 }
3637
3638
3639 static const char *
3640 dwarf_encoding_string (unsigned int code)
3641 {
3642   static const char *const known[] =
3643     {
3644 #define ONE_KNOWN_DW_ATE(NAME, CODE) [CODE] = #NAME,
3645       ALL_KNOWN_DW_ATE
3646 #undef ONE_KNOWN_DW_ATE
3647     };
3648
3649   if (likely (code < sizeof (known) / sizeof (known[0])))
3650     return known[code];
3651
3652   return NULL;
3653 }
3654
3655
3656 static const char *
3657 dwarf_access_string (unsigned int code)
3658 {
3659   static const char *const known[] =
3660     {
3661 #define ONE_KNOWN_DW_ACCESS(NAME, CODE) [CODE] = #NAME,
3662       ALL_KNOWN_DW_ACCESS
3663 #undef ONE_KNOWN_DW_ACCESS
3664     };
3665
3666   if (likely (code < sizeof (known) / sizeof (known[0])))
3667     return known[code];
3668
3669   return NULL;
3670 }
3671
3672
3673 static const char *
3674 dwarf_visibility_string (unsigned int code)
3675 {
3676   static const char *const known[] =
3677     {
3678 #define ONE_KNOWN_DW_VIS(NAME, CODE) [CODE] = #NAME,
3679       ALL_KNOWN_DW_VIS
3680 #undef ONE_KNOWN_DW_VIS
3681     };
3682
3683   if (likely (code < sizeof (known) / sizeof (known[0])))
3684     return known[code];
3685
3686   return NULL;
3687 }
3688
3689
3690 static const char *
3691 dwarf_virtuality_string (unsigned int code)
3692 {
3693   static const char *const known[] =
3694     {
3695 #define ONE_KNOWN_DW_VIRTUALITY(NAME, CODE) [CODE] = #NAME,
3696       ALL_KNOWN_DW_VIRTUALITY
3697 #undef ONE_KNOWN_DW_VIRTUALITY
3698     };
3699
3700   if (likely (code < sizeof (known) / sizeof (known[0])))
3701     return known[code];
3702
3703   return NULL;
3704 }
3705
3706
3707 static const char *
3708 dwarf_identifier_case_string (unsigned int code)
3709 {
3710   static const char *const known[] =
3711     {
3712 #define ONE_KNOWN_DW_ID(NAME, CODE) [CODE] = #NAME,
3713       ALL_KNOWN_DW_ID
3714 #undef ONE_KNOWN_DW_ID
3715     };
3716
3717   if (likely (code < sizeof (known) / sizeof (known[0])))
3718     return known[code];
3719
3720   return NULL;
3721 }
3722
3723
3724 static const char *
3725 dwarf_calling_convention_string (unsigned int code)
3726 {
3727   static const char *const known[] =
3728     {
3729 #define ONE_KNOWN_DW_CC(NAME, CODE) [CODE] = #NAME,
3730       ALL_KNOWN_DW_CC
3731 #undef ONE_KNOWN_DW_CC
3732     };
3733
3734   if (likely (code < sizeof (known) / sizeof (known[0])))
3735     return known[code];
3736
3737   return NULL;
3738 }
3739
3740
3741 static const char *
3742 dwarf_ordering_string (unsigned int code)
3743 {
3744   static const char *const known[] =
3745     {
3746 #define ONE_KNOWN_DW_ORD(NAME, CODE) [CODE] = #NAME,
3747       ALL_KNOWN_DW_ORD
3748 #undef ONE_KNOWN_DW_ORD
3749     };
3750
3751   if (likely (code < sizeof (known) / sizeof (known[0])))
3752     return known[code];
3753
3754   return NULL;
3755 }
3756
3757
3758 static const char *
3759 dwarf_discr_list_string (unsigned int code)
3760 {
3761   static const char *const known[] =
3762     {
3763 #define ONE_KNOWN_DW_DSC(NAME, CODE) [CODE] = #NAME,
3764       ALL_KNOWN_DW_DSC
3765 #undef ONE_KNOWN_DW_DSC
3766     };
3767
3768   if (likely (code < sizeof (known) / sizeof (known[0])))
3769     return known[code];
3770
3771   return NULL;
3772 }
3773
3774
3775 static const char *
3776 dwarf_locexpr_opcode_string (unsigned int code)
3777 {
3778   static const char *const known[] =
3779     {
3780       /* Normally we can't affort building huge table of 64K entries,
3781          most of them zero, just because there are a couple defined
3782          values at the far end.  In case of opcodes, it's OK.  */
3783 #define ONE_KNOWN_DW_OP_DESC(NAME, CODE, DESC) ONE_KNOWN_DW_OP (NAME, CODE)
3784 #define ONE_KNOWN_DW_OP(NAME, CODE) [CODE] = #NAME,
3785       ALL_KNOWN_DW_OP
3786 #undef ONE_KNOWN_DW_OP
3787 #undef ONE_KNOWN_DW_OP_DESC
3788     };
3789
3790   if (likely (code < sizeof (known) / sizeof (known[0])))
3791     return known[code];
3792
3793   return NULL;
3794 }
3795
3796
3797 /* Used by all dwarf_foo_name functions.  */
3798 static const char *
3799 string_or_unknown (const char *known, unsigned int code,
3800                    unsigned int lo_user, unsigned int hi_user,
3801                    bool print_unknown_num)
3802 {
3803   static char unknown_buf[20];
3804
3805   if (likely (known != NULL))
3806     return known;
3807
3808   if (lo_user != 0 && code >= lo_user && code <= hi_user)
3809     {
3810       snprintf (unknown_buf, sizeof unknown_buf, "lo_user+%#x",
3811                 code - lo_user);
3812       return unknown_buf;
3813     }
3814
3815   if (print_unknown_num)
3816     {
3817       snprintf (unknown_buf, sizeof unknown_buf, "??? (%#x)", code);
3818       return unknown_buf;
3819     }
3820
3821   return "???";
3822 }
3823
3824
3825 static const char *
3826 dwarf_tag_name (unsigned int tag)
3827 {
3828   const char *ret = dwarf_tag_string (tag);
3829   return string_or_unknown (ret, tag, DW_TAG_lo_user, DW_TAG_hi_user, true);
3830 }
3831
3832 static const char *
3833 dwarf_attr_name (unsigned int attr)
3834 {
3835   const char *ret = dwarf_attr_string (attr);
3836   return string_or_unknown (ret, attr, DW_AT_lo_user, DW_AT_hi_user, true);
3837 }
3838
3839
3840 static const char *
3841 dwarf_form_name (unsigned int form)
3842 {
3843   const char *ret = dwarf_form_string (form);
3844   return string_or_unknown (ret, form, 0, 0, true);
3845 }
3846
3847
3848 static const char *
3849 dwarf_lang_name (unsigned int lang)
3850 {
3851   const char *ret = dwarf_lang_string (lang);
3852   return string_or_unknown (ret, lang, DW_LANG_lo_user, DW_LANG_hi_user, false);
3853 }
3854
3855
3856 static const char *
3857 dwarf_inline_name (unsigned int code)
3858 {
3859   const char *ret = dwarf_inline_string (code);
3860   return string_or_unknown (ret, code, 0, 0, false);
3861 }
3862
3863
3864 static const char *
3865 dwarf_encoding_name (unsigned int code)
3866 {
3867   const char *ret = dwarf_encoding_string (code);
3868   return string_or_unknown (ret, code, DW_ATE_lo_user, DW_ATE_hi_user, false);
3869 }
3870
3871
3872 static const char *
3873 dwarf_access_name (unsigned int code)
3874 {
3875   const char *ret = dwarf_access_string (code);
3876   return string_or_unknown (ret, code, 0, 0, false);
3877 }
3878
3879
3880 static const char *
3881 dwarf_visibility_name (unsigned int code)
3882 {
3883   const char *ret = dwarf_visibility_string (code);
3884   return string_or_unknown (ret, code, 0, 0, false);
3885 }
3886
3887
3888 static const char *
3889 dwarf_virtuality_name (unsigned int code)
3890 {
3891   const char *ret = dwarf_virtuality_string (code);
3892   return string_or_unknown (ret, code, 0, 0, false);
3893 }
3894
3895
3896 static const char *
3897 dwarf_identifier_case_name (unsigned int code)
3898 {
3899   const char *ret = dwarf_identifier_case_string (code);
3900   return string_or_unknown (ret, code, 0, 0, false);
3901 }
3902
3903
3904 static const char *
3905 dwarf_calling_convention_name (unsigned int code)
3906 {
3907   const char *ret = dwarf_calling_convention_string (code);
3908   return string_or_unknown (ret, code, DW_CC_lo_user, DW_CC_hi_user, false);
3909 }
3910
3911
3912 static const char *
3913 dwarf_ordering_name (unsigned int code)
3914 {
3915   const char *ret = dwarf_ordering_string (code);
3916   return string_or_unknown (ret, code, 0, 0, false);
3917 }
3918
3919
3920 static const char *
3921 dwarf_discr_list_name (unsigned int code)
3922 {
3923   const char *ret = dwarf_discr_list_string (code);
3924   return string_or_unknown (ret, code, 0, 0, false);
3925 }
3926
3927
3928 static void
3929 print_block (size_t n, const void *block)
3930 {
3931   if (n == 0)
3932     puts (_("empty block"));
3933   else
3934     {
3935       printf (_("%zu byte block:"), n);
3936       const unsigned char *data = block;
3937       do
3938         printf (" %02x", *data++);
3939       while (--n > 0);
3940       putchar ('\n');
3941     }
3942 }
3943
3944 static void
3945 print_ops (Dwfl_Module *dwflmod, Dwarf *dbg, int indent, int indentrest,
3946            unsigned int vers, unsigned int addrsize, unsigned int offset_size,
3947            struct Dwarf_CU *cu, Dwarf_Word len, const unsigned char *data)
3948 {
3949   const unsigned int ref_size = vers < 3 ? addrsize : offset_size;
3950
3951   if (len == 0)
3952     {
3953       printf ("%*s(empty)\n", indent, "");
3954       return;
3955     }
3956
3957 #define NEED(n)         if (len < (Dwarf_Word) (n)) goto invalid
3958 #define CONSUME(n)      NEED (n); else len -= (n)
3959
3960   Dwarf_Word offset = 0;
3961   while (len-- > 0)
3962     {
3963       uint_fast8_t op = *data++;
3964
3965       const char *op_name = dwarf_locexpr_opcode_string (op);
3966       if (unlikely (op_name == NULL))
3967         {
3968           static char buf[20];
3969           if (op >= DW_OP_lo_user)
3970             snprintf (buf, sizeof buf, "lo_user+%#x", op - DW_OP_lo_user);
3971           else
3972             snprintf (buf, sizeof buf, "??? (%#x)", op);
3973           op_name = buf;
3974         }
3975
3976       switch (op)
3977         {
3978         case DW_OP_addr:;
3979           /* Address operand.  */
3980           Dwarf_Word addr;
3981           NEED (addrsize);
3982           if (addrsize == 4)
3983             addr = read_4ubyte_unaligned (dbg, data);
3984           else if (addrsize == 8)
3985             addr = read_8ubyte_unaligned (dbg, data);
3986           else
3987             goto invalid;
3988           data += addrsize;
3989           CONSUME (addrsize);
3990
3991           char *a = format_dwarf_addr (dwflmod, 0, addr, addr);
3992           printf ("%*s[%4" PRIuMAX "] %s %s\n",
3993                   indent, "", (uintmax_t) offset, op_name, a);
3994           free (a);
3995
3996           offset += 1 + addrsize;
3997           break;
3998
3999         case DW_OP_call_ref:
4000           /* Offset operand.  */
4001           if (ref_size != 4 && ref_size != 8)
4002             goto invalid; /* Cannot be used in CFA.  */
4003           NEED (ref_size);
4004           if (ref_size == 4)
4005             addr = read_4ubyte_unaligned (dbg, data);
4006           else
4007             addr = read_8ubyte_unaligned (dbg, data);
4008           data += ref_size;
4009           CONSUME (ref_size);
4010
4011           printf ("%*s[%4" PRIuMAX "] %s %#" PRIxMAX "\n",
4012                   indent, "", (uintmax_t) offset,
4013                   op_name, (uintmax_t) addr);
4014           offset += 1 + ref_size;
4015           break;
4016
4017         case DW_OP_deref_size:
4018         case DW_OP_xderef_size:
4019         case DW_OP_pick:
4020         case DW_OP_const1u:
4021           // XXX value might be modified by relocation
4022           NEED (1);
4023           printf ("%*s[%4" PRIuMAX "] %s %" PRIu8 "\n",
4024                   indent, "", (uintmax_t) offset,
4025                   op_name, *((uint8_t *) data));
4026           ++data;
4027           --len;
4028           offset += 2;
4029           break;
4030
4031         case DW_OP_const2u:
4032           NEED (2);
4033           // XXX value might be modified by relocation
4034           printf ("%*s[%4" PRIuMAX "] %s %" PRIu16 "\n",
4035                   indent, "", (uintmax_t) offset,
4036                   op_name, read_2ubyte_unaligned (dbg, data));
4037           CONSUME (2);
4038           data += 2;
4039           offset += 3;
4040           break;
4041
4042         case DW_OP_const4u:
4043           NEED (4);
4044           // XXX value might be modified by relocation
4045           printf ("%*s[%4" PRIuMAX "] %s %" PRIu32 "\n",
4046                   indent, "", (uintmax_t) offset,
4047                   op_name, read_4ubyte_unaligned (dbg, data));
4048           CONSUME (4);
4049           data += 4;
4050           offset += 5;
4051           break;
4052
4053         case DW_OP_const8u:
4054           NEED (8);
4055           // XXX value might be modified by relocation
4056           printf ("%*s[%4" PRIuMAX "] %s %" PRIu64 "\n",
4057                   indent, "", (uintmax_t) offset,
4058                   op_name, (uint64_t) read_8ubyte_unaligned (dbg, data));
4059           CONSUME (8);
4060           data += 8;
4061           offset += 9;
4062           break;
4063
4064         case DW_OP_const1s:
4065           NEED (1);
4066           // XXX value might be modified by relocation
4067           printf ("%*s[%4" PRIuMAX "] %s %" PRId8 "\n",
4068                   indent, "", (uintmax_t) offset,
4069                   op_name, *((int8_t *) data));
4070           ++data;
4071           --len;
4072           offset += 2;
4073           break;
4074
4075         case DW_OP_const2s:
4076           NEED (2);
4077           // XXX value might be modified by relocation
4078           printf ("%*s[%4" PRIuMAX "] %s %" PRId16 "\n",
4079                   indent, "", (uintmax_t) offset,
4080                   op_name, read_2sbyte_unaligned (dbg, data));
4081           CONSUME (2);
4082           data += 2;
4083           offset += 3;
4084           break;
4085
4086         case DW_OP_const4s:
4087           NEED (4);
4088           // XXX value might be modified by relocation
4089           printf ("%*s[%4" PRIuMAX "] %s %" PRId32 "\n",
4090                   indent, "", (uintmax_t) offset,
4091                   op_name, read_4sbyte_unaligned (dbg, data));
4092           CONSUME (4);
4093           data += 4;
4094           offset += 5;
4095           break;
4096
4097         case DW_OP_const8s:
4098           NEED (8);
4099           // XXX value might be modified by relocation
4100           printf ("%*s[%4" PRIuMAX "] %s %" PRId64 "\n",
4101                   indent, "", (uintmax_t) offset,
4102                   op_name, read_8sbyte_unaligned (dbg, data));
4103           CONSUME (8);
4104           data += 8;
4105           offset += 9;
4106           break;
4107
4108         case DW_OP_piece:
4109         case DW_OP_regx:
4110         case DW_OP_plus_uconst:
4111         case DW_OP_constu:;
4112           const unsigned char *start = data;
4113           uint64_t uleb;
4114           NEED (1);
4115           get_uleb128 (uleb, data, data + len);
4116           printf ("%*s[%4" PRIuMAX "] %s %" PRIu64 "\n",
4117                   indent, "", (uintmax_t) offset, op_name, uleb);
4118           CONSUME (data - start);
4119           offset += 1 + (data - start);
4120           break;
4121
4122         case DW_OP_bit_piece:
4123           start = data;
4124           uint64_t uleb2;
4125           NEED (1);
4126           get_uleb128 (uleb, data, data + len);
4127           NEED (1);
4128           get_uleb128 (uleb2, data, data + len);
4129           printf ("%*s[%4" PRIuMAX "] %s %" PRIu64 ", %" PRIu64 "\n",
4130                   indent, "", (uintmax_t) offset, op_name, uleb, uleb2);
4131           CONSUME (data - start);
4132           offset += 1 + (data - start);
4133           break;
4134
4135         case DW_OP_fbreg:
4136         case DW_OP_breg0 ... DW_OP_breg31:
4137         case DW_OP_consts:
4138           start = data;
4139           int64_t sleb;
4140           NEED (1);
4141           get_sleb128 (sleb, data, data + len);
4142           printf ("%*s[%4" PRIuMAX "] %s %" PRId64 "\n",
4143                   indent, "", (uintmax_t) offset, op_name, sleb);
4144           CONSUME (data - start);
4145           offset += 1 + (data - start);
4146           break;
4147
4148         case DW_OP_bregx:
4149           start = data;
4150           NEED (1);
4151           get_uleb128 (uleb, data, data + len);
4152           NEED (1);
4153           get_sleb128 (sleb, data, data + len);
4154           printf ("%*s[%4" PRIuMAX "] %s %" PRIu64 " %" PRId64 "\n",
4155                   indent, "", (uintmax_t) offset, op_name, uleb, sleb);
4156           CONSUME (data - start);
4157           offset += 1 + (data - start);
4158           break;
4159
4160         case DW_OP_call2:
4161           NEED (2);
4162           printf ("%*s[%4" PRIuMAX "] %s %" PRIu16 "\n",
4163                   indent, "", (uintmax_t) offset, op_name,
4164                   read_2ubyte_unaligned (dbg, data));
4165           CONSUME (2);
4166           offset += 3;
4167           break;
4168
4169         case DW_OP_call4:
4170           NEED (4);
4171           printf ("%*s[%4" PRIuMAX "] %s %" PRIu32 "\n",
4172                   indent, "", (uintmax_t) offset, op_name,
4173                   read_4ubyte_unaligned (dbg, data));
4174           CONSUME (4);
4175           offset += 5;
4176           break;
4177
4178         case DW_OP_skip:
4179         case DW_OP_bra:
4180           NEED (2);
4181           printf ("%*s[%4" PRIuMAX "] %s %" PRIuMAX "\n",
4182                   indent, "", (uintmax_t) offset, op_name,
4183                   (uintmax_t) (offset + read_2sbyte_unaligned (dbg, data) + 3));
4184           CONSUME (2);
4185           data += 2;
4186           offset += 3;
4187           break;
4188
4189         case DW_OP_implicit_value:
4190           start = data;
4191           NEED (1);
4192           get_uleb128 (uleb, data, data + len);
4193           printf ("%*s[%4" PRIuMAX "] %s: ",
4194                   indent, "", (uintmax_t) offset, op_name);
4195           NEED (uleb);
4196           print_block (uleb, data);
4197           data += uleb;
4198           CONSUME (data - start);
4199           offset += 1 + (data - start);
4200           break;
4201
4202         case DW_OP_GNU_implicit_pointer:
4203           /* DIE offset operand.  */
4204           start = data;
4205           NEED (ref_size);
4206           if (ref_size != 4 && ref_size != 8)
4207             goto invalid; /* Cannot be used in CFA.  */
4208           if (ref_size == 4)
4209             addr = read_4ubyte_unaligned (dbg, data);
4210           else
4211             addr = read_8ubyte_unaligned (dbg, data);
4212           data += ref_size;
4213           /* Byte offset operand.  */
4214           NEED (1);
4215           get_sleb128 (sleb, data, data + len);
4216
4217           printf ("%*s[%4" PRIuMAX "] %s [%6" PRIxMAX "] %+" PRId64 "\n",
4218                   indent, "", (intmax_t) offset,
4219                   op_name, (uintmax_t) addr, sleb);
4220           CONSUME (data - start);
4221           offset += 1 + (data - start);
4222           break;
4223
4224         case DW_OP_GNU_entry_value:
4225           /* Size plus expression block.  */
4226           start = data;
4227           NEED (1);
4228           get_uleb128 (uleb, data, data + len);
4229           printf ("%*s[%4" PRIuMAX "] %s:\n",
4230                   indent, "", (uintmax_t) offset, op_name);
4231           NEED (uleb);
4232           print_ops (dwflmod, dbg, indent + 6, indent + 6, vers,
4233                      addrsize, offset_size, cu, uleb, data);
4234           data += uleb;
4235           CONSUME (data - start);
4236           offset += 1 + (data - start);
4237           break;
4238
4239         case DW_OP_GNU_const_type:
4240           /* uleb128 CU relative DW_TAG_base_type DIE offset, 1-byte
4241              unsigned size plus block.  */
4242           start = data;
4243           NEED (1);
4244           get_uleb128 (uleb, data, data + len);
4245           if (! print_unresolved_addresses && cu != NULL)
4246             uleb += cu->start;
4247           NEED (1);
4248           uint8_t usize = *(uint8_t *) data++;
4249           NEED (usize);
4250           printf ("%*s[%4" PRIuMAX "] %s [%6" PRIxMAX "] ",
4251                   indent, "", (uintmax_t) offset, op_name, uleb);
4252           print_block (usize, data);
4253           data += usize;
4254           CONSUME (data - start);
4255           offset += 1 + (data - start);
4256           break;
4257
4258         case DW_OP_GNU_regval_type:
4259           /* uleb128 register number, uleb128 CU relative
4260              DW_TAG_base_type DIE offset.  */
4261           start = data;
4262           NEED (1);
4263           get_uleb128 (uleb, data, data + len);
4264           NEED (1);
4265           get_uleb128 (uleb2, data, data + len);
4266           if (! print_unresolved_addresses && cu != NULL)
4267             uleb2 += cu->start;
4268           printf ("%*s[%4" PRIuMAX "] %s %" PRIu64 " [%6" PRIx64 "]\n",
4269                   indent, "", (uintmax_t) offset, op_name, uleb, uleb2);
4270           CONSUME (data - start);
4271           offset += 1 + (data - start);
4272           break;
4273
4274         case DW_OP_GNU_deref_type:
4275           /* 1-byte unsigned size of value, uleb128 CU relative
4276              DW_TAG_base_type DIE offset.  */
4277           start = data;
4278           NEED (1);
4279           usize = *(uint8_t *) data++;
4280           NEED (1);
4281           get_uleb128 (uleb, data, data + len);
4282           if (! print_unresolved_addresses && cu != NULL)
4283             uleb += cu->start;
4284           printf ("%*s[%4" PRIuMAX "] %s %" PRIu8 " [%6" PRIxMAX "]\n",
4285                   indent, "", (uintmax_t) offset,
4286                   op_name, usize, uleb);
4287           CONSUME (data - start);
4288           offset += 1 + (data - start);
4289           break;
4290
4291         case DW_OP_GNU_convert:
4292         case DW_OP_GNU_reinterpret:
4293           /* uleb128 CU relative offset to DW_TAG_base_type, or zero
4294              for conversion to untyped.  */
4295           start = data;
4296           NEED (1);
4297           get_uleb128 (uleb, data, data + len);
4298           if (uleb != 0 && ! print_unresolved_addresses && cu != NULL)
4299             uleb += cu->start;
4300           printf ("%*s[%4" PRIuMAX "] %s [%6" PRIxMAX "]\n",
4301                   indent, "", (uintmax_t) offset, op_name, uleb);
4302           CONSUME (data - start);
4303           offset += 1 + (data - start);
4304           break;
4305
4306         case DW_OP_GNU_parameter_ref:
4307           /* 4 byte CU relative reference to the abstract optimized away
4308              DW_TAG_formal_parameter.  */
4309           NEED (4);
4310           uintmax_t param_off = (uintmax_t) read_4ubyte_unaligned (dbg, data);
4311           if (! print_unresolved_addresses && cu != NULL)
4312             param_off += cu->start;
4313           printf ("%*s[%4" PRIuMAX "] %s [%6" PRIxMAX "]\n",
4314                   indent, "", (uintmax_t) offset, op_name, param_off);
4315           CONSUME (4);
4316           data += 4;
4317           offset += 5;
4318           break;
4319
4320         default:
4321           /* No Operand.  */
4322           printf ("%*s[%4" PRIuMAX "] %s\n",
4323                   indent, "", (uintmax_t) offset, op_name);
4324           ++offset;
4325           break;
4326         }
4327
4328       indent = indentrest;
4329       continue;
4330
4331     invalid:
4332       printf (gettext ("%*s[%4" PRIuMAX "] %s  <TRUNCATED>\n"),
4333               indent, "", (uintmax_t) offset, op_name);
4334       break;
4335     }
4336 }
4337
4338
4339 struct listptr
4340 {
4341   Dwarf_Off offset:(64 - 3);
4342   bool addr64:1;
4343   bool dwarf64:1;
4344   bool warned:1;
4345   struct Dwarf_CU *cu;
4346 };
4347
4348 #define listptr_offset_size(p)  ((p)->dwarf64 ? 8 : 4)
4349 #define listptr_address_size(p) ((p)->addr64 ? 8 : 4)
4350
4351 static Dwarf_Addr
4352 listptr_base (struct listptr *p)
4353 {
4354   Dwarf_Addr base;
4355   Dwarf_Die cu = CUDIE (p->cu);
4356   /* Find the base address of the compilation unit.  It will normally
4357      be specified by DW_AT_low_pc.  In DWARF-3 draft 4, the base
4358      address could be overridden by DW_AT_entry_pc.  It's been
4359      removed, but GCC emits DW_AT_entry_pc and not DW_AT_lowpc for
4360      compilation units with discontinuous ranges.  */
4361   if (unlikely (dwarf_lowpc (&cu, &base) != 0))
4362     {
4363       Dwarf_Attribute attr_mem;
4364       if (dwarf_formaddr (dwarf_attr (&cu, DW_AT_entry_pc, &attr_mem),
4365                           &base) != 0)
4366         base = 0;
4367     }
4368   return base;
4369 }
4370
4371 static int
4372 compare_listptr (const void *a, const void *b, void *arg)
4373 {
4374   const char *name = arg;
4375   struct listptr *p1 = (void *) a;
4376   struct listptr *p2 = (void *) b;
4377
4378   if (p1->offset < p2->offset)
4379     return -1;
4380   if (p1->offset > p2->offset)
4381     return 1;
4382
4383   if (!p1->warned && !p2->warned)
4384     {
4385       if (p1->addr64 != p2->addr64)
4386         {
4387           p1->warned = p2->warned = true;
4388           error (0, 0,
4389                  gettext ("%s %#" PRIx64 " used with different address sizes"),
4390                  name, (uint64_t) p1->offset);
4391         }
4392       if (p1->dwarf64 != p2->dwarf64)
4393         {
4394           p1->warned = p2->warned = true;
4395           error (0, 0,
4396                  gettext ("%s %#" PRIx64 " used with different offset sizes"),
4397                  name, (uint64_t) p1->offset);
4398         }
4399       if (listptr_base (p1) != listptr_base (p2))
4400         {
4401           p1->warned = p2->warned = true;
4402           error (0, 0,
4403                  gettext ("%s %#" PRIx64 " used with different base addresses"),
4404                  name, (uint64_t) p1->offset);
4405         }
4406     }
4407
4408   return 0;
4409 }
4410
4411 struct listptr_table
4412 {
4413   size_t n;
4414   size_t alloc;
4415   struct listptr *table;
4416 };
4417
4418 static struct listptr_table known_loclistptr;
4419 static struct listptr_table known_rangelistptr;
4420
4421 static void
4422 reset_listptr (struct listptr_table *table)
4423 {
4424   free (table->table);
4425   table->table = NULL;
4426   table->n = table->alloc = 0;
4427 }
4428
4429 /* Returns false if offset doesn't fit.  See struct listptr.  */
4430 static bool
4431 notice_listptr (enum section_e section, struct listptr_table *table,
4432                 uint_fast8_t address_size, uint_fast8_t offset_size,
4433                 struct Dwarf_CU *cu, Dwarf_Off offset)
4434 {
4435   if (print_debug_sections & section)
4436     {
4437       if (table->n == table->alloc)
4438         {
4439           if (table->alloc == 0)
4440             table->alloc = 128;
4441           else
4442             table->alloc *= 2;
4443           table->table = xrealloc (table->table,
4444                                    table->alloc * sizeof table->table[0]);
4445         }
4446
4447       struct listptr *p = &table->table[table->n++];
4448
4449       *p = (struct listptr)
4450         {
4451           .addr64 = address_size == 8,
4452           .dwarf64 = offset_size == 8,
4453           .offset = offset,
4454           .cu = cu
4455         };
4456
4457       if (p->offset != offset)
4458         {
4459           table->n--;
4460           return false;
4461         }
4462     }
4463   return true;
4464 }
4465
4466 static void
4467 sort_listptr (struct listptr_table *table, const char *name)
4468 {
4469   if (table->n > 0)
4470     qsort_r (table->table, table->n, sizeof table->table[0],
4471              &compare_listptr, (void *) name);
4472 }
4473
4474 static bool
4475 skip_listptr_hole (struct listptr_table *table, size_t *idxp,
4476                    uint_fast8_t *address_sizep, uint_fast8_t *offset_sizep,
4477                    Dwarf_Addr *base, struct Dwarf_CU **cu, ptrdiff_t offset,
4478                    unsigned char **readp, unsigned char *endp)
4479 {
4480   if (table->n == 0)
4481     return false;
4482
4483   while (*idxp < table->n && table->table[*idxp].offset < (Dwarf_Off) offset)
4484     ++*idxp;
4485
4486   struct listptr *p = &table->table[*idxp];
4487
4488   if (*idxp == table->n
4489       || p->offset >= (Dwarf_Off) (endp - *readp + offset))
4490     {
4491       *readp = endp;
4492       printf (gettext (" [%6tx]  <UNUSED GARBAGE IN REST OF SECTION>\n"),
4493               offset);
4494       return true;
4495     }
4496
4497   if (p->offset != (Dwarf_Off) offset)
4498     {
4499       *readp += p->offset - offset;
4500       printf (gettext (" [%6tx]  <UNUSED GARBAGE> ... %" PRIu64 " bytes ...\n"),
4501               offset, (Dwarf_Off) p->offset - offset);
4502       return true;
4503     }
4504
4505   if (address_sizep != NULL)
4506     *address_sizep = listptr_address_size (p);
4507   if (offset_sizep != NULL)
4508     *offset_sizep = listptr_offset_size (p);
4509   if (base != NULL)
4510     *base = listptr_base (p);
4511   if (cu != NULL)
4512     *cu = p->cu;
4513
4514   return false;
4515 }
4516
4517
4518 static void
4519 print_debug_abbrev_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
4520                             Ebl *ebl, GElf_Ehdr *ehdr,
4521                             Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
4522 {
4523   const size_t sh_size = (dbg->sectiondata[IDX_debug_abbrev] ?
4524                           dbg->sectiondata[IDX_debug_abbrev]->d_size : 0);
4525
4526   printf (gettext ("\nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"
4527                    " [ Code]\n"),
4528           elf_ndxscn (scn), section_name (ebl, ehdr, shdr),
4529           (uint64_t) shdr->sh_offset);
4530
4531   Dwarf_Off offset = 0;
4532   while (offset < sh_size)
4533     {
4534       printf (gettext ("\nAbbreviation section at offset %" PRIu64 ":\n"),
4535               offset);
4536
4537       while (1)
4538         {
4539           size_t length;
4540           Dwarf_Abbrev abbrev;
4541
4542           int res = dwarf_offabbrev (dbg, offset, &length, &abbrev);
4543           if (res != 0)
4544             {
4545               if (unlikely (res < 0))
4546                 {
4547                   printf (gettext ("\
4548  *** error while reading abbreviation: %s\n"),
4549                           dwarf_errmsg (-1));
4550                   return;
4551                 }
4552
4553               /* This is the NUL byte at the end of the section.  */
4554               ++offset;
4555               break;
4556             }
4557
4558           /* We know these calls can never fail.  */
4559           unsigned int code = dwarf_getabbrevcode (&abbrev);
4560           unsigned int tag = dwarf_getabbrevtag (&abbrev);
4561           int has_children = dwarf_abbrevhaschildren (&abbrev);
4562
4563           printf (gettext (" [%5u] offset: %" PRId64
4564                            ", children: %s, tag: %s\n"),
4565                   code, (int64_t) offset,
4566                   has_children ? gettext ("yes") : gettext ("no"),
4567                   dwarf_tag_name (tag));
4568
4569           size_t cnt = 0;
4570           unsigned int name;
4571           unsigned int form;
4572           Dwarf_Off enoffset;
4573           while (dwarf_getabbrevattr (&abbrev, cnt,
4574                                       &name, &form, &enoffset) == 0)
4575             {
4576               printf ("          attr: %s, form: %s, offset: %#" PRIx64 "\n",
4577                       dwarf_attr_name (name), dwarf_form_name (form),
4578                       (uint64_t) enoffset);
4579
4580               ++cnt;
4581             }
4582
4583           offset += length;
4584         }
4585     }
4586 }
4587
4588
4589 /* Print content of DWARF .debug_aranges section.  We fortunately do
4590    not have to know a bit about the structure of the section, libdwarf
4591    takes care of it.  */
4592 static void
4593 print_decoded_aranges_section (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn,
4594                                GElf_Shdr *shdr, Dwarf *dbg)
4595 {
4596   Dwarf_Aranges *aranges;
4597   size_t cnt;
4598   if (unlikely (dwarf_getaranges (dbg, &aranges, &cnt) != 0))
4599     {
4600       error (0, 0, gettext ("cannot get .debug_aranges content: %s"),
4601              dwarf_errmsg (-1));
4602       return;
4603     }
4604
4605   GElf_Shdr glink_mem;
4606   GElf_Shdr *glink;
4607   glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link), &glink_mem);
4608   if (glink == NULL)
4609     {
4610       error (0, 0, gettext ("invalid sh_link value in section %Zu"),
4611              elf_ndxscn (scn));
4612       return;
4613     }
4614
4615   printf (ngettext ("\
4616 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 " contains %zu entry:\n",
4617                     "\
4618 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 " contains %zu entries:\n",
4619                     cnt),
4620           elf_ndxscn (scn), section_name (ebl, ehdr, shdr),
4621           (uint64_t) shdr->sh_offset, cnt);
4622
4623   /* Compute floor(log16(cnt)).  */
4624   size_t tmp = cnt;
4625   int digits = 1;
4626   while (tmp >= 16)
4627     {
4628       ++digits;
4629       tmp >>= 4;
4630     }
4631
4632   for (size_t n = 0; n < cnt; ++n)
4633     {
4634       Dwarf_Arange *runp = dwarf_onearange (aranges, n);
4635       if (unlikely (runp == NULL))
4636         {
4637           printf ("cannot get arange %zu: %s\n", n, dwarf_errmsg (-1));
4638           return;
4639         }
4640
4641       Dwarf_Addr start;
4642       Dwarf_Word length;
4643       Dwarf_Off offset;
4644
4645       if (unlikely (dwarf_getarangeinfo (runp, &start, &length, &offset) != 0))
4646         printf (gettext (" [%*zu] ???\n"), digits, n);
4647       else
4648         printf (gettext (" [%*zu] start: %0#*" PRIx64
4649                          ", length: %5" PRIu64 ", CU DIE offset: %6"
4650                          PRId64 "\n"),
4651                 digits, n, ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 10 : 18,
4652                 (uint64_t) start, (uint64_t) length, (int64_t) offset);
4653     }
4654 }
4655
4656
4657 /* Print content of DWARF .debug_aranges section.  */
4658 static void
4659 print_debug_aranges_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
4660                              Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn,
4661                              GElf_Shdr *shdr, Dwarf *dbg)
4662 {
4663   if (decodedaranges)
4664     {
4665       print_decoded_aranges_section (ebl, ehdr, scn, shdr, dbg);
4666       return;
4667     }
4668
4669   Elf_Data *data = dbg->sectiondata[IDX_debug_aranges];
4670
4671   if (unlikely (data == NULL))
4672     {
4673       error (0, 0, gettext ("cannot get .debug_aranges content: %s"),
4674              elf_errmsg (-1));
4675       return;
4676     }
4677
4678   printf (gettext ("\
4679 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
4680           elf_ndxscn (scn), section_name (ebl, ehdr, shdr),
4681           (uint64_t) shdr->sh_offset);
4682
4683   const unsigned char *readp = data->d_buf;
4684   const unsigned char *readendp = readp + data->d_size;
4685
4686   while (readp < readendp)
4687     {
4688       const unsigned char *hdrstart = readp;
4689       size_t start_offset = hdrstart - (const unsigned char *) data->d_buf;
4690
4691       printf (gettext ("\nTable at offset %Zu:\n"), start_offset);
4692       if (readp + 4 > readendp)
4693         {
4694         invalid_data:
4695           error (0, 0, gettext ("invalid data in section [%zu] '%s'"),
4696                  elf_ndxscn (scn), section_name (ebl, ehdr, shdr));
4697           return;
4698         }
4699
4700       Dwarf_Word length = read_4ubyte_unaligned_inc (dbg, readp);
4701       unsigned int length_bytes = 4;
4702       if (length == DWARF3_LENGTH_64_BIT)
4703         {
4704           if (readp + 8 > readendp)
4705             goto invalid_data;
4706           length = read_8ubyte_unaligned_inc (dbg, readp);
4707           length_bytes = 8;
4708         }
4709
4710       const unsigned char *nexthdr = readp + length;
4711       printf (gettext ("\n Length:        %6" PRIu64 "\n"),
4712               (uint64_t) length);
4713
4714       if (unlikely ((ptrdiff_t) length > readendp - readp))
4715         goto invalid_data;
4716
4717       if (length == 0)
4718         continue;
4719
4720       if (readp + 2 > readendp)
4721         goto invalid_data;
4722       uint_fast16_t version = read_2ubyte_unaligned_inc (dbg, readp);
4723       printf (gettext (" DWARF version: %6" PRIuFAST16 "\n"),
4724               version);
4725       if (version != 2)
4726         {
4727           error (0, 0, gettext ("unsupported aranges version"));
4728           goto next_table;
4729         }
4730
4731       Dwarf_Word offset;
4732       if (readp + length_bytes > readendp)
4733         goto invalid_data;
4734       if (length_bytes == 8)
4735         offset = read_8ubyte_unaligned_inc (dbg, readp);
4736       else
4737         offset = read_4ubyte_unaligned_inc (dbg, readp);
4738       printf (gettext (" CU offset:     %6" PRIx64 "\n"),
4739               (uint64_t) offset);
4740
4741       if (readp + 1 > readendp)
4742         goto invalid_data;
4743       unsigned int address_size = *readp++;
4744       printf (gettext (" Address size:  %6" PRIu64 "\n"),
4745               (uint64_t) address_size);
4746       if (address_size != 4 && address_size != 8)
4747         {
4748           error (0, 0, gettext ("unsupported address size"));
4749           goto next_table;
4750         }
4751
4752       unsigned int segment_size = *readp++;
4753       printf (gettext (" Segment size:  %6" PRIu64 "\n\n"),
4754               (uint64_t) segment_size);
4755       if (segment_size != 0 && segment_size != 4 && segment_size != 8)
4756         {
4757           error (0, 0, gettext ("unsupported segment size"));
4758           goto next_table;
4759         }
4760
4761       /* Round the address to the next multiple of 2*address_size.  */
4762       readp += ((2 * address_size - ((readp - hdrstart) % (2 * address_size)))
4763                 % (2 * address_size));
4764
4765       while (readp < nexthdr)
4766         {
4767           Dwarf_Word range_address;
4768           Dwarf_Word range_length;
4769           Dwarf_Word segment = 0;
4770           if (readp + 2 * address_size + segment_size > readendp)
4771             goto invalid_data;
4772           if (address_size == 4)
4773             {
4774               range_address = read_4ubyte_unaligned_inc (dbg, readp);
4775               range_length = read_4ubyte_unaligned_inc (dbg, readp);
4776             }
4777           else
4778             {
4779               range_address = read_8ubyte_unaligned_inc (dbg, readp);
4780               range_length = read_8ubyte_unaligned_inc (dbg, readp);
4781             }
4782
4783           if (segment_size == 4)
4784             segment = read_4ubyte_unaligned_inc (dbg, readp);
4785           else if (segment_size == 8)
4786             segment = read_8ubyte_unaligned_inc (dbg, readp);
4787
4788           if (range_address == 0 && range_length == 0 && segment == 0)
4789             break;
4790
4791           char *b = format_dwarf_addr (dwflmod, address_size, range_address,
4792                                        range_address);
4793           char *e = format_dwarf_addr (dwflmod, address_size,
4794                                        range_address + range_length - 1,
4795                                        range_length);
4796           if (segment_size != 0)
4797             printf (gettext ("   %s..%s (%" PRIx64 ")\n"), b, e,
4798                     (uint64_t) segment);
4799           else
4800             printf (gettext ("   %s..%s\n"), b, e);
4801           free (b);
4802           free (e);
4803         }
4804
4805     next_table:
4806       if (readp != nexthdr)
4807         {
4808           size_t padding = nexthdr - readp;
4809           printf (gettext ("   %Zu padding bytes\n"), padding);
4810           readp = nexthdr;
4811         }
4812     }
4813 }
4814
4815
4816 /* Print content of DWARF .debug_ranges section.  */
4817 static void
4818 print_debug_ranges_section (Dwfl_Module *dwflmod,
4819                             Ebl *ebl, GElf_Ehdr *ehdr,
4820                             Elf_Scn *scn, GElf_Shdr *shdr,
4821                             Dwarf *dbg)
4822 {
4823   Elf_Data *data = dbg->sectiondata[IDX_debug_ranges];
4824
4825   if (unlikely (data == NULL))
4826     {
4827       error (0, 0, gettext ("cannot get .debug_ranges content: %s"),
4828              elf_errmsg (-1));
4829       return;
4830     }
4831
4832   printf (gettext ("\
4833 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
4834           elf_ndxscn (scn), section_name (ebl, ehdr, shdr),
4835           (uint64_t) shdr->sh_offset);
4836
4837   sort_listptr (&known_rangelistptr, "rangelistptr");
4838   size_t listptr_idx = 0;
4839
4840   uint_fast8_t address_size = ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
4841
4842   bool first = true;
4843   Dwarf_Addr base = 0;
4844   unsigned char *const endp = (unsigned char *) data->d_buf + data->d_size;
4845   unsigned char *readp = data->d_buf;
4846   while (readp < endp)
4847     {
4848       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
4849
4850       if (first && skip_listptr_hole (&known_rangelistptr, &listptr_idx,
4851                                       &address_size, NULL, &base, NULL,
4852                                       offset, &readp, endp))
4853         continue;
4854
4855       if (unlikely (data->d_size - offset < (size_t) address_size * 2))
4856         {
4857           printf (gettext (" [%6tx]  <INVALID DATA>\n"), offset);
4858           break;
4859         }
4860
4861       Dwarf_Addr begin;
4862       Dwarf_Addr end;
4863       if (address_size == 8)
4864         {
4865           begin = read_8ubyte_unaligned_inc (dbg, readp);
4866           end = read_8ubyte_unaligned_inc (dbg, readp);
4867         }
4868       else
4869         {
4870           begin = read_4ubyte_unaligned_inc (dbg, readp);
4871           end = read_4ubyte_unaligned_inc (dbg, readp);
4872           if (begin == (Dwarf_Addr) (uint32_t) -1)
4873             begin = (Dwarf_Addr) -1l;
4874         }
4875
4876       if (begin == (Dwarf_Addr) -1l) /* Base address entry.  */
4877         {
4878           char *b = format_dwarf_addr (dwflmod, address_size, end, end);
4879           printf (gettext (" [%6tx]  base address %s\n"), offset, b);
4880           free (b);
4881           base = end;
4882         }
4883       else if (begin == 0 && end == 0) /* End of list entry.  */
4884         {
4885           if (first)
4886             printf (gettext (" [%6tx]  empty list\n"), offset);
4887           first = true;
4888         }
4889       else
4890         {
4891           char *b = format_dwarf_addr (dwflmod, address_size, base + begin,
4892                                        begin);
4893           char *e = format_dwarf_addr (dwflmod, address_size, base + end,
4894                                        end);
4895           /* We have an address range entry.  */
4896           if (first)            /* First address range entry in a list.  */
4897             printf (gettext (" [%6tx]  %s..%s\n"), offset, b, e);
4898           else
4899             printf (gettext ("           %s..%s\n"), b, e);
4900           free (b);
4901           free (e);
4902
4903           first = false;
4904         }
4905     }
4906 }
4907
4908 #define REGNAMESZ 16
4909 static const char *
4910 register_info (Ebl *ebl, unsigned int regno, const Ebl_Register_Location *loc,
4911                char name[REGNAMESZ], int *bits, int *type)
4912 {
4913   const char *set;
4914   const char *pfx;
4915   int ignore;
4916   ssize_t n = ebl_register_info (ebl, regno, name, REGNAMESZ, &pfx, &set,
4917                                  bits ?: &ignore, type ?: &ignore);
4918   if (n <= 0)
4919     {
4920       if (loc != NULL)
4921         snprintf (name, REGNAMESZ, "reg%u", loc->regno);
4922       else
4923         snprintf (name, REGNAMESZ, "??? 0x%x", regno);
4924       if (bits != NULL)
4925         *bits = loc != NULL ? loc->bits : 0;
4926       if (type != NULL)
4927         *type = DW_ATE_unsigned;
4928       set = "??? unrecognized";
4929     }
4930   else
4931     {
4932       if (bits != NULL && *bits <= 0)
4933         *bits = loc != NULL ? loc->bits : 0;
4934       if (type != NULL && *type == DW_ATE_void)
4935         *type = DW_ATE_unsigned;
4936
4937     }
4938   return set;
4939 }
4940
4941 static void
4942 print_cfa_program (const unsigned char *readp, const unsigned char *const endp,
4943                    Dwarf_Word vma_base, unsigned int code_align,
4944                    int data_align,
4945                    unsigned int version, unsigned int ptr_size,
4946                    Dwfl_Module *dwflmod, Ebl *ebl, Dwarf *dbg)
4947 {
4948   char regnamebuf[REGNAMESZ];
4949   const char *regname (unsigned int regno)
4950   {
4951     register_info (ebl, regno, NULL, regnamebuf, NULL, NULL);
4952     return regnamebuf;
4953   }
4954
4955   puts ("\n   Program:");
4956   Dwarf_Word pc = vma_base;
4957   while (readp < endp)
4958     {
4959       unsigned int opcode = *readp++;
4960
4961       if (opcode < DW_CFA_advance_loc)
4962         /* Extended opcode.  */
4963         switch (opcode)
4964           {
4965             uint64_t op1;
4966             int64_t sop1;
4967             uint64_t op2;
4968             int64_t sop2;
4969
4970           case DW_CFA_nop:
4971             puts ("     nop");
4972             break;
4973           case DW_CFA_set_loc:
4974             get_uleb128 (op1, readp, endp);
4975             op1 += vma_base;
4976             printf ("     set_loc %" PRIu64 "\n", op1 * code_align);
4977             break;
4978           case DW_CFA_advance_loc1:
4979             printf ("     advance_loc1 %u to %#" PRIx64 "\n",
4980                     *readp, pc += *readp * code_align);
4981             ++readp;
4982             break;
4983           case DW_CFA_advance_loc2:
4984             if ((uint64_t) (endp - readp) < 2)
4985               goto invalid;
4986             op1 = read_2ubyte_unaligned_inc (dbg, readp);
4987             printf ("     advance_loc2 %" PRIu64 " to %#" PRIx64 "\n",
4988                     op1, pc += op1 * code_align);
4989             break;
4990           case DW_CFA_advance_loc4:
4991             if ((uint64_t) (endp - readp) < 4)
4992               goto invalid;
4993             op1 = read_4ubyte_unaligned_inc (dbg, readp);
4994             printf ("     advance_loc4 %" PRIu64 " to %#" PRIx64 "\n",
4995                     op1, pc += op1 * code_align);
4996             break;
4997           case DW_CFA_offset_extended:
4998             get_uleb128 (op1, readp, endp);
4999             if ((uint64_t) (endp - readp) < 1)
5000               goto invalid;
5001             get_uleb128 (op2, readp, endp);
5002             printf ("     offset_extended r%" PRIu64 " (%s) at cfa%+" PRId64
5003                     "\n",
5004                     op1, regname (op1), op2 * data_align);
5005             break;
5006           case DW_CFA_restore_extended:
5007             get_uleb128 (op1, readp, endp);
5008             printf ("     restore_extended r%" PRIu64 " (%s)\n",
5009                     op1, regname (op1));
5010             break;
5011           case DW_CFA_undefined:
5012             get_uleb128 (op1, readp, endp);
5013             printf ("     undefined r%" PRIu64 " (%s)\n", op1, regname (op1));
5014             break;
5015           case DW_CFA_same_value:
5016             get_uleb128 (op1, readp, endp);
5017             printf ("     same_value r%" PRIu64 " (%s)\n", op1, regname (op1));
5018             break;
5019           case DW_CFA_register:
5020             get_uleb128 (op1, readp, endp);
5021             if ((uint64_t) (endp - readp) < 1)
5022               goto invalid;
5023             get_uleb128 (op2, readp, endp);
5024             printf ("     register r%" PRIu64 " (%s) in r%" PRIu64 " (%s)\n",
5025                     op1, regname (op1), op2, regname (op2));
5026             break;
5027           case DW_CFA_remember_state:
5028             puts ("     remember_state");
5029             break;
5030           case DW_CFA_restore_state:
5031             puts ("     restore_state");
5032             break;
5033           case DW_CFA_def_cfa:
5034             get_uleb128 (op1, readp, endp);
5035             if ((uint64_t) (endp - readp) < 1)
5036               goto invalid;
5037             get_uleb128 (op2, readp, endp);
5038             printf ("     def_cfa r%" PRIu64 " (%s) at offset %" PRIu64 "\n",
5039                     op1, regname (op1), op2);
5040             break;
5041           case DW_CFA_def_cfa_register:
5042             get_uleb128 (op1, readp, endp);
5043             printf ("     def_cfa_register r%" PRIu64 " (%s)\n",
5044                     op1, regname (op1));
5045             break;
5046           case DW_CFA_def_cfa_offset:
5047             get_uleb128 (op1, readp, endp);
5048             printf ("     def_cfa_offset %" PRIu64 "\n", op1);
5049             break;
5050           case DW_CFA_def_cfa_expression:
5051             get_uleb128 (op1, readp, endp);     /* Length of DW_FORM_block.  */
5052             printf ("     def_cfa_expression %" PRIu64 "\n", op1);
5053             if ((uint64_t) (endp - readp) < op1)
5054               {
5055             invalid:
5056                 fputs (gettext ("         <INVALID DATA>\n"), stdout);
5057                 return;
5058               }
5059             print_ops (dwflmod, dbg, 10, 10, version, ptr_size, 0, NULL,
5060                        op1, readp);
5061             readp += op1;
5062             break;
5063           case DW_CFA_expression:
5064             get_uleb128 (op1, readp, endp);
5065             if ((uint64_t) (endp - readp) < 1)
5066               goto invalid;
5067             get_uleb128 (op2, readp, endp);     /* Length of DW_FORM_block.  */
5068             printf ("     expression r%" PRIu64 " (%s) \n",
5069                     op1, regname (op1));
5070             if ((uint64_t) (endp - readp) < op2)
5071               goto invalid;
5072             print_ops (dwflmod, dbg, 10, 10, version, ptr_size, 0, NULL,
5073                        op2, readp);
5074             readp += op2;
5075             break;
5076           case DW_CFA_offset_extended_sf:
5077             get_uleb128 (op1, readp, endp);
5078             if ((uint64_t) (endp - readp) < 1)
5079               goto invalid;
5080             get_sleb128 (sop2, readp, endp);
5081             printf ("     offset_extended_sf r%" PRIu64 " (%s) at cfa%+"
5082                     PRId64 "\n",
5083                     op1, regname (op1), sop2 * data_align);
5084             break;
5085           case DW_CFA_def_cfa_sf:
5086             get_uleb128 (op1, readp, endp);
5087             if ((uint64_t) (endp - readp) < 1)
5088               goto invalid;
5089             get_sleb128 (sop2, readp, endp);
5090             printf ("     def_cfa_sf r%" PRIu64 " (%s) at offset %" PRId64 "\n",
5091                     op1, regname (op1), sop2 * data_align);
5092             break;
5093           case DW_CFA_def_cfa_offset_sf:
5094             get_sleb128 (sop1, readp, endp);
5095             printf ("     def_cfa_offset_sf %" PRId64 "\n", sop1 * data_align);
5096             break;
5097           case DW_CFA_val_offset:
5098             // XXX overflow check
5099             get_uleb128 (op1, readp, endp);
5100             if ((uint64_t) (endp - readp) < 1)
5101               goto invalid;
5102             get_uleb128 (op2, readp, endp);
5103             printf ("     val_offset %" PRIu64 " at offset %" PRIu64 "\n",
5104                     op1, op2 * data_align);
5105             break;
5106           case DW_CFA_val_offset_sf:
5107             // XXX overflow check
5108             get_uleb128 (op1, readp, endp);
5109             if ((uint64_t) (endp - readp) < 1)
5110               goto invalid;
5111             get_sleb128 (sop2, readp, endp);
5112             printf ("     val_offset_sf %" PRIu64 " at offset %" PRId64 "\n",
5113                     op1, sop2 * data_align);
5114             break;
5115           case DW_CFA_val_expression:
5116             get_uleb128 (op1, readp, endp);
5117             if ((uint64_t) (endp - readp) < 1)
5118               goto invalid;
5119             get_uleb128 (op2, readp, endp);     /* Length of DW_FORM_block.  */
5120             printf ("     val_expression r%" PRIu64 " (%s)\n",
5121                     op1, regname (op1));
5122             if ((uint64_t) (endp - readp) < op2)
5123               goto invalid;
5124             print_ops (dwflmod, dbg, 10, 10, version, ptr_size, 0,
5125                        NULL, op2, readp);
5126             readp += op2;
5127             break;
5128           case DW_CFA_MIPS_advance_loc8:
5129             if ((uint64_t) (endp - readp) < 8)
5130               goto invalid;
5131             op1 = read_8ubyte_unaligned_inc (dbg, readp);
5132             printf ("     MIPS_advance_loc8 %" PRIu64 " to %#" PRIx64 "\n",
5133                     op1, pc += op1 * code_align);
5134             break;
5135           case DW_CFA_GNU_window_save:
5136             puts ("     GNU_window_save");
5137             break;
5138           case DW_CFA_GNU_args_size:
5139             get_uleb128 (op1, readp, endp);
5140             printf ("     args_size %" PRIu64 "\n", op1);
5141             break;
5142           default:
5143             printf ("     ??? (%u)\n", opcode);
5144             break;
5145           }
5146       else if (opcode < DW_CFA_offset)
5147         printf ("     advance_loc %u to %#" PRIx64 "\n",
5148                 opcode & 0x3f, pc += (opcode & 0x3f) * code_align);
5149       else if (opcode < DW_CFA_restore)
5150         {
5151           uint64_t offset;
5152           get_uleb128 (offset, readp, endp);
5153           printf ("     offset r%u (%s) at cfa%+" PRId64 "\n",
5154                   opcode & 0x3f, regname (opcode & 0x3f), offset * data_align);
5155         }
5156       else
5157         printf ("     restore r%u (%s)\n",
5158                 opcode & 0x3f, regname (opcode & 0x3f));
5159     }
5160 }
5161
5162
5163 static unsigned int
5164 encoded_ptr_size (int encoding, unsigned int ptr_size)
5165 {
5166   switch (encoding & 7)
5167     {
5168     case DW_EH_PE_udata4:
5169       return 4;
5170     case DW_EH_PE_udata8:
5171       return 8;
5172     case 0:
5173       return ptr_size;
5174     }
5175
5176   fprintf (stderr, "Unsupported pointer encoding: %#x, "
5177            "assuming pointer size of %d.\n", encoding, ptr_size);
5178   return ptr_size;
5179 }
5180
5181
5182 static unsigned int
5183 print_encoding (unsigned int val)
5184 {
5185   switch (val & 0xf)
5186     {
5187     case DW_EH_PE_absptr:
5188       fputs ("absptr", stdout);
5189       break;
5190     case DW_EH_PE_uleb128:
5191       fputs ("uleb128", stdout);
5192       break;
5193     case DW_EH_PE_udata2:
5194       fputs ("udata2", stdout);
5195       break;
5196     case DW_EH_PE_udata4:
5197       fputs ("udata4", stdout);
5198       break;
5199     case DW_EH_PE_udata8:
5200       fputs ("udata8", stdout);
5201       break;
5202     case DW_EH_PE_sleb128:
5203       fputs ("sleb128", stdout);
5204       break;
5205     case DW_EH_PE_sdata2:
5206       fputs ("sdata2", stdout);
5207       break;
5208     case DW_EH_PE_sdata4:
5209       fputs ("sdata4", stdout);
5210       break;
5211     case DW_EH_PE_sdata8:
5212       fputs ("sdata8", stdout);
5213       break;
5214     default:
5215       /* We did not use any of the bits after all.  */
5216       return val;
5217     }
5218
5219   return val & ~0xf;
5220 }
5221
5222
5223 static unsigned int
5224 print_relinfo (unsigned int val)
5225 {
5226   switch (val & 0x70)
5227     {
5228     case DW_EH_PE_pcrel:
5229       fputs ("pcrel", stdout);
5230       break;
5231     case DW_EH_PE_textrel:
5232       fputs ("textrel", stdout);
5233       break;
5234     case DW_EH_PE_datarel:
5235       fputs ("datarel", stdout);
5236       break;
5237     case DW_EH_PE_funcrel:
5238       fputs ("funcrel", stdout);
5239       break;
5240     case DW_EH_PE_aligned:
5241       fputs ("aligned", stdout);
5242       break;
5243     default:
5244       return val;
5245     }
5246
5247   return val & ~0x70;
5248 }
5249
5250
5251 static void
5252 print_encoding_base (const char *pfx, unsigned int fde_encoding)
5253 {
5254   printf ("(%s", pfx);
5255
5256   if (fde_encoding == DW_EH_PE_omit)
5257     puts ("omit)");
5258   else
5259     {
5260       unsigned int w = fde_encoding;
5261
5262       w = print_encoding (w);
5263
5264       if (w & 0x70)
5265         {
5266           if (w != fde_encoding)
5267             fputc_unlocked (' ', stdout);
5268
5269           w = print_relinfo (w);
5270         }
5271
5272       if (w != 0)
5273         printf ("%s%x", w != fde_encoding ? " " : "", w);
5274
5275       puts (")");
5276     }
5277 }
5278
5279
5280 static const unsigned char *
5281 read_encoded (unsigned int encoding, const unsigned char *readp,
5282               const unsigned char *const endp, uint64_t *res, Dwarf *dbg)
5283 {
5284   if ((encoding & 0xf) == DW_EH_PE_absptr)
5285     encoding = gelf_getclass (dbg->elf) == ELFCLASS32
5286       ? DW_EH_PE_udata4 : DW_EH_PE_udata8;
5287
5288   switch (encoding & 0xf)
5289     {
5290     case DW_EH_PE_uleb128:
5291       get_uleb128 (*res, readp, endp);
5292       break;
5293     case DW_EH_PE_sleb128:
5294       get_sleb128 (*res, readp, endp);
5295       break;
5296     case DW_EH_PE_udata2:
5297       if (readp + 2 > endp)
5298         goto invalid;
5299       *res = read_2ubyte_unaligned_inc (dbg, readp);
5300       break;
5301     case DW_EH_PE_udata4:
5302       if (readp + 4 > endp)
5303         goto invalid;
5304       *res = read_4ubyte_unaligned_inc (dbg, readp);
5305       break;
5306     case DW_EH_PE_udata8:
5307       if (readp + 8 > endp)
5308         goto invalid;
5309       *res = read_8ubyte_unaligned_inc (dbg, readp);
5310       break;
5311     case DW_EH_PE_sdata2:
5312       if (readp + 2 > endp)
5313         goto invalid;
5314       *res = read_2sbyte_unaligned_inc (dbg, readp);
5315       break;
5316     case DW_EH_PE_sdata4:
5317       if (readp + 4 > endp)
5318         goto invalid;
5319       *res = read_4sbyte_unaligned_inc (dbg, readp);
5320       break;
5321     case DW_EH_PE_sdata8:
5322       if (readp + 8 > endp)
5323         goto invalid;
5324       *res = read_8sbyte_unaligned_inc (dbg, readp);
5325       break;
5326     default:
5327     invalid:
5328       error (1, 0,
5329              gettext ("invalid encoding"));
5330     }
5331
5332   return readp;
5333 }
5334
5335
5336 static void
5337 print_debug_frame_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
5338                            Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
5339 {
5340   size_t shstrndx;
5341   /* We know this call will succeed since it did in the caller.  */
5342   (void) elf_getshdrstrndx (ebl->elf, &shstrndx);
5343   const char *scnname = elf_strptr (ebl->elf, shstrndx, shdr->sh_name);
5344
5345   /* Needed if we find PC-relative addresses.  */
5346   GElf_Addr bias;
5347   if (dwfl_module_getelf (dwflmod, &bias) == NULL)
5348     {
5349       error (0, 0, gettext ("cannot get ELF: %s"), dwfl_errmsg (-1));
5350       return;
5351     }
5352
5353   bool is_eh_frame = strcmp (scnname, ".eh_frame") == 0;
5354   Elf_Data *data = (is_eh_frame
5355                     ? elf_rawdata (scn, NULL)
5356                     : dbg->sectiondata[IDX_debug_frame]);
5357
5358   if (unlikely (data == NULL))
5359     {
5360       error (0, 0, gettext ("cannot get %s content: %s"),
5361              scnname, elf_errmsg (-1));
5362       return;
5363     }
5364
5365   if (is_eh_frame)
5366     printf (gettext ("\
5367 \nCall frame information section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
5368             elf_ndxscn (scn), scnname, (uint64_t) shdr->sh_offset);
5369   else
5370     printf (gettext ("\
5371 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
5372             elf_ndxscn (scn), scnname, (uint64_t) shdr->sh_offset);
5373
5374   struct cieinfo
5375   {
5376     ptrdiff_t cie_offset;
5377     const char *augmentation;
5378     unsigned int code_alignment_factor;
5379     unsigned int data_alignment_factor;
5380     uint8_t address_size;
5381     uint8_t fde_encoding;
5382     uint8_t lsda_encoding;
5383     struct cieinfo *next;
5384   } *cies = NULL;
5385
5386   const unsigned char *readp = data->d_buf;
5387   const unsigned char *const dataend = ((unsigned char *) data->d_buf
5388                                         + data->d_size);
5389   while (readp < dataend)
5390     {
5391       if (unlikely (readp + 4 > dataend))
5392         {
5393         invalid_data:
5394           error (0, 0, gettext ("invalid data in section [%zu] '%s'"),
5395                      elf_ndxscn (scn), scnname);
5396               return;
5397         }
5398
5399       /* At the beginning there must be a CIE.  There can be multiple,
5400          hence we test tis in a loop.  */
5401       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
5402
5403       Dwarf_Word unit_length = read_4ubyte_unaligned_inc (dbg, readp);
5404       unsigned int length = 4;
5405       if (unlikely (unit_length == 0xffffffff))
5406         {
5407           if (unlikely (readp + 8 > dataend))
5408             goto invalid_data;
5409
5410           unit_length = read_8ubyte_unaligned_inc (dbg, readp);
5411           length = 8;
5412         }
5413
5414       if (unlikely (unit_length == 0))
5415         {
5416           printf (gettext ("\n [%6tx] Zero terminator\n"), offset);
5417           continue;
5418         }
5419
5420       Dwarf_Word maxsize = dataend - readp;
5421       if (unlikely (unit_length > maxsize))
5422         goto invalid_data;
5423
5424       unsigned int ptr_size = ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
5425
5426       ptrdiff_t start = readp - (unsigned char *) data->d_buf;
5427       const unsigned char *const cieend = readp + unit_length;
5428       if (unlikely (cieend > dataend || readp + 8 > dataend))
5429         goto invalid_data;
5430
5431       Dwarf_Off cie_id;
5432       if (length == 4)
5433         {
5434           cie_id = read_4ubyte_unaligned_inc (dbg, readp);
5435           if (!is_eh_frame && cie_id == DW_CIE_ID_32)
5436             cie_id = DW_CIE_ID_64;
5437         }
5438       else
5439         cie_id = read_8ubyte_unaligned_inc (dbg, readp);
5440
5441       uint_fast8_t version = 2;
5442       unsigned int code_alignment_factor;
5443       int data_alignment_factor;
5444       unsigned int fde_encoding = 0;
5445       unsigned int lsda_encoding = 0;
5446       Dwarf_Word initial_location = 0;
5447       Dwarf_Word vma_base = 0;
5448
5449       if (cie_id == (is_eh_frame ? 0 : DW_CIE_ID_64))
5450         {
5451           version = *readp++;
5452           const char *const augmentation = (const char *) readp;
5453           readp = memchr (readp, '\0', cieend - readp);
5454           if (unlikely (readp == NULL))
5455             goto invalid_data;
5456           ++readp;
5457
5458           uint_fast8_t segment_size = 0;
5459           if (version >= 4)
5460             {
5461               if (cieend - readp < 5)
5462                 goto invalid_data;
5463               ptr_size = *readp++;
5464               segment_size = *readp++;
5465             }
5466
5467           if (cieend - readp < 1)
5468             goto invalid_data;
5469           get_uleb128 (code_alignment_factor, readp, cieend);
5470           if (cieend - readp < 1)
5471             goto invalid_data;
5472           get_sleb128 (data_alignment_factor, readp, cieend);
5473
5474           /* In some variant for unwind data there is another field.  */
5475           if (strcmp (augmentation, "eh") == 0)
5476             readp += ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
5477
5478           unsigned int return_address_register;
5479           if (cieend - readp < 1)
5480             goto invalid_data;
5481           if (unlikely (version == 1))
5482             return_address_register = *readp++;
5483           else
5484             get_uleb128 (return_address_register, readp, cieend);
5485
5486           printf ("\n [%6tx] CIE length=%" PRIu64 "\n"
5487                   "   CIE_id:                   %" PRIu64 "\n"
5488                   "   version:                  %u\n"
5489                   "   augmentation:             \"%s\"\n",
5490                   offset, (uint64_t) unit_length, (uint64_t) cie_id,
5491                   version, augmentation);
5492           if (version >= 4)
5493             printf ("   address_size:             %u\n"
5494                     "   segment_size:             %u\n",
5495                     ptr_size, segment_size);
5496           printf ("   code_alignment_factor:    %u\n"
5497                   "   data_alignment_factor:    %d\n"
5498                   "   return_address_register:  %u\n",
5499                   code_alignment_factor,
5500                   data_alignment_factor, return_address_register);
5501
5502           if (augmentation[0] == 'z')
5503             {
5504               unsigned int augmentationlen;
5505               get_uleb128 (augmentationlen, readp, cieend);
5506
5507               if (augmentationlen > (size_t) (cieend - readp))
5508                 {
5509                   error (0, 0, gettext ("invalid augmentation length"));
5510                   readp = cieend;
5511                   continue;
5512                 }
5513
5514               const char *hdr = "Augmentation data:";
5515               const char *cp = augmentation + 1;
5516               while (*cp != '\0' && cp < augmentation + augmentationlen + 1)
5517                 {
5518                   printf ("   %-26s%#x ", hdr, *readp);
5519                   hdr = "";
5520
5521                   if (*cp == 'R')
5522                     {
5523                       fde_encoding = *readp++;
5524                       print_encoding_base (gettext ("FDE address encoding: "),
5525                                            fde_encoding);
5526                     }
5527                   else if (*cp == 'L')
5528                     {
5529                       lsda_encoding = *readp++;
5530                       print_encoding_base (gettext ("LSDA pointer encoding: "),
5531                                            lsda_encoding);
5532                     }
5533                   else if (*cp == 'P')
5534                     {
5535                       /* Personality.  This field usually has a relocation
5536                          attached pointing to __gcc_personality_v0.  */
5537                       const unsigned char *startp = readp;
5538                       unsigned int encoding = *readp++;
5539                       uint64_t val = 0;
5540                       readp = read_encoded (encoding, readp,
5541                                             readp - 1 + augmentationlen,
5542                                             &val, dbg);
5543
5544                       while (++startp < readp)
5545                         printf ("%#x ", *startp);
5546
5547                       putchar ('(');
5548                       print_encoding (encoding);
5549                       putchar (' ');
5550                       switch (encoding & 0xf)
5551                         {
5552                         case DW_EH_PE_sleb128:
5553                         case DW_EH_PE_sdata2:
5554                         case DW_EH_PE_sdata4:
5555                           printf ("%" PRId64 ")\n", val);
5556                           break;
5557                         default:
5558                           printf ("%#" PRIx64 ")\n", val);
5559                           break;
5560                         }
5561                     }
5562                   else
5563                     printf ("(%x)\n", *readp++);
5564
5565                   ++cp;
5566                 }
5567             }
5568
5569           if (likely (ptr_size == 4 || ptr_size == 8))
5570             {
5571               struct cieinfo *newp = alloca (sizeof (*newp));
5572               newp->cie_offset = offset;
5573               newp->augmentation = augmentation;
5574               newp->fde_encoding = fde_encoding;
5575               newp->lsda_encoding = lsda_encoding;
5576               newp->address_size = ptr_size;
5577               newp->code_alignment_factor = code_alignment_factor;
5578               newp->data_alignment_factor = data_alignment_factor;
5579               newp->next = cies;
5580               cies = newp;
5581             }
5582         }
5583       else
5584         {
5585           struct cieinfo *cie = cies;
5586           while (cie != NULL)
5587             if (is_eh_frame
5588                 ? start - (ptrdiff_t) cie_id == cie->cie_offset
5589                 : (ptrdiff_t) cie_id == cie->cie_offset)
5590               break;
5591             else
5592               cie = cie->next;
5593           if (unlikely (cie == NULL))
5594             {
5595               puts ("invalid CIE reference in FDE");
5596               return;
5597             }
5598
5599           /* Initialize from CIE data.  */
5600           fde_encoding = cie->fde_encoding;
5601           lsda_encoding = cie->lsda_encoding;
5602           ptr_size = encoded_ptr_size (fde_encoding, cie->address_size);
5603           code_alignment_factor = cie->code_alignment_factor;
5604           data_alignment_factor = cie->data_alignment_factor;
5605
5606           const unsigned char *base = readp;
5607           // XXX There are sometimes relocations for this value
5608           initial_location = read_addr_unaligned_inc (ptr_size, dbg, readp);
5609           Dwarf_Word address_range
5610             = read_addr_unaligned_inc (ptr_size, dbg, readp);
5611
5612           /* pcrel for an FDE address is relative to the runtime
5613              address of the start_address field itself.  Sign extend
5614              if necessary to make sure the calculation is done on the
5615              full 64 bit address even when initial_location only holds
5616              the lower 32 bits.  */
5617           Dwarf_Addr pc_start = initial_location;
5618           if (ptr_size == 4)
5619             pc_start = (uint64_t) (int32_t) pc_start;
5620           if ((fde_encoding & 0x70) == DW_EH_PE_pcrel)
5621             pc_start += ((uint64_t) shdr->sh_addr
5622                          + (base - (const unsigned char *) data->d_buf)
5623                          - bias);
5624
5625           char *a = format_dwarf_addr (dwflmod, cie->address_size,
5626                                        pc_start, initial_location);
5627           printf ("\n [%6tx] FDE length=%" PRIu64 " cie=[%6tx]\n"
5628                   "   CIE_pointer:              %" PRIu64 "\n"
5629                   "   initial_location:         %s",
5630                   offset, (uint64_t) unit_length,
5631                   cie->cie_offset, (uint64_t) cie_id, a);
5632           free (a);
5633           if ((fde_encoding & 0x70) == DW_EH_PE_pcrel)
5634             {
5635               vma_base = (((uint64_t) shdr->sh_offset
5636                            + (base - (const unsigned char *) data->d_buf)
5637                            + (uint64_t) initial_location)
5638                           & (ptr_size == 4
5639                              ? UINT64_C (0xffffffff)
5640                              : UINT64_C (0xffffffffffffffff)));
5641               printf (gettext (" (offset: %#" PRIx64 ")"),
5642                       (uint64_t) vma_base);
5643             }
5644
5645           printf ("\n   address_range:            %#" PRIx64,
5646                   (uint64_t) address_range);
5647           if ((fde_encoding & 0x70) == DW_EH_PE_pcrel)
5648             printf (gettext (" (end offset: %#" PRIx64 ")"),
5649                     ((uint64_t) vma_base + (uint64_t) address_range)
5650                     & (ptr_size == 4
5651                        ? UINT64_C (0xffffffff)
5652                        : UINT64_C (0xffffffffffffffff)));
5653           putchar ('\n');
5654
5655           if (cie->augmentation[0] == 'z')
5656             {
5657               unsigned int augmentationlen;
5658               if (cieend - readp < 1)
5659                 goto invalid_data;
5660               get_uleb128 (augmentationlen, readp, cieend);
5661
5662               if (augmentationlen > (size_t) (cieend - readp))
5663                 {
5664                   error (0, 0, gettext ("invalid augmentation length"));
5665                   readp = cieend;
5666                   continue;
5667                 }
5668
5669               if (augmentationlen > 0)
5670                 {
5671                   const char *hdr = "Augmentation data:";
5672                   const char *cp = cie->augmentation + 1;
5673                   unsigned int u = 0;
5674                   while (*cp != '\0'
5675                          && cp < cie->augmentation + augmentationlen + 1)
5676                     {
5677                       if (*cp == 'L')
5678                         {
5679                           uint64_t lsda_pointer;
5680                           const unsigned char *p
5681                             = read_encoded (lsda_encoding, &readp[u],
5682                                             &readp[augmentationlen],
5683                                             &lsda_pointer, dbg);
5684                           u = p - readp;
5685                           printf (gettext ("\
5686    %-26sLSDA pointer: %#" PRIx64 "\n"),
5687                                   hdr, lsda_pointer);
5688                           hdr = "";
5689                         }
5690                       ++cp;
5691                     }
5692
5693                   while (u < augmentationlen)
5694                     {
5695                       printf ("   %-26s%#x\n", hdr, readp[u++]);
5696                       hdr = "";
5697                     }
5698                 }
5699
5700               readp += augmentationlen;
5701             }
5702         }
5703
5704       /* Handle the initialization instructions.  */
5705       if (ptr_size != 4 && ptr_size !=8)
5706         printf ("invalid CIE pointer size (%u), must be 4 or 8.\n", ptr_size);
5707       else
5708         print_cfa_program (readp, cieend, vma_base, code_alignment_factor,
5709                            data_alignment_factor, version, ptr_size,
5710                            dwflmod, ebl, dbg);
5711       readp = cieend;
5712     }
5713 }
5714
5715
5716 struct attrcb_args
5717 {
5718   Dwfl_Module *dwflmod;
5719   Dwarf *dbg;
5720   Dwarf_Die *die;
5721   int level;
5722   bool silent;
5723   unsigned int version;
5724   unsigned int addrsize;
5725   unsigned int offset_size;
5726   struct Dwarf_CU *cu;
5727 };
5728
5729
5730 static int
5731 attr_callback (Dwarf_Attribute *attrp, void *arg)
5732 {
5733   struct attrcb_args *cbargs = (struct attrcb_args *) arg;
5734   const int level = cbargs->level;
5735
5736   unsigned int attr = dwarf_whatattr (attrp);
5737   if (unlikely (attr == 0))
5738     {
5739       if (!cbargs->silent)
5740         error (0, 0, gettext ("cannot get attribute code: %s"),
5741                dwarf_errmsg (-1));
5742       return DWARF_CB_ABORT;
5743     }
5744
5745   unsigned int form = dwarf_whatform (attrp);
5746   if (unlikely (form == 0))
5747     {
5748       if (!cbargs->silent)
5749         error (0, 0, gettext ("cannot get attribute form: %s"),
5750                dwarf_errmsg (-1));
5751       return DWARF_CB_ABORT;
5752     }
5753
5754   switch (form)
5755     {
5756     case DW_FORM_addr:
5757       if (!cbargs->silent)
5758         {
5759           Dwarf_Addr addr;
5760           if (unlikely (dwarf_formaddr (attrp, &addr) != 0))
5761             {
5762             attrval_out:
5763               if (!cbargs->silent)
5764                 error (0, 0, gettext ("cannot get attribute value: %s"),
5765                        dwarf_errmsg (-1));
5766               return DWARF_CB_ABORT;
5767             }
5768           char *a = format_dwarf_addr (cbargs->dwflmod, cbargs->addrsize,
5769                                        addr, addr);
5770           printf ("           %*s%-20s (%s) %s\n",
5771                   (int) (level * 2), "", dwarf_attr_name (attr),
5772                   dwarf_form_name (form), a);
5773           free (a);
5774         }
5775       break;
5776
5777     case DW_FORM_indirect:
5778     case DW_FORM_strp:
5779     case DW_FORM_string:
5780     case DW_FORM_GNU_strp_alt:
5781       if (cbargs->silent)
5782         break;
5783       const char *str = dwarf_formstring (attrp);
5784       if (unlikely (str == NULL))
5785         goto attrval_out;
5786       printf ("           %*s%-20s (%s) \"%s\"\n",
5787               (int) (level * 2), "", dwarf_attr_name (attr),
5788               dwarf_form_name (form), str);
5789       break;
5790
5791     case DW_FORM_ref_addr:
5792     case DW_FORM_ref_udata:
5793     case DW_FORM_ref8:
5794     case DW_FORM_ref4:
5795     case DW_FORM_ref2:
5796     case DW_FORM_ref1:
5797     case DW_FORM_GNU_ref_alt:
5798       if (cbargs->silent)
5799         break;
5800       Dwarf_Die ref;
5801       if (unlikely (dwarf_formref_die (attrp, &ref) == NULL))
5802         goto attrval_out;
5803
5804       printf ("           %*s%-20s (%s) [%6" PRIxMAX "]\n",
5805               (int) (level * 2), "", dwarf_attr_name (attr),
5806               dwarf_form_name (form), (uintmax_t) dwarf_dieoffset (&ref));
5807       break;
5808
5809     case DW_FORM_ref_sig8:
5810       if (cbargs->silent)
5811         break;
5812       printf ("           %*s%-20s (%s) {%6" PRIx64 "}\n",
5813               (int) (level * 2), "", dwarf_attr_name (attr),
5814               dwarf_form_name (form),
5815               (uint64_t) read_8ubyte_unaligned (attrp->cu->dbg, attrp->valp));
5816       break;
5817
5818     case DW_FORM_sec_offset:
5819     case DW_FORM_udata:
5820     case DW_FORM_sdata:
5821     case DW_FORM_data8:
5822     case DW_FORM_data4:
5823     case DW_FORM_data2:
5824     case DW_FORM_data1:;
5825       Dwarf_Word num;
5826       if (unlikely (dwarf_formudata (attrp, &num) != 0))
5827         goto attrval_out;
5828
5829       const char *valuestr = NULL;
5830       switch (attr)
5831         {
5832           /* This case can take either a constant or a loclistptr.  */
5833         case DW_AT_data_member_location:
5834           if (form != DW_FORM_sec_offset
5835               && (cbargs->version >= 4
5836                   || (form != DW_FORM_data4 && form != DW_FORM_data8)))
5837             {
5838               if (!cbargs->silent)
5839                 printf ("           %*s%-20s (%s) %" PRIxMAX "\n",
5840                         (int) (level * 2), "", dwarf_attr_name (attr),
5841                         dwarf_form_name (form), (uintmax_t) num);
5842               return DWARF_CB_OK;
5843             }
5844           /* else fallthrough */
5845
5846         /* These cases always take a loclistptr and no constant. */
5847         case DW_AT_location:
5848         case DW_AT_data_location:
5849         case DW_AT_vtable_elem_location:
5850         case DW_AT_string_length:
5851         case DW_AT_use_location:
5852         case DW_AT_frame_base:
5853         case DW_AT_return_addr:
5854         case DW_AT_static_link:
5855         case DW_AT_GNU_call_site_value:
5856         case DW_AT_GNU_call_site_data_value:
5857         case DW_AT_GNU_call_site_target:
5858         case DW_AT_GNU_call_site_target_clobbered:
5859           {
5860             bool nlpt = notice_listptr (section_loc, &known_loclistptr,
5861                                         cbargs->addrsize, cbargs->offset_size,
5862                                         cbargs->cu, num);
5863             if (!cbargs->silent)
5864               printf ("           %*s%-20s (%s) location list [%6" PRIxMAX "]%s\n",
5865                       (int) (level * 2), "", dwarf_attr_name (attr),
5866                       dwarf_form_name (form), (uintmax_t) num,
5867                       nlpt ? "" : " <WARNING offset too big>");
5868           }
5869           return DWARF_CB_OK;
5870
5871         case DW_AT_ranges:
5872           {
5873             bool nlpt = notice_listptr (section_ranges, &known_rangelistptr,
5874                                         cbargs->addrsize, cbargs->offset_size,
5875                                         cbargs->cu, num);
5876             if (!cbargs->silent)
5877               printf ("           %*s%-20s (%s) range list [%6" PRIxMAX "]%s\n",
5878                       (int) (level * 2), "", dwarf_attr_name (attr),
5879                       dwarf_form_name (form), (uintmax_t) num,
5880                       nlpt ? "" : " <WARNING offset too big>");
5881           }
5882           return DWARF_CB_OK;
5883
5884         case DW_AT_language:
5885           valuestr = dwarf_lang_name (num);
5886           break;
5887         case DW_AT_encoding:
5888           valuestr = dwarf_encoding_name (num);
5889           break;
5890         case DW_AT_accessibility:
5891           valuestr = dwarf_access_name (num);
5892           break;
5893         case DW_AT_visibility:
5894           valuestr = dwarf_visibility_name (num);
5895           break;
5896         case DW_AT_virtuality:
5897           valuestr = dwarf_virtuality_name (num);
5898           break;
5899         case DW_AT_identifier_case:
5900           valuestr = dwarf_identifier_case_name (num);
5901           break;
5902         case DW_AT_calling_convention:
5903           valuestr = dwarf_calling_convention_name (num);
5904           break;
5905         case DW_AT_inline:
5906           valuestr = dwarf_inline_name (num);
5907           break;
5908         case DW_AT_ordering:
5909           valuestr = dwarf_ordering_name (num);
5910           break;
5911         case DW_AT_discr_list:
5912           valuestr = dwarf_discr_list_name (num);
5913           break;
5914         default:
5915           /* Nothing.  */
5916           break;
5917         }
5918
5919       if (cbargs->silent)
5920         break;
5921
5922       /* When highpc is in constant form it is relative to lowpc.
5923          In that case also show the address.  */
5924       Dwarf_Addr highpc;
5925       if (attr == DW_AT_high_pc && dwarf_highpc (cbargs->die, &highpc) == 0)
5926         {
5927           char *a = format_dwarf_addr (cbargs->dwflmod, cbargs->addrsize,
5928                                        highpc, highpc);
5929           printf ("           %*s%-20s (%s) %" PRIuMAX " (%s)\n",
5930                   (int) (level * 2), "", dwarf_attr_name (attr),
5931                   dwarf_form_name (form), (uintmax_t) num, a);
5932           free (a);
5933         }
5934       else
5935         {
5936           Dwarf_Sword snum = 0;
5937           if (form == DW_FORM_sdata)
5938             if (unlikely (dwarf_formsdata (attrp, &snum) != 0))
5939               goto attrval_out;
5940
5941           if (valuestr == NULL)
5942             {
5943               printf ("           %*s%-20s (%s)",
5944                       (int) (level * 2), "", dwarf_attr_name (attr),
5945                       dwarf_form_name (form));
5946               if (form == DW_FORM_sdata)
5947                 printf (" %" PRIdMAX "\n", (intmax_t) snum);
5948               else
5949                 printf (" %" PRIuMAX "\n", (uintmax_t) num);
5950             }
5951           else
5952             {
5953               printf ("           %*s%-20s (%s) %s",
5954                       (int) (level * 2), "", dwarf_attr_name (attr),
5955                       dwarf_form_name (form), valuestr);
5956               if (form == DW_FORM_sdata)
5957                 printf (" (%" PRIdMAX ")\n", (intmax_t) snum);
5958               else
5959                 printf (" (%" PRIuMAX ")\n", (uintmax_t) num);
5960             }
5961         }
5962       break;
5963
5964     case DW_FORM_flag:
5965       if (cbargs->silent)
5966         break;
5967       bool flag;
5968       if (unlikely (dwarf_formflag (attrp, &flag) != 0))
5969         goto attrval_out;
5970
5971       printf ("           %*s%-20s (%s) %s\n",
5972               (int) (level * 2), "", dwarf_attr_name (attr),
5973               dwarf_form_name (form), nl_langinfo (flag ? YESSTR : NOSTR));
5974       break;
5975
5976     case DW_FORM_flag_present:
5977       if (cbargs->silent)
5978         break;
5979       printf ("           %*s%-20s (%s) %s\n",
5980               (int) (level * 2), "", dwarf_attr_name (attr),
5981               dwarf_form_name (form), nl_langinfo (YESSTR));
5982       break;
5983
5984     case DW_FORM_exprloc:
5985     case DW_FORM_block4:
5986     case DW_FORM_block2:
5987     case DW_FORM_block1:
5988     case DW_FORM_block:
5989       if (cbargs->silent)
5990         break;
5991       Dwarf_Block block;
5992       if (unlikely (dwarf_formblock (attrp, &block) != 0))
5993         goto attrval_out;
5994
5995       printf ("           %*s%-20s (%s) ",
5996               (int) (level * 2), "", dwarf_attr_name (attr),
5997               dwarf_form_name (form));
5998
5999       switch (attr)
6000         {
6001         default:
6002           if (form != DW_FORM_exprloc)
6003             {
6004               print_block (block.length, block.data);
6005               break;
6006             }
6007           /* Fall through.  */
6008
6009         case DW_AT_location:
6010         case DW_AT_data_location:
6011         case DW_AT_data_member_location:
6012         case DW_AT_vtable_elem_location:
6013         case DW_AT_string_length:
6014         case DW_AT_use_location:
6015         case DW_AT_frame_base:
6016         case DW_AT_return_addr:
6017         case DW_AT_static_link:
6018         case DW_AT_allocated:
6019         case DW_AT_associated:
6020         case DW_AT_bit_size:
6021         case DW_AT_bit_offset:
6022         case DW_AT_bit_stride:
6023         case DW_AT_byte_size:
6024         case DW_AT_byte_stride:
6025         case DW_AT_count:
6026         case DW_AT_lower_bound:
6027         case DW_AT_upper_bound:
6028         case DW_AT_GNU_call_site_value:
6029         case DW_AT_GNU_call_site_data_value:
6030         case DW_AT_GNU_call_site_target:
6031         case DW_AT_GNU_call_site_target_clobbered:
6032           putchar ('\n');
6033           print_ops (cbargs->dwflmod, cbargs->dbg,
6034                      12 + level * 2, 12 + level * 2,
6035                      cbargs->version, cbargs->addrsize, cbargs->offset_size,
6036                      attrp->cu, block.length, block.data);
6037           break;
6038         }
6039       break;
6040
6041     default:
6042       if (cbargs->silent)
6043         break;
6044       printf ("           %*s%-20s (form: %#x) ???\n",
6045               (int) (level * 2), "", dwarf_attr_name (attr),
6046               (int) form);
6047       break;
6048     }
6049
6050   return DWARF_CB_OK;
6051 }
6052
6053 static void
6054 print_debug_units (Dwfl_Module *dwflmod,
6055                    Ebl *ebl, GElf_Ehdr *ehdr,
6056                    Elf_Scn *scn, GElf_Shdr *shdr,
6057                    Dwarf *dbg, bool debug_types)
6058 {
6059   const bool silent = !(print_debug_sections & section_info);
6060   const char *secname = section_name (ebl, ehdr, shdr);
6061
6062   if (!silent)
6063     printf (gettext ("\
6064 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n [Offset]\n"),
6065             elf_ndxscn (scn), secname, (uint64_t) shdr->sh_offset);
6066
6067   /* If the section is empty we don't have to do anything.  */
6068   if (!silent && shdr->sh_size == 0)
6069     return;
6070
6071   int maxdies = 20;
6072   Dwarf_Die *dies = (Dwarf_Die *) xmalloc (maxdies * sizeof (Dwarf_Die));
6073
6074   Dwarf_Off offset = 0;
6075
6076   /* New compilation unit.  */
6077   size_t cuhl;
6078   Dwarf_Half version;
6079   Dwarf_Off abbroffset;
6080   uint8_t addrsize;
6081   uint8_t offsize;
6082   Dwarf_Off nextcu;
6083   uint64_t typesig;
6084   Dwarf_Off typeoff;
6085  next_cu:
6086   if (dwarf_next_unit (dbg, offset, &nextcu, &cuhl, &version,
6087                        &abbroffset, &addrsize, &offsize,
6088                        debug_types ? &typesig : NULL,
6089                        debug_types ? &typeoff : NULL) != 0)
6090     goto do_return;
6091
6092   if (!silent)
6093     {
6094       if (debug_types)
6095         printf (gettext (" Type unit at offset %" PRIu64 ":\n"
6096                          " Version: %" PRIu16 ", Abbreviation section offset: %"
6097                          PRIu64 ", Address size: %" PRIu8
6098                          ", Offset size: %" PRIu8
6099                          "\n Type signature: %#" PRIx64
6100                          ", Type offset: %#" PRIx64 "\n"),
6101                 (uint64_t) offset, version, abbroffset, addrsize, offsize,
6102                 typesig, (uint64_t) typeoff);
6103       else
6104         printf (gettext (" Compilation unit at offset %" PRIu64 ":\n"
6105                          " Version: %" PRIu16 ", Abbreviation section offset: %"
6106                          PRIu64 ", Address size: %" PRIu8
6107                          ", Offset size: %" PRIu8 "\n"),
6108                 (uint64_t) offset, version, abbroffset, addrsize, offsize);
6109     }
6110
6111   struct attrcb_args args =
6112     {
6113       .dwflmod = dwflmod,
6114       .dbg = dbg,
6115       .silent = silent,
6116       .version = version,
6117       .addrsize = addrsize,
6118       .offset_size = offsize
6119     };
6120
6121   offset += cuhl;
6122
6123   int level = 0;
6124
6125   if (unlikely ((debug_types ? dwarf_offdie_types : dwarf_offdie)
6126                 (dbg, offset, &dies[level]) == NULL))
6127     {
6128       if (!silent)
6129         error (0, 0, gettext ("cannot get DIE at offset %" PRIu64
6130                               " in section '%s': %s"),
6131                (uint64_t) offset, secname, dwarf_errmsg (-1));
6132       goto do_return;
6133     }
6134
6135   args.cu = dies[0].cu;
6136
6137   do
6138     {
6139       offset = dwarf_dieoffset (&dies[level]);
6140       if (unlikely (offset == ~0ul))
6141         {
6142           if (!silent)
6143             error (0, 0, gettext ("cannot get DIE offset: %s"),
6144                    dwarf_errmsg (-1));
6145           goto do_return;
6146         }
6147
6148       int tag = dwarf_tag (&dies[level]);
6149       if (unlikely (tag == DW_TAG_invalid))
6150         {
6151           if (!silent)
6152             error (0, 0, gettext ("cannot get tag of DIE at offset %" PRIu64
6153                                   " in section '%s': %s"),
6154                    (uint64_t) offset, secname, dwarf_errmsg (-1));
6155           goto do_return;
6156         }
6157
6158       if (!silent)
6159         printf (" [%6" PRIx64 "]  %*s%s\n",
6160                 (uint64_t) offset, (int) (level * 2), "",
6161                 dwarf_tag_name (tag));
6162
6163       /* Print the attribute values.  */
6164       args.level = level;
6165       args.die = &dies[level];
6166       (void) dwarf_getattrs (&dies[level], attr_callback, &args, 0);
6167
6168       /* Make room for the next level's DIE.  */
6169       if (level + 1 == maxdies)
6170         dies = (Dwarf_Die *) xrealloc (dies,
6171                                        (maxdies += 10)
6172                                        * sizeof (Dwarf_Die));
6173
6174       int res = dwarf_child (&dies[level], &dies[level + 1]);
6175       if (res > 0)
6176         {
6177           while ((res = dwarf_siblingof (&dies[level], &dies[level])) == 1)
6178             if (level-- == 0)
6179               break;
6180
6181           if (unlikely (res == -1))
6182             {
6183               if (!silent)
6184                 error (0, 0, gettext ("cannot get next DIE: %s\n"),
6185                        dwarf_errmsg (-1));
6186               goto do_return;
6187             }
6188         }
6189       else if (unlikely (res < 0))
6190         {
6191           if (!silent)
6192             error (0, 0, gettext ("cannot get next DIE: %s"),
6193                    dwarf_errmsg (-1));
6194           goto do_return;
6195         }
6196       else
6197         ++level;
6198     }
6199   while (level >= 0);
6200
6201   offset = nextcu;
6202   if (offset != 0)
6203      goto next_cu;
6204
6205  do_return:
6206   free (dies);
6207 }
6208
6209 static void
6210 print_debug_info_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
6211                           Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
6212 {
6213   print_debug_units (dwflmod, ebl, ehdr, scn, shdr, dbg, false);
6214 }
6215
6216 static void
6217 print_debug_types_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
6218                            Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
6219 {
6220   print_debug_units (dwflmod, ebl, ehdr, scn, shdr, dbg, true);
6221 }
6222
6223
6224 static void
6225 print_decoded_line_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
6226                             Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
6227 {
6228   printf (gettext ("\
6229 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n\n"),
6230           elf_ndxscn (scn), section_name (ebl, ehdr, shdr),
6231           (uint64_t) shdr->sh_offset);
6232
6233   size_t address_size
6234     = elf_getident (ebl->elf, NULL)[EI_CLASS] == ELFCLASS32 ? 4 : 8;
6235
6236   Dwarf_Off cuoffset;
6237   Dwarf_Off ncuoffset = 0;
6238   size_t hsize;
6239   while (dwarf_nextcu (dbg, cuoffset = ncuoffset, &ncuoffset, &hsize,
6240                        NULL, NULL, NULL) == 0)
6241     {
6242       Dwarf_Die cudie;
6243       if (dwarf_offdie (dbg, cuoffset + hsize, &cudie) == NULL)
6244         continue;
6245
6246       size_t nlines;
6247       Dwarf_Lines *lines;
6248       if (dwarf_getsrclines (&cudie, &lines, &nlines) != 0)
6249         continue;
6250
6251       printf (" CU [%" PRIx64 "] %s\n",
6252               dwarf_dieoffset (&cudie), dwarf_diename (&cudie));
6253       printf ("  line:col SBPE* disc isa op address"
6254               " (Statement Block Prologue Epilogue *End)\n");
6255       const char *last_file = "";
6256       for (size_t n = 0; n < nlines; n++)
6257         {
6258           Dwarf_Line *line = dwarf_onesrcline (lines, n);
6259           Dwarf_Word mtime, length;
6260           const char *file = dwarf_linesrc (line, &mtime, &length);
6261           if (strcmp (last_file, file) != 0)
6262             {
6263               printf ("  %s (mtime: %" PRIu64 ", length: %" PRIu64 ")\n",
6264                       file, mtime, length);
6265               last_file = file;
6266             }
6267
6268           int lineno, colno;
6269           bool statement, endseq, block, prologue_end, epilogue_begin;
6270           unsigned int lineop, isa, disc;
6271           Dwarf_Addr address;
6272           dwarf_lineaddr (line, &address);
6273           dwarf_lineno (line, &lineno);
6274           dwarf_linecol (line, &colno);
6275           dwarf_lineop_index (line, &lineop);
6276           dwarf_linebeginstatement (line, &statement);
6277           dwarf_lineendsequence (line, &endseq);
6278           dwarf_lineblock (line, &block);
6279           dwarf_lineprologueend (line, &prologue_end);
6280           dwarf_lineepiloguebegin (line, &epilogue_begin);
6281           dwarf_lineisa (line, &isa);
6282           dwarf_linediscriminator (line, &disc);
6283
6284           /* End sequence is special, it is one byte past.  */
6285           char *a = format_dwarf_addr (dwflmod, address_size,
6286                                        address - (endseq ? 1 : 0), address);
6287           printf ("  %4d:%-3d %c%c%c%c%c %4d %3d %2d %s\n",
6288                   lineno, colno,
6289                   (statement ? 'S' : ' '),
6290                   (block ? 'B' : ' '),
6291                   (prologue_end ? 'P' : ' '),
6292                   (epilogue_begin ? 'E' : ' '),
6293                   (endseq ? '*' : ' '),
6294                   disc, isa, lineop, a);
6295           free (a);
6296
6297           if (endseq)
6298             printf("\n");
6299         }
6300     }
6301 }
6302
6303
6304 static void
6305 print_debug_line_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
6306                           Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
6307 {
6308   if (decodedline)
6309     {
6310       print_decoded_line_section (dwflmod, ebl, ehdr, scn, shdr, dbg);
6311       return;
6312     }
6313
6314   printf (gettext ("\
6315 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
6316           elf_ndxscn (scn), section_name (ebl, ehdr, shdr),
6317           (uint64_t) shdr->sh_offset);
6318
6319   if (shdr->sh_size == 0)
6320     return;
6321
6322   /* There is no functionality in libdw to read the information in the
6323      way it is represented here.  Hardcode the decoder.  */
6324   Elf_Data *data = dbg->sectiondata[IDX_debug_line];
6325   if (unlikely (data == NULL || data->d_buf == NULL))
6326     {
6327       error (0, 0, gettext ("cannot get line data section data: %s"),
6328              elf_errmsg (-1));
6329       return;
6330     }
6331
6332   const unsigned char *linep = (const unsigned char *) data->d_buf;
6333   const unsigned char *lineendp;
6334
6335   while (linep
6336          < (lineendp = (const unsigned char *) data->d_buf + data->d_size))
6337     {
6338       size_t start_offset = linep - (const unsigned char *) data->d_buf;
6339
6340       printf (gettext ("\nTable at offset %Zu:\n"), start_offset);
6341
6342       if (unlikely (linep + 4 > lineendp))
6343         goto invalid_data;
6344       Dwarf_Word unit_length = read_4ubyte_unaligned_inc (dbg, linep);
6345       unsigned int length = 4;
6346       if (unlikely (unit_length == 0xffffffff))
6347         {
6348           if (unlikely (linep + 8 > lineendp))
6349             {
6350             invalid_data:
6351               error (0, 0, gettext ("invalid data in section [%zu] '%s'"),
6352                      elf_ndxscn (scn), section_name (ebl, ehdr, shdr));
6353               return;
6354             }
6355           unit_length = read_8ubyte_unaligned_inc (dbg, linep);
6356           length = 8;
6357         }
6358
6359       /* Check whether we have enough room in the section.  */
6360       if (unlikely (unit_length > (size_t) (lineendp - linep)
6361           || unit_length < 2 + length + 5 * 1))
6362         goto invalid_data;
6363       lineendp = linep + unit_length;
6364
6365       /* The next element of the header is the version identifier.  */
6366       uint_fast16_t version = read_2ubyte_unaligned_inc (dbg, linep);
6367
6368       /* Next comes the header length.  */
6369       Dwarf_Word header_length;
6370       if (length == 4)
6371         header_length = read_4ubyte_unaligned_inc (dbg, linep);
6372       else
6373         header_length = read_8ubyte_unaligned_inc (dbg, linep);
6374       //const unsigned char *header_start = linep;
6375
6376       /* Next the minimum instruction length.  */
6377       uint_fast8_t minimum_instr_len = *linep++;
6378
6379       /* Next the maximum operations per instruction, in version 4 format.  */
6380       uint_fast8_t max_ops_per_instr = version < 4 ? 1 : *linep++;
6381
6382         /* Then the flag determining the default value of the is_stmt
6383            register.  */
6384       uint_fast8_t default_is_stmt = *linep++;
6385
6386       /* Now the line base.  */
6387       int_fast8_t line_base = *((const int_fast8_t *) linep);
6388       ++linep;
6389
6390       /* And the line range.  */
6391       uint_fast8_t line_range = *linep++;
6392
6393       /* The opcode base.  */
6394       uint_fast8_t opcode_base = *linep++;
6395
6396       /* Print what we got so far.  */
6397       printf (gettext ("\n"
6398                        " Length:                     %" PRIu64 "\n"
6399                        " DWARF version:              %" PRIuFAST16 "\n"
6400                        " Prologue length:            %" PRIu64 "\n"
6401                        " Minimum instruction length: %" PRIuFAST8 "\n"
6402                        " Maximum operations per instruction: %" PRIuFAST8 "\n"
6403                        " Initial value if '%s': %" PRIuFAST8 "\n"
6404                        " Line base:                  %" PRIdFAST8 "\n"
6405                        " Line range:                 %" PRIuFAST8 "\n"
6406                        " Opcode base:                %" PRIuFAST8 "\n"
6407                        "\n"
6408                        "Opcodes:\n"),
6409               (uint64_t) unit_length, version, (uint64_t) header_length,
6410               minimum_instr_len, max_ops_per_instr,
6411               "is_stmt", default_is_stmt, line_base,
6412               line_range, opcode_base);
6413
6414       if (unlikely (linep + opcode_base - 1 >= lineendp))
6415         {
6416         invalid_unit:
6417           error (0, 0,
6418                  gettext ("invalid data at offset %tu in section [%zu] '%s'"),
6419                  linep - (const unsigned char *) data->d_buf,
6420                  elf_ndxscn (scn), section_name (ebl, ehdr, shdr));
6421           linep = lineendp;
6422           continue;
6423         }
6424       int opcode_base_l10 = 1;
6425       unsigned int tmp = opcode_base;
6426       while (tmp > 10)
6427         {
6428           tmp /= 10;
6429           ++opcode_base_l10;
6430         }
6431       const uint8_t *standard_opcode_lengths = linep - 1;
6432       for (uint_fast8_t cnt = 1; cnt < opcode_base; ++cnt)
6433         printf (ngettext ("  [%*" PRIuFAST8 "]  %hhu argument\n",
6434                           "  [%*" PRIuFAST8 "]  %hhu arguments\n",
6435                           (int) linep[cnt - 1]),
6436                 opcode_base_l10, cnt, linep[cnt - 1]);
6437       linep += opcode_base - 1;
6438       if (unlikely (linep >= lineendp))
6439         goto invalid_unit;
6440
6441       puts (gettext ("\nDirectory table:"));
6442       while (*linep != 0)
6443         {
6444           unsigned char *endp = memchr (linep, '\0', lineendp - linep);
6445           if (unlikely (endp == NULL))
6446             goto invalid_unit;
6447
6448           printf (" %s\n", (char *) linep);
6449
6450           linep = endp + 1;
6451         }
6452       /* Skip the final NUL byte.  */
6453       ++linep;
6454
6455       if (unlikely (linep >= lineendp))
6456         goto invalid_unit;
6457       puts (gettext ("\nFile name table:\n"
6458                      " Entry Dir   Time      Size      Name"));
6459       for (unsigned int cnt = 1; *linep != 0; ++cnt)
6460         {
6461           /* First comes the file name.  */
6462           char *fname = (char *) linep;
6463           unsigned char *endp = memchr (fname, '\0', lineendp - linep);
6464           if (unlikely (endp == NULL))
6465             goto invalid_unit;
6466           linep = endp + 1;
6467
6468           /* Then the index.  */
6469           unsigned int diridx;
6470           if (lineendp - linep < 1)
6471             goto invalid_unit;
6472           get_uleb128 (diridx, linep, lineendp);
6473
6474           /* Next comes the modification time.  */
6475           unsigned int mtime;
6476           if (lineendp - linep < 1)
6477             goto invalid_unit;
6478           get_uleb128 (mtime, linep, lineendp);
6479
6480           /* Finally the length of the file.  */
6481           unsigned int fsize;
6482           if (lineendp - linep < 1)
6483             goto invalid_unit;
6484           get_uleb128 (fsize, linep, lineendp);
6485
6486           printf (" %-5u %-5u %-9u %-9u %s\n",
6487                   cnt, diridx, mtime, fsize, fname);
6488         }
6489       /* Skip the final NUL byte.  */
6490       ++linep;
6491
6492       puts (gettext ("\nLine number statements:"));
6493       Dwarf_Word address = 0;
6494       unsigned int op_index = 0;
6495       size_t line = 1;
6496       uint_fast8_t is_stmt = default_is_stmt;
6497
6498       /* Default address value, in case we do not find the CU.  */
6499       size_t address_size
6500         = elf_getident (ebl->elf, NULL)[EI_CLASS] == ELFCLASS32 ? 4 : 8;
6501
6502       /* Determine the CU this block is for.  */
6503       Dwarf_Off cuoffset;
6504       Dwarf_Off ncuoffset = 0;
6505       size_t hsize;
6506       while (dwarf_nextcu (dbg, cuoffset = ncuoffset, &ncuoffset, &hsize,
6507                            NULL, NULL, NULL) == 0)
6508         {
6509           Dwarf_Die cudie;
6510           if (dwarf_offdie (dbg, cuoffset + hsize, &cudie) == NULL)
6511             continue;
6512           Dwarf_Attribute stmt_list;
6513           if (dwarf_attr (&cudie, DW_AT_stmt_list, &stmt_list) == NULL)
6514             continue;
6515           Dwarf_Word lineoff;
6516           if (dwarf_formudata (&stmt_list, &lineoff) != 0)
6517             continue;
6518           if (lineoff == start_offset)
6519             {
6520               /* Found the CU.  */
6521               address_size = cudie.cu->address_size;
6522               break;
6523             }
6524         }
6525
6526       /* Apply the "operation advance" from a special opcode
6527          or DW_LNS_advance_pc (as per DWARF4 6.2.5.1).  */
6528       unsigned int op_addr_advance;
6529       bool show_op_index;
6530       inline void advance_pc (unsigned int op_advance)
6531       {
6532         op_addr_advance = minimum_instr_len * ((op_index + op_advance)
6533                                                / max_ops_per_instr);
6534         address += op_advance;
6535         show_op_index = (op_index > 0 ||
6536                          (op_index + op_advance) % max_ops_per_instr > 0);
6537         op_index = (op_index + op_advance) % max_ops_per_instr;
6538       }
6539
6540       if (max_ops_per_instr == 0)
6541         {
6542           error (0, 0,
6543                  gettext ("invalid maximum operations per instruction is zero"));
6544           linep = lineendp;
6545           continue;
6546         }
6547
6548       while (linep < lineendp)
6549         {
6550           size_t offset = linep - (const unsigned char *) data->d_buf;
6551           unsigned int u128;
6552           int s128;
6553
6554           /* Read the opcode.  */
6555           unsigned int opcode = *linep++;
6556
6557           printf (" [%6" PRIx64 "]", (uint64_t)offset);
6558           /* Is this a special opcode?  */
6559           if (likely (opcode >= opcode_base))
6560             {
6561               if (unlikely (line_range == 0))
6562                 goto invalid_unit;
6563
6564               /* Yes.  Handling this is quite easy since the opcode value
6565                  is computed with
6566
6567                  opcode = (desired line increment - line_base)
6568                            + (line_range * address advance) + opcode_base
6569               */
6570               int line_increment = (line_base
6571                                     + (opcode - opcode_base) % line_range);
6572
6573               /* Perform the increments.  */
6574               line += line_increment;
6575               advance_pc ((opcode - opcode_base) / line_range);
6576
6577               char *a = format_dwarf_addr (dwflmod, 0, address, address);
6578               if (show_op_index)
6579                 printf (gettext ("\
6580  special opcode %u: address+%u = %s, op_index = %u, line%+d = %zu\n"),
6581                         opcode, op_addr_advance, a, op_index,
6582                         line_increment, line);
6583               else
6584                 printf (gettext ("\
6585  special opcode %u: address+%u = %s, line%+d = %zu\n"),
6586                         opcode, op_addr_advance, a, line_increment, line);
6587               free (a);
6588             }
6589           else if (opcode == 0)
6590             {
6591               /* This an extended opcode.  */
6592               if (unlikely (linep + 2 > lineendp))
6593                 goto invalid_unit;
6594
6595               /* The length.  */
6596               unsigned int len = *linep++;
6597
6598               if (unlikely (linep + len > lineendp))
6599                 goto invalid_unit;
6600
6601               /* The sub-opcode.  */
6602               opcode = *linep++;
6603
6604               printf (gettext (" extended opcode %u: "), opcode);
6605
6606               switch (opcode)
6607                 {
6608                 case DW_LNE_end_sequence:
6609                   puts (gettext (" end of sequence"));
6610
6611                   /* Reset the registers we care about.  */
6612                   address = 0;
6613                   op_index = 0;
6614                   line = 1;
6615                   is_stmt = default_is_stmt;
6616                   break;
6617
6618                 case DW_LNE_set_address:
6619                   op_index = 0;
6620                   if (unlikely ((size_t) (lineendp - linep) < address_size))
6621                     goto invalid_unit;
6622                   if (address_size == 4)
6623                     address = read_4ubyte_unaligned_inc (dbg, linep);
6624                   else
6625                     address = read_8ubyte_unaligned_inc (dbg, linep);
6626                   {
6627                     char *a = format_dwarf_addr (dwflmod, 0, address, address);
6628                     printf (gettext (" set address to %s\n"), a);
6629                     free (a);
6630                   }
6631                   break;
6632
6633                 case DW_LNE_define_file:
6634                   {
6635                     char *fname = (char *) linep;
6636                     unsigned char *endp = memchr (linep, '\0',
6637                                                   lineendp - linep);
6638                     if (unlikely (endp == NULL))
6639                       goto invalid_unit;
6640                     linep = endp + 1;
6641
6642                     unsigned int diridx;
6643                     if (lineendp - linep < 1)
6644                       goto invalid_unit;
6645                     get_uleb128 (diridx, linep, lineendp);
6646                     Dwarf_Word mtime;
6647                     if (lineendp - linep < 1)
6648                       goto invalid_unit;
6649                     get_uleb128 (mtime, linep, lineendp);
6650                     Dwarf_Word filelength;
6651                     if (lineendp - linep < 1)
6652                       goto invalid_unit;
6653                     get_uleb128 (filelength, linep, lineendp);
6654
6655                     printf (gettext ("\
6656  define new file: dir=%u, mtime=%" PRIu64 ", length=%" PRIu64 ", name=%s\n"),
6657                             diridx, (uint64_t) mtime, (uint64_t) filelength,
6658                             fname);
6659                   }
6660                   break;
6661
6662                 case DW_LNE_set_discriminator:
6663                   /* Takes one ULEB128 parameter, the discriminator.  */
6664                   if (unlikely (standard_opcode_lengths[opcode] != 1))
6665                     goto invalid_unit;
6666
6667                   get_uleb128 (u128, linep, lineendp);
6668                   printf (gettext (" set discriminator to %u\n"), u128);
6669                   break;
6670
6671                 default:
6672                   /* Unknown, ignore it.  */
6673                   puts (gettext (" unknown opcode"));
6674                   linep += len - 1;
6675                   break;
6676                 }
6677             }
6678           else if (opcode <= DW_LNS_set_isa)
6679             {
6680               /* This is a known standard opcode.  */
6681               switch (opcode)
6682                 {
6683                 case DW_LNS_copy:
6684                   /* Takes no argument.  */
6685                   puts (gettext (" copy"));
6686                   break;
6687
6688                 case DW_LNS_advance_pc:
6689                   /* Takes one uleb128 parameter which is added to the
6690                      address.  */
6691                   get_uleb128 (u128, linep, lineendp);
6692                   advance_pc (u128);
6693                   {
6694                     char *a = format_dwarf_addr (dwflmod, 0, address, address);
6695                     if (show_op_index)
6696                       printf (gettext ("\
6697  advance address by %u to %s, op_index to %u\n"),
6698                               op_addr_advance, a, op_index);
6699                     else
6700                       printf (gettext (" advance address by %u to %s\n"),
6701                               op_addr_advance, a);
6702                     free (a);
6703                   }
6704                   break;
6705
6706                 case DW_LNS_advance_line:
6707                   /* Takes one sleb128 parameter which is added to the
6708                      line.  */
6709                   get_sleb128 (s128, linep, lineendp);
6710                   line += s128;
6711                   printf (gettext ("\
6712  advance line by constant %d to %" PRId64 "\n"),
6713                           s128, (int64_t) line);
6714                   break;
6715
6716                 case DW_LNS_set_file:
6717                   /* Takes one uleb128 parameter which is stored in file.  */
6718                   get_uleb128 (u128, linep, lineendp);
6719                   printf (gettext (" set file to %" PRIu64 "\n"),
6720                           (uint64_t) u128);
6721                   break;
6722
6723                 case DW_LNS_set_column:
6724                   /* Takes one uleb128 parameter which is stored in column.  */
6725                   if (unlikely (standard_opcode_lengths[opcode] != 1))
6726                     goto invalid_unit;
6727
6728                   get_uleb128 (u128, linep, lineendp);
6729                   printf (gettext (" set column to %" PRIu64 "\n"),
6730                           (uint64_t) u128);
6731                   break;
6732
6733                 case DW_LNS_negate_stmt:
6734                   /* Takes no argument.  */
6735                   is_stmt = 1 - is_stmt;
6736                   printf (gettext (" set '%s' to %" PRIuFAST8 "\n"),
6737                           "is_stmt", is_stmt);
6738                   break;
6739
6740                 case DW_LNS_set_basic_block:
6741                   /* Takes no argument.  */
6742                   puts (gettext (" set basic block flag"));
6743                   break;
6744
6745                 case DW_LNS_const_add_pc:
6746                   /* Takes no argument.  */
6747
6748                   if (unlikely (line_range == 0))
6749                     goto invalid_unit;
6750
6751                   advance_pc ((255 - opcode_base) / line_range);
6752                   {
6753                     char *a = format_dwarf_addr (dwflmod, 0, address, address);
6754                     if (show_op_index)
6755                       printf (gettext ("\
6756  advance address by constant %u to %s, op_index to %u\n"),
6757                               op_addr_advance, a, op_index);
6758                     else
6759                       printf (gettext ("\
6760  advance address by constant %u to %s\n"),
6761                               op_addr_advance, a);
6762                     free (a);
6763                   }
6764                   break;
6765
6766                 case DW_LNS_fixed_advance_pc:
6767                   /* Takes one 16 bit parameter which is added to the
6768                      address.  */
6769                   if (unlikely (standard_opcode_lengths[opcode] != 1))
6770                     goto invalid_unit;
6771
6772                   u128 = read_2ubyte_unaligned_inc (dbg, linep);
6773                   address += u128;
6774                   op_index = 0;
6775                   {
6776                     char *a = format_dwarf_addr (dwflmod, 0, address, address);
6777                     printf (gettext ("\
6778  advance address by fixed value %u to %s\n"),
6779                             u128, a);
6780                     free (a);
6781                   }
6782                   break;
6783
6784                 case DW_LNS_set_prologue_end:
6785                   /* Takes no argument.  */
6786                   puts (gettext (" set prologue end flag"));
6787                   break;
6788
6789                 case DW_LNS_set_epilogue_begin:
6790                   /* Takes no argument.  */
6791                   puts (gettext (" set epilogue begin flag"));
6792                   break;
6793
6794                 case DW_LNS_set_isa:
6795                   /* Takes one uleb128 parameter which is stored in isa.  */
6796                   if (unlikely (standard_opcode_lengths[opcode] != 1))
6797                     goto invalid_unit;
6798
6799                   get_uleb128 (u128, linep, lineendp);
6800                   printf (gettext (" set isa to %u\n"), u128);
6801                   break;
6802                 }
6803             }
6804           else
6805             {
6806               /* This is a new opcode the generator but not we know about.
6807                  Read the parameters associated with it but then discard
6808                  everything.  Read all the parameters for this opcode.  */
6809               printf (ngettext (" unknown opcode with %" PRIu8 " parameter:",
6810                                 " unknown opcode with %" PRIu8 " parameters:",
6811                                 standard_opcode_lengths[opcode]),
6812                       standard_opcode_lengths[opcode]);
6813               for (int n = standard_opcode_lengths[opcode]; n > 0; --n)
6814                 {
6815                   get_uleb128 (u128, linep, lineendp);
6816                   if (n != standard_opcode_lengths[opcode])
6817                     putc_unlocked (',', stdout);
6818                   printf (" %u", u128);
6819                 }
6820
6821               /* Next round, ignore this opcode.  */
6822               continue;
6823             }
6824         }
6825     }
6826
6827   /* There must only be one data block.  */
6828   assert (elf_getdata (scn, data) == NULL);
6829 }
6830
6831
6832 static void
6833 print_debug_loc_section (Dwfl_Module *dwflmod,
6834                          Ebl *ebl, GElf_Ehdr *ehdr,
6835                          Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
6836 {
6837   Elf_Data *data = dbg->sectiondata[IDX_debug_loc];
6838
6839   if (unlikely (data == NULL))
6840     {
6841       error (0, 0, gettext ("cannot get .debug_loc content: %s"),
6842              elf_errmsg (-1));
6843       return;
6844     }
6845
6846   printf (gettext ("\
6847 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
6848           elf_ndxscn (scn), section_name (ebl, ehdr, shdr),
6849           (uint64_t) shdr->sh_offset);
6850
6851   sort_listptr (&known_loclistptr, "loclistptr");
6852   size_t listptr_idx = 0;
6853
6854   uint_fast8_t address_size = ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
6855   uint_fast8_t offset_size = 4;
6856
6857   bool first = true;
6858   struct Dwarf_CU *cu = NULL;
6859   Dwarf_Addr base = 0;
6860   unsigned char *readp = data->d_buf;
6861   unsigned char *const endp = (unsigned char *) data->d_buf + data->d_size;
6862   while (readp < endp)
6863     {
6864       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
6865
6866       if (first && skip_listptr_hole (&known_loclistptr, &listptr_idx,
6867                                       &address_size, &offset_size, &base,
6868                                       &cu, offset, &readp, endp))
6869         continue;
6870
6871       if (unlikely (data->d_size - offset < (size_t) address_size * 2))
6872         {
6873           printf (gettext (" [%6tx]  <INVALID DATA>\n"), offset);
6874           break;
6875         }
6876
6877       Dwarf_Addr begin;
6878       Dwarf_Addr end;
6879       if (address_size == 8)
6880         {
6881           begin = read_8ubyte_unaligned_inc (dbg, readp);
6882           end = read_8ubyte_unaligned_inc (dbg, readp);
6883         }
6884       else
6885         {
6886           begin = read_4ubyte_unaligned_inc (dbg, readp);
6887           end = read_4ubyte_unaligned_inc (dbg, readp);
6888           if (begin == (Dwarf_Addr) (uint32_t) -1)
6889             begin = (Dwarf_Addr) -1l;
6890         }
6891
6892       if (begin == (Dwarf_Addr) -1l) /* Base address entry.  */
6893         {
6894           char *b = format_dwarf_addr (dwflmod, address_size, end, end);
6895           printf (gettext (" [%6tx]  base address %s\n"), offset, b);
6896           free (b);
6897           base = end;
6898         }
6899       else if (begin == 0 && end == 0) /* End of list entry.  */
6900         {
6901           if (first)
6902             printf (gettext (" [%6tx]  empty list\n"), offset);
6903           first = true;
6904         }
6905       else
6906         {
6907           /* We have a location expression entry.  */
6908           uint_fast16_t len = read_2ubyte_unaligned_inc (dbg, readp);
6909
6910           char *b = format_dwarf_addr (dwflmod, address_size, base + begin,
6911                                        begin);
6912           char *e = format_dwarf_addr (dwflmod, address_size, base + end,
6913                                        end);
6914
6915           if (first)            /* First entry in a list.  */
6916             printf (gettext (" [%6tx]  %s..%s"), offset, b, e);
6917           else
6918             printf (gettext ("           %s..%s"), b, e);
6919
6920           free (b);
6921           free (e);
6922
6923           if (endp - readp <= (ptrdiff_t) len)
6924             {
6925               fputs (gettext ("   <INVALID DATA>\n"), stdout);
6926               break;
6927             }
6928
6929           print_ops (dwflmod, dbg, 1, 18 + (address_size * 4),
6930                      3 /*XXX*/, address_size, offset_size, cu, len, readp);
6931
6932           first = false;
6933           readp += len;
6934         }
6935     }
6936 }
6937
6938 struct mac_culist
6939 {
6940   Dwarf_Die die;
6941   Dwarf_Off offset;
6942   Dwarf_Files *files;
6943   struct mac_culist *next;
6944 };
6945
6946
6947 static int
6948 mac_compare (const void *p1, const void *p2)
6949 {
6950   struct mac_culist *m1 = (struct mac_culist *) p1;
6951   struct mac_culist *m2 = (struct mac_culist *) p2;
6952
6953   if (m1->offset < m2->offset)
6954     return -1;
6955   if (m1->offset > m2->offset)
6956     return 1;
6957   return 0;
6958 }
6959
6960
6961 static void
6962 print_debug_macinfo_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
6963                              Ebl *ebl, GElf_Ehdr *ehdr,
6964                              Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
6965 {
6966   printf (gettext ("\
6967 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
6968           elf_ndxscn (scn), section_name (ebl, ehdr, shdr),
6969           (uint64_t) shdr->sh_offset);
6970   putc_unlocked ('\n', stdout);
6971
6972   /* There is no function in libdw to iterate over the raw content of
6973      the section but it is easy enough to do.  */
6974   Elf_Data *data = dbg->sectiondata[IDX_debug_macinfo];
6975   if (unlikely (data == NULL || data->d_buf == NULL))
6976     {
6977       error (0, 0, gettext ("cannot get macro information section data: %s"),
6978              elf_errmsg (-1));
6979       return;
6980     }
6981
6982   /* Get the source file information for all CUs.  */
6983   Dwarf_Off offset;
6984   Dwarf_Off ncu = 0;
6985   size_t hsize;
6986   struct mac_culist *culist = NULL;
6987   size_t nculist = 0;
6988   while (dwarf_nextcu (dbg, offset = ncu, &ncu, &hsize, NULL, NULL, NULL) == 0)
6989     {
6990       Dwarf_Die cudie;
6991       if (dwarf_offdie (dbg, offset + hsize, &cudie) == NULL)
6992         continue;
6993
6994       Dwarf_Attribute attr;
6995       if (dwarf_attr (&cudie, DW_AT_macro_info, &attr) == NULL)
6996         continue;
6997
6998       Dwarf_Word macoff;
6999       if (dwarf_formudata (&attr, &macoff) != 0)
7000         continue;
7001
7002       struct mac_culist *newp = (struct mac_culist *) alloca (sizeof (*newp));
7003       newp->die = cudie;
7004       newp->offset = macoff;
7005       newp->files = NULL;
7006       newp->next = culist;
7007       culist = newp;
7008       ++nculist;
7009     }
7010
7011   /* Convert the list into an array for easier consumption.  */
7012   struct mac_culist *cus = (struct mac_culist *) alloca ((nculist + 1)
7013                                                          * sizeof (*cus));
7014   /* Add sentinel.  */
7015   cus[nculist].offset = data->d_size;
7016   if (nculist > 0)
7017     {
7018       for (size_t cnt = nculist - 1; culist != NULL; --cnt)
7019         {
7020           assert (cnt < nculist);
7021           cus[cnt] = *culist;
7022           culist = culist->next;
7023         }
7024
7025       /* Sort the array according to the offset in the .debug_macinfo
7026          section.  Note we keep the sentinel at the end.  */
7027       qsort (cus, nculist, sizeof (*cus), mac_compare);
7028     }
7029
7030   const unsigned char *readp = (const unsigned char *) data->d_buf;
7031   const unsigned char *readendp = readp + data->d_size;
7032   int level = 1;
7033
7034   while (readp < readendp)
7035     {
7036       unsigned int opcode = *readp++;
7037       unsigned int u128;
7038       unsigned int u128_2;
7039       const unsigned char *endp;
7040
7041       switch (opcode)
7042         {
7043         case DW_MACINFO_define:
7044         case DW_MACINFO_undef:
7045         case DW_MACINFO_vendor_ext:
7046           /*  For the first two opcodes the parameters are
7047                 line, string
7048               For the latter
7049                 number, string.
7050               We can treat these cases together.  */
7051           get_uleb128 (u128, readp, readendp);
7052
7053           endp = memchr (readp, '\0', readendp - readp);
7054           if (unlikely (endp == NULL))
7055             {
7056               printf (gettext ("\
7057 %*s*** non-terminated string at end of section"),
7058                       level, "");
7059               return;
7060             }
7061
7062           if (opcode == DW_MACINFO_define)
7063             printf ("%*s#define %s, line %u\n",
7064                     level, "", (char *) readp, u128);
7065           else if (opcode == DW_MACINFO_undef)
7066             printf ("%*s#undef %s, line %u\n",
7067                     level, "", (char *) readp, u128);
7068           else
7069             printf (" #vendor-ext %s, number %u\n", (char *) readp, u128);
7070
7071           readp = endp + 1;
7072           break;
7073
7074         case DW_MACINFO_start_file:
7075           /* The two parameters are line and file index, in this order.  */
7076           get_uleb128 (u128, readp, readendp);
7077           if (readendp - readp < 1)
7078             {
7079               printf (gettext ("\
7080 %*s*** missing DW_MACINFO_start_file argument at end of section"),
7081                       level, "");
7082               return;
7083             }
7084           get_uleb128 (u128_2, readp, readendp);
7085
7086           /* Find the CU DIE for this file.  */
7087           size_t macoff = readp - (const unsigned char *) data->d_buf;
7088           const char *fname = "???";
7089           if (macoff >= cus[0].offset)
7090             {
7091               while (macoff >= cus[1].offset)
7092                 ++cus;
7093
7094               if (cus[0].files == NULL
7095                 && dwarf_getsrcfiles (&cus[0].die, &cus[0].files, NULL) != 0)
7096                 cus[0].files = (Dwarf_Files *) -1l;
7097
7098               if (cus[0].files != (Dwarf_Files *) -1l)
7099                 fname = (dwarf_filesrc (cus[0].files, u128_2, NULL, NULL)
7100                          ?: "???");
7101             }
7102
7103           printf ("%*sstart_file %u, [%u] %s\n",
7104                   level, "", u128, u128_2, fname);
7105           ++level;
7106           break;
7107
7108         case DW_MACINFO_end_file:
7109           --level;
7110           printf ("%*send_file\n", level, "");
7111           /* Nothing more to do.  */
7112           break;
7113
7114         default:
7115           // XXX gcc seems to generate files with a trailing zero.
7116           if (unlikely (opcode != 0 || readp != readendp))
7117             printf ("%*s*** invalid opcode %u\n", level, "", opcode);
7118           break;
7119         }
7120     }
7121 }
7122
7123
7124 static void
7125 print_debug_macro_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
7126                            Ebl *ebl, GElf_Ehdr *ehdr,
7127                            Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
7128 {
7129   printf (gettext ("\
7130 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
7131           elf_ndxscn (scn), section_name (ebl, ehdr, shdr),
7132           (uint64_t) shdr->sh_offset);
7133   putc_unlocked ('\n', stdout);
7134
7135   Elf_Data *data = dbg->sectiondata[IDX_debug_macro];
7136   if (unlikely (data == NULL || data->d_buf == NULL))
7137     {
7138       error (0, 0, gettext ("cannot get macro information section data: %s"),
7139              elf_errmsg (-1));
7140       return;
7141     }
7142
7143   /* Get the source file information for all CUs.  Uses same
7144      datastructure as macinfo.  But uses offset field to directly
7145      match .debug_line offset.  And just stored in a list.  */
7146   Dwarf_Off offset;
7147   Dwarf_Off ncu = 0;
7148   size_t hsize;
7149   struct mac_culist *culist = NULL;
7150   size_t nculist = 0;
7151   while (dwarf_nextcu (dbg, offset = ncu, &ncu, &hsize, NULL, NULL, NULL) == 0)
7152     {
7153       Dwarf_Die cudie;
7154       if (dwarf_offdie (dbg, offset + hsize, &cudie) == NULL)
7155         continue;
7156
7157       Dwarf_Attribute attr;
7158       if (dwarf_attr (&cudie, DW_AT_stmt_list, &attr) == NULL)
7159         continue;
7160
7161       Dwarf_Word lineoff;
7162       if (dwarf_formudata (&attr, &lineoff) != 0)
7163         continue;
7164
7165       struct mac_culist *newp = (struct mac_culist *) alloca (sizeof (*newp));
7166       newp->die = cudie;
7167       newp->offset = lineoff;
7168       newp->files = NULL;
7169       newp->next = culist;
7170       culist = newp;
7171       ++nculist;
7172     }
7173
7174   const unsigned char *readp = (const unsigned char *) data->d_buf;
7175   const unsigned char *readendp = readp + data->d_size;
7176
7177   while (readp < readendp)
7178     {
7179       printf (gettext (" Offset:             0x%" PRIx64 "\n"),
7180               (uint64_t) (readp - (const unsigned char *) data->d_buf));
7181
7182       // Header, 2 byte version, 1 byte flag, optional .debug_line offset,
7183       // optional vendor extension macro entry table.
7184       if (readp + 2 > readendp)
7185         {
7186         invalid_data:
7187           error (0, 0, gettext ("invalid data"));
7188           return;
7189         }
7190       const uint16_t vers = read_2ubyte_unaligned_inc (dbg, readp);
7191       printf (gettext (" Version:            %" PRIu16 "\n"), vers);
7192
7193       // Version 4 is the GNU extension for DWARF4.  DWARF5 will use version
7194       // 5 when it gets standardized.
7195       if (vers != 4)
7196         {
7197           printf (gettext ("  unknown version, cannot parse section\n"));
7198           return;
7199         }
7200
7201       if (readp + 1 > readendp)
7202         goto invalid_data;
7203       const unsigned char flag = *readp++;
7204       printf (gettext (" Flag:               0x%" PRIx8 "\n"), flag);
7205
7206       unsigned int offset_len = (flag & 0x01) ? 8 : 4;
7207       printf (gettext (" Offset length:      %" PRIu8 "\n"), offset_len);
7208       Dwarf_Off line_offset = -1;
7209       if (flag & 0x02)
7210         {
7211           if (offset_len == 8)
7212             line_offset = read_8ubyte_unaligned_inc (dbg, readp);
7213           else
7214             line_offset = read_4ubyte_unaligned_inc (dbg, readp);
7215           printf (gettext (" .debug_line offset: 0x%" PRIx64 "\n"),
7216                   line_offset);
7217         }
7218
7219       const unsigned char *vendor[DW_MACRO_GNU_hi_user - DW_MACRO_GNU_lo_user];
7220       memset (vendor, 0, sizeof vendor);
7221       if (flag & 0x04)
7222         {
7223           // 1 byte length, for each item, 1 byte opcode, uleb128 number
7224           // of arguments, for each argument 1 byte form code.
7225           if (readp + 1 > readendp)
7226             goto invalid_data;
7227           unsigned int tlen = *readp++;
7228           printf (gettext ("  extension opcode table, %" PRIu8 " items:\n"),
7229                   tlen);
7230           for (unsigned int i = 0; i < tlen; i++)
7231             {
7232               if (readp + 1 > readendp)
7233                 goto invalid_data;
7234               unsigned int opcode = *readp++;
7235               printf (gettext ("    [%" PRIx8 "]"), opcode);
7236               if (opcode < DW_MACRO_GNU_lo_user
7237                   || opcode > DW_MACRO_GNU_hi_user)
7238                 goto invalid_data;
7239               // Record the start of description for this vendor opcode.
7240               // uleb128 nr args, 1 byte per arg form.
7241               vendor[opcode - DW_MACRO_GNU_lo_user] = readp;
7242               if (readp + 1 > readendp)
7243                 goto invalid_data;
7244               unsigned int args = *readp++;
7245               if (args > 0)
7246                 {
7247                   printf (gettext (" %" PRIu8 " arguments:"), args);
7248                   while (args > 0)
7249                     {
7250                       if (readp + 1 > readendp)
7251                         goto invalid_data;
7252                       unsigned int form = *readp++;
7253                       printf (" %s", dwarf_form_string (form));
7254                       if (form != DW_FORM_data1
7255                           && form != DW_FORM_data2
7256                           && form != DW_FORM_data4
7257                           && form != DW_FORM_data8
7258                           && form != DW_FORM_sdata
7259                           && form != DW_FORM_udata
7260                           && form != DW_FORM_block
7261                           && form != DW_FORM_block1
7262                           && form != DW_FORM_block2
7263                           && form != DW_FORM_block4
7264                           && form != DW_FORM_flag
7265                           && form != DW_FORM_string
7266                           && form != DW_FORM_strp
7267                           && form != DW_FORM_sec_offset)
7268                         goto invalid_data;
7269                       args--;
7270                       if (args > 0)
7271                         putchar_unlocked (',');
7272                     }
7273                 }
7274               else
7275                 printf (gettext (" no arguments."));
7276               putchar_unlocked ('\n');
7277             }
7278         }
7279       putchar_unlocked ('\n');
7280
7281       int level = 1;
7282       if (readp + 1 > readendp)
7283         goto invalid_data;
7284       unsigned int opcode = *readp++;
7285       while (opcode != 0)
7286         {
7287           unsigned int u128;
7288           unsigned int u128_2;
7289           const unsigned char *endp;
7290           uint64_t off;
7291
7292           switch (opcode)
7293             {
7294             case DW_MACRO_GNU_start_file:
7295               get_uleb128 (u128, readp, readendp);
7296               if (readp >= readendp)
7297                 goto invalid_data;
7298               get_uleb128 (u128_2, readp, readendp);
7299
7300               /* Find the CU DIE that matches this line offset.  */
7301               const char *fname = "???";
7302               if (line_offset != (Dwarf_Off) -1)
7303                 {
7304                   struct mac_culist *cu = culist;
7305                   while (cu != NULL && line_offset != cu->offset)
7306                     cu = cu->next;
7307                   if (cu != NULL)
7308                     {
7309                       if (cu->files == NULL
7310                           && dwarf_getsrcfiles (&cu->die, &cu->files,
7311                                                 NULL) != 0)
7312                         cu->files = (Dwarf_Files *) -1l;
7313
7314                       if (cu->files != (Dwarf_Files *) -1l)
7315                         fname = (dwarf_filesrc (cu->files, u128_2,
7316                                                 NULL, NULL) ?: "???");
7317                     }
7318                 }
7319               printf ("%*sstart_file %u, [%u] %s\n",
7320                       level, "", u128, u128_2, fname);
7321               ++level;
7322               break;
7323
7324             case DW_MACRO_GNU_end_file:
7325               --level;
7326               printf ("%*send_file\n", level, "");
7327               break;
7328
7329             case DW_MACRO_GNU_define:
7330               get_uleb128 (u128, readp, readendp);
7331               endp = memchr (readp, '\0', readendp - readp);
7332               if (endp == NULL)
7333                 goto invalid_data;
7334               printf ("%*s#define %s, line %u\n",
7335                       level, "", readp, u128);
7336               readp = endp + 1;
7337               break;
7338
7339             case DW_MACRO_GNU_undef:
7340               get_uleb128 (u128, readp, readendp);
7341               endp = memchr (readp, '\0', readendp - readp);
7342               if (endp == NULL)
7343                 goto invalid_data;
7344               printf ("%*s#undef %s, line %u\n",
7345                       level, "", readp, u128);
7346               readp = endp + 1;
7347               break;
7348
7349             case DW_MACRO_GNU_define_indirect:
7350               get_uleb128 (u128, readp, readendp);
7351               if (readp + offset_len > readendp)
7352                 goto invalid_data;
7353               if (offset_len == 8)
7354                 off = read_8ubyte_unaligned_inc (dbg, readp);
7355               else
7356                 off = read_4ubyte_unaligned_inc (dbg, readp);
7357               printf ("%*s#define %s, line %u (indirect)\n",
7358                       level, "", dwarf_getstring (dbg, off, NULL), u128);
7359               break;
7360
7361             case DW_MACRO_GNU_undef_indirect:
7362               get_uleb128 (u128, readp, readendp);
7363               if (readp + offset_len > readendp)
7364                 goto invalid_data;
7365               if (offset_len == 8)
7366                 off = read_8ubyte_unaligned_inc (dbg, readp);
7367               else
7368                 off = read_4ubyte_unaligned_inc (dbg, readp);
7369               printf ("%*s#undef %s, line %u (indirect)\n",
7370                       level, "", dwarf_getstring (dbg, off, NULL), u128);
7371               break;
7372
7373             case DW_MACRO_GNU_transparent_include:
7374               if (readp + offset_len > readendp)
7375                 goto invalid_data;
7376               if (offset_len == 8)
7377                 off = read_8ubyte_unaligned_inc (dbg, readp);
7378               else
7379                 off = read_4ubyte_unaligned_inc (dbg, readp);
7380               printf ("%*s#include offset 0x%" PRIx64 "\n",
7381                       level, "", off);
7382               break;
7383
7384             default:
7385               printf ("%*svendor opcode 0x%" PRIx8, level, "", opcode);
7386               if (opcode < DW_MACRO_GNU_lo_user
7387                   || opcode > DW_MACRO_GNU_lo_user
7388                   || vendor[opcode - DW_MACRO_GNU_lo_user] == NULL)
7389                 goto invalid_data;
7390
7391               const unsigned char *op_desc;
7392               op_desc = vendor[opcode - DW_MACRO_GNU_lo_user];
7393
7394               // Just skip the arguments, we cannot really interpret them,
7395               // but print as much as we can.
7396               unsigned int args = *op_desc++;
7397               while (args > 0)
7398                 {
7399                   unsigned int form = *op_desc++;
7400                   Dwarf_Word val;
7401                   switch (form)
7402                     {
7403                     case DW_FORM_data1:
7404                       if (readp + 1 > readendp)
7405                         goto invalid_data;
7406                       val = *readp++;
7407                       printf (" %" PRIx8, (unsigned int) val);
7408                       break;
7409
7410                     case DW_FORM_data2:
7411                       if (readp + 2 > readendp)
7412                         goto invalid_data;
7413                       val = read_2ubyte_unaligned_inc (dbg, readp);
7414                       printf(" %" PRIx16, (unsigned int) val);
7415                       break;
7416
7417                     case DW_FORM_data4:
7418                       if (readp + 4 > readendp)
7419                         goto invalid_data;
7420                       val = read_4ubyte_unaligned_inc (dbg, readp);
7421                       printf (" %" PRIx32, (unsigned int) val);
7422                       break;
7423
7424                     case DW_FORM_data8:
7425                       if (readp + 8 > readendp)
7426                         goto invalid_data;
7427                       val = read_8ubyte_unaligned_inc (dbg, readp);
7428                       printf (" %" PRIx64, val);
7429                       break;
7430
7431                     case DW_FORM_sdata:
7432                       get_sleb128 (val, readp, readendp);
7433                       printf (" %" PRIx64, val);
7434                       break;
7435
7436                     case DW_FORM_udata:
7437                       get_uleb128 (val, readp, readendp);
7438                       printf (" %" PRIx64, val);
7439                       break;
7440
7441                     case DW_FORM_block:
7442                       get_uleb128 (val, readp, readendp);
7443                       printf (" block[%" PRIu64 "]", val);
7444                       if (readp + val > readendp)
7445                         goto invalid_data;
7446                       readp += val;
7447                       break;
7448
7449                     case DW_FORM_block1:
7450                       if (readp + 1 > readendp)
7451                         goto invalid_data;
7452                       val = *readp++;
7453                       printf (" block[%" PRIu64 "]", val);
7454                       if (readp + val > readendp)
7455                         goto invalid_data;
7456                       break;
7457
7458                     case DW_FORM_block2:
7459                       if (readp + 2 > readendp)
7460                         goto invalid_data;
7461                       val = read_2ubyte_unaligned_inc (dbg, readp);
7462                       printf (" block[%" PRIu64 "]", val);
7463                       if (readp + val > readendp)
7464                         goto invalid_data;
7465                       break;
7466
7467                     case DW_FORM_block4:
7468                       if (readp + 2 > readendp)
7469                         goto invalid_data;
7470                       val =read_4ubyte_unaligned_inc (dbg, readp);
7471                       printf (" block[%" PRIu64 "]", val);
7472                       if (readp + val > readendp)
7473                         goto invalid_data;
7474                       break;
7475
7476                     case DW_FORM_flag:
7477                       if (readp + 1 > readendp)
7478                         goto invalid_data;
7479                       val = *readp++;
7480                       printf (" %s", nl_langinfo (val != 0 ? YESSTR : NOSTR));
7481                       break;
7482
7483                     case DW_FORM_string:
7484                       endp = memchr (readp, '\0', readendp - readp);
7485                       if (endp == NULL)
7486                         goto invalid_data;
7487                       printf (" %s", readp);
7488                       readp = endp + 1;
7489                       break;
7490
7491                     case DW_FORM_strp:
7492                       if (readp + offset_len > readendp)
7493                         goto invalid_data;
7494                       if (offset_len == 8)
7495                         val = read_8ubyte_unaligned_inc (dbg, readp);
7496                       else
7497                         val = read_4ubyte_unaligned_inc (dbg, readp);
7498                       printf (" %s", dwarf_getstring (dbg, val, NULL));
7499                       break;
7500
7501                     case DW_FORM_sec_offset:
7502                       if (readp + offset_len > readendp)
7503                         goto invalid_data;
7504                       if (offset_len == 8)
7505                         val = read_8ubyte_unaligned_inc (dbg, readp);
7506                       else
7507                         val = read_4ubyte_unaligned_inc (dbg, readp);
7508                       printf (" %" PRIx64, val);
7509                       break;
7510
7511                       default:
7512                         error (0, 0, gettext ("vendor opcode not verified?"));
7513                         return;
7514                     }
7515
7516                   args--;
7517                   if (args > 0)
7518                     putchar_unlocked (',');
7519                 }
7520               putchar_unlocked ('\n');
7521             }
7522
7523           if (readp + 1 > readendp)
7524             goto invalid_data;
7525           opcode = *readp++;
7526           if (opcode == 0)
7527             putchar_unlocked ('\n');
7528         }
7529     }
7530 }
7531
7532
7533 /* Callback for printing global names.  */
7534 static int
7535 print_pubnames (Dwarf *dbg __attribute__ ((unused)), Dwarf_Global *global,
7536                 void *arg)
7537 {
7538   int *np = (int *) arg;
7539
7540   printf (gettext (" [%5d] DIE offset: %6" PRId64
7541                    ", CU DIE offset: %6" PRId64 ", name: %s\n"),
7542           (*np)++, global->die_offset, global->cu_offset, global->name);
7543
7544   return 0;
7545 }
7546
7547
7548 /* Print the known exported symbols in the DWARF section '.debug_pubnames'.  */
7549 static void
7550 print_debug_pubnames_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
7551                               Ebl *ebl, GElf_Ehdr *ehdr,
7552                               Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
7553 {
7554   printf (gettext ("\nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
7555           elf_ndxscn (scn), section_name (ebl, ehdr, shdr),
7556           (uint64_t) shdr->sh_offset);
7557
7558   int n = 0;
7559   (void) dwarf_getpubnames (dbg, print_pubnames, &n, 0);
7560 }
7561
7562 /* Print the content of the DWARF string section '.debug_str'.  */
7563 static void
7564 print_debug_str_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
7565                          Ebl *ebl, GElf_Ehdr *ehdr,
7566                          Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
7567 {
7568   const size_t sh_size = (dbg->sectiondata[IDX_debug_str] ?
7569                           dbg->sectiondata[IDX_debug_str]->d_size : 0);
7570
7571   /* Compute floor(log16(shdr->sh_size)).  */
7572   GElf_Addr tmp = sh_size;
7573   int digits = 1;
7574   while (tmp >= 16)
7575     {
7576       ++digits;
7577       tmp >>= 4;
7578     }
7579   digits = MAX (4, digits);
7580
7581   printf (gettext ("\nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"
7582                    " %*s  String\n"),
7583           elf_ndxscn (scn),
7584           section_name (ebl, ehdr, shdr), (uint64_t) shdr->sh_offset,
7585           /* TRANS: the debugstr| prefix makes the string unique.  */
7586           digits + 2, sgettext ("debugstr|Offset"));
7587
7588   Dwarf_Off offset = 0;
7589   while (offset < sh_size)
7590     {
7591       size_t len;
7592       const char *str = dwarf_getstring (dbg, offset, &len);
7593       if (unlikely (str == NULL))
7594         {
7595           printf (gettext (" *** error while reading strings: %s\n"),
7596                   dwarf_errmsg (-1));
7597           break;
7598         }
7599
7600       printf (" [%*" PRIx64 "]  \"%s\"\n", digits, (uint64_t) offset, str);
7601
7602       offset += len + 1;
7603     }
7604 }
7605
7606
7607 /* Print the content of the call frame search table section
7608    '.eh_frame_hdr'.  */
7609 static void
7610 print_debug_frame_hdr_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
7611                                Ebl *ebl __attribute__ ((unused)),
7612                                GElf_Ehdr *ehdr __attribute__ ((unused)),
7613                                Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
7614 {
7615   printf (gettext ("\
7616 \nCall frame search table section [%2zu] '.eh_frame_hdr':\n"),
7617           elf_ndxscn (scn));
7618
7619   Elf_Data *data = elf_rawdata (scn, NULL);
7620
7621   if (unlikely (data == NULL))
7622     {
7623       error (0, 0, gettext ("cannot get %s content: %s"),
7624              ".eh_frame_hdr", elf_errmsg (-1));
7625       return;
7626     }
7627
7628   const unsigned char *readp = data->d_buf;
7629   const unsigned char *const dataend = ((unsigned char *) data->d_buf
7630                                         + data->d_size);
7631
7632   if (unlikely (readp + 4 > dataend))
7633     {
7634     invalid_data:
7635       error (0, 0, gettext ("invalid data"));
7636       return;
7637     }
7638
7639   unsigned int version = *readp++;
7640   unsigned int eh_frame_ptr_enc = *readp++;
7641   unsigned int fde_count_enc = *readp++;
7642   unsigned int table_enc = *readp++;
7643
7644   printf (" version:          %u\n"
7645           " eh_frame_ptr_enc: %#x ",
7646           version, eh_frame_ptr_enc);
7647   print_encoding_base ("", eh_frame_ptr_enc);
7648   printf (" fde_count_enc:    %#x ", fde_count_enc);
7649   print_encoding_base ("", fde_count_enc);
7650   printf (" table_enc:        %#x ", table_enc);
7651   print_encoding_base ("", table_enc);
7652
7653   uint64_t eh_frame_ptr = 0;
7654   if (eh_frame_ptr_enc != DW_EH_PE_omit)
7655     {
7656       readp = read_encoded (eh_frame_ptr_enc, readp, dataend, &eh_frame_ptr,
7657                             dbg);
7658       if (unlikely (readp == NULL))
7659         goto invalid_data;
7660
7661       printf (" eh_frame_ptr:     %#" PRIx64, eh_frame_ptr);
7662       if ((eh_frame_ptr_enc & 0x70) == DW_EH_PE_pcrel)
7663         printf (" (offset: %#" PRIx64 ")",
7664                 /* +4 because of the 4 byte header of the section.  */
7665                 (uint64_t) shdr->sh_offset + 4 + eh_frame_ptr);
7666
7667       putchar_unlocked ('\n');
7668     }
7669
7670   uint64_t fde_count = 0;
7671   if (fde_count_enc != DW_EH_PE_omit)
7672     {
7673       readp = read_encoded (fde_count_enc, readp, dataend, &fde_count, dbg);
7674       if (unlikely (readp == NULL))
7675         goto invalid_data;
7676
7677       printf (" fde_count:        %" PRIu64 "\n", fde_count);
7678     }
7679
7680   if (fde_count == 0 || table_enc == DW_EH_PE_omit)
7681     return;
7682
7683   puts (" Table:");
7684
7685   /* Optimize for the most common case.  */
7686   if (table_enc == (DW_EH_PE_datarel | DW_EH_PE_sdata4))
7687     while (fde_count > 0 && readp + 8 <= dataend)
7688       {
7689         int32_t initial_location = read_4sbyte_unaligned_inc (dbg, readp);
7690         uint64_t initial_offset = ((uint64_t) shdr->sh_offset
7691                                    + (int64_t) initial_location);
7692         int32_t address = read_4sbyte_unaligned_inc (dbg, readp);
7693         // XXX Possibly print symbol name or section offset for initial_offset
7694         printf ("  %#" PRIx32 " (offset: %#6" PRIx64 ") -> %#" PRIx32
7695                 " fde=[%6" PRIx64 "]\n",
7696                 initial_location, initial_offset,
7697                 address, address - (eh_frame_ptr + 4));
7698       }
7699   else
7700     while (0 && readp < dataend)
7701       {
7702
7703       }
7704 }
7705
7706
7707 /* Print the content of the exception handling table section
7708    '.eh_frame_hdr'.  */
7709 static void
7710 print_debug_exception_table (Dwfl_Module *dwflmod __attribute__ ((unused)),
7711                              Ebl *ebl __attribute__ ((unused)),
7712                              GElf_Ehdr *ehdr __attribute__ ((unused)),
7713                              Elf_Scn *scn,
7714                              GElf_Shdr *shdr __attribute__ ((unused)),
7715                              Dwarf *dbg __attribute__ ((unused)))
7716 {
7717   printf (gettext ("\
7718 \nException handling table section [%2zu] '.gcc_except_table':\n"),
7719           elf_ndxscn (scn));
7720
7721   Elf_Data *data = elf_rawdata (scn, NULL);
7722
7723   if (unlikely (data == NULL))
7724     {
7725       error (0, 0, gettext ("cannot get %s content: %s"),
7726              ".gcc_except_table", elf_errmsg (-1));
7727       return;
7728     }
7729
7730   const unsigned char *readp = data->d_buf;
7731   const unsigned char *const dataend = readp + data->d_size;
7732
7733   if (unlikely (readp + 1 > dataend))
7734     {
7735     invalid_data:
7736       error (0, 0, gettext ("invalid data"));
7737       return;
7738     }
7739   unsigned int lpstart_encoding = *readp++;
7740   printf (gettext (" LPStart encoding:    %#x "), lpstart_encoding);
7741   print_encoding_base ("", lpstart_encoding);
7742   if (lpstart_encoding != DW_EH_PE_omit)
7743     {
7744       uint64_t lpstart;
7745       readp = read_encoded (lpstart_encoding, readp, dataend, &lpstart, dbg);
7746       printf (" LPStart:             %#" PRIx64 "\n", lpstart);
7747     }
7748
7749   if (unlikely (readp + 1 > dataend))
7750     goto invalid_data;
7751   unsigned int ttype_encoding = *readp++;
7752   printf (gettext (" TType encoding:      %#x "), ttype_encoding);
7753   print_encoding_base ("", ttype_encoding);
7754   const unsigned char *ttype_base = NULL;
7755   if (ttype_encoding != DW_EH_PE_omit)
7756     {
7757       unsigned int ttype_base_offset;
7758       get_uleb128 (ttype_base_offset, readp, dataend);
7759       printf (" TType base offset:   %#x\n", ttype_base_offset);
7760       if ((size_t) (dataend - readp) > ttype_base_offset)
7761         ttype_base = readp + ttype_base_offset;
7762     }
7763
7764   if (unlikely (readp + 1 > dataend))
7765     goto invalid_data;
7766   unsigned int call_site_encoding = *readp++;
7767   printf (gettext (" Call site encoding:  %#x "), call_site_encoding);
7768   print_encoding_base ("", call_site_encoding);
7769   unsigned int call_site_table_len;
7770   get_uleb128 (call_site_table_len, readp, dataend);
7771
7772   const unsigned char *const action_table = readp + call_site_table_len;
7773   if (unlikely (action_table > dataend))
7774     goto invalid_data;
7775   unsigned int u = 0;
7776   unsigned int max_action = 0;
7777   while (readp < action_table)
7778     {
7779       if (u == 0)
7780         puts (gettext ("\n Call site table:"));
7781
7782       uint64_t call_site_start;
7783       readp = read_encoded (call_site_encoding, readp, dataend,
7784                             &call_site_start, dbg);
7785       uint64_t call_site_length;
7786       readp = read_encoded (call_site_encoding, readp, dataend,
7787                             &call_site_length, dbg);
7788       uint64_t landing_pad;
7789       readp = read_encoded (call_site_encoding, readp, dataend,
7790                             &landing_pad, dbg);
7791       unsigned int action;
7792       get_uleb128 (action, readp, dataend);
7793       max_action = MAX (action, max_action);
7794       printf (gettext (" [%4u] Call site start:   %#" PRIx64 "\n"
7795                        "        Call site length:  %" PRIu64 "\n"
7796                        "        Landing pad:       %#" PRIx64 "\n"
7797                        "        Action:            %u\n"),
7798               u++, call_site_start, call_site_length, landing_pad, action);
7799     }
7800   if (readp != action_table)
7801     goto invalid_data;
7802
7803   unsigned int max_ar_filter = 0;
7804   if (max_action > 0)
7805     {
7806       puts ("\n Action table:");
7807
7808       if ((size_t) (dataend - action_table) < max_action + 1)
7809         {
7810           fputs (gettext ("   <INVALID DATA>\n"), stdout);
7811           return;
7812         }
7813
7814       const unsigned char *const action_table_end
7815         = action_table + max_action + 1;
7816
7817       u = 0;
7818       do
7819         {
7820           int ar_filter;
7821           get_sleb128 (ar_filter, readp, action_table_end);
7822           if (ar_filter > 0 && (unsigned int) ar_filter > max_ar_filter)
7823             max_ar_filter = ar_filter;
7824           int ar_disp;
7825           get_sleb128 (ar_disp, readp, action_table_end);
7826
7827           printf (" [%4u] ar_filter:  % d\n"
7828                   "        ar_disp:    % -5d",
7829                   u, ar_filter, ar_disp);
7830           if (abs (ar_disp) & 1)
7831             printf (" -> [%4u]\n", u + (ar_disp + 1) / 2);
7832           else if (ar_disp != 0)
7833             puts (" -> ???");
7834           else
7835             putchar_unlocked ('\n');
7836           ++u;
7837         }
7838       while (readp < action_table_end);
7839     }
7840
7841   if (max_ar_filter > 0 && ttype_base != NULL)
7842     {
7843       puts ("\n TType table:");
7844
7845       // XXX Not *4, size of encoding;
7846       switch (ttype_encoding & 7)
7847         {
7848         case DW_EH_PE_udata2:
7849         case DW_EH_PE_sdata2:
7850           readp = ttype_base - max_ar_filter * 2;
7851           break;
7852         case DW_EH_PE_udata4:
7853         case DW_EH_PE_sdata4:
7854           readp = ttype_base - max_ar_filter * 4;
7855           break;
7856         case DW_EH_PE_udata8:
7857         case DW_EH_PE_sdata8:
7858           readp = ttype_base - max_ar_filter * 8;
7859           break;
7860         default:
7861           error (1, 0, gettext ("invalid TType encoding"));
7862         }
7863
7864       do
7865         {
7866           uint64_t ttype;
7867           readp = read_encoded (ttype_encoding, readp, ttype_base, &ttype,
7868                                 dbg);
7869           printf (" [%4u] %#" PRIx64 "\n", max_ar_filter--, ttype);
7870         }
7871       while (readp < ttype_base);
7872     }
7873 }
7874
7875 /* Print the content of the '.gdb_index' section.
7876    http://sourceware.org/gdb/current/onlinedocs/gdb/Index-Section-Format.html
7877 */
7878 static void
7879 print_gdb_index_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
7880                          Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
7881 {
7882   printf (gettext ("\nGDB section [%2zu] '%s' at offset %#" PRIx64
7883                    " contains %" PRId64 " bytes :\n"),
7884           elf_ndxscn (scn), section_name (ebl, ehdr, shdr),
7885           (uint64_t) shdr->sh_offset, (uint64_t) shdr->sh_size);
7886
7887   Elf_Data *data = elf_rawdata (scn, NULL);
7888
7889   if (unlikely (data == NULL))
7890     {
7891       error (0, 0, gettext ("cannot get %s content: %s"),
7892              ".gdb_index", elf_errmsg (-1));
7893       return;
7894     }
7895
7896   // .gdb_index is always in little endian.
7897   Dwarf dummy_dbg = { .other_byte_order = MY_ELFDATA != ELFDATA2LSB };
7898   dbg = &dummy_dbg;
7899
7900   const unsigned char *readp = data->d_buf;
7901   const unsigned char *const dataend = readp + data->d_size;
7902
7903   if (unlikely (readp + 4 > dataend))
7904     {
7905     invalid_data:
7906       error (0, 0, gettext ("invalid data"));
7907       return;
7908     }
7909
7910   int32_t vers = read_4ubyte_unaligned (dbg, readp);
7911   printf (gettext (" Version:         %" PRId32 "\n"), vers);
7912
7913   // The only difference between version 4 and version 5 is the
7914   // hash used for generating the table.  Version 6 contains symbols
7915   // for inlined functions, older versions didn't.  Version 7 adds
7916   // symbol kinds.  Version 8 just indicates that it correctly includes
7917   // TUs for symbols.
7918   if (vers < 4 || vers > 8)
7919     {
7920       printf (gettext ("  unknown version, cannot parse section\n"));
7921       return;
7922     }
7923
7924   readp += 4;
7925   if (unlikely (readp + 4 > dataend))
7926     goto invalid_data;
7927
7928   uint32_t cu_off = read_4ubyte_unaligned (dbg, readp);
7929   printf (gettext (" CU offset:       %#" PRIx32 "\n"), cu_off);
7930
7931   readp += 4;
7932   if (unlikely (readp + 4 > dataend))
7933     goto invalid_data;
7934
7935   uint32_t tu_off = read_4ubyte_unaligned (dbg, readp);
7936   printf (gettext (" TU offset:       %#" PRIx32 "\n"), tu_off);
7937
7938   readp += 4;
7939   if (unlikely (readp + 4 > dataend))
7940     goto invalid_data;
7941
7942   uint32_t addr_off = read_4ubyte_unaligned (dbg, readp);
7943   printf (gettext (" address offset:  %#" PRIx32 "\n"), addr_off);
7944
7945   readp += 4;
7946   if (unlikely (readp + 4 > dataend))
7947     goto invalid_data;
7948
7949   uint32_t sym_off = read_4ubyte_unaligned (dbg, readp);
7950   printf (gettext (" symbol offset:   %#" PRIx32 "\n"), sym_off);
7951
7952   readp += 4;
7953   if (unlikely (readp + 4 > dataend))
7954     goto invalid_data;
7955
7956   uint32_t const_off = read_4ubyte_unaligned (dbg, readp);
7957   printf (gettext (" constant offset: %#" PRIx32 "\n"), const_off);
7958
7959   readp = data->d_buf + cu_off;
7960
7961   const unsigned char *nextp = data->d_buf + tu_off;
7962   size_t cu_nr = (nextp - readp) / 16;
7963
7964   printf (gettext ("\n CU list at offset %#" PRIx32
7965                    " contains %zu entries:\n"),
7966           cu_off, cu_nr);
7967
7968   size_t n = 0;
7969   while (readp + 16 <= dataend && n < cu_nr)
7970     {
7971       uint64_t off = read_8ubyte_unaligned (dbg, readp);
7972       readp += 8;
7973
7974       uint64_t len = read_8ubyte_unaligned (dbg, readp);
7975       readp += 8;
7976
7977       printf (" [%4zu] start: %0#8" PRIx64
7978               ", length: %5" PRIu64 "\n", n, off, len);
7979       n++;
7980     }
7981
7982   readp = data->d_buf + tu_off;
7983   nextp = data->d_buf + addr_off;
7984   size_t tu_nr = (nextp - readp) / 24;
7985
7986   printf (gettext ("\n TU list at offset %#" PRIx32
7987                    " contains %zu entries:\n"),
7988           tu_off, tu_nr);
7989
7990   n = 0;
7991   while (readp + 24 <= dataend && n < tu_nr)
7992     {
7993       uint64_t off = read_8ubyte_unaligned (dbg, readp);
7994       readp += 8;
7995
7996       uint64_t type = read_8ubyte_unaligned (dbg, readp);
7997       readp += 8;
7998
7999       uint64_t sig = read_8ubyte_unaligned (dbg, readp);
8000       readp += 8;
8001
8002       printf (" [%4zu] CU offset: %5" PRId64
8003               ", type offset: %5" PRId64
8004               ", signature: %0#8" PRIx64 "\n", n, off, type, sig);
8005       n++;
8006     }
8007
8008   readp = data->d_buf + addr_off;
8009   nextp = data->d_buf + sym_off;
8010   size_t addr_nr = (nextp - readp) / 20;
8011
8012   printf (gettext ("\n Address list at offset %#" PRIx32
8013                    " contains %zu entries:\n"),
8014           addr_off, addr_nr);
8015
8016   n = 0;
8017   while (readp + 20 <= dataend && n < addr_nr)
8018     {
8019       uint64_t low = read_8ubyte_unaligned (dbg, readp);
8020       readp += 8;
8021
8022       uint64_t high = read_8ubyte_unaligned (dbg, readp);
8023       readp += 8;
8024
8025       uint32_t idx = read_4ubyte_unaligned (dbg, readp);
8026       readp += 4;
8027
8028       char *l = format_dwarf_addr (dwflmod, 8, low, low);
8029       char *h = format_dwarf_addr (dwflmod, 8, high - 1, high);
8030       printf (" [%4zu] %s..%s, CU index: %5" PRId32 "\n",
8031               n, l, h, idx);
8032       free (l);
8033       free (h);
8034       n++;
8035     }
8036
8037   readp = data->d_buf + sym_off;
8038   nextp = data->d_buf + const_off;
8039   size_t sym_nr = (nextp - readp) / 8;
8040
8041   printf (gettext ("\n Symbol table at offset %#" PRIx32
8042                    " contains %zu slots:\n"),
8043           addr_off, sym_nr);
8044
8045   n = 0;
8046   while (readp + 8 <= dataend && n < sym_nr)
8047     {
8048       uint32_t name = read_4ubyte_unaligned (dbg, readp);
8049       readp += 4;
8050
8051       uint32_t vector = read_4ubyte_unaligned (dbg, readp);
8052       readp += 4;
8053
8054       if (name != 0 || vector != 0)
8055         {
8056           const unsigned char *sym = data->d_buf + const_off + name;
8057           if (unlikely (sym > dataend
8058                         || memchr (sym, '\0', dataend - sym) == NULL))
8059             goto invalid_data;
8060
8061           printf (" [%4zu] symbol: %s, CUs: ", n, sym);
8062
8063           const unsigned char *readcus = data->d_buf + const_off + vector;
8064           if (unlikely (readcus + 4 > dataend))
8065             goto invalid_data;
8066           uint32_t cus = read_4ubyte_unaligned (dbg, readcus);
8067           while (cus--)
8068             {
8069               uint32_t cu_kind, cu, kind;
8070               bool is_static;
8071               readcus += 4;
8072               if (unlikely (readcus + 4 > dataend))
8073                 goto invalid_data;
8074               cu_kind = read_4ubyte_unaligned (dbg, readcus);
8075               cu = cu_kind & ((1 << 24) - 1);
8076               kind = (cu_kind >> 28) & 7;
8077               is_static = cu_kind & (1U << 31);
8078               if (cu > cu_nr - 1)
8079                 printf ("%" PRId32 "T", cu - (uint32_t) cu_nr);
8080               else
8081                 printf ("%" PRId32, cu);
8082               if (kind != 0)
8083                 {
8084                   printf (" (");
8085                   switch (kind)
8086                     {
8087                     case 1:
8088                       printf ("type");
8089                       break;
8090                     case 2:
8091                       printf ("var");
8092                       break;
8093                     case 3:
8094                       printf ("func");
8095                       break;
8096                     case 4:
8097                       printf ("other");
8098                       break;
8099                     default:
8100                       printf ("unknown-0x%" PRIx32, kind);
8101                       break;
8102                     }
8103                   printf (":%c)", (is_static ? 'S' : 'G'));
8104                 }
8105               if (cus > 0)
8106                 printf (", ");
8107             }
8108           printf ("\n");
8109         }
8110       n++;
8111     }
8112 }
8113
8114 static void
8115 print_debug (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr)
8116 {
8117   /* Before we start the real work get a debug context descriptor.  */
8118   Dwarf_Addr dwbias;
8119   Dwarf *dbg = dwfl_module_getdwarf (dwflmod, &dwbias);
8120   Dwarf dummy_dbg =
8121     {
8122       .elf = ebl->elf,
8123       .other_byte_order = MY_ELFDATA != ehdr->e_ident[EI_DATA]
8124     };
8125   if (dbg == NULL)
8126     {
8127       if ((print_debug_sections & ~section_exception) != 0)
8128         error (0, 0, gettext ("cannot get debug context descriptor: %s"),
8129                dwfl_errmsg (-1));
8130       if ((print_debug_sections & section_exception) == 0)
8131         return;
8132       dbg = &dummy_dbg;
8133     }
8134
8135   /* Get the section header string table index.  */
8136   size_t shstrndx;
8137   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
8138     error (EXIT_FAILURE, 0,
8139            gettext ("cannot get section header string table index"));
8140
8141   /* Look through all the sections for the debugging sections to print.  */
8142   Elf_Scn *scn = NULL;
8143   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
8144     {
8145       GElf_Shdr shdr_mem;
8146       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
8147
8148       if (shdr != NULL && shdr->sh_type == SHT_PROGBITS)
8149         {
8150           static const struct
8151           {
8152             const char *name;
8153             enum section_e bitmask;
8154             void (*fp) (Dwfl_Module *, Ebl *,
8155                         GElf_Ehdr *, Elf_Scn *, GElf_Shdr *, Dwarf *);
8156           } debug_sections[] =
8157             {
8158 #define NEW_SECTION(name) \
8159               { ".debug_" #name, section_##name, print_debug_##name##_section }
8160               NEW_SECTION (abbrev),
8161               NEW_SECTION (aranges),
8162               NEW_SECTION (frame),
8163               NEW_SECTION (info),
8164               NEW_SECTION (types),
8165               NEW_SECTION (line),
8166               NEW_SECTION (loc),
8167               NEW_SECTION (pubnames),
8168               NEW_SECTION (str),
8169               NEW_SECTION (macinfo),
8170               NEW_SECTION (macro),
8171               NEW_SECTION (ranges),
8172               { ".eh_frame", section_frame | section_exception,
8173                 print_debug_frame_section },
8174               { ".eh_frame_hdr", section_frame | section_exception,
8175                 print_debug_frame_hdr_section },
8176               { ".gcc_except_table", section_frame | section_exception,
8177                 print_debug_exception_table },
8178               { ".gdb_index", section_gdb_index, print_gdb_index_section }
8179             };
8180           const int ndebug_sections = (sizeof (debug_sections)
8181                                        / sizeof (debug_sections[0]));
8182           const char *name = elf_strptr (ebl->elf, shstrndx,
8183                                          shdr->sh_name);
8184           if (name == NULL)
8185             continue;
8186
8187           int n;
8188           for (n = 0; n < ndebug_sections; ++n)
8189             if (strcmp (name, debug_sections[n].name) == 0
8190 #if USE_ZLIB
8191                 || (name[0] == '.' && name[1] == 'z'
8192                     && debug_sections[n].name[1] == 'd'
8193                     && strcmp (&name[2], &debug_sections[n].name[1]) == 0)
8194 #endif
8195                 )
8196               {
8197                 if ((print_debug_sections | implicit_debug_sections)
8198                     & debug_sections[n].bitmask)
8199                   debug_sections[n].fp (dwflmod, ebl, ehdr, scn, shdr, dbg);
8200                 break;
8201               }
8202         }
8203     }
8204
8205   reset_listptr (&known_loclistptr);
8206   reset_listptr (&known_rangelistptr);
8207 }
8208
8209
8210 #define ITEM_INDENT             4
8211 #define WRAP_COLUMN             75
8212
8213 /* Print "NAME: FORMAT", wrapping when output text would make the line
8214    exceed WRAP_COLUMN.  Unpadded numbers look better for the core items
8215    but this function is also used for registers which should be printed
8216    aligned.  Fortunately registers output uses fixed fields width (such
8217    as %11d) for the alignment.
8218
8219    Line breaks should not depend on the particular values although that
8220    may happen in some cases of the core items.  */
8221
8222 static unsigned int
8223 __attribute__ ((format (printf, 6, 7)))
8224 print_core_item (unsigned int colno, char sep, unsigned int wrap,
8225                  size_t name_width, const char *name, const char *format, ...)
8226 {
8227   size_t len = strlen (name);
8228   if (name_width < len)
8229     name_width = len;
8230
8231   char *out;
8232   va_list ap;
8233   va_start (ap, format);
8234   int out_len = vasprintf (&out, format, ap);
8235   va_end (ap);
8236   if (out_len == -1)
8237     error (EXIT_FAILURE, 0, _("memory exhausted"));
8238
8239   size_t n = name_width + sizeof ": " - 1 + out_len;
8240
8241   if (colno == 0)
8242     {
8243       printf ("%*s", ITEM_INDENT, "");
8244       colno = ITEM_INDENT + n;
8245     }
8246   else if (colno + 2 + n < wrap)
8247     {
8248       printf ("%c ", sep);
8249       colno += 2 + n;
8250     }
8251   else
8252     {
8253       printf ("\n%*s", ITEM_INDENT, "");
8254       colno = ITEM_INDENT + n;
8255     }
8256
8257   printf ("%s: %*s%s", name, (int) (name_width - len), "", out);
8258
8259   free (out);
8260
8261   return colno;
8262 }
8263
8264 static const void *
8265 convert (Elf *core, Elf_Type type, uint_fast16_t count,
8266          void *value, const void *data, size_t size)
8267 {
8268   Elf_Data valuedata =
8269     {
8270       .d_type = type,
8271       .d_buf = value,
8272       .d_size = size ?: gelf_fsize (core, type, count, EV_CURRENT),
8273       .d_version = EV_CURRENT,
8274     };
8275   Elf_Data indata =
8276     {
8277       .d_type = type,
8278       .d_buf = (void *) data,
8279       .d_size = valuedata.d_size,
8280       .d_version = EV_CURRENT,
8281     };
8282
8283   Elf_Data *d = (gelf_getclass (core) == ELFCLASS32
8284                  ? elf32_xlatetom : elf64_xlatetom)
8285     (&valuedata, &indata, elf_getident (core, NULL)[EI_DATA]);
8286   if (d == NULL)
8287     error (EXIT_FAILURE, 0,
8288            gettext ("cannot convert core note data: %s"), elf_errmsg (-1));
8289
8290   return data + indata.d_size;
8291 }
8292
8293 typedef uint8_t GElf_Byte;
8294
8295 static unsigned int
8296 handle_core_item (Elf *core, const Ebl_Core_Item *item, const void *desc,
8297                   unsigned int colno, size_t *repeated_size)
8298 {
8299   uint_fast16_t count = item->count ?: 1;
8300
8301 #define TYPES                                                                 \
8302   DO_TYPE (BYTE, Byte, "0x%.2" PRIx8, "%" PRId8);                             \
8303   DO_TYPE (HALF, Half, "0x%.4" PRIx16, "%" PRId16);                           \
8304   DO_TYPE (WORD, Word, "0x%.8" PRIx32, "%" PRId32);                           \
8305   DO_TYPE (SWORD, Sword, "%" PRId32, "%" PRId32);                             \
8306   DO_TYPE (XWORD, Xword, "0x%.16" PRIx64, "%" PRId64);                        \
8307   DO_TYPE (SXWORD, Sxword, "%" PRId64, "%" PRId64)
8308
8309 #define DO_TYPE(NAME, Name, hex, dec) GElf_##Name Name[count]
8310   union { TYPES; } value;
8311 #undef DO_TYPE
8312
8313   void *data = &value;
8314   size_t size = gelf_fsize (core, item->type, count, EV_CURRENT);
8315   size_t convsize = size;
8316   if (repeated_size != NULL)
8317     {
8318       if (*repeated_size > size && (item->format == 'b' || item->format == 'B'))
8319         {
8320           data = alloca (*repeated_size);
8321           count *= *repeated_size / size;
8322           convsize = count * size;
8323           *repeated_size -= convsize;
8324         }
8325       else if (item->count != 0 || item->format != '\n')
8326         *repeated_size -= size;
8327     }
8328
8329   convert (core, item->type, count, data, desc + item->offset, convsize);
8330
8331   Elf_Type type = item->type;
8332   if (type == ELF_T_ADDR)
8333     type = gelf_getclass (core) == ELFCLASS32 ? ELF_T_WORD : ELF_T_XWORD;
8334
8335   switch (item->format)
8336     {
8337     case 'd':
8338       assert (count == 1);
8339       switch (type)
8340         {
8341 #define DO_TYPE(NAME, Name, hex, dec)                                         \
8342           case ELF_T_##NAME:                                                  \
8343             colno = print_core_item (colno, ',', WRAP_COLUMN,                 \
8344                                      0, item->name, dec, value.Name[0]); \
8345             break
8346           TYPES;
8347 #undef DO_TYPE
8348         default:
8349           abort ();
8350         }
8351       break;
8352
8353     case 'x':
8354       assert (count == 1);
8355       switch (type)
8356         {
8357 #define DO_TYPE(NAME, Name, hex, dec)                                         \
8358           case ELF_T_##NAME:                                                  \
8359             colno = print_core_item (colno, ',', WRAP_COLUMN,                 \
8360                                      0, item->name, hex, value.Name[0]);      \
8361             break
8362           TYPES;
8363 #undef DO_TYPE
8364         default:
8365           abort ();
8366         }
8367       break;
8368
8369     case 'b':
8370     case 'B':
8371       assert (size % sizeof (unsigned int) == 0);
8372       unsigned int nbits = count * size * 8;
8373       unsigned int pop = 0;
8374       for (const unsigned int *i = data; (void *) i < data + count * size; ++i)
8375         pop += __builtin_popcount (*i);
8376       bool negate = pop > nbits / 2;
8377       const unsigned int bias = item->format == 'b';
8378
8379       {
8380         char printed[(negate ? nbits - pop : pop) * 16 + 1];
8381         char *p = printed;
8382         *p = '\0';
8383
8384         if (BYTE_ORDER != LITTLE_ENDIAN && size > sizeof (unsigned int))
8385           {
8386             assert (size == sizeof (unsigned int) * 2);
8387             for (unsigned int *i = data;
8388                  (void *) i < data + count * size; i += 2)
8389               {
8390                 unsigned int w = i[1];
8391                 i[1] = i[0];
8392                 i[0] = w;
8393               }
8394           }
8395
8396         unsigned int lastbit = 0;
8397         unsigned int run = 0;
8398         for (const unsigned int *i = data;
8399              (void *) i < data + count * size; ++i)
8400           {
8401             unsigned int bit = ((void *) i - data) * 8;
8402             unsigned int w = negate ? ~*i : *i;
8403             while (w != 0)
8404               {
8405                 int n = ffs (w);
8406                 w >>= n;
8407                 bit += n;
8408
8409                 if (lastbit != 0 && lastbit + 1 == bit)
8410                   ++run;
8411                 else
8412                   {
8413                     if (lastbit == 0)
8414                       p += sprintf (p, "%u", bit - bias);
8415                     else if (run == 0)
8416                       p += sprintf (p, ",%u", bit - bias);
8417                     else
8418                       p += sprintf (p, "-%u,%u", lastbit - bias, bit - bias);
8419                     run = 0;
8420                   }
8421
8422                 lastbit = bit;
8423               }
8424           }
8425         if (lastbit > 0 && run > 0 && lastbit + 1 != nbits)
8426           p += sprintf (p, "-%u", lastbit - bias);
8427
8428         colno = print_core_item (colno, ',', WRAP_COLUMN, 0, item->name,
8429                                  negate ? "~<%s>" : "<%s>", printed);
8430       }
8431       break;
8432
8433     case 'T':
8434     case (char) ('T'|0x80):
8435       assert (count == 2);
8436       Dwarf_Word sec;
8437       Dwarf_Word usec;
8438       switch (type)
8439         {
8440 #define DO_TYPE(NAME, Name, hex, dec)                                         \
8441           case ELF_T_##NAME:                                                  \
8442             sec = value.Name[0];                                              \
8443             usec = value.Name[1];                                             \
8444             break
8445           TYPES;
8446 #undef DO_TYPE
8447         default:
8448           abort ();
8449         }
8450       if (unlikely (item->format == (char) ('T'|0x80)))
8451         {
8452           /* This is a hack for an ill-considered 64-bit ABI where
8453              tv_usec is actually a 32-bit field with 32 bits of padding
8454              rounding out struct timeval.  We've already converted it as
8455              a 64-bit field.  For little-endian, this just means the
8456              high half is the padding; it's presumably zero, but should
8457              be ignored anyway.  For big-endian, it means the 32-bit
8458              field went into the high half of USEC.  */
8459           GElf_Ehdr ehdr_mem;
8460           GElf_Ehdr *ehdr = gelf_getehdr (core, &ehdr_mem);
8461           if (likely (ehdr->e_ident[EI_DATA] == ELFDATA2MSB))
8462             usec >>= 32;
8463           else
8464             usec &= UINT32_MAX;
8465         }
8466       colno = print_core_item (colno, ',', WRAP_COLUMN, 0, item->name,
8467                                "%" PRIu64 ".%.6" PRIu64, sec, usec);
8468       break;
8469
8470     case 'c':
8471       assert (count == 1);
8472       colno = print_core_item (colno, ',', WRAP_COLUMN, 0, item->name,
8473                                "%c", value.Byte[0]);
8474       break;
8475
8476     case 's':
8477       colno = print_core_item (colno, ',', WRAP_COLUMN, 0, item->name,
8478                                "%.*s", (int) count, value.Byte);
8479       break;
8480
8481     case '\n':
8482       /* This is a list of strings separated by '\n'.  */
8483       assert (item->count == 0);
8484       assert (repeated_size != NULL);
8485       assert (item->name == NULL);
8486       if (unlikely (item->offset >= *repeated_size))
8487         break;
8488
8489       const char *s = desc + item->offset;
8490       size = *repeated_size - item->offset;
8491       *repeated_size = 0;
8492       while (size > 0)
8493         {
8494           const char *eol = memchr (s, '\n', size);
8495           int len = size;
8496           if (eol != NULL)
8497             len = eol - s;
8498           printf ("%*s%.*s\n", ITEM_INDENT, "", len, s);
8499           if (eol == NULL)
8500             break;
8501           size -= eol + 1 - s;
8502           s = eol + 1;
8503         }
8504
8505       colno = WRAP_COLUMN;
8506       break;
8507
8508     case 'h':
8509       break;
8510
8511     default:
8512       error (0, 0, "XXX not handling format '%c' for %s",
8513              item->format, item->name);
8514       break;
8515     }
8516
8517 #undef TYPES
8518
8519   return colno;
8520 }
8521
8522
8523 /* Sort items by group, and by layout offset within each group.  */
8524 static int
8525 compare_core_items (const void *a, const void *b)
8526 {
8527   const Ebl_Core_Item *const *p1 = a;
8528   const Ebl_Core_Item *const *p2 = b;
8529   const Ebl_Core_Item *item1 = *p1;
8530   const Ebl_Core_Item *item2 = *p2;
8531
8532   return ((item1->group == item2->group ? 0
8533            : strcmp (item1->group, item2->group))
8534           ?: (int) item1->offset - (int) item2->offset);
8535 }
8536
8537 /* Sort item groups by layout offset of the first item in the group.  */
8538 static int
8539 compare_core_item_groups (const void *a, const void *b)
8540 {
8541   const Ebl_Core_Item *const *const *p1 = a;
8542   const Ebl_Core_Item *const *const *p2 = b;
8543   const Ebl_Core_Item *const *group1 = *p1;
8544   const Ebl_Core_Item *const *group2 = *p2;
8545   const Ebl_Core_Item *item1 = *group1;
8546   const Ebl_Core_Item *item2 = *group2;
8547
8548   return (int) item1->offset - (int) item2->offset;
8549 }
8550
8551 static unsigned int
8552 handle_core_items (Elf *core, const void *desc, size_t descsz,
8553                    const Ebl_Core_Item *items, size_t nitems)
8554 {
8555   if (nitems == 0)
8556     return 0;
8557   unsigned int colno = 0;
8558
8559   /* FORMAT '\n' makes sense to be present only as a single item as it
8560      processes all the data of a note.  FORMATs 'b' and 'B' have a special case
8561      if present as a single item but they can be also processed with other
8562      items below.  */
8563   if (nitems == 1 && (items[0].format == '\n' || items[0].format == 'b'
8564                       || items[0].format == 'B'))
8565     {
8566       assert (items[0].offset == 0);
8567       size_t size = descsz;
8568       colno = handle_core_item (core, items, desc, colno, &size);
8569       /* If SIZE is not zero here there is some remaining data.  But we do not
8570          know how to process it anyway.  */
8571       return colno;
8572     }
8573   for (size_t i = 0; i < nitems; ++i)
8574     assert (items[i].format != '\n');
8575
8576   /* Sort to collect the groups together.  */
8577   const Ebl_Core_Item *sorted_items[nitems];
8578   for (size_t i = 0; i < nitems; ++i)
8579     sorted_items[i] = &items[i];
8580   qsort (sorted_items, nitems, sizeof sorted_items[0], &compare_core_items);
8581
8582   /* Collect the unique groups and sort them.  */
8583   const Ebl_Core_Item **groups[nitems];
8584   groups[0] = &sorted_items[0];
8585   size_t ngroups = 1;
8586   for (size_t i = 1; i < nitems; ++i)
8587     if (sorted_items[i]->group != sorted_items[i - 1]->group
8588         && strcmp (sorted_items[i]->group, sorted_items[i - 1]->group))
8589       groups[ngroups++] = &sorted_items[i];
8590   qsort (groups, ngroups, sizeof groups[0], &compare_core_item_groups);
8591
8592   /* Write out all the groups.  */
8593   const void *last = desc;
8594   do
8595     {
8596       for (size_t i = 0; i < ngroups; ++i)
8597         {
8598           for (const Ebl_Core_Item **item = groups[i];
8599                (item < &sorted_items[nitems]
8600                 && ((*item)->group == groups[i][0]->group
8601                     || !strcmp ((*item)->group, groups[i][0]->group)));
8602                ++item)
8603             colno = handle_core_item (core, *item, desc, colno, NULL);
8604
8605           /* Force a line break at the end of the group.  */
8606           colno = WRAP_COLUMN;
8607         }
8608
8609       if (descsz == 0)
8610         break;
8611
8612       /* This set of items consumed a certain amount of the note's data.
8613          If there is more data there, we have another unit of the same size.
8614          Loop to print that out too.  */
8615       const Ebl_Core_Item *item = &items[nitems - 1];
8616       size_t eltsz = item->offset + gelf_fsize (core, item->type,
8617                                                 item->count ?: 1, EV_CURRENT);
8618
8619       int reps = -1;
8620       do
8621         {
8622           ++reps;
8623           desc += eltsz;
8624           descsz -= eltsz;
8625         }
8626       while (descsz >= eltsz && !memcmp (desc, last, eltsz));
8627
8628       if (reps == 1)
8629         {
8630           /* For just one repeat, print it unabridged twice.  */
8631           desc -= eltsz;
8632           descsz += eltsz;
8633         }
8634       else if (reps > 1)
8635         printf (gettext ("\n%*s... <repeats %u more times> ..."),
8636                 ITEM_INDENT, "", reps);
8637
8638       last = desc;
8639     }
8640   while (descsz > 0);
8641
8642   return colno;
8643 }
8644
8645 static unsigned int
8646 handle_bit_registers (const Ebl_Register_Location *regloc, const void *desc,
8647                       unsigned int colno)
8648 {
8649   desc += regloc->offset;
8650
8651   abort ();                     /* XXX */
8652   return colno;
8653 }
8654
8655
8656 static unsigned int
8657 handle_core_register (Ebl *ebl, Elf *core, int maxregname,
8658                       const Ebl_Register_Location *regloc, const void *desc,
8659                       unsigned int colno)
8660 {
8661   if (regloc->bits % 8 != 0)
8662     return handle_bit_registers (regloc, desc, colno);
8663
8664   desc += regloc->offset;
8665
8666   for (int reg = regloc->regno; reg < regloc->regno + regloc->count; ++reg)
8667     {
8668       char name[REGNAMESZ];
8669       int bits;
8670       int type;
8671       register_info (ebl, reg, regloc, name, &bits, &type);
8672
8673 #define TYPES                                                                 \
8674       BITS (8, BYTE, "%4" PRId8, "0x%.2" PRIx8);                              \
8675       BITS (16, HALF, "%6" PRId16, "0x%.4" PRIx16);                           \
8676       BITS (32, WORD, "%11" PRId32, " 0x%.8" PRIx32);                         \
8677       BITS (64, XWORD, "%20" PRId64, "  0x%.16" PRIx64)
8678
8679 #define BITS(bits, xtype, sfmt, ufmt)                           \
8680       uint##bits##_t b##bits; int##bits##_t b##bits##s
8681       union { TYPES; uint64_t b128[2]; } value;
8682 #undef  BITS
8683
8684       switch (type)
8685         {
8686         case DW_ATE_unsigned:
8687         case DW_ATE_signed:
8688         case DW_ATE_address:
8689           switch (bits)
8690             {
8691 #define BITS(bits, xtype, sfmt, ufmt)                                         \
8692             case bits:                                                        \
8693               desc = convert (core, ELF_T_##xtype, 1, &value, desc, 0);       \
8694               if (type == DW_ATE_signed)                                      \
8695                 colno = print_core_item (colno, ' ', WRAP_COLUMN,             \
8696                                          maxregname, name,                    \
8697                                          sfmt, value.b##bits##s);             \
8698               else                                                            \
8699                 colno = print_core_item (colno, ' ', WRAP_COLUMN,             \
8700                                          maxregname, name,                    \
8701                                          ufmt, value.b##bits);                \
8702               break
8703
8704             TYPES;
8705
8706             case 128:
8707               assert (type == DW_ATE_unsigned);
8708               desc = convert (core, ELF_T_XWORD, 2, &value, desc, 0);
8709               int be = elf_getident (core, NULL)[EI_DATA] == ELFDATA2MSB;
8710               colno = print_core_item (colno, ' ', WRAP_COLUMN,
8711                                        maxregname, name,
8712                                        "0x%.16" PRIx64 "%.16" PRIx64,
8713                                        value.b128[!be], value.b128[be]);
8714               break;
8715
8716             default:
8717               abort ();
8718 #undef  BITS
8719             }
8720           break;
8721
8722         default:
8723           /* Print each byte in hex, the whole thing in native byte order.  */
8724           assert (bits % 8 == 0);
8725           const uint8_t *bytes = desc;
8726           desc += bits / 8;
8727           char hex[bits / 4 + 1];
8728           hex[bits / 4] = '\0';
8729           int incr = 1;
8730           if (elf_getident (core, NULL)[EI_DATA] == ELFDATA2LSB)
8731             {
8732               bytes += bits / 8 - 1;
8733               incr = -1;
8734             }
8735           size_t idx = 0;
8736           for (char *h = hex; bits > 0; bits -= 8, idx += incr)
8737             {
8738               *h++ = "0123456789abcdef"[bytes[idx] >> 4];
8739               *h++ = "0123456789abcdef"[bytes[idx] & 0xf];
8740             }
8741           colno = print_core_item (colno, ' ', WRAP_COLUMN,
8742                                    maxregname, name, "0x%s", hex);
8743           break;
8744         }
8745       desc += regloc->pad;
8746
8747 #undef TYPES
8748     }
8749
8750   return colno;
8751 }
8752
8753
8754 struct register_info
8755 {
8756   const Ebl_Register_Location *regloc;
8757   const char *set;
8758   char name[REGNAMESZ];
8759   int regno;
8760   int bits;
8761   int type;
8762 };
8763
8764 static int
8765 register_bitpos (const struct register_info *r)
8766 {
8767   return (r->regloc->offset * 8
8768           + ((r->regno - r->regloc->regno)
8769              * (r->regloc->bits + r->regloc->pad * 8)));
8770 }
8771
8772 static int
8773 compare_sets_by_info (const struct register_info *r1,
8774                       const struct register_info *r2)
8775 {
8776   return ((int) r2->bits - (int) r1->bits
8777           ?: register_bitpos (r1) - register_bitpos (r2));
8778 }
8779
8780 /* Sort registers by set, and by size and layout offset within each set.  */
8781 static int
8782 compare_registers (const void *a, const void *b)
8783 {
8784   const struct register_info *r1 = a;
8785   const struct register_info *r2 = b;
8786
8787   /* Unused elements sort last.  */
8788   if (r1->regloc == NULL)
8789     return r2->regloc == NULL ? 0 : 1;
8790   if (r2->regloc == NULL)
8791     return -1;
8792
8793   return ((r1->set == r2->set ? 0 : strcmp (r1->set, r2->set))
8794           ?: compare_sets_by_info (r1, r2));
8795 }
8796
8797 /* Sort register sets by layout offset of the first register in the set.  */
8798 static int
8799 compare_register_sets (const void *a, const void *b)
8800 {
8801   const struct register_info *const *p1 = a;
8802   const struct register_info *const *p2 = b;
8803   return compare_sets_by_info (*p1, *p2);
8804 }
8805
8806 static unsigned int
8807 handle_core_registers (Ebl *ebl, Elf *core, const void *desc,
8808                        const Ebl_Register_Location *reglocs, size_t nregloc)
8809 {
8810   if (nregloc == 0)
8811     return 0;
8812
8813   ssize_t maxnreg = ebl_register_info (ebl, 0, NULL, 0, NULL, NULL, NULL, NULL);
8814   if (maxnreg <= 0)
8815     {
8816       for (size_t i = 0; i < nregloc; ++i)
8817         if (maxnreg < reglocs[i].regno + reglocs[i].count)
8818           maxnreg = reglocs[i].regno + reglocs[i].count;
8819       assert (maxnreg > 0);
8820     }
8821
8822   struct register_info regs[maxnreg];
8823   memset (regs, 0, sizeof regs);
8824
8825   /* Sort to collect the sets together.  */
8826   int maxreg = 0;
8827   for (size_t i = 0; i < nregloc; ++i)
8828     for (int reg = reglocs[i].regno;
8829          reg < reglocs[i].regno + reglocs[i].count;
8830          ++reg)
8831       {
8832         assert (reg < maxnreg);
8833         if (reg > maxreg)
8834           maxreg = reg;
8835         struct register_info *info = &regs[reg];
8836         info->regloc = &reglocs[i];
8837         info->regno = reg;
8838         info->set = register_info (ebl, reg, &reglocs[i],
8839                                    info->name, &info->bits, &info->type);
8840       }
8841   qsort (regs, maxreg + 1, sizeof regs[0], &compare_registers);
8842
8843   /* Collect the unique sets and sort them.  */
8844   inline bool same_set (const struct register_info *a,
8845                         const struct register_info *b)
8846   {
8847     return (a < &regs[maxnreg] && a->regloc != NULL
8848             && b < &regs[maxnreg] && b->regloc != NULL
8849             && a->bits == b->bits
8850             && (a->set == b->set || !strcmp (a->set, b->set)));
8851   }
8852   struct register_info *sets[maxreg + 1];
8853   sets[0] = &regs[0];
8854   size_t nsets = 1;
8855   for (int i = 1; i <= maxreg; ++i)
8856     if (regs[i].regloc != NULL && !same_set (&regs[i], &regs[i - 1]))
8857       sets[nsets++] = &regs[i];
8858   qsort (sets, nsets, sizeof sets[0], &compare_register_sets);
8859
8860   /* Write out all the sets.  */
8861   unsigned int colno = 0;
8862   for (size_t i = 0; i < nsets; ++i)
8863     {
8864       /* Find the longest name of a register in this set.  */
8865       size_t maxname = 0;
8866       const struct register_info *end;
8867       for (end = sets[i]; same_set (sets[i], end); ++end)
8868         {
8869           size_t len = strlen (end->name);
8870           if (len > maxname)
8871             maxname = len;
8872         }
8873
8874       for (const struct register_info *reg = sets[i];
8875            reg < end;
8876            reg += reg->regloc->count ?: 1)
8877         colno = handle_core_register (ebl, core, maxname,
8878                                       reg->regloc, desc, colno);
8879
8880       /* Force a line break at the end of the group.  */
8881       colno = WRAP_COLUMN;
8882     }
8883
8884   return colno;
8885 }
8886
8887 static void
8888 handle_auxv_note (Ebl *ebl, Elf *core, GElf_Word descsz, GElf_Off desc_pos)
8889 {
8890   Elf_Data *data = elf_getdata_rawchunk (core, desc_pos, descsz, ELF_T_AUXV);
8891   if (data == NULL)
8892   elf_error:
8893     error (EXIT_FAILURE, 0,
8894            gettext ("cannot convert core note data: %s"), elf_errmsg (-1));
8895
8896   const size_t nauxv = descsz / gelf_fsize (core, ELF_T_AUXV, 1, EV_CURRENT);
8897   for (size_t i = 0; i < nauxv; ++i)
8898     {
8899       GElf_auxv_t av_mem;
8900       GElf_auxv_t *av = gelf_getauxv (data, i, &av_mem);
8901       if (av == NULL)
8902         goto elf_error;
8903
8904       const char *name;
8905       const char *fmt;
8906       if (ebl_auxv_info (ebl, av->a_type, &name, &fmt) == 0)
8907         {
8908           /* Unknown type.  */
8909           if (av->a_un.a_val == 0)
8910             printf ("    %" PRIu64 "\n", av->a_type);
8911           else
8912             printf ("    %" PRIu64 ": %#" PRIx64 "\n",
8913                     av->a_type, av->a_un.a_val);
8914         }
8915       else
8916         switch (fmt[0])
8917           {
8918           case '\0':            /* Normally zero.  */
8919             if (av->a_un.a_val == 0)
8920               {
8921                 printf ("    %s\n", name);
8922                 break;
8923               }
8924             /* Fall through */
8925           case 'x':             /* hex */
8926           case 'p':             /* address */
8927           case 's':             /* address of string */
8928             printf ("    %s: %#" PRIx64 "\n", name, av->a_un.a_val);
8929             break;
8930           case 'u':
8931             printf ("    %s: %" PRIu64 "\n", name, av->a_un.a_val);
8932             break;
8933           case 'd':
8934             printf ("    %s: %" PRId64 "\n", name, av->a_un.a_val);
8935             break;
8936
8937           case 'b':
8938             printf ("    %s: %#" PRIx64 "  ", name, av->a_un.a_val);
8939             GElf_Xword bit = 1;
8940             const char *pfx = "<";
8941             for (const char *p = fmt + 1; *p != 0; p = strchr (p, '\0') + 1)
8942               {
8943                 if (av->a_un.a_val & bit)
8944                   {
8945                     printf ("%s%s", pfx, p);
8946                     pfx = " ";
8947                   }
8948                 bit <<= 1;
8949               }
8950             printf (">\n");
8951             break;
8952
8953           default:
8954             abort ();
8955           }
8956     }
8957 }
8958
8959 static bool
8960 buf_has_data (unsigned char const *ptr, unsigned char const *end, size_t sz)
8961 {
8962   return ptr < end && (size_t) (end - ptr) >= sz;
8963 }
8964
8965 static bool
8966 buf_read_int (Elf *core, unsigned char const **ptrp, unsigned char const *end,
8967               int *retp)
8968 {
8969   if (! buf_has_data (*ptrp, end, 4))
8970     return false;
8971
8972   *ptrp = convert (core, ELF_T_WORD, 1, retp, *ptrp, 4);
8973   return true;
8974 }
8975
8976 static bool
8977 buf_read_ulong (Elf *core, unsigned char const **ptrp, unsigned char const *end,
8978                 uint64_t *retp)
8979 {
8980   size_t sz = gelf_fsize (core, ELF_T_ADDR, 1, EV_CURRENT);
8981   if (! buf_has_data (*ptrp, end, sz))
8982     return false;
8983
8984   union
8985   {
8986     uint64_t u64;
8987     uint32_t u32;
8988   } u;
8989
8990   *ptrp = convert (core, ELF_T_ADDR, 1, &u, *ptrp, sz);
8991
8992   if (sz == 4)
8993     *retp = u.u32;
8994   else
8995     *retp = u.u64;
8996   return true;
8997 }
8998
8999 static void
9000 handle_siginfo_note (Elf *core, GElf_Word descsz, GElf_Off desc_pos)
9001 {
9002   Elf_Data *data = elf_getdata_rawchunk (core, desc_pos, descsz, ELF_T_BYTE);
9003   if (data == NULL)
9004     error (EXIT_FAILURE, 0,
9005            gettext ("cannot convert core note data: %s"), elf_errmsg (-1));
9006
9007   unsigned char const *ptr = data->d_buf;
9008   unsigned char const *const end = data->d_buf + data->d_size;
9009
9010   /* Siginfo head is three ints: signal number, error number, origin
9011      code.  */
9012   int si_signo, si_errno, si_code;
9013   if (! buf_read_int (core, &ptr, end, &si_signo)
9014       || ! buf_read_int (core, &ptr, end, &si_errno)
9015       || ! buf_read_int (core, &ptr, end, &si_code))
9016     {
9017     fail:
9018       printf ("    Not enough data in NT_SIGINFO note.\n");
9019       return;
9020     }
9021
9022   /* Next is a pointer-aligned union of structures.  On 64-bit
9023      machines, that implies a word of padding.  */
9024   if (gelf_getclass (core) == ELFCLASS64)
9025     ptr += 4;
9026
9027   printf ("    si_signo: %d, si_errno: %d, si_code: %d\n",
9028           si_signo, si_errno, si_code);
9029
9030   if (si_code > 0)
9031     switch (si_signo)
9032       {
9033       case SIGILL:
9034       case SIGFPE:
9035       case SIGSEGV:
9036       case SIGBUS:
9037         {
9038           uint64_t addr;
9039           if (! buf_read_ulong (core, &ptr, end, &addr))
9040             goto fail;
9041           printf ("    fault address: %#" PRIx64 "\n", addr);
9042           break;
9043         }
9044       default:
9045         ;
9046       }
9047   else if (si_code == SI_USER)
9048     {
9049       int pid, uid;
9050       if (! buf_read_int (core, &ptr, end, &pid)
9051           || ! buf_read_int (core, &ptr, end, &uid))
9052         goto fail;
9053       printf ("    sender PID: %d, sender UID: %d\n", pid, uid);
9054     }
9055 }
9056
9057 static void
9058 handle_file_note (Elf *core, GElf_Word descsz, GElf_Off desc_pos)
9059 {
9060   Elf_Data *data = elf_getdata_rawchunk (core, desc_pos, descsz, ELF_T_BYTE);
9061   if (data == NULL)
9062     error (EXIT_FAILURE, 0,
9063            gettext ("cannot convert core note data: %s"), elf_errmsg (-1));
9064
9065   unsigned char const *ptr = data->d_buf;
9066   unsigned char const *const end = data->d_buf + data->d_size;
9067
9068   uint64_t count, page_size;
9069   if (! buf_read_ulong (core, &ptr, end, &count)
9070       || ! buf_read_ulong (core, &ptr, end, &page_size))
9071     {
9072     fail:
9073       printf ("    Not enough data in NT_FILE note.\n");
9074       return;
9075     }
9076
9077   size_t addrsize = gelf_fsize (core, ELF_T_ADDR, 1, EV_CURRENT);
9078   uint64_t maxcount = (size_t) (end - ptr) / (3 * addrsize);
9079   if (count > maxcount)
9080     goto fail;
9081
9082   /* Where file names are stored.  */
9083   unsigned char const *const fstart = ptr + 3 * count * addrsize;
9084   char const *fptr = (char *) fstart;
9085
9086   printf ("    %" PRId64 " files:\n", count);
9087   for (uint64_t i = 0; i < count; ++i)
9088     {
9089       uint64_t mstart, mend, moffset;
9090       if (! buf_read_ulong (core, &ptr, fstart, &mstart)
9091           || ! buf_read_ulong (core, &ptr, fstart, &mend)
9092           || ! buf_read_ulong (core, &ptr, fstart, &moffset))
9093         goto fail;
9094
9095       const char *fnext = memchr (fptr, '\0', (char *) end - fptr);
9096       if (fnext == NULL)
9097         goto fail;
9098
9099       int ct = printf ("      %08" PRIx64 "-%08" PRIx64
9100                        " %08" PRIx64 " %" PRId64,
9101                        mstart, mend, moffset * page_size, mend - mstart);
9102       printf ("%*s%s\n", ct > 50 ? 3 : 53 - ct, "", fptr);
9103
9104       fptr = fnext + 1;
9105     }
9106 }
9107
9108 static void
9109 handle_core_note (Ebl *ebl, const GElf_Nhdr *nhdr,
9110                   const char *name, const void *desc)
9111 {
9112   GElf_Word regs_offset;
9113   size_t nregloc;
9114   const Ebl_Register_Location *reglocs;
9115   size_t nitems;
9116   const Ebl_Core_Item *items;
9117
9118   if (! ebl_core_note (ebl, nhdr, name,
9119                        &regs_offset, &nregloc, &reglocs, &nitems, &items))
9120     return;
9121
9122   /* Pass 0 for DESCSZ when there are registers in the note,
9123      so that the ITEMS array does not describe the whole thing.
9124      For non-register notes, the actual descsz might be a multiple
9125      of the unit size, not just exactly the unit size.  */
9126   unsigned int colno = handle_core_items (ebl->elf, desc,
9127                                           nregloc == 0 ? nhdr->n_descsz : 0,
9128                                           items, nitems);
9129   if (colno != 0)
9130     putchar_unlocked ('\n');
9131
9132   colno = handle_core_registers (ebl, ebl->elf, desc + regs_offset,
9133                                  reglocs, nregloc);
9134   if (colno != 0)
9135     putchar_unlocked ('\n');
9136 }
9137
9138 static void
9139 handle_notes_data (Ebl *ebl, const GElf_Ehdr *ehdr,
9140                    GElf_Off start, Elf_Data *data)
9141 {
9142   fputs_unlocked (gettext ("  Owner          Data size  Type\n"), stdout);
9143
9144   if (data == NULL)
9145     goto bad_note;
9146
9147   size_t offset = 0;
9148   GElf_Nhdr nhdr;
9149   size_t name_offset;
9150   size_t desc_offset;
9151   while (offset < data->d_size
9152          && (offset = gelf_getnote (data, offset,
9153                                     &nhdr, &name_offset, &desc_offset)) > 0)
9154     {
9155       const char *name = data->d_buf + name_offset;
9156       const char *desc = data->d_buf + desc_offset;
9157
9158       char buf[100];
9159       char buf2[100];
9160       printf (gettext ("  %-13.*s  %9" PRId32 "  %s\n"),
9161               (int) nhdr.n_namesz, name, nhdr.n_descsz,
9162               ehdr->e_type == ET_CORE
9163               ? ebl_core_note_type_name (ebl, nhdr.n_type,
9164                                          buf, sizeof (buf))
9165               : ebl_object_note_type_name (ebl, name, nhdr.n_type,
9166                                            buf2, sizeof (buf2)));
9167
9168       /* Filter out invalid entries.  */
9169       if (memchr (name, '\0', nhdr.n_namesz) != NULL
9170           /* XXX For now help broken Linux kernels.  */
9171           || 1)
9172         {
9173           if (ehdr->e_type == ET_CORE)
9174             {
9175               if (nhdr.n_type == NT_AUXV
9176                   && (nhdr.n_namesz == 4 /* Broken old Linux kernels.  */
9177                       || (nhdr.n_namesz == 5 && name[4] == '\0'))
9178                   && !memcmp (name, "CORE", 4))
9179                 handle_auxv_note (ebl, ebl->elf, nhdr.n_descsz,
9180                                   start + desc_offset);
9181               else if (nhdr.n_namesz == 5 && strcmp (name, "CORE") == 0)
9182                 switch (nhdr.n_type)
9183                   {
9184                   case NT_SIGINFO:
9185                     handle_siginfo_note (ebl->elf, nhdr.n_descsz,
9186                                          start + desc_offset);
9187                     break;
9188
9189                   case NT_FILE:
9190                     handle_file_note (ebl->elf, nhdr.n_descsz,
9191                                       start + desc_offset);
9192                     break;
9193
9194                   default:
9195                     handle_core_note (ebl, &nhdr, name, desc);
9196                   }
9197               else
9198                 handle_core_note (ebl, &nhdr, name, desc);
9199             }
9200           else
9201             ebl_object_note (ebl, name, nhdr.n_type, nhdr.n_descsz, desc);
9202         }
9203     }
9204
9205   if (offset == data->d_size)
9206     return;
9207
9208  bad_note:
9209   error (EXIT_FAILURE, 0,
9210          gettext ("cannot get content of note section: %s"),
9211          elf_errmsg (-1));
9212 }
9213
9214 static void
9215 handle_notes (Ebl *ebl, GElf_Ehdr *ehdr)
9216 {
9217   /* If we have section headers, just look for SHT_NOTE sections.
9218      In a debuginfo file, the program headers are not reliable.  */
9219   if (shnum != 0)
9220     {
9221       /* Get the section header string table index.  */
9222       size_t shstrndx;
9223       if (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0)
9224         error (EXIT_FAILURE, 0,
9225                gettext ("cannot get section header string table index"));
9226
9227       Elf_Scn *scn = NULL;
9228       while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
9229         {
9230           GElf_Shdr shdr_mem;
9231           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
9232
9233           if (shdr == NULL || shdr->sh_type != SHT_NOTE)
9234             /* Not what we are looking for.  */
9235             continue;
9236
9237           printf (gettext ("\
9238 \nNote section [%2zu] '%s' of %" PRIu64 " bytes at offset %#0" PRIx64 ":\n"),
9239                   elf_ndxscn (scn),
9240                   elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
9241                   shdr->sh_size, shdr->sh_offset);
9242
9243           handle_notes_data (ebl, ehdr, shdr->sh_offset,
9244                              elf_getdata (scn, NULL));
9245         }
9246       return;
9247     }
9248
9249   /* We have to look through the program header to find the note
9250      sections.  There can be more than one.  */
9251   for (size_t cnt = 0; cnt < phnum; ++cnt)
9252     {
9253       GElf_Phdr mem;
9254       GElf_Phdr *phdr = gelf_getphdr (ebl->elf, cnt, &mem);
9255
9256       if (phdr == NULL || phdr->p_type != PT_NOTE)
9257         /* Not what we are looking for.  */
9258         continue;
9259
9260       printf (gettext ("\
9261 \nNote segment of %" PRIu64 " bytes at offset %#0" PRIx64 ":\n"),
9262               phdr->p_filesz, phdr->p_offset);
9263
9264       handle_notes_data (ebl, ehdr, phdr->p_offset,
9265                          elf_getdata_rawchunk (ebl->elf,
9266                                                phdr->p_offset, phdr->p_filesz,
9267                                                ELF_T_NHDR));
9268     }
9269 }
9270
9271
9272 static void
9273 hex_dump (const uint8_t *data, size_t len)
9274 {
9275   size_t pos = 0;
9276   while (pos < len)
9277     {
9278       printf ("  0x%08Zx ", pos);
9279
9280       const size_t chunk = MIN (len - pos, 16);
9281
9282       for (size_t i = 0; i < chunk; ++i)
9283         if (i % 4 == 3)
9284           printf ("%02x ", data[pos + i]);
9285         else
9286           printf ("%02x", data[pos + i]);
9287
9288       if (chunk < 16)
9289         printf ("%*s", (int) ((16 - chunk) * 2 + (16 - chunk + 3) / 4), "");
9290
9291       for (size_t i = 0; i < chunk; ++i)
9292         {
9293           unsigned char b = data[pos + i];
9294           printf ("%c", isprint (b) ? b : '.');
9295         }
9296
9297       putchar ('\n');
9298       pos += chunk;
9299     }
9300 }
9301
9302 static void
9303 dump_data_section (Elf_Scn *scn, const GElf_Shdr *shdr, const char *name)
9304 {
9305   if (shdr->sh_size == 0 || shdr->sh_type == SHT_NOBITS)
9306     printf (gettext ("\nSection [%Zu] '%s' has no data to dump.\n"),
9307             elf_ndxscn (scn), name);
9308   else
9309     {
9310       Elf_Data *data = elf_rawdata (scn, NULL);
9311       if (data == NULL)
9312         error (0, 0, gettext ("cannot get data for section [%Zu] '%s': %s"),
9313                elf_ndxscn (scn), name, elf_errmsg (-1));
9314       else
9315         {
9316           printf (gettext ("\nHex dump of section [%Zu] '%s', %" PRIu64
9317                            " bytes at offset %#0" PRIx64 ":\n"),
9318                   elf_ndxscn (scn), name,
9319                   shdr->sh_size, shdr->sh_offset);
9320           hex_dump (data->d_buf, data->d_size);
9321         }
9322     }
9323 }
9324
9325 static void
9326 print_string_section (Elf_Scn *scn, const GElf_Shdr *shdr, const char *name)
9327 {
9328   if (shdr->sh_size == 0 || shdr->sh_type == SHT_NOBITS)
9329     printf (gettext ("\nSection [%Zu] '%s' has no strings to dump.\n"),
9330             elf_ndxscn (scn), name);
9331   else
9332     {
9333       Elf_Data *data = elf_rawdata (scn, NULL);
9334       if (data == NULL)
9335         error (0, 0, gettext ("cannot get data for section [%Zu] '%s': %s"),
9336                elf_ndxscn (scn), name, elf_errmsg (-1));
9337       else
9338         {
9339           printf (gettext ("\nString section [%Zu] '%s' contains %" PRIu64
9340                            " bytes at offset %#0" PRIx64 ":\n"),
9341                   elf_ndxscn (scn), name,
9342                   shdr->sh_size, shdr->sh_offset);
9343
9344           const char *start = data->d_buf;
9345           const char *const limit = start + data->d_size;
9346           do
9347             {
9348               const char *end = memchr (start, '\0', limit - start);
9349               const size_t pos = start - (const char *) data->d_buf;
9350               if (unlikely (end == NULL))
9351                 {
9352                   printf ("  [%6Zx]- %.*s\n",
9353                           pos, (int) (limit - start), start);
9354                   break;
9355                 }
9356               printf ("  [%6Zx]  %s\n", pos, start);
9357               start = end + 1;
9358             } while (start < limit);
9359         }
9360     }
9361 }
9362
9363 static void
9364 for_each_section_argument (Elf *elf, const struct section_argument *list,
9365                            void (*dump) (Elf_Scn *scn, const GElf_Shdr *shdr,
9366                                          const char *name))
9367 {
9368   /* Get the section header string table index.  */
9369   size_t shstrndx;
9370   if (elf_getshdrstrndx (elf, &shstrndx) < 0)
9371     error (EXIT_FAILURE, 0,
9372            gettext ("cannot get section header string table index"));
9373
9374   for (const struct section_argument *a = list; a != NULL; a = a->next)
9375     {
9376       Elf_Scn *scn;
9377       GElf_Shdr shdr_mem;
9378       const char *name = NULL;
9379
9380       char *endp = NULL;
9381       unsigned long int shndx = strtoul (a->arg, &endp, 0);
9382       if (endp != a->arg && *endp == '\0')
9383         {
9384           scn = elf_getscn (elf, shndx);
9385           if (scn == NULL)
9386             {
9387               error (0, 0, gettext ("\nsection [%lu] does not exist"), shndx);
9388               continue;
9389             }
9390
9391           if (gelf_getshdr (scn, &shdr_mem) == NULL)
9392             error (EXIT_FAILURE, 0, gettext ("cannot get section header: %s"),
9393                    elf_errmsg (-1));
9394           name = elf_strptr (elf, shstrndx, shdr_mem.sh_name);
9395         }
9396       else
9397         {
9398           /* Need to look up the section by name.  */
9399           scn = NULL;
9400           bool found = false;
9401           while ((scn = elf_nextscn (elf, scn)) != NULL)
9402             {
9403               if (gelf_getshdr (scn, &shdr_mem) == NULL)
9404                 continue;
9405               name = elf_strptr (elf, shstrndx, shdr_mem.sh_name);
9406               if (name == NULL)
9407                 continue;
9408               if (!strcmp (name, a->arg))
9409                 {
9410                   found = true;
9411                   (*dump) (scn, &shdr_mem, name);
9412                 }
9413             }
9414
9415           if (unlikely (!found) && !a->implicit)
9416             error (0, 0, gettext ("\nsection '%s' does not exist"), a->arg);
9417         }
9418     }
9419 }
9420
9421 static void
9422 dump_data (Ebl *ebl)
9423 {
9424   for_each_section_argument (ebl->elf, dump_data_sections, &dump_data_section);
9425 }
9426
9427 static void
9428 dump_strings (Ebl *ebl)
9429 {
9430   for_each_section_argument (ebl->elf, string_sections, &print_string_section);
9431 }
9432
9433 static void
9434 print_strings (Ebl *ebl)
9435 {
9436   /* Get the section header string table index.  */
9437   size_t shstrndx;
9438   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
9439     error (EXIT_FAILURE, 0,
9440            gettext ("cannot get section header string table index"));
9441
9442   Elf_Scn *scn;
9443   GElf_Shdr shdr_mem;
9444   const char *name;
9445   scn = NULL;
9446   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
9447     {
9448       if (gelf_getshdr (scn, &shdr_mem) == NULL)
9449         continue;
9450
9451       if (shdr_mem.sh_type != SHT_PROGBITS
9452           || !(shdr_mem.sh_flags & SHF_STRINGS))
9453         continue;
9454
9455       name = elf_strptr (ebl->elf, shstrndx, shdr_mem.sh_name);
9456       if (name == NULL)
9457         continue;
9458
9459       print_string_section (scn, &shdr_mem, name);
9460     }
9461 }
9462
9463 static void
9464 dump_archive_index (Elf *elf, const char *fname)
9465 {
9466   size_t narsym;
9467   const Elf_Arsym *arsym = elf_getarsym (elf, &narsym);
9468   if (arsym == NULL)
9469     {
9470       int result = elf_errno ();
9471       if (unlikely (result != ELF_E_NO_INDEX))
9472         error (EXIT_FAILURE, 0,
9473                gettext ("cannot get symbol index of archive '%s': %s"),
9474                fname, elf_errmsg (result));
9475       else
9476         printf (gettext ("\nArchive '%s' has no symbol index\n"), fname);
9477       return;
9478     }
9479
9480   printf (gettext ("\nIndex of archive '%s' has %Zu entries:\n"),
9481           fname, narsym);
9482
9483   size_t as_off = 0;
9484   for (const Elf_Arsym *s = arsym; s < &arsym[narsym - 1]; ++s)
9485     {
9486       if (s->as_off != as_off)
9487         {
9488           as_off = s->as_off;
9489
9490           Elf *subelf;
9491           if (unlikely (elf_rand (elf, as_off) == 0)
9492               || unlikely ((subelf = elf_begin (-1, ELF_C_READ_MMAP, elf))
9493                            == NULL))
9494 #if __GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 7)
9495             while (1)
9496 #endif
9497               error (EXIT_FAILURE, 0,
9498                      gettext ("cannot extract member at offset %Zu in '%s': %s"),
9499                      as_off, fname, elf_errmsg (-1));
9500
9501           const Elf_Arhdr *h = elf_getarhdr (subelf);
9502
9503           printf (gettext ("Archive member '%s' contains:\n"), h->ar_name);
9504
9505           elf_end (subelf);
9506         }
9507
9508       printf ("\t%s\n", s->as_name);
9509     }
9510 }
9511
9512 #include "debugpred.h"