readelf: Handle DW_LLE_GNU_view_pair
[platform/upstream/elfutils.git] / src / readelf.c
1 /* Print information from ELF file in human-readable form.
2    Copyright (C) 1999-2018 Red Hat, Inc.
3    This file is part of elfutils.
4
5    This file is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    elfutils is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 #ifdef HAVE_CONFIG_H
19 # include <config.h>
20 #endif
21
22 #include <argp.h>
23 #include <assert.h>
24 #include <ctype.h>
25 #include <dwarf.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <gelf.h>
29 #include <inttypes.h>
30 #include <langinfo.h>
31 #include <libdw.h>
32 #include <libdwfl.h>
33 #include <locale.h>
34 #include <stdarg.h>
35 #include <stdbool.h>
36 #include <stdio.h>
37 #include <stdio_ext.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <strings.h>
41 #include <time.h>
42 #include <unistd.h>
43 #include <sys/stat.h>
44 #include <signal.h>
45
46 #include <libeu.h>
47 #include <system.h>
48 #include <printversion.h>
49 #include "../libelf/libelfP.h"
50 #include "../libelf/common.h"
51 #include "../libebl/libeblP.h"
52 #include "../libdwelf/libdwelf.h"
53 #include "../libdw/libdwP.h"
54 #include "../libdwfl/libdwflP.h"
55 #include "../libdw/memory-access.h"
56
57 #include "../libdw/known-dwarf.h"
58
59 #ifdef __linux__
60 #define CORE_SIGILL  SIGILL
61 #define CORE_SIGBUS  SIGBUS
62 #define CORE_SIGFPE  SIGFPE
63 #define CORE_SIGSEGV SIGSEGV
64 #define CORE_SI_USER SI_USER
65 #else
66 /* We want the linux version of those as that is what shows up in the core files. */
67 #define CORE_SIGILL  4  /* Illegal instruction (ANSI).  */
68 #define CORE_SIGBUS  7  /* BUS error (4.2 BSD).  */
69 #define CORE_SIGFPE  8  /* Floating-point exception (ANSI).  */
70 #define CORE_SIGSEGV 11 /* Segmentation violation (ANSI).  */
71 #define CORE_SI_USER 0  /* Sent by kill, sigsend.  */
72 #endif
73
74 /* Name and version of program.  */
75 ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
76
77 /* Bug report address.  */
78 ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
79
80 /* argp key value for --elf-section, non-ascii.  */
81 #define ELF_INPUT_SECTION 256
82
83 /* argp key value for --dwarf-skeleton, non-ascii.  */
84 #define DWARF_SKELETON 257
85
86 /* argp key value for --dyn-syms, non-ascii.  */
87 #define PRINT_DYNSYM_TABLE 258
88
89 /* Terrible hack for hooking unrelated skeleton/split compile units,
90    see __libdw_link_skel_split in print_debug.  */
91 static bool do_not_close_dwfl = false;
92
93 /* Definitions of arguments for argp functions.  */
94 static const struct argp_option options[] =
95 {
96   { NULL, 0, NULL, 0, N_("ELF input selection:"), 0 },
97   { "elf-section", ELF_INPUT_SECTION, "SECTION", OPTION_ARG_OPTIONAL,
98     N_("Use the named SECTION (default .gnu_debugdata) as (compressed) ELF "
99        "input data"), 0 },
100   { "dwarf-skeleton", DWARF_SKELETON, "FILE", 0,
101     N_("Used with -w to find the skeleton Compile Units in FILE associated "
102        "with the Split Compile units in a .dwo input file"), 0 },
103   { NULL, 0, NULL, 0, N_("ELF output selection:"), 0 },
104   { "all", 'a', NULL, 0,
105     N_("All these plus -p .strtab -p .dynstr -p .comment"), 0 },
106   { "dynamic", 'd', NULL, 0, N_("Display the dynamic segment"), 0 },
107   { "file-header", 'h', NULL, 0, N_("Display the ELF file header"), 0 },
108   { "histogram", 'I', NULL, 0,
109     N_("Display histogram of bucket list lengths"), 0 },
110   { "program-headers", 'l', NULL, 0, N_("Display the program headers"), 0 },
111   { "segments", 'l', NULL, OPTION_ALIAS | OPTION_HIDDEN, NULL, 0 },
112   { "relocs", 'r', NULL, 0, N_("Display relocations"), 0 },
113   { "section-groups", 'g', NULL, 0, N_("Display the section groups"), 0 },
114   { "section-headers", 'S', NULL, 0, N_("Display the sections' headers"), 0 },
115   { "sections", 'S', NULL, OPTION_ALIAS | OPTION_HIDDEN, NULL, 0 },
116   { "symbols", 's', "SECTION", OPTION_ARG_OPTIONAL,
117     N_("Display the symbol table sections"), 0 },
118   { "dyn-syms", PRINT_DYNSYM_TABLE, NULL, 0,
119     N_("Display (only) the dynamic symbol table"), 0 },
120   { "version-info", 'V', NULL, 0, N_("Display versioning information"), 0 },
121   { "notes", 'n', "SECTION", OPTION_ARG_OPTIONAL, N_("Display the ELF notes"), 0 },
122   { "arch-specific", 'A', NULL, 0,
123     N_("Display architecture specific information, if any"), 0 },
124   { "exception", 'e', NULL, 0,
125     N_("Display sections for exception handling"), 0 },
126
127   { NULL, 0, NULL, 0, N_("Additional output selection:"), 0 },
128   { "debug-dump", 'w', "SECTION", OPTION_ARG_OPTIONAL,
129     N_("Display DWARF section content.  SECTION can be one of abbrev, addr, "
130        "aranges, decodedaranges, frame, gdb_index, info, info+, loc, line, "
131        "decodedline, ranges, pubnames, str, macinfo, macro or exception"), 0 },
132   { "hex-dump", 'x', "SECTION", 0,
133     N_("Dump the uninterpreted contents of SECTION, by number or name"), 0 },
134   { "strings", 'p', "SECTION", OPTION_ARG_OPTIONAL,
135     N_("Print string contents of sections"), 0 },
136   { "string-dump", 'p', NULL, OPTION_ALIAS | OPTION_HIDDEN, NULL, 0 },
137   { "archive-index", 'c', NULL, 0,
138     N_("Display the symbol index of an archive"), 0 },
139   { "use-dynamic", 'D', NULL, 0,
140     N_("Use the dynamic segment when possible for displaying info"), 0 },
141
142   { NULL, 0, NULL, 0, N_("Output control:"), 0 },
143   { "numeric-addresses", 'N', NULL, 0,
144     N_("Do not find symbol names for addresses in DWARF data"), 0 },
145   { "unresolved-address-offsets", 'U', NULL, 0,
146     N_("Display just offsets instead of resolving values to addresses in DWARF data"), 0 },
147   { "wide", 'W', NULL, 0,
148     N_("Ignored for compatibility (lines always wide)"), 0 },
149   { "decompress", 'z', NULL, 0,
150     N_("Show compression information for compressed sections (when used with -S); decompress section before dumping data (when used with -p or -x)"), 0 },
151   { NULL, 0, NULL, 0, NULL, 0 }
152 };
153
154 /* Short description of program.  */
155 static const char doc[] = N_("\
156 Print information from ELF file in human-readable form.");
157
158 /* Strings for arguments in help texts.  */
159 static const char args_doc[] = N_("FILE...");
160
161 /* Prototype for option handler.  */
162 static error_t parse_opt (int key, char *arg, struct argp_state *state);
163
164 /* Data structure to communicate with argp functions.  */
165 static struct argp argp =
166 {
167   options, parse_opt, args_doc, doc, NULL, NULL, NULL
168 };
169
170 /* If non-null, the section from which we should read to (compressed) ELF.  */
171 static const char *elf_input_section = NULL;
172
173 /* If non-null, the file that contains the skeleton CUs.  */
174 static const char *dwarf_skeleton = NULL;
175
176 /* Flags set by the option controlling the output.  */
177
178 /* True if dynamic segment should be printed.  */
179 static bool print_dynamic_table;
180
181 /* True if the file header should be printed.  */
182 static bool print_file_header;
183
184 /* True if the program headers should be printed.  */
185 static bool print_program_header;
186
187 /* True if relocations should be printed.  */
188 static bool print_relocations;
189
190 /* True if the section headers should be printed.  */
191 static bool print_section_header;
192
193 /* True if the symbol table should be printed.  */
194 static bool print_symbol_table;
195
196 /* True if (only) the dynsym table should be printed.  */
197 static bool print_dynsym_table;
198
199 /* True if reconstruct dynamic symbol table from the PT_DYNAMIC segment.  */
200 static bool use_dynamic_segment;
201
202 /* A specific section name, or NULL to print all symbol tables.  */
203 static char *symbol_table_section;
204
205 /* A specific section name, or NULL to print all ELF notes.  */
206 static char *notes_section;
207
208 /* True if the version information should be printed.  */
209 static bool print_version_info;
210
211 /* True if section groups should be printed.  */
212 static bool print_section_groups;
213
214 /* True if bucket list length histogram should be printed.  */
215 static bool print_histogram;
216
217 /* True if the architecture specific data should be printed.  */
218 static bool print_arch;
219
220 /* True if note section content should be printed.  */
221 static bool print_notes;
222
223 /* True if SHF_STRINGS section content should be printed.  */
224 static bool print_string_sections;
225
226 /* True if archive index should be printed.  */
227 static bool print_archive_index;
228
229 /* True if any of the control options except print_archive_index is set.  */
230 static bool any_control_option;
231
232 /* True if we should print addresses from DWARF in symbolic form.  */
233 static bool print_address_names = true;
234
235 /* True if we should print raw values instead of relativized addresses.  */
236 static bool print_unresolved_addresses = false;
237
238 /* True if we should print the .debug_aranges section using libdw.  */
239 static bool decodedaranges = false;
240
241 /* True if we should print the .debug_aranges section using libdw.  */
242 static bool decodedline = false;
243
244 /* True if we want to show more information about compressed sections.  */
245 static bool print_decompress = false;
246
247 /* True if we want to show split compile units for debug_info skeletons.  */
248 static bool show_split_units = false;
249
250 /* Select printing of debugging sections.  */
251 static enum section_e
252 {
253   section_abbrev = 1,           /* .debug_abbrev  */
254   section_aranges = 2,          /* .debug_aranges  */
255   section_frame = 4,            /* .debug_frame or .eh_frame & al.  */
256   section_info = 8,             /* .debug_info, (implies .debug_types)  */
257   section_line = 16,            /* .debug_line  */
258   section_loc = 32,             /* .debug_loc  */
259   section_pubnames = 64,        /* .debug_pubnames  */
260   section_str = 128,            /* .debug_str  */
261   section_macinfo = 256,        /* .debug_macinfo  */
262   section_ranges = 512,         /* .debug_ranges  */
263   section_exception = 1024,     /* .eh_frame & al.  */
264   section_gdb_index = 2048,     /* .gdb_index  */
265   section_macro = 4096,         /* .debug_macro  */
266   section_addr = 8192,          /* .debug_addr  */
267   section_types = 16384,        /* .debug_types (implied by .debug_info)  */
268   section_all = (section_abbrev | section_aranges | section_frame
269                  | section_info | section_line | section_loc
270                  | section_pubnames | section_str | section_macinfo
271                  | section_ranges | section_exception | section_gdb_index
272                  | section_macro | section_addr | section_types)
273 } print_debug_sections, implicit_debug_sections;
274
275 /* Select hex dumping of sections.  */
276 static struct section_argument *dump_data_sections;
277 static struct section_argument **dump_data_sections_tail = &dump_data_sections;
278
279 /* Select string dumping of sections.  */
280 static struct section_argument *string_sections;
281 static struct section_argument **string_sections_tail = &string_sections;
282
283 struct section_argument
284 {
285   struct section_argument *next;
286   const char *arg;
287   bool implicit;
288 };
289
290 /* Numbers of sections and program headers in the file.  */
291 static size_t shnum;
292 static size_t phnum;
293
294
295 /* Declarations of local functions.  */
296 static void process_file (int fd, const char *fname, bool only_one);
297 static void process_elf_file (Dwfl_Module *dwflmod, int fd);
298 static void print_ehdr (Ebl *ebl, GElf_Ehdr *ehdr);
299 static void print_shdr (Ebl *ebl, GElf_Ehdr *ehdr);
300 static void print_phdr (Ebl *ebl, GElf_Ehdr *ehdr);
301 static void print_scngrp (Ebl *ebl);
302 static void print_dynamic (Ebl *ebl);
303 static void print_relocs (Ebl *ebl, GElf_Ehdr *ehdr);
304 static void handle_relocs_rel (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn,
305                                GElf_Shdr *shdr);
306 static void handle_relocs_rela (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn,
307                                 GElf_Shdr *shdr);
308 static void print_symtab (Ebl *ebl, int type);
309 static void handle_symtab (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr);
310 static void print_verinfo (Ebl *ebl);
311 static void handle_verneed (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr);
312 static void handle_verdef (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr);
313 static void handle_versym (Ebl *ebl, Elf_Scn *scn,
314                            GElf_Shdr *shdr);
315 static void print_debug (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr);
316 static void handle_hash (Ebl *ebl);
317 static void handle_notes (Ebl *ebl, GElf_Ehdr *ehdr);
318 static void print_liblist (Ebl *ebl);
319 static void print_attributes (Ebl *ebl, const GElf_Ehdr *ehdr);
320 static void dump_data (Ebl *ebl);
321 static void dump_strings (Ebl *ebl);
322 static void print_strings (Ebl *ebl);
323 static void dump_archive_index (Elf *, const char *);
324
325 enum dyn_idx
326 {
327   i_strsz,
328   i_verneed,
329   i_verdef,
330   i_versym,
331   i_symtab,
332   i_strtab,
333   i_hash,
334   i_gnu_hash,
335   i_max
336 };
337
338 /* Declarations of local functions for use-dynamic.  */
339 static Elf_Data *get_dynscn_strtab (Elf *elf, GElf_Phdr *phdr);
340 static void get_dynscn_addrs (Elf *elf, GElf_Phdr *phdr, GElf_Addr addrs[i_max]);
341 static void find_offsets (Elf *elf, GElf_Addr main_bias, size_t n,
342                           GElf_Addr addrs[n], GElf_Off offs[n]);
343
344 /* Looked up once with gettext in main.  */
345 static char *yes_str;
346 static char *no_str;
347
348 static void
349 cleanup_list (struct section_argument *list)
350 {
351   while (list != NULL)
352     {
353       struct section_argument *a = list;
354       list = a->next;
355       free (a);
356     }
357 }
358
359 int
360 main (int argc, char *argv[])
361 {
362   /* We use no threads here which can interfere with handling a stream.  */
363   (void) __fsetlocking (stdout, FSETLOCKING_BYCALLER);
364
365   /* Set locale.  */
366   setlocale (LC_ALL, "");
367
368   /* Initialize the message catalog.  */
369   textdomain (PACKAGE_TARNAME);
370
371   /* Look up once.  */
372   yes_str = _("yes");
373   no_str = _("no");
374
375   /* Parse and process arguments.  */
376   int remaining;
377   argp_parse (&argp, argc, argv, 0, &remaining, NULL);
378
379   /* Before we start tell the ELF library which version we are using.  */
380   elf_version (EV_CURRENT);
381
382   /* Now process all the files given at the command line.  */
383   bool only_one = remaining + 1 == argc;
384   do
385     {
386       /* Open the file.  */
387       int fd = open (argv[remaining], O_RDONLY);
388       if (fd == -1)
389         {
390           error (0, errno, _("cannot open input file '%s'"), argv[remaining]);
391           continue;
392         }
393
394       process_file (fd, argv[remaining], only_one);
395
396       close (fd);
397     }
398   while (++remaining < argc);
399
400   cleanup_list (dump_data_sections);
401   cleanup_list (string_sections);
402
403   return error_message_count != 0;
404 }
405
406 static void
407 add_dump_section (const char *name,
408                   int key,
409                   bool implicit)
410 {
411   struct section_argument *a = xmalloc (sizeof *a);
412   a->arg = name;
413   a->next = NULL;
414   a->implicit = implicit;
415   struct section_argument ***tailp
416     = key == 'x' ? &dump_data_sections_tail : &string_sections_tail;
417   **tailp = a;
418   *tailp = &a->next;
419 }
420
421 /* Handle program arguments.  */
422 static error_t
423 parse_opt (int key, char *arg,
424            struct argp_state *state __attribute__ ((unused)))
425 {
426   switch (key)
427     {
428     case 'a':
429       print_file_header = true;
430       print_program_header = true;
431       print_relocations = true;
432       print_section_header = true;
433       print_symbol_table = true;
434       print_version_info = true;
435       print_dynamic_table = true;
436       print_section_groups = true;
437       print_histogram = true;
438       print_arch = true;
439       print_notes = true;
440       implicit_debug_sections |= section_exception;
441       add_dump_section (".strtab", key, true);
442       add_dump_section (".dynstr", key, true);
443       add_dump_section (".comment", key, true);
444       any_control_option = true;
445       break;
446     case 'A':
447       print_arch = true;
448       any_control_option = true;
449       break;
450     case 'd':
451       print_dynamic_table = true;
452       any_control_option = true;
453       break;
454     case 'D':
455       use_dynamic_segment = true;
456       break;
457     case 'e':
458       print_debug_sections |= section_exception;
459       any_control_option = true;
460       break;
461     case 'g':
462       print_section_groups = true;
463       any_control_option = true;
464       break;
465     case 'h':
466       print_file_header = true;
467       any_control_option = true;
468       break;
469     case 'I':
470       print_histogram = true;
471       any_control_option = true;
472       break;
473     case 'l':
474       print_program_header = true;
475       any_control_option = true;
476       break;
477     case 'n':
478       print_notes = true;
479       any_control_option = true;
480       notes_section = arg;
481       break;
482     case 'r':
483       print_relocations = true;
484       any_control_option = true;
485      break;
486     case 'S':
487       print_section_header = true;
488       any_control_option = true;
489       break;
490     case 's':
491       print_symbol_table = true;
492       any_control_option = true;
493       symbol_table_section = arg;
494       break;
495     case PRINT_DYNSYM_TABLE:
496       print_dynsym_table = true;
497       any_control_option = true;
498       break;
499     case 'V':
500       print_version_info = true;
501       any_control_option = true;
502       break;
503     case 'c':
504       print_archive_index = true;
505       break;
506     case 'w':
507       if (arg == NULL)
508         {
509           print_debug_sections = section_all;
510           implicit_debug_sections = section_info;
511           show_split_units = true;
512         }
513       else if (strcmp (arg, "abbrev") == 0)
514         print_debug_sections |= section_abbrev;
515       else if (strcmp (arg, "addr") == 0)
516         {
517           print_debug_sections |= section_addr;
518           implicit_debug_sections |= section_info;
519         }
520       else if (strcmp (arg, "aranges") == 0)
521         print_debug_sections |= section_aranges;
522       else if (strcmp (arg, "decodedaranges") == 0)
523         {
524           print_debug_sections |= section_aranges;
525           decodedaranges = true;
526         }
527       else if (strcmp (arg, "ranges") == 0)
528         {
529           print_debug_sections |= section_ranges;
530           implicit_debug_sections |= section_info;
531         }
532       else if (strcmp (arg, "frame") == 0 || strcmp (arg, "frames") == 0)
533         print_debug_sections |= section_frame;
534       else if (strcmp (arg, "info") == 0)
535         {
536           print_debug_sections |= section_info;
537           print_debug_sections |= section_types;
538         }
539       else if (strcmp (arg, "info+") == 0)
540         {
541           print_debug_sections |= section_info;
542           print_debug_sections |= section_types;
543           show_split_units = true;
544         }
545       else if (strcmp (arg, "loc") == 0)
546         {
547           print_debug_sections |= section_loc;
548           implicit_debug_sections |= section_info;
549         }
550       else if (strcmp (arg, "line") == 0)
551         print_debug_sections |= section_line;
552       else if (strcmp (arg, "decodedline") == 0)
553         {
554           print_debug_sections |= section_line;
555           decodedline = true;
556         }
557       else if (strcmp (arg, "pubnames") == 0)
558         print_debug_sections |= section_pubnames;
559       else if (strcmp (arg, "str") == 0)
560         {
561           print_debug_sections |= section_str;
562           /* For mapping string offset tables to CUs.  */
563           implicit_debug_sections |= section_info;
564         }
565       else if (strcmp (arg, "macinfo") == 0)
566         print_debug_sections |= section_macinfo;
567       else if (strcmp (arg, "macro") == 0)
568         print_debug_sections |= section_macro;
569       else if (strcmp (arg, "exception") == 0)
570         print_debug_sections |= section_exception;
571       else if (strcmp (arg, "gdb_index") == 0)
572         print_debug_sections |= section_gdb_index;
573       else
574         {
575           fprintf (stderr, _("Unknown DWARF debug section `%s'.\n"),
576                    arg);
577           argp_help (&argp, stderr, ARGP_HELP_SEE,
578                      program_invocation_short_name);
579           exit (1);
580         }
581       any_control_option = true;
582       break;
583     case 'p':
584       any_control_option = true;
585       if (arg == NULL)
586         {
587           print_string_sections = true;
588           break;
589         }
590       FALLTHROUGH;
591     case 'x':
592       add_dump_section (arg, key, false);
593       any_control_option = true;
594       break;
595     case 'N':
596       print_address_names = false;
597       break;
598     case 'U':
599       print_unresolved_addresses = true;
600       break;
601     case ARGP_KEY_NO_ARGS:
602       fputs (_("Missing file name.\n"), stderr);
603       goto do_argp_help;
604     case ARGP_KEY_FINI:
605       if (! any_control_option && ! print_archive_index)
606         {
607           fputs (_("No operation specified.\n"), stderr);
608         do_argp_help:
609           argp_help (&argp, stderr, ARGP_HELP_SEE,
610                      program_invocation_short_name);
611           exit (EXIT_FAILURE);
612         }
613       break;
614     case 'W':                   /* Ignored.  */
615       break;
616     case 'z':
617       print_decompress = true;
618       break;
619     case ELF_INPUT_SECTION:
620       if (arg == NULL)
621         elf_input_section = ".gnu_debugdata";
622       else
623         elf_input_section = arg;
624       break;
625     case DWARF_SKELETON:
626       dwarf_skeleton = arg;
627       break;
628     default:
629       return ARGP_ERR_UNKNOWN;
630     }
631   return 0;
632 }
633
634
635 /* Create a file descriptor to read the data from the
636    elf_input_section given a file descriptor to an ELF file.  */
637 static int
638 open_input_section (int fd)
639 {
640   size_t shnums;
641   size_t cnt;
642   size_t shstrndx;
643   Elf *elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
644   if (elf == NULL)
645     {
646       error (0, 0, _("cannot generate Elf descriptor: %s"),
647              elf_errmsg (-1));
648       return -1;
649     }
650
651   if (elf_getshdrnum (elf, &shnums) < 0)
652     {
653       error (0, 0, _("cannot determine number of sections: %s"),
654              elf_errmsg (-1));
655     open_error:
656       elf_end (elf);
657       return -1;
658     }
659
660   if (elf_getshdrstrndx (elf, &shstrndx) < 0)
661     {
662       error (0, 0, _("cannot get section header string table index"));
663       goto open_error;
664     }
665
666   for (cnt = 0; cnt < shnums; ++cnt)
667     {
668       Elf_Scn *scn = elf_getscn (elf, cnt);
669       if (scn == NULL)
670         {
671           error (0, 0, _("cannot get section: %s"),
672                  elf_errmsg (-1));
673           goto open_error;
674         }
675
676       GElf_Shdr shdr_mem;
677       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
678       if (unlikely (shdr == NULL))
679         {
680           error (0, 0, _("cannot get section header: %s"),
681                  elf_errmsg (-1));
682           goto open_error;
683         }
684
685       const char *sname = elf_strptr (elf, shstrndx, shdr->sh_name);
686       if (sname == NULL)
687         {
688           error (0, 0, _("cannot get section name"));
689           goto open_error;
690         }
691
692       if (strcmp (sname, elf_input_section) == 0)
693         {
694           Elf_Data *data = elf_rawdata (scn, NULL);
695           if (data == NULL)
696             {
697               error (0, 0, _("cannot get %s content: %s"),
698                      sname, elf_errmsg (-1));
699               goto open_error;
700             }
701
702           /* Create (and immediately unlink) a temporary file to store
703              section data in to create a file descriptor for it.  */
704           const char *tmpdir = getenv ("TMPDIR") ?: P_tmpdir;
705           static const char suffix[] = "/readelfXXXXXX";
706           int tmplen = strlen (tmpdir) + sizeof (suffix);
707           char *tempname = alloca (tmplen);
708           sprintf (tempname, "%s%s", tmpdir, suffix);
709
710           int sfd = mkstemp (tempname);
711           if (sfd == -1)
712             {
713               error (0, 0, _("cannot create temp file '%s'"),
714                      tempname);
715               goto open_error;
716             }
717           unlink (tempname);
718
719           ssize_t size = data->d_size;
720           if (write_retry (sfd, data->d_buf, size) != size)
721             {
722               error (0, 0, _("cannot write section data"));
723               goto open_error;
724             }
725
726           if (elf_end (elf) != 0)
727             {
728               error (0, 0, _("error while closing Elf descriptor: %s"),
729                      elf_errmsg (-1));
730               return -1;
731             }
732
733           if (lseek (sfd, 0, SEEK_SET) == -1)
734             {
735               error (0, 0, _("error while rewinding file descriptor"));
736               return -1;
737             }
738
739           return sfd;
740         }
741     }
742
743   /* Named section not found.  */
744   if (elf_end (elf) != 0)
745     error (0, 0, _("error while closing Elf descriptor: %s"),
746            elf_errmsg (-1));
747   return -1;
748 }
749
750 /* Check if the file is an archive, and if so dump its index.  */
751 static void
752 check_archive_index (int fd, const char *fname, bool only_one)
753 {
754   /* Create an `Elf' descriptor.  */
755   Elf *elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
756   if (elf == NULL)
757     error (0, 0, _("cannot generate Elf descriptor: %s"),
758            elf_errmsg (-1));
759   else
760     {
761       if (elf_kind (elf) == ELF_K_AR)
762         {
763           if (!only_one)
764             printf ("\n%s:\n\n", fname);
765           dump_archive_index (elf, fname);
766         }
767       else
768         error (0, 0,
769                _("'%s' is not an archive, cannot print archive index"),
770                fname);
771
772       /* Now we can close the descriptor.  */
773       if (elf_end (elf) != 0)
774         error (0, 0, _("error while closing Elf descriptor: %s"),
775                elf_errmsg (-1));
776     }
777 }
778
779 /* Trivial callback used for checking if we opened an archive.  */
780 static int
781 count_dwflmod (Dwfl_Module *dwflmod __attribute__ ((unused)),
782                void **userdata __attribute__ ((unused)),
783                const char *name __attribute__ ((unused)),
784                Dwarf_Addr base __attribute__ ((unused)),
785                void *arg)
786 {
787   if (*(bool *) arg)
788     return DWARF_CB_ABORT;
789   *(bool *) arg = true;
790   return DWARF_CB_OK;
791 }
792
793 struct process_dwflmod_args
794 {
795   int fd;
796   bool only_one;
797 };
798
799 static int
800 process_dwflmod (Dwfl_Module *dwflmod,
801                  void **userdata __attribute__ ((unused)),
802                  const char *name __attribute__ ((unused)),
803                  Dwarf_Addr base __attribute__ ((unused)),
804                  void *arg)
805 {
806   const struct process_dwflmod_args *a = arg;
807
808   /* Print the file name.  */
809   if (!a->only_one)
810     {
811       const char *fname;
812       dwfl_module_info (dwflmod, NULL, NULL, NULL, NULL, NULL, &fname, NULL);
813
814       printf ("\n%s:\n\n", fname);
815     }
816
817   process_elf_file (dwflmod, a->fd);
818
819   return DWARF_CB_OK;
820 }
821
822 /* Stub libdwfl callback, only the ELF handle already open is ever used.
823    Only used for finding the alternate debug file if the Dwarf comes from
824    the main file.  We are not interested in separate debuginfo.  */
825 static int
826 find_no_debuginfo (Dwfl_Module *mod,
827                    void **userdata,
828                    const char *modname,
829                    Dwarf_Addr base,
830                    const char *file_name,
831                    const char *debuglink_file,
832                    GElf_Word debuglink_crc,
833                    char **debuginfo_file_name)
834 {
835   Dwarf_Addr dwbias;
836   dwfl_module_info (mod, NULL, NULL, NULL, &dwbias, NULL, NULL, NULL);
837
838   /* We are only interested if the Dwarf has been setup on the main
839      elf file but is only missing the alternate debug link.  If dwbias
840      hasn't even been setup, this is searching for separate debuginfo
841      for the main elf.  We don't care in that case.  */
842   if (dwbias == (Dwarf_Addr) -1)
843     return -1;
844
845   return dwfl_standard_find_debuginfo (mod, userdata, modname, base,
846                                        file_name, debuglink_file,
847                                        debuglink_crc, debuginfo_file_name);
848 }
849
850 static Dwfl *
851 create_dwfl (int fd, const char *fname)
852 {
853   /* Duplicate an fd for dwfl_report_offline to swallow.  */
854   int dwfl_fd = dup (fd);
855   if (unlikely (dwfl_fd < 0))
856     error_exit (errno, "dup");
857
858   /* Use libdwfl in a trivial way to open the libdw handle for us.
859      This takes care of applying relocations to DWARF data in ET_REL files.  */
860   static const Dwfl_Callbacks callbacks =
861     {
862       .section_address = dwfl_offline_section_address,
863       .find_debuginfo = find_no_debuginfo
864     };
865   Dwfl *dwfl = dwfl_begin (&callbacks);
866   if (likely (dwfl != NULL))
867     /* Let 0 be the logical address of the file (or first in archive).  */
868     dwfl->offline_next_address = 0;
869   if (dwfl_report_offline (dwfl, fname, fname, dwfl_fd) == NULL)
870     {
871       struct stat st;
872       if (fstat (dwfl_fd, &st) != 0)
873         error (0, errno, _("cannot stat input file"));
874       else if (unlikely (st.st_size == 0))
875         error (0, 0, _("input file is empty"));
876       else
877         error (0, 0, _("failed reading '%s': %s"),
878                fname, dwfl_errmsg (-1));
879       close (dwfl_fd);          /* Consumed on success, not on failure.  */
880       dwfl = NULL;
881     }
882   else
883     dwfl_report_end (dwfl, NULL, NULL);
884
885   return dwfl;
886 }
887
888 /* Process one input file.  */
889 static void
890 process_file (int fd, const char *fname, bool only_one)
891 {
892   if (print_archive_index)
893     check_archive_index (fd, fname, only_one);
894
895   if (!any_control_option)
896     return;
897
898   if (elf_input_section != NULL)
899     {
900       /* Replace fname and fd with section content. */
901       char *fnname = alloca (strlen (fname) + strlen (elf_input_section) + 2);
902       sprintf (fnname, "%s:%s", fname, elf_input_section);
903       fd = open_input_section (fd);
904       if (fd == -1)
905         {
906           error (0, 0, _("No such section '%s' in '%s'"),
907                  elf_input_section, fname);
908           return;
909         }
910       fname = fnname;
911     }
912
913   Dwfl *dwfl = create_dwfl (fd, fname);
914   if (dwfl != NULL)
915     {
916       if (only_one)
917         {
918           /* Clear ONLY_ONE if we have multiple modules, from an archive.  */
919           bool seen = false;
920           only_one = dwfl_getmodules (dwfl, &count_dwflmod, &seen, 0) == 0;
921         }
922
923       /* Process the one or more modules gleaned from this file.  */
924       struct process_dwflmod_args a = { .fd = fd, .only_one = only_one };
925       dwfl_getmodules (dwfl, &process_dwflmod, &a, 0);
926     }
927   /* Terrible hack for hooking unrelated skeleton/split compile units,
928      see __libdw_link_skel_split in print_debug.  */
929   if (! do_not_close_dwfl)
930     dwfl_end (dwfl);
931
932   /* Need to close the replaced fd if we created it.  Caller takes
933      care of original.  */
934   if (elf_input_section != NULL)
935     close (fd);
936 }
937
938 /* Check whether there are any compressed sections in the ELF file.  */
939 static bool
940 elf_contains_chdrs (Elf *elf)
941 {
942   Elf_Scn *scn = NULL;
943   while ((scn = elf_nextscn (elf, scn)) != NULL)
944     {
945       GElf_Shdr shdr_mem;
946       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
947       if (shdr != NULL && (shdr->sh_flags & SHF_COMPRESSED) != 0)
948         return true;
949     }
950   return false;
951 }
952
953 /* Process one ELF file.  */
954 static void
955 process_elf_file (Dwfl_Module *dwflmod, int fd)
956 {
957   GElf_Addr dwflbias;
958   Elf *elf = dwfl_module_getelf (dwflmod, &dwflbias);
959
960   GElf_Ehdr ehdr_mem;
961   GElf_Ehdr *ehdr = gelf_getehdr (elf, &ehdr_mem);
962
963   if (ehdr == NULL)
964     {
965       error (0, 0, _("cannot read ELF header: %s"), elf_errmsg (-1));
966       return;
967     }
968
969   Ebl *ebl = ebl_openbackend (elf);
970   if (unlikely (ebl == NULL))
971     {
972     ebl_error:
973       error (0, errno, _("cannot create EBL handle"));
974       return;
975     }
976
977   /* Determine the number of sections.  */
978   if (unlikely (elf_getshdrnum (ebl->elf, &shnum) < 0))
979     error_exit (0, _("cannot determine number of sections: %s"),
980                 elf_errmsg (-1));
981
982   /* Determine the number of phdrs.  */
983   if (unlikely (elf_getphdrnum (ebl->elf, &phnum) < 0))
984     error_exit (0, _("cannot determine number of program headers: %s"),
985                 elf_errmsg (-1));
986
987   /* For an ET_REL file, libdwfl has adjusted the in-core shdrs and
988      may have applied relocation to some sections.  If there are any
989      compressed sections, any pass (or libdw/libdwfl) might have
990      uncompressed them.  So we need to get a fresh Elf handle on the
991      file to display those.  */
992   bool print_unchanged = ((print_section_header
993                            || print_relocations
994                            || dump_data_sections != NULL
995                            || print_notes)
996                           && (ehdr->e_type == ET_REL
997                               || elf_contains_chdrs (ebl->elf)));
998
999   Elf *pure_elf = NULL;
1000   Ebl *pure_ebl = ebl;
1001   if (print_unchanged)
1002     {
1003       /* Read the file afresh.  */
1004       off_t aroff = elf_getaroff (elf);
1005       pure_elf = dwelf_elf_begin (fd);
1006       if (aroff > 0)
1007         {
1008           /* Archive member.  */
1009           (void) elf_rand (pure_elf, aroff);
1010           Elf *armem = elf_begin (-1, ELF_C_READ_MMAP, pure_elf);
1011           elf_end (pure_elf);
1012           pure_elf = armem;
1013         }
1014       if (pure_elf == NULL)
1015         {
1016           error (0, 0, _("cannot read ELF: %s"), elf_errmsg (-1));
1017           return;
1018         }
1019       pure_ebl = ebl_openbackend (pure_elf);
1020       if (pure_ebl == NULL)
1021         goto ebl_error;
1022     }
1023
1024   if (print_file_header)
1025     print_ehdr (ebl, ehdr);
1026   if (print_section_header)
1027     print_shdr (pure_ebl, ehdr);
1028   if (print_program_header)
1029     print_phdr (ebl, ehdr);
1030   if (print_section_groups)
1031     print_scngrp (ebl);
1032   if (print_dynamic_table)
1033     print_dynamic (ebl);
1034   if (print_relocations)
1035     print_relocs (pure_ebl, ehdr);
1036   if (print_histogram)
1037     handle_hash (ebl);
1038   if (print_symbol_table || print_dynsym_table)
1039     print_symtab (ebl, SHT_DYNSYM);
1040   if (print_version_info)
1041     print_verinfo (ebl);
1042   if (print_symbol_table)
1043     print_symtab (ebl, SHT_SYMTAB);
1044   if (print_arch)
1045     print_liblist (ebl);
1046   if (print_arch)
1047     print_attributes (ebl, ehdr);
1048   if (dump_data_sections != NULL)
1049     dump_data (pure_ebl);
1050   if (string_sections != NULL)
1051     dump_strings (ebl);
1052   if ((print_debug_sections | implicit_debug_sections) != 0)
1053     print_debug (dwflmod, ebl, ehdr);
1054   if (print_notes)
1055     handle_notes (pure_ebl, ehdr);
1056   if (print_string_sections)
1057     print_strings (ebl);
1058
1059   ebl_closebackend (ebl);
1060
1061   if (pure_ebl != ebl)
1062     {
1063       ebl_closebackend (pure_ebl);
1064       elf_end (pure_elf);
1065     }
1066 }
1067
1068
1069 /* Print file type.  */
1070 static void
1071 print_file_type (unsigned short int e_type)
1072 {
1073   if (likely (e_type <= ET_CORE))
1074     {
1075       static const char *const knowntypes[] =
1076       {
1077         N_("NONE (None)"),
1078         N_("REL (Relocatable file)"),
1079         N_("EXEC (Executable file)"),
1080         N_("DYN (Shared object file)"),
1081         N_("CORE (Core file)")
1082       };
1083       puts (_(knowntypes[e_type]));
1084     }
1085   else if (e_type >= ET_LOOS && e_type <= ET_HIOS)
1086     printf (_("OS Specific: (%x)\n"),  e_type);
1087   else if (e_type >= ET_LOPROC /* && e_type <= ET_HIPROC always true */)
1088     printf (_("Processor Specific: (%x)\n"),  e_type);
1089   else
1090     puts ("???");
1091 }
1092
1093
1094 /* Print ELF header.  */
1095 static void
1096 print_ehdr (Ebl *ebl, GElf_Ehdr *ehdr)
1097 {
1098   fputs_unlocked (_("ELF Header:\n  Magic:  "), stdout);
1099   for (size_t cnt = 0; cnt < EI_NIDENT; ++cnt)
1100     printf (" %02hhx", ehdr->e_ident[cnt]);
1101
1102   printf (_("\n  Class:                             %s\n"),
1103           ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? "ELF32"
1104           : ehdr->e_ident[EI_CLASS] == ELFCLASS64 ? "ELF64"
1105           : "\?\?\?");
1106
1107   printf (_("  Data:                              %s\n"),
1108           ehdr->e_ident[EI_DATA] == ELFDATA2LSB
1109           ? "2's complement, little endian"
1110           : ehdr->e_ident[EI_DATA] == ELFDATA2MSB
1111           ? "2's complement, big endian" : "\?\?\?");
1112
1113   printf (_("  Ident Version:                     %hhd %s\n"),
1114           ehdr->e_ident[EI_VERSION],
1115           ehdr->e_ident[EI_VERSION] == EV_CURRENT ? _("(current)")
1116           : "(\?\?\?)");
1117
1118   char buf[512];
1119   printf (_("  OS/ABI:                            %s\n"),
1120           ebl_osabi_name (ebl, ehdr->e_ident[EI_OSABI], buf, sizeof (buf)));
1121
1122   printf (_("  ABI Version:                       %hhd\n"),
1123           ehdr->e_ident[EI_ABIVERSION]);
1124
1125   fputs_unlocked (_("  Type:                              "), stdout);
1126   print_file_type (ehdr->e_type);
1127
1128   const char *machine = dwelf_elf_e_machine_string (ehdr->e_machine);
1129   if (machine != NULL)
1130     printf (_("  Machine:                           %s\n"), machine);
1131   else
1132     printf (_("  Machine:                           <unknown>: 0x%x\n"),
1133             ehdr->e_machine);
1134
1135   printf (_("  Version:                           %d %s\n"),
1136           ehdr->e_version,
1137           ehdr->e_version  == EV_CURRENT ? _("(current)") : "(\?\?\?)");
1138
1139   printf (_("  Entry point address:               %#" PRIx64 "\n"),
1140           ehdr->e_entry);
1141
1142   printf (_("  Start of program headers:          %" PRId64 " %s\n"),
1143           ehdr->e_phoff, _("(bytes into file)"));
1144
1145   printf (_("  Start of section headers:          %" PRId64 " %s\n"),
1146           ehdr->e_shoff, _("(bytes into file)"));
1147
1148   printf (_("  Flags:                             %s\n"),
1149           ebl_machine_flag_name (ebl, ehdr->e_flags, buf, sizeof (buf)));
1150
1151   printf (_("  Size of this header:               %" PRId16 " %s\n"),
1152           ehdr->e_ehsize, _("(bytes)"));
1153
1154   printf (_("  Size of program header entries:    %" PRId16 " %s\n"),
1155           ehdr->e_phentsize, _("(bytes)"));
1156
1157   printf (_("  Number of program headers entries: %" PRId16),
1158           ehdr->e_phnum);
1159   if (ehdr->e_phnum == PN_XNUM)
1160     {
1161       GElf_Shdr shdr_mem;
1162       GElf_Shdr *shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
1163       if (shdr != NULL)
1164         printf (_(" (%" PRIu32 " in [0].sh_info)"),
1165                 (uint32_t) shdr->sh_info);
1166       else
1167         fputs_unlocked (_(" ([0] not available)"), stdout);
1168     }
1169   fputc_unlocked ('\n', stdout);
1170
1171   printf (_("  Size of section header entries:    %" PRId16 " %s\n"),
1172           ehdr->e_shentsize, _("(bytes)"));
1173
1174   printf (_("  Number of section headers entries: %" PRId16),
1175           ehdr->e_shnum);
1176   if (ehdr->e_shnum == 0)
1177     {
1178       GElf_Shdr shdr_mem;
1179       GElf_Shdr *shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
1180       if (shdr != NULL)
1181         printf (_(" (%" PRIu32 " in [0].sh_size)"),
1182                 (uint32_t) shdr->sh_size);
1183       else
1184         fputs_unlocked (_(" ([0] not available)"), stdout);
1185     }
1186   fputc_unlocked ('\n', stdout);
1187
1188   if (unlikely (ehdr->e_shstrndx == SHN_XINDEX))
1189     {
1190       GElf_Shdr shdr_mem;
1191       GElf_Shdr *shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
1192       if (shdr != NULL)
1193         /* We managed to get the zeroth section.  */
1194         snprintf (buf, sizeof (buf), _(" (%" PRIu32 " in [0].sh_link)"),
1195                   (uint32_t) shdr->sh_link);
1196       else
1197         {
1198           strncpy (buf, _(" ([0] not available)"), sizeof (buf) - 1);
1199           buf[sizeof (buf) - 1] = '\0';
1200         }
1201
1202       printf (_("  Section header string table index: XINDEX%s\n\n"),
1203               buf);
1204     }
1205   else
1206     printf (_("  Section header string table index: %" PRId16 "\n\n"),
1207             ehdr->e_shstrndx);
1208 }
1209
1210
1211 static const char *
1212 get_visibility_type (int value)
1213 {
1214   switch (value)
1215     {
1216     case STV_DEFAULT:
1217       return "DEFAULT";
1218     case STV_INTERNAL:
1219       return "INTERNAL";
1220     case STV_HIDDEN:
1221       return "HIDDEN";
1222     case STV_PROTECTED:
1223       return "PROTECTED";
1224     default:
1225       return "???";
1226     }
1227 }
1228
1229 static const char *
1230 elf_ch_type_name (unsigned int code)
1231 {
1232   if (code == 0)
1233     return "NONE";
1234
1235   if (code == ELFCOMPRESS_ZLIB)
1236     return "ZLIB";
1237
1238   return "UNKNOWN";
1239 }
1240
1241 /* Print the section headers.  */
1242 static void
1243 print_shdr (Ebl *ebl, GElf_Ehdr *ehdr)
1244 {
1245   size_t cnt;
1246   size_t shstrndx;
1247
1248   if (! print_file_header)
1249     {
1250       size_t sections;
1251       if (unlikely (elf_getshdrnum (ebl->elf, &sections) < 0))
1252         error_exit (0, _("cannot get number of sections: %s"),
1253                     elf_errmsg (-1));
1254
1255       printf (_("\
1256 There are %zd section headers, starting at offset %#" PRIx64 ":\n\
1257 \n"),
1258               sections, ehdr->e_shoff);
1259     }
1260
1261   /* Get the section header string table index.  */
1262   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1263     error_exit (0, _("cannot get section header string table index: %s"),
1264                 elf_errmsg (-1));
1265
1266   puts (_("Section Headers:"));
1267
1268   if (ehdr->e_ident[EI_CLASS] == ELFCLASS32)
1269     puts (_("[Nr] Name                 Type         Addr     Off    Size   ES Flags Lk Inf Al"));
1270   else
1271     puts (_("[Nr] Name                 Type         Addr             Off      Size     ES Flags Lk Inf Al"));
1272
1273   if (print_decompress)
1274     {
1275       if (ehdr->e_ident[EI_CLASS] == ELFCLASS32)
1276         puts (_("     [Compression  Size   Al]"));
1277       else
1278         puts (_("     [Compression  Size     Al]"));
1279     }
1280
1281   for (cnt = 0; cnt < shnum; ++cnt)
1282     {
1283       Elf_Scn *scn = elf_getscn (ebl->elf, cnt);
1284
1285       if (unlikely (scn == NULL))
1286         error_exit (0, _("cannot get section: %s"),
1287                     elf_errmsg (-1));
1288
1289       /* Get the section header.  */
1290       GElf_Shdr shdr_mem;
1291       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1292       if (unlikely (shdr == NULL))
1293         error_exit (0, _("cannot get section header: %s"),
1294                     elf_errmsg (-1));
1295
1296       char flagbuf[20];
1297       char *cp = flagbuf;
1298       if (shdr->sh_flags & SHF_WRITE)
1299         *cp++ = 'W';
1300       if (shdr->sh_flags & SHF_ALLOC)
1301         *cp++ = 'A';
1302       if (shdr->sh_flags & SHF_EXECINSTR)
1303         *cp++ = 'X';
1304       if (shdr->sh_flags & SHF_MERGE)
1305         *cp++ = 'M';
1306       if (shdr->sh_flags & SHF_STRINGS)
1307         *cp++ = 'S';
1308       if (shdr->sh_flags & SHF_INFO_LINK)
1309         *cp++ = 'I';
1310       if (shdr->sh_flags & SHF_LINK_ORDER)
1311         *cp++ = 'L';
1312       if (shdr->sh_flags & SHF_OS_NONCONFORMING)
1313         *cp++ = 'N';
1314       if (shdr->sh_flags & SHF_GROUP)
1315         *cp++ = 'G';
1316       if (shdr->sh_flags & SHF_TLS)
1317         *cp++ = 'T';
1318       if (shdr->sh_flags & SHF_COMPRESSED)
1319         *cp++ = 'C';
1320       if (shdr->sh_flags & SHF_ORDERED)
1321         *cp++ = 'O';
1322       if (shdr->sh_flags & SHF_EXCLUDE)
1323         *cp++ = 'E';
1324       if (shdr->sh_flags & SHF_GNU_RETAIN)
1325         *cp++ = 'R';
1326       *cp = '\0';
1327
1328       const char *sname;
1329       char buf[128];
1330       sname = elf_strptr (ebl->elf, shstrndx, shdr->sh_name) ?: "<corrupt>";
1331       printf ("[%2zu] %-20s %-12s %0*" PRIx64 " %0*" PRIx64 " %0*" PRIx64
1332               " %2" PRId64 " %-5s %2" PRId32 " %3" PRId32
1333               " %2" PRId64 "\n",
1334               cnt, sname,
1335               ebl_section_type_name (ebl, shdr->sh_type, buf, sizeof (buf)),
1336               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 8 : 16, shdr->sh_addr,
1337               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 6 : 8, shdr->sh_offset,
1338               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 6 : 8, shdr->sh_size,
1339               shdr->sh_entsize, flagbuf, shdr->sh_link, shdr->sh_info,
1340               shdr->sh_addralign);
1341
1342       if (print_decompress)
1343         {
1344           if ((shdr->sh_flags & SHF_COMPRESSED) != 0)
1345             {
1346               GElf_Chdr chdr;
1347               if (gelf_getchdr (scn, &chdr) != NULL)
1348                 printf ("     [ELF %s (%" PRId32 ") %0*" PRIx64
1349                         " %2" PRId64 "]\n",
1350                         elf_ch_type_name (chdr.ch_type),
1351                         chdr.ch_type,
1352                         ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 6 : 8,
1353                         chdr.ch_size, chdr.ch_addralign);
1354               else
1355                 error (0, 0,
1356                        _("bad compression header for section %zd: %s"),
1357                        elf_ndxscn (scn), elf_errmsg (-1));
1358             }
1359           else if (startswith (sname, ".zdebug"))
1360             {
1361               ssize_t size;
1362               if ((size = dwelf_scn_gnu_compressed_size (scn)) >= 0)
1363                 printf ("     [GNU ZLIB     %0*zx   ]\n",
1364                         ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 6 : 8, size);
1365               else
1366                 error (0, 0,
1367                        _("bad gnu compressed size for section %zd: %s"),
1368                        elf_ndxscn (scn), elf_errmsg (-1));
1369             }
1370         }
1371     }
1372
1373   fputc_unlocked ('\n', stdout);
1374 }
1375
1376
1377 /* Print the program header.  */
1378 static void
1379 print_phdr (Ebl *ebl, GElf_Ehdr *ehdr)
1380 {
1381   if (phnum == 0)
1382     /* No program header, this is OK in relocatable objects.  */
1383     return;
1384
1385   puts (_("Program Headers:"));
1386   if (ehdr->e_ident[EI_CLASS] == ELFCLASS32)
1387     puts (_("\
1388   Type           Offset   VirtAddr   PhysAddr   FileSiz  MemSiz   Flg Align"));
1389   else
1390     puts (_("\
1391   Type           Offset   VirtAddr           PhysAddr           FileSiz  MemSiz   Flg Align"));
1392
1393   /* Process all program headers.  */
1394   bool has_relro = false;
1395   GElf_Addr relro_from = 0;
1396   GElf_Addr relro_to = 0;
1397   for (size_t cnt = 0; cnt < phnum; ++cnt)
1398     {
1399       char buf[128];
1400       GElf_Phdr mem;
1401       GElf_Phdr *phdr = gelf_getphdr (ebl->elf, cnt, &mem);
1402
1403       /* If for some reason the header cannot be returned show this.  */
1404       if (unlikely (phdr == NULL))
1405         {
1406           puts ("  ???");
1407           continue;
1408         }
1409
1410       printf ("  %-14s 0x%06" PRIx64 " 0x%0*" PRIx64 " 0x%0*" PRIx64
1411               " 0x%06" PRIx64 " 0x%06" PRIx64 " %c%c%c 0x%" PRIx64 "\n",
1412               ebl_segment_type_name (ebl, phdr->p_type, buf, sizeof (buf)),
1413               phdr->p_offset,
1414               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 8 : 16, phdr->p_vaddr,
1415               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 8 : 16, phdr->p_paddr,
1416               phdr->p_filesz,
1417               phdr->p_memsz,
1418               phdr->p_flags & PF_R ? 'R' : ' ',
1419               phdr->p_flags & PF_W ? 'W' : ' ',
1420               phdr->p_flags & PF_X ? 'E' : ' ',
1421               phdr->p_align);
1422
1423       if (phdr->p_type == PT_INTERP)
1424         {
1425           /* If we are sure the file offset is valid then we can show
1426              the user the name of the interpreter.  We check whether
1427              there is a section at the file offset.  Normally there
1428              would be a section called ".interp".  But in separate
1429              .debug files it is a NOBITS section (and so doesn't match
1430              with gelf_offscn).  Which probably means the offset is
1431              not valid another reason could be because the ELF file
1432              just doesn't contain any section headers, in that case
1433              just play it safe and don't display anything.  */
1434
1435           Elf_Scn *scn = gelf_offscn (ebl->elf, phdr->p_offset);
1436           GElf_Shdr shdr_mem;
1437           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1438
1439           size_t maxsize;
1440           char *filedata = elf_rawfile (ebl->elf, &maxsize);
1441
1442           if (shdr != NULL && shdr->sh_type == SHT_PROGBITS
1443               && filedata != NULL && phdr->p_offset < maxsize
1444               && phdr->p_filesz <= maxsize - phdr->p_offset
1445               && memchr (filedata + phdr->p_offset, '\0',
1446                          phdr->p_filesz) != NULL)
1447             printf (_("\t[Requesting program interpreter: %s]\n"),
1448                     filedata + phdr->p_offset);
1449         }
1450       else if (phdr->p_type == PT_GNU_RELRO)
1451         {
1452           has_relro = true;
1453           relro_from = phdr->p_vaddr;
1454           relro_to = relro_from + phdr->p_memsz;
1455         }
1456     }
1457
1458   size_t sections;
1459   if (unlikely (elf_getshdrnum (ebl->elf, &sections) < 0))
1460     error_exit (0, _("cannot get number of sections: %s"),
1461                 elf_errmsg (-1));
1462
1463   if (sections == 0)
1464     /* No sections in the file.  Punt.  */
1465     return;
1466
1467   /* Get the section header string table index.  */
1468   size_t shstrndx;
1469   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1470     error_exit (0, _("cannot get section header string table index"));
1471
1472   puts (_("\n Section to Segment mapping:\n  Segment Sections..."));
1473
1474   for (size_t cnt = 0; cnt < phnum; ++cnt)
1475     {
1476       /* Print the segment number.  */
1477       printf ("   %2.2zu     ", cnt);
1478
1479       GElf_Phdr phdr_mem;
1480       GElf_Phdr *phdr = gelf_getphdr (ebl->elf, cnt, &phdr_mem);
1481       /* This must not happen.  */
1482       if (unlikely (phdr == NULL))
1483         error_exit (0, _("cannot get program header: %s"),
1484                     elf_errmsg (-1));
1485
1486       /* Iterate over the sections.  */
1487       bool in_relro = false;
1488       bool in_ro = false;
1489       for (size_t inner = 1; inner < shnum; ++inner)
1490         {
1491           Elf_Scn *scn = elf_getscn (ebl->elf, inner);
1492           /* This should not happen.  */
1493           if (unlikely (scn == NULL))
1494             error_exit (0, _("cannot get section: %s"),
1495                         elf_errmsg (-1));
1496
1497           /* Get the section header.  */
1498           GElf_Shdr shdr_mem;
1499           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1500           if (unlikely (shdr == NULL))
1501             error_exit (0, _("cannot get section header: %s"),
1502                         elf_errmsg (-1));
1503
1504           if (shdr->sh_size > 0
1505               /* Compare allocated sections by VMA, unallocated
1506                  sections by file offset.  */
1507               && (shdr->sh_flags & SHF_ALLOC
1508                   ? (shdr->sh_addr >= phdr->p_vaddr
1509                      && (shdr->sh_addr + shdr->sh_size
1510                          <= phdr->p_vaddr + phdr->p_memsz))
1511                   : (shdr->sh_offset >= phdr->p_offset
1512                      && (shdr->sh_offset + shdr->sh_size
1513                          <= phdr->p_offset + phdr->p_filesz))))
1514             {
1515               if (has_relro && !in_relro
1516                   && shdr->sh_addr >= relro_from
1517                   && shdr->sh_addr + shdr->sh_size <= relro_to)
1518                 {
1519                   fputs_unlocked (" [RELRO:", stdout);
1520                   in_relro = true;
1521                 }
1522               else if (has_relro && in_relro && shdr->sh_addr >= relro_to)
1523                 {
1524                   fputs_unlocked ("]", stdout);
1525                   in_relro =  false;
1526                 }
1527               else if (has_relro && in_relro
1528                        && shdr->sh_addr + shdr->sh_size > relro_to)
1529                 fputs_unlocked ("] <RELRO:", stdout);
1530               else if (phdr->p_type == PT_LOAD && (phdr->p_flags & PF_W) == 0)
1531                 {
1532                   if (!in_ro)
1533                     {
1534                       fputs_unlocked (" [RO:", stdout);
1535                       in_ro = true;
1536                     }
1537                 }
1538               else
1539                 {
1540                   /* Determine the segment this section is part of.  */
1541                   size_t cnt2;
1542                   GElf_Phdr phdr2_mem;
1543                   GElf_Phdr *phdr2 = NULL;
1544                   for (cnt2 = 0; cnt2 < phnum; ++cnt2)
1545                     {
1546                       phdr2 = gelf_getphdr (ebl->elf, cnt2, &phdr2_mem);
1547
1548                       if (phdr2 != NULL && phdr2->p_type == PT_LOAD
1549                           && shdr->sh_addr >= phdr2->p_vaddr
1550                           && (shdr->sh_addr + shdr->sh_size
1551                               <= phdr2->p_vaddr + phdr2->p_memsz))
1552                         break;
1553                     }
1554
1555                   if (cnt2 < phnum)
1556                     {
1557                       if ((phdr2->p_flags & PF_W) == 0 && !in_ro)
1558                         {
1559                           fputs_unlocked (" [RO:", stdout);
1560                           in_ro = true;
1561                         }
1562                       else if ((phdr2->p_flags & PF_W) != 0 && in_ro)
1563                         {
1564                           fputs_unlocked ("]", stdout);
1565                           in_ro = false;
1566                         }
1567                     }
1568                 }
1569
1570               printf (" %s",
1571                       elf_strptr (ebl->elf, shstrndx, shdr->sh_name));
1572
1573               /* Signal that this section is only partially covered.  */
1574               if (has_relro && in_relro
1575                        && shdr->sh_addr + shdr->sh_size > relro_to)
1576                 {
1577                   fputs_unlocked (">", stdout);
1578                   in_relro =  false;
1579                 }
1580             }
1581         }
1582       if (in_relro || in_ro)
1583         fputs_unlocked ("]", stdout);
1584
1585       /* Finish the line.  */
1586       fputc_unlocked ('\n', stdout);
1587     }
1588 }
1589
1590
1591 static const char *
1592 section_name (Ebl *ebl, GElf_Shdr *shdr)
1593 {
1594   size_t shstrndx;
1595   if (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0)
1596     return "???";
1597   return elf_strptr (ebl->elf, shstrndx, shdr->sh_name) ?: "???";
1598 }
1599
1600
1601 static void
1602 handle_scngrp (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
1603 {
1604   /* Get the data of the section.  */
1605   Elf_Data *data = elf_getdata (scn, NULL);
1606
1607   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
1608   GElf_Shdr symshdr_mem;
1609   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
1610   Elf_Data *symdata = elf_getdata (symscn, NULL);
1611
1612   if (data == NULL || data->d_size < sizeof (Elf32_Word) || symshdr == NULL
1613       || symdata == NULL)
1614     return;
1615
1616   /* Get the section header string table index.  */
1617   size_t shstrndx;
1618   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1619     error_exit (0, _("cannot get section header string table index"));
1620
1621   Elf32_Word *grpref = (Elf32_Word *) data->d_buf;
1622
1623   GElf_Sym sym_mem;
1624   GElf_Sym *sym = gelf_getsym (symdata, shdr->sh_info, &sym_mem);
1625
1626   printf ((grpref[0] & GRP_COMDAT)
1627           ? ngettext ("\
1628 \nCOMDAT section group [%2zu] '%s' with signature '%s' contains %zu entry:\n",
1629                       "\
1630 \nCOMDAT section group [%2zu] '%s' with signature '%s' contains %zu entries:\n",
1631                       data->d_size / sizeof (Elf32_Word) - 1)
1632           : ngettext ("\
1633 \nSection group [%2zu] '%s' with signature '%s' contains %zu entry:\n", "\
1634 \nSection group [%2zu] '%s' with signature '%s' contains %zu entries:\n",
1635                       data->d_size / sizeof (Elf32_Word) - 1),
1636           elf_ndxscn (scn),
1637           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
1638           (sym == NULL ? NULL
1639            : elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name))
1640           ?: _("<INVALID SYMBOL>"),
1641           data->d_size / sizeof (Elf32_Word) - 1);
1642
1643   for (size_t cnt = 1; cnt < data->d_size / sizeof (Elf32_Word); ++cnt)
1644     {
1645       GElf_Shdr grpshdr_mem;
1646       GElf_Shdr *grpshdr = gelf_getshdr (elf_getscn (ebl->elf, grpref[cnt]),
1647                                          &grpshdr_mem);
1648
1649       const char *str;
1650       printf ("  [%2u] %s\n",
1651               grpref[cnt],
1652               grpshdr != NULL
1653               && (str = elf_strptr (ebl->elf, shstrndx, grpshdr->sh_name))
1654               ? str : _("<INVALID SECTION>"));
1655     }
1656 }
1657
1658
1659 static void
1660 print_scngrp (Ebl *ebl)
1661 {
1662   /* Find all relocation sections and handle them.  */
1663   Elf_Scn *scn = NULL;
1664
1665   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
1666     {
1667        /* Handle the section if it is a symbol table.  */
1668       GElf_Shdr shdr_mem;
1669       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1670
1671       if (shdr != NULL && shdr->sh_type == SHT_GROUP)
1672         {
1673           if ((shdr->sh_flags & SHF_COMPRESSED) != 0)
1674             {
1675               if (elf_compress (scn, 0, 0) < 0)
1676                 printf ("WARNING: %s [%zd]\n",
1677                         _("Couldn't uncompress section"),
1678                         elf_ndxscn (scn));
1679               shdr = gelf_getshdr (scn, &shdr_mem);
1680               if (unlikely (shdr == NULL))
1681                 error_exit (0, _("cannot get section [%zd] header: %s"),
1682                             elf_ndxscn (scn),
1683                             elf_errmsg (-1));
1684             }
1685           handle_scngrp (ebl, scn, shdr);
1686         }
1687     }
1688 }
1689
1690
1691 static const struct flags
1692 {
1693   int mask;
1694   const char *str;
1695 } dt_flags[] =
1696   {
1697     { DF_ORIGIN, "ORIGIN" },
1698     { DF_SYMBOLIC, "SYMBOLIC" },
1699     { DF_TEXTREL, "TEXTREL" },
1700     { DF_BIND_NOW, "BIND_NOW" },
1701     { DF_STATIC_TLS, "STATIC_TLS" }
1702   };
1703 static const int ndt_flags = sizeof (dt_flags) / sizeof (dt_flags[0]);
1704
1705 static const struct flags dt_flags_1[] =
1706   {
1707     { DF_1_NOW, "NOW" },
1708     { DF_1_GLOBAL, "GLOBAL" },
1709     { DF_1_GROUP, "GROUP" },
1710     { DF_1_NODELETE, "NODELETE" },
1711     { DF_1_LOADFLTR, "LOADFLTR" },
1712     { DF_1_INITFIRST, "INITFIRST" },
1713     { DF_1_NOOPEN, "NOOPEN" },
1714     { DF_1_ORIGIN, "ORIGIN" },
1715     { DF_1_DIRECT, "DIRECT" },
1716     { DF_1_TRANS, "TRANS" },
1717     { DF_1_INTERPOSE, "INTERPOSE" },
1718     { DF_1_NODEFLIB, "NODEFLIB" },
1719     { DF_1_NODUMP, "NODUMP" },
1720     { DF_1_CONFALT, "CONFALT" },
1721     { DF_1_ENDFILTEE, "ENDFILTEE" },
1722     { DF_1_DISPRELDNE, "DISPRELDNE" },
1723     { DF_1_DISPRELPND, "DISPRELPND" },
1724   };
1725 static const int ndt_flags_1 = sizeof (dt_flags_1) / sizeof (dt_flags_1[0]);
1726
1727 static const struct flags dt_feature_1[] =
1728   {
1729     { DTF_1_PARINIT, "PARINIT" },
1730     { DTF_1_CONFEXP, "CONFEXP" }
1731   };
1732 static const int ndt_feature_1 = (sizeof (dt_feature_1)
1733                                   / sizeof (dt_feature_1[0]));
1734
1735 static const struct flags dt_posflag_1[] =
1736   {
1737     { DF_P1_LAZYLOAD, "LAZYLOAD" },
1738     { DF_P1_GROUPPERM, "GROUPPERM" }
1739   };
1740 static const int ndt_posflag_1 = (sizeof (dt_posflag_1)
1741                                   / sizeof (dt_posflag_1[0]));
1742
1743
1744 static void
1745 print_flags (int class, GElf_Xword d_val, const struct flags *flags,
1746                 int nflags)
1747 {
1748   bool first = true;
1749   int cnt;
1750
1751   for (cnt = 0; cnt < nflags; ++cnt)
1752     if (d_val & flags[cnt].mask)
1753       {
1754         if (!first)
1755           putchar_unlocked (' ');
1756         fputs_unlocked (flags[cnt].str, stdout);
1757         d_val &= ~flags[cnt].mask;
1758         first = false;
1759       }
1760
1761   if (d_val != 0)
1762     {
1763       if (!first)
1764         putchar_unlocked (' ');
1765       printf ("%#0*" PRIx64, class == ELFCLASS32 ? 10 : 18, d_val);
1766     }
1767
1768   putchar_unlocked ('\n');
1769 }
1770
1771
1772 static void
1773 print_dt_flags (int class, GElf_Xword d_val)
1774 {
1775   print_flags (class, d_val, dt_flags, ndt_flags);
1776 }
1777
1778
1779 static void
1780 print_dt_flags_1 (int class, GElf_Xword d_val)
1781 {
1782   print_flags (class, d_val, dt_flags_1, ndt_flags_1);
1783 }
1784
1785
1786 static void
1787 print_dt_feature_1 (int class, GElf_Xword d_val)
1788 {
1789   print_flags (class, d_val, dt_feature_1, ndt_feature_1);
1790 }
1791
1792
1793 static void
1794 print_dt_posflag_1 (int class, GElf_Xword d_val)
1795 {
1796   print_flags (class, d_val, dt_posflag_1, ndt_posflag_1);
1797 }
1798
1799
1800 static size_t
1801 get_dyn_ents (Elf_Data * dyn_data)
1802 {
1803   GElf_Dyn *dyn;
1804   GElf_Dyn dyn_mem;
1805   size_t dyn_idx = 0;
1806   do
1807     {
1808       dyn = gelf_getdyn(dyn_data, dyn_idx, &dyn_mem);
1809       if (dyn != NULL)
1810         ++dyn_idx;
1811     }
1812   while (dyn != NULL && dyn->d_tag != DT_NULL);
1813
1814   return dyn_idx;
1815 }
1816
1817
1818 static void
1819 handle_dynamic (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, GElf_Phdr *phdr)
1820 {
1821   int class = gelf_getclass (ebl->elf);
1822   GElf_Shdr glink_mem;
1823   GElf_Shdr *glink;
1824   Elf_Data *data;
1825   size_t cnt;
1826   size_t shstrndx;
1827   size_t dyn_ents;
1828
1829   /* Get the data of the section.  */
1830   if (use_dynamic_segment)
1831     data = elf_getdata_rawchunk(ebl->elf, phdr->p_offset,
1832                                 phdr->p_filesz, ELF_T_DYN);
1833   else
1834     data = elf_getdata (scn, NULL);
1835
1836   if (data == NULL)
1837     return;
1838
1839   /* Get the dynamic section entry number */
1840   dyn_ents = get_dyn_ents (data);
1841
1842   if (!use_dynamic_segment)
1843     {
1844       /* Get the section header string table index.  */
1845       if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1846         error_exit (0, _("cannot get section header string table index"));
1847
1848       glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link), &glink_mem);
1849       if (glink == NULL)
1850         error_exit (0, _("invalid sh_link value in section %zu"),
1851                     elf_ndxscn (scn));
1852
1853       printf (ngettext ("\
1854 \nDynamic segment contains %lu entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
1855                     "\
1856 \nDynamic segment contains %lu entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
1857                         dyn_ents),
1858               (unsigned long int) dyn_ents,
1859               class == ELFCLASS32 ? 10 : 18, shdr->sh_addr,
1860               shdr->sh_offset,
1861               (int) shdr->sh_link,
1862               elf_strptr (ebl->elf, shstrndx, glink->sh_name));
1863     }
1864   else
1865     {
1866       printf (ngettext ("\
1867 \nDynamic segment contains %lu entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "\n",
1868                     "\
1869 \nDynamic segment contains %lu entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "\n",
1870                         dyn_ents),
1871               (unsigned long int) dyn_ents,
1872               class == ELFCLASS32 ? 10 : 18, phdr->p_paddr,
1873               phdr->p_offset);
1874     }
1875
1876   fputs_unlocked (_("  Type              Value\n"), stdout);
1877
1878   /* if --use-dynamic option is enabled,
1879      use the string table to get the related library info.  */
1880   Elf_Data *strtab_data = NULL;
1881   if (use_dynamic_segment)
1882     {
1883       strtab_data = get_dynscn_strtab(ebl->elf, phdr);
1884       if (strtab_data == NULL)
1885         error_exit (0, _("cannot get string table by using dynamic segment"));
1886     }
1887
1888   for (cnt = 0; cnt < dyn_ents; ++cnt)
1889     {
1890       GElf_Dyn dynmem;
1891       GElf_Dyn *dyn = gelf_getdyn (data, cnt, &dynmem);
1892       if (dyn == NULL)
1893         break;
1894
1895       char buf[64];
1896       printf ("  %-17s ",
1897               ebl_dynamic_tag_name (ebl, dyn->d_tag, buf, sizeof (buf)));
1898
1899       char *name = NULL;
1900       if (dyn->d_tag == DT_NEEDED
1901           || dyn->d_tag == DT_SONAME
1902           || dyn->d_tag == DT_RPATH
1903           || dyn->d_tag == DT_RUNPATH)
1904         {
1905           if (! use_dynamic_segment)
1906             name = elf_strptr (ebl->elf, shdr->sh_link, dyn->d_un.d_val);
1907           else if (dyn->d_un.d_val < strtab_data->d_size
1908                    && memrchr (strtab_data->d_buf + dyn->d_un.d_val, '\0',
1909                                strtab_data->d_size - 1 - dyn->d_un.d_val) != NULL)
1910             name = ((char *) strtab_data->d_buf) + dyn->d_un.d_val;
1911         }
1912
1913       switch (dyn->d_tag)
1914         {
1915         case DT_NULL:
1916         case DT_DEBUG:
1917         case DT_BIND_NOW:
1918         case DT_TEXTREL:
1919           /* No further output.  */
1920           fputc_unlocked ('\n', stdout);
1921           break;
1922
1923         case DT_NEEDED:
1924           printf (_("Shared library: [%s]\n"), name);
1925           break;
1926
1927         case DT_SONAME:
1928           printf (_("Library soname: [%s]\n"), name);
1929           break;
1930
1931         case DT_RPATH:
1932           printf (_("Library rpath: [%s]\n"), name);
1933           break;
1934
1935         case DT_RUNPATH:
1936           printf (_("Library runpath: [%s]\n"), name);
1937           break;
1938
1939         case DT_PLTRELSZ:
1940         case DT_RELASZ:
1941         case DT_STRSZ:
1942         case DT_RELSZ:
1943         case DT_RELAENT:
1944         case DT_SYMENT:
1945         case DT_RELENT:
1946         case DT_PLTPADSZ:
1947         case DT_MOVEENT:
1948         case DT_MOVESZ:
1949         case DT_INIT_ARRAYSZ:
1950         case DT_FINI_ARRAYSZ:
1951         case DT_SYMINSZ:
1952         case DT_SYMINENT:
1953         case DT_GNU_CONFLICTSZ:
1954         case DT_GNU_LIBLISTSZ:
1955           printf (_("%" PRId64 " (bytes)\n"), dyn->d_un.d_val);
1956           break;
1957
1958         case DT_VERDEFNUM:
1959         case DT_VERNEEDNUM:
1960         case DT_RELACOUNT:
1961         case DT_RELCOUNT:
1962           printf ("%" PRId64 "\n", dyn->d_un.d_val);
1963           break;
1964
1965         case DT_PLTREL:;
1966           const char *tagname = ebl_dynamic_tag_name (ebl, dyn->d_un.d_val,
1967                                                       NULL, 0);
1968           puts (tagname ?: "???");
1969           break;
1970
1971         case DT_FLAGS:
1972           print_dt_flags (class, dyn->d_un.d_val);
1973           break;
1974
1975         case DT_FLAGS_1:
1976           print_dt_flags_1 (class, dyn->d_un.d_val);
1977           break;
1978
1979         case DT_FEATURE_1:
1980           print_dt_feature_1 (class, dyn->d_un.d_val);
1981           break;
1982
1983         case DT_POSFLAG_1:
1984           print_dt_posflag_1 (class, dyn->d_un.d_val);
1985           break;
1986
1987         default:
1988           printf ("%#0*" PRIx64 "\n",
1989                   class == ELFCLASS32 ? 10 : 18, dyn->d_un.d_val);
1990           break;
1991         }
1992     }
1993 }
1994
1995
1996 /* Print the dynamic segment.  */
1997 static void
1998 print_dynamic (Ebl *ebl)
1999 {
2000   for (size_t i = 0; i < phnum; ++i)
2001     {
2002       GElf_Phdr phdr_mem;
2003       GElf_Phdr *phdr = gelf_getphdr (ebl->elf, i, &phdr_mem);
2004
2005       if (phdr != NULL && phdr->p_type == PT_DYNAMIC)
2006         {
2007           Elf_Scn *scn = gelf_offscn (ebl->elf, phdr->p_offset);
2008           GElf_Shdr shdr_mem;
2009           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
2010           if ((use_dynamic_segment && phdr != NULL)
2011               || (shdr != NULL && shdr->sh_type == SHT_DYNAMIC))
2012             handle_dynamic (ebl, scn, shdr, phdr);
2013           break;
2014         }
2015     }
2016 }
2017
2018
2019 /* Print relocations.  */
2020 static void
2021 print_relocs (Ebl *ebl, GElf_Ehdr *ehdr)
2022 {
2023   /* Find all relocation sections and handle them.  */
2024   Elf_Scn *scn = NULL;
2025
2026   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
2027     {
2028        /* Handle the section if it is a symbol table.  */
2029       GElf_Shdr shdr_mem;
2030       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
2031
2032       if (likely (shdr != NULL))
2033         {
2034           if (shdr->sh_type == SHT_REL)
2035             handle_relocs_rel (ebl, ehdr, scn, shdr);
2036           else if (shdr->sh_type == SHT_RELA)
2037             handle_relocs_rela (ebl, ehdr, scn, shdr);
2038         }
2039     }
2040 }
2041
2042
2043 /* Handle a relocation section.  */
2044 static void
2045 handle_relocs_rel (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn, GElf_Shdr *shdr)
2046 {
2047   int class = gelf_getclass (ebl->elf);
2048   size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_REL, 1, EV_CURRENT);
2049   int nentries = shdr->sh_size / sh_entsize;
2050
2051   /* Get the data of the section.  */
2052   Elf_Data *data = elf_getdata (scn, NULL);
2053   if (data == NULL)
2054     return;
2055
2056   /* Get the symbol table information.  */
2057   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
2058   GElf_Shdr symshdr_mem;
2059   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
2060   Elf_Data *symdata = elf_getdata (symscn, NULL);
2061
2062   /* Get the section header of the section the relocations are for.  */
2063   GElf_Shdr destshdr_mem;
2064   GElf_Shdr *destshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_info),
2065                                       &destshdr_mem);
2066
2067   if (unlikely (symshdr == NULL || symdata == NULL || destshdr == NULL))
2068     {
2069       printf (_("\nInvalid symbol table at offset %#0" PRIx64 "\n"),
2070               shdr->sh_offset);
2071       return;
2072     }
2073
2074   /* Search for the optional extended section index table.  */
2075   Elf_Data *xndxdata = NULL;
2076   int xndxscnidx = elf_scnshndx (scn);
2077   if (unlikely (xndxscnidx > 0))
2078     xndxdata = elf_getdata (elf_getscn (ebl->elf, xndxscnidx), NULL);
2079
2080   /* Get the section header string table index.  */
2081   size_t shstrndx;
2082   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2083     error_exit (0, _("cannot get section header string table index"));
2084
2085   if (shdr->sh_info != 0)
2086     printf (ngettext ("\
2087 \nRelocation section [%2zu] '%s' for section [%2u] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
2088                     "\
2089 \nRelocation section [%2zu] '%s' for section [%2u] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
2090                       nentries),
2091             elf_ndxscn (scn),
2092             elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2093             (unsigned int) shdr->sh_info,
2094             elf_strptr (ebl->elf, shstrndx, destshdr->sh_name),
2095             shdr->sh_offset,
2096             nentries);
2097   else
2098     /* The .rel.dyn section does not refer to a specific section but
2099        instead of section index zero.  Do not try to print a section
2100        name.  */
2101     printf (ngettext ("\
2102 \nRelocation section [%2u] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
2103                     "\
2104 \nRelocation section [%2u] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
2105                       nentries),
2106             (unsigned int) elf_ndxscn (scn),
2107             elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2108             shdr->sh_offset,
2109             nentries);
2110   fputs_unlocked (class == ELFCLASS32
2111                   ? _("\
2112   Offset      Type                 Value       Name\n")
2113                   : _("\
2114   Offset              Type                 Value               Name\n"),
2115          stdout);
2116
2117   int is_statically_linked = 0;
2118   for (int cnt = 0; cnt < nentries; ++cnt)
2119     {
2120       GElf_Rel relmem;
2121       GElf_Rel *rel = gelf_getrel (data, cnt, &relmem);
2122       if (likely (rel != NULL))
2123         {
2124           char buf[128];
2125           GElf_Sym symmem;
2126           Elf32_Word xndx;
2127           GElf_Sym *sym = gelf_getsymshndx (symdata, xndxdata,
2128                                             GELF_R_SYM (rel->r_info),
2129                                             &symmem, &xndx);
2130           if (unlikely (sym == NULL))
2131             {
2132               /* As a special case we have to handle relocations in static
2133                  executables.  This only happens for IRELATIVE relocations
2134                  (so far).  There is no symbol table.  */
2135               if (is_statically_linked == 0)
2136                 {
2137                   /* Find the program header and look for a PT_INTERP entry. */
2138                   is_statically_linked = -1;
2139                   if (ehdr->e_type == ET_EXEC)
2140                     {
2141                       is_statically_linked = 1;
2142
2143                       for (size_t inner = 0; inner < phnum; ++inner)
2144                         {
2145                           GElf_Phdr phdr_mem;
2146                           GElf_Phdr *phdr = gelf_getphdr (ebl->elf, inner,
2147                                                           &phdr_mem);
2148                           if (phdr != NULL && phdr->p_type == PT_INTERP)
2149                             {
2150                               is_statically_linked = -1;
2151                               break;
2152                             }
2153                         }
2154                     }
2155                 }
2156
2157               if (is_statically_linked > 0 && shdr->sh_link == 0)
2158                 printf ("\
2159   %#0*" PRIx64 "  %-20s %*s  %s\n",
2160                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2161                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2162                         /* Avoid the leading R_ which isn't carrying any
2163                            information.  */
2164                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2165                                                buf, sizeof (buf)) + 2
2166                         : _("<INVALID RELOC>"),
2167                         class == ELFCLASS32 ? 10 : 18, "",
2168                         elf_strptr (ebl->elf, shstrndx, destshdr->sh_name));
2169               else
2170                 printf ("  %#0*" PRIx64 "  %-20s <%s %ld>\n",
2171                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2172                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2173                         /* Avoid the leading R_ which isn't carrying any
2174                            information.  */
2175                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2176                                                buf, sizeof (buf)) + 2
2177                         : _("<INVALID RELOC>"),
2178                         _("INVALID SYMBOL"),
2179                         (long int) GELF_R_SYM (rel->r_info));
2180             }
2181           else if (GELF_ST_TYPE (sym->st_info) != STT_SECTION)
2182             printf ("  %#0*" PRIx64 "  %-20s %#0*" PRIx64 "  %s\n",
2183                     class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2184                     likely (ebl_reloc_type_check (ebl,
2185                                                   GELF_R_TYPE (rel->r_info)))
2186                     /* Avoid the leading R_ which isn't carrying any
2187                        information.  */
2188                     ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2189                                            buf, sizeof (buf)) + 2
2190                     : _("<INVALID RELOC>"),
2191                     class == ELFCLASS32 ? 10 : 18, sym->st_value,
2192                     elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name));
2193           else
2194             {
2195               /* This is a relocation against a STT_SECTION symbol.  */
2196               GElf_Shdr secshdr_mem;
2197               GElf_Shdr *secshdr;
2198               secshdr = gelf_getshdr (elf_getscn (ebl->elf,
2199                                                   sym->st_shndx == SHN_XINDEX
2200                                                   ? xndx : sym->st_shndx),
2201                                       &secshdr_mem);
2202
2203               if (unlikely (secshdr == NULL))
2204                 printf ("  %#0*" PRIx64 "  %-20s <%s %ld>\n",
2205                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2206                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2207                         /* Avoid the leading R_ which isn't carrying any
2208                            information.  */
2209                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2210                                                buf, sizeof (buf)) + 2
2211                         : _("<INVALID RELOC>"),
2212                         _("INVALID SECTION"),
2213                         (long int) (sym->st_shndx == SHN_XINDEX
2214                                     ? xndx : sym->st_shndx));
2215               else
2216                 printf ("  %#0*" PRIx64 "  %-20s %#0*" PRIx64 "  %s\n",
2217                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2218                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2219                         /* Avoid the leading R_ which isn't carrying any
2220                            information.  */
2221                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2222                                                buf, sizeof (buf)) + 2
2223                         : _("<INVALID RELOC>"),
2224                         class == ELFCLASS32 ? 10 : 18, sym->st_value,
2225                         elf_strptr (ebl->elf, shstrndx, secshdr->sh_name));
2226             }
2227         }
2228     }
2229 }
2230
2231
2232 /* Handle a relocation section.  */
2233 static void
2234 handle_relocs_rela (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn, GElf_Shdr *shdr)
2235 {
2236   int class = gelf_getclass (ebl->elf);
2237   size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_RELA, 1, EV_CURRENT);
2238   int nentries = shdr->sh_size / sh_entsize;
2239
2240   /* Get the data of the section.  */
2241   Elf_Data *data = elf_getdata (scn, NULL);
2242   if (data == NULL)
2243     return;
2244
2245   /* Get the symbol table information.  */
2246   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
2247   GElf_Shdr symshdr_mem;
2248   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
2249   Elf_Data *symdata = elf_getdata (symscn, NULL);
2250
2251   /* Get the section header of the section the relocations are for.  */
2252   GElf_Shdr destshdr_mem;
2253   GElf_Shdr *destshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_info),
2254                                       &destshdr_mem);
2255
2256   if (unlikely (symshdr == NULL || symdata == NULL || destshdr == NULL))
2257     {
2258       printf (_("\nInvalid symbol table at offset %#0" PRIx64 "\n"),
2259               shdr->sh_offset);
2260       return;
2261     }
2262
2263   /* Search for the optional extended section index table.  */
2264   Elf_Data *xndxdata = NULL;
2265   int xndxscnidx = elf_scnshndx (scn);
2266   if (unlikely (xndxscnidx > 0))
2267     xndxdata = elf_getdata (elf_getscn (ebl->elf, xndxscnidx), NULL);
2268
2269   /* Get the section header string table index.  */
2270   size_t shstrndx;
2271   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2272     error_exit (0, _("cannot get section header string table index"));
2273
2274   if (shdr->sh_info != 0)
2275     printf (ngettext ("\
2276 \nRelocation section [%2zu] '%s' for section [%2u] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
2277                     "\
2278 \nRelocation section [%2zu] '%s' for section [%2u] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
2279                     nentries),
2280           elf_ndxscn (scn),
2281           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2282           (unsigned int) shdr->sh_info,
2283           elf_strptr (ebl->elf, shstrndx, destshdr->sh_name),
2284           shdr->sh_offset,
2285           nentries);
2286   else
2287     /* The .rela.dyn section does not refer to a specific section but
2288        instead of section index zero.  Do not try to print a section
2289        name.  */
2290     printf (ngettext ("\
2291 \nRelocation section [%2u] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
2292                     "\
2293 \nRelocation section [%2u] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
2294                       nentries),
2295             (unsigned int) elf_ndxscn (scn),
2296             elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2297             shdr->sh_offset,
2298             nentries);
2299   fputs_unlocked (class == ELFCLASS32
2300                   ? _("\
2301   Offset      Type            Value       Addend Name\n")
2302                   : _("\
2303   Offset              Type            Value               Addend Name\n"),
2304                   stdout);
2305
2306   int is_statically_linked = 0;
2307   for (int cnt = 0; cnt < nentries; ++cnt)
2308     {
2309       GElf_Rela relmem;
2310       GElf_Rela *rel = gelf_getrela (data, cnt, &relmem);
2311       if (likely (rel != NULL))
2312         {
2313           char buf[64];
2314           GElf_Sym symmem;
2315           Elf32_Word xndx;
2316           GElf_Sym *sym = gelf_getsymshndx (symdata, xndxdata,
2317                                             GELF_R_SYM (rel->r_info),
2318                                             &symmem, &xndx);
2319
2320           if (unlikely (sym == NULL))
2321             {
2322               /* As a special case we have to handle relocations in static
2323                  executables.  This only happens for IRELATIVE relocations
2324                  (so far).  There is no symbol table.  */
2325               if (is_statically_linked == 0)
2326                 {
2327                   /* Find the program header and look for a PT_INTERP entry. */
2328                   is_statically_linked = -1;
2329                   if (ehdr->e_type == ET_EXEC)
2330                     {
2331                       is_statically_linked = 1;
2332
2333                       for (size_t inner = 0; inner < phnum; ++inner)
2334                         {
2335                           GElf_Phdr phdr_mem;
2336                           GElf_Phdr *phdr = gelf_getphdr (ebl->elf, inner,
2337                                                           &phdr_mem);
2338                           if (phdr != NULL && phdr->p_type == PT_INTERP)
2339                             {
2340                               is_statically_linked = -1;
2341                               break;
2342                             }
2343                         }
2344                     }
2345                 }
2346
2347               if (is_statically_linked > 0 && shdr->sh_link == 0)
2348                 printf ("\
2349   %#0*" PRIx64 "  %-15s %*s  %#6" PRIx64 " %s\n",
2350                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2351                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2352                         /* Avoid the leading R_ which isn't carrying any
2353                            information.  */
2354                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2355                                                buf, sizeof (buf)) + 2
2356                         : _("<INVALID RELOC>"),
2357                         class == ELFCLASS32 ? 10 : 18, "",
2358                         rel->r_addend,
2359                         elf_strptr (ebl->elf, shstrndx, destshdr->sh_name));
2360               else
2361                 printf ("  %#0*" PRIx64 "  %-15s <%s %ld>\n",
2362                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2363                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2364                         /* Avoid the leading R_ which isn't carrying any
2365                            information.  */
2366                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2367                                                buf, sizeof (buf)) + 2
2368                         : _("<INVALID RELOC>"),
2369                         _("INVALID SYMBOL"),
2370                         (long int) GELF_R_SYM (rel->r_info));
2371             }
2372           else if (GELF_ST_TYPE (sym->st_info) != STT_SECTION)
2373             printf ("\
2374   %#0*" PRIx64 "  %-15s %#0*" PRIx64 "  %+6" PRId64 " %s\n",
2375                     class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2376                     likely (ebl_reloc_type_check (ebl,
2377                                                   GELF_R_TYPE (rel->r_info)))
2378                     /* Avoid the leading R_ which isn't carrying any
2379                        information.  */
2380                     ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2381                                            buf, sizeof (buf)) + 2
2382                     : _("<INVALID RELOC>"),
2383                     class == ELFCLASS32 ? 10 : 18, sym->st_value,
2384                     rel->r_addend,
2385                     elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name));
2386           else
2387             {
2388               /* This is a relocation against a STT_SECTION symbol.  */
2389               GElf_Shdr secshdr_mem;
2390               GElf_Shdr *secshdr;
2391               secshdr = gelf_getshdr (elf_getscn (ebl->elf,
2392                                                   sym->st_shndx == SHN_XINDEX
2393                                                   ? xndx : sym->st_shndx),
2394                                       &secshdr_mem);
2395
2396               if (unlikely (secshdr == NULL))
2397                 printf ("  %#0*" PRIx64 "  %-15s <%s %ld>\n",
2398                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2399                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2400                         /* Avoid the leading R_ which isn't carrying any
2401                            information.  */
2402                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2403                                                buf, sizeof (buf)) + 2
2404                         : _("<INVALID RELOC>"),
2405                         _("INVALID SECTION"),
2406                         (long int) (sym->st_shndx == SHN_XINDEX
2407                                     ? xndx : sym->st_shndx));
2408               else
2409                 printf ("\
2410   %#0*" PRIx64 "  %-15s %#0*" PRIx64 "  %+6" PRId64 " %s\n",
2411                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2412                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2413                         /* Avoid the leading R_ which isn't carrying any
2414                            information.  */
2415                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2416                                                buf, sizeof (buf)) + 2
2417                         : _("<INVALID RELOC>"),
2418                         class == ELFCLASS32 ? 10 : 18, sym->st_value,
2419                         rel->r_addend,
2420                         elf_strptr (ebl->elf, shstrndx, secshdr->sh_name));
2421             }
2422         }
2423     }
2424 }
2425
2426
2427 /* Print the program header.  */
2428 static void
2429 print_symtab (Ebl *ebl, int type)
2430 {
2431   /* Find the symbol table(s).  For this we have to search through the
2432      section table.  */
2433   Elf_Scn *scn = NULL;
2434
2435   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
2436     {
2437       /* Handle the section if it is a symbol table.  */
2438       GElf_Shdr shdr_mem;
2439       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
2440
2441       if (shdr != NULL && shdr->sh_type == (GElf_Word) type)
2442         {
2443           if (symbol_table_section != NULL)
2444             {
2445               /* Get the section header string table index.  */
2446               size_t shstrndx;
2447               const char *sname;
2448               if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2449                 error_exit (0,
2450                             _("cannot get section header string table index"));
2451               sname = elf_strptr (ebl->elf, shstrndx, shdr->sh_name);
2452               if (sname == NULL || strcmp (sname, symbol_table_section) != 0)
2453                 continue;
2454             }
2455
2456           if ((shdr->sh_flags & SHF_COMPRESSED) != 0)
2457             {
2458               if (elf_compress (scn, 0, 0) < 0)
2459                 printf ("WARNING: %s [%zd]\n",
2460                         _("Couldn't uncompress section"),
2461                         elf_ndxscn (scn));
2462               shdr = gelf_getshdr (scn, &shdr_mem);
2463               if (unlikely (shdr == NULL))
2464                 error_exit (0,
2465                             _("cannot get section [%zd] header: %s"),
2466                             elf_ndxscn (scn), elf_errmsg (-1));
2467             }
2468           handle_symtab (ebl, scn, shdr);
2469         }
2470     }
2471 }
2472
2473
2474 static void
2475 handle_symtab (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
2476 {
2477   Elf_Data *versym_data = NULL;
2478   Elf_Data *verneed_data = NULL;
2479   Elf_Data *verdef_data = NULL;
2480   Elf_Data *xndx_data = NULL;
2481   int class = gelf_getclass (ebl->elf);
2482   Elf32_Word verneed_stridx = 0;
2483   Elf32_Word verdef_stridx = 0;
2484
2485   /* Get the data of the section.  */
2486   Elf_Data *data = elf_getdata (scn, NULL);
2487   if (data == NULL)
2488     return;
2489
2490   /* Find out whether we have other sections we might need.  */
2491   Elf_Scn *runscn = NULL;
2492   while ((runscn = elf_nextscn (ebl->elf, runscn)) != NULL)
2493     {
2494       GElf_Shdr runshdr_mem;
2495       GElf_Shdr *runshdr = gelf_getshdr (runscn, &runshdr_mem);
2496
2497       if (likely (runshdr != NULL))
2498         {
2499           if (runshdr->sh_type == SHT_GNU_versym
2500               && runshdr->sh_link == elf_ndxscn (scn))
2501             /* Bingo, found the version information.  Now get the data.  */
2502             versym_data = elf_getdata (runscn, NULL);
2503           else if (runshdr->sh_type == SHT_GNU_verneed)
2504             {
2505               /* This is the information about the needed versions.  */
2506               verneed_data = elf_getdata (runscn, NULL);
2507               verneed_stridx = runshdr->sh_link;
2508             }
2509           else if (runshdr->sh_type == SHT_GNU_verdef)
2510             {
2511               /* This is the information about the defined versions.  */
2512               verdef_data = elf_getdata (runscn, NULL);
2513               verdef_stridx = runshdr->sh_link;
2514             }
2515           else if (runshdr->sh_type == SHT_SYMTAB_SHNDX
2516               && runshdr->sh_link == elf_ndxscn (scn))
2517             /* Extended section index.  */
2518             xndx_data = elf_getdata (runscn, NULL);
2519         }
2520     }
2521
2522   /* Get the section header string table index.  */
2523   size_t shstrndx;
2524   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2525     error_exit (0, _("cannot get section header string table index"));
2526
2527   GElf_Shdr glink_mem;
2528   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
2529                                    &glink_mem);
2530   if (glink == NULL)
2531     error_exit (0, _("invalid sh_link value in section %zu"),
2532                 elf_ndxscn (scn));
2533
2534   /* Now we can compute the number of entries in the section.  */
2535   unsigned int nsyms = data->d_size / (class == ELFCLASS32
2536                                        ? sizeof (Elf32_Sym)
2537                                        : sizeof (Elf64_Sym));
2538
2539   printf (ngettext ("\nSymbol table [%2u] '%s' contains %u entry:\n",
2540                     "\nSymbol table [%2u] '%s' contains %u entries:\n",
2541                     nsyms),
2542           (unsigned int) elf_ndxscn (scn),
2543           elf_strptr (ebl->elf, shstrndx, shdr->sh_name), nsyms);
2544   printf (ngettext (" %lu local symbol  String table: [%2u] '%s'\n",
2545                     " %lu local symbols  String table: [%2u] '%s'\n",
2546                     shdr->sh_info),
2547           (unsigned long int) shdr->sh_info,
2548           (unsigned int) shdr->sh_link,
2549           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
2550
2551   fputs_unlocked (class == ELFCLASS32
2552                   ? _("\
2553   Num:    Value   Size Type    Bind   Vis          Ndx Name\n")
2554                   : _("\
2555   Num:            Value   Size Type    Bind   Vis          Ndx Name\n"),
2556                   stdout);
2557
2558   for (unsigned int cnt = 0; cnt < nsyms; ++cnt)
2559     {
2560       char typebuf[64];
2561       char bindbuf[64];
2562       char scnbuf[64];
2563       Elf32_Word xndx;
2564       GElf_Sym sym_mem;
2565       GElf_Sym *sym = gelf_getsymshndx (data, xndx_data, cnt, &sym_mem, &xndx);
2566
2567       if (unlikely (sym == NULL))
2568         continue;
2569
2570       /* Determine the real section index.  */
2571       if (likely (sym->st_shndx != SHN_XINDEX))
2572         xndx = sym->st_shndx;
2573
2574       printf (_("\
2575 %5u: %0*" PRIx64 " %6" PRId64 " %-7s %-6s %-9s %6s %s"),
2576               cnt,
2577               class == ELFCLASS32 ? 8 : 16,
2578               sym->st_value,
2579               sym->st_size,
2580               ebl_symbol_type_name (ebl, GELF_ST_TYPE (sym->st_info),
2581                                     typebuf, sizeof (typebuf)),
2582               ebl_symbol_binding_name (ebl, GELF_ST_BIND (sym->st_info),
2583                                        bindbuf, sizeof (bindbuf)),
2584               get_visibility_type (GELF_ST_VISIBILITY (sym->st_other)),
2585               ebl_section_name (ebl, sym->st_shndx, xndx, scnbuf,
2586                                 sizeof (scnbuf), NULL, shnum),
2587               elf_strptr (ebl->elf, shdr->sh_link, sym->st_name));
2588
2589       if (versym_data != NULL)
2590         {
2591           /* Get the version information.  */
2592           GElf_Versym versym_mem;
2593           GElf_Versym *versym = gelf_getversym (versym_data, cnt, &versym_mem);
2594
2595           if (versym != NULL && ((*versym & 0x8000) != 0 || *versym > 1))
2596             {
2597               bool is_nobits = false;
2598               bool check_def = xndx != SHN_UNDEF;
2599
2600               if (xndx < SHN_LORESERVE || sym->st_shndx == SHN_XINDEX)
2601                 {
2602                   GElf_Shdr symshdr_mem;
2603                   GElf_Shdr *symshdr =
2604                     gelf_getshdr (elf_getscn (ebl->elf, xndx), &symshdr_mem);
2605
2606                   is_nobits = (symshdr != NULL
2607                                && symshdr->sh_type == SHT_NOBITS);
2608                 }
2609
2610               if (is_nobits || ! check_def)
2611                 {
2612                   /* We must test both.  */
2613                   GElf_Vernaux vernaux_mem;
2614                   GElf_Vernaux *vernaux = NULL;
2615                   size_t vn_offset = 0;
2616
2617                   GElf_Verneed verneed_mem;
2618                   GElf_Verneed *verneed = gelf_getverneed (verneed_data, 0,
2619                                                            &verneed_mem);
2620                   while (verneed != NULL)
2621                     {
2622                       size_t vna_offset = vn_offset;
2623
2624                       vernaux = gelf_getvernaux (verneed_data,
2625                                                  vna_offset += verneed->vn_aux,
2626                                                  &vernaux_mem);
2627                       while (vernaux != NULL
2628                              && vernaux->vna_other != *versym
2629                              && vernaux->vna_next != 0
2630                              && (verneed_data->d_size - vna_offset
2631                                  >= vernaux->vna_next))
2632                         {
2633                           /* Update the offset.  */
2634                           vna_offset += vernaux->vna_next;
2635
2636                           vernaux = (vernaux->vna_next == 0
2637                                      ? NULL
2638                                      : gelf_getvernaux (verneed_data,
2639                                                         vna_offset,
2640                                                         &vernaux_mem));
2641                         }
2642
2643                       /* Check whether we found the version.  */
2644                       if (vernaux != NULL && vernaux->vna_other == *versym)
2645                         /* Found it.  */
2646                         break;
2647
2648                       if (verneed_data->d_size - vn_offset < verneed->vn_next)
2649                         break;
2650
2651                       vn_offset += verneed->vn_next;
2652                       verneed = (verneed->vn_next == 0
2653                                  ? NULL
2654                                  : gelf_getverneed (verneed_data, vn_offset,
2655                                                     &verneed_mem));
2656                     }
2657
2658                   if (vernaux != NULL && vernaux->vna_other == *versym)
2659                     {
2660                       printf ("@%s (%u)",
2661                               elf_strptr (ebl->elf, verneed_stridx,
2662                                           vernaux->vna_name),
2663                               (unsigned int) vernaux->vna_other);
2664                       check_def = 0;
2665                     }
2666                   else if (unlikely (! is_nobits))
2667                     error (0, 0, _("bad dynamic symbol"));
2668                   else
2669                     check_def = 1;
2670                 }
2671
2672               if (check_def && *versym != 0x8001)
2673                 {
2674                   /* We must test both.  */
2675                   size_t vd_offset = 0;
2676
2677                   GElf_Verdef verdef_mem;
2678                   GElf_Verdef *verdef = gelf_getverdef (verdef_data, 0,
2679                                                         &verdef_mem);
2680                   while (verdef != NULL)
2681                     {
2682                       if (verdef->vd_ndx == (*versym & 0x7fff))
2683                         /* Found the definition.  */
2684                         break;
2685
2686                       if (verdef_data->d_size - vd_offset < verdef->vd_next)
2687                         break;
2688
2689                       vd_offset += verdef->vd_next;
2690                       verdef = (verdef->vd_next == 0
2691                                 ? NULL
2692                                 : gelf_getverdef (verdef_data, vd_offset,
2693                                                   &verdef_mem));
2694                     }
2695
2696                   if (verdef != NULL)
2697                     {
2698                       GElf_Verdaux verdaux_mem;
2699                       GElf_Verdaux *verdaux
2700                         = gelf_getverdaux (verdef_data,
2701                                            vd_offset + verdef->vd_aux,
2702                                            &verdaux_mem);
2703
2704                       if (verdaux != NULL)
2705                         printf ((*versym & 0x8000) ? "@%s" : "@@%s",
2706                                 elf_strptr (ebl->elf, verdef_stridx,
2707                                             verdaux->vda_name));
2708                     }
2709                 }
2710             }
2711         }
2712
2713       putchar_unlocked ('\n');
2714     }
2715 }
2716
2717
2718 /* Print version information.  */
2719 static void
2720 print_verinfo (Ebl *ebl)
2721 {
2722   /* Find the version information sections.  For this we have to
2723      search through the section table.  */
2724   Elf_Scn *scn = NULL;
2725
2726   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
2727     {
2728       /* Handle the section if it is part of the versioning handling.  */
2729       GElf_Shdr shdr_mem;
2730       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
2731
2732       if (likely (shdr != NULL))
2733         {
2734           if (shdr->sh_type == SHT_GNU_verneed)
2735             handle_verneed (ebl, scn, shdr);
2736           else if (shdr->sh_type == SHT_GNU_verdef)
2737             handle_verdef (ebl, scn, shdr);
2738           else if (shdr->sh_type == SHT_GNU_versym)
2739             handle_versym (ebl, scn, shdr);
2740         }
2741     }
2742 }
2743
2744
2745 static const char *
2746 get_ver_flags (unsigned int flags)
2747 {
2748   static char buf[32];
2749   char *endp;
2750
2751   if (flags == 0)
2752     return _("none");
2753
2754   if (flags & VER_FLG_BASE)
2755     endp = stpcpy (buf, "BASE ");
2756   else
2757     endp = buf;
2758
2759   if (flags & VER_FLG_WEAK)
2760     {
2761       if (endp != buf)
2762         endp = stpcpy (endp, "| ");
2763
2764       endp = stpcpy (endp, "WEAK ");
2765     }
2766
2767   if (unlikely (flags & ~(VER_FLG_BASE | VER_FLG_WEAK)))
2768     {
2769       strncpy (endp, _("| <unknown>"), buf + sizeof (buf) - endp);
2770       buf[sizeof (buf) - 1] = '\0';
2771     }
2772
2773   return buf;
2774 }
2775
2776
2777 static void
2778 handle_verneed (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
2779 {
2780   int class = gelf_getclass (ebl->elf);
2781
2782   /* Get the data of the section.  */
2783   Elf_Data *data = elf_getdata (scn, NULL);
2784   if (data == NULL)
2785     return;
2786
2787   /* Get the section header string table index.  */
2788   size_t shstrndx;
2789   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2790     error_exit (0, _("cannot get section header string table index"));
2791
2792   GElf_Shdr glink_mem;
2793   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
2794                                    &glink_mem);
2795   if (glink == NULL)
2796     error_exit (0, _("invalid sh_link value in section %zu"),
2797                 elf_ndxscn (scn));
2798
2799   printf (ngettext ("\
2800 \nVersion needs section [%2u] '%s' contains %d entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2801                     "\
2802 \nVersion needs section [%2u] '%s' contains %d entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2803                     shdr->sh_info),
2804           (unsigned int) elf_ndxscn (scn),
2805           elf_strptr (ebl->elf, shstrndx, shdr->sh_name), shdr->sh_info,
2806           class == ELFCLASS32 ? 10 : 18, shdr->sh_addr,
2807           shdr->sh_offset,
2808           (unsigned int) shdr->sh_link,
2809           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
2810
2811   unsigned int offset = 0;
2812   for (int cnt = shdr->sh_info; --cnt >= 0; )
2813     {
2814       /* Get the data at the next offset.  */
2815       GElf_Verneed needmem;
2816       GElf_Verneed *need = gelf_getverneed (data, offset, &needmem);
2817       if (unlikely (need == NULL))
2818         break;
2819
2820       printf (_("  %#06x: Version: %hu  File: %s  Cnt: %hu\n"),
2821               offset, (unsigned short int) need->vn_version,
2822               elf_strptr (ebl->elf, shdr->sh_link, need->vn_file),
2823               (unsigned short int) need->vn_cnt);
2824
2825       unsigned int auxoffset = offset + need->vn_aux;
2826       for (int cnt2 = need->vn_cnt; --cnt2 >= 0; )
2827         {
2828           GElf_Vernaux auxmem;
2829           GElf_Vernaux *aux = gelf_getvernaux (data, auxoffset, &auxmem);
2830           if (unlikely (aux == NULL))
2831             break;
2832
2833           printf (_("  %#06x: Name: %s  Flags: %s  Version: %hu\n"),
2834                   auxoffset,
2835                   elf_strptr (ebl->elf, shdr->sh_link, aux->vna_name),
2836                   get_ver_flags (aux->vna_flags),
2837                   (unsigned short int) aux->vna_other);
2838
2839           if (aux->vna_next == 0)
2840             break;
2841
2842           auxoffset += aux->vna_next;
2843         }
2844
2845       /* Find the next offset.  */
2846       if (need->vn_next == 0)
2847         break;
2848
2849       offset += need->vn_next;
2850     }
2851 }
2852
2853
2854 static void
2855 handle_verdef (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
2856 {
2857   /* Get the data of the section.  */
2858   Elf_Data *data = elf_getdata (scn, NULL);
2859   if (data == NULL)
2860     return;
2861
2862   /* Get the section header string table index.  */
2863   size_t shstrndx;
2864   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2865     error_exit (0, _("cannot get section header string table index"));
2866
2867   GElf_Shdr glink_mem;
2868   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
2869                                    &glink_mem);
2870   if (glink == NULL)
2871     error_exit (0, _("invalid sh_link value in section %zu"),
2872                 elf_ndxscn (scn));
2873
2874   int class = gelf_getclass (ebl->elf);
2875   printf (ngettext ("\
2876 \nVersion definition section [%2u] '%s' contains %d entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2877                     "\
2878 \nVersion definition section [%2u] '%s' contains %d entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2879                     shdr->sh_info),
2880           (unsigned int) elf_ndxscn (scn),
2881           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2882           shdr->sh_info,
2883           class == ELFCLASS32 ? 10 : 18, shdr->sh_addr,
2884           shdr->sh_offset,
2885           (unsigned int) shdr->sh_link,
2886           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
2887
2888   unsigned int offset = 0;
2889   for (int cnt = shdr->sh_info; --cnt >= 0; )
2890     {
2891       /* Get the data at the next offset.  */
2892       GElf_Verdef defmem;
2893       GElf_Verdef *def = gelf_getverdef (data, offset, &defmem);
2894       if (unlikely (def == NULL))
2895         break;
2896
2897       unsigned int auxoffset = offset + def->vd_aux;
2898       GElf_Verdaux auxmem;
2899       GElf_Verdaux *aux = gelf_getverdaux (data, auxoffset, &auxmem);
2900       if (unlikely (aux == NULL))
2901         break;
2902
2903       printf (_("\
2904   %#06x: Version: %hd  Flags: %s  Index: %hd  Cnt: %hd  Name: %s\n"),
2905               offset, def->vd_version,
2906               get_ver_flags (def->vd_flags),
2907               def->vd_ndx,
2908               def->vd_cnt,
2909               elf_strptr (ebl->elf, shdr->sh_link, aux->vda_name));
2910
2911       auxoffset += aux->vda_next;
2912       for (int cnt2 = 1; cnt2 < def->vd_cnt; ++cnt2)
2913         {
2914           aux = gelf_getverdaux (data, auxoffset, &auxmem);
2915           if (unlikely (aux == NULL))
2916             break;
2917
2918           printf (_("  %#06x: Parent %d: %s\n"),
2919                   auxoffset, cnt2,
2920                   elf_strptr (ebl->elf, shdr->sh_link, aux->vda_name));
2921
2922           if (aux->vda_next == 0)
2923             break;
2924
2925           auxoffset += aux->vda_next;
2926         }
2927
2928       /* Find the next offset.  */
2929       if (def->vd_next == 0)
2930         break;
2931       offset += def->vd_next;
2932     }
2933 }
2934
2935
2936 static void
2937 handle_versym (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
2938 {
2939   int class = gelf_getclass (ebl->elf);
2940   const char **vername;
2941   const char **filename;
2942
2943   /* Get the data of the section.  */
2944   Elf_Data *data = elf_getdata (scn, NULL);
2945   if (data == NULL)
2946     return;
2947
2948   /* Get the section header string table index.  */
2949   size_t shstrndx;
2950   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2951     error_exit (0, _("cannot get section header string table index"));
2952
2953   /* We have to find the version definition section and extract the
2954      version names.  */
2955   Elf_Scn *defscn = NULL;
2956   Elf_Scn *needscn = NULL;
2957
2958   Elf_Scn *verscn = NULL;
2959   while ((verscn = elf_nextscn (ebl->elf, verscn)) != NULL)
2960     {
2961       GElf_Shdr vershdr_mem;
2962       GElf_Shdr *vershdr = gelf_getshdr (verscn, &vershdr_mem);
2963
2964       if (likely (vershdr != NULL))
2965         {
2966           if (vershdr->sh_type == SHT_GNU_verdef)
2967             defscn = verscn;
2968           else if (vershdr->sh_type == SHT_GNU_verneed)
2969             needscn = verscn;
2970         }
2971     }
2972
2973   size_t nvername;
2974   if (defscn != NULL || needscn != NULL)
2975     {
2976       /* We have a version information (better should have).  Now get
2977          the version names.  First find the maximum version number.  */
2978       nvername = 0;
2979       if (defscn != NULL)
2980         {
2981           /* Run through the version definitions and find the highest
2982              index.  */
2983           unsigned int offset = 0;
2984           Elf_Data *defdata;
2985           GElf_Shdr defshdrmem;
2986           GElf_Shdr *defshdr;
2987
2988           defdata = elf_getdata (defscn, NULL);
2989           if (unlikely (defdata == NULL))
2990             return;
2991
2992           defshdr = gelf_getshdr (defscn, &defshdrmem);
2993           if (unlikely (defshdr == NULL))
2994             return;
2995
2996           for (unsigned int cnt = 0; cnt < defshdr->sh_info; ++cnt)
2997             {
2998               GElf_Verdef defmem;
2999               GElf_Verdef *def;
3000
3001               /* Get the data at the next offset.  */
3002               def = gelf_getverdef (defdata, offset, &defmem);
3003               if (unlikely (def == NULL))
3004                 break;
3005
3006               nvername = MAX (nvername, (size_t) (def->vd_ndx & 0x7fff));
3007
3008               if (def->vd_next == 0)
3009                 break;
3010               offset += def->vd_next;
3011             }
3012         }
3013       if (needscn != NULL)
3014         {
3015           unsigned int offset = 0;
3016           Elf_Data *needdata;
3017           GElf_Shdr needshdrmem;
3018           GElf_Shdr *needshdr;
3019
3020           needdata = elf_getdata (needscn, NULL);
3021           if (unlikely (needdata == NULL))
3022             return;
3023
3024           needshdr = gelf_getshdr (needscn, &needshdrmem);
3025           if (unlikely (needshdr == NULL))
3026             return;
3027
3028           for (unsigned int cnt = 0; cnt < needshdr->sh_info; ++cnt)
3029             {
3030               GElf_Verneed needmem;
3031               GElf_Verneed *need;
3032               unsigned int auxoffset;
3033               int cnt2;
3034
3035               /* Get the data at the next offset.  */
3036               need = gelf_getverneed (needdata, offset, &needmem);
3037               if (unlikely (need == NULL))
3038                 break;
3039
3040               /* Run through the auxiliary entries.  */
3041               auxoffset = offset + need->vn_aux;
3042               for (cnt2 = need->vn_cnt; --cnt2 >= 0; )
3043                 {
3044                   GElf_Vernaux auxmem;
3045                   GElf_Vernaux *aux;
3046
3047                   aux = gelf_getvernaux (needdata, auxoffset, &auxmem);
3048                   if (unlikely (aux == NULL))
3049                     break;
3050
3051                   nvername = MAX (nvername,
3052                                   (size_t) (aux->vna_other & 0x7fff));
3053
3054                   if (aux->vna_next == 0)
3055                     break;
3056                   auxoffset += aux->vna_next;
3057                 }
3058
3059               if (need->vn_next == 0)
3060                 break;
3061               offset += need->vn_next;
3062             }
3063         }
3064
3065       /* This is the number of versions we know about.  */
3066       ++nvername;
3067
3068       /* Allocate the array.  */
3069       vername = (const char **) alloca (nvername * sizeof (const char *));
3070       memset(vername, 0, nvername * sizeof (const char *));
3071       filename = (const char **) alloca (nvername * sizeof (const char *));
3072       memset(filename, 0, nvername * sizeof (const char *));
3073
3074       /* Run through the data structures again and collect the strings.  */
3075       if (defscn != NULL)
3076         {
3077           /* Run through the version definitions and find the highest
3078              index.  */
3079           unsigned int offset = 0;
3080           Elf_Data *defdata;
3081           GElf_Shdr defshdrmem;
3082           GElf_Shdr *defshdr;
3083
3084           defdata = elf_getdata (defscn, NULL);
3085           if (unlikely (defdata == NULL))
3086             return;
3087
3088           defshdr = gelf_getshdr (defscn, &defshdrmem);
3089           if (unlikely (defshdr == NULL))
3090             return;
3091
3092           for (unsigned int cnt = 0; cnt < defshdr->sh_info; ++cnt)
3093             {
3094
3095               /* Get the data at the next offset.  */
3096               GElf_Verdef defmem;
3097               GElf_Verdef *def = gelf_getverdef (defdata, offset, &defmem);
3098               if (unlikely (def == NULL))
3099                 break;
3100
3101               GElf_Verdaux auxmem;
3102               GElf_Verdaux *aux = gelf_getverdaux (defdata,
3103                                                    offset + def->vd_aux,
3104                                                    &auxmem);
3105               if (unlikely (aux == NULL))
3106                 break;
3107
3108               vername[def->vd_ndx & 0x7fff]
3109                 = elf_strptr (ebl->elf, defshdr->sh_link, aux->vda_name);
3110               filename[def->vd_ndx & 0x7fff] = NULL;
3111
3112               if (def->vd_next == 0)
3113                 break;
3114               offset += def->vd_next;
3115             }
3116         }
3117       if (needscn != NULL)
3118         {
3119           unsigned int offset = 0;
3120
3121           Elf_Data *needdata = elf_getdata (needscn, NULL);
3122           GElf_Shdr needshdrmem;
3123           GElf_Shdr *needshdr = gelf_getshdr (needscn, &needshdrmem);
3124           if (unlikely (needdata == NULL || needshdr == NULL))
3125             return;
3126
3127           for (unsigned int cnt = 0; cnt < needshdr->sh_info; ++cnt)
3128             {
3129               /* Get the data at the next offset.  */
3130               GElf_Verneed needmem;
3131               GElf_Verneed *need = gelf_getverneed (needdata, offset,
3132                                                     &needmem);
3133               if (unlikely (need == NULL))
3134                 break;
3135
3136               /* Run through the auxiliary entries.  */
3137               unsigned int auxoffset = offset + need->vn_aux;
3138               for (int cnt2 = need->vn_cnt; --cnt2 >= 0; )
3139                 {
3140                   GElf_Vernaux auxmem;
3141                   GElf_Vernaux *aux = gelf_getvernaux (needdata, auxoffset,
3142                                                        &auxmem);
3143                   if (unlikely (aux == NULL))
3144                     break;
3145
3146                   vername[aux->vna_other & 0x7fff]
3147                     = elf_strptr (ebl->elf, needshdr->sh_link, aux->vna_name);
3148                   filename[aux->vna_other & 0x7fff]
3149                     = elf_strptr (ebl->elf, needshdr->sh_link, need->vn_file);
3150
3151                   if (aux->vna_next == 0)
3152                     break;
3153                   auxoffset += aux->vna_next;
3154                 }
3155
3156               if (need->vn_next == 0)
3157                 break;
3158               offset += need->vn_next;
3159             }
3160         }
3161     }
3162   else
3163     {
3164       vername = NULL;
3165       nvername = 1;
3166       filename = NULL;
3167     }
3168
3169   GElf_Shdr glink_mem;
3170   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
3171                                    &glink_mem);
3172   size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_HALF, 1, EV_CURRENT);
3173   if (glink == NULL)
3174     error_exit (0, _("invalid sh_link value in section %zu"),
3175                 elf_ndxscn (scn));
3176
3177   /* Print the header.  */
3178   printf (ngettext ("\
3179 \nVersion symbols section [%2u] '%s' contains %d entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'",
3180                     "\
3181 \nVersion symbols section [%2u] '%s' contains %d entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'",
3182                     shdr->sh_size / sh_entsize),
3183           (unsigned int) elf_ndxscn (scn),
3184           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
3185           (int) (shdr->sh_size / sh_entsize),
3186           class == ELFCLASS32 ? 10 : 18, shdr->sh_addr,
3187           shdr->sh_offset,
3188           (unsigned int) shdr->sh_link,
3189           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
3190
3191   /* Now we can finally look at the actual contents of this section.  */
3192   for (unsigned int cnt = 0; cnt < shdr->sh_size / sh_entsize; ++cnt)
3193     {
3194       if (cnt % 2 == 0)
3195         printf ("\n %4d:", cnt);
3196
3197       GElf_Versym symmem;
3198       GElf_Versym *sym = gelf_getversym (data, cnt, &symmem);
3199       if (sym == NULL)
3200         break;
3201
3202       switch (*sym)
3203         {
3204           ssize_t n;
3205         case 0:
3206           fputs_unlocked (_("   0 *local*                     "),
3207                           stdout);
3208           break;
3209
3210         case 1:
3211           fputs_unlocked (_("   1 *global*                    "),
3212                           stdout);
3213           break;
3214
3215         default:
3216           n = printf ("%4d%c%s",
3217                       *sym & 0x7fff, *sym & 0x8000 ? 'h' : ' ',
3218                       (vername != NULL
3219                        && (unsigned int) (*sym & 0x7fff) < nvername)
3220                       ? vername[*sym & 0x7fff] : "???");
3221           if ((unsigned int) (*sym & 0x7fff) < nvername
3222               && filename != NULL && filename[*sym & 0x7fff] != NULL)
3223             n += printf ("(%s)", filename[*sym & 0x7fff]);
3224           printf ("%*s", MAX (0, 33 - (int) n), " ");
3225           break;
3226         }
3227     }
3228   putchar_unlocked ('\n');
3229 }
3230
3231
3232 static void
3233 print_hash_info (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, size_t shstrndx,
3234                  uint_fast32_t maxlength, Elf32_Word nbucket,
3235                  uint_fast32_t nsyms, uint32_t *lengths, const char *extrastr)
3236 {
3237   uint32_t *counts = xcalloc (maxlength + 1, sizeof (uint32_t));
3238
3239   for (Elf32_Word cnt = 0; cnt < nbucket; ++cnt)
3240     ++counts[lengths[cnt]];
3241
3242   GElf_Shdr glink_mem;
3243   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf,
3244                                                shdr->sh_link),
3245                                    &glink_mem);
3246   if (glink == NULL)
3247     {
3248       error (0, 0, _("invalid sh_link value in section %zu"),
3249              elf_ndxscn (scn));
3250       return;
3251     }
3252
3253   printf (ngettext ("\
3254 \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",
3255                     "\
3256 \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",
3257                     nbucket),
3258           (unsigned int) elf_ndxscn (scn),
3259           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
3260           (int) nbucket,
3261           gelf_getclass (ebl->elf) == ELFCLASS32 ? 10 : 18,
3262           shdr->sh_addr,
3263           shdr->sh_offset,
3264           (unsigned int) shdr->sh_link,
3265           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
3266
3267   if (extrastr != NULL)
3268     fputs (extrastr, stdout);
3269
3270   if (likely (nbucket > 0))
3271     {
3272       uint64_t success = 0;
3273
3274       /* xgettext:no-c-format */
3275       fputs_unlocked (_("\
3276  Length  Number  % of total  Coverage\n"), stdout);
3277       printf (_("      0  %6" PRIu32 "      %5.1f%%\n"),
3278               counts[0], (counts[0] * 100.0) / nbucket);
3279
3280       uint64_t nzero_counts = 0;
3281       for (Elf32_Word cnt = 1; cnt <= maxlength; ++cnt)
3282         {
3283           nzero_counts += counts[cnt] * cnt;
3284           printf (_("\
3285 %7d  %6" PRIu32 "      %5.1f%%    %5.1f%%\n"),
3286                   (int) cnt, counts[cnt], (counts[cnt] * 100.0) / nbucket,
3287                   (nzero_counts * 100.0) / nsyms);
3288         }
3289
3290       Elf32_Word acc = 0;
3291       for (Elf32_Word cnt = 1; cnt <= maxlength; ++cnt)
3292         {
3293           acc += cnt;
3294           success += counts[cnt] * acc;
3295         }
3296
3297       printf (_("\
3298  Average number of tests:   successful lookup: %f\n\
3299                           unsuccessful lookup: %f\n"),
3300               (double) success / (double) nzero_counts,
3301               (double) nzero_counts / (double) nbucket);
3302     }
3303
3304   free (counts);
3305 }
3306
3307
3308 /* This function handles the traditional System V-style hash table format.  */
3309 static void
3310 handle_sysv_hash (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, size_t shstrndx)
3311 {
3312   Elf_Data *data = elf_getdata (scn, NULL);
3313   if (unlikely (data == NULL))
3314     {
3315       error (0, 0, _("cannot get data for section %d: %s"),
3316              (int) elf_ndxscn (scn), elf_errmsg (-1));
3317       return;
3318     }
3319
3320   if (unlikely (data->d_size < 2 * sizeof (Elf32_Word)))
3321     {
3322     invalid_data:
3323       error (0, 0, _("invalid data in sysv.hash section %d"),
3324              (int) elf_ndxscn (scn));
3325       return;
3326     }
3327
3328   Elf32_Word nbucket = ((Elf32_Word *) data->d_buf)[0];
3329   Elf32_Word nchain = ((Elf32_Word *) data->d_buf)[1];
3330
3331   uint64_t used_buf = (2ULL + nchain + nbucket) * sizeof (Elf32_Word);
3332   if (used_buf > data->d_size)
3333     goto invalid_data;
3334
3335   Elf32_Word *bucket = &((Elf32_Word *) data->d_buf)[2];
3336   Elf32_Word *chain = &((Elf32_Word *) data->d_buf)[2 + nbucket];
3337
3338   uint32_t *lengths = xcalloc (nbucket, sizeof (uint32_t));
3339
3340   uint_fast32_t maxlength = 0;
3341   uint_fast32_t nsyms = 0;
3342   for (Elf32_Word cnt = 0; cnt < nbucket; ++cnt)
3343     {
3344       Elf32_Word inner = bucket[cnt];
3345       Elf32_Word chain_len = 0;
3346       while (inner > 0 && inner < nchain)
3347         {
3348           ++nsyms;
3349           ++chain_len;
3350           if (chain_len > nchain)
3351             {
3352               error (0, 0, _("invalid chain in sysv.hash section %d"),
3353                      (int) elf_ndxscn (scn));
3354               free (lengths);
3355               return;
3356             }
3357           if (maxlength < ++lengths[cnt])
3358             ++maxlength;
3359
3360           inner = chain[inner];
3361         }
3362     }
3363
3364   print_hash_info (ebl, scn, shdr, shstrndx, maxlength, nbucket, nsyms,
3365                    lengths, NULL);
3366
3367   free (lengths);
3368 }
3369
3370
3371 /* This function handles the incorrect, System V-style hash table
3372    format some 64-bit architectures use.  */
3373 static void
3374 handle_sysv_hash64 (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, size_t shstrndx)
3375 {
3376   Elf_Data *data = elf_getdata (scn, NULL);
3377   if (unlikely (data == NULL))
3378     {
3379       error (0, 0, _("cannot get data for section %d: %s"),
3380              (int) elf_ndxscn (scn), elf_errmsg (-1));
3381       return;
3382     }
3383
3384   if (unlikely (data->d_size < 2 * sizeof (Elf64_Xword)))
3385     {
3386     invalid_data:
3387       error (0, 0, _("invalid data in sysv.hash64 section %d"),
3388              (int) elf_ndxscn (scn));
3389       return;
3390     }
3391
3392   Elf64_Xword nbucket = ((Elf64_Xword *) data->d_buf)[0];
3393   Elf64_Xword nchain = ((Elf64_Xword *) data->d_buf)[1];
3394
3395   uint64_t maxwords = data->d_size / sizeof (Elf64_Xword);
3396   if (maxwords < 2
3397       || maxwords - 2 < nbucket
3398       || maxwords - 2 - nbucket < nchain)
3399     goto invalid_data;
3400
3401   Elf64_Xword *bucket = &((Elf64_Xword *) data->d_buf)[2];
3402   Elf64_Xword *chain = &((Elf64_Xword *) data->d_buf)[2 + nbucket];
3403
3404   uint32_t *lengths = xcalloc (nbucket, sizeof (uint32_t));
3405
3406   uint_fast32_t maxlength = 0;
3407   uint_fast32_t nsyms = 0;
3408   for (Elf64_Xword cnt = 0; cnt < nbucket; ++cnt)
3409     {
3410       Elf64_Xword inner = bucket[cnt];
3411       Elf64_Xword chain_len = 0;
3412       while (inner > 0 && inner < nchain)
3413         {
3414           ++nsyms;
3415           ++chain_len;
3416           if (chain_len > nchain)
3417             {
3418               error (0, 0, _("invalid chain in sysv.hash64 section %d"),
3419                      (int) elf_ndxscn (scn));
3420               free (lengths);
3421               return;
3422             }
3423           if (maxlength < ++lengths[cnt])
3424             ++maxlength;
3425
3426           inner = chain[inner];
3427         }
3428     }
3429
3430   print_hash_info (ebl, scn, shdr, shstrndx, maxlength, nbucket, nsyms,
3431                    lengths, NULL);
3432
3433   free (lengths);
3434 }
3435
3436
3437 /* This function handles the GNU-style hash table format.  */
3438 static void
3439 handle_gnu_hash (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, size_t shstrndx)
3440 {
3441   uint32_t *lengths = NULL;
3442   Elf_Data *data = elf_getdata (scn, NULL);
3443   if (unlikely (data == NULL))
3444     {
3445       error (0, 0, _("cannot get data for section %d: %s"),
3446              (int) elf_ndxscn (scn), elf_errmsg (-1));
3447       return;
3448     }
3449
3450   if (unlikely (data->d_size < 4 * sizeof (Elf32_Word)))
3451     {
3452     invalid_data:
3453       free (lengths);
3454       error (0, 0, _("invalid data in gnu.hash section %d"),
3455              (int) elf_ndxscn (scn));
3456       return;
3457     }
3458
3459   Elf32_Word nbucket = ((Elf32_Word *) data->d_buf)[0];
3460   Elf32_Word symbias = ((Elf32_Word *) data->d_buf)[1];
3461
3462   /* Next comes the size of the bitmap.  It's measured in words for
3463      the architecture.  It's 32 bits for 32 bit archs, and 64 bits for
3464      64 bit archs.  There is always a bloom filter present, so zero is
3465      an invalid value.  */
3466   Elf32_Word bitmask_words = ((Elf32_Word *) data->d_buf)[2];
3467   if (gelf_getclass (ebl->elf) == ELFCLASS64)
3468     bitmask_words *= 2;
3469
3470   if (bitmask_words == 0)
3471     goto invalid_data;
3472
3473   Elf32_Word shift = ((Elf32_Word *) data->d_buf)[3];
3474
3475   /* Is there still room for the sym chain?
3476      Use uint64_t calculation to prevent 32bit overflow.  */
3477   uint64_t used_buf = (4ULL + bitmask_words + nbucket) * sizeof (Elf32_Word);
3478   uint32_t max_nsyms = (data->d_size - used_buf) / sizeof (Elf32_Word);
3479   if (used_buf > data->d_size)
3480     goto invalid_data;
3481
3482   lengths = xcalloc (nbucket, sizeof (uint32_t));
3483
3484   Elf32_Word *bitmask = &((Elf32_Word *) data->d_buf)[4];
3485   Elf32_Word *bucket = &((Elf32_Word *) data->d_buf)[4 + bitmask_words];
3486   Elf32_Word *chain = &((Elf32_Word *) data->d_buf)[4 + bitmask_words
3487                                                     + nbucket];
3488
3489   /* Compute distribution of chain lengths.  */
3490   uint_fast32_t maxlength = 0;
3491   uint_fast32_t nsyms = 0;
3492   for (Elf32_Word cnt = 0; cnt < nbucket; ++cnt)
3493     if (bucket[cnt] != 0)
3494       {
3495         Elf32_Word inner = bucket[cnt] - symbias;
3496         do
3497           {
3498             ++nsyms;
3499             if (maxlength < ++lengths[cnt])
3500               ++maxlength;
3501             if (inner >= max_nsyms)
3502               goto invalid_data;
3503           }
3504         while ((chain[inner++] & 1) == 0);
3505       }
3506
3507   /* Count bits in bitmask.  */
3508   uint_fast32_t nbits = 0;
3509   for (Elf32_Word cnt = 0; cnt < bitmask_words; ++cnt)
3510     {
3511       uint_fast32_t word = bitmask[cnt];
3512
3513       word = (word & 0x55555555) + ((word >> 1) & 0x55555555);
3514       word = (word & 0x33333333) + ((word >> 2) & 0x33333333);
3515       word = (word & 0x0f0f0f0f) + ((word >> 4) & 0x0f0f0f0f);
3516       word = (word & 0x00ff00ff) + ((word >> 8) & 0x00ff00ff);
3517       nbits += (word & 0x0000ffff) + ((word >> 16) & 0x0000ffff);
3518     }
3519
3520   char *str = xasprintf (_("\
3521  Symbol Bias: %u\n\
3522  Bitmask Size: %zu bytes  %" PRIuFAST32 "%% bits set  2nd hash shift: %u\n"),
3523                          (unsigned int) symbias,
3524                          bitmask_words * sizeof (Elf32_Word),
3525                          ((nbits * 100 + 50)
3526                           / (uint_fast32_t) (bitmask_words
3527                                               * sizeof (Elf32_Word) * 8)),
3528                           (unsigned int) shift);
3529
3530   print_hash_info (ebl, scn, shdr, shstrndx, maxlength, nbucket, nsyms,
3531                    lengths, str);
3532
3533   free (str);
3534   free (lengths);
3535 }
3536
3537
3538 /* Find the symbol table(s).  For this we have to search through the
3539    section table.  */
3540 static void
3541 handle_hash (Ebl *ebl)
3542 {
3543   /* Get the section header string table index.  */
3544   size_t shstrndx;
3545   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
3546     error_exit (0, _("cannot get section header string table index"));
3547
3548   Elf_Scn *scn = NULL;
3549   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
3550     {
3551       /* Handle the section if it is a symbol table.  */
3552       GElf_Shdr shdr_mem;
3553       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
3554
3555       if (likely (shdr != NULL))
3556         {
3557           if ((shdr->sh_type == SHT_HASH || shdr->sh_type == SHT_GNU_HASH)
3558               && (shdr->sh_flags & SHF_COMPRESSED) != 0)
3559             {
3560               if (elf_compress (scn, 0, 0) < 0)
3561                 printf ("WARNING: %s [%zd]\n",
3562                         _("Couldn't uncompress section"),
3563                         elf_ndxscn (scn));
3564               shdr = gelf_getshdr (scn, &shdr_mem);
3565               if (unlikely (shdr == NULL))
3566                 error_exit (0, _("cannot get section [%zd] header: %s"),
3567                             elf_ndxscn (scn), elf_errmsg (-1));
3568             }
3569
3570           if (shdr->sh_type == SHT_HASH)
3571             {
3572               if (ebl_sysvhash_entrysize (ebl) == sizeof (Elf64_Xword))
3573                 handle_sysv_hash64 (ebl, scn, shdr, shstrndx);
3574               else
3575                 handle_sysv_hash (ebl, scn, shdr, shstrndx);
3576             }
3577           else if (shdr->sh_type == SHT_GNU_HASH)
3578             handle_gnu_hash (ebl, scn, shdr, shstrndx);
3579         }
3580     }
3581 }
3582
3583
3584 static void
3585 print_liblist (Ebl *ebl)
3586 {
3587   /* Find the library list sections.  For this we have to search
3588      through the section table.  */
3589   Elf_Scn *scn = NULL;
3590
3591   /* Get the section header string table index.  */
3592   size_t shstrndx;
3593   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
3594     error_exit (0, _("cannot get section header string table index"));
3595
3596   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
3597     {
3598       GElf_Shdr shdr_mem;
3599       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
3600
3601       if (shdr != NULL && shdr->sh_type == SHT_GNU_LIBLIST)
3602         {
3603           size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_LIB, 1, EV_CURRENT);
3604           int nentries = shdr->sh_size / sh_entsize;
3605           printf (ngettext ("\
3606 \nLibrary list section [%2zu] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
3607                             "\
3608 \nLibrary list section [%2zu] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
3609                             nentries),
3610                   elf_ndxscn (scn),
3611                   elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
3612                   shdr->sh_offset,
3613                   nentries);
3614
3615           Elf_Data *data = elf_getdata (scn, NULL);
3616           if (data == NULL)
3617             return;
3618
3619           puts (_("\
3620        Library                       Time Stamp          Checksum Version Flags"));
3621
3622           for (int cnt = 0; cnt < nentries; ++cnt)
3623             {
3624               GElf_Lib lib_mem;
3625               GElf_Lib *lib = gelf_getlib (data, cnt, &lib_mem);
3626               if (unlikely (lib == NULL))
3627                 continue;
3628
3629               time_t t = (time_t) lib->l_time_stamp;
3630               struct tm *tm = gmtime (&t);
3631               if (unlikely (tm == NULL))
3632                 continue;
3633
3634               printf ("  [%2d] %-29s %04u-%02u-%02uT%02u:%02u:%02u %08x %-7u %u\n",
3635                       cnt, elf_strptr (ebl->elf, shdr->sh_link, lib->l_name),
3636                       tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
3637                       tm->tm_hour, tm->tm_min, tm->tm_sec,
3638                       (unsigned int) lib->l_checksum,
3639                       (unsigned int) lib->l_version,
3640                       (unsigned int) lib->l_flags);
3641             }
3642         }
3643     }
3644 }
3645
3646 static inline size_t
3647 left (Elf_Data *data,
3648       const unsigned char *p)
3649 {
3650   return (const unsigned char *) data->d_buf + data->d_size - p;
3651 }
3652
3653 static void
3654 print_attributes (Ebl *ebl, const GElf_Ehdr *ehdr)
3655 {
3656   /* Find the object attributes sections.  For this we have to search
3657      through the section table.  */
3658   Elf_Scn *scn = NULL;
3659
3660   /* Get the section header string table index.  */
3661   size_t shstrndx;
3662   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
3663     error_exit (0, _("cannot get section header string table index"));
3664
3665   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
3666     {
3667       GElf_Shdr shdr_mem;
3668       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
3669
3670       if (shdr == NULL || (shdr->sh_type != SHT_GNU_ATTRIBUTES
3671                            && (shdr->sh_type != SHT_ARM_ATTRIBUTES
3672                                || ehdr->e_machine != EM_ARM)
3673                            && (shdr->sh_type != SHT_CSKY_ATTRIBUTES
3674                                || ehdr->e_machine != EM_CSKY)
3675                            && (shdr->sh_type != SHT_RISCV_ATTRIBUTES
3676                                || ehdr->e_machine != EM_RISCV)))
3677         continue;
3678
3679       printf (_("\
3680 \nObject attributes section [%2zu] '%s' of %" PRIu64
3681                        " bytes at offset %#0" PRIx64 ":\n"),
3682               elf_ndxscn (scn),
3683               elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
3684               shdr->sh_size, shdr->sh_offset);
3685
3686       Elf_Data *data = elf_rawdata (scn, NULL);
3687       if (unlikely (data == NULL || data->d_size == 0))
3688         return;
3689
3690       const unsigned char *p = data->d_buf;
3691
3692       /* There is only one 'version', A.  */
3693       if (unlikely (*p++ != 'A'))
3694         return;
3695
3696       fputs_unlocked (_("  Owner          Size\n"), stdout);
3697
3698       /* Loop over the sections.  */
3699       while (left (data, p) >= 4)
3700         {
3701           /* Section length.  */
3702           uint32_t len;
3703           memcpy (&len, p, sizeof len);
3704
3705           if (MY_ELFDATA != ehdr->e_ident[EI_DATA])
3706             CONVERT (len);
3707
3708           if (unlikely (len > left (data, p)))
3709             break;
3710
3711           /* Section vendor name.  */
3712           const unsigned char *name = p + sizeof len;
3713           p += len;
3714
3715           unsigned const char *q = memchr (name, '\0', len);
3716           if (unlikely (q == NULL))
3717             break;
3718           ++q;
3719
3720           printf (_("  %-13s  %4" PRIu32 "\n"), name, len);
3721
3722           bool gnu_vendor = (q - name == sizeof "gnu"
3723                              && !memcmp (name, "gnu", sizeof "gnu"));
3724
3725           /* Loop over subsections.  */
3726           if (shdr->sh_type != SHT_GNU_ATTRIBUTES
3727               || gnu_vendor)
3728             while (q < p)
3729               {
3730                 const unsigned char *const sub = q;
3731
3732                 unsigned int subsection_tag;
3733                 get_uleb128 (subsection_tag, q, p);
3734                 if (unlikely (q >= p))
3735                   break;
3736
3737                 uint32_t subsection_len;
3738                 if (unlikely (p - sub < (ptrdiff_t) sizeof subsection_len))
3739                   break;
3740
3741                 memcpy (&subsection_len, q, sizeof subsection_len);
3742
3743                 if (MY_ELFDATA != ehdr->e_ident[EI_DATA])
3744                   CONVERT (subsection_len);
3745
3746                 /* Don't overflow, ptrdiff_t might be 32bits, but signed.  */
3747                 if (unlikely (subsection_len == 0
3748                               || subsection_len >= (uint32_t) PTRDIFF_MAX
3749                               || p - sub < (ptrdiff_t) subsection_len))
3750                   break;
3751
3752                 const unsigned char *r = q + sizeof subsection_len;
3753                 q = sub + subsection_len;
3754
3755                 switch (subsection_tag)
3756                   {
3757                   default:
3758                     /* Unknown subsection, print and skip.  */
3759                     printf (_("    %-4u %12" PRIu32 "\n"),
3760                             subsection_tag, subsection_len);
3761                     break;
3762
3763                   case 1:       /* Tag_File */
3764                     printf (_("    File: %11" PRIu32 "\n"),
3765                             subsection_len);
3766
3767                     while (r < q)
3768                       {
3769                         unsigned int tag;
3770                         get_uleb128 (tag, r, q);
3771                         if (unlikely (r >= q))
3772                           break;
3773
3774                         /* GNU style tags have either a uleb128 value,
3775                            when lowest bit is not set, or a string
3776                            when the lowest bit is set.
3777                            "compatibility" (32) is special.  It has
3778                            both a string and a uleb128 value.  For
3779                            non-gnu we assume 6 till 31 only take ints.
3780                            XXX see arm backend, do we need a separate
3781                            hook?  */
3782                         uint64_t value = 0;
3783                         const char *string = NULL;
3784                         if (tag == 32 || (tag & 1) == 0
3785                             || (! gnu_vendor && (tag > 5 && tag < 32)))
3786                           {
3787                             get_uleb128 (value, r, q);
3788                             if (r > q)
3789                               break;
3790                           }
3791                         if (tag == 32
3792                             || ((tag & 1) != 0
3793                                 && (gnu_vendor
3794                                     || (! gnu_vendor && tag > 32)))
3795                             || (! gnu_vendor && tag > 3 && tag < 6))
3796                           {
3797                             string = (const char *) r;
3798                             r = memchr (r, '\0', q - r);
3799                             if (r == NULL)
3800                               break;
3801                             ++r;
3802                           }
3803
3804                         const char *tag_name = NULL;
3805                         const char *value_name = NULL;
3806                         ebl_check_object_attribute (ebl, (const char *) name,
3807                                                     tag, value,
3808                                                     &tag_name, &value_name);
3809
3810                         if (tag_name != NULL)
3811                           {
3812                             if (tag == 32)
3813                               printf (_("      %s: %" PRId64 ", %s\n"),
3814                                       tag_name, value, string);
3815                             else if (string == NULL && value_name == NULL)
3816                               printf (_("      %s: %" PRId64 "\n"),
3817                                       tag_name, value);
3818                             else
3819                               printf (_("      %s: %s\n"),
3820                                       tag_name, string ?: value_name);
3821                           }
3822                         else
3823                           {
3824                             /* For "gnu" vendor 32 "compatibility" has
3825                                already been handled above.  */
3826                             assert (tag != 32
3827                                     || strcmp ((const char *) name, "gnu"));
3828                             if (string == NULL)
3829                               printf (_("      %u: %" PRId64 "\n"),
3830                                       tag, value);
3831                             else
3832                               printf (_("      %u: %s\n"),
3833                                       tag, string);
3834                           }
3835                       }
3836                   }
3837               }
3838         }
3839     }
3840 }
3841
3842
3843 void
3844 print_dwarf_addr (Dwfl_Module *dwflmod,
3845                   int address_size, Dwarf_Addr address, Dwarf_Addr raw)
3846 {
3847   /* See if there is a name we can give for this address.  */
3848   GElf_Sym sym;
3849   GElf_Off off = 0;
3850   const char *name = (print_address_names && ! print_unresolved_addresses)
3851     ? dwfl_module_addrinfo (dwflmod, address, &off, &sym, NULL, NULL, NULL)
3852     : NULL;
3853
3854   const char *scn;
3855   if (print_unresolved_addresses)
3856     {
3857       address = raw;
3858       scn = NULL;
3859     }
3860   else
3861     {
3862       /* Relativize the address.  */
3863       int n = dwfl_module_relocations (dwflmod);
3864       int i = n < 1 ? -1 : dwfl_module_relocate_address (dwflmod, &address);
3865
3866       /* In an ET_REL file there is a section name to refer to.  */
3867       scn = (i < 0 ? NULL
3868              : dwfl_module_relocation_info (dwflmod, i, NULL));
3869     }
3870
3871   if ((name != NULL
3872        ? (off != 0
3873           ? (scn != NULL
3874              ? (address_size == 0
3875                 ? printf ("%s+%#" PRIx64 " <%s+%#" PRIx64 ">",
3876                           scn, address, name, off)
3877                 : printf ("%s+%#0*" PRIx64 " <%s+%#" PRIx64 ">",
3878                           scn, 2 + address_size * 2, address,
3879                           name, off))
3880              : (address_size == 0
3881                 ? printf ("%#" PRIx64 " <%s+%#" PRIx64 ">",
3882                           address, name, off)
3883                 : printf ("%#0*" PRIx64 " <%s+%#" PRIx64 ">",
3884                           2 + address_size * 2, address,
3885                           name, off)))
3886           : (scn != NULL
3887              ? (address_size == 0
3888                 ? printf ("%s+%#" PRIx64 " <%s>", scn, address, name)
3889                 : printf ("%s+%#0*" PRIx64 " <%s>",
3890                            scn, 2 + address_size * 2, address, name))
3891              : (address_size == 0
3892                 ? printf ("%#" PRIx64 " <%s>", address, name)
3893                 : printf ("%#0*" PRIx64 " <%s>",
3894                           2 + address_size * 2, address, name))))
3895        : (scn != NULL
3896           ? (address_size == 0
3897              ? printf ("%s+%#" PRIx64, scn, address)
3898              : printf ("%s+%#0*" PRIx64, scn, 2 + address_size * 2, address))
3899           : (address_size == 0
3900              ? printf ("%#" PRIx64, address)
3901              : printf ("%#0*" PRIx64, 2 + address_size * 2, address)))) < 0)
3902     error_exit (0, _("sprintf failure"));
3903 }
3904
3905
3906 static const char *
3907 dwarf_tag_string (unsigned int tag)
3908 {
3909   switch (tag)
3910     {
3911 #define DWARF_ONE_KNOWN_DW_TAG(NAME, CODE) case CODE: return #NAME;
3912       DWARF_ALL_KNOWN_DW_TAG
3913 #undef DWARF_ONE_KNOWN_DW_TAG
3914     default:
3915       return NULL;
3916     }
3917 }
3918
3919
3920 static const char *
3921 dwarf_attr_string (unsigned int attrnum)
3922 {
3923   switch (attrnum)
3924     {
3925 #define DWARF_ONE_KNOWN_DW_AT(NAME, CODE) case CODE: return #NAME;
3926       DWARF_ALL_KNOWN_DW_AT
3927 #undef DWARF_ONE_KNOWN_DW_AT
3928     default:
3929       return NULL;
3930     }
3931 }
3932
3933
3934 static const char *
3935 dwarf_form_string (unsigned int form)
3936 {
3937   switch (form)
3938     {
3939 #define DWARF_ONE_KNOWN_DW_FORM(NAME, CODE) case CODE: return #NAME;
3940       DWARF_ALL_KNOWN_DW_FORM
3941 #undef DWARF_ONE_KNOWN_DW_FORM
3942     default:
3943       return NULL;
3944     }
3945 }
3946
3947
3948 static const char *
3949 dwarf_lang_string (unsigned int lang)
3950 {
3951   switch (lang)
3952     {
3953 #define DWARF_ONE_KNOWN_DW_LANG(NAME, CODE) case CODE: return #NAME;
3954       DWARF_ALL_KNOWN_DW_LANG
3955 #undef DWARF_ONE_KNOWN_DW_LANG
3956     default:
3957       return NULL;
3958     }
3959 }
3960
3961
3962 static const char *
3963 dwarf_inline_string (unsigned int code)
3964 {
3965   static const char *const known[] =
3966     {
3967 #define DWARF_ONE_KNOWN_DW_INL(NAME, CODE) [CODE] = #NAME,
3968       DWARF_ALL_KNOWN_DW_INL
3969 #undef DWARF_ONE_KNOWN_DW_INL
3970     };
3971
3972   if (likely (code < sizeof (known) / sizeof (known[0])))
3973     return known[code];
3974
3975   return NULL;
3976 }
3977
3978
3979 static const char *
3980 dwarf_encoding_string (unsigned int code)
3981 {
3982   static const char *const known[] =
3983     {
3984 #define DWARF_ONE_KNOWN_DW_ATE(NAME, CODE) [CODE] = #NAME,
3985       DWARF_ALL_KNOWN_DW_ATE
3986 #undef DWARF_ONE_KNOWN_DW_ATE
3987     };
3988
3989   if (likely (code < sizeof (known) / sizeof (known[0])))
3990     return known[code];
3991
3992   return NULL;
3993 }
3994
3995
3996 static const char *
3997 dwarf_access_string (unsigned int code)
3998 {
3999   static const char *const known[] =
4000     {
4001 #define DWARF_ONE_KNOWN_DW_ACCESS(NAME, CODE) [CODE] = #NAME,
4002       DWARF_ALL_KNOWN_DW_ACCESS
4003 #undef DWARF_ONE_KNOWN_DW_ACCESS
4004     };
4005
4006   if (likely (code < sizeof (known) / sizeof (known[0])))
4007     return known[code];
4008
4009   return NULL;
4010 }
4011
4012
4013 static const char *
4014 dwarf_defaulted_string (unsigned int code)
4015 {
4016   static const char *const known[] =
4017     {
4018 #define DWARF_ONE_KNOWN_DW_DEFAULTED(NAME, CODE) [CODE] = #NAME,
4019       DWARF_ALL_KNOWN_DW_DEFAULTED
4020 #undef DWARF_ONE_KNOWN_DW_DEFAULTED
4021     };
4022
4023   if (likely (code < sizeof (known) / sizeof (known[0])))
4024     return known[code];
4025
4026   return NULL;
4027 }
4028
4029
4030 static const char *
4031 dwarf_visibility_string (unsigned int code)
4032 {
4033   static const char *const known[] =
4034     {
4035 #define DWARF_ONE_KNOWN_DW_VIS(NAME, CODE) [CODE] = #NAME,
4036       DWARF_ALL_KNOWN_DW_VIS
4037 #undef DWARF_ONE_KNOWN_DW_VIS
4038     };
4039
4040   if (likely (code < sizeof (known) / sizeof (known[0])))
4041     return known[code];
4042
4043   return NULL;
4044 }
4045
4046
4047 static const char *
4048 dwarf_virtuality_string (unsigned int code)
4049 {
4050   static const char *const known[] =
4051     {
4052 #define DWARF_ONE_KNOWN_DW_VIRTUALITY(NAME, CODE) [CODE] = #NAME,
4053       DWARF_ALL_KNOWN_DW_VIRTUALITY
4054 #undef DWARF_ONE_KNOWN_DW_VIRTUALITY
4055     };
4056
4057   if (likely (code < sizeof (known) / sizeof (known[0])))
4058     return known[code];
4059
4060   return NULL;
4061 }
4062
4063
4064 static const char *
4065 dwarf_identifier_case_string (unsigned int code)
4066 {
4067   static const char *const known[] =
4068     {
4069 #define DWARF_ONE_KNOWN_DW_ID(NAME, CODE) [CODE] = #NAME,
4070       DWARF_ALL_KNOWN_DW_ID
4071 #undef DWARF_ONE_KNOWN_DW_ID
4072     };
4073
4074   if (likely (code < sizeof (known) / sizeof (known[0])))
4075     return known[code];
4076
4077   return NULL;
4078 }
4079
4080
4081 static const char *
4082 dwarf_calling_convention_string (unsigned int code)
4083 {
4084   static const char *const known[] =
4085     {
4086 #define DWARF_ONE_KNOWN_DW_CC(NAME, CODE) [CODE] = #NAME,
4087       DWARF_ALL_KNOWN_DW_CC
4088 #undef DWARF_ONE_KNOWN_DW_CC
4089     };
4090
4091   if (likely (code < sizeof (known) / sizeof (known[0])))
4092     return known[code];
4093
4094   return NULL;
4095 }
4096
4097
4098 static const char *
4099 dwarf_ordering_string (unsigned int code)
4100 {
4101   static const char *const known[] =
4102     {
4103 #define DWARF_ONE_KNOWN_DW_ORD(NAME, CODE) [CODE] = #NAME,
4104       DWARF_ALL_KNOWN_DW_ORD
4105 #undef DWARF_ONE_KNOWN_DW_ORD
4106     };
4107
4108   if (likely (code < sizeof (known) / sizeof (known[0])))
4109     return known[code];
4110
4111   return NULL;
4112 }
4113
4114
4115 static const char *
4116 dwarf_discr_list_string (unsigned int code)
4117 {
4118   static const char *const known[] =
4119     {
4120 #define DWARF_ONE_KNOWN_DW_DSC(NAME, CODE) [CODE] = #NAME,
4121       DWARF_ALL_KNOWN_DW_DSC
4122 #undef DWARF_ONE_KNOWN_DW_DSC
4123     };
4124
4125   if (likely (code < sizeof (known) / sizeof (known[0])))
4126     return known[code];
4127
4128   return NULL;
4129 }
4130
4131
4132 static const char *
4133 dwarf_locexpr_opcode_string (unsigned int code)
4134 {
4135   static const char *const known[] =
4136     {
4137       /* Normally we can't afford building huge table of 64K entries,
4138          most of them zero, just because there are a couple defined
4139          values at the far end.  In case of opcodes, it's OK.  */
4140 #define DWARF_ONE_KNOWN_DW_OP(NAME, CODE) [CODE] = #NAME,
4141       DWARF_ALL_KNOWN_DW_OP
4142 #undef DWARF_ONE_KNOWN_DW_OP
4143     };
4144
4145   if (likely (code < sizeof (known) / sizeof (known[0])))
4146     return known[code];
4147
4148   return NULL;
4149 }
4150
4151
4152 static const char *
4153 dwarf_unit_string (unsigned int type)
4154 {
4155   switch (type)
4156     {
4157 #define DWARF_ONE_KNOWN_DW_UT(NAME, CODE) case CODE: return #NAME;
4158       DWARF_ALL_KNOWN_DW_UT
4159 #undef DWARF_ONE_KNOWN_DW_UT
4160     default:
4161       return NULL;
4162     }
4163 }
4164
4165
4166 static const char *
4167 dwarf_range_list_encoding_string (unsigned int kind)
4168 {
4169   switch (kind)
4170     {
4171 #define DWARF_ONE_KNOWN_DW_RLE(NAME, CODE) case CODE: return #NAME;
4172       DWARF_ALL_KNOWN_DW_RLE
4173 #undef DWARF_ONE_KNOWN_DW_RLE
4174     default:
4175       return NULL;
4176     }
4177 }
4178
4179
4180 static const char *
4181 dwarf_loc_list_encoding_string (unsigned int kind)
4182 {
4183   switch (kind)
4184     {
4185 #define DWARF_ONE_KNOWN_DW_LLE(NAME, CODE) case CODE: return #NAME;
4186       DWARF_ALL_KNOWN_DW_LLE
4187 #undef DWARF_ONE_KNOWN_DW_LLE
4188     /* DW_LLE_GNU_view_pair is special/incompatible with default codes.  */
4189     case DW_LLE_GNU_view_pair: return "GNU_view_pair";
4190     default:
4191       return NULL;
4192     }
4193 }
4194
4195
4196 static const char *
4197 dwarf_line_content_description_string (unsigned int kind)
4198 {
4199   switch (kind)
4200     {
4201 #define DWARF_ONE_KNOWN_DW_LNCT(NAME, CODE) case CODE: return #NAME;
4202       DWARF_ALL_KNOWN_DW_LNCT
4203 #undef DWARF_ONE_KNOWN_DW_LNCT
4204     default:
4205       return NULL;
4206     }
4207 }
4208
4209
4210 /* Used by all dwarf_foo_name functions.  */
4211 static const char *
4212 string_or_unknown (const char *known, unsigned int code,
4213                    unsigned int lo_user, unsigned int hi_user,
4214                    bool print_unknown_num)
4215 {
4216   static char unknown_buf[20];
4217
4218   if (likely (known != NULL))
4219     return known;
4220
4221   if (lo_user != 0 && code >= lo_user && code <= hi_user)
4222     {
4223       snprintf (unknown_buf, sizeof unknown_buf, "lo_user+%#x",
4224                 code - lo_user);
4225       return unknown_buf;
4226     }
4227
4228   if (print_unknown_num)
4229     {
4230       snprintf (unknown_buf, sizeof unknown_buf, "??? (%#x)", code);
4231       return unknown_buf;
4232     }
4233
4234   return "???";
4235 }
4236
4237
4238 static const char *
4239 dwarf_tag_name (unsigned int tag)
4240 {
4241   const char *ret = dwarf_tag_string (tag);
4242   return string_or_unknown (ret, tag, DW_TAG_lo_user, DW_TAG_hi_user, true);
4243 }
4244
4245 static const char *
4246 dwarf_attr_name (unsigned int attr)
4247 {
4248   const char *ret = dwarf_attr_string (attr);
4249   return string_or_unknown (ret, attr, DW_AT_lo_user, DW_AT_hi_user, true);
4250 }
4251
4252
4253 static const char *
4254 dwarf_form_name (unsigned int form)
4255 {
4256   const char *ret = dwarf_form_string (form);
4257   return string_or_unknown (ret, form, 0, 0, true);
4258 }
4259
4260
4261 static const char *
4262 dwarf_lang_name (unsigned int lang)
4263 {
4264   const char *ret = dwarf_lang_string (lang);
4265   return string_or_unknown (ret, lang, DW_LANG_lo_user, DW_LANG_hi_user, false);
4266 }
4267
4268
4269 static const char *
4270 dwarf_inline_name (unsigned int code)
4271 {
4272   const char *ret = dwarf_inline_string (code);
4273   return string_or_unknown (ret, code, 0, 0, false);
4274 }
4275
4276
4277 static const char *
4278 dwarf_encoding_name (unsigned int code)
4279 {
4280   const char *ret = dwarf_encoding_string (code);
4281   return string_or_unknown (ret, code, DW_ATE_lo_user, DW_ATE_hi_user, false);
4282 }
4283
4284
4285 static const char *
4286 dwarf_access_name (unsigned int code)
4287 {
4288   const char *ret = dwarf_access_string (code);
4289   return string_or_unknown (ret, code, 0, 0, false);
4290 }
4291
4292
4293 static const char *
4294 dwarf_defaulted_name (unsigned int code)
4295 {
4296   const char *ret = dwarf_defaulted_string (code);
4297   return string_or_unknown (ret, code, 0, 0, false);
4298 }
4299
4300
4301 static const char *
4302 dwarf_visibility_name (unsigned int code)
4303 {
4304   const char *ret = dwarf_visibility_string (code);
4305   return string_or_unknown (ret, code, 0, 0, false);
4306 }
4307
4308
4309 static const char *
4310 dwarf_virtuality_name (unsigned int code)
4311 {
4312   const char *ret = dwarf_virtuality_string (code);
4313   return string_or_unknown (ret, code, 0, 0, false);
4314 }
4315
4316
4317 static const char *
4318 dwarf_identifier_case_name (unsigned int code)
4319 {
4320   const char *ret = dwarf_identifier_case_string (code);
4321   return string_or_unknown (ret, code, 0, 0, false);
4322 }
4323
4324
4325 static const char *
4326 dwarf_calling_convention_name (unsigned int code)
4327 {
4328   const char *ret = dwarf_calling_convention_string (code);
4329   return string_or_unknown (ret, code, DW_CC_lo_user, DW_CC_hi_user, false);
4330 }
4331
4332
4333 static const char *
4334 dwarf_ordering_name (unsigned int code)
4335 {
4336   const char *ret = dwarf_ordering_string (code);
4337   return string_or_unknown (ret, code, 0, 0, false);
4338 }
4339
4340
4341 static const char *
4342 dwarf_discr_list_name (unsigned int code)
4343 {
4344   const char *ret = dwarf_discr_list_string (code);
4345   return string_or_unknown (ret, code, 0, 0, false);
4346 }
4347
4348
4349 static const char *
4350 dwarf_unit_name (unsigned int type)
4351 {
4352   const char *ret = dwarf_unit_string (type);
4353   return string_or_unknown (ret, type, DW_UT_lo_user, DW_UT_hi_user, true);
4354 }
4355
4356
4357 static const char *
4358 dwarf_range_list_encoding_name (unsigned int kind)
4359 {
4360   const char *ret = dwarf_range_list_encoding_string (kind);
4361   return string_or_unknown (ret, kind, 0, 0, false);
4362 }
4363
4364
4365 static const char *
4366 dwarf_loc_list_encoding_name (unsigned int kind)
4367 {
4368   const char *ret = dwarf_loc_list_encoding_string (kind);
4369   return string_or_unknown (ret, kind, 0, 0, false);
4370 }
4371
4372
4373 static const char *
4374 dwarf_line_content_description_name (unsigned int kind)
4375 {
4376   const char *ret = dwarf_line_content_description_string (kind);
4377   return string_or_unknown (ret, kind, DW_LNCT_lo_user, DW_LNCT_hi_user,
4378                             false);
4379 }
4380
4381
4382 static void
4383 print_block (size_t n, const void *block)
4384 {
4385   if (n == 0)
4386     puts (_("empty block"));
4387   else
4388     {
4389       printf (_("%zu byte block:"), n);
4390       const unsigned char *data = block;
4391       do
4392         printf (" %02x", *data++);
4393       while (--n > 0);
4394       putchar ('\n');
4395     }
4396 }
4397
4398 static void
4399 print_bytes (size_t n, const unsigned char *bytes)
4400 {
4401   while (n-- > 0)
4402     {
4403       printf ("%02x", *bytes++);
4404       if (n > 0)
4405         printf (" ");
4406     }
4407 }
4408
4409 static int
4410 get_indexed_addr (Dwarf_CU *cu, Dwarf_Word idx, Dwarf_Addr *addr)
4411 {
4412   if (cu == NULL)
4413     return -1;
4414
4415   Elf_Data *debug_addr = cu->dbg->sectiondata[IDX_debug_addr];
4416   if (debug_addr == NULL)
4417     return -1;
4418
4419   Dwarf_Off base = __libdw_cu_addr_base (cu);
4420   Dwarf_Word off = idx * cu->address_size;
4421   if (base > debug_addr->d_size
4422       || off > debug_addr->d_size - base
4423       || cu->address_size > debug_addr->d_size - base - off)
4424     return -1;
4425
4426   const unsigned char *addrp = debug_addr->d_buf + base + off;
4427   if (cu->address_size == 4)
4428     *addr = read_4ubyte_unaligned (cu->dbg, addrp);
4429   else
4430     *addr = read_8ubyte_unaligned (cu->dbg, addrp);
4431
4432   return 0;
4433 }
4434
4435 static void
4436 print_ops (Dwfl_Module *dwflmod, Dwarf *dbg, int indent, int indentrest,
4437            unsigned int vers, unsigned int addrsize, unsigned int offset_size,
4438            struct Dwarf_CU *cu, Dwarf_Word len, const unsigned char *data)
4439 {
4440   const unsigned int ref_size = vers < 3 ? addrsize : offset_size;
4441
4442   if (len == 0)
4443     {
4444       printf ("%*s(empty)\n", indent, "");
4445       return;
4446     }
4447
4448 #define NEED(n)         if (len < (Dwarf_Word) (n)) goto invalid
4449 #define CONSUME(n)      NEED (n); else len -= (n)
4450
4451   Dwarf_Word offset = 0;
4452   while (len-- > 0)
4453     {
4454       uint_fast8_t op = *data++;
4455
4456       const char *op_name = dwarf_locexpr_opcode_string (op);
4457       if (unlikely (op_name == NULL))
4458         {
4459           static char buf[20];
4460           if (op >= DW_OP_lo_user)
4461             snprintf (buf, sizeof buf, "lo_user+%#x", op - DW_OP_lo_user);
4462           else
4463             snprintf (buf, sizeof buf, "??? (%#x)", op);
4464           op_name = buf;
4465         }
4466
4467       switch (op)
4468         {
4469         case DW_OP_addr:;
4470           /* Address operand.  */
4471           Dwarf_Word addr;
4472           NEED (addrsize);
4473           if (addrsize == 4)
4474             addr = read_4ubyte_unaligned (dbg, data);
4475           else if (addrsize == 8)
4476             addr = read_8ubyte_unaligned (dbg, data);
4477           else
4478             goto invalid;
4479           data += addrsize;
4480           CONSUME (addrsize);
4481
4482           printf ("%*s[%2" PRIuMAX "] %s ",
4483                   indent, "", (uintmax_t) offset, op_name);
4484           print_dwarf_addr (dwflmod, 0, addr, addr);
4485           printf ("\n");
4486
4487           offset += 1 + addrsize;
4488           break;
4489
4490         case DW_OP_call_ref:
4491         case DW_OP_GNU_variable_value:
4492           /* Offset operand.  */
4493           if (ref_size != 4 && ref_size != 8)
4494             goto invalid; /* Cannot be used in CFA.  */
4495           NEED (ref_size);
4496           if (ref_size == 4)
4497             addr = read_4ubyte_unaligned (dbg, data);
4498           else
4499             addr = read_8ubyte_unaligned (dbg, data);
4500           data += ref_size;
4501           CONSUME (ref_size);
4502           /* addr is a DIE offset, so format it as one.  */
4503           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIxMAX "]\n",
4504                   indent, "", (uintmax_t) offset,
4505                   op_name, (uintmax_t) addr);
4506           offset += 1 + ref_size;
4507           break;
4508
4509         case DW_OP_deref_size:
4510         case DW_OP_xderef_size:
4511         case DW_OP_pick:
4512         case DW_OP_const1u:
4513           // XXX value might be modified by relocation
4514           NEED (1);
4515           printf ("%*s[%2" PRIuMAX "] %s %" PRIu8 "\n",
4516                   indent, "", (uintmax_t) offset,
4517                   op_name, *((uint8_t *) data));
4518           ++data;
4519           --len;
4520           offset += 2;
4521           break;
4522
4523         case DW_OP_const2u:
4524           NEED (2);
4525           // XXX value might be modified by relocation
4526           printf ("%*s[%2" PRIuMAX "] %s %" PRIu16 "\n",
4527                   indent, "", (uintmax_t) offset,
4528                   op_name, read_2ubyte_unaligned (dbg, data));
4529           CONSUME (2);
4530           data += 2;
4531           offset += 3;
4532           break;
4533
4534         case DW_OP_const4u:
4535           NEED (4);
4536           // XXX value might be modified by relocation
4537           printf ("%*s[%2" PRIuMAX "] %s %" PRIu32 "\n",
4538                   indent, "", (uintmax_t) offset,
4539                   op_name, read_4ubyte_unaligned (dbg, data));
4540           CONSUME (4);
4541           data += 4;
4542           offset += 5;
4543           break;
4544
4545         case DW_OP_const8u:
4546           NEED (8);
4547           // XXX value might be modified by relocation
4548           printf ("%*s[%2" PRIuMAX "] %s %" PRIu64 "\n",
4549                   indent, "", (uintmax_t) offset,
4550                   op_name, (uint64_t) read_8ubyte_unaligned (dbg, data));
4551           CONSUME (8);
4552           data += 8;
4553           offset += 9;
4554           break;
4555
4556         case DW_OP_const1s:
4557           NEED (1);
4558           // XXX value might be modified by relocation
4559           printf ("%*s[%2" PRIuMAX "] %s %" PRId8 "\n",
4560                   indent, "", (uintmax_t) offset,
4561                   op_name, *((int8_t *) data));
4562           ++data;
4563           --len;
4564           offset += 2;
4565           break;
4566
4567         case DW_OP_const2s:
4568           NEED (2);
4569           // XXX value might be modified by relocation
4570           printf ("%*s[%2" PRIuMAX "] %s %" PRId16 "\n",
4571                   indent, "", (uintmax_t) offset,
4572                   op_name, read_2sbyte_unaligned (dbg, data));
4573           CONSUME (2);
4574           data += 2;
4575           offset += 3;
4576           break;
4577
4578         case DW_OP_const4s:
4579           NEED (4);
4580           // XXX value might be modified by relocation
4581           printf ("%*s[%2" PRIuMAX "] %s %" PRId32 "\n",
4582                   indent, "", (uintmax_t) offset,
4583                   op_name, read_4sbyte_unaligned (dbg, data));
4584           CONSUME (4);
4585           data += 4;
4586           offset += 5;
4587           break;
4588
4589         case DW_OP_const8s:
4590           NEED (8);
4591           // XXX value might be modified by relocation
4592           printf ("%*s[%2" PRIuMAX "] %s %" PRId64 "\n",
4593                   indent, "", (uintmax_t) offset,
4594                   op_name, read_8sbyte_unaligned (dbg, data));
4595           CONSUME (8);
4596           data += 8;
4597           offset += 9;
4598           break;
4599
4600         case DW_OP_piece:
4601         case DW_OP_regx:
4602         case DW_OP_plus_uconst:
4603         case DW_OP_constu:;
4604           const unsigned char *start = data;
4605           uint64_t uleb;
4606           NEED (1);
4607           get_uleb128 (uleb, data, data + len);
4608           printf ("%*s[%2" PRIuMAX "] %s %" PRIu64 "\n",
4609                   indent, "", (uintmax_t) offset, op_name, uleb);
4610           CONSUME (data - start);
4611           offset += 1 + (data - start);
4612           break;
4613
4614         case DW_OP_addrx:
4615         case DW_OP_GNU_addr_index:
4616         case DW_OP_constx:
4617         case DW_OP_GNU_const_index:;
4618           start = data;
4619           NEED (1);
4620           get_uleb128 (uleb, data, data + len);
4621           printf ("%*s[%2" PRIuMAX "] %s [%" PRIu64 "] ",
4622                   indent, "", (uintmax_t) offset, op_name, uleb);
4623           CONSUME (data - start);
4624           offset += 1 + (data - start);
4625           if (get_indexed_addr (cu, uleb, &addr) != 0)
4626             printf ("???\n");
4627           else
4628             {
4629               print_dwarf_addr (dwflmod, 0, addr, addr);
4630               printf ("\n");
4631             }
4632           break;
4633
4634         case DW_OP_bit_piece:
4635           start = data;
4636           uint64_t uleb2;
4637           NEED (1);
4638           get_uleb128 (uleb, data, data + len);
4639           NEED (1);
4640           get_uleb128 (uleb2, data, data + len);
4641           printf ("%*s[%2" PRIuMAX "] %s %" PRIu64 ", %" PRIu64 "\n",
4642                   indent, "", (uintmax_t) offset, op_name, uleb, uleb2);
4643           CONSUME (data - start);
4644           offset += 1 + (data - start);
4645           break;
4646
4647         case DW_OP_fbreg:
4648         case DW_OP_breg0 ... DW_OP_breg31:
4649         case DW_OP_consts:
4650           start = data;
4651           int64_t sleb;
4652           NEED (1);
4653           get_sleb128 (sleb, data, data + len);
4654           printf ("%*s[%2" PRIuMAX "] %s %" PRId64 "\n",
4655                   indent, "", (uintmax_t) offset, op_name, sleb);
4656           CONSUME (data - start);
4657           offset += 1 + (data - start);
4658           break;
4659
4660         case DW_OP_bregx:
4661           start = data;
4662           NEED (1);
4663           get_uleb128 (uleb, data, data + len);
4664           NEED (1);
4665           get_sleb128 (sleb, data, data + len);
4666           printf ("%*s[%2" PRIuMAX "] %s %" PRIu64 " %" PRId64 "\n",
4667                   indent, "", (uintmax_t) offset, op_name, uleb, sleb);
4668           CONSUME (data - start);
4669           offset += 1 + (data - start);
4670           break;
4671
4672         case DW_OP_call2:
4673           NEED (2);
4674           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIx16 "]\n",
4675                   indent, "", (uintmax_t) offset, op_name,
4676                   read_2ubyte_unaligned (dbg, data));
4677           CONSUME (2);
4678           data += 2;
4679           offset += 3;
4680           break;
4681
4682         case DW_OP_call4:
4683           NEED (4);
4684           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIx32 "]\n",
4685                   indent, "", (uintmax_t) offset, op_name,
4686                   read_4ubyte_unaligned (dbg, data));
4687           CONSUME (4);
4688           data += 4;
4689           offset += 5;
4690           break;
4691
4692         case DW_OP_skip:
4693         case DW_OP_bra:
4694           NEED (2);
4695           printf ("%*s[%2" PRIuMAX "] %s %" PRIuMAX "\n",
4696                   indent, "", (uintmax_t) offset, op_name,
4697                   (uintmax_t) (offset + read_2sbyte_unaligned (dbg, data) + 3));
4698           CONSUME (2);
4699           data += 2;
4700           offset += 3;
4701           break;
4702
4703         case DW_OP_implicit_value:
4704           start = data;
4705           NEED (1);
4706           get_uleb128 (uleb, data, data + len);
4707           printf ("%*s[%2" PRIuMAX "] %s: ",
4708                   indent, "", (uintmax_t) offset, op_name);
4709           NEED (uleb);
4710           print_block (uleb, data);
4711           data += uleb;
4712           CONSUME (data - start);
4713           offset += 1 + (data - start);
4714           break;
4715
4716         case DW_OP_implicit_pointer:
4717         case DW_OP_GNU_implicit_pointer:
4718           /* DIE offset operand.  */
4719           start = data;
4720           NEED (ref_size);
4721           if (ref_size != 4 && ref_size != 8)
4722             goto invalid; /* Cannot be used in CFA.  */
4723           if (ref_size == 4)
4724             addr = read_4ubyte_unaligned (dbg, data);
4725           else
4726             addr = read_8ubyte_unaligned (dbg, data);
4727           data += ref_size;
4728           /* Byte offset operand.  */
4729           NEED (1);
4730           get_sleb128 (sleb, data, data + len);
4731
4732           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIxMAX "] %+" PRId64 "\n",
4733                   indent, "", (intmax_t) offset,
4734                   op_name, (uintmax_t) addr, sleb);
4735           CONSUME (data - start);
4736           offset += 1 + (data - start);
4737           break;
4738
4739         case DW_OP_entry_value:
4740         case DW_OP_GNU_entry_value:
4741           /* Size plus expression block.  */
4742           start = data;
4743           NEED (1);
4744           get_uleb128 (uleb, data, data + len);
4745           printf ("%*s[%2" PRIuMAX "] %s:\n",
4746                   indent, "", (uintmax_t) offset, op_name);
4747           NEED (uleb);
4748           print_ops (dwflmod, dbg, indent + 5, indent + 5, vers,
4749                      addrsize, offset_size, cu, uleb, data);
4750           data += uleb;
4751           CONSUME (data - start);
4752           offset += 1 + (data - start);
4753           break;
4754
4755         case DW_OP_const_type:
4756         case DW_OP_GNU_const_type:
4757           /* uleb128 CU relative DW_TAG_base_type DIE offset, 1-byte
4758              unsigned size plus block.  */
4759           start = data;
4760           NEED (1);
4761           get_uleb128 (uleb, data, data + len);
4762           if (! print_unresolved_addresses && cu != NULL)
4763             uleb += cu->start;
4764           NEED (1);
4765           uint8_t usize = *(uint8_t *) data++;
4766           NEED (usize);
4767           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIxMAX "] ",
4768                   indent, "", (uintmax_t) offset, op_name, uleb);
4769           print_block (usize, data);
4770           data += usize;
4771           CONSUME (data - start);
4772           offset += 1 + (data - start);
4773           break;
4774
4775         case DW_OP_regval_type:
4776         case DW_OP_GNU_regval_type:
4777           /* uleb128 register number, uleb128 CU relative
4778              DW_TAG_base_type DIE offset.  */
4779           start = data;
4780           NEED (1);
4781           get_uleb128 (uleb, data, data + len);
4782           NEED (1);
4783           get_uleb128 (uleb2, data, data + len);
4784           if (! print_unresolved_addresses && cu != NULL)
4785             uleb2 += cu->start;
4786           printf ("%*s[%2" PRIuMAX "] %s %" PRIu64 " [%6" PRIx64 "]\n",
4787                   indent, "", (uintmax_t) offset, op_name, uleb, uleb2);
4788           CONSUME (data - start);
4789           offset += 1 + (data - start);
4790           break;
4791
4792         case DW_OP_deref_type:
4793         case DW_OP_GNU_deref_type:
4794           /* 1-byte unsigned size of value, uleb128 CU relative
4795              DW_TAG_base_type DIE offset.  */
4796           start = data;
4797           NEED (1);
4798           usize = *(uint8_t *) data++;
4799           NEED (1);
4800           get_uleb128 (uleb, data, data + len);
4801           if (! print_unresolved_addresses && cu != NULL)
4802             uleb += cu->start;
4803           printf ("%*s[%2" PRIuMAX "] %s %" PRIu8 " [%6" PRIxMAX "]\n",
4804                   indent, "", (uintmax_t) offset,
4805                   op_name, usize, uleb);
4806           CONSUME (data - start);
4807           offset += 1 + (data - start);
4808           break;
4809
4810         case DW_OP_xderef_type:
4811           /* 1-byte unsigned size of value, uleb128 base_type DIE offset.  */
4812           start = data;
4813           NEED (1);
4814           usize = *(uint8_t *) data++;
4815           NEED (1);
4816           get_uleb128 (uleb, data, data + len);
4817           printf ("%*s[%4" PRIuMAX "] %s %" PRIu8 " [%6" PRIxMAX "]\n",
4818                   indent, "", (uintmax_t) offset,
4819                   op_name, usize, uleb);
4820           CONSUME (data - start);
4821           offset += 1 + (data - start);
4822           break;
4823
4824         case DW_OP_convert:
4825         case DW_OP_GNU_convert:
4826         case DW_OP_reinterpret:
4827         case DW_OP_GNU_reinterpret:
4828           /* uleb128 CU relative offset to DW_TAG_base_type, or zero
4829              for conversion to untyped.  */
4830           start = data;
4831           NEED (1);
4832           get_uleb128 (uleb, data, data + len);
4833           if (uleb != 0 && ! print_unresolved_addresses && cu != NULL)
4834             uleb += cu->start;
4835           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIxMAX "]\n",
4836                   indent, "", (uintmax_t) offset, op_name, uleb);
4837           CONSUME (data - start);
4838           offset += 1 + (data - start);
4839           break;
4840
4841         case DW_OP_GNU_parameter_ref:
4842           /* 4 byte CU relative reference to the abstract optimized away
4843              DW_TAG_formal_parameter.  */
4844           NEED (4);
4845           uintmax_t param_off = (uintmax_t) read_4ubyte_unaligned (dbg, data);
4846           if (! print_unresolved_addresses && cu != NULL)
4847             param_off += cu->start;
4848           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIxMAX "]\n",
4849                   indent, "", (uintmax_t) offset, op_name, param_off);
4850           CONSUME (4);
4851           data += 4;
4852           offset += 5;
4853           break;
4854
4855         default:
4856           /* No Operand.  */
4857           printf ("%*s[%2" PRIuMAX "] %s\n",
4858                   indent, "", (uintmax_t) offset, op_name);
4859           ++offset;
4860           break;
4861         }
4862
4863       indent = indentrest;
4864       continue;
4865
4866     invalid:
4867       printf (_("%*s[%2" PRIuMAX "] %s  <TRUNCATED>\n"),
4868               indent, "", (uintmax_t) offset, op_name);
4869       break;
4870     }
4871 }
4872
4873
4874 /* Turn the addresses into file offsets by using the phdrs.  */
4875 static void
4876 find_offsets(Elf *elf, GElf_Addr main_bias, size_t n,
4877                   GElf_Addr addrs[n], GElf_Off offs[n])
4878 {
4879   size_t unsolved = n;
4880   for (size_t i = 0; i < phnum; ++i) {
4881     GElf_Phdr phdr_mem;
4882     GElf_Phdr *phdr = gelf_getphdr(elf, i, &phdr_mem);
4883     if (phdr != NULL && phdr->p_type == PT_LOAD && phdr->p_memsz > 0)
4884       for (size_t j = 0; j < n; ++j)
4885         if (offs[j] == 0 && addrs[j] >= phdr->p_vaddr + main_bias &&
4886             addrs[j] - (phdr->p_vaddr + main_bias) < phdr->p_filesz) {
4887           offs[j] = addrs[j] - (phdr->p_vaddr + main_bias) + phdr->p_offset;
4888           if (--unsolved == 0)
4889             break;
4890         }
4891   }
4892 }
4893
4894 /* The dynamic segment (type PT_DYNAMIC), contains the .dynamic section.
4895    And .dynamic section contains an array of the dynamic structures.
4896    We use the array to get:
4897     DT_STRTAB: the address of the string table
4898     DT_SYMTAB: the address of the symbol table
4899     DT_STRSZ: the size, in bytes, of the string table
4900     ...  */
4901 static void
4902 get_dynscn_addrs(Elf *elf, GElf_Phdr *phdr, GElf_Addr addrs[i_max])
4903 {
4904   Elf_Data *data = elf_getdata_rawchunk(
4905     elf, phdr->p_offset, phdr->p_filesz, ELF_T_DYN);
4906
4907   int dyn_idx = 0;
4908   for (;; ++dyn_idx) {
4909     GElf_Dyn dyn_mem;
4910     GElf_Dyn *dyn = gelf_getdyn(data, dyn_idx, &dyn_mem);
4911     /* DT_NULL Marks end of dynamic section.  */
4912     if (dyn->d_tag == DT_NULL)
4913       break;
4914
4915     switch (dyn->d_tag) {
4916     case DT_SYMTAB:
4917       addrs[i_symtab] = dyn->d_un.d_ptr;
4918       break;
4919
4920     case DT_HASH:
4921       addrs[i_hash] = dyn->d_un.d_ptr;
4922       break;
4923
4924     case DT_GNU_HASH:
4925       addrs[i_gnu_hash] = dyn->d_un.d_ptr;
4926       break;
4927
4928     case DT_STRTAB:
4929       addrs[i_strtab] = dyn->d_un.d_ptr;
4930       break;
4931
4932     case DT_VERSYM:
4933       addrs[i_versym] = dyn->d_un.d_ptr;
4934       break;
4935
4936     case DT_VERDEF:
4937       addrs[i_verdef] = dyn->d_un.d_ptr;
4938       break;
4939
4940     case DT_VERNEED:
4941       addrs[i_verneed] = dyn->d_un.d_ptr;
4942       break;
4943
4944     case DT_STRSZ:
4945       addrs[i_strsz] = dyn->d_un.d_val;
4946       break;
4947     }
4948   }
4949 }
4950
4951
4952 /* Use dynamic segment to get data for the string table section.  */
4953 static Elf_Data *
4954 get_dynscn_strtab(Elf *elf, GElf_Phdr *phdr)
4955 {
4956   Elf_Data *strtab_data;
4957   GElf_Addr addrs[i_max] = {0,};
4958   GElf_Off offs[i_max] = {0,};
4959   get_dynscn_addrs(elf, phdr, addrs);
4960   find_offsets(elf, 0, i_max, addrs, offs);
4961   strtab_data = elf_getdata_rawchunk(
4962           elf, offs[i_strtab], addrs[i_strsz], ELF_T_BYTE);
4963   return strtab_data;
4964 }
4965
4966
4967 struct listptr
4968 {
4969   Dwarf_Off offset:(64 - 3);
4970   bool addr64:1;
4971   bool dwarf64:1;
4972   bool warned:1;
4973   struct Dwarf_CU *cu;
4974   unsigned int attr;
4975 };
4976
4977 #define listptr_offset_size(p)  ((p)->dwarf64 ? 8 : 4)
4978 #define listptr_address_size(p) ((p)->addr64 ? 8 : 4)
4979
4980 static Dwarf_Addr
4981 cudie_base (Dwarf_Die *cudie)
4982 {
4983   Dwarf_Addr base;
4984   /* Find the base address of the compilation unit.  It will normally
4985      be specified by DW_AT_low_pc.  In DWARF-3 draft 4, the base
4986      address could be overridden by DW_AT_entry_pc.  It's been
4987      removed, but GCC emits DW_AT_entry_pc and not DW_AT_lowpc for
4988      compilation units with discontinuous ranges.  */
4989   if (unlikely (dwarf_lowpc (cudie, &base) != 0))
4990     {
4991       Dwarf_Attribute attr_mem;
4992       if (dwarf_formaddr (dwarf_attr (cudie, DW_AT_entry_pc, &attr_mem),
4993                           &base) != 0)
4994         base = 0;
4995     }
4996   return base;
4997 }
4998
4999 static Dwarf_Addr
5000 listptr_base (struct listptr *p)
5001 {
5002   Dwarf_Die cu = CUDIE (p->cu);
5003   return cudie_base (&cu);
5004 }
5005
5006 /* To store the name used in compare_listptr */
5007 static const char *sort_listptr_name;
5008
5009 static int
5010 compare_listptr (const void *a, const void *b)
5011 {
5012   const char *name = sort_listptr_name;
5013   struct listptr *p1 = (void *) a;
5014   struct listptr *p2 = (void *) b;
5015
5016   if (p1->offset < p2->offset)
5017     return -1;
5018   if (p1->offset > p2->offset)
5019     return 1;
5020
5021   if (!p1->warned && !p2->warned)
5022     {
5023       if (p1->addr64 != p2->addr64)
5024         {
5025           p1->warned = p2->warned = true;
5026           error (0, 0,
5027                  _("%s %#" PRIx64 " used with different address sizes"),
5028                  name, (uint64_t) p1->offset);
5029         }
5030       if (p1->dwarf64 != p2->dwarf64)
5031         {
5032           p1->warned = p2->warned = true;
5033           error (0, 0,
5034                  _("%s %#" PRIx64 " used with different offset sizes"),
5035                  name, (uint64_t) p1->offset);
5036         }
5037       if (listptr_base (p1) != listptr_base (p2))
5038         {
5039           p1->warned = p2->warned = true;
5040           error (0, 0,
5041                  _("%s %#" PRIx64 " used with different base addresses"),
5042                  name, (uint64_t) p1->offset);
5043         }
5044       if (p1->attr != p2 ->attr)
5045         {
5046           p1->warned = p2->warned = true;
5047           error (0, 0,
5048                  _("%s %#" PRIx64
5049                           " used with different attribute %s and %s"),
5050                  name, (uint64_t) p1->offset, dwarf_attr_name (p1->attr),
5051                  dwarf_attr_name (p2->attr));
5052         }
5053     }
5054
5055   return 0;
5056 }
5057
5058 struct listptr_table
5059 {
5060   size_t n;
5061   size_t alloc;
5062   struct listptr *table;
5063 };
5064
5065 static struct listptr_table known_locsptr;
5066 static struct listptr_table known_loclistsptr;
5067 static struct listptr_table known_rangelistptr;
5068 static struct listptr_table known_rnglistptr;
5069 static struct listptr_table known_addrbases;
5070 static struct listptr_table known_stroffbases;
5071
5072 static void
5073 reset_listptr (struct listptr_table *table)
5074 {
5075   free (table->table);
5076   table->table = NULL;
5077   table->n = table->alloc = 0;
5078 }
5079
5080 /* Returns false if offset doesn't fit.  See struct listptr.  */
5081 static bool
5082 notice_listptr (enum section_e section, struct listptr_table *table,
5083                 uint_fast8_t address_size, uint_fast8_t offset_size,
5084                 struct Dwarf_CU *cu, Dwarf_Off offset, unsigned int attr)
5085 {
5086   if (print_debug_sections & section)
5087     {
5088       if (table->n == table->alloc)
5089         {
5090           if (table->alloc == 0)
5091             table->alloc = 128;
5092           else
5093             table->alloc *= 2;
5094           table->table = xrealloc (table->table,
5095                                    table->alloc * sizeof table->table[0]);
5096         }
5097
5098       struct listptr *p = &table->table[table->n++];
5099
5100       *p = (struct listptr)
5101         {
5102           .addr64 = address_size == 8,
5103           .dwarf64 = offset_size == 8,
5104           .offset = offset,
5105           .cu = cu,
5106           .attr = attr
5107         };
5108
5109       if (p->offset != offset)
5110         {
5111           table->n--;
5112           return false;
5113         }
5114     }
5115   return true;
5116 }
5117
5118 static void
5119 sort_listptr (struct listptr_table *table, const char *name)
5120 {
5121   if (table->n > 0)
5122     {
5123       sort_listptr_name = name;
5124       qsort (table->table, table->n, sizeof table->table[0],
5125              &compare_listptr);
5126     }
5127 }
5128
5129 static bool
5130 skip_listptr_hole (struct listptr_table *table, size_t *idxp,
5131                    uint_fast8_t *address_sizep, uint_fast8_t *offset_sizep,
5132                    Dwarf_Addr *base, struct Dwarf_CU **cu, ptrdiff_t offset,
5133                    unsigned char **readp, unsigned char *endp,
5134                    unsigned int *attr)
5135 {
5136   if (table->n == 0)
5137     return false;
5138
5139   while (*idxp < table->n && table->table[*idxp].offset < (Dwarf_Off) offset)
5140     ++*idxp;
5141
5142   struct listptr *p = &table->table[*idxp];
5143
5144   if (*idxp == table->n
5145       || p->offset >= (Dwarf_Off) (endp - *readp + offset))
5146     {
5147       *readp = endp;
5148       printf (_(" [%6tx]  <UNUSED GARBAGE IN REST OF SECTION>\n"),
5149               offset);
5150       return true;
5151     }
5152
5153   if (p->offset != (Dwarf_Off) offset)
5154     {
5155       *readp += p->offset - offset;
5156       printf (_(" [%6tx]  <UNUSED GARBAGE> ... %" PRIu64 " bytes ...\n"),
5157               offset, (Dwarf_Off) p->offset - offset);
5158       return true;
5159     }
5160
5161   if (address_sizep != NULL)
5162     *address_sizep = listptr_address_size (p);
5163   if (offset_sizep != NULL)
5164     *offset_sizep = listptr_offset_size (p);
5165   if (base != NULL)
5166     *base = listptr_base (p);
5167   if (cu != NULL)
5168     *cu = p->cu;
5169   if (attr != NULL)
5170     *attr = p->attr;
5171
5172   return false;
5173 }
5174
5175 static Dwarf_Off
5176 next_listptr_offset (struct listptr_table *table, size_t *idxp, Dwarf_Off off)
5177 {
5178   /* Note that multiple attributes could in theory point to the same loclist
5179      offset, so make sure we pick one that is bigger than the current one.
5180      The table is sorted on offset.  */
5181   if (*idxp < table->n)
5182     {
5183       while (++*idxp < table->n)
5184         {
5185           Dwarf_Off next = table->table[*idxp].offset;
5186           if (next > off)
5187             return next;
5188         }
5189     }
5190   return 0;
5191 }
5192
5193 /* Returns the listptr associated with the given index, or NULL.  */
5194 static struct listptr *
5195 get_listptr (struct listptr_table *table, size_t idx)
5196 {
5197   if (idx >= table->n)
5198     return NULL;
5199   return &table->table[idx];
5200 }
5201
5202 /* Returns the next index, base address and CU associated with the
5203    list unit offsets.  If there is none false is returned, otherwise
5204    true.  Assumes the table has been sorted.  */
5205 static bool
5206 listptr_cu (struct listptr_table *table, size_t *idxp,
5207             Dwarf_Off start, Dwarf_Off end,
5208             Dwarf_Addr *base, struct Dwarf_CU **cu)
5209 {
5210   while (*idxp < table->n
5211          && table->table[*idxp].offset < start)
5212     ++*idxp;
5213
5214   if (*idxp < table->n
5215       && table->table[*idxp].offset >= start
5216       && table->table[*idxp].offset < end)
5217     {
5218       struct listptr *p = &table->table[*idxp];
5219       *base = listptr_base (p);
5220       *cu = p->cu;
5221       return true;
5222     }
5223
5224   return false;
5225 }
5226
5227 /* Returns the next index with the current CU for the given attribute.
5228    If there is none false is returned, otherwise true.  Assumes the
5229    table has been sorted.  */
5230 static bool
5231 listptr_attr (struct listptr_table *table, size_t idxp,
5232               Dwarf_Off offset, unsigned int attr)
5233 {
5234   struct listptr *listptr;
5235   do
5236     {
5237       listptr = get_listptr (table, idxp);
5238       if (listptr == NULL)
5239         return false;
5240
5241       if (listptr->offset == offset && listptr->attr == attr)
5242         return true;
5243
5244       idxp++;
5245     }
5246   while (listptr->offset <= offset);
5247
5248   return false;
5249 }
5250
5251 static void
5252 print_debug_abbrev_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
5253                             Ebl *ebl, GElf_Ehdr *ehdr __attribute__ ((unused)),
5254                             Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
5255 {
5256   const size_t sh_size = (dbg->sectiondata[IDX_debug_abbrev] ?
5257                           dbg->sectiondata[IDX_debug_abbrev]->d_size : 0);
5258
5259   printf (_("\nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"
5260                    " [ Code]\n"),
5261           elf_ndxscn (scn), section_name (ebl, shdr),
5262           (uint64_t) shdr->sh_offset);
5263
5264   Dwarf_Off offset = 0;
5265   while (offset < sh_size)
5266     {
5267       printf (_("\nAbbreviation section at offset %" PRIu64 ":\n"),
5268               offset);
5269
5270       while (1)
5271         {
5272           size_t length;
5273           Dwarf_Abbrev abbrev;
5274
5275           int res = dwarf_offabbrev (dbg, offset, &length, &abbrev);
5276           if (res != 0)
5277             {
5278               if (unlikely (res < 0))
5279                 {
5280                   printf (_("\
5281  *** error while reading abbreviation: %s\n"),
5282                           dwarf_errmsg (-1));
5283                   return;
5284                 }
5285
5286               /* This is the NUL byte at the end of the section.  */
5287               ++offset;
5288               break;
5289             }
5290
5291           /* We know these calls can never fail.  */
5292           unsigned int code = dwarf_getabbrevcode (&abbrev);
5293           unsigned int tag = dwarf_getabbrevtag (&abbrev);
5294           int has_children = dwarf_abbrevhaschildren (&abbrev);
5295
5296           printf (_(" [%5u] offset: %" PRId64
5297                            ", children: %s, tag: %s\n"),
5298                   code, (int64_t) offset,
5299                   has_children ? yes_str : no_str,
5300                   dwarf_tag_name (tag));
5301
5302           size_t cnt = 0;
5303           unsigned int name;
5304           unsigned int form;
5305           Dwarf_Sword data;
5306           Dwarf_Off enoffset;
5307           while (dwarf_getabbrevattr_data (&abbrev, cnt, &name, &form,
5308                                            &data, &enoffset) == 0)
5309             {
5310               printf ("          attr: %s, form: %s",
5311                       dwarf_attr_name (name), dwarf_form_name (form));
5312               if (form == DW_FORM_implicit_const)
5313                 printf (" (%" PRId64 ")", data);
5314               printf (", offset: %#" PRIx64 "\n", (uint64_t) enoffset);
5315               ++cnt;
5316             }
5317
5318           offset += length;
5319         }
5320     }
5321 }
5322
5323
5324 static void
5325 print_debug_addr_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
5326                           Ebl *ebl, GElf_Ehdr *ehdr,
5327                           Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
5328 {
5329   printf (_("\
5330 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
5331           elf_ndxscn (scn), section_name (ebl, shdr),
5332           (uint64_t) shdr->sh_offset);
5333
5334   if (shdr->sh_size == 0)
5335     return;
5336
5337   /* We like to get the section from libdw to make sure they are relocated.  */
5338   Elf_Data *data = (dbg->sectiondata[IDX_debug_addr]
5339                     ?: elf_rawdata (scn, NULL));
5340   if (unlikely (data == NULL))
5341     {
5342       error (0, 0, _("cannot get .debug_addr section data: %s"),
5343              elf_errmsg (-1));
5344       return;
5345     }
5346
5347   size_t idx = 0;
5348   sort_listptr (&known_addrbases, "addr_base");
5349
5350   const unsigned char *start = (const unsigned char *) data->d_buf;
5351   const unsigned char *readp = start;
5352   const unsigned char *readendp = ((const unsigned char *) data->d_buf
5353                                    + data->d_size);
5354
5355   while (readp < readendp)
5356     {
5357       /* We cannot really know whether or not there is an header.  The
5358          DebugFission extension to DWARF4 doesn't add one.  The DWARF5
5359          .debug_addr variant does.  Whether or not we have an header,
5360          DW_AT_[GNU_]addr_base points at "index 0".  So if the current
5361          offset equals the CU addr_base then we can just start
5362          printing addresses.  If there is no CU with an exact match
5363          then we'll try to parse the header first.  */
5364       Dwarf_Off off = (Dwarf_Off) (readp
5365                                    - (const unsigned char *) data->d_buf);
5366
5367       printf ("Table at offset %" PRIx64 " ", off);
5368
5369       struct listptr *listptr = get_listptr (&known_addrbases, idx++);
5370       const unsigned char *next_unitp;
5371
5372       uint64_t unit_length;
5373       uint16_t version;
5374       uint8_t address_size;
5375       uint8_t segment_size;
5376       if (listptr == NULL)
5377         {
5378           error (0, 0, "Warning: No CU references .debug_addr after %" PRIx64,
5379                  off);
5380
5381           /* We will have to assume it is just addresses to the end... */
5382           address_size = ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
5383           next_unitp = readendp;
5384           printf ("Unknown CU:\n");
5385         }
5386       else
5387         {
5388           Dwarf_Die cudie;
5389           if (dwarf_cu_die (listptr->cu, &cudie,
5390                             NULL, NULL, NULL, NULL,
5391                             NULL, NULL) == NULL)
5392             printf ("Unknown CU (%s):\n", dwarf_errmsg (-1));
5393           else
5394             printf ("for CU [%6" PRIx64 "]:\n", dwarf_dieoffset (&cudie));
5395
5396           if (listptr->offset == off)
5397             {
5398               address_size = listptr_address_size (listptr);
5399               segment_size = 0;
5400               version = 4;
5401
5402               /* The addresses start here, but where do they end?  */
5403               listptr = get_listptr (&known_addrbases, idx);
5404               if (listptr == NULL)
5405                 next_unitp = readendp;
5406               else if (listptr->cu->version < 5)
5407                 {
5408                   next_unitp = start + listptr->offset;
5409                   if (listptr->offset < off || listptr->offset > data->d_size)
5410                     {
5411                       error (0, 0,
5412                              "Warning: Bad address base for next unit at %"
5413                              PRIx64, off);
5414                       next_unitp = readendp;
5415                     }
5416                 }
5417               else
5418                 {
5419                   /* Tricky, we don't have a header for this unit, but
5420                      there is one for the next.  We will have to
5421                      "guess" how big it is and subtract it from the
5422                      offset (because that points after the header).  */
5423                   unsigned int offset_size = listptr_offset_size (listptr);
5424                   Dwarf_Off next_off = (listptr->offset
5425                                         - (offset_size == 4 ? 4 : 12) /* len */
5426                                         - 2 /* version */
5427                                         - 1 /* address size */
5428                                         - 1); /* segment selector size */
5429                   next_unitp = start + next_off;
5430                   if (next_off < off || next_off > data->d_size)
5431                     {
5432                       error (0, 0,
5433                              "Warning: Couldn't calculate .debug_addr "
5434                              " unit length at %" PRIx64, off);
5435                       next_unitp = readendp;
5436                     }
5437                 }
5438               unit_length = (uint64_t) (next_unitp - readp);
5439
5440               /* Pretend we have a header.  */
5441               printf ("\n");
5442               printf (_(" Length:         %8" PRIu64 "\n"),
5443                       unit_length);
5444               printf (_(" DWARF version:  %8" PRIu16 "\n"), version);
5445               printf (_(" Address size:   %8" PRIu64 "\n"),
5446                       (uint64_t) address_size);
5447               printf (_(" Segment size:   %8" PRIu64 "\n"),
5448                       (uint64_t) segment_size);
5449               printf ("\n");
5450             }
5451           else
5452             {
5453               /* OK, we have to parse an header first.  */
5454               unit_length = read_4ubyte_unaligned_inc (dbg, readp);
5455               if (unlikely (unit_length == 0xffffffff))
5456                 {
5457                   if (unlikely (readp > readendp - 8))
5458                     {
5459                     invalid_data:
5460                       error (0, 0, "Invalid data");
5461                       return;
5462                     }
5463                   unit_length = read_8ubyte_unaligned_inc (dbg, readp);
5464                 }
5465               printf ("\n");
5466               printf (_(" Length:         %8" PRIu64 "\n"),
5467                       unit_length);
5468
5469               /* We need at least 2-bytes (version) + 1-byte
5470                  (addr_size) + 1-byte (segment_size) = 4 bytes to
5471                  complete the header.  And this unit cannot go beyond
5472                  the section data.  */
5473               if (readp > readendp - 4
5474                   || unit_length < 4
5475                   || unit_length > (uint64_t) (readendp - readp))
5476                 goto invalid_data;
5477
5478               next_unitp = readp + unit_length;
5479
5480               version = read_2ubyte_unaligned_inc (dbg, readp);
5481               printf (_(" DWARF version:  %8" PRIu16 "\n"), version);
5482
5483               if (version != 5)
5484                 {
5485                   error (0, 0, _("Unknown version"));
5486                   goto next_unit;
5487                 }
5488
5489               address_size = *readp++;
5490               printf (_(" Address size:   %8" PRIu64 "\n"),
5491                       (uint64_t) address_size);
5492
5493               if (address_size != 4 && address_size != 8)
5494                 {
5495                   error (0, 0, _("unsupported address size"));
5496                   goto next_unit;
5497                 }
5498
5499               segment_size = *readp++;
5500               printf (_(" Segment size:   %8" PRIu64 "\n"),
5501                       (uint64_t) segment_size);
5502               printf ("\n");
5503
5504               if (segment_size != 0)
5505                 {
5506                   error (0, 0, _("unsupported segment size"));
5507                   goto next_unit;
5508                 }
5509
5510               if (listptr->offset != (Dwarf_Off) (readp - start))
5511                 {
5512                   error (0, 0, "Address index doesn't start after header");
5513                   goto next_unit;
5514                 }
5515             }
5516         }
5517
5518       int digits = 1;
5519       size_t addresses = (next_unitp - readp) / address_size;
5520       while (addresses >= 10)
5521         {
5522           ++digits;
5523           addresses /= 10;
5524         }
5525
5526       unsigned int uidx = 0;
5527       size_t index_offset =  readp - (const unsigned char *) data->d_buf;
5528       printf (" Addresses start at offset 0x%zx:\n", index_offset);
5529       while (readp <= next_unitp - address_size)
5530         {
5531           Dwarf_Addr addr = read_addr_unaligned_inc (address_size, dbg,
5532                                                      readp);
5533           printf (" [%*u] ", digits, uidx++);
5534           print_dwarf_addr (dwflmod, address_size, addr, addr);
5535           printf ("\n");
5536         }
5537       printf ("\n");
5538
5539       if (readp != next_unitp)
5540         error (0, 0, "extra %zd bytes at end of unit",
5541                (size_t) (next_unitp - readp));
5542
5543     next_unit:
5544       readp = next_unitp;
5545     }
5546 }
5547
5548 /* Print content of DWARF .debug_aranges section.  We fortunately do
5549    not have to know a bit about the structure of the section, libdwarf
5550    takes care of it.  */
5551 static void
5552 print_decoded_aranges_section (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn,
5553                                GElf_Shdr *shdr, Dwarf *dbg)
5554 {
5555   Dwarf_Aranges *aranges;
5556   size_t cnt;
5557   if (unlikely (dwarf_getaranges (dbg, &aranges, &cnt) != 0))
5558     {
5559       error (0, 0, _("cannot get .debug_aranges content: %s"),
5560              dwarf_errmsg (-1));
5561       return;
5562     }
5563
5564   GElf_Shdr glink_mem;
5565   GElf_Shdr *glink;
5566   glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link), &glink_mem);
5567   if (glink == NULL)
5568     {
5569       error (0, 0, _("invalid sh_link value in section %zu"),
5570              elf_ndxscn (scn));
5571       return;
5572     }
5573
5574   printf (ngettext ("\
5575 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 " contains %zu entry:\n",
5576                     "\
5577 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 " contains %zu entries:\n",
5578                     cnt),
5579           elf_ndxscn (scn), section_name (ebl, shdr),
5580           (uint64_t) shdr->sh_offset, cnt);
5581
5582   /* Compute floor(log16(cnt)).  */
5583   size_t tmp = cnt;
5584   int digits = 1;
5585   while (tmp >= 16)
5586     {
5587       ++digits;
5588       tmp >>= 4;
5589     }
5590
5591   for (size_t n = 0; n < cnt; ++n)
5592     {
5593       Dwarf_Arange *runp = dwarf_onearange (aranges, n);
5594       if (unlikely (runp == NULL))
5595         {
5596           printf ("cannot get arange %zu: %s\n", n, dwarf_errmsg (-1));
5597           return;
5598         }
5599
5600       Dwarf_Addr start;
5601       Dwarf_Word length;
5602       Dwarf_Off offset;
5603
5604       if (unlikely (dwarf_getarangeinfo (runp, &start, &length, &offset) != 0))
5605         printf (_(" [%*zu] ???\n"), digits, n);
5606       else
5607         printf (_(" [%*zu] start: %0#*" PRIx64
5608                          ", length: %5" PRIu64 ", CU DIE offset: %6"
5609                          PRId64 "\n"),
5610                 digits, n, ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 10 : 18,
5611                 (uint64_t) start, (uint64_t) length, (int64_t) offset);
5612     }
5613 }
5614
5615
5616 /* Print content of DWARF .debug_aranges section.  */
5617 static void
5618 print_debug_aranges_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
5619                              Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn,
5620                              GElf_Shdr *shdr, Dwarf *dbg)
5621 {
5622   if (decodedaranges)
5623     {
5624       print_decoded_aranges_section (ebl, ehdr, scn, shdr, dbg);
5625       return;
5626     }
5627
5628   Elf_Data *data = (dbg->sectiondata[IDX_debug_aranges]
5629                     ?: elf_rawdata (scn, NULL));
5630
5631   if (unlikely (data == NULL))
5632     {
5633       error (0, 0, _("cannot get .debug_aranges content: %s"),
5634              elf_errmsg (-1));
5635       return;
5636     }
5637
5638   printf (_("\
5639 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
5640           elf_ndxscn (scn), section_name (ebl, shdr),
5641           (uint64_t) shdr->sh_offset);
5642
5643   const unsigned char *readp = data->d_buf;
5644   const unsigned char *readendp = readp + data->d_size;
5645
5646   while (readp < readendp)
5647     {
5648       const unsigned char *hdrstart = readp;
5649       size_t start_offset = hdrstart - (const unsigned char *) data->d_buf;
5650
5651       printf (_("\nTable at offset %zu:\n"), start_offset);
5652       if (readp + 4 > readendp)
5653         {
5654         invalid_data:
5655           error (0, 0, _("invalid data in section [%zu] '%s'"),
5656                  elf_ndxscn (scn), section_name (ebl, shdr));
5657           return;
5658         }
5659
5660       Dwarf_Word length = read_4ubyte_unaligned_inc (dbg, readp);
5661       unsigned int length_bytes = 4;
5662       if (length == DWARF3_LENGTH_64_BIT)
5663         {
5664           if (readp + 8 > readendp)
5665             goto invalid_data;
5666           length = read_8ubyte_unaligned_inc (dbg, readp);
5667           length_bytes = 8;
5668         }
5669
5670       const unsigned char *nexthdr = readp + length;
5671       printf (_("\n Length:        %6" PRIu64 "\n"),
5672               (uint64_t) length);
5673
5674       if (unlikely (length > (size_t) (readendp - readp)))
5675         goto invalid_data;
5676
5677       if (length == 0)
5678         continue;
5679
5680       if (readp + 2 > readendp)
5681         goto invalid_data;
5682       uint_fast16_t version = read_2ubyte_unaligned_inc (dbg, readp);
5683       printf (_(" DWARF version: %6" PRIuFAST16 "\n"),
5684               version);
5685       if (version != 2)
5686         {
5687           error (0, 0, _("unsupported aranges version"));
5688           goto next_table;
5689         }
5690
5691       Dwarf_Word offset;
5692       if (readp + length_bytes > readendp)
5693         goto invalid_data;
5694       if (length_bytes == 8)
5695         offset = read_8ubyte_unaligned_inc (dbg, readp);
5696       else
5697         offset = read_4ubyte_unaligned_inc (dbg, readp);
5698       printf (_(" CU offset:     %6" PRIx64 "\n"),
5699               (uint64_t) offset);
5700
5701       if (readp + 1 > readendp)
5702         goto invalid_data;
5703       unsigned int address_size = *readp++;
5704       printf (_(" Address size:  %6" PRIu64 "\n"),
5705               (uint64_t) address_size);
5706       if (address_size != 4 && address_size != 8)
5707         {
5708           error (0, 0, _("unsupported address size"));
5709           goto next_table;
5710         }
5711
5712       if (readp + 1 > readendp)
5713         goto invalid_data;
5714       unsigned int segment_size = *readp++;
5715       printf (_(" Segment size:  %6" PRIu64 "\n\n"),
5716               (uint64_t) segment_size);
5717       if (segment_size != 0 && segment_size != 4 && segment_size != 8)
5718         {
5719           error (0, 0, _("unsupported segment size"));
5720           goto next_table;
5721         }
5722
5723       /* Round the address to the next multiple of 2*address_size.  */
5724       readp += ((2 * address_size - ((readp - hdrstart) % (2 * address_size)))
5725                 % (2 * address_size));
5726
5727       while (readp < nexthdr)
5728         {
5729           Dwarf_Word range_address;
5730           Dwarf_Word range_length;
5731           Dwarf_Word segment = 0;
5732           if (readp + 2 * address_size + segment_size > readendp)
5733             goto invalid_data;
5734           if (address_size == 4)
5735             {
5736               range_address = read_4ubyte_unaligned_inc (dbg, readp);
5737               range_length = read_4ubyte_unaligned_inc (dbg, readp);
5738             }
5739           else
5740             {
5741               range_address = read_8ubyte_unaligned_inc (dbg, readp);
5742               range_length = read_8ubyte_unaligned_inc (dbg, readp);
5743             }
5744
5745           if (segment_size == 4)
5746             segment = read_4ubyte_unaligned_inc (dbg, readp);
5747           else if (segment_size == 8)
5748             segment = read_8ubyte_unaligned_inc (dbg, readp);
5749
5750           if (range_address == 0 && range_length == 0 && segment == 0)
5751             break;
5752
5753           printf ("   ");
5754           print_dwarf_addr (dwflmod, address_size, range_address,
5755                             range_address);
5756           printf ("..");
5757           print_dwarf_addr (dwflmod, address_size,
5758                             range_address + range_length - 1,
5759                             range_length);
5760           if (segment_size != 0)
5761             printf (" (%" PRIx64 ")\n", (uint64_t) segment);
5762           else
5763             printf ("\n");
5764         }
5765
5766     next_table:
5767       if (readp != nexthdr)
5768         {
5769           size_t padding = nexthdr - readp;
5770           printf (_("   %zu padding bytes\n"), padding);
5771           readp = nexthdr;
5772         }
5773     }
5774 }
5775
5776
5777 static bool is_split_dwarf (Dwarf *dbg, uint64_t *id, Dwarf_CU **split_cu);
5778
5779 /* Returns true and sets cu and cu_base if the given Dwarf is a split
5780    DWARF (.dwo) file.  */
5781 static bool
5782 split_dwarf_cu_base (Dwarf *dbg, Dwarf_CU **cu, Dwarf_Addr *cu_base)
5783 {
5784   uint64_t id;
5785   if (is_split_dwarf (dbg, &id, cu))
5786     {
5787       Dwarf_Die cudie;
5788       if (dwarf_cu_info (*cu, NULL, NULL, &cudie, NULL, NULL, NULL, NULL) == 0)
5789         {
5790           *cu_base = cudie_base (&cudie);
5791           return true;
5792         }
5793     }
5794   return false;
5795 }
5796
5797 /* Print content of DWARF .debug_rnglists section.  */
5798 static void
5799 print_debug_rnglists_section (Dwfl_Module *dwflmod,
5800                               Ebl *ebl,
5801                               GElf_Ehdr *ehdr __attribute__ ((unused)),
5802                               Elf_Scn *scn, GElf_Shdr *shdr,
5803                               Dwarf *dbg __attribute__((unused)))
5804 {
5805   printf (_("\
5806 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
5807           elf_ndxscn (scn), section_name (ebl, shdr),
5808           (uint64_t) shdr->sh_offset);
5809
5810   Elf_Data *data =(dbg->sectiondata[IDX_debug_rnglists]
5811                    ?: elf_rawdata (scn, NULL));
5812   if (unlikely (data == NULL))
5813     {
5814       error (0, 0, _("cannot get .debug_rnglists content: %s"),
5815              elf_errmsg (-1));
5816       return;
5817     }
5818
5819   /* For the listptr to get the base address/CU.  */
5820   sort_listptr (&known_rnglistptr, "rnglistptr");
5821   size_t listptr_idx = 0;
5822
5823   const unsigned char *readp = data->d_buf;
5824   const unsigned char *const dataend = ((unsigned char *) data->d_buf
5825                                         + data->d_size);
5826   while (readp < dataend)
5827     {
5828       if (unlikely (readp > dataend - 4))
5829         {
5830         invalid_data:
5831           error (0, 0, _("invalid data in section [%zu] '%s'"),
5832                  elf_ndxscn (scn), section_name (ebl, shdr));
5833           return;
5834         }
5835
5836       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
5837       printf (_("Table at Offset 0x%" PRIx64 ":\n\n"),
5838               (uint64_t) offset);
5839
5840       uint64_t unit_length = read_4ubyte_unaligned_inc (dbg, readp);
5841       unsigned int offset_size = 4;
5842       if (unlikely (unit_length == 0xffffffff))
5843         {
5844           if (unlikely (readp > dataend - 8))
5845             goto invalid_data;
5846
5847           unit_length = read_8ubyte_unaligned_inc (dbg, readp);
5848           offset_size = 8;
5849         }
5850       printf (_(" Length:         %8" PRIu64 "\n"), unit_length);
5851
5852       /* We need at least 2-bytes + 1-byte + 1-byte + 4-bytes = 8
5853          bytes to complete the header.  And this unit cannot go beyond
5854          the section data.  */
5855       if (readp > dataend - 8
5856           || unit_length < 8
5857           || unit_length > (uint64_t) (dataend - readp))
5858         goto invalid_data;
5859
5860       const unsigned char *nexthdr = readp + unit_length;
5861
5862       uint16_t version = read_2ubyte_unaligned_inc (dbg, readp);
5863       printf (_(" DWARF version:  %8" PRIu16 "\n"), version);
5864
5865       if (version != 5)
5866         {
5867           error (0, 0, _("Unknown version"));
5868           goto next_table;
5869         }
5870
5871       uint8_t address_size = *readp++;
5872       printf (_(" Address size:   %8" PRIu64 "\n"),
5873               (uint64_t) address_size);
5874
5875       if (address_size != 4 && address_size != 8)
5876         {
5877           error (0, 0, _("unsupported address size"));
5878           goto next_table;
5879         }
5880
5881       uint8_t segment_size = *readp++;
5882       printf (_(" Segment size:   %8" PRIu64 "\n"),
5883               (uint64_t) segment_size);
5884
5885       if (segment_size != 0 && segment_size != 4 && segment_size != 8)
5886         {
5887           error (0, 0, _("unsupported segment size"));
5888           goto next_table;
5889         }
5890
5891       uint32_t offset_entry_count = read_4ubyte_unaligned_inc (dbg, readp);
5892       printf (_(" Offset entries: %8" PRIu64 "\n"),
5893               (uint64_t) offset_entry_count);
5894
5895       /* We need the CU that uses this unit to get the initial base address. */
5896       Dwarf_Addr cu_base = 0;
5897       struct Dwarf_CU *cu = NULL;
5898       if (listptr_cu (&known_rnglistptr, &listptr_idx,
5899                       (Dwarf_Off) offset,
5900                       (Dwarf_Off) (nexthdr - (unsigned char *) data->d_buf),
5901                       &cu_base, &cu)
5902           || split_dwarf_cu_base (dbg, &cu, &cu_base))
5903         {
5904           Dwarf_Die cudie;
5905           if (dwarf_cu_die (cu, &cudie,
5906                             NULL, NULL, NULL, NULL,
5907                             NULL, NULL) == NULL)
5908             printf (_(" Unknown CU base: "));
5909           else
5910             printf (_(" CU [%6" PRIx64 "] base: "),
5911                     dwarf_dieoffset (&cudie));
5912           print_dwarf_addr (dwflmod, address_size, cu_base, cu_base);
5913           printf ("\n");
5914         }
5915       else
5916         printf (_(" Not associated with a CU.\n"));
5917
5918       printf ("\n");
5919
5920       const unsigned char *offset_array_start = readp;
5921       if (offset_entry_count > 0)
5922         {
5923           uint64_t max_entries = (unit_length - 8) / offset_size;
5924           if (offset_entry_count > max_entries)
5925             {
5926               error (0, 0,
5927                      _("too many offset entries for unit length"));
5928               offset_entry_count = max_entries;
5929             }
5930
5931           printf (_("  Offsets starting at 0x%" PRIx64 ":\n"),
5932                   (uint64_t) (offset_array_start
5933                               - (unsigned char *) data->d_buf));
5934           for (uint32_t idx = 0; idx < offset_entry_count; idx++)
5935             {
5936               printf ("   [%6" PRIu32 "] ", idx);
5937               if (offset_size == 4)
5938                 {
5939                   uint32_t off = read_4ubyte_unaligned_inc (dbg, readp);
5940                   printf ("0x%" PRIx32 "\n", off);
5941                 }
5942               else
5943                 {
5944                   uint64_t off = read_8ubyte_unaligned_inc (dbg, readp);
5945                   printf ("0x%" PRIx64 "\n", off);
5946                 }
5947             }
5948           printf ("\n");
5949         }
5950
5951       Dwarf_Addr base = cu_base;
5952       bool start_of_list = true;
5953       while (readp < nexthdr)
5954         {
5955           uint8_t kind = *readp++;
5956           uint64_t op1, op2;
5957
5958           /* Skip padding.  */
5959           if (start_of_list && kind == DW_RLE_end_of_list)
5960             continue;
5961
5962           if (start_of_list)
5963             {
5964               base = cu_base;
5965               printf ("  Offset: %" PRIx64 ", Index: %" PRIx64 "\n",
5966                       (uint64_t) (readp - (unsigned char *) data->d_buf - 1),
5967                       (uint64_t) (readp - offset_array_start - 1));
5968               start_of_list = false;
5969             }
5970
5971           printf ("    %s", dwarf_range_list_encoding_name (kind));
5972           switch (kind)
5973             {
5974             case DW_RLE_end_of_list:
5975               start_of_list = true;
5976               printf ("\n\n");
5977               break;
5978
5979             case DW_RLE_base_addressx:
5980               if ((uint64_t) (nexthdr - readp) < 1)
5981                 {
5982                 invalid_range:
5983                   error (0, 0, _("invalid range list data"));
5984                   goto next_table;
5985                 }
5986               get_uleb128 (op1, readp, nexthdr);
5987               printf (" %" PRIx64 "\n", op1);
5988               if (! print_unresolved_addresses)
5989                 {
5990                   Dwarf_Addr addr;
5991                   if (get_indexed_addr (cu, op1, &addr) != 0)
5992                     printf ("      ???\n");
5993                   else
5994                     {
5995                       printf ("      ");
5996                       print_dwarf_addr (dwflmod, address_size, addr, addr);
5997                       printf ("\n");
5998                     }
5999                 }
6000               break;
6001
6002             case DW_RLE_startx_endx:
6003               if ((uint64_t) (nexthdr - readp) < 1)
6004                 goto invalid_range;
6005               get_uleb128 (op1, readp, nexthdr);
6006               if ((uint64_t) (nexthdr - readp) < 1)
6007                 goto invalid_range;
6008               get_uleb128 (op2, readp, nexthdr);
6009               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
6010               if (! print_unresolved_addresses)
6011                 {
6012                   Dwarf_Addr addr1;
6013                   Dwarf_Addr addr2;
6014                   if (get_indexed_addr (cu, op1, &addr1) != 0
6015                       || get_indexed_addr (cu, op2, &addr2) != 0)
6016                     {
6017                       printf ("      ???..\n");
6018                       printf ("      ???\n");
6019                     }
6020                   else
6021                     {
6022                       printf ("      ");
6023                       print_dwarf_addr (dwflmod, address_size, addr1, addr1);
6024                       printf ("..\n      ");
6025                       print_dwarf_addr (dwflmod, address_size,
6026                                         addr2 - 1, addr2);
6027                       printf ("\n");
6028                     }
6029                 }
6030               break;
6031
6032             case DW_RLE_startx_length:
6033               if ((uint64_t) (nexthdr - readp) < 1)
6034                 goto invalid_range;
6035               get_uleb128 (op1, readp, nexthdr);
6036               if ((uint64_t) (nexthdr - readp) < 1)
6037                 goto invalid_range;
6038               get_uleb128 (op2, readp, nexthdr);
6039               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
6040               if (! print_unresolved_addresses)
6041                 {
6042                   Dwarf_Addr addr1;
6043                   Dwarf_Addr addr2;
6044                   if (get_indexed_addr (cu, op1, &addr1) != 0)
6045                     {
6046                       printf ("      ???..\n");
6047                       printf ("      ???\n");
6048                     }
6049                   else
6050                     {
6051                       addr2 = addr1 + op2;
6052                       printf ("      ");
6053                       print_dwarf_addr (dwflmod, address_size, addr1, addr1);
6054                       printf ("..\n      ");
6055                       print_dwarf_addr (dwflmod, address_size,
6056                                         addr2 - 1, addr2);
6057                       printf ("\n");
6058                     }
6059                 }
6060               break;
6061
6062             case DW_RLE_offset_pair:
6063               if ((uint64_t) (nexthdr - readp) < 1)
6064                 goto invalid_range;
6065               get_uleb128 (op1, readp, nexthdr);
6066               if ((uint64_t) (nexthdr - readp) < 1)
6067                 goto invalid_range;
6068               get_uleb128 (op2, readp, nexthdr);
6069               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
6070               if (! print_unresolved_addresses)
6071                 {
6072                   op1 += base;
6073                   op2 += base;
6074                   printf ("      ");
6075                   print_dwarf_addr (dwflmod, address_size, op1, op1);
6076                   printf ("..\n      ");
6077                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
6078                   printf ("\n");
6079                 }
6080               break;
6081
6082             case DW_RLE_base_address:
6083               if (address_size == 4)
6084                 {
6085                   if ((uint64_t) (nexthdr - readp) < 4)
6086                     goto invalid_range;
6087                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
6088                 }
6089               else
6090                 {
6091                   if ((uint64_t) (nexthdr - readp) < 8)
6092                     goto invalid_range;
6093                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
6094                 }
6095               base = op1;
6096               printf (" 0x%" PRIx64 "\n", base);
6097               if (! print_unresolved_addresses)
6098                 {
6099                   printf ("      ");
6100                   print_dwarf_addr (dwflmod, address_size, base, base);
6101                   printf ("\n");
6102                 }
6103               break;
6104
6105             case DW_RLE_start_end:
6106               if (address_size == 4)
6107                 {
6108                   if ((uint64_t) (nexthdr - readp) < 8)
6109                     goto invalid_range;
6110                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
6111                   op2 = read_4ubyte_unaligned_inc (dbg, readp);
6112                 }
6113               else
6114                 {
6115                   if ((uint64_t) (nexthdr - readp) < 16)
6116                     goto invalid_range;
6117                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
6118                   op2 = read_8ubyte_unaligned_inc (dbg, readp);
6119                 }
6120               printf (" 0x%" PRIx64 "..0x%" PRIx64 "\n", op1, op2);
6121               if (! print_unresolved_addresses)
6122                 {
6123                   printf ("      ");
6124                   print_dwarf_addr (dwflmod, address_size, op1, op1);
6125                   printf ("..\n      ");
6126                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
6127                   printf ("\n");
6128                 }
6129               break;
6130
6131             case DW_RLE_start_length:
6132               if (address_size == 4)
6133                 {
6134                   if ((uint64_t) (nexthdr - readp) < 4)
6135                     goto invalid_range;
6136                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
6137                 }
6138               else
6139                 {
6140                   if ((uint64_t) (nexthdr - readp) < 8)
6141                     goto invalid_range;
6142                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
6143                 }
6144               if ((uint64_t) (nexthdr - readp) < 1)
6145                 goto invalid_range;
6146               get_uleb128 (op2, readp, nexthdr);
6147               printf (" 0x%" PRIx64 ", %" PRIx64 "\n", op1, op2);
6148               if (! print_unresolved_addresses)
6149                 {
6150                   op2 = op1 + op2;
6151                   printf ("      ");
6152                   print_dwarf_addr (dwflmod, address_size, op1, op1);
6153                   printf ("..\n      ");
6154                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
6155                   printf ("\n");
6156                 }
6157               break;
6158
6159             default:
6160               goto invalid_range;
6161             }
6162         }
6163
6164     next_table:
6165       if (readp != nexthdr)
6166         {
6167           size_t padding = nexthdr - readp;
6168           printf (_("   %zu padding bytes\n\n"), padding);
6169           readp = nexthdr;
6170         }
6171     }
6172 }
6173
6174 /* Print content of DWARF .debug_ranges section.  */
6175 static void
6176 print_debug_ranges_section (Dwfl_Module *dwflmod,
6177                             Ebl *ebl, GElf_Ehdr *ehdr,
6178                             Elf_Scn *scn, GElf_Shdr *shdr,
6179                             Dwarf *dbg)
6180 {
6181   Elf_Data *data = (dbg->sectiondata[IDX_debug_ranges]
6182                     ?: elf_rawdata (scn, NULL));
6183   if (unlikely (data == NULL))
6184     {
6185       error (0, 0, _("cannot get .debug_ranges content: %s"),
6186              elf_errmsg (-1));
6187       return;
6188     }
6189
6190   printf (_("\
6191 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
6192           elf_ndxscn (scn), section_name (ebl, shdr),
6193           (uint64_t) shdr->sh_offset);
6194
6195   sort_listptr (&known_rangelistptr, "rangelistptr");
6196   size_t listptr_idx = 0;
6197
6198   uint_fast8_t address_size = ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
6199
6200   bool first = true;
6201   Dwarf_Addr base = 0;
6202   unsigned char *const endp = (unsigned char *) data->d_buf + data->d_size;
6203   unsigned char *readp = data->d_buf;
6204   Dwarf_CU *last_cu = NULL;
6205   while (readp < endp)
6206     {
6207       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
6208       Dwarf_CU *cu = last_cu;
6209
6210       if (first && skip_listptr_hole (&known_rangelistptr, &listptr_idx,
6211                                       &address_size, NULL, &base, &cu,
6212                                       offset, &readp, endp, NULL))
6213         continue;
6214
6215       if (last_cu != cu)
6216         {
6217           Dwarf_Die cudie;
6218           if (dwarf_cu_die (cu, &cudie,
6219                             NULL, NULL, NULL, NULL,
6220                             NULL, NULL) == NULL)
6221             printf (_("\n Unknown CU base: "));
6222           else
6223             printf (_("\n CU [%6" PRIx64 "] base: "),
6224                     dwarf_dieoffset (&cudie));
6225           print_dwarf_addr (dwflmod, address_size, base, base);
6226           printf ("\n");
6227         }
6228       last_cu = cu;
6229
6230       if (unlikely (data->d_size - offset < (size_t) address_size * 2))
6231         {
6232           printf (_(" [%6tx]  <INVALID DATA>\n"), offset);
6233           break;
6234         }
6235
6236       Dwarf_Addr begin;
6237       Dwarf_Addr end;
6238       if (address_size == 8)
6239         {
6240           begin = read_8ubyte_unaligned_inc (dbg, readp);
6241           end = read_8ubyte_unaligned_inc (dbg, readp);
6242         }
6243       else
6244         {
6245           begin = read_4ubyte_unaligned_inc (dbg, readp);
6246           end = read_4ubyte_unaligned_inc (dbg, readp);
6247           if (begin == (Dwarf_Addr) (uint32_t) -1)
6248             begin = (Dwarf_Addr) -1l;
6249         }
6250
6251       if (begin == (Dwarf_Addr) -1l) /* Base address entry.  */
6252         {
6253           if (first)
6254             printf (" [%6tx] ", offset);
6255           else
6256             printf ("          ");
6257           puts (_("base address"));
6258           printf ("          ");
6259           print_dwarf_addr (dwflmod, address_size, end, end);
6260           printf ("\n");
6261           base = end;
6262           first = false;
6263         }
6264       else if (begin == 0 && end == 0) /* End of list entry.  */
6265         {
6266           if (first)
6267             printf (_(" [%6tx] empty list\n"), offset);
6268           first = true;
6269         }
6270       else
6271         {
6272           /* We have an address range entry.  */
6273           if (first)            /* First address range entry in a list.  */
6274             printf (" [%6tx] ", offset);
6275           else
6276             printf ("          ");
6277
6278           printf ("range %" PRIx64 ", %" PRIx64 "\n", begin, end);
6279           if (! print_unresolved_addresses)
6280             {
6281               printf ("          ");
6282               print_dwarf_addr (dwflmod, address_size, base + begin,
6283                                 base + begin);
6284               printf ("..\n          ");
6285               print_dwarf_addr (dwflmod, address_size,
6286                                 base + end - 1, base + end);
6287               printf ("\n");
6288             }
6289
6290           first = false;
6291         }
6292     }
6293 }
6294
6295 #define REGNAMESZ 16
6296 static const char *
6297 register_info (Ebl *ebl, unsigned int regno, const Ebl_Register_Location *loc,
6298                char name[REGNAMESZ], int *bits, int *type)
6299 {
6300   const char *set;
6301   const char *pfx;
6302   int ignore;
6303   ssize_t n = ebl_register_info (ebl, regno, name, REGNAMESZ, &pfx, &set,
6304                                  bits ?: &ignore, type ?: &ignore);
6305   if (n <= 0)
6306     {
6307       if (loc != NULL)
6308         snprintf (name, REGNAMESZ, "reg%u", loc->regno);
6309       else
6310         snprintf (name, REGNAMESZ, "??? 0x%x", regno);
6311       if (bits != NULL)
6312         *bits = loc != NULL ? loc->bits : 0;
6313       if (type != NULL)
6314         *type = DW_ATE_unsigned;
6315       set = "??? unrecognized";
6316     }
6317   else
6318     {
6319       if (bits != NULL && *bits <= 0)
6320         *bits = loc != NULL ? loc->bits : 0;
6321       if (type != NULL && *type == DW_ATE_void)
6322         *type = DW_ATE_unsigned;
6323
6324     }
6325   return set;
6326 }
6327
6328 static const unsigned char *
6329 read_encoded (unsigned int encoding, const unsigned char *readp,
6330               const unsigned char *const endp, uint64_t *res, Dwarf *dbg)
6331 {
6332   if ((encoding & 0xf) == DW_EH_PE_absptr)
6333     encoding = gelf_getclass (dbg->elf) == ELFCLASS32
6334       ? DW_EH_PE_udata4 : DW_EH_PE_udata8;
6335
6336   switch (encoding & 0xf)
6337     {
6338     case DW_EH_PE_uleb128:
6339       get_uleb128 (*res, readp, endp);
6340       break;
6341     case DW_EH_PE_sleb128:
6342       get_sleb128 (*res, readp, endp);
6343       break;
6344     case DW_EH_PE_udata2:
6345       if (readp + 2 > endp)
6346         goto invalid;
6347       *res = read_2ubyte_unaligned_inc (dbg, readp);
6348       break;
6349     case DW_EH_PE_udata4:
6350       if (readp + 4 > endp)
6351         goto invalid;
6352       *res = read_4ubyte_unaligned_inc (dbg, readp);
6353       break;
6354     case DW_EH_PE_udata8:
6355       if (readp + 8 > endp)
6356         goto invalid;
6357       *res = read_8ubyte_unaligned_inc (dbg, readp);
6358       break;
6359     case DW_EH_PE_sdata2:
6360       if (readp + 2 > endp)
6361         goto invalid;
6362       *res = read_2sbyte_unaligned_inc (dbg, readp);
6363       break;
6364     case DW_EH_PE_sdata4:
6365       if (readp + 4 > endp)
6366         goto invalid;
6367       *res = read_4sbyte_unaligned_inc (dbg, readp);
6368       break;
6369     case DW_EH_PE_sdata8:
6370       if (readp + 8 > endp)
6371         goto invalid;
6372       *res = read_8sbyte_unaligned_inc (dbg, readp);
6373       break;
6374     default:
6375     invalid:
6376       error (1, 0,
6377              _("invalid encoding"));
6378     }
6379
6380   return readp;
6381 }
6382
6383 static const char *
6384 regname (Ebl *ebl, unsigned int regno, char *regnamebuf)
6385 {
6386   register_info (ebl, regno, NULL, regnamebuf, NULL, NULL);
6387
6388   return regnamebuf;
6389 }
6390
6391 static void
6392 print_cfa_program (const unsigned char *readp, const unsigned char *const endp,
6393                    Dwarf_Word vma_base, unsigned int code_align,
6394                    int data_align,
6395                    unsigned int version, unsigned int ptr_size,
6396                    unsigned int encoding,
6397                    Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr, Dwarf *dbg)
6398 {
6399   char regnamebuf[REGNAMESZ];
6400
6401   puts ("\n   Program:");
6402   Dwarf_Word pc = vma_base;
6403   while (readp < endp)
6404     {
6405       unsigned int opcode = *readp++;
6406
6407       if (opcode < DW_CFA_advance_loc)
6408         /* Extended opcode.  */
6409         switch (opcode)
6410           {
6411             uint64_t op1;
6412             int64_t sop1;
6413             uint64_t op2;
6414             int64_t sop2;
6415
6416           case DW_CFA_nop:
6417             puts ("     nop");
6418             break;
6419           case DW_CFA_set_loc:
6420             if ((uint64_t) (endp - readp) < 1)
6421               goto invalid;
6422             readp = read_encoded (encoding, readp, endp, &op1, dbg);
6423             printf ("     set_loc %#" PRIx64 " to %#" PRIx64 "\n",
6424                     op1, pc = vma_base + op1);
6425             break;
6426           case DW_CFA_advance_loc1:
6427             if ((uint64_t) (endp - readp) < 1)
6428               goto invalid;
6429             printf ("     advance_loc1 %u to %#" PRIx64 "\n",
6430                     *readp, pc += *readp * code_align);
6431             ++readp;
6432             break;
6433           case DW_CFA_advance_loc2:
6434             if ((uint64_t) (endp - readp) < 2)
6435               goto invalid;
6436             op1 = read_2ubyte_unaligned_inc (dbg, readp);
6437             printf ("     advance_loc2 %" PRIu64 " to %#" PRIx64 "\n",
6438                     op1, pc += op1 * code_align);
6439             break;
6440           case DW_CFA_advance_loc4:
6441             if ((uint64_t) (endp - readp) < 4)
6442               goto invalid;
6443             op1 = read_4ubyte_unaligned_inc (dbg, readp);
6444             printf ("     advance_loc4 %" PRIu64 " to %#" PRIx64 "\n",
6445                     op1, pc += op1 * code_align);
6446             break;
6447           case DW_CFA_offset_extended:
6448             if ((uint64_t) (endp - readp) < 1)
6449               goto invalid;
6450             get_uleb128 (op1, readp, endp);
6451             if ((uint64_t) (endp - readp) < 1)
6452               goto invalid;
6453             get_uleb128 (op2, readp, endp);
6454             printf ("     offset_extended r%" PRIu64 " (%s) at cfa%+" PRId64
6455                     "\n",
6456                     op1, regname (ebl, op1, regnamebuf), op2 * data_align);
6457             break;
6458           case DW_CFA_restore_extended:
6459             if ((uint64_t) (endp - readp) < 1)
6460               goto invalid;
6461             get_uleb128 (op1, readp, endp);
6462             printf ("     restore_extended r%" PRIu64 " (%s)\n",
6463                     op1, regname (ebl, op1, regnamebuf));
6464             break;
6465           case DW_CFA_undefined:
6466             if ((uint64_t) (endp - readp) < 1)
6467               goto invalid;
6468             get_uleb128 (op1, readp, endp);
6469             printf ("     undefined r%" PRIu64 " (%s)\n", op1,
6470                     regname (ebl, op1, regnamebuf));
6471             break;
6472           case DW_CFA_same_value:
6473             if ((uint64_t) (endp - readp) < 1)
6474               goto invalid;
6475             get_uleb128 (op1, readp, endp);
6476             printf ("     same_value r%" PRIu64 " (%s)\n", op1,
6477                     regname (ebl, op1, regnamebuf));
6478             break;
6479           case DW_CFA_register:
6480             if ((uint64_t) (endp - readp) < 1)
6481               goto invalid;
6482             get_uleb128 (op1, readp, endp);
6483             if ((uint64_t) (endp - readp) < 1)
6484               goto invalid;
6485             get_uleb128 (op2, readp, endp);
6486             printf ("     register r%" PRIu64 " (%s) in r%" PRIu64 " (%s)\n",
6487                     op1, regname (ebl, op1, regnamebuf), op2,
6488                     regname (ebl, op2, regnamebuf));
6489             break;
6490           case DW_CFA_remember_state:
6491             puts ("     remember_state");
6492             break;
6493           case DW_CFA_restore_state:
6494             puts ("     restore_state");
6495             break;
6496           case DW_CFA_def_cfa:
6497             if ((uint64_t) (endp - readp) < 1)
6498               goto invalid;
6499             get_uleb128 (op1, readp, endp);
6500             if ((uint64_t) (endp - readp) < 1)
6501               goto invalid;
6502             get_uleb128 (op2, readp, endp);
6503             printf ("     def_cfa r%" PRIu64 " (%s) at offset %" PRIu64 "\n",
6504                     op1, regname (ebl, op1, regnamebuf), op2);
6505             break;
6506           case DW_CFA_def_cfa_register:
6507             if ((uint64_t) (endp - readp) < 1)
6508               goto invalid;
6509             get_uleb128 (op1, readp, endp);
6510             printf ("     def_cfa_register r%" PRIu64 " (%s)\n",
6511                     op1, regname (ebl, op1, regnamebuf));
6512             break;
6513           case DW_CFA_def_cfa_offset:
6514             if ((uint64_t) (endp - readp) < 1)
6515               goto invalid;
6516             get_uleb128 (op1, readp, endp);
6517             printf ("     def_cfa_offset %" PRIu64 "\n", op1);
6518             break;
6519           case DW_CFA_def_cfa_expression:
6520             if ((uint64_t) (endp - readp) < 1)
6521               goto invalid;
6522             get_uleb128 (op1, readp, endp);     /* Length of DW_FORM_block.  */
6523             printf ("     def_cfa_expression %" PRIu64 "\n", op1);
6524             if ((uint64_t) (endp - readp) < op1)
6525               {
6526             invalid:
6527                 fputs (_("         <INVALID DATA>\n"), stdout);
6528                 return;
6529               }
6530             print_ops (dwflmod, dbg, 10, 10, version, ptr_size, 0, NULL,
6531                        op1, readp);
6532             readp += op1;
6533             break;
6534           case DW_CFA_expression:
6535             if ((uint64_t) (endp - readp) < 1)
6536               goto invalid;
6537             get_uleb128 (op1, readp, endp);
6538             if ((uint64_t) (endp - readp) < 1)
6539               goto invalid;
6540             get_uleb128 (op2, readp, endp);     /* Length of DW_FORM_block.  */
6541             printf ("     expression r%" PRIu64 " (%s) \n",
6542                     op1, regname (ebl, op1, regnamebuf));
6543             if ((uint64_t) (endp - readp) < op2)
6544               goto invalid;
6545             print_ops (dwflmod, dbg, 10, 10, version, ptr_size, 0, NULL,
6546                        op2, readp);
6547             readp += op2;
6548             break;
6549           case DW_CFA_offset_extended_sf:
6550             if ((uint64_t) (endp - readp) < 1)
6551               goto invalid;
6552             get_uleb128 (op1, readp, endp);
6553             if ((uint64_t) (endp - readp) < 1)
6554               goto invalid;
6555             get_sleb128 (sop2, readp, endp);
6556             printf ("     offset_extended_sf r%" PRIu64 " (%s) at cfa%+"
6557                     PRId64 "\n",
6558                     op1, regname (ebl, op1, regnamebuf), sop2 * data_align);
6559             break;
6560           case DW_CFA_def_cfa_sf:
6561             if ((uint64_t) (endp - readp) < 1)
6562               goto invalid;
6563             get_uleb128 (op1, readp, endp);
6564             if ((uint64_t) (endp - readp) < 1)
6565               goto invalid;
6566             get_sleb128 (sop2, readp, endp);
6567             printf ("     def_cfa_sf r%" PRIu64 " (%s) at offset %" PRId64 "\n",
6568                     op1, regname (ebl, op1, regnamebuf), sop2 * data_align);
6569             break;
6570           case DW_CFA_def_cfa_offset_sf:
6571             if ((uint64_t) (endp - readp) < 1)
6572               goto invalid;
6573             get_sleb128 (sop1, readp, endp);
6574             printf ("     def_cfa_offset_sf %" PRId64 "\n", sop1 * data_align);
6575             break;
6576           case DW_CFA_val_offset:
6577             if ((uint64_t) (endp - readp) < 1)
6578               goto invalid;
6579             get_uleb128 (op1, readp, endp);
6580             if ((uint64_t) (endp - readp) < 1)
6581               goto invalid;
6582             get_uleb128 (op2, readp, endp);
6583             printf ("     val_offset %" PRIu64 " at offset %" PRIu64 "\n",
6584                     op1, op2 * data_align);
6585             break;
6586           case DW_CFA_val_offset_sf:
6587             if ((uint64_t) (endp - readp) < 1)
6588               goto invalid;
6589             get_uleb128 (op1, readp, endp);
6590             if ((uint64_t) (endp - readp) < 1)
6591               goto invalid;
6592             get_sleb128 (sop2, readp, endp);
6593             printf ("     val_offset_sf %" PRIu64 " at offset %" PRId64 "\n",
6594                     op1, sop2 * data_align);
6595             break;
6596           case DW_CFA_val_expression:
6597             if ((uint64_t) (endp - readp) < 1)
6598               goto invalid;
6599             get_uleb128 (op1, readp, endp);
6600             if ((uint64_t) (endp - readp) < 1)
6601               goto invalid;
6602             get_uleb128 (op2, readp, endp);     /* Length of DW_FORM_block.  */
6603             printf ("     val_expression r%" PRIu64 " (%s)\n",
6604                     op1, regname (ebl, op1, regnamebuf));
6605             if ((uint64_t) (endp - readp) < op2)
6606               goto invalid;
6607             print_ops (dwflmod, dbg, 10, 10, version, ptr_size, 0,
6608                        NULL, op2, readp);
6609             readp += op2;
6610             break;
6611           case DW_CFA_MIPS_advance_loc8:
6612             if ((uint64_t) (endp - readp) < 8)
6613               goto invalid;
6614             op1 = read_8ubyte_unaligned_inc (dbg, readp);
6615             printf ("     MIPS_advance_loc8 %" PRIu64 " to %#" PRIx64 "\n",
6616                     op1, pc += op1 * code_align);
6617             break;
6618           case DW_CFA_GNU_window_save:  /* DW_CFA_AARCH64_negate_ra_state  */
6619             if (ehdr->e_machine == EM_AARCH64)
6620               puts ("     AARCH64_negate_ra_state");
6621             else
6622               puts ("     GNU_window_save");
6623             break;
6624           case DW_CFA_GNU_args_size:
6625             if ((uint64_t) (endp - readp) < 1)
6626               goto invalid;
6627             get_uleb128 (op1, readp, endp);
6628             printf ("     args_size %" PRIu64 "\n", op1);
6629             break;
6630           default:
6631             printf ("     ??? (%u)\n", opcode);
6632             break;
6633           }
6634       else if (opcode < DW_CFA_offset)
6635         printf ("     advance_loc %u to %#" PRIx64 "\n",
6636                 opcode & 0x3f, pc += (opcode & 0x3f) * code_align);
6637       else if (opcode < DW_CFA_restore)
6638         {
6639           uint64_t offset;
6640           if ((uint64_t) (endp - readp) < 1)
6641             goto invalid;
6642           get_uleb128 (offset, readp, endp);
6643           printf ("     offset r%u (%s) at cfa%+" PRId64 "\n",
6644                   opcode & 0x3f, regname (ebl, opcode & 0x3f, regnamebuf),
6645                   offset * data_align);
6646         }
6647       else
6648         printf ("     restore r%u (%s)\n",
6649                 opcode & 0x3f, regname (ebl, opcode & 0x3f, regnamebuf));
6650     }
6651 }
6652
6653
6654 static unsigned int
6655 encoded_ptr_size (int encoding, unsigned int ptr_size)
6656 {
6657   switch (encoding & 7)
6658     {
6659     case DW_EH_PE_udata4:
6660       return 4;
6661     case DW_EH_PE_udata8:
6662       return 8;
6663     case 0:
6664       return ptr_size;
6665     }
6666
6667   fprintf (stderr, "Unsupported pointer encoding: %#x, "
6668            "assuming pointer size of %d.\n", encoding, ptr_size);
6669   return ptr_size;
6670 }
6671
6672
6673 static unsigned int
6674 print_encoding (unsigned int val)
6675 {
6676   switch (val & 0xf)
6677     {
6678     case DW_EH_PE_absptr:
6679       fputs ("absptr", stdout);
6680       break;
6681     case DW_EH_PE_uleb128:
6682       fputs ("uleb128", stdout);
6683       break;
6684     case DW_EH_PE_udata2:
6685       fputs ("udata2", stdout);
6686       break;
6687     case DW_EH_PE_udata4:
6688       fputs ("udata4", stdout);
6689       break;
6690     case DW_EH_PE_udata8:
6691       fputs ("udata8", stdout);
6692       break;
6693     case DW_EH_PE_sleb128:
6694       fputs ("sleb128", stdout);
6695       break;
6696     case DW_EH_PE_sdata2:
6697       fputs ("sdata2", stdout);
6698       break;
6699     case DW_EH_PE_sdata4:
6700       fputs ("sdata4", stdout);
6701       break;
6702     case DW_EH_PE_sdata8:
6703       fputs ("sdata8", stdout);
6704       break;
6705     default:
6706       /* We did not use any of the bits after all.  */
6707       return val;
6708     }
6709
6710   return val & ~0xf;
6711 }
6712
6713
6714 static unsigned int
6715 print_relinfo (unsigned int val)
6716 {
6717   switch (val & 0x70)
6718     {
6719     case DW_EH_PE_pcrel:
6720       fputs ("pcrel", stdout);
6721       break;
6722     case DW_EH_PE_textrel:
6723       fputs ("textrel", stdout);
6724       break;
6725     case DW_EH_PE_datarel:
6726       fputs ("datarel", stdout);
6727       break;
6728     case DW_EH_PE_funcrel:
6729       fputs ("funcrel", stdout);
6730       break;
6731     case DW_EH_PE_aligned:
6732       fputs ("aligned", stdout);
6733       break;
6734     default:
6735       return val;
6736     }
6737
6738   return val & ~0x70;
6739 }
6740
6741
6742 static void
6743 print_encoding_base (const char *pfx, unsigned int fde_encoding)
6744 {
6745   printf ("(%s", pfx);
6746
6747   if (fde_encoding == DW_EH_PE_omit)
6748     puts ("omit)");
6749   else
6750     {
6751       unsigned int w = fde_encoding;
6752
6753       w = print_encoding (w);
6754
6755       if (w & 0x70)
6756         {
6757           if (w != fde_encoding)
6758             fputc_unlocked (' ', stdout);
6759
6760           w = print_relinfo (w);
6761         }
6762
6763       if (w != 0)
6764         printf ("%s%x", w != fde_encoding ? " " : "", w);
6765
6766       puts (")");
6767     }
6768 }
6769
6770
6771 static void
6772 print_debug_frame_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
6773                            Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
6774 {
6775   size_t shstrndx;
6776   /* We know this call will succeed since it did in the caller.  */
6777   (void) elf_getshdrstrndx (ebl->elf, &shstrndx);
6778   const char *scnname = elf_strptr (ebl->elf, shstrndx, shdr->sh_name);
6779
6780   /* Needed if we find PC-relative addresses.  */
6781   GElf_Addr bias;
6782   if (dwfl_module_getelf (dwflmod, &bias) == NULL)
6783     {
6784       error (0, 0, _("cannot get ELF: %s"), dwfl_errmsg (-1));
6785       return;
6786     }
6787
6788   bool is_eh_frame = strcmp (scnname, ".eh_frame") == 0;
6789   Elf_Data *data = (is_eh_frame
6790                     ? elf_rawdata (scn, NULL)
6791                     : (dbg->sectiondata[IDX_debug_frame]
6792                        ?: elf_rawdata (scn, NULL)));
6793
6794   if (unlikely (data == NULL))
6795     {
6796       error (0, 0, _("cannot get %s content: %s"),
6797              scnname, elf_errmsg (-1));
6798       return;
6799     }
6800
6801   if (is_eh_frame)
6802     printf (_("\
6803 \nCall frame information section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
6804             elf_ndxscn (scn), scnname, (uint64_t) shdr->sh_offset);
6805   else
6806     printf (_("\
6807 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
6808             elf_ndxscn (scn), scnname, (uint64_t) shdr->sh_offset);
6809
6810   struct cieinfo
6811   {
6812     ptrdiff_t cie_offset;
6813     const char *augmentation;
6814     unsigned int code_alignment_factor;
6815     unsigned int data_alignment_factor;
6816     uint8_t address_size;
6817     uint8_t fde_encoding;
6818     uint8_t lsda_encoding;
6819     struct cieinfo *next;
6820   } *cies = NULL;
6821
6822   const unsigned char *readp = data->d_buf;
6823   const unsigned char *const dataend = ((unsigned char *) data->d_buf
6824                                         + data->d_size);
6825   while (readp < dataend)
6826     {
6827       if (unlikely (readp + 4 > dataend))
6828         {
6829         invalid_data:
6830           error (0, 0, _("invalid data in section [%zu] '%s'"),
6831                      elf_ndxscn (scn), scnname);
6832               return;
6833         }
6834
6835       /* At the beginning there must be a CIE.  There can be multiple,
6836          hence we test tis in a loop.  */
6837       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
6838
6839       Dwarf_Word unit_length = read_4ubyte_unaligned_inc (dbg, readp);
6840       unsigned int length = 4;
6841       if (unlikely (unit_length == 0xffffffff))
6842         {
6843           if (unlikely (readp + 8 > dataend))
6844             goto invalid_data;
6845
6846           unit_length = read_8ubyte_unaligned_inc (dbg, readp);
6847           length = 8;
6848         }
6849
6850       if (unlikely (unit_length == 0))
6851         {
6852           printf (_("\n [%6tx] Zero terminator\n"), offset);
6853           continue;
6854         }
6855
6856       Dwarf_Word maxsize = dataend - readp;
6857       if (unlikely (unit_length > maxsize))
6858         goto invalid_data;
6859
6860       unsigned int ptr_size = ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
6861
6862       ptrdiff_t start = readp - (unsigned char *) data->d_buf;
6863       const unsigned char *const cieend = readp + unit_length;
6864       if (unlikely (cieend > dataend))
6865         goto invalid_data;
6866
6867       Dwarf_Off cie_id;
6868       if (length == 4)
6869         {
6870           if (unlikely (cieend - readp < 4))
6871             goto invalid_data;
6872           cie_id = read_4ubyte_unaligned_inc (dbg, readp);
6873           if (!is_eh_frame && cie_id == DW_CIE_ID_32)
6874             cie_id = DW_CIE_ID_64;
6875         }
6876       else
6877         {
6878           if (unlikely (cieend - readp < 8))
6879             goto invalid_data;
6880           cie_id = read_8ubyte_unaligned_inc (dbg, readp);
6881         }
6882
6883       uint_fast8_t version = 2;
6884       unsigned int code_alignment_factor;
6885       int data_alignment_factor;
6886       unsigned int fde_encoding = 0;
6887       unsigned int lsda_encoding = 0;
6888       Dwarf_Word initial_location = 0;
6889       Dwarf_Word vma_base = 0;
6890
6891       if (cie_id == (is_eh_frame ? 0 : DW_CIE_ID_64))
6892         {
6893           if (unlikely (cieend - readp < 2))
6894             goto invalid_data;
6895           version = *readp++;
6896           const char *const augmentation = (const char *) readp;
6897           readp = memchr (readp, '\0', cieend - readp);
6898           if (unlikely (readp == NULL))
6899             goto invalid_data;
6900           ++readp;
6901
6902           uint_fast8_t segment_size = 0;
6903           if (version >= 4)
6904             {
6905               if (cieend - readp < 5)
6906                 goto invalid_data;
6907               ptr_size = *readp++;
6908               segment_size = *readp++;
6909             }
6910
6911           if (cieend - readp < 1)
6912             goto invalid_data;
6913           get_uleb128 (code_alignment_factor, readp, cieend);
6914           if (cieend - readp < 1)
6915             goto invalid_data;
6916           get_sleb128 (data_alignment_factor, readp, cieend);
6917
6918           /* In some variant for unwind data there is another field.  */
6919           if (strcmp (augmentation, "eh") == 0)
6920             readp += ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
6921
6922           unsigned int return_address_register;
6923           if (cieend - readp < 1)
6924             goto invalid_data;
6925           if (unlikely (version == 1))
6926             return_address_register = *readp++;
6927           else
6928             get_uleb128 (return_address_register, readp, cieend);
6929
6930           printf ("\n [%6tx] CIE length=%" PRIu64 "\n"
6931                   "   CIE_id:                   %" PRIu64 "\n"
6932                   "   version:                  %u\n"
6933                   "   augmentation:             \"%s\"\n",
6934                   offset, (uint64_t) unit_length, (uint64_t) cie_id,
6935                   version, augmentation);
6936           if (version >= 4)
6937             printf ("   address_size:             %u\n"
6938                     "   segment_size:             %u\n",
6939                     ptr_size, segment_size);
6940           printf ("   code_alignment_factor:    %u\n"
6941                   "   data_alignment_factor:    %d\n"
6942                   "   return_address_register:  %u\n",
6943                   code_alignment_factor,
6944                   data_alignment_factor, return_address_register);
6945
6946           if (augmentation[0] == 'z')
6947             {
6948               unsigned int augmentationlen;
6949               get_uleb128 (augmentationlen, readp, cieend);
6950
6951               if (augmentationlen > (size_t) (cieend - readp))
6952                 {
6953                   error (0, 0, _("invalid augmentation length"));
6954                   readp = cieend;
6955                   continue;
6956                 }
6957
6958               const char *hdr = "Augmentation data:";
6959               const char *cp = augmentation + 1;
6960               while (*cp != '\0' && cp < augmentation + augmentationlen + 1)
6961                 {
6962                   printf ("   %-26s%#x ", hdr, *readp);
6963                   hdr = "";
6964
6965                   if (*cp == 'R')
6966                     {
6967                       fde_encoding = *readp++;
6968                       print_encoding_base (_("FDE address encoding: "),
6969                                            fde_encoding);
6970                     }
6971                   else if (*cp == 'L')
6972                     {
6973                       lsda_encoding = *readp++;
6974                       print_encoding_base (_("LSDA pointer encoding: "),
6975                                            lsda_encoding);
6976                     }
6977                   else if (*cp == 'P')
6978                     {
6979                       /* Personality.  This field usually has a relocation
6980                          attached pointing to __gcc_personality_v0.  */
6981                       const unsigned char *startp = readp;
6982                       unsigned int encoding = *readp++;
6983                       uint64_t val = 0;
6984                       readp = read_encoded (encoding, readp,
6985                                             readp - 1 + augmentationlen,
6986                                             &val, dbg);
6987
6988                       while (++startp < readp)
6989                         printf ("%#x ", *startp);
6990
6991                       putchar ('(');
6992                       print_encoding (encoding);
6993                       putchar (' ');
6994                       switch (encoding & 0xf)
6995                         {
6996                         case DW_EH_PE_sleb128:
6997                         case DW_EH_PE_sdata2:
6998                         case DW_EH_PE_sdata4:
6999                           printf ("%" PRId64 ")\n", val);
7000                           break;
7001                         default:
7002                           printf ("%#" PRIx64 ")\n", val);
7003                           break;
7004                         }
7005                     }
7006                   else
7007                     printf ("(%x)\n", *readp++);
7008
7009                   ++cp;
7010                 }
7011             }
7012
7013           if (likely (ptr_size == 4 || ptr_size == 8))
7014             {
7015               struct cieinfo *newp = alloca (sizeof (*newp));
7016               newp->cie_offset = offset;
7017               newp->augmentation = augmentation;
7018               newp->fde_encoding = fde_encoding;
7019               newp->lsda_encoding = lsda_encoding;
7020               newp->address_size = ptr_size;
7021               newp->code_alignment_factor = code_alignment_factor;
7022               newp->data_alignment_factor = data_alignment_factor;
7023               newp->next = cies;
7024               cies = newp;
7025             }
7026         }
7027       else
7028         {
7029           struct cieinfo *cie = cies;
7030           while (cie != NULL)
7031             if (is_eh_frame
7032                 ? ((Dwarf_Off) start - cie_id) == (Dwarf_Off) cie->cie_offset
7033                 : cie_id == (Dwarf_Off) cie->cie_offset)
7034               break;
7035             else
7036               cie = cie->next;
7037           if (unlikely (cie == NULL))
7038             {
7039               puts ("invalid CIE reference in FDE");
7040               return;
7041             }
7042
7043           /* Initialize from CIE data.  */
7044           fde_encoding = cie->fde_encoding;
7045           lsda_encoding = cie->lsda_encoding;
7046           ptr_size = encoded_ptr_size (fde_encoding, cie->address_size);
7047           code_alignment_factor = cie->code_alignment_factor;
7048           data_alignment_factor = cie->data_alignment_factor;
7049
7050           const unsigned char *base = readp;
7051           // XXX There are sometimes relocations for this value
7052           initial_location = read_addr_unaligned_inc (ptr_size, dbg, readp);
7053           Dwarf_Word address_range
7054             = read_addr_unaligned_inc (ptr_size, dbg, readp);
7055
7056           /* pcrel for an FDE address is relative to the runtime
7057              address of the start_address field itself.  Sign extend
7058              if necessary to make sure the calculation is done on the
7059              full 64 bit address even when initial_location only holds
7060              the lower 32 bits.  */
7061           Dwarf_Addr pc_start = initial_location;
7062           if (ptr_size == 4)
7063             pc_start = (uint64_t) (int32_t) pc_start;
7064           if ((fde_encoding & 0x70) == DW_EH_PE_pcrel)
7065             pc_start += ((uint64_t) shdr->sh_addr
7066                          + (base - (const unsigned char *) data->d_buf)
7067                          - bias);
7068
7069           printf ("\n [%6tx] FDE length=%" PRIu64 " cie=[%6tx]\n"
7070                   "   CIE_pointer:              %" PRIu64 "\n"
7071                   "   initial_location:         ",
7072                   offset, (uint64_t) unit_length,
7073                   cie->cie_offset, (uint64_t) cie_id);
7074           print_dwarf_addr (dwflmod, cie->address_size,
7075                             pc_start, initial_location);
7076           if ((fde_encoding & 0x70) == DW_EH_PE_pcrel)
7077             {
7078               vma_base = (((uint64_t) shdr->sh_offset
7079                            + (base - (const unsigned char *) data->d_buf)
7080                            + (uint64_t) initial_location)
7081                           & (ptr_size == 4
7082                              ? UINT64_C (0xffffffff)
7083                              : UINT64_C (0xffffffffffffffff)));
7084               printf (_(" (offset: %#" PRIx64 ")"),
7085                       (uint64_t) vma_base);
7086             }
7087
7088           printf ("\n   address_range:            %#" PRIx64,
7089                   (uint64_t) address_range);
7090           if ((fde_encoding & 0x70) == DW_EH_PE_pcrel)
7091             printf (_(" (end offset: %#" PRIx64 ")"),
7092                     ((uint64_t) vma_base + (uint64_t) address_range)
7093                     & (ptr_size == 4
7094                        ? UINT64_C (0xffffffff)
7095                        : UINT64_C (0xffffffffffffffff)));
7096           putchar ('\n');
7097
7098           if (cie->augmentation[0] == 'z')
7099             {
7100               unsigned int augmentationlen;
7101               if (cieend - readp < 1)
7102                 goto invalid_data;
7103               get_uleb128 (augmentationlen, readp, cieend);
7104
7105               if (augmentationlen > (size_t) (cieend - readp))
7106                 {
7107                   error (0, 0, _("invalid augmentation length"));
7108                   readp = cieend;
7109                   continue;
7110                 }
7111
7112               if (augmentationlen > 0)
7113                 {
7114                   const char *hdr = "Augmentation data:";
7115                   const char *cp = cie->augmentation + 1;
7116                   unsigned int u = 0;
7117                   while (*cp != '\0'
7118                          && cp < cie->augmentation + augmentationlen + 1)
7119                     {
7120                       if (*cp == 'L')
7121                         {
7122                           uint64_t lsda_pointer;
7123                           const unsigned char *p
7124                             = read_encoded (lsda_encoding, &readp[u],
7125                                             &readp[augmentationlen],
7126                                             &lsda_pointer, dbg);
7127                           u = p - readp;
7128                           printf (_("\
7129    %-26sLSDA pointer: %#" PRIx64 "\n"),
7130                                   hdr, lsda_pointer);
7131                           hdr = "";
7132                         }
7133                       ++cp;
7134                     }
7135
7136                   while (u < augmentationlen)
7137                     {
7138                       printf ("   %-26s%#x\n", hdr, readp[u++]);
7139                       hdr = "";
7140                     }
7141                 }
7142
7143               readp += augmentationlen;
7144             }
7145         }
7146
7147       /* Handle the initialization instructions.  */
7148       if (ptr_size != 4 && ptr_size !=8)
7149         printf ("invalid CIE pointer size (%u), must be 4 or 8.\n", ptr_size);
7150       else
7151         print_cfa_program (readp, cieend, vma_base, code_alignment_factor,
7152                            data_alignment_factor, version, ptr_size,
7153                            fde_encoding, dwflmod, ebl, ehdr, dbg);
7154       readp = cieend;
7155     }
7156 }
7157
7158
7159 /* Returns the signedness (or false if it cannot be determined) and
7160    the byte size (or zero if it cannot be gotten) of the given DIE
7161    DW_AT_type attribute.  Uses dwarf_peel_type and dwarf_aggregate_size.  */
7162 static void
7163 die_type_sign_bytes (Dwarf_Die *die, bool *is_signed, int *bytes)
7164 {
7165   Dwarf_Attribute attr;
7166   Dwarf_Die type;
7167
7168   *bytes = 0;
7169   *is_signed = false;
7170
7171   if (dwarf_peel_type (dwarf_formref_die (dwarf_attr_integrate (die,
7172                                                                 DW_AT_type,
7173                                                                 &attr), &type),
7174                        &type) == 0)
7175     {
7176       Dwarf_Word val;
7177       *is_signed = (dwarf_formudata (dwarf_attr (&type, DW_AT_encoding,
7178                                                  &attr), &val) == 0
7179                     && (val == DW_ATE_signed || val == DW_ATE_signed_char));
7180
7181       if (dwarf_aggregate_size (&type, &val) == 0)
7182         *bytes = val;
7183     }
7184 }
7185
7186 struct attrcb_args
7187 {
7188   Dwfl_Module *dwflmod;
7189   Dwarf *dbg;
7190   Dwarf_Die *dies;
7191   int level;
7192   bool silent;
7193   bool is_split;
7194   unsigned int version;
7195   unsigned int addrsize;
7196   unsigned int offset_size;
7197   struct Dwarf_CU *cu;
7198 };
7199
7200
7201 static int
7202 attr_callback (Dwarf_Attribute *attrp, void *arg)
7203 {
7204   struct attrcb_args *cbargs = (struct attrcb_args *) arg;
7205   const int level = cbargs->level;
7206   Dwarf_Die *die = &cbargs->dies[level];
7207   bool is_split = cbargs->is_split;
7208
7209   unsigned int attr = dwarf_whatattr (attrp);
7210   if (unlikely (attr == 0))
7211     {
7212       if (!cbargs->silent)
7213         error (0, 0, _("DIE [%" PRIx64 "] "
7214                               "cannot get attribute code: %s"),
7215                dwarf_dieoffset (die), dwarf_errmsg (-1));
7216       return DWARF_CB_ABORT;
7217     }
7218
7219   unsigned int form = dwarf_whatform (attrp);
7220   if (unlikely (form == 0))
7221     {
7222       if (!cbargs->silent)
7223         error (0, 0, _("DIE [%" PRIx64 "] "
7224                               "cannot get attribute form: %s"),
7225                dwarf_dieoffset (die), dwarf_errmsg (-1));
7226       return DWARF_CB_ABORT;
7227     }
7228
7229   switch (form)
7230     {
7231     case DW_FORM_addr:
7232     case DW_FORM_addrx:
7233     case DW_FORM_addrx1:
7234     case DW_FORM_addrx2:
7235     case DW_FORM_addrx3:
7236     case DW_FORM_addrx4:
7237     case DW_FORM_GNU_addr_index:
7238       if (!cbargs->silent)
7239         {
7240           Dwarf_Addr addr;
7241           if (unlikely (dwarf_formaddr (attrp, &addr) != 0))
7242             {
7243             attrval_out:
7244               if (!cbargs->silent)
7245                 error (0, 0, _("DIE [%" PRIx64 "] "
7246                                       "cannot get attribute '%s' (%s) value: "
7247                                       "%s"),
7248                        dwarf_dieoffset (die),
7249                        dwarf_attr_name (attr),
7250                        dwarf_form_name (form),
7251                        dwarf_errmsg (-1));
7252               /* Don't ABORT, it might be other attributes can be resolved.  */
7253               return DWARF_CB_OK;
7254             }
7255           if (form != DW_FORM_addr )
7256             {
7257               Dwarf_Word word;
7258               if (dwarf_formudata (attrp, &word) != 0)
7259                 goto attrval_out;
7260               printf ("           %*s%-20s (%s) [%" PRIx64 "] ",
7261                       (int) (level * 2), "", dwarf_attr_name (attr),
7262                       dwarf_form_name (form), word);
7263             }
7264           else
7265             printf ("           %*s%-20s (%s) ",
7266                     (int) (level * 2), "", dwarf_attr_name (attr),
7267                     dwarf_form_name (form));
7268           print_dwarf_addr (cbargs->dwflmod, cbargs->addrsize, addr, addr);
7269           printf ("\n");
7270         }
7271       break;
7272
7273     case DW_FORM_indirect:
7274     case DW_FORM_strp:
7275     case DW_FORM_line_strp:
7276     case DW_FORM_strx:
7277     case DW_FORM_strx1:
7278     case DW_FORM_strx2:
7279     case DW_FORM_strx3:
7280     case DW_FORM_strx4:
7281     case DW_FORM_string:
7282     case DW_FORM_GNU_strp_alt:
7283     case DW_FORM_GNU_str_index:
7284       if (cbargs->silent)
7285         break;
7286       const char *str = dwarf_formstring (attrp);
7287       if (unlikely (str == NULL))
7288         goto attrval_out;
7289       printf ("           %*s%-20s (%s) \"%s\"\n",
7290               (int) (level * 2), "", dwarf_attr_name (attr),
7291               dwarf_form_name (form), str);
7292       break;
7293
7294     case DW_FORM_ref_addr:
7295     case DW_FORM_ref_udata:
7296     case DW_FORM_ref8:
7297     case DW_FORM_ref4:
7298     case DW_FORM_ref2:
7299     case DW_FORM_ref1:
7300     case DW_FORM_GNU_ref_alt:
7301     case DW_FORM_ref_sup4:
7302     case DW_FORM_ref_sup8:
7303       if (cbargs->silent)
7304         break;
7305       Dwarf_Die ref;
7306       if (unlikely (dwarf_formref_die (attrp, &ref) == NULL))
7307         goto attrval_out;
7308
7309       printf ("           %*s%-20s (%s) ",
7310               (int) (level * 2), "", dwarf_attr_name (attr),
7311               dwarf_form_name (form));
7312       if (is_split)
7313         printf ("{%6" PRIxMAX "}\n", (uintmax_t) dwarf_dieoffset (&ref));
7314       else
7315         printf ("[%6" PRIxMAX "]\n", (uintmax_t) dwarf_dieoffset (&ref));
7316       break;
7317
7318     case DW_FORM_ref_sig8:
7319       if (cbargs->silent)
7320         break;
7321       printf ("           %*s%-20s (%s) {%6" PRIx64 "}\n",
7322               (int) (level * 2), "", dwarf_attr_name (attr),
7323               dwarf_form_name (form),
7324               (uint64_t) read_8ubyte_unaligned (attrp->cu->dbg, attrp->valp));
7325       break;
7326
7327     case DW_FORM_sec_offset:
7328     case DW_FORM_rnglistx:
7329     case DW_FORM_loclistx:
7330     case DW_FORM_implicit_const:
7331     case DW_FORM_udata:
7332     case DW_FORM_sdata:
7333     case DW_FORM_data8: /* Note no data16 here, we see that as block. */
7334     case DW_FORM_data4:
7335     case DW_FORM_data2:
7336     case DW_FORM_data1:;
7337       Dwarf_Word num;
7338       if (unlikely (dwarf_formudata (attrp, &num) != 0))
7339         goto attrval_out;
7340
7341       const char *valuestr = NULL;
7342       bool as_hex_id = false;
7343       switch (attr)
7344         {
7345           /* This case can take either a constant or a loclistptr.  */
7346         case DW_AT_data_member_location:
7347           if (form != DW_FORM_sec_offset
7348               && (cbargs->version >= 4
7349                   || (form != DW_FORM_data4 && form != DW_FORM_data8)))
7350             {
7351               if (!cbargs->silent)
7352                 printf ("           %*s%-20s (%s) %" PRIuMAX "\n",
7353                         (int) (level * 2), "", dwarf_attr_name (attr),
7354                         dwarf_form_name (form), (uintmax_t) num);
7355               return DWARF_CB_OK;
7356             }
7357           FALLTHROUGH;
7358
7359         /* These cases always take a loclist[ptr] and no constant. */
7360         case DW_AT_location:
7361         case DW_AT_data_location:
7362         case DW_AT_vtable_elem_location:
7363         case DW_AT_string_length:
7364         case DW_AT_use_location:
7365         case DW_AT_frame_base:
7366         case DW_AT_return_addr:
7367         case DW_AT_static_link:
7368         case DW_AT_segment:
7369         case DW_AT_GNU_call_site_value:
7370         case DW_AT_GNU_call_site_data_value:
7371         case DW_AT_GNU_call_site_target:
7372         case DW_AT_GNU_call_site_target_clobbered:
7373         case DW_AT_GNU_locviews:
7374           {
7375             bool nlpt;
7376             if (cbargs->cu->version < 5)
7377               {
7378                 if (! cbargs->is_split)
7379                   {
7380                     nlpt = notice_listptr (section_loc, &known_locsptr,
7381                                            cbargs->addrsize,
7382                                            cbargs->offset_size,
7383                                            cbargs->cu, num, attr);
7384                   }
7385                 else
7386                   nlpt = true;
7387               }
7388             else
7389               {
7390                 /* Only register for a real section offset.  Otherwise
7391                    it is a DW_FORM_loclistx which is just an index
7392                    number and we should already have registered the
7393                    section offset for the index when we saw the
7394                    DW_AT_loclists_base CU attribute.  */
7395                 if (form == DW_FORM_sec_offset)
7396                   nlpt = notice_listptr (section_loc, &known_loclistsptr,
7397                                          cbargs->addrsize, cbargs->offset_size,
7398                                          cbargs->cu, num, attr);
7399                 else
7400                   nlpt = true;
7401
7402               }
7403
7404             if (!cbargs->silent)
7405               {
7406                 if (cbargs->cu->version < 5 || form == DW_FORM_sec_offset)
7407                   printf ("           %*s%-20s (%s) location list [%6"
7408                           PRIxMAX "]%s\n",
7409                           (int) (level * 2), "", dwarf_attr_name (attr),
7410                           dwarf_form_name (form), (uintmax_t) num,
7411                           nlpt ? "" : " <WARNING offset too big>");
7412                 else
7413                   printf ("           %*s%-20s (%s) location index [%6"
7414                           PRIxMAX "]\n",
7415                           (int) (level * 2), "", dwarf_attr_name (attr),
7416                           dwarf_form_name (form), (uintmax_t) num);
7417               }
7418           }
7419           return DWARF_CB_OK;
7420
7421         case DW_AT_loclists_base:
7422           {
7423             bool nlpt = notice_listptr (section_loc, &known_loclistsptr,
7424                                         cbargs->addrsize, cbargs->offset_size,
7425                                         cbargs->cu, num, attr);
7426
7427             if (!cbargs->silent)
7428               printf ("           %*s%-20s (%s) location list [%6" PRIxMAX "]%s\n",
7429                       (int) (level * 2), "", dwarf_attr_name (attr),
7430                       dwarf_form_name (form), (uintmax_t) num,
7431                       nlpt ? "" : " <WARNING offset too big>");
7432           }
7433           return DWARF_CB_OK;
7434
7435         case DW_AT_ranges:
7436         case DW_AT_start_scope:
7437           {
7438             bool nlpt;
7439             if (cbargs->cu->version < 5)
7440               nlpt = notice_listptr (section_ranges, &known_rangelistptr,
7441                                      cbargs->addrsize, cbargs->offset_size,
7442                                      cbargs->cu, num, attr);
7443             else
7444               {
7445                 /* Only register for a real section offset.  Otherwise
7446                    it is a DW_FORM_rangelistx which is just an index
7447                    number and we should already have registered the
7448                    section offset for the index when we saw the
7449                    DW_AT_rnglists_base CU attribute.  */
7450                 if (form == DW_FORM_sec_offset)
7451                   nlpt = notice_listptr (section_ranges, &known_rnglistptr,
7452                                          cbargs->addrsize, cbargs->offset_size,
7453                                          cbargs->cu, num, attr);
7454                 else
7455                   nlpt = true;
7456               }
7457
7458             if (!cbargs->silent)
7459               {
7460                 if (cbargs->cu->version < 5 || form == DW_FORM_sec_offset)
7461                   printf ("           %*s%-20s (%s) range list [%6"
7462                           PRIxMAX "]%s\n",
7463                           (int) (level * 2), "", dwarf_attr_name (attr),
7464                           dwarf_form_name (form), (uintmax_t) num,
7465                           nlpt ? "" : " <WARNING offset too big>");
7466                 else
7467                   printf ("           %*s%-20s (%s) range index [%6"
7468                           PRIxMAX "]\n",
7469                           (int) (level * 2), "", dwarf_attr_name (attr),
7470                           dwarf_form_name (form), (uintmax_t) num);
7471               }
7472           }
7473           return DWARF_CB_OK;
7474
7475         case DW_AT_rnglists_base:
7476           {
7477             bool nlpt = notice_listptr (section_ranges, &known_rnglistptr,
7478                                         cbargs->addrsize, cbargs->offset_size,
7479                                         cbargs->cu, num, attr);
7480             if (!cbargs->silent)
7481               printf ("           %*s%-20s (%s) range list [%6"
7482                       PRIxMAX "]%s\n",
7483                       (int) (level * 2), "", dwarf_attr_name (attr),
7484                       dwarf_form_name (form), (uintmax_t) num,
7485                       nlpt ? "" : " <WARNING offset too big>");
7486           }
7487           return DWARF_CB_OK;
7488
7489         case DW_AT_addr_base:
7490         case DW_AT_GNU_addr_base:
7491           {
7492             bool addrbase = notice_listptr (section_addr, &known_addrbases,
7493                                             cbargs->addrsize,
7494                                             cbargs->offset_size,
7495                                             cbargs->cu, num, attr);
7496             if (!cbargs->silent)
7497               printf ("           %*s%-20s (%s) address base [%6"
7498                       PRIxMAX "]%s\n",
7499                       (int) (level * 2), "", dwarf_attr_name (attr),
7500                       dwarf_form_name (form), (uintmax_t) num,
7501                       addrbase ? "" : " <WARNING offset too big>");
7502           }
7503           return DWARF_CB_OK;
7504
7505         case DW_AT_str_offsets_base:
7506           {
7507             bool stroffbase = notice_listptr (section_str, &known_stroffbases,
7508                                               cbargs->addrsize,
7509                                               cbargs->offset_size,
7510                                               cbargs->cu, num, attr);
7511             if (!cbargs->silent)
7512               printf ("           %*s%-20s (%s) str offsets base [%6"
7513                       PRIxMAX "]%s\n",
7514                       (int) (level * 2), "", dwarf_attr_name (attr),
7515                       dwarf_form_name (form), (uintmax_t) num,
7516                       stroffbase ? "" : " <WARNING offset too big>");
7517           }
7518           return DWARF_CB_OK;
7519
7520         case DW_AT_language:
7521           valuestr = dwarf_lang_name (num);
7522           break;
7523         case DW_AT_encoding:
7524           valuestr = dwarf_encoding_name (num);
7525           break;
7526         case DW_AT_accessibility:
7527           valuestr = dwarf_access_name (num);
7528           break;
7529         case DW_AT_defaulted:
7530           valuestr = dwarf_defaulted_name (num);
7531           break;
7532         case DW_AT_visibility:
7533           valuestr = dwarf_visibility_name (num);
7534           break;
7535         case DW_AT_virtuality:
7536           valuestr = dwarf_virtuality_name (num);
7537           break;
7538         case DW_AT_identifier_case:
7539           valuestr = dwarf_identifier_case_name (num);
7540           break;
7541         case DW_AT_calling_convention:
7542           valuestr = dwarf_calling_convention_name (num);
7543           break;
7544         case DW_AT_inline:
7545           valuestr = dwarf_inline_name (num);
7546           break;
7547         case DW_AT_ordering:
7548           valuestr = dwarf_ordering_name (num);
7549           break;
7550         case DW_AT_decl_file:
7551         case DW_AT_call_file:
7552           {
7553             if (cbargs->silent)
7554               break;
7555
7556             /* Try to get the actual file, the current interface only
7557                gives us full paths, but we only want to show the file
7558                name for now.  */
7559             Dwarf_Die cudie;
7560             if (dwarf_cu_die (cbargs->cu, &cudie,
7561                               NULL, NULL, NULL, NULL, NULL, NULL) != NULL)
7562               {
7563                 Dwarf_Files *files;
7564                 size_t nfiles;
7565                 if (dwarf_getsrcfiles (&cudie, &files, &nfiles) == 0)
7566                   {
7567                     valuestr = dwarf_filesrc (files, num, NULL, NULL);
7568                     if (valuestr != NULL)
7569                       {
7570                         char *filename = strrchr (valuestr, '/');
7571                         if (filename != NULL)
7572                           valuestr = filename + 1;
7573                       }
7574                     else
7575                       error (0, 0, _("invalid file (%" PRId64 "): %s"),
7576                              num, dwarf_errmsg (-1));
7577                   }
7578                 else
7579                   error (0, 0, _("no srcfiles for CU [%" PRIx64 "]"),
7580                          dwarf_dieoffset (&cudie));
7581               }
7582             else
7583              error (0, 0, _("couldn't get DWARF CU: %s"),
7584                     dwarf_errmsg (-1));
7585             if (valuestr == NULL)
7586               valuestr = "???";
7587           }
7588           break;
7589         case DW_AT_GNU_dwo_id:
7590           as_hex_id = true;
7591           break;
7592
7593         default:
7594           /* Nothing.  */
7595           break;
7596         }
7597
7598       if (cbargs->silent)
7599         break;
7600
7601       /* When highpc is in constant form it is relative to lowpc.
7602          In that case also show the address.  */
7603       Dwarf_Addr highpc;
7604       if (attr == DW_AT_high_pc && dwarf_highpc (die, &highpc) == 0)
7605         {
7606           printf ("           %*s%-20s (%s) %" PRIuMAX " (",
7607                   (int) (level * 2), "", dwarf_attr_name (attr),
7608                   dwarf_form_name (form), (uintmax_t) num);
7609           print_dwarf_addr (cbargs->dwflmod, cbargs->addrsize, highpc, highpc);
7610           printf (")\n");
7611         }
7612       else
7613         {
7614           if (as_hex_id)
7615             {
7616               printf ("           %*s%-20s (%s) 0x%.16" PRIx64 "\n",
7617                       (int) (level * 2), "", dwarf_attr_name (attr),
7618                       dwarf_form_name (form), num);
7619             }
7620           else
7621             {
7622               Dwarf_Sword snum = 0;
7623               bool is_signed;
7624               int bytes = 0;
7625               if (attr == DW_AT_const_value)
7626                 die_type_sign_bytes (die, &is_signed, &bytes);
7627               else
7628                 is_signed = (form == DW_FORM_sdata
7629                              || form == DW_FORM_implicit_const);
7630
7631               if (is_signed)
7632                 if (unlikely (dwarf_formsdata (attrp, &snum) != 0))
7633                   goto attrval_out;
7634
7635               if (valuestr == NULL)
7636                 {
7637                   printf ("           %*s%-20s (%s) ",
7638                           (int) (level * 2), "", dwarf_attr_name (attr),
7639                           dwarf_form_name (form));
7640                 }
7641               else
7642                 {
7643                   printf ("           %*s%-20s (%s) %s (",
7644                           (int) (level * 2), "", dwarf_attr_name (attr),
7645                           dwarf_form_name (form), valuestr);
7646                 }
7647
7648               switch (bytes)
7649                 {
7650                 case 1:
7651                   if (is_signed)
7652                     printf ("%" PRId8, (int8_t) snum);
7653                   else
7654                     printf ("%" PRIu8, (uint8_t) num);
7655                   break;
7656
7657                 case 2:
7658                   if (is_signed)
7659                     printf ("%" PRId16, (int16_t) snum);
7660                   else
7661                     printf ("%" PRIu16, (uint16_t) num);
7662                   break;
7663
7664                 case 4:
7665                   if (is_signed)
7666                     printf ("%" PRId32, (int32_t) snum);
7667                   else
7668                     printf ("%" PRIu32, (uint32_t) num);
7669                   break;
7670
7671                 case 8:
7672                   if (is_signed)
7673                     printf ("%" PRId64, (int64_t) snum);
7674                   else
7675                     printf ("%" PRIu64, (uint64_t) num);
7676                   break;
7677
7678                 default:
7679                   if (is_signed)
7680                     printf ("%" PRIdMAX, (intmax_t) snum);
7681                   else
7682                     printf ("%" PRIuMAX, (uintmax_t) num);
7683                   break;
7684                 }
7685
7686               /* Make clear if we switched from a signed encoding to
7687                  an unsigned value.  */
7688               if (attr == DW_AT_const_value
7689                   && (form == DW_FORM_sdata || form == DW_FORM_implicit_const)
7690                   && !is_signed)
7691                 printf (" (%" PRIdMAX ")", (intmax_t) num);
7692
7693               if (valuestr == NULL)
7694                 printf ("\n");
7695               else
7696                 printf (")\n");
7697             }
7698         }
7699       break;
7700
7701     case DW_FORM_flag:
7702       if (cbargs->silent)
7703         break;
7704       bool flag;
7705       if (unlikely (dwarf_formflag (attrp, &flag) != 0))
7706         goto attrval_out;
7707
7708       printf ("           %*s%-20s (%s) %s\n",
7709               (int) (level * 2), "", dwarf_attr_name (attr),
7710               dwarf_form_name (form), flag ? yes_str : no_str);
7711       break;
7712
7713     case DW_FORM_flag_present:
7714       if (cbargs->silent)
7715         break;
7716       printf ("           %*s%-20s (%s) %s\n",
7717               (int) (level * 2), "", dwarf_attr_name (attr),
7718               dwarf_form_name (form), yes_str);
7719       break;
7720
7721     case DW_FORM_exprloc:
7722     case DW_FORM_block4:
7723     case DW_FORM_block2:
7724     case DW_FORM_block1:
7725     case DW_FORM_block:
7726     case DW_FORM_data16: /* DWARF5 calls this a constant class.  */
7727       if (cbargs->silent)
7728         break;
7729       Dwarf_Block block;
7730       if (unlikely (dwarf_formblock (attrp, &block) != 0))
7731         goto attrval_out;
7732
7733       printf ("           %*s%-20s (%s) ",
7734               (int) (level * 2), "", dwarf_attr_name (attr),
7735               dwarf_form_name (form));
7736
7737       switch (attr)
7738         {
7739         default:
7740           if (form != DW_FORM_exprloc)
7741             {
7742               print_block (block.length, block.data);
7743               break;
7744             }
7745           FALLTHROUGH;
7746
7747         case DW_AT_location:
7748         case DW_AT_data_location:
7749         case DW_AT_data_member_location:
7750         case DW_AT_vtable_elem_location:
7751         case DW_AT_string_length:
7752         case DW_AT_use_location:
7753         case DW_AT_frame_base:
7754         case DW_AT_return_addr:
7755         case DW_AT_static_link:
7756         case DW_AT_allocated:
7757         case DW_AT_associated:
7758         case DW_AT_bit_size:
7759         case DW_AT_bit_offset:
7760         case DW_AT_bit_stride:
7761         case DW_AT_byte_size:
7762         case DW_AT_byte_stride:
7763         case DW_AT_count:
7764         case DW_AT_lower_bound:
7765         case DW_AT_upper_bound:
7766         case DW_AT_GNU_call_site_value:
7767         case DW_AT_GNU_call_site_data_value:
7768         case DW_AT_GNU_call_site_target:
7769         case DW_AT_GNU_call_site_target_clobbered:
7770           if (form == DW_FORM_exprloc
7771               || (form != DW_FORM_data16
7772                   && attrp->cu->version < 4)) /* blocks were expressions.  */
7773             {
7774               putchar ('\n');
7775               print_ops (cbargs->dwflmod, cbargs->dbg,
7776                          12 + level * 2, 12 + level * 2,
7777                          cbargs->version, cbargs->addrsize, cbargs->offset_size,
7778                          attrp->cu, block.length, block.data);
7779             }
7780           else
7781             print_block (block.length, block.data);
7782           break;
7783
7784         case DW_AT_discr_list:
7785           if (block.length == 0)
7786             puts ("<default>");
7787           else if (form != DW_FORM_data16)
7788             {
7789               const unsigned char *readp = block.data;
7790               const unsigned char *readendp = readp + block.length;
7791
7792               /* See if we are dealing with a signed or unsigned
7793                  values.  If the parent of this variant DIE is a
7794                  variant_part then it will either have a discriminant
7795                  which points to the member which type is the
7796                  discriminant type.  Or the variant_part itself has a
7797                  type representing the discriminant.  */
7798               bool is_signed = false;
7799               if (level > 0)
7800                 {
7801                   Dwarf_Die *parent = &cbargs->dies[level - 1];
7802                   if (dwarf_tag (die) == DW_TAG_variant
7803                       && dwarf_tag (parent) == DW_TAG_variant_part)
7804                     {
7805                       Dwarf_Die member;
7806                       Dwarf_Attribute discr_attr;
7807                       int bytes;
7808                       if (dwarf_formref_die (dwarf_attr (parent,
7809                                                          DW_AT_discr,
7810                                                          &discr_attr),
7811                                              &member) != NULL)
7812                         die_type_sign_bytes (&member, &is_signed, &bytes);
7813                       else
7814                         die_type_sign_bytes (parent, &is_signed, &bytes);
7815                     }
7816                 }
7817               while (readp < readendp)
7818                 {
7819                   int d = (int) *readp++;
7820                   printf ("%s ", dwarf_discr_list_name (d));
7821                   if (readp >= readendp)
7822                     goto attrval_out;
7823
7824                   Dwarf_Word val;
7825                   Dwarf_Sword sval;
7826                   if (d == DW_DSC_label)
7827                     {
7828                       if (is_signed)
7829                         {
7830                           get_sleb128 (sval, readp, readendp);
7831                           printf ("%" PRId64 "", sval);
7832                         }
7833                       else
7834                         {
7835                           get_uleb128 (val, readp, readendp);
7836                           printf ("%" PRIu64 "", val);
7837                         }
7838                     }
7839                   else if (d == DW_DSC_range)
7840                     {
7841                       if (is_signed)
7842                         {
7843                           get_sleb128 (sval, readp, readendp);
7844                           printf ("%" PRId64 "..", sval);
7845                           if (readp >= readendp)
7846                             goto attrval_out;
7847                           get_sleb128 (sval, readp, readendp);
7848                           printf ("%" PRId64 "", sval);
7849                         }
7850                       else
7851                         {
7852                           get_uleb128 (val, readp, readendp);
7853                           printf ("%" PRIu64 "..", val);
7854                           if (readp >= readendp)
7855                             goto attrval_out;
7856                           get_uleb128 (val, readp, readendp);
7857                           printf ("%" PRIu64 "", val);
7858                         }
7859                     }
7860                   else
7861                     {
7862                       print_block (readendp - readp, readp);
7863                       break;
7864                     }
7865                   if (readp < readendp)
7866                     printf (", ");
7867                 }
7868               putchar ('\n');
7869             }
7870           else
7871             print_block (block.length, block.data);
7872           break;
7873         }
7874       break;
7875
7876     default:
7877       if (cbargs->silent)
7878         break;
7879       printf ("           %*s%-20s (%s) ???\n",
7880               (int) (level * 2), "", dwarf_attr_name (attr),
7881               dwarf_form_name (form));
7882       break;
7883     }
7884
7885   return DWARF_CB_OK;
7886 }
7887
7888 static void
7889 print_debug_units (Dwfl_Module *dwflmod,
7890                    Ebl *ebl, GElf_Ehdr *ehdr __attribute__ ((unused)),
7891                    Elf_Scn *scn, GElf_Shdr *shdr,
7892                    Dwarf *dbg, bool debug_types)
7893 {
7894   const bool silent = !(print_debug_sections & section_info) && !debug_types;
7895   const char *secname = section_name (ebl, shdr);
7896
7897   if (!silent)
7898     printf (_("\
7899 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n [Offset]\n"),
7900             elf_ndxscn (scn), secname, (uint64_t) shdr->sh_offset);
7901
7902   /* If the section is empty we don't have to do anything.  */
7903   if (!silent && shdr->sh_size == 0)
7904     return;
7905
7906   int maxdies = 20;
7907   Dwarf_Die *dies = xmalloc (maxdies * sizeof (Dwarf_Die));
7908
7909   /* New compilation unit.  */
7910   Dwarf_Half version;
7911
7912   Dwarf_Die result;
7913   Dwarf_Off abbroffset;
7914   uint8_t addrsize;
7915   uint8_t offsize;
7916   uint64_t unit_id;
7917   Dwarf_Off subdie_off;
7918
7919   int unit_res;
7920   Dwarf_CU *cu;
7921   Dwarf_CU cu_mem;
7922   uint8_t unit_type;
7923   Dwarf_Die cudie;
7924
7925   /* We cheat a little because we want to see only the CUs from .debug_info
7926      or .debug_types.  We know the Dwarf_CU struct layout.  Set it up at
7927      the end of .debug_info if we want .debug_types only.  Check the returned
7928      Dwarf_CU is still in the expected section.  */
7929   if (debug_types)
7930     {
7931       cu_mem.dbg = dbg;
7932       cu_mem.end = dbg->sectiondata[IDX_debug_info]->d_size;
7933       cu_mem.sec_idx = IDX_debug_info;
7934       cu = &cu_mem;
7935     }
7936   else
7937     cu = NULL;
7938
7939  next_cu:
7940   unit_res = dwarf_get_units (dbg, cu, &cu, &version, &unit_type,
7941                               &cudie, NULL);
7942   if (unit_res == 1)
7943     goto do_return;
7944
7945   if (unit_res == -1)
7946     {
7947       if (!silent)
7948         error (0, 0, _("cannot get next unit: %s"), dwarf_errmsg (-1));
7949       goto do_return;
7950     }
7951
7952   if (cu->sec_idx != (size_t) (debug_types ? IDX_debug_types : IDX_debug_info))
7953     goto do_return;
7954
7955   dwarf_cu_die (cu, &result, NULL, &abbroffset, &addrsize, &offsize,
7956                 &unit_id, &subdie_off);
7957
7958   if (!silent)
7959     {
7960       Dwarf_Off offset = cu->start;
7961       if (debug_types && version < 5)
7962         {
7963           Dwarf_Die typedie;
7964           Dwarf_Off dieoffset;
7965           dieoffset = dwarf_dieoffset (dwarf_offdie_types (dbg, cu->start
7966                                                            + subdie_off,
7967                                                            &typedie));
7968           printf (_(" Type unit at offset %" PRIu64 ":\n"
7969                            " Version: %" PRIu16
7970                            ", Abbreviation section offset: %" PRIu64
7971                            ", Address size: %" PRIu8
7972                            ", Offset size: %" PRIu8
7973                            "\n Type signature: %#" PRIx64
7974                            ", Type offset: %#" PRIx64 " [%" PRIx64 "]\n"),
7975                   (uint64_t) offset, version, abbroffset, addrsize, offsize,
7976                   unit_id, (uint64_t) subdie_off, dieoffset);
7977         }
7978       else
7979         {
7980           printf (_(" Compilation unit at offset %" PRIu64 ":\n"
7981                            " Version: %" PRIu16
7982                            ", Abbreviation section offset: %" PRIu64
7983                            ", Address size: %" PRIu8
7984                            ", Offset size: %" PRIu8 "\n"),
7985                   (uint64_t) offset, version, abbroffset, addrsize, offsize);
7986
7987           if (version >= 5 || (unit_type != DW_UT_compile
7988                                && unit_type != DW_UT_partial))
7989             {
7990               printf (_(" Unit type: %s (%" PRIu8 ")"),
7991                                dwarf_unit_name (unit_type), unit_type);
7992               if (unit_type == DW_UT_type
7993                   || unit_type == DW_UT_skeleton
7994                   || unit_type == DW_UT_split_compile
7995                   || unit_type == DW_UT_split_type)
7996                 printf (", Unit id: 0x%.16" PRIx64 "", unit_id);
7997               if (unit_type == DW_UT_type
7998                   || unit_type == DW_UT_split_type)
7999                 {
8000                   Dwarf_Die typedie;
8001                   Dwarf_Off dieoffset;
8002                   dwarf_cu_info (cu, NULL, NULL, NULL, &typedie,
8003                                  NULL, NULL, NULL);
8004                   dieoffset = dwarf_dieoffset (&typedie);
8005                   printf (", Unit DIE off: %#" PRIx64 " [%" PRIx64 "]",
8006                           subdie_off, dieoffset);
8007                 }
8008               printf ("\n");
8009             }
8010         }
8011     }
8012
8013   if (version < 2 || version > 5
8014       || unit_type < DW_UT_compile || unit_type > DW_UT_split_type)
8015     {
8016       if (!silent)
8017         error (0, 0, _("unknown version (%d) or unit type (%d)"),
8018                version, unit_type);
8019       goto next_cu;
8020     }
8021
8022   struct attrcb_args args =
8023     {
8024       .dwflmod = dwflmod,
8025       .silent = silent,
8026       .version = version,
8027       .addrsize = addrsize,
8028       .offset_size = offsize
8029     };
8030
8031   bool is_split = false;
8032   int level = 0;
8033   dies[0] = cudie;
8034   args.cu = dies[0].cu;
8035   args.dbg = dbg;
8036   args.is_split = is_split;
8037
8038   /* We might return here again for the split CU subdie.  */
8039   do_cu:
8040   do
8041     {
8042       Dwarf_Off offset = dwarf_dieoffset (&dies[level]);
8043       if (unlikely (offset == (Dwarf_Off) -1))
8044         {
8045           if (!silent)
8046             error (0, 0, _("cannot get DIE offset: %s"),
8047                    dwarf_errmsg (-1));
8048           goto do_return;
8049         }
8050
8051       int tag = dwarf_tag (&dies[level]);
8052       if (unlikely (tag == DW_TAG_invalid))
8053         {
8054           if (!silent)
8055             error (0, 0, _("cannot get tag of DIE at offset [%" PRIx64
8056                                   "] in section '%s': %s"),
8057                    (uint64_t) offset, secname, dwarf_errmsg (-1));
8058           goto do_return;
8059         }
8060
8061       if (!silent)
8062         {
8063           unsigned int code = dwarf_getabbrevcode (dies[level].abbrev);
8064           if (is_split)
8065             printf (" {%6" PRIx64 "}  ", (uint64_t) offset);
8066           else
8067             printf (" [%6" PRIx64 "]  ", (uint64_t) offset);
8068           printf ("%*s%-20s abbrev: %u\n", (int) (level * 2), "",
8069                   dwarf_tag_name (tag), code);
8070         }
8071
8072       /* Print the attribute values.  */
8073       args.level = level;
8074       args.dies = dies;
8075       (void) dwarf_getattrs (&dies[level], attr_callback, &args, 0);
8076
8077       /* Make room for the next level's DIE.  */
8078       if (level + 1 == maxdies)
8079         dies = xrealloc (dies, (maxdies += 10) * sizeof (Dwarf_Die));
8080
8081       int res = dwarf_child (&dies[level], &dies[level + 1]);
8082       if (res > 0)
8083         {
8084           while ((res = dwarf_siblingof (&dies[level], &dies[level])) == 1)
8085             if (level-- == 0)
8086               break;
8087
8088           if (unlikely (res == -1))
8089             {
8090               if (!silent)
8091                 error (0, 0, _("cannot get next DIE: %s\n"),
8092                        dwarf_errmsg (-1));
8093               goto do_return;
8094             }
8095         }
8096       else if (unlikely (res < 0))
8097         {
8098           if (!silent)
8099             error (0, 0, _("cannot get next DIE: %s"),
8100                    dwarf_errmsg (-1));
8101           goto do_return;
8102         }
8103       else
8104         ++level;
8105     }
8106   while (level >= 0);
8107
8108   /* We might want to show the split compile unit if this was a skeleton.
8109      We need to scan it if we are requesting printing .debug_ranges for
8110      DWARF4 since GNU DebugFission uses "offsets" into the main ranges
8111      section.  */
8112   if (unit_type == DW_UT_skeleton
8113       && ((!silent && show_split_units)
8114           || (version < 5 && (print_debug_sections & section_ranges) != 0)))
8115     {
8116       Dwarf_Die subdie;
8117       if (dwarf_cu_info (cu, NULL, NULL, NULL, &subdie, NULL, NULL, NULL) != 0
8118           || dwarf_tag (&subdie) == DW_TAG_invalid)
8119         {
8120           if (!silent)
8121             {
8122               Dwarf_Attribute dwo_at;
8123               const char *dwo_name =
8124                 (dwarf_formstring (dwarf_attr (&cudie, DW_AT_dwo_name,
8125                                                &dwo_at))
8126                  ?: (dwarf_formstring (dwarf_attr (&cudie, DW_AT_GNU_dwo_name,
8127                                                    &dwo_at))
8128                      ?: "<unknown>"));
8129               fprintf (stderr,
8130                        "Could not find split unit '%s', id: %" PRIx64 "\n",
8131                        dwo_name, unit_id);
8132             }
8133         }
8134       else
8135         {
8136           Dwarf_CU *split_cu = subdie.cu;
8137           dwarf_cu_die (split_cu, &result, NULL, &abbroffset,
8138                         &addrsize, &offsize, &unit_id, &subdie_off);
8139           Dwarf_Off offset = cu->start;
8140
8141           if (!silent)
8142             {
8143               printf (_(" Split compilation unit at offset %"
8144                                PRIu64 ":\n"
8145                                " Version: %" PRIu16
8146                                ", Abbreviation section offset: %" PRIu64
8147                                ", Address size: %" PRIu8
8148                                ", Offset size: %" PRIu8 "\n"),
8149                       (uint64_t) offset, version, abbroffset,
8150                       addrsize, offsize);
8151               printf (_(" Unit type: %s (%" PRIu8 ")"),
8152                       dwarf_unit_name (unit_type), unit_type);
8153               printf (", Unit id: 0x%.16" PRIx64 "", unit_id);
8154               printf ("\n");
8155             }
8156
8157           unit_type = DW_UT_split_compile;
8158           is_split = true;
8159           level = 0;
8160           dies[0] = subdie;
8161           args.cu = dies[0].cu;
8162           args.dbg = split_cu->dbg;
8163           args.is_split = is_split;
8164           goto do_cu;
8165         }
8166     }
8167
8168   /* And again... */
8169   goto next_cu;
8170
8171  do_return:
8172   free (dies);
8173 }
8174
8175 static void
8176 print_debug_info_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
8177                           Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
8178 {
8179   print_debug_units (dwflmod, ebl, ehdr, scn, shdr, dbg, false);
8180 }
8181
8182 static void
8183 print_debug_types_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
8184                            Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
8185 {
8186   print_debug_units (dwflmod, ebl, ehdr, scn, shdr, dbg, true);
8187 }
8188
8189
8190 static void
8191 print_decoded_line_section (Dwfl_Module *dwflmod, Ebl *ebl,
8192                             GElf_Ehdr *ehdr __attribute__ ((unused)),
8193                             Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
8194 {
8195   printf (_("\
8196 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n\n"),
8197           elf_ndxscn (scn), section_name (ebl, shdr),
8198           (uint64_t) shdr->sh_offset);
8199
8200   size_t address_size
8201     = elf_getident (ebl->elf, NULL)[EI_CLASS] == ELFCLASS32 ? 4 : 8;
8202
8203   Dwarf_Lines *lines;
8204   size_t nlines;
8205   Dwarf_Off off, next_off = 0;
8206   Dwarf_CU *cu = NULL;
8207   while (dwarf_next_lines (dbg, off = next_off, &next_off, &cu, NULL, NULL,
8208                            &lines, &nlines) == 0)
8209     {
8210       Dwarf_Die cudie;
8211       if (cu != NULL && dwarf_cu_info (cu, NULL, NULL, &cudie,
8212                                        NULL, NULL, NULL, NULL) == 0)
8213         printf (" CU [%" PRIx64 "] %s\n",
8214                 dwarf_dieoffset (&cudie), dwarf_diename (&cudie));
8215       else
8216         {
8217           /* DWARF5 lines can be independent of any CU, but they probably
8218              are used by some CU.  Determine the CU this block is for.  */
8219           Dwarf_Off cuoffset;
8220           Dwarf_Off ncuoffset = 0;
8221           size_t hsize;
8222           while (dwarf_nextcu (dbg, cuoffset = ncuoffset, &ncuoffset, &hsize,
8223                                NULL, NULL, NULL) == 0)
8224             {
8225               if (dwarf_offdie (dbg, cuoffset + hsize, &cudie) == NULL)
8226                 continue;
8227               Dwarf_Attribute stmt_list;
8228               if (dwarf_attr (&cudie, DW_AT_stmt_list, &stmt_list) == NULL)
8229                 continue;
8230               Dwarf_Word lineoff;
8231               if (dwarf_formudata (&stmt_list, &lineoff) != 0)
8232                 continue;
8233               if (lineoff == off)
8234                 {
8235                   /* Found the CU.  */
8236                   cu = cudie.cu;
8237                   break;
8238                 }
8239             }
8240
8241           if (cu != NULL)
8242             printf (" CU [%" PRIx64 "] %s\n",
8243                     dwarf_dieoffset (&cudie), dwarf_diename (&cudie));
8244           else
8245             printf (" No CU\n");
8246         }
8247
8248       printf ("  line:col SBPE* disc isa op address"
8249               " (Statement Block Prologue Epilogue *End)\n");
8250       const char *last_file = "";
8251       for (size_t n = 0; n < nlines; n++)
8252         {
8253           Dwarf_Line *line = dwarf_onesrcline (lines, n);
8254           if (line == NULL)
8255             {
8256               printf ("  dwarf_onesrcline: %s\n", dwarf_errmsg (-1));
8257               continue;
8258             }
8259           Dwarf_Word mtime, length;
8260           const char *file = dwarf_linesrc (line, &mtime, &length);
8261           if (file == NULL)
8262             {
8263               printf ("  <%s> (mtime: ?, length: ?)\n", dwarf_errmsg (-1));
8264               last_file = "";
8265             }
8266           else if (strcmp (last_file, file) != 0)
8267             {
8268               printf ("  %s (mtime: %" PRIu64 ", length: %" PRIu64 ")\n",
8269                       file, mtime, length);
8270               last_file = file;
8271             }
8272
8273           int lineno, colno;
8274           bool statement, endseq, block, prologue_end, epilogue_begin;
8275           unsigned int lineop, isa, disc;
8276           Dwarf_Addr address;
8277           dwarf_lineaddr (line, &address);
8278           dwarf_lineno (line, &lineno);
8279           dwarf_linecol (line, &colno);
8280           dwarf_lineop_index (line, &lineop);
8281           dwarf_linebeginstatement (line, &statement);
8282           dwarf_lineendsequence (line, &endseq);
8283           dwarf_lineblock (line, &block);
8284           dwarf_lineprologueend (line, &prologue_end);
8285           dwarf_lineepiloguebegin (line, &epilogue_begin);
8286           dwarf_lineisa (line, &isa);
8287           dwarf_linediscriminator (line, &disc);
8288
8289           /* End sequence is special, it is one byte past.  */
8290           printf ("  %4d:%-3d %c%c%c%c%c %4d %3d %2d ",
8291                   lineno, colno,
8292                   (statement ? 'S' : ' '),
8293                   (block ? 'B' : ' '),
8294                   (prologue_end ? 'P' : ' '),
8295                   (epilogue_begin ? 'E' : ' '),
8296                   (endseq ? '*' : ' '),
8297                   disc, isa, lineop);
8298           print_dwarf_addr (dwflmod, address_size,
8299                             address - (endseq ? 1 : 0), address);
8300           printf ("\n");
8301
8302           if (endseq)
8303             printf("\n");
8304         }
8305     }
8306 }
8307
8308
8309 /* Print the value of a form.
8310    Returns new value of readp, or readendp on failure.  */
8311 static const unsigned char *
8312 print_form_data (Dwarf *dbg, int form, const unsigned char *readp,
8313                  const unsigned char *readendp, unsigned int offset_len,
8314                  Dwarf_Off str_offsets_base)
8315 {
8316   Dwarf_Word val;
8317   unsigned char *endp;
8318   Elf_Data *data;
8319   char *str;
8320   switch (form)
8321     {
8322     case DW_FORM_data1:
8323       if (readendp - readp < 1)
8324         {
8325         invalid_data:
8326           error (0, 0, "invalid data");
8327           return readendp;
8328         }
8329       val = *readp++;
8330       printf (" %" PRIx8, (unsigned int) val);
8331       break;
8332
8333     case DW_FORM_data2:
8334       if (readendp - readp < 2)
8335         goto invalid_data;
8336       val = read_2ubyte_unaligned_inc (dbg, readp);
8337       printf(" %" PRIx16, (unsigned int) val);
8338       break;
8339
8340     case DW_FORM_data4:
8341       if (readendp - readp < 4)
8342         goto invalid_data;
8343       val = read_4ubyte_unaligned_inc (dbg, readp);
8344       printf (" %" PRIx32, (unsigned int) val);
8345       break;
8346
8347     case DW_FORM_data8:
8348       if (readendp - readp < 8)
8349         goto invalid_data;
8350       val = read_8ubyte_unaligned_inc (dbg, readp);
8351       printf (" %" PRIx64, val);
8352       break;
8353
8354     case DW_FORM_sdata:
8355       if (readendp - readp < 1)
8356         goto invalid_data;
8357       get_sleb128 (val, readp, readendp);
8358       printf (" %" PRIx64, val);
8359       break;
8360
8361     case DW_FORM_udata:
8362       if (readendp - readp < 1)
8363         goto invalid_data;
8364       get_uleb128 (val, readp, readendp);
8365       printf (" %" PRIx64, val);
8366       break;
8367
8368     case DW_FORM_block:
8369       if (readendp - readp < 1)
8370         goto invalid_data;
8371       get_uleb128 (val, readp, readendp);
8372       if ((size_t) (readendp - readp) < val)
8373         goto invalid_data;
8374       print_bytes (val, readp);
8375       readp += val;
8376       break;
8377
8378     case DW_FORM_block1:
8379       if (readendp - readp < 1)
8380         goto invalid_data;
8381       val = *readp++;
8382       if ((size_t) (readendp - readp) < val)
8383         goto invalid_data;
8384       print_bytes (val, readp);
8385       readp += val;
8386       break;
8387
8388     case DW_FORM_block2:
8389       if (readendp - readp < 2)
8390         goto invalid_data;
8391       val = read_2ubyte_unaligned_inc (dbg, readp);
8392       if ((size_t) (readendp - readp) < val)
8393         goto invalid_data;
8394       print_bytes (val, readp);
8395       readp += val;
8396       break;
8397
8398     case DW_FORM_block4:
8399       if (readendp - readp < 4)
8400         goto invalid_data;
8401       val = read_4ubyte_unaligned_inc (dbg, readp);
8402       if ((size_t) (readendp - readp) < val)
8403         goto invalid_data;
8404       print_bytes (val, readp);
8405       readp += val;
8406       break;
8407
8408     case DW_FORM_data16:
8409       if (readendp - readp < 16)
8410         goto invalid_data;
8411       print_bytes (16, readp);
8412       readp += 16;
8413       break;
8414
8415     case DW_FORM_flag:
8416       if (readendp - readp < 1)
8417         goto invalid_data;
8418       val = *readp++;
8419       printf ("%s", val != 0 ? yes_str : no_str);
8420       break;
8421
8422     case DW_FORM_string:
8423       endp = memchr (readp, '\0', readendp - readp);
8424       if (endp == NULL)
8425         goto invalid_data;
8426       printf ("%s", readp);
8427       readp = endp + 1;
8428       break;
8429
8430     case DW_FORM_strp:
8431     case DW_FORM_line_strp:
8432     case DW_FORM_strp_sup:
8433       if ((size_t) (readendp - readp) < offset_len)
8434         goto invalid_data;
8435       if (offset_len == 8)
8436         val = read_8ubyte_unaligned_inc (dbg, readp);
8437       else
8438         val = read_4ubyte_unaligned_inc (dbg, readp);
8439       if (form == DW_FORM_strp)
8440         data = dbg->sectiondata[IDX_debug_str];
8441       else if (form == DW_FORM_line_strp)
8442         data = dbg->sectiondata[IDX_debug_line_str];
8443       else /* form == DW_FORM_strp_sup */
8444         {
8445           Dwarf *alt = dwarf_getalt (dbg);
8446           data = alt != NULL ? alt->sectiondata[IDX_debug_str] : NULL;
8447         }
8448       if (data == NULL || val >= data->d_size
8449           || memchr (data->d_buf + val, '\0', data->d_size - val) == NULL)
8450         str = "???";
8451       else
8452         str = (char *) data->d_buf + val;
8453       printf ("%s (%" PRIu64 ")", str, val);
8454       break;
8455
8456     case DW_FORM_sec_offset:
8457       if ((size_t) (readendp - readp) < offset_len)
8458         goto invalid_data;
8459       if (offset_len == 8)
8460         val = read_8ubyte_unaligned_inc (dbg, readp);
8461       else
8462         val = read_4ubyte_unaligned_inc (dbg, readp);
8463       printf ("[%" PRIx64 "]", val);
8464       break;
8465
8466     case DW_FORM_strx:
8467     case DW_FORM_GNU_str_index:
8468       if (readendp - readp < 1)
8469         goto invalid_data;
8470       get_uleb128 (val, readp, readendp);
8471     strx_val:
8472       data = dbg->sectiondata[IDX_debug_str_offsets];
8473       if (data == NULL
8474           || data->d_size - str_offsets_base < val)
8475         str = "???";
8476       else
8477         {
8478           const unsigned char *strreadp = data->d_buf + str_offsets_base + val;
8479           const unsigned char *strreadendp = data->d_buf + data->d_size;
8480           if ((size_t) (strreadendp - strreadp) < offset_len)
8481             str = "???";
8482           else
8483             {
8484               Dwarf_Off idx;
8485               if (offset_len == 8)
8486                 idx = read_8ubyte_unaligned (dbg, strreadp);
8487               else
8488                 idx = read_4ubyte_unaligned (dbg, strreadp);
8489
8490               data = dbg->sectiondata[IDX_debug_str];
8491               if (data == NULL || idx >= data->d_size
8492                   || memchr (data->d_buf + idx, '\0',
8493                              data->d_size - idx) == NULL)
8494                 str = "???";
8495               else
8496                 str = (char *) data->d_buf + idx;
8497             }
8498         }
8499       printf ("%s (%" PRIu64 ")", str, val);
8500       break;
8501
8502     case DW_FORM_strx1:
8503       if (readendp - readp < 1)
8504         goto invalid_data;
8505       val = *readp++;
8506       goto strx_val;
8507
8508     case DW_FORM_strx2:
8509       if (readendp - readp < 2)
8510         goto invalid_data;
8511       val = read_2ubyte_unaligned_inc (dbg, readp);
8512       goto strx_val;
8513
8514     case DW_FORM_strx3:
8515       if (readendp - readp < 3)
8516         goto invalid_data;
8517       val = read_3ubyte_unaligned_inc (dbg, readp);
8518       goto strx_val;
8519
8520     case DW_FORM_strx4:
8521       if (readendp - readp < 4)
8522         goto invalid_data;
8523       val = read_4ubyte_unaligned_inc (dbg, readp);
8524       goto strx_val;
8525
8526     default:
8527       error (0, 0, _("unknown form: %s"), dwarf_form_name (form));
8528       return readendp;
8529     }
8530
8531   return readp;
8532 }
8533
8534 /* Only used via run_advance_pc() macro */
8535 static inline void
8536 run_advance_pc (unsigned int op_advance,
8537                 unsigned int minimum_instr_len,
8538                 unsigned int max_ops_per_instr,
8539                 unsigned int *op_addr_advance,
8540                 Dwarf_Word *address,
8541                 unsigned int *op_index)
8542 {
8543   const unsigned int advanced_op_index = (*op_index) + op_advance;
8544
8545   *op_addr_advance = minimum_instr_len * (advanced_op_index
8546                                          / max_ops_per_instr);
8547   *address = *address + *op_addr_advance;
8548   *op_index = advanced_op_index % max_ops_per_instr;
8549 }
8550
8551 static void
8552 print_debug_line_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
8553                           Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
8554 {
8555   if (decodedline)
8556     {
8557       print_decoded_line_section (dwflmod, ebl, ehdr, scn, shdr, dbg);
8558       return;
8559     }
8560
8561   printf (_("\
8562 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
8563           elf_ndxscn (scn), section_name (ebl, shdr),
8564           (uint64_t) shdr->sh_offset);
8565
8566   if (shdr->sh_size == 0)
8567     return;
8568
8569   /* There is no functionality in libdw to read the information in the
8570      way it is represented here.  Hardcode the decoder.  */
8571   Elf_Data *data = (dbg->sectiondata[IDX_debug_line]
8572                     ?: elf_rawdata (scn, NULL));
8573   if (unlikely (data == NULL))
8574     {
8575       error (0, 0, _("cannot get line data section data: %s"),
8576              elf_errmsg (-1));
8577       return;
8578     }
8579
8580   const unsigned char *linep = (const unsigned char *) data->d_buf;
8581   const unsigned char *lineendp;
8582
8583   while (linep
8584          < (lineendp = (const unsigned char *) data->d_buf + data->d_size))
8585     {
8586       size_t start_offset = linep - (const unsigned char *) data->d_buf;
8587
8588       printf (_("\nTable at offset %zu:\n"), start_offset);
8589
8590       if (unlikely (linep + 4 > lineendp))
8591         goto invalid_data;
8592       Dwarf_Word unit_length = read_4ubyte_unaligned_inc (dbg, linep);
8593       unsigned int length = 4;
8594       if (unlikely (unit_length == 0xffffffff))
8595         {
8596           if (unlikely (linep + 8 > lineendp))
8597             {
8598             invalid_data:
8599               error (0, 0, _("invalid data in section [%zu] '%s'"),
8600                      elf_ndxscn (scn), section_name (ebl, shdr));
8601               return;
8602             }
8603           unit_length = read_8ubyte_unaligned_inc (dbg, linep);
8604           length = 8;
8605         }
8606
8607       /* Check whether we have enough room in the section.  */
8608       if (unlikely (unit_length > (size_t) (lineendp - linep)))
8609         goto invalid_data;
8610       lineendp = linep + unit_length;
8611
8612       /* The next element of the header is the version identifier.  */
8613       if ((size_t) (lineendp - linep) < 2)
8614         goto invalid_data;
8615       uint_fast16_t version = read_2ubyte_unaligned_inc (dbg, linep);
8616
8617       size_t address_size
8618         = elf_getident (ebl->elf, NULL)[EI_CLASS] == ELFCLASS32 ? 4 : 8;
8619       unsigned char segment_selector_size = 0;
8620       if (version > 4)
8621         {
8622           if ((size_t) (lineendp - linep) < 2)
8623             goto invalid_data;
8624           address_size = *linep++;
8625           segment_selector_size = *linep++;
8626         }
8627
8628       /* Next comes the header length.  */
8629       Dwarf_Word header_length;
8630       if (length == 4)
8631         {
8632           if ((size_t) (lineendp - linep) < 4)
8633             goto invalid_data;
8634           header_length = read_4ubyte_unaligned_inc (dbg, linep);
8635         }
8636       else
8637         {
8638           if ((size_t) (lineendp - linep) < 8)
8639             goto invalid_data;
8640           header_length = read_8ubyte_unaligned_inc (dbg, linep);
8641         }
8642
8643       const unsigned char *header_start = linep;
8644
8645       /* Next the minimum instruction length.  */
8646       if ((size_t) (lineendp - linep) < 1)
8647         goto invalid_data;
8648       uint_fast8_t minimum_instr_len = *linep++;
8649
8650       /* Next the maximum operations per instruction, in version 4 format.  */
8651       uint_fast8_t max_ops_per_instr;
8652       if (version < 4)
8653         max_ops_per_instr = 1;
8654       else
8655         {
8656           if ((size_t) (lineendp - linep) < 1)
8657             goto invalid_data;
8658           max_ops_per_instr = *linep++;
8659         }
8660
8661       /* We need at least 4 more bytes.  */
8662       if ((size_t) (lineendp - linep) < 4)
8663         goto invalid_data;
8664
8665       /* Then the flag determining the default value of the is_stmt
8666          register.  */
8667       uint_fast8_t default_is_stmt = *linep++;
8668
8669       /* Now the line base.  */
8670       int_fast8_t line_base = *linep++;
8671
8672       /* And the line range.  */
8673       uint_fast8_t line_range = *linep++;
8674
8675       /* The opcode base.  */
8676       uint_fast8_t opcode_base = *linep++;
8677
8678       /* Print what we got so far.  */
8679       printf (_("\n"
8680                        " Length:                         %" PRIu64 "\n"
8681                        " DWARF version:                  %" PRIuFAST16 "\n"
8682                        " Prologue length:                %" PRIu64 "\n"
8683                        " Address size:                   %zd\n"
8684                        " Segment selector size:          %zd\n"
8685                        " Min instruction length:         %" PRIuFAST8 "\n"
8686                        " Max operations per instruction: %" PRIuFAST8 "\n"
8687                        " Initial value if 'is_stmt':     %" PRIuFAST8 "\n"
8688                        " Line base:                      %" PRIdFAST8 "\n"
8689                        " Line range:                     %" PRIuFAST8 "\n"
8690                        " Opcode base:                    %" PRIuFAST8 "\n"
8691                        "\n"
8692                        "Opcodes:\n"),
8693               (uint64_t) unit_length, version, (uint64_t) header_length,
8694               address_size, (size_t) segment_selector_size,
8695               minimum_instr_len, max_ops_per_instr,
8696               default_is_stmt, line_base,
8697               line_range, opcode_base);
8698
8699       if (version < 2 || version > 5)
8700         {
8701           error (0, 0, _("cannot handle .debug_line version: %u\n"),
8702                  (unsigned int) version);
8703           linep = lineendp;
8704           continue;
8705         }
8706
8707       if (address_size != 4 && address_size != 8)
8708         {
8709           error (0, 0, _("cannot handle address size: %u\n"),
8710                  (unsigned int) address_size);
8711           linep = lineendp;
8712           continue;
8713         }
8714
8715       if (segment_selector_size != 0)
8716         {
8717           error (0, 0, _("cannot handle segment selector size: %u\n"),
8718                  (unsigned int) segment_selector_size);
8719           linep = lineendp;
8720           continue;
8721         }
8722
8723       if (unlikely (linep + opcode_base - 1 >= lineendp))
8724         {
8725         invalid_unit:
8726           error (0, 0,
8727                  _("invalid data at offset %tu in section [%zu] '%s'"),
8728                  linep - (const unsigned char *) data->d_buf,
8729                  elf_ndxscn (scn), section_name (ebl, shdr));
8730           linep = lineendp;
8731           continue;
8732         }
8733       int opcode_base_l10 = 1;
8734       unsigned int tmp = opcode_base;
8735       while (tmp > 10)
8736         {
8737           tmp /= 10;
8738           ++opcode_base_l10;
8739         }
8740       const uint8_t *standard_opcode_lengths = linep - 1;
8741       for (uint_fast8_t cnt = 1; cnt < opcode_base; ++cnt)
8742         printf (ngettext ("  [%*" PRIuFAST8 "]  %hhu argument\n",
8743                           "  [%*" PRIuFAST8 "]  %hhu arguments\n",
8744                           (int) linep[cnt - 1]),
8745                 opcode_base_l10, cnt, linep[cnt - 1]);
8746       linep += opcode_base - 1;
8747
8748       if (unlikely (linep >= lineendp))
8749         goto invalid_unit;
8750
8751       Dwarf_Off str_offsets_base = str_offsets_base_off (dbg, NULL);
8752
8753       puts (_("\nDirectory table:"));
8754       if (version > 4)
8755         {
8756           struct encpair { uint16_t desc; uint16_t form; };
8757           struct encpair enc[256];
8758
8759           printf (_("      ["));
8760           if ((size_t) (lineendp - linep) < 1)
8761             goto invalid_data;
8762           unsigned char directory_entry_format_count = *linep++;
8763           for (int i = 0; i < directory_entry_format_count; i++)
8764             {
8765               uint16_t desc, form;
8766               if ((size_t) (lineendp - linep) < 1)
8767                 goto invalid_data;
8768               get_uleb128 (desc, linep, lineendp);
8769               if ((size_t) (lineendp - linep) < 1)
8770                 goto invalid_data;
8771               get_uleb128 (form, linep, lineendp);
8772
8773               enc[i].desc = desc;
8774               enc[i].form = form;
8775
8776               printf ("%s(%s)",
8777                       dwarf_line_content_description_name (desc),
8778                       dwarf_form_name (form));
8779               if (i + 1 < directory_entry_format_count)
8780                 printf (", ");
8781             }
8782           printf ("]\n");
8783
8784           uint64_t directories_count;
8785           if ((size_t) (lineendp - linep) < 1)
8786             goto invalid_data;
8787           get_uleb128 (directories_count, linep, lineendp);
8788
8789           if (directory_entry_format_count == 0
8790               && directories_count != 0)
8791             goto invalid_data;
8792
8793           for (uint64_t i = 0; i < directories_count; i++)
8794             {
8795               printf (" %-5" PRIu64 " ", i);
8796               for (int j = 0; j < directory_entry_format_count; j++)
8797                 {
8798                   linep = print_form_data (dbg, enc[j].form,
8799                                            linep, lineendp, length,
8800                                            str_offsets_base);
8801                   if (j + 1 < directory_entry_format_count)
8802                     printf (", ");
8803                 }
8804               printf ("\n");
8805               if (linep >= lineendp)
8806                 goto invalid_unit;
8807             }
8808         }
8809       else
8810         {
8811           while (linep < lineendp && *linep != 0)
8812             {
8813               unsigned char *endp = memchr (linep, '\0', lineendp - linep);
8814               if (unlikely (endp == NULL))
8815                 goto invalid_unit;
8816
8817               printf (" %s\n", (char *) linep);
8818
8819               linep = endp + 1;
8820             }
8821           if (linep >= lineendp || *linep != 0)
8822             goto invalid_unit;
8823           /* Skip the final NUL byte.  */
8824           ++linep;
8825         }
8826
8827       if (unlikely (linep >= lineendp))
8828         goto invalid_unit;
8829
8830       puts (_("\nFile name table:"));
8831       if (version > 4)
8832         {
8833           struct encpair { uint16_t desc; uint16_t form; };
8834           struct encpair enc[256];
8835
8836           printf (_("      ["));
8837           if ((size_t) (lineendp - linep) < 1)
8838             goto invalid_data;
8839           unsigned char file_name_format_count = *linep++;
8840           for (int i = 0; i < file_name_format_count; i++)
8841             {
8842               uint64_t desc, form;
8843               if ((size_t) (lineendp - linep) < 1)
8844                 goto invalid_data;
8845               get_uleb128 (desc, linep, lineendp);
8846               if ((size_t) (lineendp - linep) < 1)
8847                 goto invalid_data;
8848               get_uleb128 (form, linep, lineendp);
8849
8850               if (! libdw_valid_user_form (form))
8851                 goto invalid_data;
8852
8853               enc[i].desc = desc;
8854               enc[i].form = form;
8855
8856               printf ("%s(%s)",
8857                       dwarf_line_content_description_name (desc),
8858                       dwarf_form_name (form));
8859               if (i + 1 < file_name_format_count)
8860                 printf (", ");
8861             }
8862           printf ("]\n");
8863
8864           uint64_t file_name_count;
8865           if ((size_t) (lineendp - linep) < 1)
8866             goto invalid_data;
8867           get_uleb128 (file_name_count, linep, lineendp);
8868
8869           if (file_name_format_count == 0
8870               && file_name_count != 0)
8871             goto invalid_data;
8872
8873           for (uint64_t i = 0; i < file_name_count; i++)
8874             {
8875               printf (" %-5" PRIu64 " ", i);
8876               for (int j = 0; j < file_name_format_count; j++)
8877                 {
8878                   linep = print_form_data (dbg, enc[j].form,
8879                                            linep, lineendp, length,
8880                                            str_offsets_base);
8881                   if (j + 1 < file_name_format_count)
8882                     printf (", ");
8883                 }
8884               printf ("\n");
8885               if (linep > lineendp)
8886                 goto invalid_unit;
8887             }
8888         }
8889       else
8890         {
8891           puts (_(" Entry Dir   Time      Size      Name"));
8892           for (unsigned int cnt = 1; linep < lineendp && *linep != 0; ++cnt)
8893             {
8894               /* First comes the file name.  */
8895               char *fname = (char *) linep;
8896               unsigned char *endp = memchr (fname, '\0', lineendp - linep);
8897               if (unlikely (endp == NULL))
8898                 goto invalid_unit;
8899               linep = endp + 1;
8900
8901               /* Then the index.  */
8902               unsigned int diridx;
8903               if (lineendp - linep < 1)
8904                 goto invalid_unit;
8905               get_uleb128 (diridx, linep, lineendp);
8906
8907               /* Next comes the modification time.  */
8908               unsigned int mtime;
8909               if (lineendp - linep < 1)
8910                 goto invalid_unit;
8911               get_uleb128 (mtime, linep, lineendp);
8912
8913               /* Finally the length of the file.  */
8914               unsigned int fsize;
8915               if (lineendp - linep < 1)
8916                 goto invalid_unit;
8917               get_uleb128 (fsize, linep, lineendp);
8918
8919               printf (" %-5u %-5u %-9u %-9u %s\n",
8920                       cnt, diridx, mtime, fsize, fname);
8921             }
8922           if (linep >= lineendp || *linep != '\0')
8923             goto invalid_unit;
8924           /* Skip the final NUL byte.  */
8925           ++linep;
8926         }
8927
8928       unsigned int debug_str_offset = 0;
8929       if (unlikely (linep == header_start + header_length - 4))
8930         {
8931           /* CUBINs contain an unsigned 4-byte offset */
8932           debug_str_offset = read_4ubyte_unaligned_inc (dbg, linep);
8933         }
8934
8935       if (linep == lineendp)
8936         {
8937           puts (_("\nNo line number statements."));
8938           continue;
8939         }
8940
8941       puts (_("\nLine number statements:"));
8942       Dwarf_Word address = 0;
8943       unsigned int op_index = 0;
8944       size_t line = 1;
8945       uint_fast8_t is_stmt = default_is_stmt;
8946
8947       /* Apply the "operation advance" from a special opcode
8948          or DW_LNS_advance_pc (as per DWARF4 6.2.5.1).  */
8949       unsigned int op_addr_advance;
8950 #define advance_pc(op_advance) run_advance_pc(op_advance, minimum_instr_len, \
8951                       max_ops_per_instr, &op_addr_advance, &address, &op_index)
8952
8953       if (max_ops_per_instr == 0)
8954         {
8955           error (0, 0,
8956                  _("invalid maximum operations per instruction is zero"));
8957           linep = lineendp;
8958           continue;
8959         }
8960
8961       while (linep < lineendp)
8962         {
8963           size_t offset = linep - (const unsigned char *) data->d_buf;
8964           unsigned int u128;
8965           int s128;
8966
8967           /* Read the opcode.  */
8968           unsigned int opcode = *linep++;
8969
8970           printf (" [%6" PRIx64 "]", (uint64_t)offset);
8971           /* Is this a special opcode?  */
8972           if (likely (opcode >= opcode_base))
8973             {
8974               if (unlikely (line_range == 0))
8975                 goto invalid_unit;
8976
8977               /* Yes.  Handling this is quite easy since the opcode value
8978                  is computed with
8979
8980                  opcode = (desired line increment - line_base)
8981                            + (line_range * address advance) + opcode_base
8982               */
8983               int line_increment = (line_base
8984                                     + (opcode - opcode_base) % line_range);
8985
8986               /* Perform the increments.  */
8987               line += line_increment;
8988               advance_pc ((opcode - opcode_base) / line_range);
8989
8990               printf (_(" special opcode %u: address+%u = "),
8991                       opcode, op_addr_advance);
8992               print_dwarf_addr (dwflmod, 0, address, address);
8993               if (op_index > 0)
8994                 printf (_(", op_index = %u, line%+d = %zu\n"),
8995                         op_index, line_increment, line);
8996               else
8997                 printf (_(", line%+d = %zu\n"),
8998                         line_increment, line);
8999             }
9000           else if (opcode == 0)
9001             {
9002               /* This an extended opcode.  */
9003               if (unlikely (linep + 2 > lineendp))
9004                 goto invalid_unit;
9005
9006               /* The length.  */
9007               unsigned int len = *linep++;
9008
9009               if (unlikely (linep + len > lineendp))
9010                 goto invalid_unit;
9011
9012               /* The sub-opcode.  */
9013               opcode = *linep++;
9014
9015               printf (_(" extended opcode %u: "), opcode);
9016
9017               switch (opcode)
9018                 {
9019                 case DW_LNE_end_sequence:
9020                   puts (_(" end of sequence"));
9021
9022                   /* Reset the registers we care about.  */
9023                   address = 0;
9024                   op_index = 0;
9025                   line = 1;
9026                   is_stmt = default_is_stmt;
9027                   break;
9028
9029                 case DW_LNE_set_address:
9030                   op_index = 0;
9031                   if (unlikely ((size_t) (lineendp - linep) < address_size))
9032                     goto invalid_unit;
9033                   if (address_size == 4)
9034                     address = read_4ubyte_unaligned_inc (dbg, linep);
9035                   else
9036                     address = read_8ubyte_unaligned_inc (dbg, linep);
9037                   {
9038                     printf (_(" set address to "));
9039                     print_dwarf_addr (dwflmod, 0, address, address);
9040                     printf ("\n");
9041                   }
9042                   break;
9043
9044                 case DW_LNE_define_file:
9045                   {
9046                     char *fname = (char *) linep;
9047                     unsigned char *endp = memchr (linep, '\0',
9048                                                   lineendp - linep);
9049                     if (unlikely (endp == NULL))
9050                       goto invalid_unit;
9051                     linep = endp + 1;
9052
9053                     unsigned int diridx;
9054                     if (lineendp - linep < 1)
9055                       goto invalid_unit;
9056                     get_uleb128 (diridx, linep, lineendp);
9057                     Dwarf_Word mtime;
9058                     if (lineendp - linep < 1)
9059                       goto invalid_unit;
9060                     get_uleb128 (mtime, linep, lineendp);
9061                     Dwarf_Word filelength;
9062                     if (lineendp - linep < 1)
9063                       goto invalid_unit;
9064                     get_uleb128 (filelength, linep, lineendp);
9065
9066                     printf (_("\
9067  define new file: dir=%u, mtime=%" PRIu64 ", length=%" PRIu64 ", name=%s\n"),
9068                             diridx, (uint64_t) mtime, (uint64_t) filelength,
9069                             fname);
9070                   }
9071                   break;
9072
9073                 case DW_LNE_set_discriminator:
9074                   /* Takes one ULEB128 parameter, the discriminator.  */
9075                   if (unlikely (standard_opcode_lengths[opcode] != 1
9076                                 || lineendp - linep < 1))
9077                     goto invalid_unit;
9078
9079                   get_uleb128 (u128, linep, lineendp);
9080                   printf (_(" set discriminator to %u\n"), u128);
9081                   break;
9082
9083                 case DW_LNE_NVIDIA_inlined_call:
9084                   {
9085                     if (unlikely (linep >= lineendp))
9086                       goto invalid_data;
9087
9088                     unsigned int context;
9089                     get_uleb128 (context, linep, lineendp);
9090
9091                     if (unlikely (linep >= lineendp))
9092                       goto invalid_data;
9093
9094                     unsigned int function_name;
9095                     get_uleb128 (function_name, linep, lineendp);
9096                     function_name += debug_str_offset;
9097
9098                     Elf_Data *str_data = dbg->sectiondata[IDX_debug_str];
9099                     char *function_str;
9100                     if (str_data == NULL || function_name >= str_data->d_size
9101                         || memchr (str_data->d_buf + function_name, '\0',
9102                                    str_data->d_size - function_name) == NULL)
9103                       function_str = "???";
9104                     else
9105                       function_str = (char *) str_data->d_buf + function_name;
9106
9107                     printf (_(" set inlined context %u,"
9108                               " function name %s (0x%x)\n"),
9109                             context, function_str, function_name);
9110                     break;
9111                   }
9112
9113                 case DW_LNE_NVIDIA_set_function_name:
9114                   {
9115                     if (unlikely (linep >= lineendp))
9116                       goto invalid_data;
9117
9118                     unsigned int function_name;
9119                     get_uleb128 (function_name, linep, lineendp);
9120                     function_name += debug_str_offset;
9121
9122                     Elf_Data *str_data = dbg->sectiondata[IDX_debug_str];
9123                     char *function_str;
9124                     if (str_data == NULL || function_name >= str_data->d_size
9125                         || memchr (str_data->d_buf + function_name, '\0',
9126                                    str_data->d_size - function_name) == NULL)
9127                       function_str = "???";
9128                     else
9129                       function_str = (char *) str_data->d_buf + function_name;
9130
9131                     printf (_(" set function name %s (0x%x)\n"),
9132                             function_str, function_name);
9133                   }
9134                   break;
9135
9136                 default:
9137                   /* Unknown, ignore it.  */
9138                   puts (_(" unknown opcode"));
9139                   linep += len - 1;
9140                   break;
9141                 }
9142             }
9143           else if (opcode <= DW_LNS_set_isa)
9144             {
9145               /* This is a known standard opcode.  */
9146               switch (opcode)
9147                 {
9148                 case DW_LNS_copy:
9149                   /* Takes no argument.  */
9150                   puts (_(" copy"));
9151                   break;
9152
9153                 case DW_LNS_advance_pc:
9154                   /* Takes one uleb128 parameter which is added to the
9155                      address.  */
9156                   if (lineendp - linep < 1)
9157                     goto invalid_unit;
9158                   get_uleb128 (u128, linep, lineendp);
9159                   advance_pc (u128);
9160                   {
9161                     printf (_(" advance address by %u to "),
9162                             op_addr_advance);
9163                     print_dwarf_addr (dwflmod, 0, address, address);
9164                     if (op_index > 0)
9165                       printf (_(", op_index to %u"), op_index);
9166                     printf ("\n");
9167                   }
9168                   break;
9169
9170                 case DW_LNS_advance_line:
9171                   /* Takes one sleb128 parameter which is added to the
9172                      line.  */
9173                   if (lineendp - linep < 1)
9174                     goto invalid_unit;
9175                   get_sleb128 (s128, linep, lineendp);
9176                   line += s128;
9177                   printf (_("\
9178  advance line by constant %d to %" PRId64 "\n"),
9179                           s128, (int64_t) line);
9180                   break;
9181
9182                 case DW_LNS_set_file:
9183                   /* Takes one uleb128 parameter which is stored in file.  */
9184                   if (lineendp - linep < 1)
9185                     goto invalid_unit;
9186                   get_uleb128 (u128, linep, lineendp);
9187                   printf (_(" set file to %" PRIu64 "\n"),
9188                           (uint64_t) u128);
9189                   break;
9190
9191                 case DW_LNS_set_column:
9192                   /* Takes one uleb128 parameter which is stored in column.  */
9193                   if (unlikely (standard_opcode_lengths[opcode] != 1
9194                                 || lineendp - linep < 1))
9195                     goto invalid_unit;
9196
9197                   get_uleb128 (u128, linep, lineendp);
9198                   printf (_(" set column to %" PRIu64 "\n"),
9199                           (uint64_t) u128);
9200                   break;
9201
9202                 case DW_LNS_negate_stmt:
9203                   /* Takes no argument.  */
9204                   is_stmt = 1 - is_stmt;
9205                   printf (_(" set '%s' to %" PRIuFAST8 "\n"),
9206                           "is_stmt", is_stmt);
9207                   break;
9208
9209                 case DW_LNS_set_basic_block:
9210                   /* Takes no argument.  */
9211                   puts (_(" set basic block flag"));
9212                   break;
9213
9214                 case DW_LNS_const_add_pc:
9215                   /* Takes no argument.  */
9216
9217                   if (unlikely (line_range == 0))
9218                     goto invalid_unit;
9219
9220                   advance_pc ((255 - opcode_base) / line_range);
9221                   {
9222                     printf (_(" advance address by constant %u to "),
9223                             op_addr_advance);
9224                     print_dwarf_addr (dwflmod, 0, address, address);
9225                     if (op_index > 0)
9226                       printf (_(", op_index to %u"), op_index);
9227                     printf ("\n");
9228                   }
9229                   break;
9230
9231                 case DW_LNS_fixed_advance_pc:
9232                   /* Takes one 16 bit parameter which is added to the
9233                      address.  */
9234                   if (unlikely (standard_opcode_lengths[opcode] != 1
9235                                 || lineendp - linep < 2))
9236                     goto invalid_unit;
9237
9238                   u128 = read_2ubyte_unaligned_inc (dbg, linep);
9239                   address += u128;
9240                   op_index = 0;
9241                   {
9242                     printf (_("\
9243  advance address by fixed value %u to \n"),
9244                             u128);
9245                     print_dwarf_addr (dwflmod, 0, address, address);
9246                     printf ("\n");
9247                   }
9248                   break;
9249
9250                 case DW_LNS_set_prologue_end:
9251                   /* Takes no argument.  */
9252                   puts (_(" set prologue end flag"));
9253                   break;
9254
9255                 case DW_LNS_set_epilogue_begin:
9256                   /* Takes no argument.  */
9257                   puts (_(" set epilogue begin flag"));
9258                   break;
9259
9260                 case DW_LNS_set_isa:
9261                   /* Takes one uleb128 parameter which is stored in isa.  */
9262                   if (unlikely (standard_opcode_lengths[opcode] != 1
9263                                 || lineendp - linep < 1))
9264                     goto invalid_unit;
9265
9266                   get_uleb128 (u128, linep, lineendp);
9267                   printf (_(" set isa to %u\n"), u128);
9268                   break;
9269                 }
9270             }
9271           else
9272             {
9273               /* This is a new opcode the generator but not we know about.
9274                  Read the parameters associated with it but then discard
9275                  everything.  Read all the parameters for this opcode.  */
9276               printf (ngettext (" unknown opcode with %" PRIu8 " parameter:",
9277                                 " unknown opcode with %" PRIu8 " parameters:",
9278                                 standard_opcode_lengths[opcode]),
9279                       standard_opcode_lengths[opcode]);
9280               for (int n = standard_opcode_lengths[opcode];
9281                    n > 0 && linep < lineendp; --n)
9282                 {
9283                   get_uleb128 (u128, linep, lineendp);
9284                   if (n != standard_opcode_lengths[opcode])
9285                     putc_unlocked (',', stdout);
9286                   printf (" %u", u128);
9287                 }
9288
9289               /* Next round, ignore this opcode.  */
9290               continue;
9291             }
9292         }
9293     }
9294
9295   /* There must only be one data block.  */
9296   assert (elf_getdata (scn, data) == NULL);
9297 }
9298
9299
9300 static void
9301 print_debug_loclists_section (Dwfl_Module *dwflmod,
9302                               Ebl *ebl,
9303                               GElf_Ehdr *ehdr __attribute__ ((unused)),
9304                               Elf_Scn *scn, GElf_Shdr *shdr,
9305                               Dwarf *dbg)
9306 {
9307   printf (_("\
9308 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
9309           elf_ndxscn (scn), section_name (ebl, shdr),
9310           (uint64_t) shdr->sh_offset);
9311
9312   Elf_Data *data = (dbg->sectiondata[IDX_debug_loclists]
9313                     ?: elf_rawdata (scn, NULL));
9314   if (unlikely (data == NULL))
9315     {
9316       error (0, 0, _("cannot get .debug_loclists content: %s"),
9317              elf_errmsg (-1));
9318       return;
9319     }
9320
9321   /* For the listptr to get the base address/CU.  */
9322   sort_listptr (&known_loclistsptr, "loclistsptr");
9323   size_t listptr_idx = 0;
9324
9325   const unsigned char *readp = data->d_buf;
9326   const unsigned char *const dataend = ((unsigned char *) data->d_buf
9327                                         + data->d_size);
9328   while (readp < dataend)
9329     {
9330       if (unlikely (readp > dataend - 4))
9331         {
9332         invalid_data:
9333           error (0, 0, _("invalid data in section [%zu] '%s'"),
9334                  elf_ndxscn (scn), section_name (ebl, shdr));
9335           return;
9336         }
9337
9338       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
9339       printf (_("Table at Offset 0x%" PRIx64 ":\n\n"),
9340               (uint64_t) offset);
9341
9342       uint64_t unit_length = read_4ubyte_unaligned_inc (dbg, readp);
9343       unsigned int offset_size = 4;
9344       if (unlikely (unit_length == 0xffffffff))
9345         {
9346           if (unlikely (readp > dataend - 8))
9347             goto invalid_data;
9348
9349           unit_length = read_8ubyte_unaligned_inc (dbg, readp);
9350           offset_size = 8;
9351         }
9352       printf (_(" Length:         %8" PRIu64 "\n"), unit_length);
9353
9354       /* We need at least 2-bytes + 1-byte + 1-byte + 4-bytes = 8
9355          bytes to complete the header.  And this unit cannot go beyond
9356          the section data.  */
9357       if (readp > dataend - 8
9358           || unit_length < 8
9359           || unit_length > (uint64_t) (dataend - readp))
9360         goto invalid_data;
9361
9362       const unsigned char *nexthdr = readp + unit_length;
9363
9364       uint16_t version = read_2ubyte_unaligned_inc (dbg, readp);
9365       printf (_(" DWARF version:  %8" PRIu16 "\n"), version);
9366
9367       if (version != 5)
9368         {
9369           error (0, 0, _("Unknown version"));
9370           goto next_table;
9371         }
9372
9373       uint8_t address_size = *readp++;
9374       printf (_(" Address size:   %8" PRIu64 "\n"),
9375               (uint64_t) address_size);
9376
9377       if (address_size != 4 && address_size != 8)
9378         {
9379           error (0, 0, _("unsupported address size"));
9380           goto next_table;
9381         }
9382
9383       uint8_t segment_size = *readp++;
9384       printf (_(" Segment size:   %8" PRIu64 "\n"),
9385               (uint64_t) segment_size);
9386
9387       if (segment_size != 0)
9388         {
9389           error (0, 0, _("unsupported segment size"));
9390           goto next_table;
9391         }
9392
9393       uint32_t offset_entry_count = read_4ubyte_unaligned_inc (dbg, readp);
9394       printf (_(" Offset entries: %8" PRIu64 "\n"),
9395               (uint64_t) offset_entry_count);
9396
9397       /* We need the CU that uses this unit to get the initial base address. */
9398       Dwarf_Addr cu_base = 0;
9399       struct Dwarf_CU *cu = NULL;
9400       if (listptr_cu (&known_loclistsptr, &listptr_idx,
9401                       (Dwarf_Off) offset,
9402                       (Dwarf_Off) (nexthdr - (unsigned char *) data->d_buf),
9403                       &cu_base, &cu)
9404           || split_dwarf_cu_base (dbg, &cu, &cu_base))
9405         {
9406           Dwarf_Die cudie;
9407           if (dwarf_cu_die (cu, &cudie,
9408                             NULL, NULL, NULL, NULL,
9409                             NULL, NULL) == NULL)
9410             printf (_(" Unknown CU base: "));
9411           else
9412             printf (_(" CU [%6" PRIx64 "] base: "),
9413                     dwarf_dieoffset (&cudie));
9414           print_dwarf_addr (dwflmod, address_size, cu_base, cu_base);
9415           printf ("\n");
9416         }
9417       else
9418         printf (_(" Not associated with a CU.\n"));
9419
9420       printf ("\n");
9421
9422       const unsigned char *offset_array_start = readp;
9423       if (offset_entry_count > 0)
9424         {
9425           uint64_t max_entries = (unit_length - 8) / offset_size;
9426           if (offset_entry_count > max_entries)
9427             {
9428               error (0, 0,
9429                      _("too many offset entries for unit length"));
9430               offset_entry_count = max_entries;
9431             }
9432
9433           printf (_("  Offsets starting at 0x%" PRIx64 ":\n"),
9434                   (uint64_t) (offset_array_start
9435                               - (unsigned char *) data->d_buf));
9436           for (uint32_t idx = 0; idx < offset_entry_count; idx++)
9437             {
9438               printf ("   [%6" PRIu32 "] ", idx);
9439               if (offset_size == 4)
9440                 {
9441                   uint32_t off = read_4ubyte_unaligned_inc (dbg, readp);
9442                   printf ("0x%" PRIx32 "\n", off);
9443                 }
9444               else
9445                 {
9446                   uint64_t off = read_8ubyte_unaligned_inc (dbg, readp);
9447                   printf ("0x%" PRIx64 "\n", off);
9448                 }
9449             }
9450           printf ("\n");
9451         }
9452
9453       Dwarf_Addr base = cu_base;
9454       bool start_of_list = true;
9455       while (readp < nexthdr)
9456         {
9457           Dwarf_Off off = (Dwarf_Off) (readp - (unsigned char *) data->d_buf);
9458           if (listptr_attr (&known_loclistsptr, listptr_idx, off,
9459                             DW_AT_GNU_locviews))
9460             {
9461               Dwarf_Off next_off = next_listptr_offset (&known_loclistsptr,
9462                                                         &listptr_idx, off);
9463               const unsigned char *locp = readp;
9464               const unsigned char *locendp;
9465               if (next_off == 0
9466                   || next_off > (size_t) (nexthdr - ((const unsigned char *)
9467                                                      data->d_buf)))
9468                 locendp = nexthdr;
9469               else
9470                 locendp = (const unsigned char *) data->d_buf + next_off;
9471
9472               printf ("  Offset: %" PRIx64 ", Index: %" PRIx64 "\n",
9473                       (uint64_t) (readp - (unsigned char *) data->d_buf),
9474                       (uint64_t) (readp - offset_array_start));
9475
9476               while (locp < locendp)
9477                 {
9478                   uint64_t v1, v2;
9479                   get_uleb128 (v1, locp, locendp);
9480                   if (locp >= locendp)
9481                     {
9482                       printf (_("    <INVALID DATA>\n"));
9483                       break;
9484                     }
9485                   get_uleb128 (v2, locp, locendp);
9486                   printf ("    view pair %" PRId64 ", %" PRId64 "\n", v1, v2);
9487                 }
9488
9489               printf ("\n");
9490               readp = (unsigned char *) locendp;
9491               continue;
9492             }
9493
9494           uint8_t kind = *readp++;
9495           uint64_t op1, op2, len;
9496
9497           /* Skip padding.  */
9498           if (start_of_list && kind == DW_LLE_end_of_list)
9499             continue;
9500
9501           if (start_of_list)
9502             {
9503               base = cu_base;
9504               printf ("  Offset: %" PRIx64 ", Index: %" PRIx64 "\n",
9505                       (uint64_t) (readp - (unsigned char *) data->d_buf - 1),
9506                       (uint64_t) (readp - offset_array_start - 1));
9507               start_of_list = false;
9508             }
9509
9510           printf ("    %s", dwarf_loc_list_encoding_name (kind));
9511           switch (kind)
9512             {
9513             case DW_LLE_end_of_list:
9514               start_of_list = true;
9515               printf ("\n\n");
9516               break;
9517
9518             case DW_LLE_base_addressx:
9519               if ((uint64_t) (nexthdr - readp) < 1)
9520                 {
9521                 invalid_entry:
9522                   error (0, 0, _("invalid loclists data"));
9523                   goto next_table;
9524                 }
9525               get_uleb128 (op1, readp, nexthdr);
9526               printf (" %" PRIx64 "\n", op1);
9527               if (! print_unresolved_addresses)
9528                 {
9529                   Dwarf_Addr addr;
9530                   if (get_indexed_addr (cu, op1, &addr) != 0)
9531                     printf ("      ???\n");
9532                   else
9533                     {
9534                       printf ("      ");
9535                       print_dwarf_addr (dwflmod, address_size, addr, addr);
9536                       printf ("\n");
9537                     }
9538                 }
9539               break;
9540
9541             case DW_LLE_startx_endx:
9542               if ((uint64_t) (nexthdr - readp) < 1)
9543                 goto invalid_entry;
9544               get_uleb128 (op1, readp, nexthdr);
9545               if ((uint64_t) (nexthdr - readp) < 1)
9546                 goto invalid_entry;
9547               get_uleb128 (op2, readp, nexthdr);
9548               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
9549               if (! print_unresolved_addresses)
9550                 {
9551                   Dwarf_Addr addr1;
9552                   Dwarf_Addr addr2;
9553                   if (get_indexed_addr (cu, op1, &addr1) != 0
9554                       || get_indexed_addr (cu, op2, &addr2) != 0)
9555                     {
9556                       printf ("      ???..\n");
9557                       printf ("      ???\n");
9558                     }
9559                   else
9560                     {
9561                       printf ("      ");
9562                       print_dwarf_addr (dwflmod, address_size, addr1, addr1);
9563                       printf ("..\n      ");
9564                       print_dwarf_addr (dwflmod, address_size,
9565                                         addr2 - 1, addr2);
9566                       printf ("\n");
9567                     }
9568                 }
9569               if ((uint64_t) (nexthdr - readp) < 1)
9570                 goto invalid_entry;
9571               get_uleb128 (len, readp, nexthdr);
9572               if ((uint64_t) (nexthdr - readp) < len)
9573                 goto invalid_entry;
9574               print_ops (dwflmod, dbg, 8, 8, version,
9575                          address_size, offset_size, cu, len, readp);
9576               readp += len;
9577               break;
9578
9579             case DW_LLE_startx_length:
9580               if ((uint64_t) (nexthdr - readp) < 1)
9581                 goto invalid_entry;
9582               get_uleb128 (op1, readp, nexthdr);
9583               if ((uint64_t) (nexthdr - readp) < 1)
9584                 goto invalid_entry;
9585               get_uleb128 (op2, readp, nexthdr);
9586               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
9587               if (! print_unresolved_addresses)
9588                 {
9589                   Dwarf_Addr addr1;
9590                   Dwarf_Addr addr2;
9591                   if (get_indexed_addr (cu, op1, &addr1) != 0)
9592                     {
9593                       printf ("      ???..\n");
9594                       printf ("      ???\n");
9595                     }
9596                   else
9597                     {
9598                       addr2 = addr1 + op2;
9599                       printf ("      ");
9600                       print_dwarf_addr (dwflmod, address_size, addr1, addr1);
9601                       printf ("..\n      ");
9602                       print_dwarf_addr (dwflmod, address_size,
9603                                         addr2 - 1, addr2);
9604                       printf ("\n");
9605                     }
9606                 }
9607               if ((uint64_t) (nexthdr - readp) < 1)
9608                 goto invalid_entry;
9609               get_uleb128 (len, readp, nexthdr);
9610               if ((uint64_t) (nexthdr - readp) < len)
9611                 goto invalid_entry;
9612               print_ops (dwflmod, dbg, 8, 8, version,
9613                          address_size, offset_size, cu, len, readp);
9614               readp += len;
9615               break;
9616
9617             case DW_LLE_offset_pair:
9618               if ((uint64_t) (nexthdr - readp) < 1)
9619                 goto invalid_entry;
9620               get_uleb128 (op1, readp, nexthdr);
9621               if ((uint64_t) (nexthdr - readp) < 1)
9622                 goto invalid_entry;
9623               get_uleb128 (op2, readp, nexthdr);
9624               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
9625               if (! print_unresolved_addresses)
9626                 {
9627                   op1 += base;
9628                   op2 += base;
9629                   printf ("      ");
9630                   print_dwarf_addr (dwflmod, address_size, op1, op1);
9631                   printf ("..\n      ");
9632                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
9633                   printf ("\n");
9634                 }
9635               if ((uint64_t) (nexthdr - readp) < 1)
9636                 goto invalid_entry;
9637               get_uleb128 (len, readp, nexthdr);
9638               if ((uint64_t) (nexthdr - readp) < len)
9639                 goto invalid_entry;
9640               print_ops (dwflmod, dbg, 8, 8, version,
9641                          address_size, offset_size, cu, len, readp);
9642               readp += len;
9643               break;
9644
9645             case DW_LLE_default_location:
9646               if ((uint64_t) (nexthdr - readp) < 1)
9647                 goto invalid_entry;
9648               get_uleb128 (len, readp, nexthdr);
9649               if ((uint64_t) (nexthdr - readp) < len)
9650                 goto invalid_entry;
9651               print_ops (dwflmod, dbg, 8, 8, version,
9652                          address_size, offset_size, cu, len, readp);
9653               readp += len;
9654               break;
9655
9656             case DW_LLE_base_address:
9657               if (address_size == 4)
9658                 {
9659                   if ((uint64_t) (nexthdr - readp) < 4)
9660                     goto invalid_entry;
9661                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
9662                 }
9663               else
9664                 {
9665                   if ((uint64_t) (nexthdr - readp) < 8)
9666                     goto invalid_entry;
9667                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
9668                 }
9669               base = op1;
9670               printf (" 0x%" PRIx64 "\n", base);
9671               if (! print_unresolved_addresses)
9672                 {
9673                   printf ("      ");
9674                   print_dwarf_addr (dwflmod, address_size, base, base);
9675                   printf ("\n");
9676                 }
9677               break;
9678
9679             case DW_LLE_start_end:
9680               if (address_size == 4)
9681                 {
9682                   if ((uint64_t) (nexthdr - readp) < 8)
9683                     goto invalid_entry;
9684                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
9685                   op2 = read_4ubyte_unaligned_inc (dbg, readp);
9686                 }
9687               else
9688                 {
9689                   if ((uint64_t) (nexthdr - readp) < 16)
9690                     goto invalid_entry;
9691                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
9692                   op2 = read_8ubyte_unaligned_inc (dbg, readp);
9693                 }
9694               printf (" 0x%" PRIx64 "..0x%" PRIx64 "\n", op1, op2);
9695               if (! print_unresolved_addresses)
9696                 {
9697                   printf ("      ");
9698                   print_dwarf_addr (dwflmod, address_size, op1, op1);
9699                   printf ("..\n      ");
9700                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
9701                   printf ("\n");
9702                 }
9703               if ((uint64_t) (nexthdr - readp) < 1)
9704                 goto invalid_entry;
9705               get_uleb128 (len, readp, nexthdr);
9706               if ((uint64_t) (nexthdr - readp) < len)
9707                 goto invalid_entry;
9708               print_ops (dwflmod, dbg, 8, 8, version,
9709                          address_size, offset_size, cu, len, readp);
9710               readp += len;
9711               break;
9712
9713             case DW_LLE_start_length:
9714               if (address_size == 4)
9715                 {
9716                   if ((uint64_t) (nexthdr - readp) < 4)
9717                     goto invalid_entry;
9718                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
9719                 }
9720               else
9721                 {
9722                   if ((uint64_t) (nexthdr - readp) < 8)
9723                     goto invalid_entry;
9724                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
9725                 }
9726               if ((uint64_t) (nexthdr - readp) < 1)
9727                 goto invalid_entry;
9728               get_uleb128 (op2, readp, nexthdr);
9729               printf (" 0x%" PRIx64 ", %" PRIx64 "\n", op1, op2);
9730               if (! print_unresolved_addresses)
9731                 {
9732                   op2 = op1 + op2;
9733                   printf ("      ");
9734                   print_dwarf_addr (dwflmod, address_size, op1, op1);
9735                   printf ("..\n      ");
9736                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
9737                   printf ("\n");
9738                 }
9739               if ((uint64_t) (nexthdr - readp) < 1)
9740                 goto invalid_entry;
9741               get_uleb128 (len, readp, nexthdr);
9742               if ((uint64_t) (nexthdr - readp) < len)
9743                 goto invalid_entry;
9744               print_ops (dwflmod, dbg, 8, 8, version,
9745                          address_size, offset_size, cu, len, readp);
9746               readp += len;
9747               break;
9748
9749             case DW_LLE_GNU_view_pair:
9750               if ((uint64_t) (nexthdr - readp) < 1)
9751                 goto invalid_entry;
9752               get_uleb128 (op1, readp, nexthdr);
9753               if ((uint64_t) (nexthdr - readp) < 1)
9754                 goto invalid_entry;
9755               get_uleb128 (op2, readp, nexthdr);
9756               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
9757               break;
9758
9759             default:
9760               goto invalid_entry;
9761             }
9762         }
9763
9764     next_table:
9765       if (readp != nexthdr)
9766         {
9767           size_t padding = nexthdr - readp;
9768           printf (_("   %zu padding bytes\n\n"), padding);
9769           readp = nexthdr;
9770         }
9771     }
9772 }
9773
9774
9775 static void
9776 print_debug_loc_section (Dwfl_Module *dwflmod,
9777                          Ebl *ebl, GElf_Ehdr *ehdr,
9778                          Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
9779 {
9780   Elf_Data *data = (dbg->sectiondata[IDX_debug_loc]
9781                     ?: elf_rawdata (scn, NULL));
9782
9783   if (unlikely (data == NULL))
9784     {
9785       error (0, 0, _("cannot get .debug_loc content: %s"),
9786              elf_errmsg (-1));
9787       return;
9788     }
9789
9790   printf (_("\
9791 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
9792           elf_ndxscn (scn), section_name (ebl, shdr),
9793           (uint64_t) shdr->sh_offset);
9794
9795   sort_listptr (&known_locsptr, "loclistptr");
9796   size_t listptr_idx = 0;
9797
9798   uint_fast8_t address_size = ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
9799   uint_fast8_t offset_size = 4;
9800
9801   bool first = true;
9802   Dwarf_Addr base = 0;
9803   unsigned char *readp = data->d_buf;
9804   unsigned char *const endp = (unsigned char *) data->d_buf + data->d_size;
9805   Dwarf_CU *last_cu = NULL;
9806   while (readp < endp)
9807     {
9808       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
9809       Dwarf_CU *cu = last_cu;
9810       unsigned int attr = 0;
9811
9812       if (first && skip_listptr_hole (&known_locsptr, &listptr_idx,
9813                                       &address_size, &offset_size, &base,
9814                                       &cu, offset, &readp, endp, &attr))
9815         continue;
9816
9817       if (last_cu != cu)
9818        {
9819         Dwarf_Die cudie;
9820         if (dwarf_cu_die (cu, &cudie,
9821                           NULL, NULL, NULL, NULL,
9822                           NULL, NULL) == NULL)
9823           printf (_("\n Unknown CU base: "));
9824         else
9825           printf (_("\n CU [%6" PRIx64 "] base: "),
9826                   dwarf_dieoffset (&cudie));
9827         print_dwarf_addr (dwflmod, address_size, base, base);
9828         printf ("\n");
9829        }
9830       last_cu = cu;
9831
9832       if (attr == DW_AT_GNU_locviews)
9833         {
9834           Dwarf_Off next_off = next_listptr_offset (&known_locsptr,
9835                                                     &listptr_idx, offset);
9836           const unsigned char *locp = readp;
9837           const unsigned char *locendp;
9838           if (next_off == 0
9839               || next_off > (size_t) (endp
9840                                       - (const unsigned char *) data->d_buf))
9841             locendp = endp;
9842           else
9843             locendp = (const unsigned char *) data->d_buf + next_off;
9844
9845           while (locp < locendp)
9846             {
9847               uint64_t v1, v2;
9848               get_uleb128 (v1, locp, locendp);
9849               if (locp >= locendp)
9850                 {
9851                   printf (_(" [%6tx]  <INVALID DATA>\n"), offset);
9852                   break;
9853                 }
9854               get_uleb128 (v2, locp, locendp);
9855               if (first)                /* First view pair in a list.  */
9856                 printf (" [%6tx] ", offset);
9857               else
9858                 printf ("          ");
9859               printf ("view pair %" PRId64 ", %" PRId64 "\n", v1, v2);
9860               first = false;
9861             }
9862
9863           first = true;
9864           readp = (unsigned char *) locendp;
9865           continue;
9866         }
9867
9868       /* GNU DebugFission encoded addresses as addrx.  */
9869       bool is_debugfission = ((cu != NULL
9870                                || split_dwarf_cu_base (dbg, &cu, &base))
9871                               && (cu->version < 5
9872                                   && cu->unit_type == DW_UT_split_compile));
9873       if (!is_debugfission
9874           && unlikely (data->d_size - offset < (size_t) address_size * 2))
9875         {
9876         invalid_data:
9877           printf (_(" [%6tx]  <INVALID DATA>\n"), offset);
9878           break;
9879         }
9880
9881       Dwarf_Addr begin;
9882       Dwarf_Addr end;
9883       bool use_base = true;
9884       if (is_debugfission)
9885         {
9886           const unsigned char *locp = readp;
9887           const unsigned char *locendp = readp + data->d_size;
9888           if (locp >= locendp)
9889             goto invalid_data;
9890
9891           Dwarf_Word idx;
9892           unsigned char code = *locp++;
9893           switch (code)
9894             {
9895             case DW_LLE_GNU_end_of_list_entry:
9896               begin = 0;
9897               end = 0;
9898               break;
9899
9900             case DW_LLE_GNU_base_address_selection_entry:
9901               if (locp >= locendp)
9902                 goto invalid_data;
9903               begin = (Dwarf_Addr) -1;
9904               get_uleb128 (idx, locp, locendp);
9905               if (get_indexed_addr (cu, idx, &end) != 0)
9906                 end = idx; /* ... */
9907               break;
9908
9909             case DW_LLE_GNU_start_end_entry:
9910               if (locp >= locendp)
9911                 goto invalid_data;
9912               get_uleb128 (idx, locp, locendp);
9913               if (get_indexed_addr (cu, idx, &begin) != 0)
9914                 begin = idx; /* ... */
9915               if (locp >= locendp)
9916                 goto invalid_data;
9917               get_uleb128 (idx, locp, locendp);
9918               if (get_indexed_addr (cu, idx, &end) != 0)
9919                 end = idx; /* ... */
9920               use_base = false;
9921               break;
9922
9923             case DW_LLE_GNU_start_length_entry:
9924               if (locp >= locendp)
9925                 goto invalid_data;
9926               get_uleb128 (idx, locp, locendp);
9927               if (get_indexed_addr (cu, idx, &begin) != 0)
9928                 begin = idx; /* ... */
9929               if (locendp - locp < 4)
9930                 goto invalid_data;
9931               end = read_4ubyte_unaligned_inc (dbg, locp);
9932               end += begin;
9933               use_base = false;
9934               break;
9935
9936             default:
9937                 goto invalid_data;
9938             }
9939
9940           readp = (unsigned char *) locp;
9941         }
9942       else if (address_size == 8)
9943         {
9944           begin = read_8ubyte_unaligned_inc (dbg, readp);
9945           end = read_8ubyte_unaligned_inc (dbg, readp);
9946         }
9947       else
9948         {
9949           begin = read_4ubyte_unaligned_inc (dbg, readp);
9950           end = read_4ubyte_unaligned_inc (dbg, readp);
9951           if (begin == (Dwarf_Addr) (uint32_t) -1)
9952             begin = (Dwarf_Addr) -1l;
9953         }
9954
9955       if (begin == (Dwarf_Addr) -1l) /* Base address entry.  */
9956         {
9957           if (first)
9958             printf (" [%6tx] ", offset);
9959           else
9960             printf ("          ");
9961           puts (_("base address"));
9962           printf ("          ");
9963           print_dwarf_addr (dwflmod, address_size, end, end);
9964           printf ("\n");
9965           base = end;
9966           first = false;
9967         }
9968       else if (begin == 0 && end == 0) /* End of list entry.  */
9969         {
9970           if (first)
9971             printf (_(" [%6tx] empty list\n"), offset);
9972           first = true;
9973         }
9974       else
9975         {
9976           /* We have a location expression entry.  */
9977           uint_fast16_t len = read_2ubyte_unaligned_inc (dbg, readp);
9978
9979           if (first)            /* First entry in a list.  */
9980             printf (" [%6tx] ", offset);
9981           else
9982             printf ("          ");
9983
9984           printf ("range %" PRIx64 ", %" PRIx64 "\n", begin, end);
9985           if (! print_unresolved_addresses)
9986             {
9987               Dwarf_Addr dab = use_base ? base + begin : begin;
9988               Dwarf_Addr dae = use_base ? base + end : end;
9989               printf ("          ");
9990               print_dwarf_addr (dwflmod, address_size, dab, dab);
9991               printf ("..\n          ");
9992               print_dwarf_addr (dwflmod, address_size, dae - 1, dae);
9993               printf ("\n");
9994             }
9995
9996           if (endp - readp <= (ptrdiff_t) len)
9997             {
9998               fputs (_("   <INVALID DATA>\n"), stdout);
9999               break;
10000             }
10001
10002           print_ops (dwflmod, dbg, 11, 11,
10003                      cu != NULL ? cu->version : 3,
10004                      address_size, offset_size, cu, len, readp);
10005
10006           first = false;
10007           readp += len;
10008         }
10009     }
10010 }
10011
10012 struct mac_culist
10013 {
10014   Dwarf_Die die;
10015   Dwarf_Off offset;
10016   Dwarf_Files *files;
10017   struct mac_culist *next;
10018 };
10019
10020
10021 static int
10022 mac_compare (const void *p1, const void *p2)
10023 {
10024   struct mac_culist *m1 = (struct mac_culist *) p1;
10025   struct mac_culist *m2 = (struct mac_culist *) p2;
10026
10027   if (m1->offset < m2->offset)
10028     return -1;
10029   if (m1->offset > m2->offset)
10030     return 1;
10031   return 0;
10032 }
10033
10034
10035 static void
10036 print_debug_macinfo_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
10037                              Ebl *ebl,
10038                              GElf_Ehdr *ehdr __attribute__ ((unused)),
10039                              Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
10040 {
10041   printf (_("\
10042 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
10043           elf_ndxscn (scn), section_name (ebl, shdr),
10044           (uint64_t) shdr->sh_offset);
10045   putc_unlocked ('\n', stdout);
10046
10047   /* There is no function in libdw to iterate over the raw content of
10048      the section but it is easy enough to do.  */
10049   Elf_Data *data = (dbg->sectiondata[IDX_debug_macinfo]
10050                     ?: elf_rawdata (scn, NULL));
10051   if (unlikely (data == NULL))
10052     {
10053       error (0, 0, _("cannot get macro information section data: %s"),
10054              elf_errmsg (-1));
10055       return;
10056     }
10057
10058   /* Get the source file information for all CUs.  */
10059   Dwarf_Off offset;
10060   Dwarf_Off ncu = 0;
10061   size_t hsize;
10062   struct mac_culist *culist = NULL;
10063   size_t nculist = 0;
10064   while (dwarf_nextcu (dbg, offset = ncu, &ncu, &hsize, NULL, NULL, NULL) == 0)
10065     {
10066       Dwarf_Die cudie;
10067       if (dwarf_offdie (dbg, offset + hsize, &cudie) == NULL)
10068         continue;
10069
10070       Dwarf_Attribute attr;
10071       if (dwarf_attr (&cudie, DW_AT_macro_info, &attr) == NULL)
10072         continue;
10073
10074       Dwarf_Word macoff;
10075       if (dwarf_formudata (&attr, &macoff) != 0)
10076         continue;
10077
10078       struct mac_culist *newp = (struct mac_culist *) alloca (sizeof (*newp));
10079       newp->die = cudie;
10080       newp->offset = macoff;
10081       newp->files = NULL;
10082       newp->next = culist;
10083       culist = newp;
10084       ++nculist;
10085     }
10086
10087   /* Convert the list into an array for easier consumption.  */
10088   struct mac_culist *cus = (struct mac_culist *) alloca ((nculist + 1)
10089                                                          * sizeof (*cus));
10090   /* Add sentinel.  */
10091   cus[nculist].offset = data->d_size;
10092   cus[nculist].files = (Dwarf_Files *) -1l;
10093   if (nculist > 0)
10094     {
10095       for (size_t cnt = nculist - 1; culist != NULL; --cnt)
10096         {
10097           assert (cnt < nculist);
10098           cus[cnt] = *culist;
10099           culist = culist->next;
10100         }
10101
10102       /* Sort the array according to the offset in the .debug_macinfo
10103          section.  Note we keep the sentinel at the end.  */
10104       qsort (cus, nculist, sizeof (*cus), mac_compare);
10105     }
10106
10107   const unsigned char *readp = (const unsigned char *) data->d_buf;
10108   const unsigned char *readendp = readp + data->d_size;
10109   int level = 1;
10110
10111   while (readp < readendp)
10112     {
10113       unsigned int opcode = *readp++;
10114       unsigned int u128;
10115       unsigned int u128_2;
10116       const unsigned char *endp;
10117
10118       switch (opcode)
10119         {
10120         case DW_MACINFO_define:
10121         case DW_MACINFO_undef:
10122         case DW_MACINFO_vendor_ext:
10123           /*  For the first two opcodes the parameters are
10124                 line, string
10125               For the latter
10126                 number, string.
10127               We can treat these cases together.  */
10128           get_uleb128 (u128, readp, readendp);
10129
10130           endp = memchr (readp, '\0', readendp - readp);
10131           if (unlikely (endp == NULL))
10132             {
10133               printf (_("\
10134 %*s*** non-terminated string at end of section"),
10135                       level, "");
10136               return;
10137             }
10138
10139           if (opcode == DW_MACINFO_define)
10140             printf ("%*s#define %s, line %u\n",
10141                     level, "", (char *) readp, u128);
10142           else if (opcode == DW_MACINFO_undef)
10143             printf ("%*s#undef %s, line %u\n",
10144                     level, "", (char *) readp, u128);
10145           else
10146             printf (" #vendor-ext %s, number %u\n", (char *) readp, u128);
10147
10148           readp = endp + 1;
10149           break;
10150
10151         case DW_MACINFO_start_file:
10152           /* The two parameters are line and file index, in this order.  */
10153           get_uleb128 (u128, readp, readendp);
10154           if (readendp - readp < 1)
10155             {
10156               printf (_("\
10157 %*s*** missing DW_MACINFO_start_file argument at end of section"),
10158                       level, "");
10159               return;
10160             }
10161           get_uleb128 (u128_2, readp, readendp);
10162
10163           /* Find the CU DIE for this file.  */
10164           size_t macoff = readp - (const unsigned char *) data->d_buf;
10165           const char *fname = "???";
10166           if (macoff >= cus[0].offset && cus[0].offset != data->d_size)
10167             {
10168               while (macoff >= cus[1].offset && cus[1].offset != data->d_size)
10169                 ++cus;
10170
10171               if (cus[0].files == NULL
10172                   && dwarf_getsrcfiles (&cus[0].die, &cus[0].files, NULL) != 0)
10173                 cus[0].files = (Dwarf_Files *) -1l;
10174
10175               if (cus[0].files != (Dwarf_Files *) -1l)
10176                 fname = (dwarf_filesrc (cus[0].files, u128_2, NULL, NULL)
10177                          ?: "???");
10178             }
10179
10180           printf ("%*sstart_file %u, [%u] %s\n",
10181                   level, "", u128, u128_2, fname);
10182           ++level;
10183           break;
10184
10185         case DW_MACINFO_end_file:
10186           --level;
10187           printf ("%*send_file\n", level, "");
10188           /* Nothing more to do.  */
10189           break;
10190
10191         default:
10192           // XXX gcc seems to generate files with a trailing zero.
10193           if (unlikely (opcode != 0 || readp != readendp))
10194             printf ("%*s*** invalid opcode %u\n", level, "", opcode);
10195           break;
10196         }
10197     }
10198 }
10199
10200
10201 static void
10202 print_debug_macro_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
10203                            Ebl *ebl,
10204                            GElf_Ehdr *ehdr __attribute__ ((unused)),
10205                            Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
10206 {
10207   printf (_("\
10208 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
10209           elf_ndxscn (scn), section_name (ebl, shdr),
10210           (uint64_t) shdr->sh_offset);
10211   putc_unlocked ('\n', stdout);
10212
10213   Elf_Data *data =  elf_getdata (scn, NULL);
10214   if (unlikely (data == NULL))
10215     {
10216       error (0, 0, _("cannot get macro information section data: %s"),
10217              elf_errmsg (-1));
10218       return;
10219     }
10220
10221   /* Get the source file information for all CUs.  Uses same
10222      datastructure as macinfo.  But uses offset field to directly
10223      match .debug_line offset.  And just stored in a list.  */
10224   Dwarf_Off offset;
10225   Dwarf_Off ncu = 0;
10226   size_t hsize;
10227   struct mac_culist *culist = NULL;
10228   size_t nculist = 0;
10229   while (dwarf_nextcu (dbg, offset = ncu, &ncu, &hsize, NULL, NULL, NULL) == 0)
10230     {
10231       Dwarf_Die cudie;
10232       if (dwarf_offdie (dbg, offset + hsize, &cudie) == NULL)
10233         continue;
10234
10235       Dwarf_Attribute attr;
10236       if (dwarf_attr (&cudie, DW_AT_stmt_list, &attr) == NULL)
10237         continue;
10238
10239       Dwarf_Word lineoff;
10240       if (dwarf_formudata (&attr, &lineoff) != 0)
10241         continue;
10242
10243       struct mac_culist *newp = (struct mac_culist *) alloca (sizeof (*newp));
10244       newp->die = cudie;
10245       newp->offset = lineoff;
10246       newp->files = NULL;
10247       newp->next = culist;
10248       culist = newp;
10249       ++nculist;
10250     }
10251
10252   const unsigned char *readp = (const unsigned char *) data->d_buf;
10253   const unsigned char *readendp = readp + data->d_size;
10254
10255   while (readp < readendp)
10256     {
10257       printf (_(" Offset:             0x%" PRIx64 "\n"),
10258               (uint64_t) (readp - (const unsigned char *) data->d_buf));
10259
10260       // Header, 2 byte version, 1 byte flag, optional .debug_line offset,
10261       // optional vendor extension macro entry table.
10262       if (readp + 2 > readendp)
10263         {
10264         invalid_data:
10265           error (0, 0, _("invalid data"));
10266           return;
10267         }
10268       const uint16_t vers = read_2ubyte_unaligned_inc (dbg, readp);
10269       printf (_(" Version:            %" PRIu16 "\n"), vers);
10270
10271       // Version 4 is the GNU extension for DWARF4.  DWARF5 will use version
10272       // 5 when it gets standardized.
10273       if (vers != 4 && vers != 5)
10274         {
10275           printf (_("  unknown version, cannot parse section\n"));
10276           return;
10277         }
10278
10279       if (readp + 1 > readendp)
10280         goto invalid_data;
10281       const unsigned char flag = *readp++;
10282       printf (_(" Flag:               0x%" PRIx8), flag);
10283       if (flag != 0)
10284         {
10285           printf (" (");
10286           if ((flag & 0x01) != 0)
10287             {
10288               printf ("offset_size");
10289               if ((flag & 0xFE) !=  0)
10290                 printf (", ");
10291             }
10292           if ((flag & 0x02) != 0)
10293             {
10294               printf ("debug_line_offset");
10295               if ((flag & 0xFC) !=  0)
10296                 printf (", ");
10297             }
10298           if ((flag & 0x04) != 0)
10299             {
10300               printf ("operands_table");
10301               if ((flag & 0xF8) !=  0)
10302                 printf (", ");
10303             }
10304           if ((flag & 0xF8) != 0)
10305             printf ("unknown");
10306           printf (")");
10307         }
10308       printf ("\n");
10309
10310       unsigned int offset_len = (flag & 0x01) ? 8 : 4;
10311       printf (_(" Offset length:      %" PRIu8 "\n"), offset_len);
10312       Dwarf_Off line_offset = -1;
10313       if (flag & 0x02)
10314         {
10315           if (offset_len == 8)
10316             line_offset = read_8ubyte_unaligned_inc (dbg, readp);
10317           else
10318             line_offset = read_4ubyte_unaligned_inc (dbg, readp);
10319           printf (_(" .debug_line offset: 0x%" PRIx64 "\n"),
10320                   line_offset);
10321         }
10322
10323       struct mac_culist *cu = NULL;
10324       if (line_offset != (Dwarf_Off) -1)
10325         {
10326           cu = culist;
10327           while (cu != NULL && line_offset != cu->offset)
10328             cu = cu->next;
10329         }
10330
10331       Dwarf_Off str_offsets_base = str_offsets_base_off (dbg, (cu != NULL
10332                                                                ? cu->die.cu
10333                                                                : NULL));
10334
10335       const unsigned char *vendor[DW_MACRO_hi_user - DW_MACRO_lo_user + 1];
10336       memset (vendor, 0, sizeof vendor);
10337       if (flag & 0x04)
10338         {
10339           // 1 byte length, for each item, 1 byte opcode, uleb128 number
10340           // of arguments, for each argument 1 byte form code.
10341           if (readp + 1 > readendp)
10342             goto invalid_data;
10343           unsigned int tlen = *readp++;
10344           printf (_("  extension opcode table, %" PRIu8 " items:\n"),
10345                   tlen);
10346           for (unsigned int i = 0; i < tlen; i++)
10347             {
10348               if (readp + 1 > readendp)
10349                 goto invalid_data;
10350               unsigned int opcode = *readp++;
10351               printf (_("    [%" PRIx8 "]"), opcode);
10352               if (opcode < DW_MACRO_lo_user
10353                   || opcode > DW_MACRO_hi_user)
10354                 goto invalid_data;
10355               // Record the start of description for this vendor opcode.
10356               // uleb128 nr args, 1 byte per arg form.
10357               vendor[opcode - DW_MACRO_lo_user] = readp;
10358               if (readp + 1 > readendp)
10359                 goto invalid_data;
10360               unsigned int args = *readp++;
10361               if (args > 0)
10362                 {
10363                   printf (_(" %" PRIu8 " arguments:"), args);
10364                   while (args > 0)
10365                     {
10366                       if (readp + 1 > readendp)
10367                         goto invalid_data;
10368                       unsigned int form = *readp++;
10369                       printf (" %s", dwarf_form_name (form));
10370                       if (! libdw_valid_user_form (form))
10371                         goto invalid_data;
10372                       args--;
10373                       if (args > 0)
10374                         putchar_unlocked (',');
10375                     }
10376                 }
10377               else
10378                 printf (_(" no arguments."));
10379               putchar_unlocked ('\n');
10380             }
10381         }
10382       putchar_unlocked ('\n');
10383
10384       int level = 1;
10385       if (readp + 1 > readendp)
10386         goto invalid_data;
10387       unsigned int opcode = *readp++;
10388       while (opcode != 0)
10389         {
10390           unsigned int u128;
10391           unsigned int u128_2;
10392           const unsigned char *endp;
10393           uint64_t off;
10394
10395           switch (opcode)
10396             {
10397             case DW_MACRO_start_file:
10398               get_uleb128 (u128, readp, readendp);
10399               if (readp >= readendp)
10400                 goto invalid_data;
10401               get_uleb128 (u128_2, readp, readendp);
10402
10403               /* Find the CU DIE that matches this line offset.  */
10404               const char *fname = "???";
10405               if (cu != NULL)
10406                 {
10407                   if (cu->files == NULL
10408                       && dwarf_getsrcfiles (&cu->die, &cu->files,
10409                                             NULL) != 0)
10410                     cu->files = (Dwarf_Files *) -1l;
10411
10412                   if (cu->files != (Dwarf_Files *) -1l)
10413                     fname = (dwarf_filesrc (cu->files, u128_2,
10414                                             NULL, NULL) ?: "???");
10415                 }
10416               printf ("%*sstart_file %u, [%u] %s\n",
10417                       level, "", u128, u128_2, fname);
10418               ++level;
10419               break;
10420
10421             case DW_MACRO_end_file:
10422               --level;
10423               printf ("%*send_file\n", level, "");
10424               break;
10425
10426             case DW_MACRO_define:
10427               get_uleb128 (u128, readp, readendp);
10428               endp = memchr (readp, '\0', readendp - readp);
10429               if (endp == NULL)
10430                 goto invalid_data;
10431               printf ("%*s#define %s, line %u\n",
10432                       level, "", readp, u128);
10433               readp = endp + 1;
10434               break;
10435
10436             case DW_MACRO_undef:
10437               get_uleb128 (u128, readp, readendp);
10438               endp = memchr (readp, '\0', readendp - readp);
10439               if (endp == NULL)
10440                 goto invalid_data;
10441               printf ("%*s#undef %s, line %u\n",
10442                       level, "", readp, u128);
10443               readp = endp + 1;
10444               break;
10445
10446             case DW_MACRO_define_strp:
10447               get_uleb128 (u128, readp, readendp);
10448               if (readp + offset_len > readendp)
10449                 goto invalid_data;
10450               if (offset_len == 8)
10451                 off = read_8ubyte_unaligned_inc (dbg, readp);
10452               else
10453                 off = read_4ubyte_unaligned_inc (dbg, readp);
10454               printf ("%*s#define %s, line %u (indirect)\n",
10455                       level, "", dwarf_getstring (dbg, off, NULL), u128);
10456               break;
10457
10458             case DW_MACRO_undef_strp:
10459               get_uleb128 (u128, readp, readendp);
10460               if (readp + offset_len > readendp)
10461                 goto invalid_data;
10462               if (offset_len == 8)
10463                 off = read_8ubyte_unaligned_inc (dbg, readp);
10464               else
10465                 off = read_4ubyte_unaligned_inc (dbg, readp);
10466               printf ("%*s#undef %s, line %u (indirect)\n",
10467                       level, "", dwarf_getstring (dbg, off, NULL), u128);
10468               break;
10469
10470             case DW_MACRO_import:
10471               if (readp + offset_len > readendp)
10472                 goto invalid_data;
10473               if (offset_len == 8)
10474                 off = read_8ubyte_unaligned_inc (dbg, readp);
10475               else
10476                 off = read_4ubyte_unaligned_inc (dbg, readp);
10477               printf ("%*s#include offset 0x%" PRIx64 "\n",
10478                       level, "", off);
10479               break;
10480
10481             case DW_MACRO_define_sup:
10482               get_uleb128 (u128, readp, readendp);
10483               if (readp + offset_len > readendp)
10484                 goto invalid_data;
10485               printf ("%*s#define ", level, "");
10486               readp =  print_form_data (dbg, DW_FORM_strp_sup,
10487                                         readp, readendp, offset_len,
10488                                         str_offsets_base);
10489               printf (", line %u (sup)\n", u128);
10490               break;
10491
10492             case DW_MACRO_undef_sup:
10493               get_uleb128 (u128, readp, readendp);
10494               if (readp + offset_len > readendp)
10495                 goto invalid_data;
10496               printf ("%*s#undef ", level, "");
10497               readp =  print_form_data (dbg, DW_FORM_strp_sup,
10498                                         readp, readendp, offset_len,
10499                                         str_offsets_base);
10500               printf (", line %u (sup)\n", u128);
10501               break;
10502
10503             case DW_MACRO_import_sup:
10504               if (readp + offset_len > readendp)
10505                 goto invalid_data;
10506               if (offset_len == 8)
10507                 off = read_8ubyte_unaligned_inc (dbg, readp);
10508               else
10509                 off = read_4ubyte_unaligned_inc (dbg, readp);
10510               // XXX Needs support for reading from supplementary object file.
10511               printf ("%*s#include offset 0x%" PRIx64 " (sup)\n",
10512                       level, "", off);
10513               break;
10514
10515             case DW_MACRO_define_strx:
10516               get_uleb128 (u128, readp, readendp);
10517               if (readp + offset_len > readendp)
10518                 goto invalid_data;
10519               printf ("%*s#define ", level, "");
10520               readp =  print_form_data (dbg, DW_FORM_strx,
10521                                         readp, readendp, offset_len,
10522                                         str_offsets_base);
10523               printf (", line %u (strx)\n", u128);
10524               break;
10525
10526             case DW_MACRO_undef_strx:
10527               get_uleb128 (u128, readp, readendp);
10528               if (readp + offset_len > readendp)
10529                 goto invalid_data;
10530               printf ("%*s#undef ", level, "");
10531               readp =  print_form_data (dbg, DW_FORM_strx,
10532                                         readp, readendp, offset_len,
10533                                         str_offsets_base);
10534               printf (", line %u (strx)\n", u128);
10535               break;
10536
10537             default:
10538               printf ("%*svendor opcode 0x%" PRIx8, level, "", opcode);
10539               if (opcode < DW_MACRO_lo_user
10540                   || opcode > DW_MACRO_lo_user
10541                   || vendor[opcode - DW_MACRO_lo_user] == NULL)
10542                 goto invalid_data;
10543
10544               const unsigned char *op_desc;
10545               op_desc = vendor[opcode - DW_MACRO_lo_user];
10546
10547               // Just skip the arguments, we cannot really interpret them,
10548               // but print as much as we can.
10549               unsigned int args = *op_desc++;
10550               while (args > 0 && readp < readendp)
10551                 {
10552                   unsigned int form = *op_desc++;
10553                   readp = print_form_data (dbg, form, readp, readendp,
10554                                            offset_len, str_offsets_base);
10555                   args--;
10556                   if (args > 0)
10557                     printf (", ");
10558                 }
10559               putchar_unlocked ('\n');
10560             }
10561
10562           if (readp + 1 > readendp)
10563             goto invalid_data;
10564           opcode = *readp++;
10565           if (opcode == 0)
10566             putchar_unlocked ('\n');
10567         }
10568     }
10569 }
10570
10571
10572 /* Callback for printing global names.  */
10573 static int
10574 print_pubnames (Dwarf *dbg __attribute__ ((unused)), Dwarf_Global *global,
10575                 void *arg)
10576 {
10577   int *np = (int *) arg;
10578
10579   printf (_(" [%5d] DIE offset: %6" PRId64
10580                    ", CU DIE offset: %6" PRId64 ", name: %s\n"),
10581           (*np)++, global->die_offset, global->cu_offset, global->name);
10582
10583   return 0;
10584 }
10585
10586
10587 /* Print the known exported symbols in the DWARF section '.debug_pubnames'.  */
10588 static void
10589 print_debug_pubnames_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
10590                               Ebl *ebl,
10591                               GElf_Ehdr *ehdr __attribute__ ((unused)),
10592                               Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
10593 {
10594   printf (_("\nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
10595           elf_ndxscn (scn), section_name (ebl, shdr),
10596           (uint64_t) shdr->sh_offset);
10597
10598   int n = 0;
10599   (void) dwarf_getpubnames (dbg, print_pubnames, &n, 0);
10600 }
10601
10602 /* Print the content of the DWARF string section '.debug_str'.  */
10603 static void
10604 print_debug_str_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
10605                          Ebl *ebl,
10606                          GElf_Ehdr *ehdr __attribute__ ((unused)),
10607                          Elf_Scn *scn, GElf_Shdr *shdr,
10608                          Dwarf *dbg __attribute__ ((unused)))
10609 {
10610   Elf_Data *data = elf_rawdata (scn, NULL);
10611   const size_t sh_size = data ? data->d_size : 0;
10612
10613   /* Compute floor(log16(shdr->sh_size)).  */
10614   GElf_Addr tmp = sh_size;
10615   int digits = 1;
10616   while (tmp >= 16)
10617     {
10618       ++digits;
10619       tmp >>= 4;
10620     }
10621   digits = MAX (4, digits);
10622
10623   printf (_("\nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"
10624                    " %*s  String\n"),
10625           elf_ndxscn (scn),
10626           section_name (ebl, shdr), (uint64_t) shdr->sh_offset,
10627           /* TRANS: the debugstr| prefix makes the string unique.  */
10628           digits + 2, sgettext ("debugstr|Offset"));
10629
10630   Dwarf_Off offset = 0;
10631   while (offset < sh_size)
10632     {
10633       size_t len;
10634       const char *str = (const char *) data->d_buf + offset;
10635       const char *endp = memchr (str, '\0', sh_size - offset);
10636       if (unlikely (endp == NULL))
10637         {
10638           printf (_(" *** error, missing string terminator\n"));
10639           break;
10640         }
10641
10642       printf (" [%*" PRIx64 "]  \"%s\"\n", digits, (uint64_t) offset, str);
10643       len = endp - str;
10644       offset += len + 1;
10645     }
10646 }
10647
10648 static void
10649 print_debug_str_offsets_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
10650                                  Ebl *ebl,
10651                                  GElf_Ehdr *ehdr __attribute__ ((unused)),
10652                                  Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
10653 {
10654   printf (_("\
10655 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
10656           elf_ndxscn (scn), section_name (ebl, shdr),
10657           (uint64_t) shdr->sh_offset);
10658
10659   if (shdr->sh_size == 0)
10660     return;
10661
10662   /* We like to get the section from libdw to make sure they are relocated.  */
10663   Elf_Data *data = (dbg->sectiondata[IDX_debug_str_offsets]
10664                     ?: elf_rawdata (scn, NULL));
10665   if (unlikely (data == NULL))
10666     {
10667       error (0, 0, _("cannot get .debug_str_offsets section data: %s"),
10668              elf_errmsg (-1));
10669       return;
10670     }
10671
10672   size_t idx = 0;
10673   sort_listptr (&known_stroffbases, "str_offsets");
10674
10675   const unsigned char *start = (const unsigned char *) data->d_buf;
10676   const unsigned char *readp = start;
10677   const unsigned char *readendp = ((const unsigned char *) data->d_buf
10678                                    + data->d_size);
10679
10680   while (readp < readendp)
10681     {
10682       /* Most string offset tables will have a header.  For split
10683          dwarf unit GNU DebugFission didn't add one.  But they were
10684          also only defined for split units (main or skeleton units
10685          didn't have indirect strings).  So if we don't have a
10686          DW_AT_str_offsets_base at all and this is offset zero, then
10687          just start printing offsets immediately, if this is a .dwo
10688          section.  */
10689       Dwarf_Off off = (Dwarf_Off) (readp
10690                                    - (const unsigned char *) data->d_buf);
10691
10692       printf ("Table at offset %" PRIx64 " ", off);
10693
10694       struct listptr *listptr = get_listptr (&known_stroffbases, idx++);
10695       const unsigned char *next_unitp = readendp;
10696       uint8_t offset_size;
10697       bool has_header;
10698       if (listptr == NULL)
10699         {
10700           /* This can happen for .dwo files.  There is only an header
10701              in the case this is a version 5 split DWARF file.  */
10702           Dwarf_CU *cu;
10703           uint8_t unit_type;
10704           if (dwarf_get_units (dbg, NULL, &cu, NULL, &unit_type,
10705                                NULL, NULL) != 0)
10706             {
10707               error (0, 0, "Warning: Cannot find any DWARF unit.");
10708               /* Just guess some values.  */
10709               has_header = false;
10710               offset_size = 4;
10711             }
10712           else if (off == 0
10713                    && (unit_type == DW_UT_split_type
10714                        || unit_type == DW_UT_split_compile))
10715             {
10716               has_header = cu->version > 4;
10717               offset_size = cu->offset_size;
10718             }
10719           else
10720             {
10721               error (0, 0,
10722                      "Warning: No CU references .debug_str_offsets after %"
10723                      PRIx64, off);
10724               has_header = cu->version > 4;
10725               offset_size = cu->offset_size;
10726             }
10727           printf ("\n");
10728         }
10729       else
10730         {
10731           /* This must be DWARF5, since GNU DebugFission didn't define
10732              DW_AT_str_offsets_base.  */
10733           has_header = true;
10734
10735           Dwarf_Die cudie;
10736           if (dwarf_cu_die (listptr->cu, &cudie,
10737                             NULL, NULL, NULL, NULL,
10738                             NULL, NULL) == NULL)
10739             printf ("Unknown CU (%s):\n", dwarf_errmsg (-1));
10740           else
10741             printf ("for CU [%6" PRIx64 "]:\n", dwarf_dieoffset (&cudie));
10742         }
10743
10744       if (has_header)
10745         {
10746           uint64_t unit_length;
10747           uint16_t version;
10748           uint16_t padding;
10749
10750           unit_length = read_4ubyte_unaligned_inc (dbg, readp);
10751           if (unlikely (unit_length == 0xffffffff))
10752             {
10753               if (unlikely (readp > readendp - 8))
10754                 {
10755                 invalid_data:
10756                   error (0, 0, "Invalid data");
10757                   return;
10758                 }
10759               unit_length = read_8ubyte_unaligned_inc (dbg, readp);
10760               offset_size = 8;
10761             }
10762           else
10763             offset_size = 4;
10764
10765           printf ("\n");
10766           printf (_(" Length:        %8" PRIu64 "\n"),
10767                   unit_length);
10768           printf (_(" Offset size:   %8" PRIu8 "\n"),
10769                   offset_size);
10770
10771           /* We need at least 2-bytes (version) + 2-bytes (padding) =
10772              4 bytes to complete the header.  And this unit cannot go
10773              beyond the section data.  */
10774           if (readp > readendp - 4
10775               || unit_length < 4
10776               || unit_length > (uint64_t) (readendp - readp))
10777             goto invalid_data;
10778
10779           next_unitp = readp + unit_length;
10780
10781           version = read_2ubyte_unaligned_inc (dbg, readp);
10782           printf (_(" DWARF version: %8" PRIu16 "\n"), version);
10783
10784           if (version != 5)
10785             {
10786               error (0, 0, _("Unknown version"));
10787               goto next_unit;
10788             }
10789
10790           padding = read_2ubyte_unaligned_inc (dbg, readp);
10791           printf (_(" Padding:       %8" PRIx16 "\n"), padding);
10792
10793           if (listptr != NULL
10794               && listptr->offset != (Dwarf_Off) (readp - start))
10795             {
10796               error (0, 0, "String offsets index doesn't start after header");
10797               goto next_unit;
10798             }
10799
10800           printf ("\n");
10801         }
10802
10803       int digits = 1;
10804       size_t offsets = (next_unitp - readp) / offset_size;
10805       while (offsets >= 10)
10806         {
10807           ++digits;
10808           offsets /= 10;
10809         }
10810
10811       unsigned int uidx = 0;
10812       size_t index_offset =  readp - (const unsigned char *) data->d_buf;
10813       printf (" Offsets start at 0x%zx:\n", index_offset);
10814       while (readp <= next_unitp - offset_size)
10815         {
10816           Dwarf_Word offset;
10817           if (offset_size == 4)
10818             offset = read_4ubyte_unaligned_inc (dbg, readp);
10819           else
10820             offset = read_8ubyte_unaligned_inc (dbg, readp);
10821           const char *str = dwarf_getstring (dbg, offset, NULL);
10822           printf (" [%*u] [%*" PRIx64 "]  \"%s\"\n",
10823                   digits, uidx++, (int) offset_size * 2, offset, str ?: "???");
10824         }
10825       printf ("\n");
10826
10827       if (readp != next_unitp)
10828         error (0, 0, "extra %zd bytes at end of unit",
10829                (size_t) (next_unitp - readp));
10830
10831     next_unit:
10832       readp = next_unitp;
10833     }
10834 }
10835
10836
10837 /* Print the content of the call frame search table section
10838    '.eh_frame_hdr'.  */
10839 static void
10840 print_debug_frame_hdr_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
10841                                Ebl *ebl __attribute__ ((unused)),
10842                                GElf_Ehdr *ehdr __attribute__ ((unused)),
10843                                Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
10844 {
10845   printf (_("\
10846 \nCall frame search table section [%2zu] '.eh_frame_hdr':\n"),
10847           elf_ndxscn (scn));
10848
10849   Elf_Data *data = elf_rawdata (scn, NULL);
10850
10851   if (unlikely (data == NULL))
10852     {
10853       error (0, 0, _("cannot get %s content: %s"),
10854              ".eh_frame_hdr", elf_errmsg (-1));
10855       return;
10856     }
10857
10858   const unsigned char *readp = data->d_buf;
10859   const unsigned char *const dataend = ((unsigned char *) data->d_buf
10860                                         + data->d_size);
10861
10862   if (unlikely (readp + 4 > dataend))
10863     {
10864     invalid_data:
10865       error (0, 0, _("invalid data"));
10866       return;
10867     }
10868
10869   unsigned int version = *readp++;
10870   unsigned int eh_frame_ptr_enc = *readp++;
10871   unsigned int fde_count_enc = *readp++;
10872   unsigned int table_enc = *readp++;
10873
10874   printf (" version:          %u\n"
10875           " eh_frame_ptr_enc: %#x ",
10876           version, eh_frame_ptr_enc);
10877   print_encoding_base ("", eh_frame_ptr_enc);
10878   printf (" fde_count_enc:    %#x ", fde_count_enc);
10879   print_encoding_base ("", fde_count_enc);
10880   printf (" table_enc:        %#x ", table_enc);
10881   print_encoding_base ("", table_enc);
10882
10883   uint64_t eh_frame_ptr = 0;
10884   if (eh_frame_ptr_enc != DW_EH_PE_omit)
10885     {
10886       readp = read_encoded (eh_frame_ptr_enc, readp, dataend, &eh_frame_ptr,
10887                             dbg);
10888       if (unlikely (readp == NULL))
10889         goto invalid_data;
10890
10891       printf (" eh_frame_ptr:     %#" PRIx64, eh_frame_ptr);
10892       if ((eh_frame_ptr_enc & 0x70) == DW_EH_PE_pcrel)
10893         printf (" (offset: %#" PRIx64 ")",
10894                 /* +4 because of the 4 byte header of the section.  */
10895                 (uint64_t) shdr->sh_offset + 4 + eh_frame_ptr);
10896
10897       putchar_unlocked ('\n');
10898     }
10899
10900   uint64_t fde_count = 0;
10901   if (fde_count_enc != DW_EH_PE_omit)
10902     {
10903       readp = read_encoded (fde_count_enc, readp, dataend, &fde_count, dbg);
10904       if (unlikely (readp == NULL))
10905         goto invalid_data;
10906
10907       printf (" fde_count:        %" PRIu64 "\n", fde_count);
10908     }
10909
10910   if (fde_count == 0 || table_enc == DW_EH_PE_omit)
10911     return;
10912
10913   puts (" Table:");
10914
10915   /* Optimize for the most common case.  */
10916   if (table_enc == (DW_EH_PE_datarel | DW_EH_PE_sdata4))
10917     while (fde_count > 0 && readp + 8 <= dataend)
10918       {
10919         int32_t initial_location = read_4sbyte_unaligned_inc (dbg, readp);
10920         uint64_t initial_offset = ((uint64_t) shdr->sh_offset
10921                                    + (int64_t) initial_location);
10922         int32_t address = read_4sbyte_unaligned_inc (dbg, readp);
10923         // XXX Possibly print symbol name or section offset for initial_offset
10924         printf ("  %#" PRIx32 " (offset: %#6" PRIx64 ") -> %#" PRIx32
10925                 " fde=[%6" PRIx64 "]\n",
10926                 initial_location, initial_offset,
10927                 address, address - (eh_frame_ptr + 4));
10928       }
10929   else
10930     while (0 && readp < dataend)
10931       {
10932
10933       }
10934 }
10935
10936
10937 /* Print the content of the exception handling table section
10938    '.eh_frame_hdr'.  */
10939 static void
10940 print_debug_exception_table (Dwfl_Module *dwflmod __attribute__ ((unused)),
10941                              Ebl *ebl __attribute__ ((unused)),
10942                              GElf_Ehdr *ehdr __attribute__ ((unused)),
10943                              Elf_Scn *scn,
10944                              GElf_Shdr *shdr __attribute__ ((unused)),
10945                              Dwarf *dbg __attribute__ ((unused)))
10946 {
10947   printf (_("\
10948 \nException handling table section [%2zu] '.gcc_except_table':\n"),
10949           elf_ndxscn (scn));
10950
10951   Elf_Data *data = elf_rawdata (scn, NULL);
10952
10953   if (unlikely (data == NULL))
10954     {
10955       error (0, 0, _("cannot get %s content: %s"),
10956              ".gcc_except_table", elf_errmsg (-1));
10957       return;
10958     }
10959
10960   const unsigned char *readp = data->d_buf;
10961   const unsigned char *const dataend = readp + data->d_size;
10962
10963   if (unlikely (readp + 1 > dataend))
10964     {
10965     invalid_data:
10966       error (0, 0, _("invalid data"));
10967       return;
10968     }
10969   unsigned int lpstart_encoding = *readp++;
10970   printf (_(" LPStart encoding:    %#x "), lpstart_encoding);
10971   print_encoding_base ("", lpstart_encoding);
10972   if (lpstart_encoding != DW_EH_PE_omit)
10973     {
10974       uint64_t lpstart;
10975       readp = read_encoded (lpstart_encoding, readp, dataend, &lpstart, dbg);
10976       printf (" LPStart:             %#" PRIx64 "\n", lpstart);
10977     }
10978
10979   if (unlikely (readp + 1 > dataend))
10980     goto invalid_data;
10981   unsigned int ttype_encoding = *readp++;
10982   printf (_(" TType encoding:      %#x "), ttype_encoding);
10983   print_encoding_base ("", ttype_encoding);
10984   const unsigned char *ttype_base = NULL;
10985   if (ttype_encoding != DW_EH_PE_omit)
10986     {
10987       unsigned int ttype_base_offset;
10988       get_uleb128 (ttype_base_offset, readp, dataend);
10989       printf (" TType base offset:   %#x\n", ttype_base_offset);
10990       if ((size_t) (dataend - readp) > ttype_base_offset)
10991         ttype_base = readp + ttype_base_offset;
10992     }
10993
10994   if (unlikely (readp + 1 > dataend))
10995     goto invalid_data;
10996   unsigned int call_site_encoding = *readp++;
10997   printf (_(" Call site encoding:  %#x "), call_site_encoding);
10998   print_encoding_base ("", call_site_encoding);
10999   unsigned int call_site_table_len;
11000   get_uleb128 (call_site_table_len, readp, dataend);
11001
11002   const unsigned char *const action_table = readp + call_site_table_len;
11003   if (unlikely (action_table > dataend))
11004     goto invalid_data;
11005   unsigned int u = 0;
11006   unsigned int max_action = 0;
11007   while (readp < action_table)
11008     {
11009       if (u == 0)
11010         puts (_("\n Call site table:"));
11011
11012       uint64_t call_site_start;
11013       readp = read_encoded (call_site_encoding, readp, dataend,
11014                             &call_site_start, dbg);
11015       uint64_t call_site_length;
11016       readp = read_encoded (call_site_encoding, readp, dataend,
11017                             &call_site_length, dbg);
11018       uint64_t landing_pad;
11019       readp = read_encoded (call_site_encoding, readp, dataend,
11020                             &landing_pad, dbg);
11021       unsigned int action;
11022       get_uleb128 (action, readp, dataend);
11023       max_action = MAX (action, max_action);
11024       printf (_(" [%4u] Call site start:   %#" PRIx64 "\n"
11025                        "        Call site length:  %" PRIu64 "\n"
11026                        "        Landing pad:       %#" PRIx64 "\n"
11027                        "        Action:            %u\n"),
11028               u++, call_site_start, call_site_length, landing_pad, action);
11029     }
11030   if (readp != action_table)
11031     goto invalid_data;
11032
11033   unsigned int max_ar_filter = 0;
11034   if (max_action > 0)
11035     {
11036       puts ("\n Action table:");
11037
11038       size_t maxdata = (size_t) (dataend - action_table);
11039       if (max_action > maxdata || maxdata - max_action < 1)
11040         {
11041         invalid_action_table:
11042           fputs (_("   <INVALID DATA>\n"), stdout);
11043           return;
11044         }
11045
11046       const unsigned char *const action_table_end
11047         = action_table + max_action + 1;
11048
11049       u = 0;
11050       do
11051         {
11052           int ar_filter;
11053           get_sleb128 (ar_filter, readp, action_table_end);
11054           if (ar_filter > 0 && (unsigned int) ar_filter > max_ar_filter)
11055             max_ar_filter = ar_filter;
11056           int ar_disp;
11057           if (readp >= action_table_end)
11058             goto invalid_action_table;
11059           get_sleb128 (ar_disp, readp, action_table_end);
11060
11061           printf (" [%4u] ar_filter:  % d\n"
11062                   "        ar_disp:    % -5d",
11063                   u, ar_filter, ar_disp);
11064           if (abs (ar_disp) & 1)
11065             printf (" -> [%4u]\n", u + (ar_disp + 1) / 2);
11066           else if (ar_disp != 0)
11067             puts (" -> ???");
11068           else
11069             putchar_unlocked ('\n');
11070           ++u;
11071         }
11072       while (readp < action_table_end);
11073     }
11074
11075   if (max_ar_filter > 0 && ttype_base != NULL)
11076     {
11077       unsigned char dsize;
11078       puts ("\n TType table:");
11079
11080       // XXX Not *4, size of encoding;
11081       switch (ttype_encoding & 7)
11082         {
11083         case DW_EH_PE_udata2:
11084         case DW_EH_PE_sdata2:
11085           dsize = 2;
11086           break;
11087         case DW_EH_PE_udata4:
11088         case DW_EH_PE_sdata4:
11089           dsize = 4;
11090           break;
11091         case DW_EH_PE_udata8:
11092         case DW_EH_PE_sdata8:
11093           dsize = 8;
11094           break;
11095         default:
11096           dsize = 0;
11097           error (1, 0, _("invalid TType encoding"));
11098         }
11099
11100       if (max_ar_filter
11101           > (size_t) (ttype_base - (const unsigned char *) data->d_buf) / dsize)
11102         goto invalid_data;
11103
11104       readp = ttype_base - max_ar_filter * dsize;
11105       do
11106         {
11107           uint64_t ttype;
11108           readp = read_encoded (ttype_encoding, readp, ttype_base, &ttype,
11109                                 dbg);
11110           printf (" [%4u] %#" PRIx64 "\n", max_ar_filter--, ttype);
11111         }
11112       while (readp < ttype_base);
11113     }
11114 }
11115
11116 /* Print the content of the '.gdb_index' section.
11117    http://sourceware.org/gdb/current/onlinedocs/gdb/Index-Section-Format.html
11118 */
11119 static void
11120 print_gdb_index_section (Dwfl_Module *dwflmod, Ebl *ebl,
11121                          GElf_Ehdr *ehdr __attribute__ ((unused)),
11122                          Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
11123 {
11124   printf (_("\nGDB section [%2zu] '%s' at offset %#" PRIx64
11125                    " contains %" PRId64 " bytes :\n"),
11126           elf_ndxscn (scn), section_name (ebl, shdr),
11127           (uint64_t) shdr->sh_offset, (uint64_t) shdr->sh_size);
11128
11129   Elf_Data *data = elf_rawdata (scn, NULL);
11130
11131   if (unlikely (data == NULL))
11132     {
11133       error (0, 0, _("cannot get %s content: %s"),
11134              ".gdb_index", elf_errmsg (-1));
11135       return;
11136     }
11137
11138   // .gdb_index is always in little endian.
11139   Dwarf dummy_dbg = { .other_byte_order = MY_ELFDATA != ELFDATA2LSB };
11140   dbg = &dummy_dbg;
11141
11142   const unsigned char *readp = data->d_buf;
11143   const unsigned char *const dataend = readp + data->d_size;
11144
11145   if (unlikely (readp + 4 > dataend))
11146     {
11147     invalid_data:
11148       error (0, 0, _("invalid data"));
11149       return;
11150     }
11151
11152   int32_t vers = read_4ubyte_unaligned (dbg, readp);
11153   printf (_(" Version:         %" PRId32 "\n"), vers);
11154
11155   // The only difference between version 4 and version 5 is the
11156   // hash used for generating the table.  Version 6 contains symbols
11157   // for inlined functions, older versions didn't.  Version 7 adds
11158   // symbol kinds.  Version 8 just indicates that it correctly includes
11159   // TUs for symbols.
11160   if (vers < 4 || vers > 8)
11161     {
11162       printf (_("  unknown version, cannot parse section\n"));
11163       return;
11164     }
11165
11166   readp += 4;
11167   if (unlikely (readp + 4 > dataend))
11168     goto invalid_data;
11169
11170   uint32_t cu_off = read_4ubyte_unaligned (dbg, readp);
11171   printf (_(" CU offset:       %#" PRIx32 "\n"), cu_off);
11172
11173   readp += 4;
11174   if (unlikely (readp + 4 > dataend))
11175     goto invalid_data;
11176
11177   uint32_t tu_off = read_4ubyte_unaligned (dbg, readp);
11178   printf (_(" TU offset:       %#" PRIx32 "\n"), tu_off);
11179
11180   readp += 4;
11181   if (unlikely (readp + 4 > dataend))
11182     goto invalid_data;
11183
11184   uint32_t addr_off = read_4ubyte_unaligned (dbg, readp);
11185   printf (_(" address offset:  %#" PRIx32 "\n"), addr_off);
11186
11187   readp += 4;
11188   if (unlikely (readp + 4 > dataend))
11189     goto invalid_data;
11190
11191   uint32_t sym_off = read_4ubyte_unaligned (dbg, readp);
11192   printf (_(" symbol offset:   %#" PRIx32 "\n"), sym_off);
11193
11194   readp += 4;
11195   if (unlikely (readp + 4 > dataend))
11196     goto invalid_data;
11197
11198   uint32_t const_off = read_4ubyte_unaligned (dbg, readp);
11199   printf (_(" constant offset: %#" PRIx32 "\n"), const_off);
11200
11201   if (unlikely ((size_t) (dataend - (const unsigned char *) data->d_buf)
11202                 < const_off))
11203     goto invalid_data;
11204
11205   readp = data->d_buf + cu_off;
11206
11207   const unsigned char *nextp = data->d_buf + tu_off;
11208   if (tu_off >= data->d_size)
11209     goto invalid_data;
11210
11211   size_t cu_nr = (nextp - readp) / 16;
11212
11213   printf (_("\n CU list at offset %#" PRIx32
11214                    " contains %zu entries:\n"),
11215           cu_off, cu_nr);
11216
11217   size_t n = 0;
11218   while (dataend - readp >= 16 && n < cu_nr)
11219     {
11220       uint64_t off = read_8ubyte_unaligned (dbg, readp);
11221       readp += 8;
11222
11223       uint64_t len = read_8ubyte_unaligned (dbg, readp);
11224       readp += 8;
11225
11226       printf (" [%4zu] start: %0#8" PRIx64
11227               ", length: %5" PRIu64 "\n", n, off, len);
11228       n++;
11229     }
11230
11231   readp = data->d_buf + tu_off;
11232   nextp = data->d_buf + addr_off;
11233   if (addr_off >= data->d_size)
11234     goto invalid_data;
11235
11236   size_t tu_nr = (nextp - readp) / 24;
11237
11238   printf (_("\n TU list at offset %#" PRIx32
11239                    " contains %zu entries:\n"),
11240           tu_off, tu_nr);
11241
11242   n = 0;
11243   while (dataend - readp >= 24 && n < tu_nr)
11244     {
11245       uint64_t off = read_8ubyte_unaligned (dbg, readp);
11246       readp += 8;
11247
11248       uint64_t type = read_8ubyte_unaligned (dbg, readp);
11249       readp += 8;
11250
11251       uint64_t sig = read_8ubyte_unaligned (dbg, readp);
11252       readp += 8;
11253
11254       printf (" [%4zu] CU offset: %5" PRId64
11255               ", type offset: %5" PRId64
11256               ", signature: %0#8" PRIx64 "\n", n, off, type, sig);
11257       n++;
11258     }
11259
11260   readp = data->d_buf + addr_off;
11261   nextp = data->d_buf + sym_off;
11262   if (sym_off >= data->d_size)
11263     goto invalid_data;
11264
11265   size_t addr_nr = (nextp - readp) / 20;
11266
11267   printf (_("\n Address list at offset %#" PRIx32
11268                    " contains %zu entries:\n"),
11269           addr_off, addr_nr);
11270
11271   n = 0;
11272   while (dataend - readp >= 20 && n < addr_nr)
11273     {
11274       uint64_t low = read_8ubyte_unaligned (dbg, readp);
11275       readp += 8;
11276
11277       uint64_t high = read_8ubyte_unaligned (dbg, readp);
11278       readp += 8;
11279
11280       uint32_t idx = read_4ubyte_unaligned (dbg, readp);
11281       readp += 4;
11282
11283       printf (" [%4zu] ", n);
11284       print_dwarf_addr (dwflmod, 8, low, low);
11285       printf ("..");
11286       print_dwarf_addr (dwflmod, 8, high - 1, high);
11287       printf (", CU index: %5" PRId32 "\n", idx);
11288       n++;
11289     }
11290
11291   const unsigned char *const_start = data->d_buf + const_off;
11292   if (const_off >= data->d_size)
11293     goto invalid_data;
11294
11295   readp = data->d_buf + sym_off;
11296   nextp = const_start;
11297   size_t sym_nr = (nextp - readp) / 8;
11298
11299   printf (_("\n Symbol table at offset %#" PRIx32
11300                    " contains %zu slots:\n"),
11301           addr_off, sym_nr);
11302
11303   n = 0;
11304   while (dataend - readp >= 8 && n < sym_nr)
11305     {
11306       uint32_t name = read_4ubyte_unaligned (dbg, readp);
11307       readp += 4;
11308
11309       uint32_t vector = read_4ubyte_unaligned (dbg, readp);
11310       readp += 4;
11311
11312       if (name != 0 || vector != 0)
11313         {
11314           const unsigned char *sym = const_start + name;
11315           if (unlikely ((size_t) (dataend - const_start) < name
11316                         || memchr (sym, '\0', dataend - sym) == NULL))
11317             goto invalid_data;
11318
11319           printf (" [%4zu] symbol: %s, CUs: ", n, sym);
11320
11321           const unsigned char *readcus = const_start + vector;
11322           if (unlikely ((size_t) (dataend - const_start) < vector))
11323             goto invalid_data;
11324           uint32_t cus = read_4ubyte_unaligned (dbg, readcus);
11325           while (cus--)
11326             {
11327               uint32_t cu_kind, cu, kind;
11328               bool is_static;
11329               readcus += 4;
11330               if (unlikely (readcus + 4 > dataend))
11331                 goto invalid_data;
11332               cu_kind = read_4ubyte_unaligned (dbg, readcus);
11333               cu = cu_kind & ((1 << 24) - 1);
11334               kind = (cu_kind >> 28) & 7;
11335               is_static = cu_kind & (1U << 31);
11336               if (cu > cu_nr - 1)
11337                 printf ("%" PRId32 "T", cu - (uint32_t) cu_nr);
11338               else
11339                 printf ("%" PRId32, cu);
11340               if (kind != 0)
11341                 {
11342                   printf (" (");
11343                   switch (kind)
11344                     {
11345                     case 1:
11346                       printf ("type");
11347                       break;
11348                     case 2:
11349                       printf ("var");
11350                       break;
11351                     case 3:
11352                       printf ("func");
11353                       break;
11354                     case 4:
11355                       printf ("other");
11356                       break;
11357                     default:
11358                       printf ("unknown-0x%" PRIx32, kind);
11359                       break;
11360                     }
11361                   printf (":%c)", (is_static ? 'S' : 'G'));
11362                 }
11363               if (cus > 0)
11364                 printf (", ");
11365             }
11366           printf ("\n");
11367         }
11368       n++;
11369     }
11370 }
11371
11372 /* Returns true and sets split DWARF CU id if there is a split compile
11373    unit in the given Dwarf, and no non-split units are found (before it).  */
11374 static bool
11375 is_split_dwarf (Dwarf *dbg, uint64_t *id, Dwarf_CU **split_cu)
11376 {
11377   Dwarf_CU *cu = NULL;
11378   while (dwarf_get_units (dbg, cu, &cu, NULL, NULL, NULL, NULL) == 0)
11379     {
11380       uint8_t unit_type;
11381       if (dwarf_cu_info (cu, NULL, &unit_type, NULL, NULL,
11382                          id, NULL, NULL) != 0)
11383         return false;
11384
11385       if (unit_type != DW_UT_split_compile && unit_type != DW_UT_split_type)
11386         return false;
11387
11388       /* We really only care about the split compile unit, the types
11389          should be fine and self sufficient.  Also they don't have an
11390          id that we can match with a skeleton unit.  */
11391       if (unit_type == DW_UT_split_compile)
11392         {
11393           *split_cu = cu;
11394           return true;
11395         }
11396     }
11397
11398   return false;
11399 }
11400
11401 /* Check that there is one and only one Dwfl_Module, return in arg.  */
11402 static int
11403 getone_dwflmod (Dwfl_Module *dwflmod,
11404                void **userdata __attribute__ ((unused)),
11405                const char *name __attribute__ ((unused)),
11406                Dwarf_Addr base __attribute__ ((unused)),
11407                void *arg)
11408 {
11409   Dwfl_Module **m = (Dwfl_Module **) arg;
11410   if (*m != NULL)
11411     return DWARF_CB_ABORT;
11412   *m = dwflmod;
11413   return DWARF_CB_OK;
11414 }
11415
11416 static void
11417 print_debug (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr)
11418 {
11419   /* Used for skeleton file, if necessary for split DWARF.  */
11420   Dwfl *skel_dwfl = NULL;
11421   Dwfl_Module *skel_mod = NULL;
11422   char *skel_name = NULL;
11423   Dwarf *split_dbg = NULL;
11424   Dwarf_CU *split_cu = NULL;
11425
11426   /* Before we start the real work get a debug context descriptor.  */
11427   Dwarf_Addr dwbias;
11428   Dwarf *dbg = dwfl_module_getdwarf (dwflmod, &dwbias);
11429   Dwarf dummy_dbg =
11430     {
11431       .elf = ebl->elf,
11432       .other_byte_order = MY_ELFDATA != ehdr->e_ident[EI_DATA]
11433     };
11434   if (dbg == NULL)
11435     {
11436       if ((print_debug_sections & ~(section_exception|section_frame)) != 0)
11437         error (0, 0, _("cannot get debug context descriptor: %s"),
11438                dwfl_errmsg (-1));
11439       dbg = &dummy_dbg;
11440     }
11441   else
11442     {
11443       /* If we are asked about a split dwarf (.dwo) file, use the user
11444          provided, or find the corresponding skeleton file. If we got
11445          a skeleton file, replace the given dwflmod and dbg, with one
11446          derived from the skeleton file to provide enough context.  */
11447       uint64_t split_id;
11448       if (is_split_dwarf (dbg, &split_id, &split_cu))
11449         {
11450           if (dwarf_skeleton != NULL)
11451             skel_name = strdup (dwarf_skeleton);
11452           else
11453             {
11454               /* Replace file.dwo with file.o and see if that matches. */
11455               const char *fname;
11456               dwfl_module_info (dwflmod, NULL, NULL, NULL, NULL, NULL,
11457                                 &fname, NULL);
11458               if (fname != NULL)
11459                 {
11460                   size_t flen = strlen (fname);
11461                   if (flen > 4 && strcmp (".dwo", fname + flen - 4) == 0)
11462                     {
11463                       skel_name = strdup (fname);
11464                       if (skel_name != NULL)
11465                         {
11466                           skel_name[flen - 3] = 'o';
11467                           skel_name[flen - 2] = '\0';
11468                         }
11469                     }
11470                 }
11471             }
11472
11473           if (skel_name != NULL)
11474             {
11475               int skel_fd = open (skel_name, O_RDONLY);
11476               if (skel_fd == -1)
11477                 fprintf (stderr, "Warning: Couldn't open DWARF skeleton file"
11478                          " '%s'\n", skel_name);
11479               else
11480                 skel_dwfl = create_dwfl (skel_fd, skel_name);
11481
11482               if (skel_dwfl != NULL)
11483                 {
11484                   if (dwfl_getmodules (skel_dwfl, &getone_dwflmod,
11485                                        &skel_mod, 0) != 0)
11486                     {
11487                       fprintf (stderr, "Warning: Bad DWARF skeleton,"
11488                                " multiple modules '%s'\n", skel_name);
11489                       dwfl_end (skel_dwfl);
11490                       skel_mod = NULL;
11491                     }
11492                 }
11493               else if (skel_fd != -1)
11494                 fprintf (stderr, "Warning: Couldn't create skeleton dwfl for"
11495                          " '%s': %s\n", skel_name, dwfl_errmsg (-1));
11496
11497               if (skel_mod != NULL)
11498                 {
11499                   Dwarf *skel_dbg = dwfl_module_getdwarf (skel_mod, &dwbias);
11500                   if (skel_dbg != NULL)
11501                     {
11502                       /* First check the skeleton CU DIE, only fetch
11503                          the split DIE if we know the id matches to
11504                          not unnecessary search for any split DIEs we
11505                          don't need. */
11506                       Dwarf_CU *cu = NULL;
11507                       while (dwarf_get_units (skel_dbg, cu, &cu,
11508                                               NULL, NULL, NULL, NULL) == 0)
11509                         {
11510                           uint8_t unit_type;
11511                           uint64_t skel_id;
11512                           if (dwarf_cu_info (cu, NULL, &unit_type, NULL, NULL,
11513                                              &skel_id, NULL, NULL) == 0
11514                               && unit_type == DW_UT_skeleton
11515                               && split_id == skel_id)
11516                             {
11517                               Dwarf_Die subdie;
11518                               if (dwarf_cu_info (cu, NULL, NULL, NULL,
11519                                                  &subdie,
11520                                                  NULL, NULL, NULL) == 0
11521                                   && dwarf_tag (&subdie) != DW_TAG_invalid)
11522                                 {
11523                                   split_dbg = dwarf_cu_getdwarf (subdie.cu);
11524                                   if (split_dbg == NULL)
11525                                     fprintf (stderr,
11526                                              "Warning: Couldn't get split_dbg:"
11527                                              " %s\n", dwarf_errmsg (-1));
11528                                   break;
11529                                 }
11530                               else
11531                                 {
11532                                   /* Everything matches up, but not
11533                                      according to libdw. Which means
11534                                      the user knew better.  So...
11535                                      Terrible hack... We can never
11536                                      destroy the underlying dwfl
11537                                      because it would free the wrong
11538                                      Dwarfs... So we leak memory...*/
11539                                   if (cu->split == NULL
11540                                       && dwarf_skeleton != NULL)
11541                                     {
11542                                       do_not_close_dwfl = true;
11543                                       __libdw_link_skel_split (cu, split_cu);
11544                                       split_dbg = dwarf_cu_getdwarf (split_cu);
11545                                       break;
11546                                     }
11547                                   else
11548                                     fprintf (stderr, "Warning: Couldn't get"
11549                                              " skeleton subdie: %s\n",
11550                                              dwarf_errmsg (-1));
11551                                 }
11552                             }
11553                         }
11554                       if (split_dbg == NULL)
11555                         fprintf (stderr, "Warning: '%s' didn't contain a skeleton for split id %" PRIx64 "\n", skel_name, split_id);
11556                     }
11557                   else
11558                     fprintf (stderr, "Warning: Couldn't get skeleton DWARF:"
11559                              " %s\n", dwfl_errmsg (-1));
11560                 }
11561             }
11562
11563           if (split_dbg != NULL)
11564             {
11565               dbg = split_dbg;
11566               dwflmod = skel_mod;
11567             }
11568           else if (skel_name == NULL)
11569             fprintf (stderr,
11570                      "Warning: split DWARF file, but no skeleton found.\n");
11571         }
11572       else if (dwarf_skeleton != NULL)
11573         fprintf (stderr, "Warning: DWARF skeleton given,"
11574                  " but not a split DWARF file\n");
11575     }
11576
11577   /* Get the section header string table index.  */
11578   size_t shstrndx;
11579   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
11580     error_exit (0, _("cannot get section header string table index"));
11581
11582   /* If the .debug_info section is listed as implicitly required then
11583      we must make sure to handle it before handling any other debug
11584      section.  Various other sections depend on the CU DIEs being
11585      scanned (silently) first.  */
11586   bool implicit_info = (implicit_debug_sections & section_info) != 0;
11587   bool explicit_info = (print_debug_sections & section_info) != 0;
11588   if (implicit_info)
11589     {
11590       Elf_Scn *scn = NULL;
11591       while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
11592         {
11593           GElf_Shdr shdr_mem;
11594           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
11595
11596           if (shdr != NULL && shdr->sh_type == SHT_PROGBITS)
11597             {
11598               const char *name = elf_strptr (ebl->elf, shstrndx,
11599                                              shdr->sh_name);
11600               if (name == NULL)
11601                 continue;
11602
11603               if (strcmp (name, ".debug_info") == 0
11604                   || strcmp (name, ".debug_info.dwo") == 0
11605                   || strcmp (name, ".zdebug_info") == 0
11606                   || strcmp (name, ".zdebug_info.dwo") == 0
11607                   || strcmp (name, ".gnu.debuglto_.debug_info") == 0)
11608                 {
11609                   print_debug_info_section (dwflmod, ebl, ehdr,
11610                                             scn, shdr, dbg);
11611                   break;
11612                 }
11613             }
11614         }
11615       print_debug_sections &= ~section_info;
11616       implicit_debug_sections &= ~section_info;
11617     }
11618
11619   /* Look through all the sections for the debugging sections to print.  */
11620   Elf_Scn *scn = NULL;
11621   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
11622     {
11623       GElf_Shdr shdr_mem;
11624       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
11625
11626       if (shdr != NULL && shdr->sh_type == SHT_PROGBITS)
11627         {
11628           static const struct
11629           {
11630             const char *name;
11631             enum section_e bitmask;
11632             void (*fp) (Dwfl_Module *, Ebl *,
11633                         GElf_Ehdr *, Elf_Scn *, GElf_Shdr *, Dwarf *);
11634           } debug_sections[] =
11635             {
11636 #define NEW_SECTION(name) \
11637               { ".debug_" #name, section_##name, print_debug_##name##_section }
11638               NEW_SECTION (abbrev),
11639               NEW_SECTION (addr),
11640               NEW_SECTION (aranges),
11641               NEW_SECTION (frame),
11642               NEW_SECTION (info),
11643               NEW_SECTION (types),
11644               NEW_SECTION (line),
11645               NEW_SECTION (loc),
11646               /* loclists is loc for DWARF5.  */
11647               { ".debug_loclists", section_loc,
11648                 print_debug_loclists_section },
11649               NEW_SECTION (pubnames),
11650               NEW_SECTION (str),
11651               /* A DWARF5 specialised debug string section.  */
11652               { ".debug_line_str", section_str,
11653                 print_debug_str_section },
11654               /* DWARF5 string offsets table.  */
11655               { ".debug_str_offsets", section_str,
11656                 print_debug_str_offsets_section },
11657               NEW_SECTION (macinfo),
11658               NEW_SECTION (macro),
11659               NEW_SECTION (ranges),
11660               /* rnglists is ranges for DWARF5.  */
11661               { ".debug_rnglists", section_ranges,
11662                 print_debug_rnglists_section },
11663               { ".eh_frame", section_frame | section_exception,
11664                 print_debug_frame_section },
11665               { ".eh_frame_hdr", section_frame | section_exception,
11666                 print_debug_frame_hdr_section },
11667               { ".gcc_except_table", section_frame | section_exception,
11668                 print_debug_exception_table },
11669               { ".gdb_index", section_gdb_index, print_gdb_index_section }
11670             };
11671           const int ndebug_sections = (sizeof (debug_sections)
11672                                        / sizeof (debug_sections[0]));
11673           const char *name = elf_strptr (ebl->elf, shstrndx,
11674                                          shdr->sh_name);
11675           if (name == NULL)
11676             continue;
11677
11678           int n;
11679           for (n = 0; n < ndebug_sections; ++n)
11680             {
11681               size_t dbglen = strlen (debug_sections[n].name);
11682               size_t scnlen = strlen (name);
11683               if ((strncmp (name, debug_sections[n].name, dbglen) == 0
11684                    && (dbglen == scnlen
11685                        || (scnlen == dbglen + 4
11686                            && strstr (name, ".dwo") == name + dbglen)))
11687                   || (name[0] == '.' && name[1] == 'z'
11688                       && debug_sections[n].name[1] == 'd'
11689                       && strncmp (&name[2], &debug_sections[n].name[1],
11690                                   dbglen - 1) == 0
11691                       && (scnlen == dbglen + 1
11692                           || (scnlen == dbglen + 5
11693                               && strstr (name, ".dwo") == name + dbglen + 1)))
11694                   || (scnlen > 14 /* .gnu.debuglto_ prefix. */
11695                       && startswith (name, ".gnu.debuglto_")
11696                       && strcmp (&name[14], debug_sections[n].name) == 0)
11697 )
11698                 {
11699                   if ((print_debug_sections | implicit_debug_sections)
11700                       & debug_sections[n].bitmask)
11701                     debug_sections[n].fp (dwflmod, ebl, ehdr, scn, shdr, dbg);
11702                   break;
11703                 }
11704             }
11705         }
11706     }
11707
11708   dwfl_end (skel_dwfl);
11709   free (skel_name);
11710
11711   /* Turn implicit and/or explicit back on in case we go over another file.  */
11712   if (implicit_info)
11713     implicit_debug_sections |= section_info;
11714   if (explicit_info)
11715     print_debug_sections |= section_info;
11716
11717   reset_listptr (&known_locsptr);
11718   reset_listptr (&known_loclistsptr);
11719   reset_listptr (&known_rangelistptr);
11720   reset_listptr (&known_rnglistptr);
11721   reset_listptr (&known_addrbases);
11722   reset_listptr (&known_stroffbases);
11723 }
11724
11725
11726 #define ITEM_INDENT             4
11727 #define WRAP_COLUMN             75
11728
11729 /* Print "NAME: FORMAT", wrapping when output text would make the line
11730    exceed WRAP_COLUMN.  Unpadded numbers look better for the core items
11731    but this function is also used for registers which should be printed
11732    aligned.  Fortunately registers output uses fixed fields width (such
11733    as %11d) for the alignment.
11734
11735    Line breaks should not depend on the particular values although that
11736    may happen in some cases of the core items.  */
11737
11738 static unsigned int
11739 __attribute__ ((format (printf, 6, 7)))
11740 print_core_item (unsigned int colno, char sep, unsigned int wrap,
11741                  size_t name_width, const char *name, const char *format, ...)
11742 {
11743   size_t len = strlen (name);
11744   if (name_width < len)
11745     name_width = len;
11746
11747   char *out;
11748   va_list ap;
11749   va_start (ap, format);
11750   int out_len = vasprintf (&out, format, ap);
11751   va_end (ap);
11752   if (out_len == -1)
11753     error_exit (0, _("memory exhausted"));
11754
11755   size_t n = name_width + sizeof ": " - 1 + out_len;
11756
11757   if (colno == 0)
11758     {
11759       printf ("%*s", ITEM_INDENT, "");
11760       colno = ITEM_INDENT + n;
11761     }
11762   else if (colno + 2 + n < wrap)
11763     {
11764       printf ("%c ", sep);
11765       colno += 2 + n;
11766     }
11767   else
11768     {
11769       printf ("\n%*s", ITEM_INDENT, "");
11770       colno = ITEM_INDENT + n;
11771     }
11772
11773   printf ("%s: %*s%s", name, (int) (name_width - len), "", out);
11774
11775   free (out);
11776
11777   return colno;
11778 }
11779
11780 static const void *
11781 convert (Elf *core, Elf_Type type, uint_fast16_t count,
11782          void *value, const void *data, size_t size)
11783 {
11784   Elf_Data valuedata =
11785     {
11786       .d_type = type,
11787       .d_buf = value,
11788       .d_size = size ?: gelf_fsize (core, type, count, EV_CURRENT),
11789       .d_version = EV_CURRENT,
11790     };
11791   Elf_Data indata =
11792     {
11793       .d_type = type,
11794       .d_buf = (void *) data,
11795       .d_size = valuedata.d_size,
11796       .d_version = EV_CURRENT,
11797     };
11798
11799   Elf_Data *d = (gelf_getclass (core) == ELFCLASS32
11800                  ? elf32_xlatetom : elf64_xlatetom)
11801     (&valuedata, &indata, elf_getident (core, NULL)[EI_DATA]);
11802   if (d == NULL)
11803     error_exit (0, _("cannot convert core note data: %s"),
11804                 elf_errmsg (-1));
11805
11806   return data + indata.d_size;
11807 }
11808
11809 typedef uint8_t GElf_Byte;
11810
11811 static unsigned int
11812 handle_core_item (Elf *core, const Ebl_Core_Item *item, const void *desc,
11813                   unsigned int colno, size_t *repeated_size)
11814 {
11815   uint_fast16_t count = item->count ?: 1;
11816   /* Ebl_Core_Item count is always a small number.
11817      Make sure the backend didn't put in some large bogus value.  */
11818   assert (count < 128);
11819
11820 #define TYPES                                                                 \
11821   DO_TYPE (BYTE, Byte, "0x%.2" PRIx8, "%" PRId8);                             \
11822   DO_TYPE (HALF, Half, "0x%.4" PRIx16, "%" PRId16);                           \
11823   DO_TYPE (WORD, Word, "0x%.8" PRIx32, "%" PRId32);                           \
11824   DO_TYPE (SWORD, Sword, "%" PRId32, "%" PRId32);                             \
11825   DO_TYPE (XWORD, Xword, "0x%.16" PRIx64, "%" PRId64);                        \
11826   DO_TYPE (SXWORD, Sxword, "%" PRId64, "%" PRId64)
11827
11828 #define DO_TYPE(NAME, Name, hex, dec) GElf_##Name Name
11829   typedef union { TYPES; } value_t;
11830   void *data = alloca (count * sizeof (value_t));
11831 #undef DO_TYPE
11832
11833 #define DO_TYPE(NAME, Name, hex, dec) \
11834     GElf_##Name *value_##Name __attribute__((unused)) = data
11835   TYPES;
11836 #undef DO_TYPE
11837
11838   size_t size = gelf_fsize (core, item->type, count, EV_CURRENT);
11839   size_t convsize = size;
11840   if (repeated_size != NULL)
11841     {
11842       if (*repeated_size > size && (item->format == 'b' || item->format == 'B'))
11843         {
11844           data = alloca (*repeated_size);
11845           count *= *repeated_size / size;
11846           convsize = count * size;
11847           *repeated_size -= convsize;
11848         }
11849       else if (item->count != 0 || item->format != '\n')
11850         *repeated_size -= size;
11851     }
11852
11853   convert (core, item->type, count, data, desc + item->offset, convsize);
11854
11855   Elf_Type type = item->type;
11856   if (type == ELF_T_ADDR)
11857     type = gelf_getclass (core) == ELFCLASS32 ? ELF_T_WORD : ELF_T_XWORD;
11858
11859   switch (item->format)
11860     {
11861     case 'd':
11862       assert (count == 1);
11863       switch (type)
11864         {
11865 #define DO_TYPE(NAME, Name, hex, dec)                                         \
11866           case ELF_T_##NAME:                                                  \
11867             colno = print_core_item (colno, ',', WRAP_COLUMN,                 \
11868                                      0, item->name, dec, value_##Name[0]); \
11869             break
11870           TYPES;
11871 #undef DO_TYPE
11872         default:
11873           abort ();
11874         }
11875       break;
11876
11877     case 'x':
11878       assert (count == 1);
11879       switch (type)
11880         {
11881 #define DO_TYPE(NAME, Name, hex, dec)                                         \
11882           case ELF_T_##NAME:                                                  \
11883             colno = print_core_item (colno, ',', WRAP_COLUMN,                 \
11884                                      0, item->name, hex, value_##Name[0]);      \
11885             break
11886           TYPES;
11887 #undef DO_TYPE
11888         default:
11889           abort ();
11890         }
11891       break;
11892
11893     case 'b':
11894     case 'B':
11895       assert (size % sizeof (unsigned int) == 0);
11896       unsigned int nbits = count * size * 8;
11897       unsigned int pop = 0;
11898       for (const unsigned int *i = data; (void *) i < data + count * size; ++i)
11899         pop += __builtin_popcount (*i);
11900       bool negate = pop > nbits / 2;
11901       const unsigned int bias = item->format == 'b';
11902
11903       {
11904         char printed[(negate ? nbits - pop : pop) * 16 + 1];
11905         char *p = printed;
11906         *p = '\0';
11907
11908         if (BYTE_ORDER != LITTLE_ENDIAN && size > sizeof (unsigned int))
11909           {
11910             assert (size == sizeof (unsigned int) * 2);
11911             for (unsigned int *i = data;
11912                  (void *) i < data + count * size; i += 2)
11913               {
11914                 unsigned int w = i[1];
11915                 i[1] = i[0];
11916                 i[0] = w;
11917               }
11918           }
11919
11920         unsigned int lastbit = 0;
11921         unsigned int run = 0;
11922         for (const unsigned int *i = data;
11923              (void *) i < data + count * size; ++i)
11924           {
11925             unsigned int bit = ((void *) i - data) * 8;
11926             unsigned int w = negate ? ~*i : *i;
11927             while (w != 0)
11928               {
11929                 /* Note that a right shift equal to (or greater than)
11930                    the number of bits of w is undefined behaviour.  In
11931                    particular when the least significant bit is bit 32
11932                    (w = 0x8000000) then w >>= n is undefined.  So
11933                    explicitly handle that case separately.  */
11934                 unsigned int n = ffs (w);
11935                 if (n < sizeof (w) * 8)
11936                   w >>= n;
11937                 else
11938                   w = 0;
11939                 bit += n;
11940
11941                 if (lastbit != 0 && lastbit + 1 == bit)
11942                   ++run;
11943                 else
11944                   {
11945                     if (lastbit == 0)
11946                       p += sprintf (p, "%u", bit - bias);
11947                     else if (run == 0)
11948                       p += sprintf (p, ",%u", bit - bias);
11949                     else
11950                       p += sprintf (p, "-%u,%u", lastbit - bias, bit - bias);
11951                     run = 0;
11952                   }
11953
11954                 lastbit = bit;
11955               }
11956           }
11957         if (lastbit > 0 && run > 0 && lastbit + 1 != nbits)
11958           p += sprintf (p, "-%u", lastbit - bias);
11959
11960         colno = print_core_item (colno, ',', WRAP_COLUMN, 0, item->name,
11961                                  negate ? "~<%s>" : "<%s>", printed);
11962       }
11963       break;
11964
11965     case 'T':
11966     case (char) ('T'|0x80):
11967       assert (count == 2);
11968       Dwarf_Word sec;
11969       Dwarf_Word usec;
11970       switch (type)
11971         {
11972 #define DO_TYPE(NAME, Name, hex, dec)                                         \
11973           case ELF_T_##NAME:                                                  \
11974             sec = value_##Name[0];                                            \
11975             usec = value_##Name[1];                                           \
11976             break
11977           TYPES;
11978 #undef DO_TYPE
11979         default:
11980           abort ();
11981         }
11982       if (unlikely (item->format == (char) ('T'|0x80)))
11983         {
11984           /* This is a hack for an ill-considered 64-bit ABI where
11985              tv_usec is actually a 32-bit field with 32 bits of padding
11986              rounding out struct timeval.  We've already converted it as
11987              a 64-bit field.  For little-endian, this just means the
11988              high half is the padding; it's presumably zero, but should
11989              be ignored anyway.  For big-endian, it means the 32-bit
11990              field went into the high half of USEC.  */
11991           GElf_Ehdr ehdr_mem;
11992           GElf_Ehdr *ehdr = gelf_getehdr (core, &ehdr_mem);
11993           if (likely (ehdr->e_ident[EI_DATA] == ELFDATA2MSB))
11994             usec >>= 32;
11995           else
11996             usec &= UINT32_MAX;
11997         }
11998       colno = print_core_item (colno, ',', WRAP_COLUMN, 0, item->name,
11999                                "%" PRIu64 ".%.6" PRIu64, sec, usec);
12000       break;
12001
12002     case 'c':
12003       assert (count == 1);
12004       colno = print_core_item (colno, ',', WRAP_COLUMN, 0, item->name,
12005                                "%c", value_Byte[0]);
12006       break;
12007
12008     case 's':
12009       colno = print_core_item (colno, ',', WRAP_COLUMN, 0, item->name,
12010                                "%.*s", (int) count, value_Byte);
12011       break;
12012
12013     case '\n':
12014       /* This is a list of strings separated by '\n'.  */
12015       assert (item->count == 0);
12016       assert (repeated_size != NULL);
12017       assert (item->name == NULL);
12018       if (unlikely (item->offset >= *repeated_size))
12019         break;
12020
12021       const char *s = desc + item->offset;
12022       size = *repeated_size - item->offset;
12023       *repeated_size = 0;
12024       while (size > 0)
12025         {
12026           const char *eol = memchr (s, '\n', size);
12027           int len = size;
12028           if (eol != NULL)
12029             len = eol - s;
12030           printf ("%*s%.*s\n", ITEM_INDENT, "", len, s);
12031           if (eol == NULL)
12032             break;
12033           size -= eol + 1 - s;
12034           s = eol + 1;
12035         }
12036
12037       colno = WRAP_COLUMN;
12038       break;
12039
12040     case 'h':
12041       break;
12042
12043     default:
12044       error (0, 0, "XXX not handling format '%c' for %s",
12045              item->format, item->name);
12046       break;
12047     }
12048
12049 #undef TYPES
12050
12051   return colno;
12052 }
12053
12054
12055 /* Sort items by group, and by layout offset within each group.  */
12056 static int
12057 compare_core_items (const void *a, const void *b)
12058 {
12059   const Ebl_Core_Item *const *p1 = a;
12060   const Ebl_Core_Item *const *p2 = b;
12061   const Ebl_Core_Item *item1 = *p1;
12062   const Ebl_Core_Item *item2 = *p2;
12063
12064   return ((item1->group == item2->group ? 0
12065            : strcmp (item1->group, item2->group))
12066           ?: (int) item1->offset - (int) item2->offset);
12067 }
12068
12069 /* Sort item groups by layout offset of the first item in the group.  */
12070 static int
12071 compare_core_item_groups (const void *a, const void *b)
12072 {
12073   const Ebl_Core_Item *const *const *p1 = a;
12074   const Ebl_Core_Item *const *const *p2 = b;
12075   const Ebl_Core_Item *const *group1 = *p1;
12076   const Ebl_Core_Item *const *group2 = *p2;
12077   const Ebl_Core_Item *item1 = *group1;
12078   const Ebl_Core_Item *item2 = *group2;
12079
12080   return (int) item1->offset - (int) item2->offset;
12081 }
12082
12083 static unsigned int
12084 handle_core_items (Elf *core, const void *desc, size_t descsz,
12085                    const Ebl_Core_Item *items, size_t nitems)
12086 {
12087   if (nitems == 0)
12088     return 0;
12089   unsigned int colno = 0;
12090
12091   /* FORMAT '\n' makes sense to be present only as a single item as it
12092      processes all the data of a note.  FORMATs 'b' and 'B' have a special case
12093      if present as a single item but they can be also processed with other
12094      items below.  */
12095   if (nitems == 1 && (items[0].format == '\n' || items[0].format == 'b'
12096                       || items[0].format == 'B'))
12097     {
12098       assert (items[0].offset == 0);
12099       size_t size = descsz;
12100       colno = handle_core_item (core, items, desc, colno, &size);
12101       /* If SIZE is not zero here there is some remaining data.  But we do not
12102          know how to process it anyway.  */
12103       return colno;
12104     }
12105   for (size_t i = 0; i < nitems; ++i)
12106     assert (items[i].format != '\n');
12107
12108   /* Sort to collect the groups together.  */
12109   const Ebl_Core_Item *sorted_items[nitems];
12110   for (size_t i = 0; i < nitems; ++i)
12111     sorted_items[i] = &items[i];
12112   qsort (sorted_items, nitems, sizeof sorted_items[0], &compare_core_items);
12113
12114   /* Collect the unique groups and sort them.  */
12115   const Ebl_Core_Item **groups[nitems];
12116   groups[0] = &sorted_items[0];
12117   size_t ngroups = 1;
12118   for (size_t i = 1; i < nitems; ++i)
12119     if (sorted_items[i]->group != sorted_items[i - 1]->group
12120         && strcmp (sorted_items[i]->group, sorted_items[i - 1]->group))
12121       groups[ngroups++] = &sorted_items[i];
12122   qsort (groups, ngroups, sizeof groups[0], &compare_core_item_groups);
12123
12124   /* Write out all the groups.  */
12125   const void *last = desc;
12126   do
12127     {
12128       for (size_t i = 0; i < ngroups; ++i)
12129         {
12130           for (const Ebl_Core_Item **item = groups[i];
12131                (item < &sorted_items[nitems]
12132                 && ((*item)->group == groups[i][0]->group
12133                     || !strcmp ((*item)->group, groups[i][0]->group)));
12134                ++item)
12135             colno = handle_core_item (core, *item, desc, colno, NULL);
12136
12137           /* Force a line break at the end of the group.  */
12138           colno = WRAP_COLUMN;
12139         }
12140
12141       if (descsz == 0)
12142         break;
12143
12144       /* This set of items consumed a certain amount of the note's data.
12145          If there is more data there, we have another unit of the same size.
12146          Loop to print that out too.  */
12147       const Ebl_Core_Item *item = &items[nitems - 1];
12148       size_t eltsz = item->offset + gelf_fsize (core, item->type,
12149                                                 item->count ?: 1, EV_CURRENT);
12150
12151       int reps = -1;
12152       do
12153         {
12154           ++reps;
12155           desc += eltsz;
12156           descsz -= eltsz;
12157         }
12158       while (descsz >= eltsz && !memcmp (desc, last, eltsz));
12159
12160       if (reps == 1)
12161         {
12162           /* For just one repeat, print it unabridged twice.  */
12163           desc -= eltsz;
12164           descsz += eltsz;
12165         }
12166       else if (reps > 1)
12167         printf (_("\n%*s... <repeats %u more times> ..."),
12168                 ITEM_INDENT, "", reps);
12169
12170       last = desc;
12171     }
12172   while (descsz > 0);
12173
12174   return colno;
12175 }
12176
12177 static unsigned int
12178 handle_bit_registers (const Ebl_Register_Location *regloc, const void *desc,
12179                       unsigned int colno)
12180 {
12181   desc += regloc->offset;
12182
12183   abort ();                     /* XXX */
12184   return colno;
12185 }
12186
12187
12188 static unsigned int
12189 handle_core_register (Ebl *ebl, Elf *core, int maxregname,
12190                       const Ebl_Register_Location *regloc, const void *desc,
12191                       unsigned int colno)
12192 {
12193   if (regloc->bits % 8 != 0)
12194     return handle_bit_registers (regloc, desc, colno);
12195
12196   desc += regloc->offset;
12197
12198   for (int reg = regloc->regno; reg < regloc->regno + regloc->count; ++reg)
12199     {
12200       char name[REGNAMESZ];
12201       int bits;
12202       int type;
12203       register_info (ebl, reg, regloc, name, &bits, &type);
12204
12205 #define TYPES                                                                 \
12206       BITS (8, BYTE, "%4" PRId8, "0x%.2" PRIx8);                              \
12207       BITS (16, HALF, "%6" PRId16, "0x%.4" PRIx16);                           \
12208       BITS (32, WORD, "%11" PRId32, " 0x%.8" PRIx32);                         \
12209       BITS (64, XWORD, "%20" PRId64, "  0x%.16" PRIx64)
12210
12211 #define BITS(bits, xtype, sfmt, ufmt)                           \
12212       uint##bits##_t b##bits; int##bits##_t b##bits##s
12213       union { TYPES; uint64_t b128[2]; } value;
12214 #undef  BITS
12215
12216       switch (type)
12217         {
12218         case DW_ATE_unsigned:
12219         case DW_ATE_signed:
12220         case DW_ATE_address:
12221           switch (bits)
12222             {
12223 #define BITS(bits, xtype, sfmt, ufmt)                                         \
12224             case bits:                                                        \
12225               desc = convert (core, ELF_T_##xtype, 1, &value, desc, 0);       \
12226               if (type == DW_ATE_signed)                                      \
12227                 colno = print_core_item (colno, ' ', WRAP_COLUMN,             \
12228                                          maxregname, name,                    \
12229                                          sfmt, value.b##bits##s);             \
12230               else                                                            \
12231                 colno = print_core_item (colno, ' ', WRAP_COLUMN,             \
12232                                          maxregname, name,                    \
12233                                          ufmt, value.b##bits);                \
12234               break
12235
12236             TYPES;
12237
12238             case 128:
12239               assert (type == DW_ATE_unsigned);
12240               desc = convert (core, ELF_T_XWORD, 2, &value, desc, 0);
12241               int be = elf_getident (core, NULL)[EI_DATA] == ELFDATA2MSB;
12242               colno = print_core_item (colno, ' ', WRAP_COLUMN,
12243                                        maxregname, name,
12244                                        "0x%.16" PRIx64 "%.16" PRIx64,
12245                                        value.b128[!be], value.b128[be]);
12246               break;
12247
12248             default:
12249               abort ();
12250 #undef  BITS
12251             }
12252           break;
12253
12254         default:
12255           /* Print each byte in hex, the whole thing in native byte order.  */
12256           assert (bits % 8 == 0);
12257           const uint8_t *bytes = desc;
12258           desc += bits / 8;
12259           char hex[bits / 4 + 1];
12260           hex[bits / 4] = '\0';
12261           int incr = 1;
12262           if (elf_getident (core, NULL)[EI_DATA] == ELFDATA2LSB)
12263             {
12264               bytes += bits / 8 - 1;
12265               incr = -1;
12266             }
12267           size_t idx = 0;
12268           for (char *h = hex; bits > 0; bits -= 8, idx += incr)
12269             {
12270               *h++ = "0123456789abcdef"[bytes[idx] >> 4];
12271               *h++ = "0123456789abcdef"[bytes[idx] & 0xf];
12272             }
12273           colno = print_core_item (colno, ' ', WRAP_COLUMN,
12274                                    maxregname, name, "0x%s", hex);
12275           break;
12276         }
12277       desc += regloc->pad;
12278
12279 #undef TYPES
12280     }
12281
12282   return colno;
12283 }
12284
12285
12286 struct register_info
12287 {
12288   const Ebl_Register_Location *regloc;
12289   const char *set;
12290   char name[REGNAMESZ];
12291   int regno;
12292   int bits;
12293   int type;
12294 };
12295
12296 static int
12297 register_bitpos (const struct register_info *r)
12298 {
12299   return (r->regloc->offset * 8
12300           + ((r->regno - r->regloc->regno)
12301              * (r->regloc->bits + r->regloc->pad * 8)));
12302 }
12303
12304 static int
12305 compare_sets_by_info (const struct register_info *r1,
12306                       const struct register_info *r2)
12307 {
12308   return ((int) r2->bits - (int) r1->bits
12309           ?: register_bitpos (r1) - register_bitpos (r2));
12310 }
12311
12312 /* Sort registers by set, and by size and layout offset within each set.  */
12313 static int
12314 compare_registers (const void *a, const void *b)
12315 {
12316   const struct register_info *r1 = a;
12317   const struct register_info *r2 = b;
12318
12319   /* Unused elements sort last.  */
12320   if (r1->regloc == NULL)
12321     return r2->regloc == NULL ? 0 : 1;
12322   if (r2->regloc == NULL)
12323     return -1;
12324
12325   return ((r1->set == r2->set ? 0 : strcmp (r1->set, r2->set))
12326           ?: compare_sets_by_info (r1, r2));
12327 }
12328
12329 /* Sort register sets by layout offset of the first register in the set.  */
12330 static int
12331 compare_register_sets (const void *a, const void *b)
12332 {
12333   const struct register_info *const *p1 = a;
12334   const struct register_info *const *p2 = b;
12335   return compare_sets_by_info (*p1, *p2);
12336 }
12337
12338 static inline bool
12339 same_set (const struct register_info *a,
12340           const struct register_info *b,
12341           const struct register_info *regs,
12342           size_t maxnreg)
12343 {
12344   return (a < &regs[maxnreg] && a->regloc != NULL
12345           && b < &regs[maxnreg] && b->regloc != NULL
12346           && a->bits == b->bits
12347           && (a->set == b->set || !strcmp (a->set, b->set)));
12348 }
12349
12350 static unsigned int
12351 handle_core_registers (Ebl *ebl, Elf *core, const void *desc,
12352                        const Ebl_Register_Location *reglocs, size_t nregloc)
12353 {
12354   if (nregloc == 0)
12355     return 0;
12356
12357   ssize_t maxnreg = ebl_register_info (ebl, 0, NULL, 0, NULL, NULL, NULL, NULL);
12358   if (maxnreg <= 0)
12359     {
12360       for (size_t i = 0; i < nregloc; ++i)
12361         if (maxnreg < reglocs[i].regno + reglocs[i].count)
12362           maxnreg = reglocs[i].regno + reglocs[i].count;
12363       assert (maxnreg > 0);
12364     }
12365
12366   struct register_info regs[maxnreg];
12367   memset (regs, 0, sizeof regs);
12368
12369   /* Sort to collect the sets together.  */
12370   int maxreg = 0;
12371   for (size_t i = 0; i < nregloc; ++i)
12372     for (int reg = reglocs[i].regno;
12373          reg < reglocs[i].regno + reglocs[i].count;
12374          ++reg)
12375       {
12376         assert (reg < maxnreg);
12377         if (reg > maxreg)
12378           maxreg = reg;
12379         struct register_info *info = &regs[reg];
12380         info->regloc = &reglocs[i];
12381         info->regno = reg;
12382         info->set = register_info (ebl, reg, &reglocs[i],
12383                                    info->name, &info->bits, &info->type);
12384       }
12385   qsort (regs, maxreg + 1, sizeof regs[0], &compare_registers);
12386
12387   /* Collect the unique sets and sort them.  */
12388   struct register_info *sets[maxreg + 1];
12389   sets[0] = &regs[0];
12390   size_t nsets = 1;
12391   for (int i = 1; i <= maxreg; ++i)
12392     if (regs[i].regloc != NULL
12393         && !same_set (&regs[i], &regs[i - 1], regs, maxnreg))
12394       sets[nsets++] = &regs[i];
12395   qsort (sets, nsets, sizeof sets[0], &compare_register_sets);
12396
12397   /* Write out all the sets.  */
12398   unsigned int colno = 0;
12399   for (size_t i = 0; i < nsets; ++i)
12400     {
12401       /* Find the longest name of a register in this set.  */
12402       size_t maxname = 0;
12403       const struct register_info *end;
12404       for (end = sets[i]; same_set (sets[i], end, regs, maxnreg); ++end)
12405         {
12406           size_t len = strlen (end->name);
12407           if (len > maxname)
12408             maxname = len;
12409         }
12410
12411       for (const struct register_info *reg = sets[i];
12412            reg < end;
12413            reg += reg->regloc->count ?: 1)
12414         colno = handle_core_register (ebl, core, maxname,
12415                                       reg->regloc, desc, colno);
12416
12417       /* Force a line break at the end of the group.  */
12418       colno = WRAP_COLUMN;
12419     }
12420
12421   return colno;
12422 }
12423
12424 static void
12425 handle_auxv_note (Ebl *ebl, Elf *core, GElf_Word descsz, GElf_Off desc_pos)
12426 {
12427   Elf_Data *data = elf_getdata_rawchunk (core, desc_pos, descsz, ELF_T_AUXV);
12428   if (data == NULL)
12429   elf_error:
12430     error_exit (0, _("cannot convert core note data: %s"), elf_errmsg (-1));
12431
12432   const size_t nauxv = descsz / gelf_fsize (core, ELF_T_AUXV, 1, EV_CURRENT);
12433   for (size_t i = 0; i < nauxv; ++i)
12434     {
12435       GElf_auxv_t av_mem;
12436       GElf_auxv_t *av = gelf_getauxv (data, i, &av_mem);
12437       if (av == NULL)
12438         goto elf_error;
12439
12440       const char *name;
12441       const char *fmt;
12442       if (ebl_auxv_info (ebl, av->a_type, &name, &fmt) == 0)
12443         {
12444           /* Unknown type.  */
12445           if (av->a_un.a_val == 0)
12446             printf ("    %" PRIu64 "\n", av->a_type);
12447           else
12448             printf ("    %" PRIu64 ": %#" PRIx64 "\n",
12449                     av->a_type, av->a_un.a_val);
12450         }
12451       else
12452         switch (fmt[0])
12453           {
12454           case '\0':            /* Normally zero.  */
12455             if (av->a_un.a_val == 0)
12456               {
12457                 printf ("    %s\n", name);
12458                 break;
12459               }
12460             FALLTHROUGH;
12461           case 'x':             /* hex */
12462           case 'p':             /* address */
12463           case 's':             /* address of string */
12464             printf ("    %s: %#" PRIx64 "\n", name, av->a_un.a_val);
12465             break;
12466           case 'u':
12467             printf ("    %s: %" PRIu64 "\n", name, av->a_un.a_val);
12468             break;
12469           case 'd':
12470             printf ("    %s: %" PRId64 "\n", name, av->a_un.a_val);
12471             break;
12472
12473           case 'b':
12474             printf ("    %s: %#" PRIx64 "  ", name, av->a_un.a_val);
12475             GElf_Xword bit = 1;
12476             const char *pfx = "<";
12477             for (const char *p = fmt + 1; *p != 0; p = strchr (p, '\0') + 1)
12478               {
12479                 if (av->a_un.a_val & bit)
12480                   {
12481                     printf ("%s%s", pfx, p);
12482                     pfx = " ";
12483                   }
12484                 bit <<= 1;
12485               }
12486             printf (">\n");
12487             break;
12488
12489           default:
12490             abort ();
12491           }
12492     }
12493 }
12494
12495 static bool
12496 buf_has_data (unsigned char const *ptr, unsigned char const *end, size_t sz)
12497 {
12498   return ptr < end && (size_t) (end - ptr) >= sz;
12499 }
12500
12501 static bool
12502 buf_read_int (Elf *core, unsigned char const **ptrp, unsigned char const *end,
12503               int *retp)
12504 {
12505   if (! buf_has_data (*ptrp, end, 4))
12506     return false;
12507
12508   *ptrp = convert (core, ELF_T_WORD, 1, retp, *ptrp, 4);
12509   return true;
12510 }
12511
12512 static bool
12513 buf_read_ulong (Elf *core, unsigned char const **ptrp, unsigned char const *end,
12514                 uint64_t *retp)
12515 {
12516   size_t sz = gelf_fsize (core, ELF_T_ADDR, 1, EV_CURRENT);
12517   if (! buf_has_data (*ptrp, end, sz))
12518     return false;
12519
12520   union
12521   {
12522     uint64_t u64;
12523     uint32_t u32;
12524   } u;
12525
12526   *ptrp = convert (core, ELF_T_ADDR, 1, &u, *ptrp, sz);
12527
12528   if (sz == 4)
12529     *retp = u.u32;
12530   else
12531     *retp = u.u64;
12532   return true;
12533 }
12534
12535 static void
12536 handle_siginfo_note (Elf *core, GElf_Word descsz, GElf_Off desc_pos)
12537 {
12538   Elf_Data *data = elf_getdata_rawchunk (core, desc_pos, descsz, ELF_T_BYTE);
12539   if (data == NULL)
12540     error_exit (0, _("cannot convert core note data: %s"), elf_errmsg (-1));
12541
12542   unsigned char const *ptr = data->d_buf;
12543   unsigned char const *const end = data->d_buf + data->d_size;
12544
12545   /* Siginfo head is three ints: signal number, error number, origin
12546      code.  */
12547   int si_signo, si_errno, si_code;
12548   if (! buf_read_int (core, &ptr, end, &si_signo)
12549       || ! buf_read_int (core, &ptr, end, &si_errno)
12550       || ! buf_read_int (core, &ptr, end, &si_code))
12551     {
12552     fail:
12553       printf ("    Not enough data in NT_SIGINFO note.\n");
12554       return;
12555     }
12556
12557   /* Next is a pointer-aligned union of structures.  On 64-bit
12558      machines, that implies a word of padding.  */
12559   if (gelf_getclass (core) == ELFCLASS64)
12560     ptr += 4;
12561
12562   printf ("    si_signo: %d, si_errno: %d, si_code: %d\n",
12563           si_signo, si_errno, si_code);
12564
12565   if (si_code > 0)
12566     switch (si_signo)
12567       {
12568       case CORE_SIGILL:
12569       case CORE_SIGFPE:
12570       case CORE_SIGSEGV:
12571       case CORE_SIGBUS:
12572         {
12573           uint64_t addr;
12574           if (! buf_read_ulong (core, &ptr, end, &addr))
12575             goto fail;
12576           printf ("    fault address: %#" PRIx64 "\n", addr);
12577           break;
12578         }
12579       default:
12580         ;
12581       }
12582   else if (si_code == CORE_SI_USER)
12583     {
12584       int pid, uid;
12585       if (! buf_read_int (core, &ptr, end, &pid)
12586           || ! buf_read_int (core, &ptr, end, &uid))
12587         goto fail;
12588       printf ("    sender PID: %d, sender UID: %d\n", pid, uid);
12589     }
12590 }
12591
12592 static void
12593 handle_file_note (Elf *core, GElf_Word descsz, GElf_Off desc_pos)
12594 {
12595   Elf_Data *data = elf_getdata_rawchunk (core, desc_pos, descsz, ELF_T_BYTE);
12596   if (data == NULL)
12597     error_exit (0, _("cannot convert core note data: %s"), elf_errmsg (-1));
12598
12599   unsigned char const *ptr = data->d_buf;
12600   unsigned char const *const end = data->d_buf + data->d_size;
12601
12602   uint64_t count, page_size;
12603   if (! buf_read_ulong (core, &ptr, end, &count)
12604       || ! buf_read_ulong (core, &ptr, end, &page_size))
12605     {
12606     fail:
12607       printf ("    Not enough data in NT_FILE note.\n");
12608       return;
12609     }
12610
12611   size_t addrsize = gelf_fsize (core, ELF_T_ADDR, 1, EV_CURRENT);
12612   uint64_t maxcount = (size_t) (end - ptr) / (3 * addrsize);
12613   if (count > maxcount)
12614     goto fail;
12615
12616   /* Where file names are stored.  */
12617   unsigned char const *const fstart = ptr + 3 * count * addrsize;
12618   char const *fptr = (char *) fstart;
12619
12620   printf ("    %" PRId64 " files:\n", count);
12621   for (uint64_t i = 0; i < count; ++i)
12622     {
12623       uint64_t mstart, mend, moffset;
12624       if (! buf_read_ulong (core, &ptr, fstart, &mstart)
12625           || ! buf_read_ulong (core, &ptr, fstart, &mend)
12626           || ! buf_read_ulong (core, &ptr, fstart, &moffset))
12627         goto fail;
12628
12629       const char *fnext = memchr (fptr, '\0', (char *) end - fptr);
12630       if (fnext == NULL)
12631         goto fail;
12632
12633       int ct = printf ("      %08" PRIx64 "-%08" PRIx64
12634                        " %08" PRIx64 " %" PRId64,
12635                        mstart, mend, moffset * page_size, mend - mstart);
12636       printf ("%*s%s\n", ct > 50 ? 3 : 53 - ct, "", fptr);
12637
12638       fptr = fnext + 1;
12639     }
12640 }
12641
12642 static void
12643 handle_core_note (Ebl *ebl, const GElf_Nhdr *nhdr,
12644                   const char *name, const void *desc)
12645 {
12646   GElf_Word regs_offset;
12647   size_t nregloc;
12648   const Ebl_Register_Location *reglocs;
12649   size_t nitems;
12650   const Ebl_Core_Item *items;
12651
12652   if (! ebl_core_note (ebl, nhdr, name, desc,
12653                        &regs_offset, &nregloc, &reglocs, &nitems, &items))
12654     return;
12655
12656   /* Pass 0 for DESCSZ when there are registers in the note,
12657      so that the ITEMS array does not describe the whole thing.
12658      For non-register notes, the actual descsz might be a multiple
12659      of the unit size, not just exactly the unit size.  */
12660   unsigned int colno = handle_core_items (ebl->elf, desc,
12661                                           nregloc == 0 ? nhdr->n_descsz : 0,
12662                                           items, nitems);
12663   if (colno != 0)
12664     putchar_unlocked ('\n');
12665
12666   colno = handle_core_registers (ebl, ebl->elf, desc + regs_offset,
12667                                  reglocs, nregloc);
12668   if (colno != 0)
12669     putchar_unlocked ('\n');
12670 }
12671
12672 static void
12673 handle_notes_data (Ebl *ebl, const GElf_Ehdr *ehdr,
12674                    GElf_Off start, Elf_Data *data)
12675 {
12676   fputs_unlocked (_("  Owner          Data size  Type\n"), stdout);
12677
12678   if (data == NULL)
12679     goto bad_note;
12680
12681   size_t offset = 0;
12682   GElf_Nhdr nhdr;
12683   size_t name_offset;
12684   size_t desc_offset;
12685   while (offset < data->d_size
12686          && (offset = gelf_getnote (data, offset,
12687                                     &nhdr, &name_offset, &desc_offset)) > 0)
12688     {
12689       const char *name = nhdr.n_namesz == 0 ? "" : data->d_buf + name_offset;
12690       const char *desc = data->d_buf + desc_offset;
12691
12692       /* GNU Build Attributes are weird, they store most of their data
12693          into the owner name field.  Extract just the owner name
12694          prefix here, then use the rest later as data.  */
12695       bool is_gnu_build_attr
12696         = startswith (name, ELF_NOTE_GNU_BUILD_ATTRIBUTE_PREFIX);
12697       const char *print_name = (is_gnu_build_attr
12698                                 ? ELF_NOTE_GNU_BUILD_ATTRIBUTE_PREFIX : name);
12699       size_t print_namesz = (is_gnu_build_attr
12700                              ? strlen (print_name) : nhdr.n_namesz);
12701
12702       char buf[100];
12703       char buf2[100];
12704       printf (_("  %-13.*s  %9" PRId32 "  %s\n"),
12705               (int) print_namesz, print_name, nhdr.n_descsz,
12706               ehdr->e_type == ET_CORE
12707               ? ebl_core_note_type_name (ebl, nhdr.n_type,
12708                                          buf, sizeof (buf))
12709               : ebl_object_note_type_name (ebl, name, nhdr.n_type,
12710                                            nhdr.n_descsz,
12711                                            buf2, sizeof (buf2)));
12712
12713       /* Filter out invalid entries.  */
12714       if (memchr (name, '\0', nhdr.n_namesz) != NULL
12715           /* XXX For now help broken Linux kernels.  */
12716           || 1)
12717         {
12718           if (ehdr->e_type == ET_CORE)
12719             {
12720               if (nhdr.n_type == NT_AUXV
12721                   && (nhdr.n_namesz == 4 /* Broken old Linux kernels.  */
12722                       || (nhdr.n_namesz == 5 && name[4] == '\0'))
12723                   && !memcmp (name, "CORE", 4))
12724                 handle_auxv_note (ebl, ebl->elf, nhdr.n_descsz,
12725                                   start + desc_offset);
12726               else if (nhdr.n_namesz == 5 && strcmp (name, "CORE") == 0)
12727                 switch (nhdr.n_type)
12728                   {
12729                   case NT_SIGINFO:
12730                     handle_siginfo_note (ebl->elf, nhdr.n_descsz,
12731                                          start + desc_offset);
12732                     break;
12733
12734                   case NT_FILE:
12735                     handle_file_note (ebl->elf, nhdr.n_descsz,
12736                                       start + desc_offset);
12737                     break;
12738
12739                   default:
12740                     handle_core_note (ebl, &nhdr, name, desc);
12741                   }
12742               else
12743                 handle_core_note (ebl, &nhdr, name, desc);
12744             }
12745           else
12746             ebl_object_note (ebl, nhdr.n_namesz, name, nhdr.n_type,
12747                              nhdr.n_descsz, desc);
12748         }
12749     }
12750
12751   if (offset == data->d_size)
12752     return;
12753
12754  bad_note:
12755   error (0, 0,
12756          _("cannot get content of note: %s"),
12757          data != NULL ? "garbage data" : elf_errmsg (-1));
12758 }
12759
12760 static void
12761 handle_notes (Ebl *ebl, GElf_Ehdr *ehdr)
12762 {
12763   /* If we have section headers, just look for SHT_NOTE sections.
12764      In a debuginfo file, the program headers are not reliable.  */
12765   if (shnum != 0)
12766     {
12767       /* Get the section header string table index.  */
12768       size_t shstrndx;
12769       if (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0)
12770         error_exit (0, _("cannot get section header string table index"));
12771
12772       Elf_Scn *scn = NULL;
12773       while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
12774         {
12775           GElf_Shdr shdr_mem;
12776           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
12777
12778           if (shdr == NULL || shdr->sh_type != SHT_NOTE)
12779             /* Not what we are looking for.  */
12780             continue;
12781
12782           if (notes_section != NULL)
12783             {
12784               char *sname = elf_strptr (ebl->elf, shstrndx, shdr->sh_name);
12785               if (sname == NULL || strcmp (sname, notes_section) != 0)
12786                 continue;
12787             }
12788
12789           printf (_("\
12790 \nNote section [%2zu] '%s' of %" PRIu64 " bytes at offset %#0" PRIx64 ":\n"),
12791                   elf_ndxscn (scn),
12792                   elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
12793                   shdr->sh_size, shdr->sh_offset);
12794
12795           handle_notes_data (ebl, ehdr, shdr->sh_offset,
12796                              elf_getdata (scn, NULL));
12797         }
12798       return;
12799     }
12800
12801   /* We have to look through the program header to find the note
12802      sections.  There can be more than one.  */
12803   for (size_t cnt = 0; cnt < phnum; ++cnt)
12804     {
12805       GElf_Phdr mem;
12806       GElf_Phdr *phdr = gelf_getphdr (ebl->elf, cnt, &mem);
12807
12808       if (phdr == NULL || phdr->p_type != PT_NOTE)
12809         /* Not what we are looking for.  */
12810         continue;
12811
12812       printf (_("\
12813 \nNote segment of %" PRIu64 " bytes at offset %#0" PRIx64 ":\n"),
12814               phdr->p_filesz, phdr->p_offset);
12815
12816       handle_notes_data (ebl, ehdr, phdr->p_offset,
12817                          elf_getdata_rawchunk (ebl->elf,
12818                                                phdr->p_offset, phdr->p_filesz,
12819                                                (phdr->p_align == 8
12820                                                 ? ELF_T_NHDR8 : ELF_T_NHDR)));
12821     }
12822 }
12823
12824
12825 static void
12826 hex_dump (const uint8_t *data, size_t len)
12827 {
12828   size_t pos = 0;
12829   while (pos < len)
12830     {
12831       printf ("  0x%08zx ", pos);
12832
12833       const size_t chunk = MIN (len - pos, 16);
12834
12835       for (size_t i = 0; i < chunk; ++i)
12836         if (i % 4 == 3)
12837           printf ("%02x ", data[pos + i]);
12838         else
12839           printf ("%02x", data[pos + i]);
12840
12841       if (chunk < 16)
12842         printf ("%*s", (int) ((16 - chunk) * 2 + (16 - chunk + 3) / 4), "");
12843
12844       for (size_t i = 0; i < chunk; ++i)
12845         {
12846           unsigned char b = data[pos + i];
12847           printf ("%c", isprint (b) ? b : '.');
12848         }
12849
12850       putchar ('\n');
12851       pos += chunk;
12852     }
12853 }
12854
12855 static void
12856 dump_data_section (Elf_Scn *scn, const GElf_Shdr *shdr, const char *name)
12857 {
12858   if (shdr->sh_size == 0 || shdr->sh_type == SHT_NOBITS)
12859     printf (_("\nSection [%zu] '%s' has no data to dump.\n"),
12860             elf_ndxscn (scn), name);
12861   else
12862     {
12863       if (print_decompress)
12864         {
12865           /* We try to decompress the section, but keep the old shdr around
12866              so we can show both the original shdr size and the uncompressed
12867              data size.   */
12868           if ((shdr->sh_flags & SHF_COMPRESSED) != 0)
12869             {
12870               if (elf_compress (scn, 0, 0) < 0)
12871                 printf ("WARNING: %s [%zd]\n",
12872                         _("Couldn't uncompress section"),
12873                         elf_ndxscn (scn));
12874             }
12875           else if (startswith (name, ".zdebug"))
12876             {
12877               if (elf_compress_gnu (scn, 0, 0) < 0)
12878                 printf ("WARNING: %s [%zd]\n",
12879                         _("Couldn't uncompress section"),
12880                         elf_ndxscn (scn));
12881             }
12882         }
12883
12884       Elf_Data *data = elf_rawdata (scn, NULL);
12885       if (data == NULL)
12886         error (0, 0, _("cannot get data for section [%zu] '%s': %s"),
12887                elf_ndxscn (scn), name, elf_errmsg (-1));
12888       else
12889         {
12890           if (data->d_size == shdr->sh_size)
12891             printf (_("\nHex dump of section [%zu] '%s', %" PRIu64
12892                              " bytes at offset %#0" PRIx64 ":\n"),
12893                     elf_ndxscn (scn), name,
12894                     shdr->sh_size, shdr->sh_offset);
12895           else
12896             printf (_("\nHex dump of section [%zu] '%s', %" PRIu64
12897                              " bytes (%zd uncompressed) at offset %#0"
12898                              PRIx64 ":\n"),
12899                     elf_ndxscn (scn), name,
12900                     shdr->sh_size, data->d_size, shdr->sh_offset);
12901           hex_dump (data->d_buf, data->d_size);
12902         }
12903     }
12904 }
12905
12906 static void
12907 print_string_section (Elf_Scn *scn, const GElf_Shdr *shdr, const char *name)
12908 {
12909   if (shdr->sh_size == 0 || shdr->sh_type == SHT_NOBITS)
12910     printf (_("\nSection [%zu] '%s' has no strings to dump.\n"),
12911             elf_ndxscn (scn), name);
12912   else
12913     {
12914       if (print_decompress)
12915         {
12916           /* We try to decompress the section, but keep the old shdr around
12917              so we can show both the original shdr size and the uncompressed
12918              data size.  */
12919           if ((shdr->sh_flags & SHF_COMPRESSED) != 0)
12920             {
12921               if (elf_compress (scn, 0, 0) < 0)
12922                 printf ("WARNING: %s [%zd]\n",
12923                         _("Couldn't uncompress section"),
12924                         elf_ndxscn (scn));
12925             }
12926           else if (startswith (name, ".zdebug"))
12927             {
12928               if (elf_compress_gnu (scn, 0, 0) < 0)
12929                 printf ("WARNING: %s [%zd]\n",
12930                         _("Couldn't uncompress section"),
12931                         elf_ndxscn (scn));
12932             }
12933         }
12934
12935       Elf_Data *data = elf_rawdata (scn, NULL);
12936       if (data == NULL)
12937         error (0, 0, _("cannot get data for section [%zu] '%s': %s"),
12938                elf_ndxscn (scn), name, elf_errmsg (-1));
12939       else
12940         {
12941           if (data->d_size == shdr->sh_size)
12942             printf (_("\nString section [%zu] '%s' contains %" PRIu64
12943                              " bytes at offset %#0" PRIx64 ":\n"),
12944                     elf_ndxscn (scn), name,
12945                     shdr->sh_size, shdr->sh_offset);
12946           else
12947             printf (_("\nString section [%zu] '%s' contains %" PRIu64
12948                              " bytes (%zd uncompressed) at offset %#0"
12949                              PRIx64 ":\n"),
12950                     elf_ndxscn (scn), name,
12951                     shdr->sh_size, data->d_size, shdr->sh_offset);
12952
12953           const char *start = data->d_buf;
12954           const char *const limit = start + data->d_size;
12955           do
12956             {
12957               const char *end = memchr (start, '\0', limit - start);
12958               const size_t pos = start - (const char *) data->d_buf;
12959               if (unlikely (end == NULL))
12960                 {
12961                   printf ("  [%6zx]- %.*s\n",
12962                           pos, (int) (limit - start), start);
12963                   break;
12964                 }
12965               printf ("  [%6zx]  %s\n", pos, start);
12966               start = end + 1;
12967             } while (start < limit);
12968         }
12969     }
12970 }
12971
12972 static void
12973 for_each_section_argument (Elf *elf, const struct section_argument *list,
12974                            void (*dump) (Elf_Scn *scn, const GElf_Shdr *shdr,
12975                                          const char *name))
12976 {
12977   /* Get the section header string table index.  */
12978   size_t shstrndx;
12979   if (elf_getshdrstrndx (elf, &shstrndx) < 0)
12980     error_exit (0, _("cannot get section header string table index"));
12981
12982   for (const struct section_argument *a = list; a != NULL; a = a->next)
12983     {
12984       Elf_Scn *scn;
12985       GElf_Shdr shdr_mem;
12986       const char *name = NULL;
12987
12988       char *endp = NULL;
12989       unsigned long int shndx = strtoul (a->arg, &endp, 0);
12990       if (endp != a->arg && *endp == '\0')
12991         {
12992           scn = elf_getscn (elf, shndx);
12993           if (scn == NULL)
12994             {
12995               error (0, 0, _("\nsection [%lu] does not exist"), shndx);
12996               continue;
12997             }
12998
12999           if (gelf_getshdr (scn, &shdr_mem) == NULL)
13000             error_exit (0, _("cannot get section header: %s"),
13001                         elf_errmsg (-1));
13002           name = elf_strptr (elf, shstrndx, shdr_mem.sh_name);
13003           (*dump) (scn, &shdr_mem, name);
13004         }
13005       else
13006         {
13007           /* Need to look up the section by name.  */
13008           scn = NULL;
13009           bool found = false;
13010           while ((scn = elf_nextscn (elf, scn)) != NULL)
13011             {
13012               if (gelf_getshdr (scn, &shdr_mem) == NULL)
13013                 continue;
13014               name = elf_strptr (elf, shstrndx, shdr_mem.sh_name);
13015               if (name == NULL)
13016                 continue;
13017               if (!strcmp (name, a->arg))
13018                 {
13019                   found = true;
13020                   (*dump) (scn, &shdr_mem, name);
13021                 }
13022             }
13023
13024           if (unlikely (!found) && !a->implicit)
13025             error (0, 0, _("\nsection '%s' does not exist"), a->arg);
13026         }
13027     }
13028 }
13029
13030 static void
13031 dump_data (Ebl *ebl)
13032 {
13033   for_each_section_argument (ebl->elf, dump_data_sections, &dump_data_section);
13034 }
13035
13036 static void
13037 dump_strings (Ebl *ebl)
13038 {
13039   for_each_section_argument (ebl->elf, string_sections, &print_string_section);
13040 }
13041
13042 static void
13043 print_strings (Ebl *ebl)
13044 {
13045   /* Get the section header string table index.  */
13046   size_t shstrndx;
13047   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
13048     error_exit (0, _("cannot get section header string table index"));
13049
13050   Elf_Scn *scn;
13051   GElf_Shdr shdr_mem;
13052   const char *name;
13053   scn = NULL;
13054   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
13055     {
13056       if (gelf_getshdr (scn, &shdr_mem) == NULL)
13057         continue;
13058
13059       if (shdr_mem.sh_type != SHT_PROGBITS
13060           || !(shdr_mem.sh_flags & SHF_STRINGS))
13061         continue;
13062
13063       name = elf_strptr (ebl->elf, shstrndx, shdr_mem.sh_name);
13064       if (name == NULL)
13065         continue;
13066
13067       print_string_section (scn, &shdr_mem, name);
13068     }
13069 }
13070
13071 static void
13072 dump_archive_index (Elf *elf, const char *fname)
13073 {
13074   size_t narsym;
13075   const Elf_Arsym *arsym = elf_getarsym (elf, &narsym);
13076   if (arsym == NULL)
13077     {
13078       int result = elf_errno ();
13079       if (unlikely (result != ELF_E_NO_INDEX))
13080         error_exit (0, _("cannot get symbol index of archive '%s': %s"),
13081                     fname, elf_errmsg (result));
13082       else
13083         printf (_("\nArchive '%s' has no symbol index\n"), fname);
13084       return;
13085     }
13086
13087   printf (_("\nIndex of archive '%s' has %zu entries:\n"),
13088           fname, narsym);
13089
13090   size_t as_off = 0;
13091   for (const Elf_Arsym *s = arsym; s < &arsym[narsym - 1]; ++s)
13092     {
13093       if (s->as_off != as_off)
13094         {
13095           as_off = s->as_off;
13096
13097           Elf *subelf = NULL;
13098           if (unlikely (elf_rand (elf, as_off) == 0)
13099               || unlikely ((subelf = elf_begin (-1, ELF_C_READ_MMAP, elf))
13100                            == NULL))
13101 #if __GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 7)
13102             while (1)
13103 #endif
13104               error_exit (0,
13105                           _("cannot extract member at offset %zu in '%s': %s"),
13106                           as_off, fname, elf_errmsg (-1));
13107
13108           const Elf_Arhdr *h = elf_getarhdr (subelf);
13109
13110           printf (_("Archive member '%s' contains:\n"), h->ar_name);
13111
13112           elf_end (subelf);
13113         }
13114
13115       printf ("\t%s\n", s->as_name);
13116     }
13117 }
13118
13119 #include "debugpred.h"