readelf: Define dyn_mem outside the while loop.
[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 <libintl.h>
34 #include <locale.h>
35 #include <stdarg.h>
36 #include <stdbool.h>
37 #include <stdio.h>
38 #include <stdio_ext.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <strings.h>
42 #include <time.h>
43 #include <unistd.h>
44 #include <sys/stat.h>
45 #include <signal.h>
46
47 #include <libeu.h>
48 #include <system.h>
49 #include <printversion.h>
50 #include "../libelf/libelfP.h"
51 #include "../libelf/common.h"
52 #include "../libebl/libeblP.h"
53 #include "../libdwelf/libdwelf.h"
54 #include "../libdw/libdwP.h"
55 #include "../libdwfl/libdwflP.h"
56 #include "../libdw/memory-access.h"
57
58 #include "../libdw/known-dwarf.h"
59
60 #ifdef __linux__
61 #define CORE_SIGILL  SIGILL
62 #define CORE_SIGBUS  SIGBUS
63 #define CORE_SIGFPE  SIGFPE
64 #define CORE_SIGSEGV SIGSEGV
65 #define CORE_SI_USER SI_USER
66 #else
67 /* We want the linux version of those as that is what shows up in the core files. */
68 #define CORE_SIGILL  4  /* Illegal instruction (ANSI).  */
69 #define CORE_SIGBUS  7  /* BUS error (4.2 BSD).  */
70 #define CORE_SIGFPE  8  /* Floating-point exception (ANSI).  */
71 #define CORE_SIGSEGV 11 /* Segmentation violation (ANSI).  */
72 #define CORE_SI_USER 0  /* Sent by kill, sigsend.  */
73 #endif
74
75 /* Name and version of program.  */
76 ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
77
78 /* Bug report address.  */
79 ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
80
81 /* argp key value for --elf-section, non-ascii.  */
82 #define ELF_INPUT_SECTION 256
83
84 /* argp key value for --dwarf-skeleton, non-ascii.  */
85 #define DWARF_SKELETON 257
86
87 /* argp key value for --dyn-syms, non-ascii.  */
88 #define PRINT_DYNSYM_TABLE 258
89
90 /* Terrible hack for hooking unrelated skeleton/split compile units,
91    see __libdw_link_skel_split in print_debug.  */
92 static bool do_not_close_dwfl = false;
93
94 /* Definitions of arguments for argp functions.  */
95 static const struct argp_option options[] =
96 {
97   { NULL, 0, NULL, 0, N_("ELF input selection:"), 0 },
98   { "elf-section", ELF_INPUT_SECTION, "SECTION", OPTION_ARG_OPTIONAL,
99     N_("Use the named SECTION (default .gnu_debugdata) as (compressed) ELF "
100        "input data"), 0 },
101   { "dwarf-skeleton", DWARF_SKELETON, "FILE", 0,
102     N_("Used with -w to find the skeleton Compile Units in FILE associated "
103        "with the Split Compile units in a .dwo input file"), 0 },
104   { NULL, 0, NULL, 0, N_("ELF output selection:"), 0 },
105   { "all", 'a', NULL, 0,
106     N_("All these plus -p .strtab -p .dynstr -p .comment"), 0 },
107   { "dynamic", 'd', NULL, 0, N_("Display the dynamic segment"), 0 },
108   { "file-header", 'h', NULL, 0, N_("Display the ELF file header"), 0 },
109   { "histogram", 'I', NULL, 0,
110     N_("Display histogram of bucket list lengths"), 0 },
111   { "program-headers", 'l', NULL, 0, N_("Display the program headers"), 0 },
112   { "segments", 'l', NULL, OPTION_ALIAS | OPTION_HIDDEN, NULL, 0 },
113   { "relocs", 'r', NULL, 0, N_("Display relocations"), 0 },
114   { "section-groups", 'g', NULL, 0, N_("Display the section groups"), 0 },
115   { "section-headers", 'S', NULL, 0, N_("Display the sections' headers"), 0 },
116   { "sections", 'S', NULL, OPTION_ALIAS | OPTION_HIDDEN, NULL, 0 },
117   { "symbols", 's', "SECTION", OPTION_ARG_OPTIONAL,
118     N_("Display the symbol table sections"), 0 },
119   { "dyn-syms", PRINT_DYNSYM_TABLE, NULL, 0,
120     N_("Display (only) the dynamic symbol table"), 0 },
121   { "version-info", 'V', NULL, 0, N_("Display versioning information"), 0 },
122   { "notes", 'n', "SECTION", OPTION_ARG_OPTIONAL, N_("Display the ELF notes"), 0 },
123   { "arch-specific", 'A', NULL, 0,
124     N_("Display architecture specific information, if any"), 0 },
125   { "exception", 'e', NULL, 0,
126     N_("Display sections for exception handling"), 0 },
127
128   { NULL, 0, NULL, 0, N_("Additional output selection:"), 0 },
129   { "debug-dump", 'w', "SECTION", OPTION_ARG_OPTIONAL,
130     N_("Display DWARF section content.  SECTION can be one of abbrev, addr, "
131        "aranges, decodedaranges, frame, gdb_index, info, info+, loc, line, "
132        "decodedline, ranges, pubnames, str, macinfo, macro or exception"), 0 },
133   { "hex-dump", 'x', "SECTION", 0,
134     N_("Dump the uninterpreted contents of SECTION, by number or name"), 0 },
135   { "strings", 'p', "SECTION", OPTION_ARG_OPTIONAL,
136     N_("Print string contents of sections"), 0 },
137   { "string-dump", 'p', NULL, OPTION_ALIAS | OPTION_HIDDEN, NULL, 0 },
138   { "archive-index", 'c', NULL, 0,
139     N_("Display the symbol index of an archive"), 0 },
140
141   { NULL, 0, NULL, 0, N_("Output control:"), 0 },
142   { "numeric-addresses", 'N', NULL, 0,
143     N_("Do not find symbol names for addresses in DWARF data"), 0 },
144   { "unresolved-address-offsets", 'U', NULL, 0,
145     N_("Display just offsets instead of resolving values to addresses in DWARF data"), 0 },
146   { "wide", 'W', NULL, 0,
147     N_("Ignored for compatibility (lines always wide)"), 0 },
148   { "decompress", 'z', NULL, 0,
149     N_("Show compression information for compressed sections (when used with -S); decompress section before dumping data (when used with -p or -x)"), 0 },
150   { NULL, 0, NULL, 0, NULL, 0 }
151 };
152
153 /* Short description of program.  */
154 static const char doc[] = N_("\
155 Print information from ELF file in human-readable form.");
156
157 /* Strings for arguments in help texts.  */
158 static const char args_doc[] = N_("FILE...");
159
160 /* Prototype for option handler.  */
161 static error_t parse_opt (int key, char *arg, struct argp_state *state);
162
163 /* Data structure to communicate with argp functions.  */
164 static struct argp argp =
165 {
166   options, parse_opt, args_doc, doc, NULL, NULL, NULL
167 };
168
169 /* If non-null, the section from which we should read to (compressed) ELF.  */
170 static const char *elf_input_section = NULL;
171
172 /* If non-null, the file that contains the skeleton CUs.  */
173 static const char *dwarf_skeleton = NULL;
174
175 /* Flags set by the option controlling the output.  */
176
177 /* True if dynamic segment should be printed.  */
178 static bool print_dynamic_table;
179
180 /* True if the file header should be printed.  */
181 static bool print_file_header;
182
183 /* True if the program headers should be printed.  */
184 static bool print_program_header;
185
186 /* True if relocations should be printed.  */
187 static bool print_relocations;
188
189 /* True if the section headers should be printed.  */
190 static bool print_section_header;
191
192 /* True if the symbol table should be printed.  */
193 static bool print_symbol_table;
194
195 /* True if (only) the dynsym table should be printed.  */
196 static bool print_dynsym_table;
197
198 /* A specific section name, or NULL to print all symbol tables.  */
199 static char *symbol_table_section;
200
201 /* A specific section name, or NULL to print all ELF notes.  */
202 static char *notes_section;
203
204 /* True if the version information should be printed.  */
205 static bool print_version_info;
206
207 /* True if section groups should be printed.  */
208 static bool print_section_groups;
209
210 /* True if bucket list length histogram should be printed.  */
211 static bool print_histogram;
212
213 /* True if the architecture specific data should be printed.  */
214 static bool print_arch;
215
216 /* True if note section content should be printed.  */
217 static bool print_notes;
218
219 /* True if SHF_STRINGS section content should be printed.  */
220 static bool print_string_sections;
221
222 /* True if archive index should be printed.  */
223 static bool print_archive_index;
224
225 /* True if any of the control options except print_archive_index is set.  */
226 static bool any_control_option;
227
228 /* True if we should print addresses from DWARF in symbolic form.  */
229 static bool print_address_names = true;
230
231 /* True if we should print raw values instead of relativized addresses.  */
232 static bool print_unresolved_addresses = false;
233
234 /* True if we should print the .debug_aranges section using libdw.  */
235 static bool decodedaranges = false;
236
237 /* True if we should print the .debug_aranges section using libdw.  */
238 static bool decodedline = false;
239
240 /* True if we want to show more information about compressed sections.  */
241 static bool print_decompress = false;
242
243 /* True if we want to show split compile units for debug_info skeletons.  */
244 static bool show_split_units = false;
245
246 /* Select printing of debugging sections.  */
247 static enum section_e
248 {
249   section_abbrev = 1,           /* .debug_abbrev  */
250   section_aranges = 2,          /* .debug_aranges  */
251   section_frame = 4,            /* .debug_frame or .eh_frame & al.  */
252   section_info = 8,             /* .debug_info, (implies .debug_types)  */
253   section_line = 16,            /* .debug_line  */
254   section_loc = 32,             /* .debug_loc  */
255   section_pubnames = 64,        /* .debug_pubnames  */
256   section_str = 128,            /* .debug_str  */
257   section_macinfo = 256,        /* .debug_macinfo  */
258   section_ranges = 512,         /* .debug_ranges  */
259   section_exception = 1024,     /* .eh_frame & al.  */
260   section_gdb_index = 2048,     /* .gdb_index  */
261   section_macro = 4096,         /* .debug_macro  */
262   section_addr = 8192,          /* .debug_addr  */
263   section_types = 16384,        /* .debug_types (implied by .debug_info)  */
264   section_all = (section_abbrev | section_aranges | section_frame
265                  | section_info | section_line | section_loc
266                  | section_pubnames | section_str | section_macinfo
267                  | section_ranges | section_exception | section_gdb_index
268                  | section_macro | section_addr | section_types)
269 } print_debug_sections, implicit_debug_sections;
270
271 /* Select hex dumping of sections.  */
272 static struct section_argument *dump_data_sections;
273 static struct section_argument **dump_data_sections_tail = &dump_data_sections;
274
275 /* Select string dumping of sections.  */
276 static struct section_argument *string_sections;
277 static struct section_argument **string_sections_tail = &string_sections;
278
279 struct section_argument
280 {
281   struct section_argument *next;
282   const char *arg;
283   bool implicit;
284 };
285
286 /* Numbers of sections and program headers in the file.  */
287 static size_t shnum;
288 static size_t phnum;
289
290
291 /* Declarations of local functions.  */
292 static void process_file (int fd, const char *fname, bool only_one);
293 static void process_elf_file (Dwfl_Module *dwflmod, int fd);
294 static void print_ehdr (Ebl *ebl, GElf_Ehdr *ehdr);
295 static void print_shdr (Ebl *ebl, GElf_Ehdr *ehdr);
296 static void print_phdr (Ebl *ebl, GElf_Ehdr *ehdr);
297 static void print_scngrp (Ebl *ebl);
298 static void print_dynamic (Ebl *ebl);
299 static void print_relocs (Ebl *ebl, GElf_Ehdr *ehdr);
300 static void handle_relocs_rel (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn,
301                                GElf_Shdr *shdr);
302 static void handle_relocs_rela (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn,
303                                 GElf_Shdr *shdr);
304 static void print_symtab (Ebl *ebl, int type);
305 static void handle_symtab (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr);
306 static void print_verinfo (Ebl *ebl);
307 static void handle_verneed (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr);
308 static void handle_verdef (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr);
309 static void handle_versym (Ebl *ebl, Elf_Scn *scn,
310                            GElf_Shdr *shdr);
311 static void print_debug (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr);
312 static void handle_hash (Ebl *ebl);
313 static void handle_notes (Ebl *ebl, GElf_Ehdr *ehdr);
314 static void print_liblist (Ebl *ebl);
315 static void print_attributes (Ebl *ebl, const GElf_Ehdr *ehdr);
316 static void dump_data (Ebl *ebl);
317 static void dump_strings (Ebl *ebl);
318 static void print_strings (Ebl *ebl);
319 static void dump_archive_index (Elf *, const char *);
320
321
322 /* Looked up once with gettext in main.  */
323 static char *yes_str;
324 static char *no_str;
325
326 static void
327 cleanup_list (struct section_argument *list)
328 {
329   while (list != NULL)
330     {
331       struct section_argument *a = list;
332       list = a->next;
333       free (a);
334     }
335 }
336
337 int
338 main (int argc, char *argv[])
339 {
340   /* We use no threads here which can interfere with handling a stream.  */
341   (void) __fsetlocking (stdout, FSETLOCKING_BYCALLER);
342
343   /* Set locale.  */
344   setlocale (LC_ALL, "");
345
346   /* Initialize the message catalog.  */
347   textdomain (PACKAGE_TARNAME);
348
349   /* Look up once.  */
350   yes_str = _("yes");
351   no_str = _("no");
352
353   /* Parse and process arguments.  */
354   int remaining;
355   argp_parse (&argp, argc, argv, 0, &remaining, NULL);
356
357   /* Before we start tell the ELF library which version we are using.  */
358   elf_version (EV_CURRENT);
359
360   /* Now process all the files given at the command line.  */
361   bool only_one = remaining + 1 == argc;
362   do
363     {
364       /* Open the file.  */
365       int fd = open (argv[remaining], O_RDONLY);
366       if (fd == -1)
367         {
368           error (0, errno, _("cannot open input file '%s'"), argv[remaining]);
369           continue;
370         }
371
372       process_file (fd, argv[remaining], only_one);
373
374       close (fd);
375     }
376   while (++remaining < argc);
377
378   cleanup_list (dump_data_sections);
379   cleanup_list (string_sections);
380
381   return error_message_count != 0;
382 }
383
384 static void
385 add_dump_section (const char *name,
386                   int key,
387                   bool implicit)
388 {
389   struct section_argument *a = xmalloc (sizeof *a);
390   a->arg = name;
391   a->next = NULL;
392   a->implicit = implicit;
393   struct section_argument ***tailp
394     = key == 'x' ? &dump_data_sections_tail : &string_sections_tail;
395   **tailp = a;
396   *tailp = &a->next;
397 }
398
399 /* Handle program arguments.  */
400 static error_t
401 parse_opt (int key, char *arg,
402            struct argp_state *state __attribute__ ((unused)))
403 {
404   switch (key)
405     {
406     case 'a':
407       print_file_header = true;
408       print_program_header = true;
409       print_relocations = true;
410       print_section_header = true;
411       print_symbol_table = true;
412       print_version_info = true;
413       print_dynamic_table = true;
414       print_section_groups = true;
415       print_histogram = true;
416       print_arch = true;
417       print_notes = true;
418       implicit_debug_sections |= section_exception;
419       add_dump_section (".strtab", key, true);
420       add_dump_section (".dynstr", key, true);
421       add_dump_section (".comment", key, true);
422       any_control_option = true;
423       break;
424     case 'A':
425       print_arch = true;
426       any_control_option = true;
427       break;
428     case 'd':
429       print_dynamic_table = true;
430       any_control_option = true;
431       break;
432     case 'e':
433       print_debug_sections |= section_exception;
434       any_control_option = true;
435       break;
436     case 'g':
437       print_section_groups = true;
438       any_control_option = true;
439       break;
440     case 'h':
441       print_file_header = true;
442       any_control_option = true;
443       break;
444     case 'I':
445       print_histogram = true;
446       any_control_option = true;
447       break;
448     case 'l':
449       print_program_header = true;
450       any_control_option = true;
451       break;
452     case 'n':
453       print_notes = true;
454       any_control_option = true;
455       notes_section = arg;
456       break;
457     case 'r':
458       print_relocations = true;
459       any_control_option = true;
460      break;
461     case 'S':
462       print_section_header = true;
463       any_control_option = true;
464       break;
465     case 's':
466       print_symbol_table = true;
467       any_control_option = true;
468       symbol_table_section = arg;
469       break;
470     case PRINT_DYNSYM_TABLE:
471       print_dynsym_table = true;
472       any_control_option = true;
473       break;
474     case 'V':
475       print_version_info = true;
476       any_control_option = true;
477       break;
478     case 'c':
479       print_archive_index = true;
480       break;
481     case 'w':
482       if (arg == NULL)
483         {
484           print_debug_sections = section_all;
485           implicit_debug_sections = section_info;
486           show_split_units = true;
487         }
488       else if (strcmp (arg, "abbrev") == 0)
489         print_debug_sections |= section_abbrev;
490       else if (strcmp (arg, "addr") == 0)
491         {
492           print_debug_sections |= section_addr;
493           implicit_debug_sections |= section_info;
494         }
495       else if (strcmp (arg, "aranges") == 0)
496         print_debug_sections |= section_aranges;
497       else if (strcmp (arg, "decodedaranges") == 0)
498         {
499           print_debug_sections |= section_aranges;
500           decodedaranges = true;
501         }
502       else if (strcmp (arg, "ranges") == 0)
503         {
504           print_debug_sections |= section_ranges;
505           implicit_debug_sections |= section_info;
506         }
507       else if (strcmp (arg, "frame") == 0 || strcmp (arg, "frames") == 0)
508         print_debug_sections |= section_frame;
509       else if (strcmp (arg, "info") == 0)
510         {
511           print_debug_sections |= section_info;
512           print_debug_sections |= section_types;
513         }
514       else if (strcmp (arg, "info+") == 0)
515         {
516           print_debug_sections |= section_info;
517           print_debug_sections |= section_types;
518           show_split_units = true;
519         }
520       else if (strcmp (arg, "loc") == 0)
521         {
522           print_debug_sections |= section_loc;
523           implicit_debug_sections |= section_info;
524         }
525       else if (strcmp (arg, "line") == 0)
526         print_debug_sections |= section_line;
527       else if (strcmp (arg, "decodedline") == 0)
528         {
529           print_debug_sections |= section_line;
530           decodedline = true;
531         }
532       else if (strcmp (arg, "pubnames") == 0)
533         print_debug_sections |= section_pubnames;
534       else if (strcmp (arg, "str") == 0)
535         {
536           print_debug_sections |= section_str;
537           /* For mapping string offset tables to CUs.  */
538           implicit_debug_sections |= section_info;
539         }
540       else if (strcmp (arg, "macinfo") == 0)
541         print_debug_sections |= section_macinfo;
542       else if (strcmp (arg, "macro") == 0)
543         print_debug_sections |= section_macro;
544       else if (strcmp (arg, "exception") == 0)
545         print_debug_sections |= section_exception;
546       else if (strcmp (arg, "gdb_index") == 0)
547         print_debug_sections |= section_gdb_index;
548       else
549         {
550           fprintf (stderr, _("Unknown DWARF debug section `%s'.\n"),
551                    arg);
552           argp_help (&argp, stderr, ARGP_HELP_SEE,
553                      program_invocation_short_name);
554           exit (1);
555         }
556       any_control_option = true;
557       break;
558     case 'p':
559       any_control_option = true;
560       if (arg == NULL)
561         {
562           print_string_sections = true;
563           break;
564         }
565       FALLTHROUGH;
566     case 'x':
567       add_dump_section (arg, key, false);
568       any_control_option = true;
569       break;
570     case 'N':
571       print_address_names = false;
572       break;
573     case 'U':
574       print_unresolved_addresses = true;
575       break;
576     case ARGP_KEY_NO_ARGS:
577       fputs (_("Missing file name.\n"), stderr);
578       goto do_argp_help;
579     case ARGP_KEY_FINI:
580       if (! any_control_option && ! print_archive_index)
581         {
582           fputs (_("No operation specified.\n"), stderr);
583         do_argp_help:
584           argp_help (&argp, stderr, ARGP_HELP_SEE,
585                      program_invocation_short_name);
586           exit (EXIT_FAILURE);
587         }
588       break;
589     case 'W':                   /* Ignored.  */
590       break;
591     case 'z':
592       print_decompress = true;
593       break;
594     case ELF_INPUT_SECTION:
595       if (arg == NULL)
596         elf_input_section = ".gnu_debugdata";
597       else
598         elf_input_section = arg;
599       break;
600     case DWARF_SKELETON:
601       dwarf_skeleton = arg;
602       break;
603     default:
604       return ARGP_ERR_UNKNOWN;
605     }
606   return 0;
607 }
608
609
610 /* Create a file descriptor to read the data from the
611    elf_input_section given a file descriptor to an ELF file.  */
612 static int
613 open_input_section (int fd)
614 {
615   size_t shnums;
616   size_t cnt;
617   size_t shstrndx;
618   Elf *elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
619   if (elf == NULL)
620     {
621       error (0, 0, _("cannot generate Elf descriptor: %s"),
622              elf_errmsg (-1));
623       return -1;
624     }
625
626   if (elf_getshdrnum (elf, &shnums) < 0)
627     {
628       error (0, 0, _("cannot determine number of sections: %s"),
629              elf_errmsg (-1));
630     open_error:
631       elf_end (elf);
632       return -1;
633     }
634
635   if (elf_getshdrstrndx (elf, &shstrndx) < 0)
636     {
637       error (0, 0, _("cannot get section header string table index"));
638       goto open_error;
639     }
640
641   for (cnt = 0; cnt < shnums; ++cnt)
642     {
643       Elf_Scn *scn = elf_getscn (elf, cnt);
644       if (scn == NULL)
645         {
646           error (0, 0, _("cannot get section: %s"),
647                  elf_errmsg (-1));
648           goto open_error;
649         }
650
651       GElf_Shdr shdr_mem;
652       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
653       if (unlikely (shdr == NULL))
654         {
655           error (0, 0, _("cannot get section header: %s"),
656                  elf_errmsg (-1));
657           goto open_error;
658         }
659
660       const char *sname = elf_strptr (elf, shstrndx, shdr->sh_name);
661       if (sname == NULL)
662         {
663           error (0, 0, _("cannot get section name"));
664           goto open_error;
665         }
666
667       if (strcmp (sname, elf_input_section) == 0)
668         {
669           Elf_Data *data = elf_rawdata (scn, NULL);
670           if (data == NULL)
671             {
672               error (0, 0, _("cannot get %s content: %s"),
673                      sname, elf_errmsg (-1));
674               goto open_error;
675             }
676
677           /* Create (and immediately unlink) a temporary file to store
678              section data in to create a file descriptor for it.  */
679           const char *tmpdir = getenv ("TMPDIR") ?: P_tmpdir;
680           static const char suffix[] = "/readelfXXXXXX";
681           int tmplen = strlen (tmpdir) + sizeof (suffix);
682           char *tempname = alloca (tmplen);
683           sprintf (tempname, "%s%s", tmpdir, suffix);
684
685           int sfd = mkstemp (tempname);
686           if (sfd == -1)
687             {
688               error (0, 0, _("cannot create temp file '%s'"),
689                      tempname);
690               goto open_error;
691             }
692           unlink (tempname);
693
694           ssize_t size = data->d_size;
695           if (write_retry (sfd, data->d_buf, size) != size)
696             {
697               error (0, 0, _("cannot write section data"));
698               goto open_error;
699             }
700
701           if (elf_end (elf) != 0)
702             {
703               error (0, 0, _("error while closing Elf descriptor: %s"),
704                      elf_errmsg (-1));
705               return -1;
706             }
707
708           if (lseek (sfd, 0, SEEK_SET) == -1)
709             {
710               error (0, 0, _("error while rewinding file descriptor"));
711               return -1;
712             }
713
714           return sfd;
715         }
716     }
717
718   /* Named section not found.  */
719   if (elf_end (elf) != 0)
720     error (0, 0, _("error while closing Elf descriptor: %s"),
721            elf_errmsg (-1));
722   return -1;
723 }
724
725 /* Check if the file is an archive, and if so dump its index.  */
726 static void
727 check_archive_index (int fd, const char *fname, bool only_one)
728 {
729   /* Create an `Elf' descriptor.  */
730   Elf *elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
731   if (elf == NULL)
732     error (0, 0, _("cannot generate Elf descriptor: %s"),
733            elf_errmsg (-1));
734   else
735     {
736       if (elf_kind (elf) == ELF_K_AR)
737         {
738           if (!only_one)
739             printf ("\n%s:\n\n", fname);
740           dump_archive_index (elf, fname);
741         }
742       else
743         error (0, 0,
744                _("'%s' is not an archive, cannot print archive index"),
745                fname);
746
747       /* Now we can close the descriptor.  */
748       if (elf_end (elf) != 0)
749         error (0, 0, _("error while closing Elf descriptor: %s"),
750                elf_errmsg (-1));
751     }
752 }
753
754 /* Trivial callback used for checking if we opened an archive.  */
755 static int
756 count_dwflmod (Dwfl_Module *dwflmod __attribute__ ((unused)),
757                void **userdata __attribute__ ((unused)),
758                const char *name __attribute__ ((unused)),
759                Dwarf_Addr base __attribute__ ((unused)),
760                void *arg)
761 {
762   if (*(bool *) arg)
763     return DWARF_CB_ABORT;
764   *(bool *) arg = true;
765   return DWARF_CB_OK;
766 }
767
768 struct process_dwflmod_args
769 {
770   int fd;
771   bool only_one;
772 };
773
774 static int
775 process_dwflmod (Dwfl_Module *dwflmod,
776                  void **userdata __attribute__ ((unused)),
777                  const char *name __attribute__ ((unused)),
778                  Dwarf_Addr base __attribute__ ((unused)),
779                  void *arg)
780 {
781   const struct process_dwflmod_args *a = arg;
782
783   /* Print the file name.  */
784   if (!a->only_one)
785     {
786       const char *fname;
787       dwfl_module_info (dwflmod, NULL, NULL, NULL, NULL, NULL, &fname, NULL);
788
789       printf ("\n%s:\n\n", fname);
790     }
791
792   process_elf_file (dwflmod, a->fd);
793
794   return DWARF_CB_OK;
795 }
796
797 /* Stub libdwfl callback, only the ELF handle already open is ever used.
798    Only used for finding the alternate debug file if the Dwarf comes from
799    the main file.  We are not interested in separate debuginfo.  */
800 static int
801 find_no_debuginfo (Dwfl_Module *mod,
802                    void **userdata,
803                    const char *modname,
804                    Dwarf_Addr base,
805                    const char *file_name,
806                    const char *debuglink_file,
807                    GElf_Word debuglink_crc,
808                    char **debuginfo_file_name)
809 {
810   Dwarf_Addr dwbias;
811   dwfl_module_info (mod, NULL, NULL, NULL, &dwbias, NULL, NULL, NULL);
812
813   /* We are only interested if the Dwarf has been setup on the main
814      elf file but is only missing the alternate debug link.  If dwbias
815      hasn't even been setup, this is searching for separate debuginfo
816      for the main elf.  We don't care in that case.  */
817   if (dwbias == (Dwarf_Addr) -1)
818     return -1;
819
820   return dwfl_standard_find_debuginfo (mod, userdata, modname, base,
821                                        file_name, debuglink_file,
822                                        debuglink_crc, debuginfo_file_name);
823 }
824
825 static Dwfl *
826 create_dwfl (int fd, const char *fname)
827 {
828   /* Duplicate an fd for dwfl_report_offline to swallow.  */
829   int dwfl_fd = dup (fd);
830   if (unlikely (dwfl_fd < 0))
831     error_exit (errno, "dup");
832
833   /* Use libdwfl in a trivial way to open the libdw handle for us.
834      This takes care of applying relocations to DWARF data in ET_REL files.  */
835   static const Dwfl_Callbacks callbacks =
836     {
837       .section_address = dwfl_offline_section_address,
838       .find_debuginfo = find_no_debuginfo
839     };
840   Dwfl *dwfl = dwfl_begin (&callbacks);
841   if (likely (dwfl != NULL))
842     /* Let 0 be the logical address of the file (or first in archive).  */
843     dwfl->offline_next_address = 0;
844   if (dwfl_report_offline (dwfl, fname, fname, dwfl_fd) == NULL)
845     {
846       struct stat st;
847       if (fstat (dwfl_fd, &st) != 0)
848         error (0, errno, _("cannot stat input file"));
849       else if (unlikely (st.st_size == 0))
850         error (0, 0, _("input file is empty"));
851       else
852         error (0, 0, _("failed reading '%s': %s"),
853                fname, dwfl_errmsg (-1));
854       close (dwfl_fd);          /* Consumed on success, not on failure.  */
855       dwfl = NULL;
856     }
857   else
858     dwfl_report_end (dwfl, NULL, NULL);
859
860   return dwfl;
861 }
862
863 /* Process one input file.  */
864 static void
865 process_file (int fd, const char *fname, bool only_one)
866 {
867   if (print_archive_index)
868     check_archive_index (fd, fname, only_one);
869
870   if (!any_control_option)
871     return;
872
873   if (elf_input_section != NULL)
874     {
875       /* Replace fname and fd with section content. */
876       char *fnname = alloca (strlen (fname) + strlen (elf_input_section) + 2);
877       sprintf (fnname, "%s:%s", fname, elf_input_section);
878       fd = open_input_section (fd);
879       if (fd == -1)
880         {
881           error (0, 0, _("No such section '%s' in '%s'"),
882                  elf_input_section, fname);
883           return;
884         }
885       fname = fnname;
886     }
887
888   Dwfl *dwfl = create_dwfl (fd, fname);
889   if (dwfl != NULL)
890     {
891       if (only_one)
892         {
893           /* Clear ONLY_ONE if we have multiple modules, from an archive.  */
894           bool seen = false;
895           only_one = dwfl_getmodules (dwfl, &count_dwflmod, &seen, 0) == 0;
896         }
897
898       /* Process the one or more modules gleaned from this file.  */
899       struct process_dwflmod_args a = { .fd = fd, .only_one = only_one };
900       dwfl_getmodules (dwfl, &process_dwflmod, &a, 0);
901     }
902   /* Terrible hack for hooking unrelated skeleton/split compile units,
903      see __libdw_link_skel_split in print_debug.  */
904   if (! do_not_close_dwfl)
905     dwfl_end (dwfl);
906
907   /* Need to close the replaced fd if we created it.  Caller takes
908      care of original.  */
909   if (elf_input_section != NULL)
910     close (fd);
911 }
912
913 /* Check whether there are any compressed sections in the ELF file.  */
914 static bool
915 elf_contains_chdrs (Elf *elf)
916 {
917   Elf_Scn *scn = NULL;
918   while ((scn = elf_nextscn (elf, scn)) != NULL)
919     {
920       GElf_Shdr shdr_mem;
921       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
922       if (shdr != NULL && (shdr->sh_flags & SHF_COMPRESSED) != 0)
923         return true;
924     }
925   return false;
926 }
927
928 /* Process one ELF file.  */
929 static void
930 process_elf_file (Dwfl_Module *dwflmod, int fd)
931 {
932   GElf_Addr dwflbias;
933   Elf *elf = dwfl_module_getelf (dwflmod, &dwflbias);
934
935   GElf_Ehdr ehdr_mem;
936   GElf_Ehdr *ehdr = gelf_getehdr (elf, &ehdr_mem);
937
938   if (ehdr == NULL)
939     {
940       error (0, 0, _("cannot read ELF header: %s"), elf_errmsg (-1));
941       return;
942     }
943
944   Ebl *ebl = ebl_openbackend (elf);
945   if (unlikely (ebl == NULL))
946     {
947     ebl_error:
948       error (0, errno, _("cannot create EBL handle"));
949       return;
950     }
951
952   /* Determine the number of sections.  */
953   if (unlikely (elf_getshdrnum (ebl->elf, &shnum) < 0))
954     error_exit (0, _("cannot determine number of sections: %s"),
955                 elf_errmsg (-1));
956
957   /* Determine the number of phdrs.  */
958   if (unlikely (elf_getphdrnum (ebl->elf, &phnum) < 0))
959     error_exit (0, _("cannot determine number of program headers: %s"),
960                 elf_errmsg (-1));
961
962   /* For an ET_REL file, libdwfl has adjusted the in-core shdrs and
963      may have applied relocation to some sections.  If there are any
964      compressed sections, any pass (or libdw/libdwfl) might have
965      uncompressed them.  So we need to get a fresh Elf handle on the
966      file to display those.  */
967   bool print_unchanged = ((print_section_header
968                            || print_relocations
969                            || dump_data_sections != NULL
970                            || print_notes)
971                           && (ehdr->e_type == ET_REL
972                               || elf_contains_chdrs (ebl->elf)));
973
974   Elf *pure_elf = NULL;
975   Ebl *pure_ebl = ebl;
976   if (print_unchanged)
977     {
978       /* Read the file afresh.  */
979       off_t aroff = elf_getaroff (elf);
980       pure_elf = dwelf_elf_begin (fd);
981       if (aroff > 0)
982         {
983           /* Archive member.  */
984           (void) elf_rand (pure_elf, aroff);
985           Elf *armem = elf_begin (-1, ELF_C_READ_MMAP, pure_elf);
986           elf_end (pure_elf);
987           pure_elf = armem;
988         }
989       if (pure_elf == NULL)
990         {
991           error (0, 0, _("cannot read ELF: %s"), elf_errmsg (-1));
992           return;
993         }
994       pure_ebl = ebl_openbackend (pure_elf);
995       if (pure_ebl == NULL)
996         goto ebl_error;
997     }
998
999   if (print_file_header)
1000     print_ehdr (ebl, ehdr);
1001   if (print_section_header)
1002     print_shdr (pure_ebl, ehdr);
1003   if (print_program_header)
1004     print_phdr (ebl, ehdr);
1005   if (print_section_groups)
1006     print_scngrp (ebl);
1007   if (print_dynamic_table)
1008     print_dynamic (ebl);
1009   if (print_relocations)
1010     print_relocs (pure_ebl, ehdr);
1011   if (print_histogram)
1012     handle_hash (ebl);
1013   if (print_symbol_table || print_dynsym_table)
1014     print_symtab (ebl, SHT_DYNSYM);
1015   if (print_version_info)
1016     print_verinfo (ebl);
1017   if (print_symbol_table)
1018     print_symtab (ebl, SHT_SYMTAB);
1019   if (print_arch)
1020     print_liblist (ebl);
1021   if (print_arch)
1022     print_attributes (ebl, ehdr);
1023   if (dump_data_sections != NULL)
1024     dump_data (pure_ebl);
1025   if (string_sections != NULL)
1026     dump_strings (ebl);
1027   if ((print_debug_sections | implicit_debug_sections) != 0)
1028     print_debug (dwflmod, ebl, ehdr);
1029   if (print_notes)
1030     handle_notes (pure_ebl, ehdr);
1031   if (print_string_sections)
1032     print_strings (ebl);
1033
1034   ebl_closebackend (ebl);
1035
1036   if (pure_ebl != ebl)
1037     {
1038       ebl_closebackend (pure_ebl);
1039       elf_end (pure_elf);
1040     }
1041 }
1042
1043
1044 /* Print file type.  */
1045 static void
1046 print_file_type (unsigned short int e_type)
1047 {
1048   if (likely (e_type <= ET_CORE))
1049     {
1050       static const char *const knowntypes[] =
1051       {
1052         N_("NONE (None)"),
1053         N_("REL (Relocatable file)"),
1054         N_("EXEC (Executable file)"),
1055         N_("DYN (Shared object file)"),
1056         N_("CORE (Core file)")
1057       };
1058       puts (_(knowntypes[e_type]));
1059     }
1060   else if (e_type >= ET_LOOS && e_type <= ET_HIOS)
1061     printf (_("OS Specific: (%x)\n"),  e_type);
1062   else if (e_type >= ET_LOPROC /* && e_type <= ET_HIPROC always true */)
1063     printf (_("Processor Specific: (%x)\n"),  e_type);
1064   else
1065     puts ("???");
1066 }
1067
1068
1069 /* Print ELF header.  */
1070 static void
1071 print_ehdr (Ebl *ebl, GElf_Ehdr *ehdr)
1072 {
1073   fputs_unlocked (_("ELF Header:\n  Magic:  "), stdout);
1074   for (size_t cnt = 0; cnt < EI_NIDENT; ++cnt)
1075     printf (" %02hhx", ehdr->e_ident[cnt]);
1076
1077   printf (_("\n  Class:                             %s\n"),
1078           ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? "ELF32"
1079           : ehdr->e_ident[EI_CLASS] == ELFCLASS64 ? "ELF64"
1080           : "\?\?\?");
1081
1082   printf (_("  Data:                              %s\n"),
1083           ehdr->e_ident[EI_DATA] == ELFDATA2LSB
1084           ? "2's complement, little endian"
1085           : ehdr->e_ident[EI_DATA] == ELFDATA2MSB
1086           ? "2's complement, big endian" : "\?\?\?");
1087
1088   printf (_("  Ident Version:                     %hhd %s\n"),
1089           ehdr->e_ident[EI_VERSION],
1090           ehdr->e_ident[EI_VERSION] == EV_CURRENT ? _("(current)")
1091           : "(\?\?\?)");
1092
1093   char buf[512];
1094   printf (_("  OS/ABI:                            %s\n"),
1095           ebl_osabi_name (ebl, ehdr->e_ident[EI_OSABI], buf, sizeof (buf)));
1096
1097   printf (_("  ABI Version:                       %hhd\n"),
1098           ehdr->e_ident[EI_ABIVERSION]);
1099
1100   fputs_unlocked (_("  Type:                              "), stdout);
1101   print_file_type (ehdr->e_type);
1102
1103   const char *machine = dwelf_elf_e_machine_string (ehdr->e_machine);
1104   if (machine != NULL)
1105     printf (_("  Machine:                           %s\n"), machine);
1106   else
1107     printf (_("  Machine:                           <unknown>: 0x%x\n"),
1108             ehdr->e_machine);
1109
1110   printf (_("  Version:                           %d %s\n"),
1111           ehdr->e_version,
1112           ehdr->e_version  == EV_CURRENT ? _("(current)") : "(\?\?\?)");
1113
1114   printf (_("  Entry point address:               %#" PRIx64 "\n"),
1115           ehdr->e_entry);
1116
1117   printf (_("  Start of program headers:          %" PRId64 " %s\n"),
1118           ehdr->e_phoff, _("(bytes into file)"));
1119
1120   printf (_("  Start of section headers:          %" PRId64 " %s\n"),
1121           ehdr->e_shoff, _("(bytes into file)"));
1122
1123   printf (_("  Flags:                             %s\n"),
1124           ebl_machine_flag_name (ebl, ehdr->e_flags, buf, sizeof (buf)));
1125
1126   printf (_("  Size of this header:               %" PRId16 " %s\n"),
1127           ehdr->e_ehsize, _("(bytes)"));
1128
1129   printf (_("  Size of program header entries:    %" PRId16 " %s\n"),
1130           ehdr->e_phentsize, _("(bytes)"));
1131
1132   printf (_("  Number of program headers entries: %" PRId16),
1133           ehdr->e_phnum);
1134   if (ehdr->e_phnum == PN_XNUM)
1135     {
1136       GElf_Shdr shdr_mem;
1137       GElf_Shdr *shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
1138       if (shdr != NULL)
1139         printf (_(" (%" PRIu32 " in [0].sh_info)"),
1140                 (uint32_t) shdr->sh_info);
1141       else
1142         fputs_unlocked (_(" ([0] not available)"), stdout);
1143     }
1144   fputc_unlocked ('\n', stdout);
1145
1146   printf (_("  Size of section header entries:    %" PRId16 " %s\n"),
1147           ehdr->e_shentsize, _("(bytes)"));
1148
1149   printf (_("  Number of section headers entries: %" PRId16),
1150           ehdr->e_shnum);
1151   if (ehdr->e_shnum == 0)
1152     {
1153       GElf_Shdr shdr_mem;
1154       GElf_Shdr *shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
1155       if (shdr != NULL)
1156         printf (_(" (%" PRIu32 " in [0].sh_size)"),
1157                 (uint32_t) shdr->sh_size);
1158       else
1159         fputs_unlocked (_(" ([0] not available)"), stdout);
1160     }
1161   fputc_unlocked ('\n', stdout);
1162
1163   if (unlikely (ehdr->e_shstrndx == SHN_XINDEX))
1164     {
1165       GElf_Shdr shdr_mem;
1166       GElf_Shdr *shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
1167       if (shdr != NULL)
1168         /* We managed to get the zeroth section.  */
1169         snprintf (buf, sizeof (buf), _(" (%" PRIu32 " in [0].sh_link)"),
1170                   (uint32_t) shdr->sh_link);
1171       else
1172         {
1173           strncpy (buf, _(" ([0] not available)"), sizeof (buf) - 1);
1174           buf[sizeof (buf) - 1] = '\0';
1175         }
1176
1177       printf (_("  Section header string table index: XINDEX%s\n\n"),
1178               buf);
1179     }
1180   else
1181     printf (_("  Section header string table index: %" PRId16 "\n\n"),
1182             ehdr->e_shstrndx);
1183 }
1184
1185
1186 static const char *
1187 get_visibility_type (int value)
1188 {
1189   switch (value)
1190     {
1191     case STV_DEFAULT:
1192       return "DEFAULT";
1193     case STV_INTERNAL:
1194       return "INTERNAL";
1195     case STV_HIDDEN:
1196       return "HIDDEN";
1197     case STV_PROTECTED:
1198       return "PROTECTED";
1199     default:
1200       return "???";
1201     }
1202 }
1203
1204 static const char *
1205 elf_ch_type_name (unsigned int code)
1206 {
1207   if (code == 0)
1208     return "NONE";
1209
1210   if (code == ELFCOMPRESS_ZLIB)
1211     return "ZLIB";
1212
1213   return "UNKNOWN";
1214 }
1215
1216 /* Print the section headers.  */
1217 static void
1218 print_shdr (Ebl *ebl, GElf_Ehdr *ehdr)
1219 {
1220   size_t cnt;
1221   size_t shstrndx;
1222
1223   if (! print_file_header)
1224     {
1225       size_t sections;
1226       if (unlikely (elf_getshdrnum (ebl->elf, &sections) < 0))
1227         error_exit (0, _("cannot get number of sections: %s"),
1228                     elf_errmsg (-1));
1229
1230       printf (_("\
1231 There are %zd section headers, starting at offset %#" PRIx64 ":\n\
1232 \n"),
1233               sections, ehdr->e_shoff);
1234     }
1235
1236   /* Get the section header string table index.  */
1237   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1238     error_exit (0, _("cannot get section header string table index: %s"),
1239                 elf_errmsg (-1));
1240
1241   puts (_("Section Headers:"));
1242
1243   if (ehdr->e_ident[EI_CLASS] == ELFCLASS32)
1244     puts (_("[Nr] Name                 Type         Addr     Off    Size   ES Flags Lk Inf Al"));
1245   else
1246     puts (_("[Nr] Name                 Type         Addr             Off      Size     ES Flags Lk Inf Al"));
1247
1248   if (print_decompress)
1249     {
1250       if (ehdr->e_ident[EI_CLASS] == ELFCLASS32)
1251         puts (_("     [Compression  Size   Al]"));
1252       else
1253         puts (_("     [Compression  Size     Al]"));
1254     }
1255
1256   for (cnt = 0; cnt < shnum; ++cnt)
1257     {
1258       Elf_Scn *scn = elf_getscn (ebl->elf, cnt);
1259
1260       if (unlikely (scn == NULL))
1261         error_exit (0, _("cannot get section: %s"),
1262                     elf_errmsg (-1));
1263
1264       /* Get the section header.  */
1265       GElf_Shdr shdr_mem;
1266       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1267       if (unlikely (shdr == NULL))
1268         error_exit (0, _("cannot get section header: %s"),
1269                     elf_errmsg (-1));
1270
1271       char flagbuf[20];
1272       char *cp = flagbuf;
1273       if (shdr->sh_flags & SHF_WRITE)
1274         *cp++ = 'W';
1275       if (shdr->sh_flags & SHF_ALLOC)
1276         *cp++ = 'A';
1277       if (shdr->sh_flags & SHF_EXECINSTR)
1278         *cp++ = 'X';
1279       if (shdr->sh_flags & SHF_MERGE)
1280         *cp++ = 'M';
1281       if (shdr->sh_flags & SHF_STRINGS)
1282         *cp++ = 'S';
1283       if (shdr->sh_flags & SHF_INFO_LINK)
1284         *cp++ = 'I';
1285       if (shdr->sh_flags & SHF_LINK_ORDER)
1286         *cp++ = 'L';
1287       if (shdr->sh_flags & SHF_OS_NONCONFORMING)
1288         *cp++ = 'N';
1289       if (shdr->sh_flags & SHF_GROUP)
1290         *cp++ = 'G';
1291       if (shdr->sh_flags & SHF_TLS)
1292         *cp++ = 'T';
1293       if (shdr->sh_flags & SHF_COMPRESSED)
1294         *cp++ = 'C';
1295       if (shdr->sh_flags & SHF_ORDERED)
1296         *cp++ = 'O';
1297       if (shdr->sh_flags & SHF_EXCLUDE)
1298         *cp++ = 'E';
1299       if (shdr->sh_flags & SHF_GNU_RETAIN)
1300         *cp++ = 'R';
1301       *cp = '\0';
1302
1303       const char *sname;
1304       char buf[128];
1305       sname = elf_strptr (ebl->elf, shstrndx, shdr->sh_name) ?: "<corrupt>";
1306       printf ("[%2zu] %-20s %-12s %0*" PRIx64 " %0*" PRIx64 " %0*" PRIx64
1307               " %2" PRId64 " %-5s %2" PRId32 " %3" PRId32
1308               " %2" PRId64 "\n",
1309               cnt, sname,
1310               ebl_section_type_name (ebl, shdr->sh_type, buf, sizeof (buf)),
1311               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 8 : 16, shdr->sh_addr,
1312               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 6 : 8, shdr->sh_offset,
1313               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 6 : 8, shdr->sh_size,
1314               shdr->sh_entsize, flagbuf, shdr->sh_link, shdr->sh_info,
1315               shdr->sh_addralign);
1316
1317       if (print_decompress)
1318         {
1319           if ((shdr->sh_flags & SHF_COMPRESSED) != 0)
1320             {
1321               GElf_Chdr chdr;
1322               if (gelf_getchdr (scn, &chdr) != NULL)
1323                 printf ("     [ELF %s (%" PRId32 ") %0*" PRIx64
1324                         " %2" PRId64 "]\n",
1325                         elf_ch_type_name (chdr.ch_type),
1326                         chdr.ch_type,
1327                         ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 6 : 8,
1328                         chdr.ch_size, chdr.ch_addralign);
1329               else
1330                 error (0, 0,
1331                        _("bad compression header for section %zd: %s"),
1332                        elf_ndxscn (scn), elf_errmsg (-1));
1333             }
1334           else if (startswith (sname, ".zdebug"))
1335             {
1336               ssize_t size;
1337               if ((size = dwelf_scn_gnu_compressed_size (scn)) >= 0)
1338                 printf ("     [GNU ZLIB     %0*zx   ]\n",
1339                         ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 6 : 8, size);
1340               else
1341                 error (0, 0,
1342                        _("bad gnu compressed size for section %zd: %s"),
1343                        elf_ndxscn (scn), elf_errmsg (-1));
1344             }
1345         }
1346     }
1347
1348   fputc_unlocked ('\n', stdout);
1349 }
1350
1351
1352 /* Print the program header.  */
1353 static void
1354 print_phdr (Ebl *ebl, GElf_Ehdr *ehdr)
1355 {
1356   if (phnum == 0)
1357     /* No program header, this is OK in relocatable objects.  */
1358     return;
1359
1360   puts (_("Program Headers:"));
1361   if (ehdr->e_ident[EI_CLASS] == ELFCLASS32)
1362     puts (_("\
1363   Type           Offset   VirtAddr   PhysAddr   FileSiz  MemSiz   Flg Align"));
1364   else
1365     puts (_("\
1366   Type           Offset   VirtAddr           PhysAddr           FileSiz  MemSiz   Flg Align"));
1367
1368   /* Process all program headers.  */
1369   bool has_relro = false;
1370   GElf_Addr relro_from = 0;
1371   GElf_Addr relro_to = 0;
1372   for (size_t cnt = 0; cnt < phnum; ++cnt)
1373     {
1374       char buf[128];
1375       GElf_Phdr mem;
1376       GElf_Phdr *phdr = gelf_getphdr (ebl->elf, cnt, &mem);
1377
1378       /* If for some reason the header cannot be returned show this.  */
1379       if (unlikely (phdr == NULL))
1380         {
1381           puts ("  ???");
1382           continue;
1383         }
1384
1385       printf ("  %-14s 0x%06" PRIx64 " 0x%0*" PRIx64 " 0x%0*" PRIx64
1386               " 0x%06" PRIx64 " 0x%06" PRIx64 " %c%c%c 0x%" PRIx64 "\n",
1387               ebl_segment_type_name (ebl, phdr->p_type, buf, sizeof (buf)),
1388               phdr->p_offset,
1389               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 8 : 16, phdr->p_vaddr,
1390               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 8 : 16, phdr->p_paddr,
1391               phdr->p_filesz,
1392               phdr->p_memsz,
1393               phdr->p_flags & PF_R ? 'R' : ' ',
1394               phdr->p_flags & PF_W ? 'W' : ' ',
1395               phdr->p_flags & PF_X ? 'E' : ' ',
1396               phdr->p_align);
1397
1398       if (phdr->p_type == PT_INTERP)
1399         {
1400           /* If we are sure the file offset is valid then we can show
1401              the user the name of the interpreter.  We check whether
1402              there is a section at the file offset.  Normally there
1403              would be a section called ".interp".  But in separate
1404              .debug files it is a NOBITS section (and so doesn't match
1405              with gelf_offscn).  Which probably means the offset is
1406              not valid another reason could be because the ELF file
1407              just doesn't contain any section headers, in that case
1408              just play it safe and don't display anything.  */
1409
1410           Elf_Scn *scn = gelf_offscn (ebl->elf, phdr->p_offset);
1411           GElf_Shdr shdr_mem;
1412           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1413
1414           size_t maxsize;
1415           char *filedata = elf_rawfile (ebl->elf, &maxsize);
1416
1417           if (shdr != NULL && shdr->sh_type == SHT_PROGBITS
1418               && filedata != NULL && phdr->p_offset < maxsize
1419               && phdr->p_filesz <= maxsize - phdr->p_offset
1420               && memchr (filedata + phdr->p_offset, '\0',
1421                          phdr->p_filesz) != NULL)
1422             printf (_("\t[Requesting program interpreter: %s]\n"),
1423                     filedata + phdr->p_offset);
1424         }
1425       else if (phdr->p_type == PT_GNU_RELRO)
1426         {
1427           has_relro = true;
1428           relro_from = phdr->p_vaddr;
1429           relro_to = relro_from + phdr->p_memsz;
1430         }
1431     }
1432
1433   size_t sections;
1434   if (unlikely (elf_getshdrnum (ebl->elf, &sections) < 0))
1435     error_exit (0, _("cannot get number of sections: %s"),
1436                 elf_errmsg (-1));
1437
1438   if (sections == 0)
1439     /* No sections in the file.  Punt.  */
1440     return;
1441
1442   /* Get the section header string table index.  */
1443   size_t shstrndx;
1444   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1445     error_exit (0, _("cannot get section header string table index"));
1446
1447   puts (_("\n Section to Segment mapping:\n  Segment Sections..."));
1448
1449   for (size_t cnt = 0; cnt < phnum; ++cnt)
1450     {
1451       /* Print the segment number.  */
1452       printf ("   %2.2zu     ", cnt);
1453
1454       GElf_Phdr phdr_mem;
1455       GElf_Phdr *phdr = gelf_getphdr (ebl->elf, cnt, &phdr_mem);
1456       /* This must not happen.  */
1457       if (unlikely (phdr == NULL))
1458         error_exit (0, _("cannot get program header: %s"),
1459                     elf_errmsg (-1));
1460
1461       /* Iterate over the sections.  */
1462       bool in_relro = false;
1463       bool in_ro = false;
1464       for (size_t inner = 1; inner < shnum; ++inner)
1465         {
1466           Elf_Scn *scn = elf_getscn (ebl->elf, inner);
1467           /* This should not happen.  */
1468           if (unlikely (scn == NULL))
1469             error_exit (0, _("cannot get section: %s"),
1470                         elf_errmsg (-1));
1471
1472           /* Get the section header.  */
1473           GElf_Shdr shdr_mem;
1474           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1475           if (unlikely (shdr == NULL))
1476             error_exit (0, _("cannot get section header: %s"),
1477                         elf_errmsg (-1));
1478
1479           if (shdr->sh_size > 0
1480               /* Compare allocated sections by VMA, unallocated
1481                  sections by file offset.  */
1482               && (shdr->sh_flags & SHF_ALLOC
1483                   ? (shdr->sh_addr >= phdr->p_vaddr
1484                      && (shdr->sh_addr + shdr->sh_size
1485                          <= phdr->p_vaddr + phdr->p_memsz))
1486                   : (shdr->sh_offset >= phdr->p_offset
1487                      && (shdr->sh_offset + shdr->sh_size
1488                          <= phdr->p_offset + phdr->p_filesz))))
1489             {
1490               if (has_relro && !in_relro
1491                   && shdr->sh_addr >= relro_from
1492                   && shdr->sh_addr + shdr->sh_size <= relro_to)
1493                 {
1494                   fputs_unlocked (" [RELRO:", stdout);
1495                   in_relro = true;
1496                 }
1497               else if (has_relro && in_relro && shdr->sh_addr >= relro_to)
1498                 {
1499                   fputs_unlocked ("]", stdout);
1500                   in_relro =  false;
1501                 }
1502               else if (has_relro && in_relro
1503                        && shdr->sh_addr + shdr->sh_size > relro_to)
1504                 fputs_unlocked ("] <RELRO:", stdout);
1505               else if (phdr->p_type == PT_LOAD && (phdr->p_flags & PF_W) == 0)
1506                 {
1507                   if (!in_ro)
1508                     {
1509                       fputs_unlocked (" [RO:", stdout);
1510                       in_ro = true;
1511                     }
1512                 }
1513               else
1514                 {
1515                   /* Determine the segment this section is part of.  */
1516                   size_t cnt2;
1517                   GElf_Phdr phdr2_mem;
1518                   GElf_Phdr *phdr2 = NULL;
1519                   for (cnt2 = 0; cnt2 < phnum; ++cnt2)
1520                     {
1521                       phdr2 = gelf_getphdr (ebl->elf, cnt2, &phdr2_mem);
1522
1523                       if (phdr2 != NULL && phdr2->p_type == PT_LOAD
1524                           && shdr->sh_addr >= phdr2->p_vaddr
1525                           && (shdr->sh_addr + shdr->sh_size
1526                               <= phdr2->p_vaddr + phdr2->p_memsz))
1527                         break;
1528                     }
1529
1530                   if (cnt2 < phnum)
1531                     {
1532                       if ((phdr2->p_flags & PF_W) == 0 && !in_ro)
1533                         {
1534                           fputs_unlocked (" [RO:", stdout);
1535                           in_ro = true;
1536                         }
1537                       else if ((phdr2->p_flags & PF_W) != 0 && in_ro)
1538                         {
1539                           fputs_unlocked ("]", stdout);
1540                           in_ro = false;
1541                         }
1542                     }
1543                 }
1544
1545               printf (" %s",
1546                       elf_strptr (ebl->elf, shstrndx, shdr->sh_name));
1547
1548               /* Signal that this section is only partially covered.  */
1549               if (has_relro && in_relro
1550                        && shdr->sh_addr + shdr->sh_size > relro_to)
1551                 {
1552                   fputs_unlocked (">", stdout);
1553                   in_relro =  false;
1554                 }
1555             }
1556         }
1557       if (in_relro || in_ro)
1558         fputs_unlocked ("]", stdout);
1559
1560       /* Finish the line.  */
1561       fputc_unlocked ('\n', stdout);
1562     }
1563 }
1564
1565
1566 static const char *
1567 section_name (Ebl *ebl, GElf_Shdr *shdr)
1568 {
1569   size_t shstrndx;
1570   if (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0)
1571     return "???";
1572   return elf_strptr (ebl->elf, shstrndx, shdr->sh_name) ?: "???";
1573 }
1574
1575
1576 static void
1577 handle_scngrp (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
1578 {
1579   /* Get the data of the section.  */
1580   Elf_Data *data = elf_getdata (scn, NULL);
1581
1582   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
1583   GElf_Shdr symshdr_mem;
1584   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
1585   Elf_Data *symdata = elf_getdata (symscn, NULL);
1586
1587   if (data == NULL || data->d_size < sizeof (Elf32_Word) || symshdr == NULL
1588       || symdata == NULL)
1589     return;
1590
1591   /* Get the section header string table index.  */
1592   size_t shstrndx;
1593   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1594     error_exit (0, _("cannot get section header string table index"));
1595
1596   Elf32_Word *grpref = (Elf32_Word *) data->d_buf;
1597
1598   GElf_Sym sym_mem;
1599   GElf_Sym *sym = gelf_getsym (symdata, shdr->sh_info, &sym_mem);
1600
1601   printf ((grpref[0] & GRP_COMDAT)
1602           ? ngettext ("\
1603 \nCOMDAT section group [%2zu] '%s' with signature '%s' contains %zu entry:\n",
1604                       "\
1605 \nCOMDAT section group [%2zu] '%s' with signature '%s' contains %zu entries:\n",
1606                       data->d_size / sizeof (Elf32_Word) - 1)
1607           : ngettext ("\
1608 \nSection group [%2zu] '%s' with signature '%s' contains %zu entry:\n", "\
1609 \nSection group [%2zu] '%s' with signature '%s' contains %zu entries:\n",
1610                       data->d_size / sizeof (Elf32_Word) - 1),
1611           elf_ndxscn (scn),
1612           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
1613           (sym == NULL ? NULL
1614            : elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name))
1615           ?: _("<INVALID SYMBOL>"),
1616           data->d_size / sizeof (Elf32_Word) - 1);
1617
1618   for (size_t cnt = 1; cnt < data->d_size / sizeof (Elf32_Word); ++cnt)
1619     {
1620       GElf_Shdr grpshdr_mem;
1621       GElf_Shdr *grpshdr = gelf_getshdr (elf_getscn (ebl->elf, grpref[cnt]),
1622                                          &grpshdr_mem);
1623
1624       const char *str;
1625       printf ("  [%2u] %s\n",
1626               grpref[cnt],
1627               grpshdr != NULL
1628               && (str = elf_strptr (ebl->elf, shstrndx, grpshdr->sh_name))
1629               ? str : _("<INVALID SECTION>"));
1630     }
1631 }
1632
1633
1634 static void
1635 print_scngrp (Ebl *ebl)
1636 {
1637   /* Find all relocation sections and handle them.  */
1638   Elf_Scn *scn = NULL;
1639
1640   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
1641     {
1642        /* Handle the section if it is a symbol table.  */
1643       GElf_Shdr shdr_mem;
1644       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1645
1646       if (shdr != NULL && shdr->sh_type == SHT_GROUP)
1647         {
1648           if ((shdr->sh_flags & SHF_COMPRESSED) != 0)
1649             {
1650               if (elf_compress (scn, 0, 0) < 0)
1651                 printf ("WARNING: %s [%zd]\n",
1652                         _("Couldn't uncompress section"),
1653                         elf_ndxscn (scn));
1654               shdr = gelf_getshdr (scn, &shdr_mem);
1655               if (unlikely (shdr == NULL))
1656                 error_exit (0, _("cannot get section [%zd] header: %s"),
1657                             elf_ndxscn (scn),
1658                             elf_errmsg (-1));
1659             }
1660           handle_scngrp (ebl, scn, shdr);
1661         }
1662     }
1663 }
1664
1665
1666 static const struct flags
1667 {
1668   int mask;
1669   const char *str;
1670 } dt_flags[] =
1671   {
1672     { DF_ORIGIN, "ORIGIN" },
1673     { DF_SYMBOLIC, "SYMBOLIC" },
1674     { DF_TEXTREL, "TEXTREL" },
1675     { DF_BIND_NOW, "BIND_NOW" },
1676     { DF_STATIC_TLS, "STATIC_TLS" }
1677   };
1678 static const int ndt_flags = sizeof (dt_flags) / sizeof (dt_flags[0]);
1679
1680 static const struct flags dt_flags_1[] =
1681   {
1682     { DF_1_NOW, "NOW" },
1683     { DF_1_GLOBAL, "GLOBAL" },
1684     { DF_1_GROUP, "GROUP" },
1685     { DF_1_NODELETE, "NODELETE" },
1686     { DF_1_LOADFLTR, "LOADFLTR" },
1687     { DF_1_INITFIRST, "INITFIRST" },
1688     { DF_1_NOOPEN, "NOOPEN" },
1689     { DF_1_ORIGIN, "ORIGIN" },
1690     { DF_1_DIRECT, "DIRECT" },
1691     { DF_1_TRANS, "TRANS" },
1692     { DF_1_INTERPOSE, "INTERPOSE" },
1693     { DF_1_NODEFLIB, "NODEFLIB" },
1694     { DF_1_NODUMP, "NODUMP" },
1695     { DF_1_CONFALT, "CONFALT" },
1696     { DF_1_ENDFILTEE, "ENDFILTEE" },
1697     { DF_1_DISPRELDNE, "DISPRELDNE" },
1698     { DF_1_DISPRELPND, "DISPRELPND" },
1699   };
1700 static const int ndt_flags_1 = sizeof (dt_flags_1) / sizeof (dt_flags_1[0]);
1701
1702 static const struct flags dt_feature_1[] =
1703   {
1704     { DTF_1_PARINIT, "PARINIT" },
1705     { DTF_1_CONFEXP, "CONFEXP" }
1706   };
1707 static const int ndt_feature_1 = (sizeof (dt_feature_1)
1708                                   / sizeof (dt_feature_1[0]));
1709
1710 static const struct flags dt_posflag_1[] =
1711   {
1712     { DF_P1_LAZYLOAD, "LAZYLOAD" },
1713     { DF_P1_GROUPPERM, "GROUPPERM" }
1714   };
1715 static const int ndt_posflag_1 = (sizeof (dt_posflag_1)
1716                                   / sizeof (dt_posflag_1[0]));
1717
1718
1719 static void
1720 print_flags (int class, GElf_Xword d_val, const struct flags *flags,
1721                 int nflags)
1722 {
1723   bool first = true;
1724   int cnt;
1725
1726   for (cnt = 0; cnt < nflags; ++cnt)
1727     if (d_val & flags[cnt].mask)
1728       {
1729         if (!first)
1730           putchar_unlocked (' ');
1731         fputs_unlocked (flags[cnt].str, stdout);
1732         d_val &= ~flags[cnt].mask;
1733         first = false;
1734       }
1735
1736   if (d_val != 0)
1737     {
1738       if (!first)
1739         putchar_unlocked (' ');
1740       printf ("%#0*" PRIx64, class == ELFCLASS32 ? 10 : 18, d_val);
1741     }
1742
1743   putchar_unlocked ('\n');
1744 }
1745
1746
1747 static void
1748 print_dt_flags (int class, GElf_Xword d_val)
1749 {
1750   print_flags (class, d_val, dt_flags, ndt_flags);
1751 }
1752
1753
1754 static void
1755 print_dt_flags_1 (int class, GElf_Xword d_val)
1756 {
1757   print_flags (class, d_val, dt_flags_1, ndt_flags_1);
1758 }
1759
1760
1761 static void
1762 print_dt_feature_1 (int class, GElf_Xword d_val)
1763 {
1764   print_flags (class, d_val, dt_feature_1, ndt_feature_1);
1765 }
1766
1767
1768 static void
1769 print_dt_posflag_1 (int class, GElf_Xword d_val)
1770 {
1771   print_flags (class, d_val, dt_posflag_1, ndt_posflag_1);
1772 }
1773
1774
1775 static size_t
1776 get_dyn_ents (Elf_Data * dyn_data)
1777 {
1778   GElf_Dyn *dyn;
1779   GElf_Dyn dyn_mem;
1780   size_t dyn_idx = 0;
1781   do
1782     {
1783       dyn = gelf_getdyn(dyn_data, dyn_idx, &dyn_mem);
1784       if (dyn != NULL)
1785         ++dyn_idx;
1786     }
1787   while (dyn != NULL && dyn->d_tag != DT_NULL);
1788
1789   return dyn_idx;
1790 }
1791
1792
1793 static void
1794 handle_dynamic (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
1795 {
1796   int class = gelf_getclass (ebl->elf);
1797   GElf_Shdr glink_mem;
1798   GElf_Shdr *glink;
1799   Elf_Data *data;
1800   size_t cnt;
1801   size_t shstrndx;
1802   size_t dyn_ents;
1803
1804   /* Get the data of the section.  */
1805   data = elf_getdata (scn, NULL);
1806   if (data == NULL)
1807     return;
1808
1809   /* Get the dynamic section entry number */
1810   dyn_ents = get_dyn_ents (data);
1811
1812   /* Get the section header string table index.  */
1813   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1814     error_exit (0, _("cannot get section header string table index"));
1815
1816   glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link), &glink_mem);
1817   if (glink == NULL)
1818     error_exit (0, _("invalid sh_link value in section %zu"),
1819                 elf_ndxscn (scn));
1820
1821   printf (ngettext ("\
1822 \nDynamic segment contains %lu entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
1823                     "\
1824 \nDynamic segment contains %lu entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
1825                     dyn_ents),
1826           (unsigned long int) dyn_ents,
1827           class == ELFCLASS32 ? 10 : 18, shdr->sh_addr,
1828           shdr->sh_offset,
1829           (int) shdr->sh_link,
1830           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
1831   fputs_unlocked (_("  Type              Value\n"), stdout);
1832
1833   for (cnt = 0; cnt < dyn_ents; ++cnt)
1834     {
1835       GElf_Dyn dynmem;
1836       GElf_Dyn *dyn = gelf_getdyn (data, cnt, &dynmem);
1837       if (dyn == NULL)
1838         break;
1839
1840       char buf[64];
1841       printf ("  %-17s ",
1842               ebl_dynamic_tag_name (ebl, dyn->d_tag, buf, sizeof (buf)));
1843
1844       switch (dyn->d_tag)
1845         {
1846         case DT_NULL:
1847         case DT_DEBUG:
1848         case DT_BIND_NOW:
1849         case DT_TEXTREL:
1850           /* No further output.  */
1851           fputc_unlocked ('\n', stdout);
1852           break;
1853
1854         case DT_NEEDED:
1855           printf (_("Shared library: [%s]\n"),
1856                   elf_strptr (ebl->elf, shdr->sh_link, dyn->d_un.d_val));
1857           break;
1858
1859         case DT_SONAME:
1860           printf (_("Library soname: [%s]\n"),
1861                   elf_strptr (ebl->elf, shdr->sh_link, dyn->d_un.d_val));
1862           break;
1863
1864         case DT_RPATH:
1865           printf (_("Library rpath: [%s]\n"),
1866                   elf_strptr (ebl->elf, shdr->sh_link, dyn->d_un.d_val));
1867           break;
1868
1869         case DT_RUNPATH:
1870           printf (_("Library runpath: [%s]\n"),
1871                   elf_strptr (ebl->elf, shdr->sh_link, dyn->d_un.d_val));
1872           break;
1873
1874         case DT_PLTRELSZ:
1875         case DT_RELASZ:
1876         case DT_STRSZ:
1877         case DT_RELSZ:
1878         case DT_RELAENT:
1879         case DT_SYMENT:
1880         case DT_RELENT:
1881         case DT_PLTPADSZ:
1882         case DT_MOVEENT:
1883         case DT_MOVESZ:
1884         case DT_INIT_ARRAYSZ:
1885         case DT_FINI_ARRAYSZ:
1886         case DT_SYMINSZ:
1887         case DT_SYMINENT:
1888         case DT_GNU_CONFLICTSZ:
1889         case DT_GNU_LIBLISTSZ:
1890           printf (_("%" PRId64 " (bytes)\n"), dyn->d_un.d_val);
1891           break;
1892
1893         case DT_VERDEFNUM:
1894         case DT_VERNEEDNUM:
1895         case DT_RELACOUNT:
1896         case DT_RELCOUNT:
1897           printf ("%" PRId64 "\n", dyn->d_un.d_val);
1898           break;
1899
1900         case DT_PLTREL:;
1901           const char *tagname = ebl_dynamic_tag_name (ebl, dyn->d_un.d_val,
1902                                                       NULL, 0);
1903           puts (tagname ?: "???");
1904           break;
1905
1906         case DT_FLAGS:
1907           print_dt_flags (class, dyn->d_un.d_val);
1908           break;
1909
1910         case DT_FLAGS_1:
1911           print_dt_flags_1 (class, dyn->d_un.d_val);
1912           break;
1913
1914         case DT_FEATURE_1:
1915           print_dt_feature_1 (class, dyn->d_un.d_val);
1916           break;
1917
1918         case DT_POSFLAG_1:
1919           print_dt_posflag_1 (class, dyn->d_un.d_val);
1920           break;
1921
1922         default:
1923           printf ("%#0*" PRIx64 "\n",
1924                   class == ELFCLASS32 ? 10 : 18, dyn->d_un.d_val);
1925           break;
1926         }
1927     }
1928 }
1929
1930
1931 /* Print the dynamic segment.  */
1932 static void
1933 print_dynamic (Ebl *ebl)
1934 {
1935   for (size_t i = 0; i < phnum; ++i)
1936     {
1937       GElf_Phdr phdr_mem;
1938       GElf_Phdr *phdr = gelf_getphdr (ebl->elf, i, &phdr_mem);
1939
1940       if (phdr != NULL && phdr->p_type == PT_DYNAMIC)
1941         {
1942           Elf_Scn *scn = gelf_offscn (ebl->elf, phdr->p_offset);
1943           GElf_Shdr shdr_mem;
1944           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1945           if (shdr != NULL && shdr->sh_type == SHT_DYNAMIC)
1946             handle_dynamic (ebl, scn, shdr);
1947           break;
1948         }
1949     }
1950 }
1951
1952
1953 /* Print relocations.  */
1954 static void
1955 print_relocs (Ebl *ebl, GElf_Ehdr *ehdr)
1956 {
1957   /* Find all relocation sections and handle them.  */
1958   Elf_Scn *scn = NULL;
1959
1960   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
1961     {
1962        /* Handle the section if it is a symbol table.  */
1963       GElf_Shdr shdr_mem;
1964       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1965
1966       if (likely (shdr != NULL))
1967         {
1968           if (shdr->sh_type == SHT_REL)
1969             handle_relocs_rel (ebl, ehdr, scn, shdr);
1970           else if (shdr->sh_type == SHT_RELA)
1971             handle_relocs_rela (ebl, ehdr, scn, shdr);
1972         }
1973     }
1974 }
1975
1976
1977 /* Handle a relocation section.  */
1978 static void
1979 handle_relocs_rel (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn, GElf_Shdr *shdr)
1980 {
1981   int class = gelf_getclass (ebl->elf);
1982   size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_REL, 1, EV_CURRENT);
1983   int nentries = shdr->sh_size / sh_entsize;
1984
1985   /* Get the data of the section.  */
1986   Elf_Data *data = elf_getdata (scn, NULL);
1987   if (data == NULL)
1988     return;
1989
1990   /* Get the symbol table information.  */
1991   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
1992   GElf_Shdr symshdr_mem;
1993   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
1994   Elf_Data *symdata = elf_getdata (symscn, NULL);
1995
1996   /* Get the section header of the section the relocations are for.  */
1997   GElf_Shdr destshdr_mem;
1998   GElf_Shdr *destshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_info),
1999                                       &destshdr_mem);
2000
2001   if (unlikely (symshdr == NULL || symdata == NULL || destshdr == NULL))
2002     {
2003       printf (_("\nInvalid symbol table at offset %#0" PRIx64 "\n"),
2004               shdr->sh_offset);
2005       return;
2006     }
2007
2008   /* Search for the optional extended section index table.  */
2009   Elf_Data *xndxdata = NULL;
2010   int xndxscnidx = elf_scnshndx (scn);
2011   if (unlikely (xndxscnidx > 0))
2012     xndxdata = elf_getdata (elf_getscn (ebl->elf, xndxscnidx), NULL);
2013
2014   /* Get the section header string table index.  */
2015   size_t shstrndx;
2016   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2017     error_exit (0, _("cannot get section header string table index"));
2018
2019   if (shdr->sh_info != 0)
2020     printf (ngettext ("\
2021 \nRelocation section [%2zu] '%s' for section [%2u] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
2022                     "\
2023 \nRelocation section [%2zu] '%s' for section [%2u] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
2024                       nentries),
2025             elf_ndxscn (scn),
2026             elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2027             (unsigned int) shdr->sh_info,
2028             elf_strptr (ebl->elf, shstrndx, destshdr->sh_name),
2029             shdr->sh_offset,
2030             nentries);
2031   else
2032     /* The .rel.dyn section does not refer to a specific section but
2033        instead of section index zero.  Do not try to print a section
2034        name.  */
2035     printf (ngettext ("\
2036 \nRelocation section [%2u] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
2037                     "\
2038 \nRelocation section [%2u] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
2039                       nentries),
2040             (unsigned int) elf_ndxscn (scn),
2041             elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2042             shdr->sh_offset,
2043             nentries);
2044   fputs_unlocked (class == ELFCLASS32
2045                   ? _("\
2046   Offset      Type                 Value       Name\n")
2047                   : _("\
2048   Offset              Type                 Value               Name\n"),
2049          stdout);
2050
2051   int is_statically_linked = 0;
2052   for (int cnt = 0; cnt < nentries; ++cnt)
2053     {
2054       GElf_Rel relmem;
2055       GElf_Rel *rel = gelf_getrel (data, cnt, &relmem);
2056       if (likely (rel != NULL))
2057         {
2058           char buf[128];
2059           GElf_Sym symmem;
2060           Elf32_Word xndx;
2061           GElf_Sym *sym = gelf_getsymshndx (symdata, xndxdata,
2062                                             GELF_R_SYM (rel->r_info),
2063                                             &symmem, &xndx);
2064           if (unlikely (sym == NULL))
2065             {
2066               /* As a special case we have to handle relocations in static
2067                  executables.  This only happens for IRELATIVE relocations
2068                  (so far).  There is no symbol table.  */
2069               if (is_statically_linked == 0)
2070                 {
2071                   /* Find the program header and look for a PT_INTERP entry. */
2072                   is_statically_linked = -1;
2073                   if (ehdr->e_type == ET_EXEC)
2074                     {
2075                       is_statically_linked = 1;
2076
2077                       for (size_t inner = 0; inner < phnum; ++inner)
2078                         {
2079                           GElf_Phdr phdr_mem;
2080                           GElf_Phdr *phdr = gelf_getphdr (ebl->elf, inner,
2081                                                           &phdr_mem);
2082                           if (phdr != NULL && phdr->p_type == PT_INTERP)
2083                             {
2084                               is_statically_linked = -1;
2085                               break;
2086                             }
2087                         }
2088                     }
2089                 }
2090
2091               if (is_statically_linked > 0 && shdr->sh_link == 0)
2092                 printf ("\
2093   %#0*" PRIx64 "  %-20s %*s  %s\n",
2094                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2095                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2096                         /* Avoid the leading R_ which isn't carrying any
2097                            information.  */
2098                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2099                                                buf, sizeof (buf)) + 2
2100                         : _("<INVALID RELOC>"),
2101                         class == ELFCLASS32 ? 10 : 18, "",
2102                         elf_strptr (ebl->elf, shstrndx, destshdr->sh_name));
2103               else
2104                 printf ("  %#0*" PRIx64 "  %-20s <%s %ld>\n",
2105                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2106                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2107                         /* Avoid the leading R_ which isn't carrying any
2108                            information.  */
2109                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2110                                                buf, sizeof (buf)) + 2
2111                         : _("<INVALID RELOC>"),
2112                         _("INVALID SYMBOL"),
2113                         (long int) GELF_R_SYM (rel->r_info));
2114             }
2115           else if (GELF_ST_TYPE (sym->st_info) != STT_SECTION)
2116             printf ("  %#0*" PRIx64 "  %-20s %#0*" PRIx64 "  %s\n",
2117                     class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2118                     likely (ebl_reloc_type_check (ebl,
2119                                                   GELF_R_TYPE (rel->r_info)))
2120                     /* Avoid the leading R_ which isn't carrying any
2121                        information.  */
2122                     ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2123                                            buf, sizeof (buf)) + 2
2124                     : _("<INVALID RELOC>"),
2125                     class == ELFCLASS32 ? 10 : 18, sym->st_value,
2126                     elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name));
2127           else
2128             {
2129               /* This is a relocation against a STT_SECTION symbol.  */
2130               GElf_Shdr secshdr_mem;
2131               GElf_Shdr *secshdr;
2132               secshdr = gelf_getshdr (elf_getscn (ebl->elf,
2133                                                   sym->st_shndx == SHN_XINDEX
2134                                                   ? xndx : sym->st_shndx),
2135                                       &secshdr_mem);
2136
2137               if (unlikely (secshdr == NULL))
2138                 printf ("  %#0*" PRIx64 "  %-20s <%s %ld>\n",
2139                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2140                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2141                         /* Avoid the leading R_ which isn't carrying any
2142                            information.  */
2143                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2144                                                buf, sizeof (buf)) + 2
2145                         : _("<INVALID RELOC>"),
2146                         _("INVALID SECTION"),
2147                         (long int) (sym->st_shndx == SHN_XINDEX
2148                                     ? xndx : sym->st_shndx));
2149               else
2150                 printf ("  %#0*" PRIx64 "  %-20s %#0*" PRIx64 "  %s\n",
2151                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2152                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2153                         /* Avoid the leading R_ which isn't carrying any
2154                            information.  */
2155                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2156                                                buf, sizeof (buf)) + 2
2157                         : _("<INVALID RELOC>"),
2158                         class == ELFCLASS32 ? 10 : 18, sym->st_value,
2159                         elf_strptr (ebl->elf, shstrndx, secshdr->sh_name));
2160             }
2161         }
2162     }
2163 }
2164
2165
2166 /* Handle a relocation section.  */
2167 static void
2168 handle_relocs_rela (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn, GElf_Shdr *shdr)
2169 {
2170   int class = gelf_getclass (ebl->elf);
2171   size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_RELA, 1, EV_CURRENT);
2172   int nentries = shdr->sh_size / sh_entsize;
2173
2174   /* Get the data of the section.  */
2175   Elf_Data *data = elf_getdata (scn, NULL);
2176   if (data == NULL)
2177     return;
2178
2179   /* Get the symbol table information.  */
2180   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
2181   GElf_Shdr symshdr_mem;
2182   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
2183   Elf_Data *symdata = elf_getdata (symscn, NULL);
2184
2185   /* Get the section header of the section the relocations are for.  */
2186   GElf_Shdr destshdr_mem;
2187   GElf_Shdr *destshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_info),
2188                                       &destshdr_mem);
2189
2190   if (unlikely (symshdr == NULL || symdata == NULL || destshdr == NULL))
2191     {
2192       printf (_("\nInvalid symbol table at offset %#0" PRIx64 "\n"),
2193               shdr->sh_offset);
2194       return;
2195     }
2196
2197   /* Search for the optional extended section index table.  */
2198   Elf_Data *xndxdata = NULL;
2199   int xndxscnidx = elf_scnshndx (scn);
2200   if (unlikely (xndxscnidx > 0))
2201     xndxdata = elf_getdata (elf_getscn (ebl->elf, xndxscnidx), NULL);
2202
2203   /* Get the section header string table index.  */
2204   size_t shstrndx;
2205   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2206     error_exit (0, _("cannot get section header string table index"));
2207
2208   if (shdr->sh_info != 0)
2209     printf (ngettext ("\
2210 \nRelocation section [%2zu] '%s' for section [%2u] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
2211                     "\
2212 \nRelocation section [%2zu] '%s' for section [%2u] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
2213                     nentries),
2214           elf_ndxscn (scn),
2215           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2216           (unsigned int) shdr->sh_info,
2217           elf_strptr (ebl->elf, shstrndx, destshdr->sh_name),
2218           shdr->sh_offset,
2219           nentries);
2220   else
2221     /* The .rela.dyn section does not refer to a specific section but
2222        instead of section index zero.  Do not try to print a section
2223        name.  */
2224     printf (ngettext ("\
2225 \nRelocation section [%2u] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
2226                     "\
2227 \nRelocation section [%2u] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
2228                       nentries),
2229             (unsigned int) elf_ndxscn (scn),
2230             elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2231             shdr->sh_offset,
2232             nentries);
2233   fputs_unlocked (class == ELFCLASS32
2234                   ? _("\
2235   Offset      Type            Value       Addend Name\n")
2236                   : _("\
2237   Offset              Type            Value               Addend Name\n"),
2238                   stdout);
2239
2240   int is_statically_linked = 0;
2241   for (int cnt = 0; cnt < nentries; ++cnt)
2242     {
2243       GElf_Rela relmem;
2244       GElf_Rela *rel = gelf_getrela (data, cnt, &relmem);
2245       if (likely (rel != NULL))
2246         {
2247           char buf[64];
2248           GElf_Sym symmem;
2249           Elf32_Word xndx;
2250           GElf_Sym *sym = gelf_getsymshndx (symdata, xndxdata,
2251                                             GELF_R_SYM (rel->r_info),
2252                                             &symmem, &xndx);
2253
2254           if (unlikely (sym == NULL))
2255             {
2256               /* As a special case we have to handle relocations in static
2257                  executables.  This only happens for IRELATIVE relocations
2258                  (so far).  There is no symbol table.  */
2259               if (is_statically_linked == 0)
2260                 {
2261                   /* Find the program header and look for a PT_INTERP entry. */
2262                   is_statically_linked = -1;
2263                   if (ehdr->e_type == ET_EXEC)
2264                     {
2265                       is_statically_linked = 1;
2266
2267                       for (size_t inner = 0; inner < phnum; ++inner)
2268                         {
2269                           GElf_Phdr phdr_mem;
2270                           GElf_Phdr *phdr = gelf_getphdr (ebl->elf, inner,
2271                                                           &phdr_mem);
2272                           if (phdr != NULL && phdr->p_type == PT_INTERP)
2273                             {
2274                               is_statically_linked = -1;
2275                               break;
2276                             }
2277                         }
2278                     }
2279                 }
2280
2281               if (is_statically_linked > 0 && shdr->sh_link == 0)
2282                 printf ("\
2283   %#0*" PRIx64 "  %-15s %*s  %#6" PRIx64 " %s\n",
2284                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2285                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2286                         /* Avoid the leading R_ which isn't carrying any
2287                            information.  */
2288                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2289                                                buf, sizeof (buf)) + 2
2290                         : _("<INVALID RELOC>"),
2291                         class == ELFCLASS32 ? 10 : 18, "",
2292                         rel->r_addend,
2293                         elf_strptr (ebl->elf, shstrndx, destshdr->sh_name));
2294               else
2295                 printf ("  %#0*" PRIx64 "  %-15s <%s %ld>\n",
2296                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2297                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2298                         /* Avoid the leading R_ which isn't carrying any
2299                            information.  */
2300                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2301                                                buf, sizeof (buf)) + 2
2302                         : _("<INVALID RELOC>"),
2303                         _("INVALID SYMBOL"),
2304                         (long int) GELF_R_SYM (rel->r_info));
2305             }
2306           else if (GELF_ST_TYPE (sym->st_info) != STT_SECTION)
2307             printf ("\
2308   %#0*" PRIx64 "  %-15s %#0*" PRIx64 "  %+6" PRId64 " %s\n",
2309                     class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2310                     likely (ebl_reloc_type_check (ebl,
2311                                                   GELF_R_TYPE (rel->r_info)))
2312                     /* Avoid the leading R_ which isn't carrying any
2313                        information.  */
2314                     ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2315                                            buf, sizeof (buf)) + 2
2316                     : _("<INVALID RELOC>"),
2317                     class == ELFCLASS32 ? 10 : 18, sym->st_value,
2318                     rel->r_addend,
2319                     elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name));
2320           else
2321             {
2322               /* This is a relocation against a STT_SECTION symbol.  */
2323               GElf_Shdr secshdr_mem;
2324               GElf_Shdr *secshdr;
2325               secshdr = gelf_getshdr (elf_getscn (ebl->elf,
2326                                                   sym->st_shndx == SHN_XINDEX
2327                                                   ? xndx : sym->st_shndx),
2328                                       &secshdr_mem);
2329
2330               if (unlikely (secshdr == NULL))
2331                 printf ("  %#0*" PRIx64 "  %-15s <%s %ld>\n",
2332                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2333                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2334                         /* Avoid the leading R_ which isn't carrying any
2335                            information.  */
2336                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2337                                                buf, sizeof (buf)) + 2
2338                         : _("<INVALID RELOC>"),
2339                         _("INVALID SECTION"),
2340                         (long int) (sym->st_shndx == SHN_XINDEX
2341                                     ? xndx : sym->st_shndx));
2342               else
2343                 printf ("\
2344   %#0*" PRIx64 "  %-15s %#0*" PRIx64 "  %+6" PRId64 " %s\n",
2345                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2346                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2347                         /* Avoid the leading R_ which isn't carrying any
2348                            information.  */
2349                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2350                                                buf, sizeof (buf)) + 2
2351                         : _("<INVALID RELOC>"),
2352                         class == ELFCLASS32 ? 10 : 18, sym->st_value,
2353                         rel->r_addend,
2354                         elf_strptr (ebl->elf, shstrndx, secshdr->sh_name));
2355             }
2356         }
2357     }
2358 }
2359
2360
2361 /* Print the program header.  */
2362 static void
2363 print_symtab (Ebl *ebl, int type)
2364 {
2365   /* Find the symbol table(s).  For this we have to search through the
2366      section table.  */
2367   Elf_Scn *scn = NULL;
2368
2369   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
2370     {
2371       /* Handle the section if it is a symbol table.  */
2372       GElf_Shdr shdr_mem;
2373       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
2374
2375       if (shdr != NULL && shdr->sh_type == (GElf_Word) type)
2376         {
2377           if (symbol_table_section != NULL)
2378             {
2379               /* Get the section header string table index.  */
2380               size_t shstrndx;
2381               const char *sname;
2382               if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2383                 error_exit (0,
2384                             _("cannot get section header string table index"));
2385               sname = elf_strptr (ebl->elf, shstrndx, shdr->sh_name);
2386               if (sname == NULL || strcmp (sname, symbol_table_section) != 0)
2387                 continue;
2388             }
2389
2390           if ((shdr->sh_flags & SHF_COMPRESSED) != 0)
2391             {
2392               if (elf_compress (scn, 0, 0) < 0)
2393                 printf ("WARNING: %s [%zd]\n",
2394                         _("Couldn't uncompress section"),
2395                         elf_ndxscn (scn));
2396               shdr = gelf_getshdr (scn, &shdr_mem);
2397               if (unlikely (shdr == NULL))
2398                 error_exit (0,
2399                             _("cannot get section [%zd] header: %s"),
2400                             elf_ndxscn (scn), elf_errmsg (-1));
2401             }
2402           handle_symtab (ebl, scn, shdr);
2403         }
2404     }
2405 }
2406
2407
2408 static void
2409 handle_symtab (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
2410 {
2411   Elf_Data *versym_data = NULL;
2412   Elf_Data *verneed_data = NULL;
2413   Elf_Data *verdef_data = NULL;
2414   Elf_Data *xndx_data = NULL;
2415   int class = gelf_getclass (ebl->elf);
2416   Elf32_Word verneed_stridx = 0;
2417   Elf32_Word verdef_stridx = 0;
2418
2419   /* Get the data of the section.  */
2420   Elf_Data *data = elf_getdata (scn, NULL);
2421   if (data == NULL)
2422     return;
2423
2424   /* Find out whether we have other sections we might need.  */
2425   Elf_Scn *runscn = NULL;
2426   while ((runscn = elf_nextscn (ebl->elf, runscn)) != NULL)
2427     {
2428       GElf_Shdr runshdr_mem;
2429       GElf_Shdr *runshdr = gelf_getshdr (runscn, &runshdr_mem);
2430
2431       if (likely (runshdr != NULL))
2432         {
2433           if (runshdr->sh_type == SHT_GNU_versym
2434               && runshdr->sh_link == elf_ndxscn (scn))
2435             /* Bingo, found the version information.  Now get the data.  */
2436             versym_data = elf_getdata (runscn, NULL);
2437           else if (runshdr->sh_type == SHT_GNU_verneed)
2438             {
2439               /* This is the information about the needed versions.  */
2440               verneed_data = elf_getdata (runscn, NULL);
2441               verneed_stridx = runshdr->sh_link;
2442             }
2443           else if (runshdr->sh_type == SHT_GNU_verdef)
2444             {
2445               /* This is the information about the defined versions.  */
2446               verdef_data = elf_getdata (runscn, NULL);
2447               verdef_stridx = runshdr->sh_link;
2448             }
2449           else if (runshdr->sh_type == SHT_SYMTAB_SHNDX
2450               && runshdr->sh_link == elf_ndxscn (scn))
2451             /* Extended section index.  */
2452             xndx_data = elf_getdata (runscn, NULL);
2453         }
2454     }
2455
2456   /* Get the section header string table index.  */
2457   size_t shstrndx;
2458   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2459     error_exit (0, _("cannot get section header string table index"));
2460
2461   GElf_Shdr glink_mem;
2462   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
2463                                    &glink_mem);
2464   if (glink == NULL)
2465     error_exit (0, _("invalid sh_link value in section %zu"),
2466                 elf_ndxscn (scn));
2467
2468   /* Now we can compute the number of entries in the section.  */
2469   unsigned int nsyms = data->d_size / (class == ELFCLASS32
2470                                        ? sizeof (Elf32_Sym)
2471                                        : sizeof (Elf64_Sym));
2472
2473   printf (ngettext ("\nSymbol table [%2u] '%s' contains %u entry:\n",
2474                     "\nSymbol table [%2u] '%s' contains %u entries:\n",
2475                     nsyms),
2476           (unsigned int) elf_ndxscn (scn),
2477           elf_strptr (ebl->elf, shstrndx, shdr->sh_name), nsyms);
2478   printf (ngettext (" %lu local symbol  String table: [%2u] '%s'\n",
2479                     " %lu local symbols  String table: [%2u] '%s'\n",
2480                     shdr->sh_info),
2481           (unsigned long int) shdr->sh_info,
2482           (unsigned int) shdr->sh_link,
2483           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
2484
2485   fputs_unlocked (class == ELFCLASS32
2486                   ? _("\
2487   Num:    Value   Size Type    Bind   Vis          Ndx Name\n")
2488                   : _("\
2489   Num:            Value   Size Type    Bind   Vis          Ndx Name\n"),
2490                   stdout);
2491
2492   for (unsigned int cnt = 0; cnt < nsyms; ++cnt)
2493     {
2494       char typebuf[64];
2495       char bindbuf[64];
2496       char scnbuf[64];
2497       Elf32_Word xndx;
2498       GElf_Sym sym_mem;
2499       GElf_Sym *sym = gelf_getsymshndx (data, xndx_data, cnt, &sym_mem, &xndx);
2500
2501       if (unlikely (sym == NULL))
2502         continue;
2503
2504       /* Determine the real section index.  */
2505       if (likely (sym->st_shndx != SHN_XINDEX))
2506         xndx = sym->st_shndx;
2507
2508       printf (_("\
2509 %5u: %0*" PRIx64 " %6" PRId64 " %-7s %-6s %-9s %6s %s"),
2510               cnt,
2511               class == ELFCLASS32 ? 8 : 16,
2512               sym->st_value,
2513               sym->st_size,
2514               ebl_symbol_type_name (ebl, GELF_ST_TYPE (sym->st_info),
2515                                     typebuf, sizeof (typebuf)),
2516               ebl_symbol_binding_name (ebl, GELF_ST_BIND (sym->st_info),
2517                                        bindbuf, sizeof (bindbuf)),
2518               get_visibility_type (GELF_ST_VISIBILITY (sym->st_other)),
2519               ebl_section_name (ebl, sym->st_shndx, xndx, scnbuf,
2520                                 sizeof (scnbuf), NULL, shnum),
2521               elf_strptr (ebl->elf, shdr->sh_link, sym->st_name));
2522
2523       if (versym_data != NULL)
2524         {
2525           /* Get the version information.  */
2526           GElf_Versym versym_mem;
2527           GElf_Versym *versym = gelf_getversym (versym_data, cnt, &versym_mem);
2528
2529           if (versym != NULL && ((*versym & 0x8000) != 0 || *versym > 1))
2530             {
2531               bool is_nobits = false;
2532               bool check_def = xndx != SHN_UNDEF;
2533
2534               if (xndx < SHN_LORESERVE || sym->st_shndx == SHN_XINDEX)
2535                 {
2536                   GElf_Shdr symshdr_mem;
2537                   GElf_Shdr *symshdr =
2538                     gelf_getshdr (elf_getscn (ebl->elf, xndx), &symshdr_mem);
2539
2540                   is_nobits = (symshdr != NULL
2541                                && symshdr->sh_type == SHT_NOBITS);
2542                 }
2543
2544               if (is_nobits || ! check_def)
2545                 {
2546                   /* We must test both.  */
2547                   GElf_Vernaux vernaux_mem;
2548                   GElf_Vernaux *vernaux = NULL;
2549                   size_t vn_offset = 0;
2550
2551                   GElf_Verneed verneed_mem;
2552                   GElf_Verneed *verneed = gelf_getverneed (verneed_data, 0,
2553                                                            &verneed_mem);
2554                   while (verneed != NULL)
2555                     {
2556                       size_t vna_offset = vn_offset;
2557
2558                       vernaux = gelf_getvernaux (verneed_data,
2559                                                  vna_offset += verneed->vn_aux,
2560                                                  &vernaux_mem);
2561                       while (vernaux != NULL
2562                              && vernaux->vna_other != *versym
2563                              && vernaux->vna_next != 0
2564                              && (verneed_data->d_size - vna_offset
2565                                  >= vernaux->vna_next))
2566                         {
2567                           /* Update the offset.  */
2568                           vna_offset += vernaux->vna_next;
2569
2570                           vernaux = (vernaux->vna_next == 0
2571                                      ? NULL
2572                                      : gelf_getvernaux (verneed_data,
2573                                                         vna_offset,
2574                                                         &vernaux_mem));
2575                         }
2576
2577                       /* Check whether we found the version.  */
2578                       if (vernaux != NULL && vernaux->vna_other == *versym)
2579                         /* Found it.  */
2580                         break;
2581
2582                       if (verneed_data->d_size - vn_offset < verneed->vn_next)
2583                         break;
2584
2585                       vn_offset += verneed->vn_next;
2586                       verneed = (verneed->vn_next == 0
2587                                  ? NULL
2588                                  : gelf_getverneed (verneed_data, vn_offset,
2589                                                     &verneed_mem));
2590                     }
2591
2592                   if (vernaux != NULL && vernaux->vna_other == *versym)
2593                     {
2594                       printf ("@%s (%u)",
2595                               elf_strptr (ebl->elf, verneed_stridx,
2596                                           vernaux->vna_name),
2597                               (unsigned int) vernaux->vna_other);
2598                       check_def = 0;
2599                     }
2600                   else if (unlikely (! is_nobits))
2601                     error (0, 0, _("bad dynamic symbol"));
2602                   else
2603                     check_def = 1;
2604                 }
2605
2606               if (check_def && *versym != 0x8001)
2607                 {
2608                   /* We must test both.  */
2609                   size_t vd_offset = 0;
2610
2611                   GElf_Verdef verdef_mem;
2612                   GElf_Verdef *verdef = gelf_getverdef (verdef_data, 0,
2613                                                         &verdef_mem);
2614                   while (verdef != NULL)
2615                     {
2616                       if (verdef->vd_ndx == (*versym & 0x7fff))
2617                         /* Found the definition.  */
2618                         break;
2619
2620                       if (verdef_data->d_size - vd_offset < verdef->vd_next)
2621                         break;
2622
2623                       vd_offset += verdef->vd_next;
2624                       verdef = (verdef->vd_next == 0
2625                                 ? NULL
2626                                 : gelf_getverdef (verdef_data, vd_offset,
2627                                                   &verdef_mem));
2628                     }
2629
2630                   if (verdef != NULL)
2631                     {
2632                       GElf_Verdaux verdaux_mem;
2633                       GElf_Verdaux *verdaux
2634                         = gelf_getverdaux (verdef_data,
2635                                            vd_offset + verdef->vd_aux,
2636                                            &verdaux_mem);
2637
2638                       if (verdaux != NULL)
2639                         printf ((*versym & 0x8000) ? "@%s" : "@@%s",
2640                                 elf_strptr (ebl->elf, verdef_stridx,
2641                                             verdaux->vda_name));
2642                     }
2643                 }
2644             }
2645         }
2646
2647       putchar_unlocked ('\n');
2648     }
2649 }
2650
2651
2652 /* Print version information.  */
2653 static void
2654 print_verinfo (Ebl *ebl)
2655 {
2656   /* Find the version information sections.  For this we have to
2657      search through the section table.  */
2658   Elf_Scn *scn = NULL;
2659
2660   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
2661     {
2662       /* Handle the section if it is part of the versioning handling.  */
2663       GElf_Shdr shdr_mem;
2664       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
2665
2666       if (likely (shdr != NULL))
2667         {
2668           if (shdr->sh_type == SHT_GNU_verneed)
2669             handle_verneed (ebl, scn, shdr);
2670           else if (shdr->sh_type == SHT_GNU_verdef)
2671             handle_verdef (ebl, scn, shdr);
2672           else if (shdr->sh_type == SHT_GNU_versym)
2673             handle_versym (ebl, scn, shdr);
2674         }
2675     }
2676 }
2677
2678
2679 static const char *
2680 get_ver_flags (unsigned int flags)
2681 {
2682   static char buf[32];
2683   char *endp;
2684
2685   if (flags == 0)
2686     return _("none");
2687
2688   if (flags & VER_FLG_BASE)
2689     endp = stpcpy (buf, "BASE ");
2690   else
2691     endp = buf;
2692
2693   if (flags & VER_FLG_WEAK)
2694     {
2695       if (endp != buf)
2696         endp = stpcpy (endp, "| ");
2697
2698       endp = stpcpy (endp, "WEAK ");
2699     }
2700
2701   if (unlikely (flags & ~(VER_FLG_BASE | VER_FLG_WEAK)))
2702     {
2703       strncpy (endp, _("| <unknown>"), buf + sizeof (buf) - endp);
2704       buf[sizeof (buf) - 1] = '\0';
2705     }
2706
2707   return buf;
2708 }
2709
2710
2711 static void
2712 handle_verneed (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
2713 {
2714   int class = gelf_getclass (ebl->elf);
2715
2716   /* Get the data of the section.  */
2717   Elf_Data *data = elf_getdata (scn, NULL);
2718   if (data == NULL)
2719     return;
2720
2721   /* Get the section header string table index.  */
2722   size_t shstrndx;
2723   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2724     error_exit (0, _("cannot get section header string table index"));
2725
2726   GElf_Shdr glink_mem;
2727   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
2728                                    &glink_mem);
2729   if (glink == NULL)
2730     error_exit (0, _("invalid sh_link value in section %zu"),
2731                 elf_ndxscn (scn));
2732
2733   printf (ngettext ("\
2734 \nVersion needs section [%2u] '%s' contains %d entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2735                     "\
2736 \nVersion needs section [%2u] '%s' contains %d entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2737                     shdr->sh_info),
2738           (unsigned int) elf_ndxscn (scn),
2739           elf_strptr (ebl->elf, shstrndx, shdr->sh_name), shdr->sh_info,
2740           class == ELFCLASS32 ? 10 : 18, shdr->sh_addr,
2741           shdr->sh_offset,
2742           (unsigned int) shdr->sh_link,
2743           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
2744
2745   unsigned int offset = 0;
2746   for (int cnt = shdr->sh_info; --cnt >= 0; )
2747     {
2748       /* Get the data at the next offset.  */
2749       GElf_Verneed needmem;
2750       GElf_Verneed *need = gelf_getverneed (data, offset, &needmem);
2751       if (unlikely (need == NULL))
2752         break;
2753
2754       printf (_("  %#06x: Version: %hu  File: %s  Cnt: %hu\n"),
2755               offset, (unsigned short int) need->vn_version,
2756               elf_strptr (ebl->elf, shdr->sh_link, need->vn_file),
2757               (unsigned short int) need->vn_cnt);
2758
2759       unsigned int auxoffset = offset + need->vn_aux;
2760       for (int cnt2 = need->vn_cnt; --cnt2 >= 0; )
2761         {
2762           GElf_Vernaux auxmem;
2763           GElf_Vernaux *aux = gelf_getvernaux (data, auxoffset, &auxmem);
2764           if (unlikely (aux == NULL))
2765             break;
2766
2767           printf (_("  %#06x: Name: %s  Flags: %s  Version: %hu\n"),
2768                   auxoffset,
2769                   elf_strptr (ebl->elf, shdr->sh_link, aux->vna_name),
2770                   get_ver_flags (aux->vna_flags),
2771                   (unsigned short int) aux->vna_other);
2772
2773           if (aux->vna_next == 0)
2774             break;
2775
2776           auxoffset += aux->vna_next;
2777         }
2778
2779       /* Find the next offset.  */
2780       if (need->vn_next == 0)
2781         break;
2782
2783       offset += need->vn_next;
2784     }
2785 }
2786
2787
2788 static void
2789 handle_verdef (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
2790 {
2791   /* Get the data of the section.  */
2792   Elf_Data *data = elf_getdata (scn, NULL);
2793   if (data == NULL)
2794     return;
2795
2796   /* Get the section header string table index.  */
2797   size_t shstrndx;
2798   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2799     error_exit (0, _("cannot get section header string table index"));
2800
2801   GElf_Shdr glink_mem;
2802   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
2803                                    &glink_mem);
2804   if (glink == NULL)
2805     error_exit (0, _("invalid sh_link value in section %zu"),
2806                 elf_ndxscn (scn));
2807
2808   int class = gelf_getclass (ebl->elf);
2809   printf (ngettext ("\
2810 \nVersion definition section [%2u] '%s' contains %d entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2811                     "\
2812 \nVersion definition section [%2u] '%s' contains %d entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2813                     shdr->sh_info),
2814           (unsigned int) elf_ndxscn (scn),
2815           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2816           shdr->sh_info,
2817           class == ELFCLASS32 ? 10 : 18, shdr->sh_addr,
2818           shdr->sh_offset,
2819           (unsigned int) shdr->sh_link,
2820           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
2821
2822   unsigned int offset = 0;
2823   for (int cnt = shdr->sh_info; --cnt >= 0; )
2824     {
2825       /* Get the data at the next offset.  */
2826       GElf_Verdef defmem;
2827       GElf_Verdef *def = gelf_getverdef (data, offset, &defmem);
2828       if (unlikely (def == NULL))
2829         break;
2830
2831       unsigned int auxoffset = offset + def->vd_aux;
2832       GElf_Verdaux auxmem;
2833       GElf_Verdaux *aux = gelf_getverdaux (data, auxoffset, &auxmem);
2834       if (unlikely (aux == NULL))
2835         break;
2836
2837       printf (_("\
2838   %#06x: Version: %hd  Flags: %s  Index: %hd  Cnt: %hd  Name: %s\n"),
2839               offset, def->vd_version,
2840               get_ver_flags (def->vd_flags),
2841               def->vd_ndx,
2842               def->vd_cnt,
2843               elf_strptr (ebl->elf, shdr->sh_link, aux->vda_name));
2844
2845       auxoffset += aux->vda_next;
2846       for (int cnt2 = 1; cnt2 < def->vd_cnt; ++cnt2)
2847         {
2848           aux = gelf_getverdaux (data, auxoffset, &auxmem);
2849           if (unlikely (aux == NULL))
2850             break;
2851
2852           printf (_("  %#06x: Parent %d: %s\n"),
2853                   auxoffset, cnt2,
2854                   elf_strptr (ebl->elf, shdr->sh_link, aux->vda_name));
2855
2856           if (aux->vda_next == 0)
2857             break;
2858
2859           auxoffset += aux->vda_next;
2860         }
2861
2862       /* Find the next offset.  */
2863       if (def->vd_next == 0)
2864         break;
2865       offset += def->vd_next;
2866     }
2867 }
2868
2869
2870 static void
2871 handle_versym (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
2872 {
2873   int class = gelf_getclass (ebl->elf);
2874   const char **vername;
2875   const char **filename;
2876
2877   /* Get the data of the section.  */
2878   Elf_Data *data = elf_getdata (scn, NULL);
2879   if (data == NULL)
2880     return;
2881
2882   /* Get the section header string table index.  */
2883   size_t shstrndx;
2884   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2885     error_exit (0, _("cannot get section header string table index"));
2886
2887   /* We have to find the version definition section and extract the
2888      version names.  */
2889   Elf_Scn *defscn = NULL;
2890   Elf_Scn *needscn = NULL;
2891
2892   Elf_Scn *verscn = NULL;
2893   while ((verscn = elf_nextscn (ebl->elf, verscn)) != NULL)
2894     {
2895       GElf_Shdr vershdr_mem;
2896       GElf_Shdr *vershdr = gelf_getshdr (verscn, &vershdr_mem);
2897
2898       if (likely (vershdr != NULL))
2899         {
2900           if (vershdr->sh_type == SHT_GNU_verdef)
2901             defscn = verscn;
2902           else if (vershdr->sh_type == SHT_GNU_verneed)
2903             needscn = verscn;
2904         }
2905     }
2906
2907   size_t nvername;
2908   if (defscn != NULL || needscn != NULL)
2909     {
2910       /* We have a version information (better should have).  Now get
2911          the version names.  First find the maximum version number.  */
2912       nvername = 0;
2913       if (defscn != NULL)
2914         {
2915           /* Run through the version definitions and find the highest
2916              index.  */
2917           unsigned int offset = 0;
2918           Elf_Data *defdata;
2919           GElf_Shdr defshdrmem;
2920           GElf_Shdr *defshdr;
2921
2922           defdata = elf_getdata (defscn, NULL);
2923           if (unlikely (defdata == NULL))
2924             return;
2925
2926           defshdr = gelf_getshdr (defscn, &defshdrmem);
2927           if (unlikely (defshdr == NULL))
2928             return;
2929
2930           for (unsigned int cnt = 0; cnt < defshdr->sh_info; ++cnt)
2931             {
2932               GElf_Verdef defmem;
2933               GElf_Verdef *def;
2934
2935               /* Get the data at the next offset.  */
2936               def = gelf_getverdef (defdata, offset, &defmem);
2937               if (unlikely (def == NULL))
2938                 break;
2939
2940               nvername = MAX (nvername, (size_t) (def->vd_ndx & 0x7fff));
2941
2942               if (def->vd_next == 0)
2943                 break;
2944               offset += def->vd_next;
2945             }
2946         }
2947       if (needscn != NULL)
2948         {
2949           unsigned int offset = 0;
2950           Elf_Data *needdata;
2951           GElf_Shdr needshdrmem;
2952           GElf_Shdr *needshdr;
2953
2954           needdata = elf_getdata (needscn, NULL);
2955           if (unlikely (needdata == NULL))
2956             return;
2957
2958           needshdr = gelf_getshdr (needscn, &needshdrmem);
2959           if (unlikely (needshdr == NULL))
2960             return;
2961
2962           for (unsigned int cnt = 0; cnt < needshdr->sh_info; ++cnt)
2963             {
2964               GElf_Verneed needmem;
2965               GElf_Verneed *need;
2966               unsigned int auxoffset;
2967               int cnt2;
2968
2969               /* Get the data at the next offset.  */
2970               need = gelf_getverneed (needdata, offset, &needmem);
2971               if (unlikely (need == NULL))
2972                 break;
2973
2974               /* Run through the auxiliary entries.  */
2975               auxoffset = offset + need->vn_aux;
2976               for (cnt2 = need->vn_cnt; --cnt2 >= 0; )
2977                 {
2978                   GElf_Vernaux auxmem;
2979                   GElf_Vernaux *aux;
2980
2981                   aux = gelf_getvernaux (needdata, auxoffset, &auxmem);
2982                   if (unlikely (aux == NULL))
2983                     break;
2984
2985                   nvername = MAX (nvername,
2986                                   (size_t) (aux->vna_other & 0x7fff));
2987
2988                   if (aux->vna_next == 0)
2989                     break;
2990                   auxoffset += aux->vna_next;
2991                 }
2992
2993               if (need->vn_next == 0)
2994                 break;
2995               offset += need->vn_next;
2996             }
2997         }
2998
2999       /* This is the number of versions we know about.  */
3000       ++nvername;
3001
3002       /* Allocate the array.  */
3003       vername = (const char **) alloca (nvername * sizeof (const char *));
3004       memset(vername, 0, nvername * sizeof (const char *));
3005       filename = (const char **) alloca (nvername * sizeof (const char *));
3006       memset(filename, 0, nvername * sizeof (const char *));
3007
3008       /* Run through the data structures again and collect the strings.  */
3009       if (defscn != NULL)
3010         {
3011           /* Run through the version definitions and find the highest
3012              index.  */
3013           unsigned int offset = 0;
3014           Elf_Data *defdata;
3015           GElf_Shdr defshdrmem;
3016           GElf_Shdr *defshdr;
3017
3018           defdata = elf_getdata (defscn, NULL);
3019           if (unlikely (defdata == NULL))
3020             return;
3021
3022           defshdr = gelf_getshdr (defscn, &defshdrmem);
3023           if (unlikely (defshdr == NULL))
3024             return;
3025
3026           for (unsigned int cnt = 0; cnt < defshdr->sh_info; ++cnt)
3027             {
3028
3029               /* Get the data at the next offset.  */
3030               GElf_Verdef defmem;
3031               GElf_Verdef *def = gelf_getverdef (defdata, offset, &defmem);
3032               if (unlikely (def == NULL))
3033                 break;
3034
3035               GElf_Verdaux auxmem;
3036               GElf_Verdaux *aux = gelf_getverdaux (defdata,
3037                                                    offset + def->vd_aux,
3038                                                    &auxmem);
3039               if (unlikely (aux == NULL))
3040                 break;
3041
3042               vername[def->vd_ndx & 0x7fff]
3043                 = elf_strptr (ebl->elf, defshdr->sh_link, aux->vda_name);
3044               filename[def->vd_ndx & 0x7fff] = NULL;
3045
3046               if (def->vd_next == 0)
3047                 break;
3048               offset += def->vd_next;
3049             }
3050         }
3051       if (needscn != NULL)
3052         {
3053           unsigned int offset = 0;
3054
3055           Elf_Data *needdata = elf_getdata (needscn, NULL);
3056           GElf_Shdr needshdrmem;
3057           GElf_Shdr *needshdr = gelf_getshdr (needscn, &needshdrmem);
3058           if (unlikely (needdata == NULL || needshdr == NULL))
3059             return;
3060
3061           for (unsigned int cnt = 0; cnt < needshdr->sh_info; ++cnt)
3062             {
3063               /* Get the data at the next offset.  */
3064               GElf_Verneed needmem;
3065               GElf_Verneed *need = gelf_getverneed (needdata, offset,
3066                                                     &needmem);
3067               if (unlikely (need == NULL))
3068                 break;
3069
3070               /* Run through the auxiliary entries.  */
3071               unsigned int auxoffset = offset + need->vn_aux;
3072               for (int cnt2 = need->vn_cnt; --cnt2 >= 0; )
3073                 {
3074                   GElf_Vernaux auxmem;
3075                   GElf_Vernaux *aux = gelf_getvernaux (needdata, auxoffset,
3076                                                        &auxmem);
3077                   if (unlikely (aux == NULL))
3078                     break;
3079
3080                   vername[aux->vna_other & 0x7fff]
3081                     = elf_strptr (ebl->elf, needshdr->sh_link, aux->vna_name);
3082                   filename[aux->vna_other & 0x7fff]
3083                     = elf_strptr (ebl->elf, needshdr->sh_link, need->vn_file);
3084
3085                   if (aux->vna_next == 0)
3086                     break;
3087                   auxoffset += aux->vna_next;
3088                 }
3089
3090               if (need->vn_next == 0)
3091                 break;
3092               offset += need->vn_next;
3093             }
3094         }
3095     }
3096   else
3097     {
3098       vername = NULL;
3099       nvername = 1;
3100       filename = NULL;
3101     }
3102
3103   GElf_Shdr glink_mem;
3104   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
3105                                    &glink_mem);
3106   size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_HALF, 1, EV_CURRENT);
3107   if (glink == NULL)
3108     error_exit (0, _("invalid sh_link value in section %zu"),
3109                 elf_ndxscn (scn));
3110
3111   /* Print the header.  */
3112   printf (ngettext ("\
3113 \nVersion symbols section [%2u] '%s' contains %d entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'",
3114                     "\
3115 \nVersion symbols section [%2u] '%s' contains %d entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'",
3116                     shdr->sh_size / sh_entsize),
3117           (unsigned int) elf_ndxscn (scn),
3118           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
3119           (int) (shdr->sh_size / sh_entsize),
3120           class == ELFCLASS32 ? 10 : 18, shdr->sh_addr,
3121           shdr->sh_offset,
3122           (unsigned int) shdr->sh_link,
3123           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
3124
3125   /* Now we can finally look at the actual contents of this section.  */
3126   for (unsigned int cnt = 0; cnt < shdr->sh_size / sh_entsize; ++cnt)
3127     {
3128       if (cnt % 2 == 0)
3129         printf ("\n %4d:", cnt);
3130
3131       GElf_Versym symmem;
3132       GElf_Versym *sym = gelf_getversym (data, cnt, &symmem);
3133       if (sym == NULL)
3134         break;
3135
3136       switch (*sym)
3137         {
3138           ssize_t n;
3139         case 0:
3140           fputs_unlocked (_("   0 *local*                     "),
3141                           stdout);
3142           break;
3143
3144         case 1:
3145           fputs_unlocked (_("   1 *global*                    "),
3146                           stdout);
3147           break;
3148
3149         default:
3150           n = printf ("%4d%c%s",
3151                       *sym & 0x7fff, *sym & 0x8000 ? 'h' : ' ',
3152                       (vername != NULL
3153                        && (unsigned int) (*sym & 0x7fff) < nvername)
3154                       ? vername[*sym & 0x7fff] : "???");
3155           if ((unsigned int) (*sym & 0x7fff) < nvername
3156               && filename != NULL && filename[*sym & 0x7fff] != NULL)
3157             n += printf ("(%s)", filename[*sym & 0x7fff]);
3158           printf ("%*s", MAX (0, 33 - (int) n), " ");
3159           break;
3160         }
3161     }
3162   putchar_unlocked ('\n');
3163 }
3164
3165
3166 static void
3167 print_hash_info (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, size_t shstrndx,
3168                  uint_fast32_t maxlength, Elf32_Word nbucket,
3169                  uint_fast32_t nsyms, uint32_t *lengths, const char *extrastr)
3170 {
3171   uint32_t *counts = xcalloc (maxlength + 1, sizeof (uint32_t));
3172
3173   for (Elf32_Word cnt = 0; cnt < nbucket; ++cnt)
3174     ++counts[lengths[cnt]];
3175
3176   GElf_Shdr glink_mem;
3177   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf,
3178                                                shdr->sh_link),
3179                                    &glink_mem);
3180   if (glink == NULL)
3181     {
3182       error (0, 0, _("invalid sh_link value in section %zu"),
3183              elf_ndxscn (scn));
3184       return;
3185     }
3186
3187   printf (ngettext ("\
3188 \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",
3189                     "\
3190 \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",
3191                     nbucket),
3192           (unsigned int) elf_ndxscn (scn),
3193           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
3194           (int) nbucket,
3195           gelf_getclass (ebl->elf) == ELFCLASS32 ? 10 : 18,
3196           shdr->sh_addr,
3197           shdr->sh_offset,
3198           (unsigned int) shdr->sh_link,
3199           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
3200
3201   if (extrastr != NULL)
3202     fputs (extrastr, stdout);
3203
3204   if (likely (nbucket > 0))
3205     {
3206       uint64_t success = 0;
3207
3208       /* xgettext:no-c-format */
3209       fputs_unlocked (_("\
3210  Length  Number  % of total  Coverage\n"), stdout);
3211       printf (_("      0  %6" PRIu32 "      %5.1f%%\n"),
3212               counts[0], (counts[0] * 100.0) / nbucket);
3213
3214       uint64_t nzero_counts = 0;
3215       for (Elf32_Word cnt = 1; cnt <= maxlength; ++cnt)
3216         {
3217           nzero_counts += counts[cnt] * cnt;
3218           printf (_("\
3219 %7d  %6" PRIu32 "      %5.1f%%    %5.1f%%\n"),
3220                   (int) cnt, counts[cnt], (counts[cnt] * 100.0) / nbucket,
3221                   (nzero_counts * 100.0) / nsyms);
3222         }
3223
3224       Elf32_Word acc = 0;
3225       for (Elf32_Word cnt = 1; cnt <= maxlength; ++cnt)
3226         {
3227           acc += cnt;
3228           success += counts[cnt] * acc;
3229         }
3230
3231       printf (_("\
3232  Average number of tests:   successful lookup: %f\n\
3233                           unsuccessful lookup: %f\n"),
3234               (double) success / (double) nzero_counts,
3235               (double) nzero_counts / (double) nbucket);
3236     }
3237
3238   free (counts);
3239 }
3240
3241
3242 /* This function handles the traditional System V-style hash table format.  */
3243 static void
3244 handle_sysv_hash (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, size_t shstrndx)
3245 {
3246   Elf_Data *data = elf_getdata (scn, NULL);
3247   if (unlikely (data == NULL))
3248     {
3249       error (0, 0, _("cannot get data for section %d: %s"),
3250              (int) elf_ndxscn (scn), elf_errmsg (-1));
3251       return;
3252     }
3253
3254   if (unlikely (data->d_size < 2 * sizeof (Elf32_Word)))
3255     {
3256     invalid_data:
3257       error (0, 0, _("invalid data in sysv.hash section %d"),
3258              (int) elf_ndxscn (scn));
3259       return;
3260     }
3261
3262   Elf32_Word nbucket = ((Elf32_Word *) data->d_buf)[0];
3263   Elf32_Word nchain = ((Elf32_Word *) data->d_buf)[1];
3264
3265   uint64_t used_buf = (2ULL + nchain + nbucket) * sizeof (Elf32_Word);
3266   if (used_buf > data->d_size)
3267     goto invalid_data;
3268
3269   Elf32_Word *bucket = &((Elf32_Word *) data->d_buf)[2];
3270   Elf32_Word *chain = &((Elf32_Word *) data->d_buf)[2 + nbucket];
3271
3272   uint32_t *lengths = xcalloc (nbucket, sizeof (uint32_t));
3273
3274   uint_fast32_t maxlength = 0;
3275   uint_fast32_t nsyms = 0;
3276   for (Elf32_Word cnt = 0; cnt < nbucket; ++cnt)
3277     {
3278       Elf32_Word inner = bucket[cnt];
3279       Elf32_Word chain_len = 0;
3280       while (inner > 0 && inner < nchain)
3281         {
3282           ++nsyms;
3283           ++chain_len;
3284           if (chain_len > nchain)
3285             {
3286               error (0, 0, _("invalid chain in sysv.hash section %d"),
3287                      (int) elf_ndxscn (scn));
3288               free (lengths);
3289               return;
3290             }
3291           if (maxlength < ++lengths[cnt])
3292             ++maxlength;
3293
3294           inner = chain[inner];
3295         }
3296     }
3297
3298   print_hash_info (ebl, scn, shdr, shstrndx, maxlength, nbucket, nsyms,
3299                    lengths, NULL);
3300
3301   free (lengths);
3302 }
3303
3304
3305 /* This function handles the incorrect, System V-style hash table
3306    format some 64-bit architectures use.  */
3307 static void
3308 handle_sysv_hash64 (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, size_t shstrndx)
3309 {
3310   Elf_Data *data = elf_getdata (scn, NULL);
3311   if (unlikely (data == NULL))
3312     {
3313       error (0, 0, _("cannot get data for section %d: %s"),
3314              (int) elf_ndxscn (scn), elf_errmsg (-1));
3315       return;
3316     }
3317
3318   if (unlikely (data->d_size < 2 * sizeof (Elf64_Xword)))
3319     {
3320     invalid_data:
3321       error (0, 0, _("invalid data in sysv.hash64 section %d"),
3322              (int) elf_ndxscn (scn));
3323       return;
3324     }
3325
3326   Elf64_Xword nbucket = ((Elf64_Xword *) data->d_buf)[0];
3327   Elf64_Xword nchain = ((Elf64_Xword *) data->d_buf)[1];
3328
3329   uint64_t maxwords = data->d_size / sizeof (Elf64_Xword);
3330   if (maxwords < 2
3331       || maxwords - 2 < nbucket
3332       || maxwords - 2 - nbucket < nchain)
3333     goto invalid_data;
3334
3335   Elf64_Xword *bucket = &((Elf64_Xword *) data->d_buf)[2];
3336   Elf64_Xword *chain = &((Elf64_Xword *) 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 (Elf64_Xword cnt = 0; cnt < nbucket; ++cnt)
3343     {
3344       Elf64_Xword inner = bucket[cnt];
3345       Elf64_Xword 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.hash64 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 GNU-style hash table format.  */
3372 static void
3373 handle_gnu_hash (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, size_t shstrndx)
3374 {
3375   uint32_t *lengths = NULL;
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 < 4 * sizeof (Elf32_Word)))
3385     {
3386     invalid_data:
3387       free (lengths);
3388       error (0, 0, _("invalid data in gnu.hash section %d"),
3389              (int) elf_ndxscn (scn));
3390       return;
3391     }
3392
3393   Elf32_Word nbucket = ((Elf32_Word *) data->d_buf)[0];
3394   Elf32_Word symbias = ((Elf32_Word *) data->d_buf)[1];
3395
3396   /* Next comes the size of the bitmap.  It's measured in words for
3397      the architecture.  It's 32 bits for 32 bit archs, and 64 bits for
3398      64 bit archs.  There is always a bloom filter present, so zero is
3399      an invalid value.  */
3400   Elf32_Word bitmask_words = ((Elf32_Word *) data->d_buf)[2];
3401   if (gelf_getclass (ebl->elf) == ELFCLASS64)
3402     bitmask_words *= 2;
3403
3404   if (bitmask_words == 0)
3405     goto invalid_data;
3406
3407   Elf32_Word shift = ((Elf32_Word *) data->d_buf)[3];
3408
3409   /* Is there still room for the sym chain?
3410      Use uint64_t calculation to prevent 32bit overflow.  */
3411   uint64_t used_buf = (4ULL + bitmask_words + nbucket) * sizeof (Elf32_Word);
3412   uint32_t max_nsyms = (data->d_size - used_buf) / sizeof (Elf32_Word);
3413   if (used_buf > data->d_size)
3414     goto invalid_data;
3415
3416   lengths = xcalloc (nbucket, sizeof (uint32_t));
3417
3418   Elf32_Word *bitmask = &((Elf32_Word *) data->d_buf)[4];
3419   Elf32_Word *bucket = &((Elf32_Word *) data->d_buf)[4 + bitmask_words];
3420   Elf32_Word *chain = &((Elf32_Word *) data->d_buf)[4 + bitmask_words
3421                                                     + nbucket];
3422
3423   /* Compute distribution of chain lengths.  */
3424   uint_fast32_t maxlength = 0;
3425   uint_fast32_t nsyms = 0;
3426   for (Elf32_Word cnt = 0; cnt < nbucket; ++cnt)
3427     if (bucket[cnt] != 0)
3428       {
3429         Elf32_Word inner = bucket[cnt] - symbias;
3430         do
3431           {
3432             ++nsyms;
3433             if (maxlength < ++lengths[cnt])
3434               ++maxlength;
3435             if (inner >= max_nsyms)
3436               goto invalid_data;
3437           }
3438         while ((chain[inner++] & 1) == 0);
3439       }
3440
3441   /* Count bits in bitmask.  */
3442   uint_fast32_t nbits = 0;
3443   for (Elf32_Word cnt = 0; cnt < bitmask_words; ++cnt)
3444     {
3445       uint_fast32_t word = bitmask[cnt];
3446
3447       word = (word & 0x55555555) + ((word >> 1) & 0x55555555);
3448       word = (word & 0x33333333) + ((word >> 2) & 0x33333333);
3449       word = (word & 0x0f0f0f0f) + ((word >> 4) & 0x0f0f0f0f);
3450       word = (word & 0x00ff00ff) + ((word >> 8) & 0x00ff00ff);
3451       nbits += (word & 0x0000ffff) + ((word >> 16) & 0x0000ffff);
3452     }
3453
3454   char *str = xasprintf (_("\
3455  Symbol Bias: %u\n\
3456  Bitmask Size: %zu bytes  %" PRIuFAST32 "%% bits set  2nd hash shift: %u\n"),
3457                          (unsigned int) symbias,
3458                          bitmask_words * sizeof (Elf32_Word),
3459                          ((nbits * 100 + 50)
3460                           / (uint_fast32_t) (bitmask_words
3461                                               * sizeof (Elf32_Word) * 8)),
3462                           (unsigned int) shift);
3463
3464   print_hash_info (ebl, scn, shdr, shstrndx, maxlength, nbucket, nsyms,
3465                    lengths, str);
3466
3467   free (str);
3468   free (lengths);
3469 }
3470
3471
3472 /* Find the symbol table(s).  For this we have to search through the
3473    section table.  */
3474 static void
3475 handle_hash (Ebl *ebl)
3476 {
3477   /* Get the section header string table index.  */
3478   size_t shstrndx;
3479   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
3480     error_exit (0, _("cannot get section header string table index"));
3481
3482   Elf_Scn *scn = NULL;
3483   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
3484     {
3485       /* Handle the section if it is a symbol table.  */
3486       GElf_Shdr shdr_mem;
3487       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
3488
3489       if (likely (shdr != NULL))
3490         {
3491           if ((shdr->sh_type == SHT_HASH || shdr->sh_type == SHT_GNU_HASH)
3492               && (shdr->sh_flags & SHF_COMPRESSED) != 0)
3493             {
3494               if (elf_compress (scn, 0, 0) < 0)
3495                 printf ("WARNING: %s [%zd]\n",
3496                         _("Couldn't uncompress section"),
3497                         elf_ndxscn (scn));
3498               shdr = gelf_getshdr (scn, &shdr_mem);
3499               if (unlikely (shdr == NULL))
3500                 error_exit (0, _("cannot get section [%zd] header: %s"),
3501                             elf_ndxscn (scn), elf_errmsg (-1));
3502             }
3503
3504           if (shdr->sh_type == SHT_HASH)
3505             {
3506               if (ebl_sysvhash_entrysize (ebl) == sizeof (Elf64_Xword))
3507                 handle_sysv_hash64 (ebl, scn, shdr, shstrndx);
3508               else
3509                 handle_sysv_hash (ebl, scn, shdr, shstrndx);
3510             }
3511           else if (shdr->sh_type == SHT_GNU_HASH)
3512             handle_gnu_hash (ebl, scn, shdr, shstrndx);
3513         }
3514     }
3515 }
3516
3517
3518 static void
3519 print_liblist (Ebl *ebl)
3520 {
3521   /* Find the library list sections.  For this we have to search
3522      through the section table.  */
3523   Elf_Scn *scn = NULL;
3524
3525   /* Get the section header string table index.  */
3526   size_t shstrndx;
3527   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
3528     error_exit (0, _("cannot get section header string table index"));
3529
3530   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
3531     {
3532       GElf_Shdr shdr_mem;
3533       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
3534
3535       if (shdr != NULL && shdr->sh_type == SHT_GNU_LIBLIST)
3536         {
3537           size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_LIB, 1, EV_CURRENT);
3538           int nentries = shdr->sh_size / sh_entsize;
3539           printf (ngettext ("\
3540 \nLibrary list section [%2zu] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
3541                             "\
3542 \nLibrary list section [%2zu] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
3543                             nentries),
3544                   elf_ndxscn (scn),
3545                   elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
3546                   shdr->sh_offset,
3547                   nentries);
3548
3549           Elf_Data *data = elf_getdata (scn, NULL);
3550           if (data == NULL)
3551             return;
3552
3553           puts (_("\
3554        Library                       Time Stamp          Checksum Version Flags"));
3555
3556           for (int cnt = 0; cnt < nentries; ++cnt)
3557             {
3558               GElf_Lib lib_mem;
3559               GElf_Lib *lib = gelf_getlib (data, cnt, &lib_mem);
3560               if (unlikely (lib == NULL))
3561                 continue;
3562
3563               time_t t = (time_t) lib->l_time_stamp;
3564               struct tm *tm = gmtime (&t);
3565               if (unlikely (tm == NULL))
3566                 continue;
3567
3568               printf ("  [%2d] %-29s %04u-%02u-%02uT%02u:%02u:%02u %08x %-7u %u\n",
3569                       cnt, elf_strptr (ebl->elf, shdr->sh_link, lib->l_name),
3570                       tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
3571                       tm->tm_hour, tm->tm_min, tm->tm_sec,
3572                       (unsigned int) lib->l_checksum,
3573                       (unsigned int) lib->l_version,
3574                       (unsigned int) lib->l_flags);
3575             }
3576         }
3577     }
3578 }
3579
3580 static inline size_t
3581 left (Elf_Data *data,
3582       const unsigned char *p)
3583 {
3584   return (const unsigned char *) data->d_buf + data->d_size - p;
3585 }
3586
3587 static void
3588 print_attributes (Ebl *ebl, const GElf_Ehdr *ehdr)
3589 {
3590   /* Find the object attributes sections.  For this we have to search
3591      through the section table.  */
3592   Elf_Scn *scn = NULL;
3593
3594   /* Get the section header string table index.  */
3595   size_t shstrndx;
3596   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
3597     error_exit (0, _("cannot get section header string table index"));
3598
3599   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
3600     {
3601       GElf_Shdr shdr_mem;
3602       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
3603
3604       if (shdr == NULL || (shdr->sh_type != SHT_GNU_ATTRIBUTES
3605                            && (shdr->sh_type != SHT_ARM_ATTRIBUTES
3606                                || ehdr->e_machine != EM_ARM)
3607                            && (shdr->sh_type != SHT_CSKY_ATTRIBUTES
3608                                || ehdr->e_machine != EM_CSKY)))
3609         continue;
3610
3611       printf (_("\
3612 \nObject attributes section [%2zu] '%s' of %" PRIu64
3613                        " bytes at offset %#0" PRIx64 ":\n"),
3614               elf_ndxscn (scn),
3615               elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
3616               shdr->sh_size, shdr->sh_offset);
3617
3618       Elf_Data *data = elf_rawdata (scn, NULL);
3619       if (unlikely (data == NULL || data->d_size == 0))
3620         return;
3621
3622       const unsigned char *p = data->d_buf;
3623
3624       /* There is only one 'version', A.  */
3625       if (unlikely (*p++ != 'A'))
3626         return;
3627
3628       fputs_unlocked (_("  Owner          Size\n"), stdout);
3629
3630       /* Loop over the sections.  */
3631       while (left (data, p) >= 4)
3632         {
3633           /* Section length.  */
3634           uint32_t len;
3635           memcpy (&len, p, sizeof len);
3636
3637           if (MY_ELFDATA != ehdr->e_ident[EI_DATA])
3638             CONVERT (len);
3639
3640           if (unlikely (len > left (data, p)))
3641             break;
3642
3643           /* Section vendor name.  */
3644           const unsigned char *name = p + sizeof len;
3645           p += len;
3646
3647           unsigned const char *q = memchr (name, '\0', len);
3648           if (unlikely (q == NULL))
3649             break;
3650           ++q;
3651
3652           printf (_("  %-13s  %4" PRIu32 "\n"), name, len);
3653
3654           bool gnu_vendor = (q - name == sizeof "gnu"
3655                              && !memcmp (name, "gnu", sizeof "gnu"));
3656
3657           /* Loop over subsections.  */
3658           if (shdr->sh_type != SHT_GNU_ATTRIBUTES
3659               || gnu_vendor)
3660             while (q < p)
3661               {
3662                 const unsigned char *const sub = q;
3663
3664                 unsigned int subsection_tag;
3665                 get_uleb128 (subsection_tag, q, p);
3666                 if (unlikely (q >= p))
3667                   break;
3668
3669                 uint32_t subsection_len;
3670                 if (unlikely (p - sub < (ptrdiff_t) sizeof subsection_len))
3671                   break;
3672
3673                 memcpy (&subsection_len, q, sizeof subsection_len);
3674
3675                 if (MY_ELFDATA != ehdr->e_ident[EI_DATA])
3676                   CONVERT (subsection_len);
3677
3678                 /* Don't overflow, ptrdiff_t might be 32bits, but signed.  */
3679                 if (unlikely (subsection_len == 0
3680                               || subsection_len >= (uint32_t) PTRDIFF_MAX
3681                               || p - sub < (ptrdiff_t) subsection_len))
3682                   break;
3683
3684                 const unsigned char *r = q + sizeof subsection_len;
3685                 q = sub + subsection_len;
3686
3687                 switch (subsection_tag)
3688                   {
3689                   default:
3690                     /* Unknown subsection, print and skip.  */
3691                     printf (_("    %-4u %12" PRIu32 "\n"),
3692                             subsection_tag, subsection_len);
3693                     break;
3694
3695                   case 1:       /* Tag_File */
3696                     printf (_("    File: %11" PRIu32 "\n"),
3697                             subsection_len);
3698
3699                     while (r < q)
3700                       {
3701                         unsigned int tag;
3702                         get_uleb128 (tag, r, q);
3703                         if (unlikely (r >= q))
3704                           break;
3705
3706                         /* GNU style tags have either a uleb128 value,
3707                            when lowest bit is not set, or a string
3708                            when the lowest bit is set.
3709                            "compatibility" (32) is special.  It has
3710                            both a string and a uleb128 value.  For
3711                            non-gnu we assume 6 till 31 only take ints.
3712                            XXX see arm backend, do we need a separate
3713                            hook?  */
3714                         uint64_t value = 0;
3715                         const char *string = NULL;
3716                         if (tag == 32 || (tag & 1) == 0
3717                             || (! gnu_vendor && (tag > 5 && tag < 32)))
3718                           {
3719                             get_uleb128 (value, r, q);
3720                             if (r > q)
3721                               break;
3722                           }
3723                         if (tag == 32
3724                             || ((tag & 1) != 0
3725                                 && (gnu_vendor
3726                                     || (! gnu_vendor && tag > 32)))
3727                             || (! gnu_vendor && tag > 3 && tag < 6))
3728                           {
3729                             string = (const char *) r;
3730                             r = memchr (r, '\0', q - r);
3731                             if (r == NULL)
3732                               break;
3733                             ++r;
3734                           }
3735
3736                         const char *tag_name = NULL;
3737                         const char *value_name = NULL;
3738                         ebl_check_object_attribute (ebl, (const char *) name,
3739                                                     tag, value,
3740                                                     &tag_name, &value_name);
3741
3742                         if (tag_name != NULL)
3743                           {
3744                             if (tag == 32)
3745                               printf (_("      %s: %" PRId64 ", %s\n"),
3746                                       tag_name, value, string);
3747                             else if (string == NULL && value_name == NULL)
3748                               printf (_("      %s: %" PRId64 "\n"),
3749                                       tag_name, value);
3750                             else
3751                               printf (_("      %s: %s\n"),
3752                                       tag_name, string ?: value_name);
3753                           }
3754                         else
3755                           {
3756                             /* For "gnu" vendor 32 "compatibility" has
3757                                already been handled above.  */
3758                             assert (tag != 32
3759                                     || strcmp ((const char *) name, "gnu"));
3760                             if (string == NULL)
3761                               printf (_("      %u: %" PRId64 "\n"),
3762                                       tag, value);
3763                             else
3764                               printf (_("      %u: %s\n"),
3765                                       tag, string);
3766                           }
3767                       }
3768                   }
3769               }
3770         }
3771     }
3772 }
3773
3774
3775 void
3776 print_dwarf_addr (Dwfl_Module *dwflmod,
3777                   int address_size, Dwarf_Addr address, Dwarf_Addr raw)
3778 {
3779   /* See if there is a name we can give for this address.  */
3780   GElf_Sym sym;
3781   GElf_Off off = 0;
3782   const char *name = (print_address_names && ! print_unresolved_addresses)
3783     ? dwfl_module_addrinfo (dwflmod, address, &off, &sym, NULL, NULL, NULL)
3784     : NULL;
3785
3786   const char *scn;
3787   if (print_unresolved_addresses)
3788     {
3789       address = raw;
3790       scn = NULL;
3791     }
3792   else
3793     {
3794       /* Relativize the address.  */
3795       int n = dwfl_module_relocations (dwflmod);
3796       int i = n < 1 ? -1 : dwfl_module_relocate_address (dwflmod, &address);
3797
3798       /* In an ET_REL file there is a section name to refer to.  */
3799       scn = (i < 0 ? NULL
3800              : dwfl_module_relocation_info (dwflmod, i, NULL));
3801     }
3802
3803   if ((name != NULL
3804        ? (off != 0
3805           ? (scn != NULL
3806              ? (address_size == 0
3807                 ? printf ("%s+%#" PRIx64 " <%s+%#" PRIx64 ">",
3808                           scn, address, name, off)
3809                 : printf ("%s+%#0*" PRIx64 " <%s+%#" PRIx64 ">",
3810                           scn, 2 + address_size * 2, address,
3811                           name, off))
3812              : (address_size == 0
3813                 ? printf ("%#" PRIx64 " <%s+%#" PRIx64 ">",
3814                           address, name, off)
3815                 : printf ("%#0*" PRIx64 " <%s+%#" PRIx64 ">",
3816                           2 + address_size * 2, address,
3817                           name, off)))
3818           : (scn != NULL
3819              ? (address_size == 0
3820                 ? printf ("%s+%#" PRIx64 " <%s>", scn, address, name)
3821                 : printf ("%s+%#0*" PRIx64 " <%s>",
3822                            scn, 2 + address_size * 2, address, name))
3823              : (address_size == 0
3824                 ? printf ("%#" PRIx64 " <%s>", address, name)
3825                 : printf ("%#0*" PRIx64 " <%s>",
3826                           2 + address_size * 2, address, name))))
3827        : (scn != NULL
3828           ? (address_size == 0
3829              ? printf ("%s+%#" PRIx64, scn, address)
3830              : printf ("%s+%#0*" PRIx64, scn, 2 + address_size * 2, address))
3831           : (address_size == 0
3832              ? printf ("%#" PRIx64, address)
3833              : printf ("%#0*" PRIx64, 2 + address_size * 2, address)))) < 0)
3834     error_exit (0, _("sprintf failure"));
3835 }
3836
3837
3838 static const char *
3839 dwarf_tag_string (unsigned int tag)
3840 {
3841   switch (tag)
3842     {
3843 #define DWARF_ONE_KNOWN_DW_TAG(NAME, CODE) case CODE: return #NAME;
3844       DWARF_ALL_KNOWN_DW_TAG
3845 #undef DWARF_ONE_KNOWN_DW_TAG
3846     default:
3847       return NULL;
3848     }
3849 }
3850
3851
3852 static const char *
3853 dwarf_attr_string (unsigned int attrnum)
3854 {
3855   switch (attrnum)
3856     {
3857 #define DWARF_ONE_KNOWN_DW_AT(NAME, CODE) case CODE: return #NAME;
3858       DWARF_ALL_KNOWN_DW_AT
3859 #undef DWARF_ONE_KNOWN_DW_AT
3860     default:
3861       return NULL;
3862     }
3863 }
3864
3865
3866 static const char *
3867 dwarf_form_string (unsigned int form)
3868 {
3869   switch (form)
3870     {
3871 #define DWARF_ONE_KNOWN_DW_FORM(NAME, CODE) case CODE: return #NAME;
3872       DWARF_ALL_KNOWN_DW_FORM
3873 #undef DWARF_ONE_KNOWN_DW_FORM
3874     default:
3875       return NULL;
3876     }
3877 }
3878
3879
3880 static const char *
3881 dwarf_lang_string (unsigned int lang)
3882 {
3883   switch (lang)
3884     {
3885 #define DWARF_ONE_KNOWN_DW_LANG(NAME, CODE) case CODE: return #NAME;
3886       DWARF_ALL_KNOWN_DW_LANG
3887 #undef DWARF_ONE_KNOWN_DW_LANG
3888     default:
3889       return NULL;
3890     }
3891 }
3892
3893
3894 static const char *
3895 dwarf_inline_string (unsigned int code)
3896 {
3897   static const char *const known[] =
3898     {
3899 #define DWARF_ONE_KNOWN_DW_INL(NAME, CODE) [CODE] = #NAME,
3900       DWARF_ALL_KNOWN_DW_INL
3901 #undef DWARF_ONE_KNOWN_DW_INL
3902     };
3903
3904   if (likely (code < sizeof (known) / sizeof (known[0])))
3905     return known[code];
3906
3907   return NULL;
3908 }
3909
3910
3911 static const char *
3912 dwarf_encoding_string (unsigned int code)
3913 {
3914   static const char *const known[] =
3915     {
3916 #define DWARF_ONE_KNOWN_DW_ATE(NAME, CODE) [CODE] = #NAME,
3917       DWARF_ALL_KNOWN_DW_ATE
3918 #undef DWARF_ONE_KNOWN_DW_ATE
3919     };
3920
3921   if (likely (code < sizeof (known) / sizeof (known[0])))
3922     return known[code];
3923
3924   return NULL;
3925 }
3926
3927
3928 static const char *
3929 dwarf_access_string (unsigned int code)
3930 {
3931   static const char *const known[] =
3932     {
3933 #define DWARF_ONE_KNOWN_DW_ACCESS(NAME, CODE) [CODE] = #NAME,
3934       DWARF_ALL_KNOWN_DW_ACCESS
3935 #undef DWARF_ONE_KNOWN_DW_ACCESS
3936     };
3937
3938   if (likely (code < sizeof (known) / sizeof (known[0])))
3939     return known[code];
3940
3941   return NULL;
3942 }
3943
3944
3945 static const char *
3946 dwarf_defaulted_string (unsigned int code)
3947 {
3948   static const char *const known[] =
3949     {
3950 #define DWARF_ONE_KNOWN_DW_DEFAULTED(NAME, CODE) [CODE] = #NAME,
3951       DWARF_ALL_KNOWN_DW_DEFAULTED
3952 #undef DWARF_ONE_KNOWN_DW_DEFAULTED
3953     };
3954
3955   if (likely (code < sizeof (known) / sizeof (known[0])))
3956     return known[code];
3957
3958   return NULL;
3959 }
3960
3961
3962 static const char *
3963 dwarf_visibility_string (unsigned int code)
3964 {
3965   static const char *const known[] =
3966     {
3967 #define DWARF_ONE_KNOWN_DW_VIS(NAME, CODE) [CODE] = #NAME,
3968       DWARF_ALL_KNOWN_DW_VIS
3969 #undef DWARF_ONE_KNOWN_DW_VIS
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_virtuality_string (unsigned int code)
3981 {
3982   static const char *const known[] =
3983     {
3984 #define DWARF_ONE_KNOWN_DW_VIRTUALITY(NAME, CODE) [CODE] = #NAME,
3985       DWARF_ALL_KNOWN_DW_VIRTUALITY
3986 #undef DWARF_ONE_KNOWN_DW_VIRTUALITY
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_identifier_case_string (unsigned int code)
3998 {
3999   static const char *const known[] =
4000     {
4001 #define DWARF_ONE_KNOWN_DW_ID(NAME, CODE) [CODE] = #NAME,
4002       DWARF_ALL_KNOWN_DW_ID
4003 #undef DWARF_ONE_KNOWN_DW_ID
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_calling_convention_string (unsigned int code)
4015 {
4016   static const char *const known[] =
4017     {
4018 #define DWARF_ONE_KNOWN_DW_CC(NAME, CODE) [CODE] = #NAME,
4019       DWARF_ALL_KNOWN_DW_CC
4020 #undef DWARF_ONE_KNOWN_DW_CC
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_ordering_string (unsigned int code)
4032 {
4033   static const char *const known[] =
4034     {
4035 #define DWARF_ONE_KNOWN_DW_ORD(NAME, CODE) [CODE] = #NAME,
4036       DWARF_ALL_KNOWN_DW_ORD
4037 #undef DWARF_ONE_KNOWN_DW_ORD
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_discr_list_string (unsigned int code)
4049 {
4050   static const char *const known[] =
4051     {
4052 #define DWARF_ONE_KNOWN_DW_DSC(NAME, CODE) [CODE] = #NAME,
4053       DWARF_ALL_KNOWN_DW_DSC
4054 #undef DWARF_ONE_KNOWN_DW_DSC
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_locexpr_opcode_string (unsigned int code)
4066 {
4067   static const char *const known[] =
4068     {
4069       /* Normally we can't afford building huge table of 64K entries,
4070          most of them zero, just because there are a couple defined
4071          values at the far end.  In case of opcodes, it's OK.  */
4072 #define DWARF_ONE_KNOWN_DW_OP(NAME, CODE) [CODE] = #NAME,
4073       DWARF_ALL_KNOWN_DW_OP
4074 #undef DWARF_ONE_KNOWN_DW_OP
4075     };
4076
4077   if (likely (code < sizeof (known) / sizeof (known[0])))
4078     return known[code];
4079
4080   return NULL;
4081 }
4082
4083
4084 static const char *
4085 dwarf_unit_string (unsigned int type)
4086 {
4087   switch (type)
4088     {
4089 #define DWARF_ONE_KNOWN_DW_UT(NAME, CODE) case CODE: return #NAME;
4090       DWARF_ALL_KNOWN_DW_UT
4091 #undef DWARF_ONE_KNOWN_DW_UT
4092     default:
4093       return NULL;
4094     }
4095 }
4096
4097
4098 static const char *
4099 dwarf_range_list_encoding_string (unsigned int kind)
4100 {
4101   switch (kind)
4102     {
4103 #define DWARF_ONE_KNOWN_DW_RLE(NAME, CODE) case CODE: return #NAME;
4104       DWARF_ALL_KNOWN_DW_RLE
4105 #undef DWARF_ONE_KNOWN_DW_RLE
4106     default:
4107       return NULL;
4108     }
4109 }
4110
4111
4112 static const char *
4113 dwarf_loc_list_encoding_string (unsigned int kind)
4114 {
4115   switch (kind)
4116     {
4117 #define DWARF_ONE_KNOWN_DW_LLE(NAME, CODE) case CODE: return #NAME;
4118       DWARF_ALL_KNOWN_DW_LLE
4119 #undef DWARF_ONE_KNOWN_DW_LLE
4120     default:
4121       return NULL;
4122     }
4123 }
4124
4125
4126 static const char *
4127 dwarf_line_content_description_string (unsigned int kind)
4128 {
4129   switch (kind)
4130     {
4131 #define DWARF_ONE_KNOWN_DW_LNCT(NAME, CODE) case CODE: return #NAME;
4132       DWARF_ALL_KNOWN_DW_LNCT
4133 #undef DWARF_ONE_KNOWN_DW_LNCT
4134     default:
4135       return NULL;
4136     }
4137 }
4138
4139
4140 /* Used by all dwarf_foo_name functions.  */
4141 static const char *
4142 string_or_unknown (const char *known, unsigned int code,
4143                    unsigned int lo_user, unsigned int hi_user,
4144                    bool print_unknown_num)
4145 {
4146   static char unknown_buf[20];
4147
4148   if (likely (known != NULL))
4149     return known;
4150
4151   if (lo_user != 0 && code >= lo_user && code <= hi_user)
4152     {
4153       snprintf (unknown_buf, sizeof unknown_buf, "lo_user+%#x",
4154                 code - lo_user);
4155       return unknown_buf;
4156     }
4157
4158   if (print_unknown_num)
4159     {
4160       snprintf (unknown_buf, sizeof unknown_buf, "??? (%#x)", code);
4161       return unknown_buf;
4162     }
4163
4164   return "???";
4165 }
4166
4167
4168 static const char *
4169 dwarf_tag_name (unsigned int tag)
4170 {
4171   const char *ret = dwarf_tag_string (tag);
4172   return string_or_unknown (ret, tag, DW_TAG_lo_user, DW_TAG_hi_user, true);
4173 }
4174
4175 static const char *
4176 dwarf_attr_name (unsigned int attr)
4177 {
4178   const char *ret = dwarf_attr_string (attr);
4179   return string_or_unknown (ret, attr, DW_AT_lo_user, DW_AT_hi_user, true);
4180 }
4181
4182
4183 static const char *
4184 dwarf_form_name (unsigned int form)
4185 {
4186   const char *ret = dwarf_form_string (form);
4187   return string_or_unknown (ret, form, 0, 0, true);
4188 }
4189
4190
4191 static const char *
4192 dwarf_lang_name (unsigned int lang)
4193 {
4194   const char *ret = dwarf_lang_string (lang);
4195   return string_or_unknown (ret, lang, DW_LANG_lo_user, DW_LANG_hi_user, false);
4196 }
4197
4198
4199 static const char *
4200 dwarf_inline_name (unsigned int code)
4201 {
4202   const char *ret = dwarf_inline_string (code);
4203   return string_or_unknown (ret, code, 0, 0, false);
4204 }
4205
4206
4207 static const char *
4208 dwarf_encoding_name (unsigned int code)
4209 {
4210   const char *ret = dwarf_encoding_string (code);
4211   return string_or_unknown (ret, code, DW_ATE_lo_user, DW_ATE_hi_user, false);
4212 }
4213
4214
4215 static const char *
4216 dwarf_access_name (unsigned int code)
4217 {
4218   const char *ret = dwarf_access_string (code);
4219   return string_or_unknown (ret, code, 0, 0, false);
4220 }
4221
4222
4223 static const char *
4224 dwarf_defaulted_name (unsigned int code)
4225 {
4226   const char *ret = dwarf_defaulted_string (code);
4227   return string_or_unknown (ret, code, 0, 0, false);
4228 }
4229
4230
4231 static const char *
4232 dwarf_visibility_name (unsigned int code)
4233 {
4234   const char *ret = dwarf_visibility_string (code);
4235   return string_or_unknown (ret, code, 0, 0, false);
4236 }
4237
4238
4239 static const char *
4240 dwarf_virtuality_name (unsigned int code)
4241 {
4242   const char *ret = dwarf_virtuality_string (code);
4243   return string_or_unknown (ret, code, 0, 0, false);
4244 }
4245
4246
4247 static const char *
4248 dwarf_identifier_case_name (unsigned int code)
4249 {
4250   const char *ret = dwarf_identifier_case_string (code);
4251   return string_or_unknown (ret, code, 0, 0, false);
4252 }
4253
4254
4255 static const char *
4256 dwarf_calling_convention_name (unsigned int code)
4257 {
4258   const char *ret = dwarf_calling_convention_string (code);
4259   return string_or_unknown (ret, code, DW_CC_lo_user, DW_CC_hi_user, false);
4260 }
4261
4262
4263 static const char *
4264 dwarf_ordering_name (unsigned int code)
4265 {
4266   const char *ret = dwarf_ordering_string (code);
4267   return string_or_unknown (ret, code, 0, 0, false);
4268 }
4269
4270
4271 static const char *
4272 dwarf_discr_list_name (unsigned int code)
4273 {
4274   const char *ret = dwarf_discr_list_string (code);
4275   return string_or_unknown (ret, code, 0, 0, false);
4276 }
4277
4278
4279 static const char *
4280 dwarf_unit_name (unsigned int type)
4281 {
4282   const char *ret = dwarf_unit_string (type);
4283   return string_or_unknown (ret, type, DW_UT_lo_user, DW_UT_hi_user, true);
4284 }
4285
4286
4287 static const char *
4288 dwarf_range_list_encoding_name (unsigned int kind)
4289 {
4290   const char *ret = dwarf_range_list_encoding_string (kind);
4291   return string_or_unknown (ret, kind, 0, 0, false);
4292 }
4293
4294
4295 static const char *
4296 dwarf_loc_list_encoding_name (unsigned int kind)
4297 {
4298   const char *ret = dwarf_loc_list_encoding_string (kind);
4299   return string_or_unknown (ret, kind, 0, 0, false);
4300 }
4301
4302
4303 static const char *
4304 dwarf_line_content_description_name (unsigned int kind)
4305 {
4306   const char *ret = dwarf_line_content_description_string (kind);
4307   return string_or_unknown (ret, kind, DW_LNCT_lo_user, DW_LNCT_hi_user,
4308                             false);
4309 }
4310
4311
4312 static void
4313 print_block (size_t n, const void *block)
4314 {
4315   if (n == 0)
4316     puts (_("empty block"));
4317   else
4318     {
4319       printf (_("%zu byte block:"), n);
4320       const unsigned char *data = block;
4321       do
4322         printf (" %02x", *data++);
4323       while (--n > 0);
4324       putchar ('\n');
4325     }
4326 }
4327
4328 static void
4329 print_bytes (size_t n, const unsigned char *bytes)
4330 {
4331   while (n-- > 0)
4332     {
4333       printf ("%02x", *bytes++);
4334       if (n > 0)
4335         printf (" ");
4336     }
4337 }
4338
4339 static int
4340 get_indexed_addr (Dwarf_CU *cu, Dwarf_Word idx, Dwarf_Addr *addr)
4341 {
4342   if (cu == NULL)
4343     return -1;
4344
4345   Elf_Data *debug_addr = cu->dbg->sectiondata[IDX_debug_addr];
4346   if (debug_addr == NULL)
4347     return -1;
4348
4349   Dwarf_Off base = __libdw_cu_addr_base (cu);
4350   Dwarf_Word off = idx * cu->address_size;
4351   if (base > debug_addr->d_size
4352       || off > debug_addr->d_size - base
4353       || cu->address_size > debug_addr->d_size - base - off)
4354     return -1;
4355
4356   const unsigned char *addrp = debug_addr->d_buf + base + off;
4357   if (cu->address_size == 4)
4358     *addr = read_4ubyte_unaligned (cu->dbg, addrp);
4359   else
4360     *addr = read_8ubyte_unaligned (cu->dbg, addrp);
4361
4362   return 0;
4363 }
4364
4365 static void
4366 print_ops (Dwfl_Module *dwflmod, Dwarf *dbg, int indent, int indentrest,
4367            unsigned int vers, unsigned int addrsize, unsigned int offset_size,
4368            struct Dwarf_CU *cu, Dwarf_Word len, const unsigned char *data)
4369 {
4370   const unsigned int ref_size = vers < 3 ? addrsize : offset_size;
4371
4372   if (len == 0)
4373     {
4374       printf ("%*s(empty)\n", indent, "");
4375       return;
4376     }
4377
4378 #define NEED(n)         if (len < (Dwarf_Word) (n)) goto invalid
4379 #define CONSUME(n)      NEED (n); else len -= (n)
4380
4381   Dwarf_Word offset = 0;
4382   while (len-- > 0)
4383     {
4384       uint_fast8_t op = *data++;
4385
4386       const char *op_name = dwarf_locexpr_opcode_string (op);
4387       if (unlikely (op_name == NULL))
4388         {
4389           static char buf[20];
4390           if (op >= DW_OP_lo_user)
4391             snprintf (buf, sizeof buf, "lo_user+%#x", op - DW_OP_lo_user);
4392           else
4393             snprintf (buf, sizeof buf, "??? (%#x)", op);
4394           op_name = buf;
4395         }
4396
4397       switch (op)
4398         {
4399         case DW_OP_addr:;
4400           /* Address operand.  */
4401           Dwarf_Word addr;
4402           NEED (addrsize);
4403           if (addrsize == 4)
4404             addr = read_4ubyte_unaligned (dbg, data);
4405           else if (addrsize == 8)
4406             addr = read_8ubyte_unaligned (dbg, data);
4407           else
4408             goto invalid;
4409           data += addrsize;
4410           CONSUME (addrsize);
4411
4412           printf ("%*s[%2" PRIuMAX "] %s ",
4413                   indent, "", (uintmax_t) offset, op_name);
4414           print_dwarf_addr (dwflmod, 0, addr, addr);
4415           printf ("\n");
4416
4417           offset += 1 + addrsize;
4418           break;
4419
4420         case DW_OP_call_ref:
4421         case DW_OP_GNU_variable_value:
4422           /* Offset operand.  */
4423           if (ref_size != 4 && ref_size != 8)
4424             goto invalid; /* Cannot be used in CFA.  */
4425           NEED (ref_size);
4426           if (ref_size == 4)
4427             addr = read_4ubyte_unaligned (dbg, data);
4428           else
4429             addr = read_8ubyte_unaligned (dbg, data);
4430           data += ref_size;
4431           CONSUME (ref_size);
4432           /* addr is a DIE offset, so format it as one.  */
4433           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIxMAX "]\n",
4434                   indent, "", (uintmax_t) offset,
4435                   op_name, (uintmax_t) addr);
4436           offset += 1 + ref_size;
4437           break;
4438
4439         case DW_OP_deref_size:
4440         case DW_OP_xderef_size:
4441         case DW_OP_pick:
4442         case DW_OP_const1u:
4443           // XXX value might be modified by relocation
4444           NEED (1);
4445           printf ("%*s[%2" PRIuMAX "] %s %" PRIu8 "\n",
4446                   indent, "", (uintmax_t) offset,
4447                   op_name, *((uint8_t *) data));
4448           ++data;
4449           --len;
4450           offset += 2;
4451           break;
4452
4453         case DW_OP_const2u:
4454           NEED (2);
4455           // XXX value might be modified by relocation
4456           printf ("%*s[%2" PRIuMAX "] %s %" PRIu16 "\n",
4457                   indent, "", (uintmax_t) offset,
4458                   op_name, read_2ubyte_unaligned (dbg, data));
4459           CONSUME (2);
4460           data += 2;
4461           offset += 3;
4462           break;
4463
4464         case DW_OP_const4u:
4465           NEED (4);
4466           // XXX value might be modified by relocation
4467           printf ("%*s[%2" PRIuMAX "] %s %" PRIu32 "\n",
4468                   indent, "", (uintmax_t) offset,
4469                   op_name, read_4ubyte_unaligned (dbg, data));
4470           CONSUME (4);
4471           data += 4;
4472           offset += 5;
4473           break;
4474
4475         case DW_OP_const8u:
4476           NEED (8);
4477           // XXX value might be modified by relocation
4478           printf ("%*s[%2" PRIuMAX "] %s %" PRIu64 "\n",
4479                   indent, "", (uintmax_t) offset,
4480                   op_name, (uint64_t) read_8ubyte_unaligned (dbg, data));
4481           CONSUME (8);
4482           data += 8;
4483           offset += 9;
4484           break;
4485
4486         case DW_OP_const1s:
4487           NEED (1);
4488           // XXX value might be modified by relocation
4489           printf ("%*s[%2" PRIuMAX "] %s %" PRId8 "\n",
4490                   indent, "", (uintmax_t) offset,
4491                   op_name, *((int8_t *) data));
4492           ++data;
4493           --len;
4494           offset += 2;
4495           break;
4496
4497         case DW_OP_const2s:
4498           NEED (2);
4499           // XXX value might be modified by relocation
4500           printf ("%*s[%2" PRIuMAX "] %s %" PRId16 "\n",
4501                   indent, "", (uintmax_t) offset,
4502                   op_name, read_2sbyte_unaligned (dbg, data));
4503           CONSUME (2);
4504           data += 2;
4505           offset += 3;
4506           break;
4507
4508         case DW_OP_const4s:
4509           NEED (4);
4510           // XXX value might be modified by relocation
4511           printf ("%*s[%2" PRIuMAX "] %s %" PRId32 "\n",
4512                   indent, "", (uintmax_t) offset,
4513                   op_name, read_4sbyte_unaligned (dbg, data));
4514           CONSUME (4);
4515           data += 4;
4516           offset += 5;
4517           break;
4518
4519         case DW_OP_const8s:
4520           NEED (8);
4521           // XXX value might be modified by relocation
4522           printf ("%*s[%2" PRIuMAX "] %s %" PRId64 "\n",
4523                   indent, "", (uintmax_t) offset,
4524                   op_name, read_8sbyte_unaligned (dbg, data));
4525           CONSUME (8);
4526           data += 8;
4527           offset += 9;
4528           break;
4529
4530         case DW_OP_piece:
4531         case DW_OP_regx:
4532         case DW_OP_plus_uconst:
4533         case DW_OP_constu:;
4534           const unsigned char *start = data;
4535           uint64_t uleb;
4536           NEED (1);
4537           get_uleb128 (uleb, data, data + len);
4538           printf ("%*s[%2" PRIuMAX "] %s %" PRIu64 "\n",
4539                   indent, "", (uintmax_t) offset, op_name, uleb);
4540           CONSUME (data - start);
4541           offset += 1 + (data - start);
4542           break;
4543
4544         case DW_OP_addrx:
4545         case DW_OP_GNU_addr_index:
4546         case DW_OP_constx:
4547         case DW_OP_GNU_const_index:;
4548           start = data;
4549           NEED (1);
4550           get_uleb128 (uleb, data, data + len);
4551           printf ("%*s[%2" PRIuMAX "] %s [%" PRIu64 "] ",
4552                   indent, "", (uintmax_t) offset, op_name, uleb);
4553           CONSUME (data - start);
4554           offset += 1 + (data - start);
4555           if (get_indexed_addr (cu, uleb, &addr) != 0)
4556             printf ("???\n");
4557           else
4558             {
4559               print_dwarf_addr (dwflmod, 0, addr, addr);
4560               printf ("\n");
4561             }
4562           break;
4563
4564         case DW_OP_bit_piece:
4565           start = data;
4566           uint64_t uleb2;
4567           NEED (1);
4568           get_uleb128 (uleb, data, data + len);
4569           NEED (1);
4570           get_uleb128 (uleb2, data, data + len);
4571           printf ("%*s[%2" PRIuMAX "] %s %" PRIu64 ", %" PRIu64 "\n",
4572                   indent, "", (uintmax_t) offset, op_name, uleb, uleb2);
4573           CONSUME (data - start);
4574           offset += 1 + (data - start);
4575           break;
4576
4577         case DW_OP_fbreg:
4578         case DW_OP_breg0 ... DW_OP_breg31:
4579         case DW_OP_consts:
4580           start = data;
4581           int64_t sleb;
4582           NEED (1);
4583           get_sleb128 (sleb, data, data + len);
4584           printf ("%*s[%2" PRIuMAX "] %s %" PRId64 "\n",
4585                   indent, "", (uintmax_t) offset, op_name, sleb);
4586           CONSUME (data - start);
4587           offset += 1 + (data - start);
4588           break;
4589
4590         case DW_OP_bregx:
4591           start = data;
4592           NEED (1);
4593           get_uleb128 (uleb, data, data + len);
4594           NEED (1);
4595           get_sleb128 (sleb, data, data + len);
4596           printf ("%*s[%2" PRIuMAX "] %s %" PRIu64 " %" PRId64 "\n",
4597                   indent, "", (uintmax_t) offset, op_name, uleb, sleb);
4598           CONSUME (data - start);
4599           offset += 1 + (data - start);
4600           break;
4601
4602         case DW_OP_call2:
4603           NEED (2);
4604           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIx16 "]\n",
4605                   indent, "", (uintmax_t) offset, op_name,
4606                   read_2ubyte_unaligned (dbg, data));
4607           CONSUME (2);
4608           data += 2;
4609           offset += 3;
4610           break;
4611
4612         case DW_OP_call4:
4613           NEED (4);
4614           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIx32 "]\n",
4615                   indent, "", (uintmax_t) offset, op_name,
4616                   read_4ubyte_unaligned (dbg, data));
4617           CONSUME (4);
4618           data += 4;
4619           offset += 5;
4620           break;
4621
4622         case DW_OP_skip:
4623         case DW_OP_bra:
4624           NEED (2);
4625           printf ("%*s[%2" PRIuMAX "] %s %" PRIuMAX "\n",
4626                   indent, "", (uintmax_t) offset, op_name,
4627                   (uintmax_t) (offset + read_2sbyte_unaligned (dbg, data) + 3));
4628           CONSUME (2);
4629           data += 2;
4630           offset += 3;
4631           break;
4632
4633         case DW_OP_implicit_value:
4634           start = data;
4635           NEED (1);
4636           get_uleb128 (uleb, data, data + len);
4637           printf ("%*s[%2" PRIuMAX "] %s: ",
4638                   indent, "", (uintmax_t) offset, op_name);
4639           NEED (uleb);
4640           print_block (uleb, data);
4641           data += uleb;
4642           CONSUME (data - start);
4643           offset += 1 + (data - start);
4644           break;
4645
4646         case DW_OP_implicit_pointer:
4647         case DW_OP_GNU_implicit_pointer:
4648           /* DIE offset operand.  */
4649           start = data;
4650           NEED (ref_size);
4651           if (ref_size != 4 && ref_size != 8)
4652             goto invalid; /* Cannot be used in CFA.  */
4653           if (ref_size == 4)
4654             addr = read_4ubyte_unaligned (dbg, data);
4655           else
4656             addr = read_8ubyte_unaligned (dbg, data);
4657           data += ref_size;
4658           /* Byte offset operand.  */
4659           NEED (1);
4660           get_sleb128 (sleb, data, data + len);
4661
4662           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIxMAX "] %+" PRId64 "\n",
4663                   indent, "", (intmax_t) offset,
4664                   op_name, (uintmax_t) addr, sleb);
4665           CONSUME (data - start);
4666           offset += 1 + (data - start);
4667           break;
4668
4669         case DW_OP_entry_value:
4670         case DW_OP_GNU_entry_value:
4671           /* Size plus expression block.  */
4672           start = data;
4673           NEED (1);
4674           get_uleb128 (uleb, data, data + len);
4675           printf ("%*s[%2" PRIuMAX "] %s:\n",
4676                   indent, "", (uintmax_t) offset, op_name);
4677           NEED (uleb);
4678           print_ops (dwflmod, dbg, indent + 5, indent + 5, vers,
4679                      addrsize, offset_size, cu, uleb, data);
4680           data += uleb;
4681           CONSUME (data - start);
4682           offset += 1 + (data - start);
4683           break;
4684
4685         case DW_OP_const_type:
4686         case DW_OP_GNU_const_type:
4687           /* uleb128 CU relative DW_TAG_base_type DIE offset, 1-byte
4688              unsigned size plus block.  */
4689           start = data;
4690           NEED (1);
4691           get_uleb128 (uleb, data, data + len);
4692           if (! print_unresolved_addresses && cu != NULL)
4693             uleb += cu->start;
4694           NEED (1);
4695           uint8_t usize = *(uint8_t *) data++;
4696           NEED (usize);
4697           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIxMAX "] ",
4698                   indent, "", (uintmax_t) offset, op_name, uleb);
4699           print_block (usize, data);
4700           data += usize;
4701           CONSUME (data - start);
4702           offset += 1 + (data - start);
4703           break;
4704
4705         case DW_OP_regval_type:
4706         case DW_OP_GNU_regval_type:
4707           /* uleb128 register number, uleb128 CU relative
4708              DW_TAG_base_type DIE offset.  */
4709           start = data;
4710           NEED (1);
4711           get_uleb128 (uleb, data, data + len);
4712           NEED (1);
4713           get_uleb128 (uleb2, data, data + len);
4714           if (! print_unresolved_addresses && cu != NULL)
4715             uleb2 += cu->start;
4716           printf ("%*s[%2" PRIuMAX "] %s %" PRIu64 " [%6" PRIx64 "]\n",
4717                   indent, "", (uintmax_t) offset, op_name, uleb, uleb2);
4718           CONSUME (data - start);
4719           offset += 1 + (data - start);
4720           break;
4721
4722         case DW_OP_deref_type:
4723         case DW_OP_GNU_deref_type:
4724           /* 1-byte unsigned size of value, uleb128 CU relative
4725              DW_TAG_base_type DIE offset.  */
4726           start = data;
4727           NEED (1);
4728           usize = *(uint8_t *) data++;
4729           NEED (1);
4730           get_uleb128 (uleb, data, data + len);
4731           if (! print_unresolved_addresses && cu != NULL)
4732             uleb += cu->start;
4733           printf ("%*s[%2" PRIuMAX "] %s %" PRIu8 " [%6" PRIxMAX "]\n",
4734                   indent, "", (uintmax_t) offset,
4735                   op_name, usize, uleb);
4736           CONSUME (data - start);
4737           offset += 1 + (data - start);
4738           break;
4739
4740         case DW_OP_xderef_type:
4741           /* 1-byte unsigned size of value, uleb128 base_type DIE offset.  */
4742           start = data;
4743           NEED (1);
4744           usize = *(uint8_t *) data++;
4745           NEED (1);
4746           get_uleb128 (uleb, data, data + len);
4747           printf ("%*s[%4" PRIuMAX "] %s %" PRIu8 " [%6" PRIxMAX "]\n",
4748                   indent, "", (uintmax_t) offset,
4749                   op_name, usize, uleb);
4750           CONSUME (data - start);
4751           offset += 1 + (data - start);
4752           break;
4753
4754         case DW_OP_convert:
4755         case DW_OP_GNU_convert:
4756         case DW_OP_reinterpret:
4757         case DW_OP_GNU_reinterpret:
4758           /* uleb128 CU relative offset to DW_TAG_base_type, or zero
4759              for conversion to untyped.  */
4760           start = data;
4761           NEED (1);
4762           get_uleb128 (uleb, data, data + len);
4763           if (uleb != 0 && ! print_unresolved_addresses && cu != NULL)
4764             uleb += cu->start;
4765           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIxMAX "]\n",
4766                   indent, "", (uintmax_t) offset, op_name, uleb);
4767           CONSUME (data - start);
4768           offset += 1 + (data - start);
4769           break;
4770
4771         case DW_OP_GNU_parameter_ref:
4772           /* 4 byte CU relative reference to the abstract optimized away
4773              DW_TAG_formal_parameter.  */
4774           NEED (4);
4775           uintmax_t param_off = (uintmax_t) read_4ubyte_unaligned (dbg, data);
4776           if (! print_unresolved_addresses && cu != NULL)
4777             param_off += cu->start;
4778           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIxMAX "]\n",
4779                   indent, "", (uintmax_t) offset, op_name, param_off);
4780           CONSUME (4);
4781           data += 4;
4782           offset += 5;
4783           break;
4784
4785         default:
4786           /* No Operand.  */
4787           printf ("%*s[%2" PRIuMAX "] %s\n",
4788                   indent, "", (uintmax_t) offset, op_name);
4789           ++offset;
4790           break;
4791         }
4792
4793       indent = indentrest;
4794       continue;
4795
4796     invalid:
4797       printf (_("%*s[%2" PRIuMAX "] %s  <TRUNCATED>\n"),
4798               indent, "", (uintmax_t) offset, op_name);
4799       break;
4800     }
4801 }
4802
4803
4804 struct listptr
4805 {
4806   Dwarf_Off offset:(64 - 3);
4807   bool addr64:1;
4808   bool dwarf64:1;
4809   bool warned:1;
4810   struct Dwarf_CU *cu;
4811   unsigned int attr;
4812 };
4813
4814 #define listptr_offset_size(p)  ((p)->dwarf64 ? 8 : 4)
4815 #define listptr_address_size(p) ((p)->addr64 ? 8 : 4)
4816
4817 static Dwarf_Addr
4818 cudie_base (Dwarf_Die *cudie)
4819 {
4820   Dwarf_Addr base;
4821   /* Find the base address of the compilation unit.  It will normally
4822      be specified by DW_AT_low_pc.  In DWARF-3 draft 4, the base
4823      address could be overridden by DW_AT_entry_pc.  It's been
4824      removed, but GCC emits DW_AT_entry_pc and not DW_AT_lowpc for
4825      compilation units with discontinuous ranges.  */
4826   if (unlikely (dwarf_lowpc (cudie, &base) != 0))
4827     {
4828       Dwarf_Attribute attr_mem;
4829       if (dwarf_formaddr (dwarf_attr (cudie, DW_AT_entry_pc, &attr_mem),
4830                           &base) != 0)
4831         base = 0;
4832     }
4833   return base;
4834 }
4835
4836 static Dwarf_Addr
4837 listptr_base (struct listptr *p)
4838 {
4839   Dwarf_Die cu = CUDIE (p->cu);
4840   return cudie_base (&cu);
4841 }
4842
4843 /* To store the name used in compare_listptr */
4844 static const char *sort_listptr_name;
4845
4846 static int
4847 compare_listptr (const void *a, const void *b)
4848 {
4849   const char *name = sort_listptr_name;
4850   struct listptr *p1 = (void *) a;
4851   struct listptr *p2 = (void *) b;
4852
4853   if (p1->offset < p2->offset)
4854     return -1;
4855   if (p1->offset > p2->offset)
4856     return 1;
4857
4858   if (!p1->warned && !p2->warned)
4859     {
4860       if (p1->addr64 != p2->addr64)
4861         {
4862           p1->warned = p2->warned = true;
4863           error (0, 0,
4864                  _("%s %#" PRIx64 " used with different address sizes"),
4865                  name, (uint64_t) p1->offset);
4866         }
4867       if (p1->dwarf64 != p2->dwarf64)
4868         {
4869           p1->warned = p2->warned = true;
4870           error (0, 0,
4871                  _("%s %#" PRIx64 " used with different offset sizes"),
4872                  name, (uint64_t) p1->offset);
4873         }
4874       if (listptr_base (p1) != listptr_base (p2))
4875         {
4876           p1->warned = p2->warned = true;
4877           error (0, 0,
4878                  _("%s %#" PRIx64 " used with different base addresses"),
4879                  name, (uint64_t) p1->offset);
4880         }
4881       if (p1->attr != p2 ->attr)
4882         {
4883           p1->warned = p2->warned = true;
4884           error (0, 0,
4885                  _("%s %#" PRIx64
4886                           " used with different attribute %s and %s"),
4887                  name, (uint64_t) p1->offset, dwarf_attr_name (p1->attr),
4888                  dwarf_attr_name (p2->attr));
4889         }
4890     }
4891
4892   return 0;
4893 }
4894
4895 struct listptr_table
4896 {
4897   size_t n;
4898   size_t alloc;
4899   struct listptr *table;
4900 };
4901
4902 static struct listptr_table known_locsptr;
4903 static struct listptr_table known_loclistsptr;
4904 static struct listptr_table known_rangelistptr;
4905 static struct listptr_table known_rnglistptr;
4906 static struct listptr_table known_addrbases;
4907 static struct listptr_table known_stroffbases;
4908
4909 static void
4910 reset_listptr (struct listptr_table *table)
4911 {
4912   free (table->table);
4913   table->table = NULL;
4914   table->n = table->alloc = 0;
4915 }
4916
4917 /* Returns false if offset doesn't fit.  See struct listptr.  */
4918 static bool
4919 notice_listptr (enum section_e section, struct listptr_table *table,
4920                 uint_fast8_t address_size, uint_fast8_t offset_size,
4921                 struct Dwarf_CU *cu, Dwarf_Off offset, unsigned int attr)
4922 {
4923   if (print_debug_sections & section)
4924     {
4925       if (table->n == table->alloc)
4926         {
4927           if (table->alloc == 0)
4928             table->alloc = 128;
4929           else
4930             table->alloc *= 2;
4931           table->table = xrealloc (table->table,
4932                                    table->alloc * sizeof table->table[0]);
4933         }
4934
4935       struct listptr *p = &table->table[table->n++];
4936
4937       *p = (struct listptr)
4938         {
4939           .addr64 = address_size == 8,
4940           .dwarf64 = offset_size == 8,
4941           .offset = offset,
4942           .cu = cu,
4943           .attr = attr
4944         };
4945
4946       if (p->offset != offset)
4947         {
4948           table->n--;
4949           return false;
4950         }
4951     }
4952   return true;
4953 }
4954
4955 static void
4956 sort_listptr (struct listptr_table *table, const char *name)
4957 {
4958   if (table->n > 0)
4959     {
4960       sort_listptr_name = name;
4961       qsort (table->table, table->n, sizeof table->table[0],
4962              &compare_listptr);
4963     }
4964 }
4965
4966 static bool
4967 skip_listptr_hole (struct listptr_table *table, size_t *idxp,
4968                    uint_fast8_t *address_sizep, uint_fast8_t *offset_sizep,
4969                    Dwarf_Addr *base, struct Dwarf_CU **cu, ptrdiff_t offset,
4970                    unsigned char **readp, unsigned char *endp,
4971                    unsigned int *attr)
4972 {
4973   if (table->n == 0)
4974     return false;
4975
4976   while (*idxp < table->n && table->table[*idxp].offset < (Dwarf_Off) offset)
4977     ++*idxp;
4978
4979   struct listptr *p = &table->table[*idxp];
4980
4981   if (*idxp == table->n
4982       || p->offset >= (Dwarf_Off) (endp - *readp + offset))
4983     {
4984       *readp = endp;
4985       printf (_(" [%6tx]  <UNUSED GARBAGE IN REST OF SECTION>\n"),
4986               offset);
4987       return true;
4988     }
4989
4990   if (p->offset != (Dwarf_Off) offset)
4991     {
4992       *readp += p->offset - offset;
4993       printf (_(" [%6tx]  <UNUSED GARBAGE> ... %" PRIu64 " bytes ...\n"),
4994               offset, (Dwarf_Off) p->offset - offset);
4995       return true;
4996     }
4997
4998   if (address_sizep != NULL)
4999     *address_sizep = listptr_address_size (p);
5000   if (offset_sizep != NULL)
5001     *offset_sizep = listptr_offset_size (p);
5002   if (base != NULL)
5003     *base = listptr_base (p);
5004   if (cu != NULL)
5005     *cu = p->cu;
5006   if (attr != NULL)
5007     *attr = p->attr;
5008
5009   return false;
5010 }
5011
5012 static Dwarf_Off
5013 next_listptr_offset (struct listptr_table *table, size_t *idxp, Dwarf_Off off)
5014 {
5015   /* Note that multiple attributes could in theory point to the same loclist
5016      offset, so make sure we pick one that is bigger than the current one.
5017      The table is sorted on offset.  */
5018   if (*idxp < table->n)
5019     {
5020       while (++*idxp < table->n)
5021         {
5022           Dwarf_Off next = table->table[*idxp].offset;
5023           if (next > off)
5024             return next;
5025         }
5026     }
5027   return 0;
5028 }
5029
5030 /* Returns the listptr associated with the given index, or NULL.  */
5031 static struct listptr *
5032 get_listptr (struct listptr_table *table, size_t idx)
5033 {
5034   if (idx >= table->n)
5035     return NULL;
5036   return &table->table[idx];
5037 }
5038
5039 /* Returns the next index, base address and CU associated with the
5040    list unit offsets.  If there is none false is returned, otherwise
5041    true.  Assumes the table has been sorted.  */
5042 static bool
5043 listptr_cu (struct listptr_table *table, size_t *idxp,
5044             Dwarf_Off start, Dwarf_Off end,
5045             Dwarf_Addr *base, struct Dwarf_CU **cu)
5046 {
5047   while (*idxp < table->n
5048          && table->table[*idxp].offset < start)
5049     ++*idxp;
5050
5051   if (*idxp < table->n
5052       && table->table[*idxp].offset >= start
5053       && table->table[*idxp].offset < end)
5054     {
5055       struct listptr *p = &table->table[*idxp];
5056       *base = listptr_base (p);
5057       *cu = p->cu;
5058       return true;
5059     }
5060
5061   return false;
5062 }
5063
5064 /* Returns the next index with the current CU for the given attribute.
5065    If there is none false is returned, otherwise true.  Assumes the
5066    table has been sorted.  */
5067 static bool
5068 listptr_attr (struct listptr_table *table, size_t idxp,
5069               Dwarf_Off offset, unsigned int attr)
5070 {
5071   struct listptr *listptr;
5072   do
5073     {
5074       listptr = get_listptr (table, idxp);
5075       if (listptr == NULL)
5076         return false;
5077
5078       if (listptr->offset == offset && listptr->attr == attr)
5079         return true;
5080
5081       idxp++;
5082     }
5083   while (listptr->offset <= offset);
5084
5085   return false;
5086 }
5087
5088 static void
5089 print_debug_abbrev_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
5090                             Ebl *ebl, GElf_Ehdr *ehdr __attribute__ ((unused)),
5091                             Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
5092 {
5093   const size_t sh_size = (dbg->sectiondata[IDX_debug_abbrev] ?
5094                           dbg->sectiondata[IDX_debug_abbrev]->d_size : 0);
5095
5096   printf (_("\nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"
5097                    " [ Code]\n"),
5098           elf_ndxscn (scn), section_name (ebl, shdr),
5099           (uint64_t) shdr->sh_offset);
5100
5101   Dwarf_Off offset = 0;
5102   while (offset < sh_size)
5103     {
5104       printf (_("\nAbbreviation section at offset %" PRIu64 ":\n"),
5105               offset);
5106
5107       while (1)
5108         {
5109           size_t length;
5110           Dwarf_Abbrev abbrev;
5111
5112           int res = dwarf_offabbrev (dbg, offset, &length, &abbrev);
5113           if (res != 0)
5114             {
5115               if (unlikely (res < 0))
5116                 {
5117                   printf (_("\
5118  *** error while reading abbreviation: %s\n"),
5119                           dwarf_errmsg (-1));
5120                   return;
5121                 }
5122
5123               /* This is the NUL byte at the end of the section.  */
5124               ++offset;
5125               break;
5126             }
5127
5128           /* We know these calls can never fail.  */
5129           unsigned int code = dwarf_getabbrevcode (&abbrev);
5130           unsigned int tag = dwarf_getabbrevtag (&abbrev);
5131           int has_children = dwarf_abbrevhaschildren (&abbrev);
5132
5133           printf (_(" [%5u] offset: %" PRId64
5134                            ", children: %s, tag: %s\n"),
5135                   code, (int64_t) offset,
5136                   has_children ? yes_str : no_str,
5137                   dwarf_tag_name (tag));
5138
5139           size_t cnt = 0;
5140           unsigned int name;
5141           unsigned int form;
5142           Dwarf_Sword data;
5143           Dwarf_Off enoffset;
5144           while (dwarf_getabbrevattr_data (&abbrev, cnt, &name, &form,
5145                                            &data, &enoffset) == 0)
5146             {
5147               printf ("          attr: %s, form: %s",
5148                       dwarf_attr_name (name), dwarf_form_name (form));
5149               if (form == DW_FORM_implicit_const)
5150                 printf (" (%" PRId64 ")", data);
5151               printf (", offset: %#" PRIx64 "\n", (uint64_t) enoffset);
5152               ++cnt;
5153             }
5154
5155           offset += length;
5156         }
5157     }
5158 }
5159
5160
5161 static void
5162 print_debug_addr_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
5163                           Ebl *ebl, GElf_Ehdr *ehdr,
5164                           Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
5165 {
5166   printf (_("\
5167 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
5168           elf_ndxscn (scn), section_name (ebl, shdr),
5169           (uint64_t) shdr->sh_offset);
5170
5171   if (shdr->sh_size == 0)
5172     return;
5173
5174   /* We like to get the section from libdw to make sure they are relocated.  */
5175   Elf_Data *data = (dbg->sectiondata[IDX_debug_addr]
5176                     ?: elf_rawdata (scn, NULL));
5177   if (unlikely (data == NULL))
5178     {
5179       error (0, 0, _("cannot get .debug_addr section data: %s"),
5180              elf_errmsg (-1));
5181       return;
5182     }
5183
5184   size_t idx = 0;
5185   sort_listptr (&known_addrbases, "addr_base");
5186
5187   const unsigned char *start = (const unsigned char *) data->d_buf;
5188   const unsigned char *readp = start;
5189   const unsigned char *readendp = ((const unsigned char *) data->d_buf
5190                                    + data->d_size);
5191
5192   while (readp < readendp)
5193     {
5194       /* We cannot really know whether or not there is an header.  The
5195          DebugFission extension to DWARF4 doesn't add one.  The DWARF5
5196          .debug_addr variant does.  Whether or not we have an header,
5197          DW_AT_[GNU_]addr_base points at "index 0".  So if the current
5198          offset equals the CU addr_base then we can just start
5199          printing addresses.  If there is no CU with an exact match
5200          then we'll try to parse the header first.  */
5201       Dwarf_Off off = (Dwarf_Off) (readp
5202                                    - (const unsigned char *) data->d_buf);
5203
5204       printf ("Table at offset %" PRIx64 " ", off);
5205
5206       struct listptr *listptr = get_listptr (&known_addrbases, idx++);
5207       const unsigned char *next_unitp;
5208
5209       uint64_t unit_length;
5210       uint16_t version;
5211       uint8_t address_size;
5212       uint8_t segment_size;
5213       if (listptr == NULL)
5214         {
5215           error (0, 0, "Warning: No CU references .debug_addr after %" PRIx64,
5216                  off);
5217
5218           /* We will have to assume it is just addresses to the end... */
5219           address_size = ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
5220           next_unitp = readendp;
5221           printf ("Unknown CU:\n");
5222         }
5223       else
5224         {
5225           Dwarf_Die cudie;
5226           if (dwarf_cu_die (listptr->cu, &cudie,
5227                             NULL, NULL, NULL, NULL,
5228                             NULL, NULL) == NULL)
5229             printf ("Unknown CU (%s):\n", dwarf_errmsg (-1));
5230           else
5231             printf ("for CU [%6" PRIx64 "]:\n", dwarf_dieoffset (&cudie));
5232
5233           if (listptr->offset == off)
5234             {
5235               address_size = listptr_address_size (listptr);
5236               segment_size = 0;
5237               version = 4;
5238
5239               /* The addresses start here, but where do they end?  */
5240               listptr = get_listptr (&known_addrbases, idx);
5241               if (listptr == NULL)
5242                 next_unitp = readendp;
5243               else if (listptr->cu->version < 5)
5244                 {
5245                   next_unitp = start + listptr->offset;
5246                   if (listptr->offset < off || listptr->offset > data->d_size)
5247                     {
5248                       error (0, 0,
5249                              "Warning: Bad address base for next unit at %"
5250                              PRIx64, off);
5251                       next_unitp = readendp;
5252                     }
5253                 }
5254               else
5255                 {
5256                   /* Tricky, we don't have a header for this unit, but
5257                      there is one for the next.  We will have to
5258                      "guess" how big it is and subtract it from the
5259                      offset (because that points after the header).  */
5260                   unsigned int offset_size = listptr_offset_size (listptr);
5261                   Dwarf_Off next_off = (listptr->offset
5262                                         - (offset_size == 4 ? 4 : 12) /* len */
5263                                         - 2 /* version */
5264                                         - 1 /* address size */
5265                                         - 1); /* segment selector size */
5266                   next_unitp = start + next_off;
5267                   if (next_off < off || next_off > data->d_size)
5268                     {
5269                       error (0, 0,
5270                              "Warning: Couldn't calculate .debug_addr "
5271                              " unit length at %" PRIx64, off);
5272                       next_unitp = readendp;
5273                     }
5274                 }
5275               unit_length = (uint64_t) (next_unitp - readp);
5276
5277               /* Pretend we have a header.  */
5278               printf ("\n");
5279               printf (_(" Length:         %8" PRIu64 "\n"),
5280                       unit_length);
5281               printf (_(" DWARF version:  %8" PRIu16 "\n"), version);
5282               printf (_(" Address size:   %8" PRIu64 "\n"),
5283                       (uint64_t) address_size);
5284               printf (_(" Segment size:   %8" PRIu64 "\n"),
5285                       (uint64_t) segment_size);
5286               printf ("\n");
5287             }
5288           else
5289             {
5290               /* OK, we have to parse an header first.  */
5291               unit_length = read_4ubyte_unaligned_inc (dbg, readp);
5292               if (unlikely (unit_length == 0xffffffff))
5293                 {
5294                   if (unlikely (readp > readendp - 8))
5295                     {
5296                     invalid_data:
5297                       error (0, 0, "Invalid data");
5298                       return;
5299                     }
5300                   unit_length = read_8ubyte_unaligned_inc (dbg, readp);
5301                 }
5302               printf ("\n");
5303               printf (_(" Length:         %8" PRIu64 "\n"),
5304                       unit_length);
5305
5306               /* We need at least 2-bytes (version) + 1-byte
5307                  (addr_size) + 1-byte (segment_size) = 4 bytes to
5308                  complete the header.  And this unit cannot go beyond
5309                  the section data.  */
5310               if (readp > readendp - 4
5311                   || unit_length < 4
5312                   || unit_length > (uint64_t) (readendp - readp))
5313                 goto invalid_data;
5314
5315               next_unitp = readp + unit_length;
5316
5317               version = read_2ubyte_unaligned_inc (dbg, readp);
5318               printf (_(" DWARF version:  %8" PRIu16 "\n"), version);
5319
5320               if (version != 5)
5321                 {
5322                   error (0, 0, _("Unknown version"));
5323                   goto next_unit;
5324                 }
5325
5326               address_size = *readp++;
5327               printf (_(" Address size:   %8" PRIu64 "\n"),
5328                       (uint64_t) address_size);
5329
5330               if (address_size != 4 && address_size != 8)
5331                 {
5332                   error (0, 0, _("unsupported address size"));
5333                   goto next_unit;
5334                 }
5335
5336               segment_size = *readp++;
5337               printf (_(" Segment size:   %8" PRIu64 "\n"),
5338                       (uint64_t) segment_size);
5339               printf ("\n");
5340
5341               if (segment_size != 0)
5342                 {
5343                   error (0, 0, _("unsupported segment size"));
5344                   goto next_unit;
5345                 }
5346
5347               if (listptr->offset != (Dwarf_Off) (readp - start))
5348                 {
5349                   error (0, 0, "Address index doesn't start after header");
5350                   goto next_unit;
5351                 }
5352             }
5353         }
5354
5355       int digits = 1;
5356       size_t addresses = (next_unitp - readp) / address_size;
5357       while (addresses >= 10)
5358         {
5359           ++digits;
5360           addresses /= 10;
5361         }
5362
5363       unsigned int uidx = 0;
5364       size_t index_offset =  readp - (const unsigned char *) data->d_buf;
5365       printf (" Addresses start at offset 0x%zx:\n", index_offset);
5366       while (readp <= next_unitp - address_size)
5367         {
5368           Dwarf_Addr addr = read_addr_unaligned_inc (address_size, dbg,
5369                                                      readp);
5370           printf (" [%*u] ", digits, uidx++);
5371           print_dwarf_addr (dwflmod, address_size, addr, addr);
5372           printf ("\n");
5373         }
5374       printf ("\n");
5375
5376       if (readp != next_unitp)
5377         error (0, 0, "extra %zd bytes at end of unit",
5378                (size_t) (next_unitp - readp));
5379
5380     next_unit:
5381       readp = next_unitp;
5382     }
5383 }
5384
5385 /* Print content of DWARF .debug_aranges section.  We fortunately do
5386    not have to know a bit about the structure of the section, libdwarf
5387    takes care of it.  */
5388 static void
5389 print_decoded_aranges_section (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn,
5390                                GElf_Shdr *shdr, Dwarf *dbg)
5391 {
5392   Dwarf_Aranges *aranges;
5393   size_t cnt;
5394   if (unlikely (dwarf_getaranges (dbg, &aranges, &cnt) != 0))
5395     {
5396       error (0, 0, _("cannot get .debug_aranges content: %s"),
5397              dwarf_errmsg (-1));
5398       return;
5399     }
5400
5401   GElf_Shdr glink_mem;
5402   GElf_Shdr *glink;
5403   glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link), &glink_mem);
5404   if (glink == NULL)
5405     {
5406       error (0, 0, _("invalid sh_link value in section %zu"),
5407              elf_ndxscn (scn));
5408       return;
5409     }
5410
5411   printf (ngettext ("\
5412 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 " contains %zu entry:\n",
5413                     "\
5414 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 " contains %zu entries:\n",
5415                     cnt),
5416           elf_ndxscn (scn), section_name (ebl, shdr),
5417           (uint64_t) shdr->sh_offset, cnt);
5418
5419   /* Compute floor(log16(cnt)).  */
5420   size_t tmp = cnt;
5421   int digits = 1;
5422   while (tmp >= 16)
5423     {
5424       ++digits;
5425       tmp >>= 4;
5426     }
5427
5428   for (size_t n = 0; n < cnt; ++n)
5429     {
5430       Dwarf_Arange *runp = dwarf_onearange (aranges, n);
5431       if (unlikely (runp == NULL))
5432         {
5433           printf ("cannot get arange %zu: %s\n", n, dwarf_errmsg (-1));
5434           return;
5435         }
5436
5437       Dwarf_Addr start;
5438       Dwarf_Word length;
5439       Dwarf_Off offset;
5440
5441       if (unlikely (dwarf_getarangeinfo (runp, &start, &length, &offset) != 0))
5442         printf (_(" [%*zu] ???\n"), digits, n);
5443       else
5444         printf (_(" [%*zu] start: %0#*" PRIx64
5445                          ", length: %5" PRIu64 ", CU DIE offset: %6"
5446                          PRId64 "\n"),
5447                 digits, n, ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 10 : 18,
5448                 (uint64_t) start, (uint64_t) length, (int64_t) offset);
5449     }
5450 }
5451
5452
5453 /* Print content of DWARF .debug_aranges section.  */
5454 static void
5455 print_debug_aranges_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
5456                              Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn,
5457                              GElf_Shdr *shdr, Dwarf *dbg)
5458 {
5459   if (decodedaranges)
5460     {
5461       print_decoded_aranges_section (ebl, ehdr, scn, shdr, dbg);
5462       return;
5463     }
5464
5465   Elf_Data *data = (dbg->sectiondata[IDX_debug_aranges]
5466                     ?: elf_rawdata (scn, NULL));
5467
5468   if (unlikely (data == NULL))
5469     {
5470       error (0, 0, _("cannot get .debug_aranges content: %s"),
5471              elf_errmsg (-1));
5472       return;
5473     }
5474
5475   printf (_("\
5476 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
5477           elf_ndxscn (scn), section_name (ebl, shdr),
5478           (uint64_t) shdr->sh_offset);
5479
5480   const unsigned char *readp = data->d_buf;
5481   const unsigned char *readendp = readp + data->d_size;
5482
5483   while (readp < readendp)
5484     {
5485       const unsigned char *hdrstart = readp;
5486       size_t start_offset = hdrstart - (const unsigned char *) data->d_buf;
5487
5488       printf (_("\nTable at offset %zu:\n"), start_offset);
5489       if (readp + 4 > readendp)
5490         {
5491         invalid_data:
5492           error (0, 0, _("invalid data in section [%zu] '%s'"),
5493                  elf_ndxscn (scn), section_name (ebl, shdr));
5494           return;
5495         }
5496
5497       Dwarf_Word length = read_4ubyte_unaligned_inc (dbg, readp);
5498       unsigned int length_bytes = 4;
5499       if (length == DWARF3_LENGTH_64_BIT)
5500         {
5501           if (readp + 8 > readendp)
5502             goto invalid_data;
5503           length = read_8ubyte_unaligned_inc (dbg, readp);
5504           length_bytes = 8;
5505         }
5506
5507       const unsigned char *nexthdr = readp + length;
5508       printf (_("\n Length:        %6" PRIu64 "\n"),
5509               (uint64_t) length);
5510
5511       if (unlikely (length > (size_t) (readendp - readp)))
5512         goto invalid_data;
5513
5514       if (length == 0)
5515         continue;
5516
5517       if (readp + 2 > readendp)
5518         goto invalid_data;
5519       uint_fast16_t version = read_2ubyte_unaligned_inc (dbg, readp);
5520       printf (_(" DWARF version: %6" PRIuFAST16 "\n"),
5521               version);
5522       if (version != 2)
5523         {
5524           error (0, 0, _("unsupported aranges version"));
5525           goto next_table;
5526         }
5527
5528       Dwarf_Word offset;
5529       if (readp + length_bytes > readendp)
5530         goto invalid_data;
5531       if (length_bytes == 8)
5532         offset = read_8ubyte_unaligned_inc (dbg, readp);
5533       else
5534         offset = read_4ubyte_unaligned_inc (dbg, readp);
5535       printf (_(" CU offset:     %6" PRIx64 "\n"),
5536               (uint64_t) offset);
5537
5538       if (readp + 1 > readendp)
5539         goto invalid_data;
5540       unsigned int address_size = *readp++;
5541       printf (_(" Address size:  %6" PRIu64 "\n"),
5542               (uint64_t) address_size);
5543       if (address_size != 4 && address_size != 8)
5544         {
5545           error (0, 0, _("unsupported address size"));
5546           goto next_table;
5547         }
5548
5549       if (readp + 1 > readendp)
5550         goto invalid_data;
5551       unsigned int segment_size = *readp++;
5552       printf (_(" Segment size:  %6" PRIu64 "\n\n"),
5553               (uint64_t) segment_size);
5554       if (segment_size != 0 && segment_size != 4 && segment_size != 8)
5555         {
5556           error (0, 0, _("unsupported segment size"));
5557           goto next_table;
5558         }
5559
5560       /* Round the address to the next multiple of 2*address_size.  */
5561       readp += ((2 * address_size - ((readp - hdrstart) % (2 * address_size)))
5562                 % (2 * address_size));
5563
5564       while (readp < nexthdr)
5565         {
5566           Dwarf_Word range_address;
5567           Dwarf_Word range_length;
5568           Dwarf_Word segment = 0;
5569           if (readp + 2 * address_size + segment_size > readendp)
5570             goto invalid_data;
5571           if (address_size == 4)
5572             {
5573               range_address = read_4ubyte_unaligned_inc (dbg, readp);
5574               range_length = read_4ubyte_unaligned_inc (dbg, readp);
5575             }
5576           else
5577             {
5578               range_address = read_8ubyte_unaligned_inc (dbg, readp);
5579               range_length = read_8ubyte_unaligned_inc (dbg, readp);
5580             }
5581
5582           if (segment_size == 4)
5583             segment = read_4ubyte_unaligned_inc (dbg, readp);
5584           else if (segment_size == 8)
5585             segment = read_8ubyte_unaligned_inc (dbg, readp);
5586
5587           if (range_address == 0 && range_length == 0 && segment == 0)
5588             break;
5589
5590           printf ("   ");
5591           print_dwarf_addr (dwflmod, address_size, range_address,
5592                             range_address);
5593           printf ("..");
5594           print_dwarf_addr (dwflmod, address_size,
5595                             range_address + range_length - 1,
5596                             range_length);
5597           if (segment_size != 0)
5598             printf (" (%" PRIx64 ")\n", (uint64_t) segment);
5599           else
5600             printf ("\n");
5601         }
5602
5603     next_table:
5604       if (readp != nexthdr)
5605         {
5606           size_t padding = nexthdr - readp;
5607           printf (_("   %zu padding bytes\n"), padding);
5608           readp = nexthdr;
5609         }
5610     }
5611 }
5612
5613
5614 static bool is_split_dwarf (Dwarf *dbg, uint64_t *id, Dwarf_CU **split_cu);
5615
5616 /* Returns true and sets cu and cu_base if the given Dwarf is a split
5617    DWARF (.dwo) file.  */
5618 static bool
5619 split_dwarf_cu_base (Dwarf *dbg, Dwarf_CU **cu, Dwarf_Addr *cu_base)
5620 {
5621   uint64_t id;
5622   if (is_split_dwarf (dbg, &id, cu))
5623     {
5624       Dwarf_Die cudie;
5625       if (dwarf_cu_info (*cu, NULL, NULL, &cudie, NULL, NULL, NULL, NULL) == 0)
5626         {
5627           *cu_base = cudie_base (&cudie);
5628           return true;
5629         }
5630     }
5631   return false;
5632 }
5633
5634 /* Print content of DWARF .debug_rnglists section.  */
5635 static void
5636 print_debug_rnglists_section (Dwfl_Module *dwflmod,
5637                               Ebl *ebl,
5638                               GElf_Ehdr *ehdr __attribute__ ((unused)),
5639                               Elf_Scn *scn, GElf_Shdr *shdr,
5640                               Dwarf *dbg __attribute__((unused)))
5641 {
5642   printf (_("\
5643 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
5644           elf_ndxscn (scn), section_name (ebl, shdr),
5645           (uint64_t) shdr->sh_offset);
5646
5647   Elf_Data *data =(dbg->sectiondata[IDX_debug_rnglists]
5648                    ?: elf_rawdata (scn, NULL));
5649   if (unlikely (data == NULL))
5650     {
5651       error (0, 0, _("cannot get .debug_rnglists content: %s"),
5652              elf_errmsg (-1));
5653       return;
5654     }
5655
5656   /* For the listptr to get the base address/CU.  */
5657   sort_listptr (&known_rnglistptr, "rnglistptr");
5658   size_t listptr_idx = 0;
5659
5660   const unsigned char *readp = data->d_buf;
5661   const unsigned char *const dataend = ((unsigned char *) data->d_buf
5662                                         + data->d_size);
5663   while (readp < dataend)
5664     {
5665       if (unlikely (readp > dataend - 4))
5666         {
5667         invalid_data:
5668           error (0, 0, _("invalid data in section [%zu] '%s'"),
5669                  elf_ndxscn (scn), section_name (ebl, shdr));
5670           return;
5671         }
5672
5673       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
5674       printf (_("Table at Offset 0x%" PRIx64 ":\n\n"),
5675               (uint64_t) offset);
5676
5677       uint64_t unit_length = read_4ubyte_unaligned_inc (dbg, readp);
5678       unsigned int offset_size = 4;
5679       if (unlikely (unit_length == 0xffffffff))
5680         {
5681           if (unlikely (readp > dataend - 8))
5682             goto invalid_data;
5683
5684           unit_length = read_8ubyte_unaligned_inc (dbg, readp);
5685           offset_size = 8;
5686         }
5687       printf (_(" Length:         %8" PRIu64 "\n"), unit_length);
5688
5689       /* We need at least 2-bytes + 1-byte + 1-byte + 4-bytes = 8
5690          bytes to complete the header.  And this unit cannot go beyond
5691          the section data.  */
5692       if (readp > dataend - 8
5693           || unit_length < 8
5694           || unit_length > (uint64_t) (dataend - readp))
5695         goto invalid_data;
5696
5697       const unsigned char *nexthdr = readp + unit_length;
5698
5699       uint16_t version = read_2ubyte_unaligned_inc (dbg, readp);
5700       printf (_(" DWARF version:  %8" PRIu16 "\n"), version);
5701
5702       if (version != 5)
5703         {
5704           error (0, 0, _("Unknown version"));
5705           goto next_table;
5706         }
5707
5708       uint8_t address_size = *readp++;
5709       printf (_(" Address size:   %8" PRIu64 "\n"),
5710               (uint64_t) address_size);
5711
5712       if (address_size != 4 && address_size != 8)
5713         {
5714           error (0, 0, _("unsupported address size"));
5715           goto next_table;
5716         }
5717
5718       uint8_t segment_size = *readp++;
5719       printf (_(" Segment size:   %8" PRIu64 "\n"),
5720               (uint64_t) segment_size);
5721
5722       if (segment_size != 0 && segment_size != 4 && segment_size != 8)
5723         {
5724           error (0, 0, _("unsupported segment size"));
5725           goto next_table;
5726         }
5727
5728       uint32_t offset_entry_count = read_4ubyte_unaligned_inc (dbg, readp);
5729       printf (_(" Offset entries: %8" PRIu64 "\n"),
5730               (uint64_t) offset_entry_count);
5731
5732       /* We need the CU that uses this unit to get the initial base address. */
5733       Dwarf_Addr cu_base = 0;
5734       struct Dwarf_CU *cu = NULL;
5735       if (listptr_cu (&known_rnglistptr, &listptr_idx,
5736                       (Dwarf_Off) offset,
5737                       (Dwarf_Off) (nexthdr - (unsigned char *) data->d_buf),
5738                       &cu_base, &cu)
5739           || split_dwarf_cu_base (dbg, &cu, &cu_base))
5740         {
5741           Dwarf_Die cudie;
5742           if (dwarf_cu_die (cu, &cudie,
5743                             NULL, NULL, NULL, NULL,
5744                             NULL, NULL) == NULL)
5745             printf (_(" Unknown CU base: "));
5746           else
5747             printf (_(" CU [%6" PRIx64 "] base: "),
5748                     dwarf_dieoffset (&cudie));
5749           print_dwarf_addr (dwflmod, address_size, cu_base, cu_base);
5750           printf ("\n");
5751         }
5752       else
5753         printf (_(" Not associated with a CU.\n"));
5754
5755       printf ("\n");
5756
5757       const unsigned char *offset_array_start = readp;
5758       if (offset_entry_count > 0)
5759         {
5760           uint64_t max_entries = (unit_length - 8) / offset_size;
5761           if (offset_entry_count > max_entries)
5762             {
5763               error (0, 0,
5764                      _("too many offset entries for unit length"));
5765               offset_entry_count = max_entries;
5766             }
5767
5768           printf (_("  Offsets starting at 0x%" PRIx64 ":\n"),
5769                   (uint64_t) (offset_array_start
5770                               - (unsigned char *) data->d_buf));
5771           for (uint32_t idx = 0; idx < offset_entry_count; idx++)
5772             {
5773               printf ("   [%6" PRIu32 "] ", idx);
5774               if (offset_size == 4)
5775                 {
5776                   uint32_t off = read_4ubyte_unaligned_inc (dbg, readp);
5777                   printf ("0x%" PRIx32 "\n", off);
5778                 }
5779               else
5780                 {
5781                   uint64_t off = read_8ubyte_unaligned_inc (dbg, readp);
5782                   printf ("0x%" PRIx64 "\n", off);
5783                 }
5784             }
5785           printf ("\n");
5786         }
5787
5788       Dwarf_Addr base = cu_base;
5789       bool start_of_list = true;
5790       while (readp < nexthdr)
5791         {
5792           uint8_t kind = *readp++;
5793           uint64_t op1, op2;
5794
5795           /* Skip padding.  */
5796           if (start_of_list && kind == DW_RLE_end_of_list)
5797             continue;
5798
5799           if (start_of_list)
5800             {
5801               base = cu_base;
5802               printf ("  Offset: %" PRIx64 ", Index: %" PRIx64 "\n",
5803                       (uint64_t) (readp - (unsigned char *) data->d_buf - 1),
5804                       (uint64_t) (readp - offset_array_start - 1));
5805               start_of_list = false;
5806             }
5807
5808           printf ("    %s", dwarf_range_list_encoding_name (kind));
5809           switch (kind)
5810             {
5811             case DW_RLE_end_of_list:
5812               start_of_list = true;
5813               printf ("\n\n");
5814               break;
5815
5816             case DW_RLE_base_addressx:
5817               if ((uint64_t) (nexthdr - readp) < 1)
5818                 {
5819                 invalid_range:
5820                   error (0, 0, _("invalid range list data"));
5821                   goto next_table;
5822                 }
5823               get_uleb128 (op1, readp, nexthdr);
5824               printf (" %" PRIx64 "\n", op1);
5825               if (! print_unresolved_addresses)
5826                 {
5827                   Dwarf_Addr addr;
5828                   if (get_indexed_addr (cu, op1, &addr) != 0)
5829                     printf ("      ???\n");
5830                   else
5831                     {
5832                       printf ("      ");
5833                       print_dwarf_addr (dwflmod, address_size, addr, addr);
5834                       printf ("\n");
5835                     }
5836                 }
5837               break;
5838
5839             case DW_RLE_startx_endx:
5840               if ((uint64_t) (nexthdr - readp) < 1)
5841                 goto invalid_range;
5842               get_uleb128 (op1, readp, nexthdr);
5843               if ((uint64_t) (nexthdr - readp) < 1)
5844                 goto invalid_range;
5845               get_uleb128 (op2, readp, nexthdr);
5846               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
5847               if (! print_unresolved_addresses)
5848                 {
5849                   Dwarf_Addr addr1;
5850                   Dwarf_Addr addr2;
5851                   if (get_indexed_addr (cu, op1, &addr1) != 0
5852                       || get_indexed_addr (cu, op2, &addr2) != 0)
5853                     {
5854                       printf ("      ???..\n");
5855                       printf ("      ???\n");
5856                     }
5857                   else
5858                     {
5859                       printf ("      ");
5860                       print_dwarf_addr (dwflmod, address_size, addr1, addr1);
5861                       printf ("..\n      ");
5862                       print_dwarf_addr (dwflmod, address_size,
5863                                         addr2 - 1, addr2);
5864                       printf ("\n");
5865                     }
5866                 }
5867               break;
5868
5869             case DW_RLE_startx_length:
5870               if ((uint64_t) (nexthdr - readp) < 1)
5871                 goto invalid_range;
5872               get_uleb128 (op1, readp, nexthdr);
5873               if ((uint64_t) (nexthdr - readp) < 1)
5874                 goto invalid_range;
5875               get_uleb128 (op2, readp, nexthdr);
5876               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
5877               if (! print_unresolved_addresses)
5878                 {
5879                   Dwarf_Addr addr1;
5880                   Dwarf_Addr addr2;
5881                   if (get_indexed_addr (cu, op1, &addr1) != 0)
5882                     {
5883                       printf ("      ???..\n");
5884                       printf ("      ???\n");
5885                     }
5886                   else
5887                     {
5888                       addr2 = addr1 + op2;
5889                       printf ("      ");
5890                       print_dwarf_addr (dwflmod, address_size, addr1, addr1);
5891                       printf ("..\n      ");
5892                       print_dwarf_addr (dwflmod, address_size,
5893                                         addr2 - 1, addr2);
5894                       printf ("\n");
5895                     }
5896                 }
5897               break;
5898
5899             case DW_RLE_offset_pair:
5900               if ((uint64_t) (nexthdr - readp) < 1)
5901                 goto invalid_range;
5902               get_uleb128 (op1, readp, nexthdr);
5903               if ((uint64_t) (nexthdr - readp) < 1)
5904                 goto invalid_range;
5905               get_uleb128 (op2, readp, nexthdr);
5906               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
5907               if (! print_unresolved_addresses)
5908                 {
5909                   op1 += base;
5910                   op2 += base;
5911                   printf ("      ");
5912                   print_dwarf_addr (dwflmod, address_size, op1, op1);
5913                   printf ("..\n      ");
5914                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
5915                   printf ("\n");
5916                 }
5917               break;
5918
5919             case DW_RLE_base_address:
5920               if (address_size == 4)
5921                 {
5922                   if ((uint64_t) (nexthdr - readp) < 4)
5923                     goto invalid_range;
5924                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
5925                 }
5926               else
5927                 {
5928                   if ((uint64_t) (nexthdr - readp) < 8)
5929                     goto invalid_range;
5930                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
5931                 }
5932               base = op1;
5933               printf (" 0x%" PRIx64 "\n", base);
5934               if (! print_unresolved_addresses)
5935                 {
5936                   printf ("      ");
5937                   print_dwarf_addr (dwflmod, address_size, base, base);
5938                   printf ("\n");
5939                 }
5940               break;
5941
5942             case DW_RLE_start_end:
5943               if (address_size == 4)
5944                 {
5945                   if ((uint64_t) (nexthdr - readp) < 8)
5946                     goto invalid_range;
5947                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
5948                   op2 = read_4ubyte_unaligned_inc (dbg, readp);
5949                 }
5950               else
5951                 {
5952                   if ((uint64_t) (nexthdr - readp) < 16)
5953                     goto invalid_range;
5954                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
5955                   op2 = read_8ubyte_unaligned_inc (dbg, readp);
5956                 }
5957               printf (" 0x%" PRIx64 "..0x%" PRIx64 "\n", op1, op2);
5958               if (! print_unresolved_addresses)
5959                 {
5960                   printf ("      ");
5961                   print_dwarf_addr (dwflmod, address_size, op1, op1);
5962                   printf ("..\n      ");
5963                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
5964                   printf ("\n");
5965                 }
5966               break;
5967
5968             case DW_RLE_start_length:
5969               if (address_size == 4)
5970                 {
5971                   if ((uint64_t) (nexthdr - readp) < 4)
5972                     goto invalid_range;
5973                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
5974                 }
5975               else
5976                 {
5977                   if ((uint64_t) (nexthdr - readp) < 8)
5978                     goto invalid_range;
5979                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
5980                 }
5981               if ((uint64_t) (nexthdr - readp) < 1)
5982                 goto invalid_range;
5983               get_uleb128 (op2, readp, nexthdr);
5984               printf (" 0x%" PRIx64 ", %" PRIx64 "\n", op1, op2);
5985               if (! print_unresolved_addresses)
5986                 {
5987                   op2 = op1 + op2;
5988                   printf ("      ");
5989                   print_dwarf_addr (dwflmod, address_size, op1, op1);
5990                   printf ("..\n      ");
5991                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
5992                   printf ("\n");
5993                 }
5994               break;
5995
5996             default:
5997               goto invalid_range;
5998             }
5999         }
6000
6001     next_table:
6002       if (readp != nexthdr)
6003         {
6004           size_t padding = nexthdr - readp;
6005           printf (_("   %zu padding bytes\n\n"), padding);
6006           readp = nexthdr;
6007         }
6008     }
6009 }
6010
6011 /* Print content of DWARF .debug_ranges section.  */
6012 static void
6013 print_debug_ranges_section (Dwfl_Module *dwflmod,
6014                             Ebl *ebl, GElf_Ehdr *ehdr,
6015                             Elf_Scn *scn, GElf_Shdr *shdr,
6016                             Dwarf *dbg)
6017 {
6018   Elf_Data *data = (dbg->sectiondata[IDX_debug_ranges]
6019                     ?: elf_rawdata (scn, NULL));
6020   if (unlikely (data == NULL))
6021     {
6022       error (0, 0, _("cannot get .debug_ranges content: %s"),
6023              elf_errmsg (-1));
6024       return;
6025     }
6026
6027   printf (_("\
6028 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
6029           elf_ndxscn (scn), section_name (ebl, shdr),
6030           (uint64_t) shdr->sh_offset);
6031
6032   sort_listptr (&known_rangelistptr, "rangelistptr");
6033   size_t listptr_idx = 0;
6034
6035   uint_fast8_t address_size = ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
6036
6037   bool first = true;
6038   Dwarf_Addr base = 0;
6039   unsigned char *const endp = (unsigned char *) data->d_buf + data->d_size;
6040   unsigned char *readp = data->d_buf;
6041   Dwarf_CU *last_cu = NULL;
6042   while (readp < endp)
6043     {
6044       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
6045       Dwarf_CU *cu = last_cu;
6046
6047       if (first && skip_listptr_hole (&known_rangelistptr, &listptr_idx,
6048                                       &address_size, NULL, &base, &cu,
6049                                       offset, &readp, endp, NULL))
6050         continue;
6051
6052       if (last_cu != cu)
6053         {
6054           Dwarf_Die cudie;
6055           if (dwarf_cu_die (cu, &cudie,
6056                             NULL, NULL, NULL, NULL,
6057                             NULL, NULL) == NULL)
6058             printf (_("\n Unknown CU base: "));
6059           else
6060             printf (_("\n CU [%6" PRIx64 "] base: "),
6061                     dwarf_dieoffset (&cudie));
6062           print_dwarf_addr (dwflmod, address_size, base, base);
6063           printf ("\n");
6064         }
6065       last_cu = cu;
6066
6067       if (unlikely (data->d_size - offset < (size_t) address_size * 2))
6068         {
6069           printf (_(" [%6tx]  <INVALID DATA>\n"), offset);
6070           break;
6071         }
6072
6073       Dwarf_Addr begin;
6074       Dwarf_Addr end;
6075       if (address_size == 8)
6076         {
6077           begin = read_8ubyte_unaligned_inc (dbg, readp);
6078           end = read_8ubyte_unaligned_inc (dbg, readp);
6079         }
6080       else
6081         {
6082           begin = read_4ubyte_unaligned_inc (dbg, readp);
6083           end = read_4ubyte_unaligned_inc (dbg, readp);
6084           if (begin == (Dwarf_Addr) (uint32_t) -1)
6085             begin = (Dwarf_Addr) -1l;
6086         }
6087
6088       if (begin == (Dwarf_Addr) -1l) /* Base address entry.  */
6089         {
6090           if (first)
6091             printf (" [%6tx] ", offset);
6092           else
6093             printf ("          ");
6094           puts (_("base address"));
6095           printf ("          ");
6096           print_dwarf_addr (dwflmod, address_size, end, end);
6097           printf ("\n");
6098           base = end;
6099           first = false;
6100         }
6101       else if (begin == 0 && end == 0) /* End of list entry.  */
6102         {
6103           if (first)
6104             printf (_(" [%6tx] empty list\n"), offset);
6105           first = true;
6106         }
6107       else
6108         {
6109           /* We have an address range entry.  */
6110           if (first)            /* First address range entry in a list.  */
6111             printf (" [%6tx] ", offset);
6112           else
6113             printf ("          ");
6114
6115           printf ("range %" PRIx64 ", %" PRIx64 "\n", begin, end);
6116           if (! print_unresolved_addresses)
6117             {
6118               printf ("          ");
6119               print_dwarf_addr (dwflmod, address_size, base + begin,
6120                                 base + begin);
6121               printf ("..\n          ");
6122               print_dwarf_addr (dwflmod, address_size,
6123                                 base + end - 1, base + end);
6124               printf ("\n");
6125             }
6126
6127           first = false;
6128         }
6129     }
6130 }
6131
6132 #define REGNAMESZ 16
6133 static const char *
6134 register_info (Ebl *ebl, unsigned int regno, const Ebl_Register_Location *loc,
6135                char name[REGNAMESZ], int *bits, int *type)
6136 {
6137   const char *set;
6138   const char *pfx;
6139   int ignore;
6140   ssize_t n = ebl_register_info (ebl, regno, name, REGNAMESZ, &pfx, &set,
6141                                  bits ?: &ignore, type ?: &ignore);
6142   if (n <= 0)
6143     {
6144       if (loc != NULL)
6145         snprintf (name, REGNAMESZ, "reg%u", loc->regno);
6146       else
6147         snprintf (name, REGNAMESZ, "??? 0x%x", regno);
6148       if (bits != NULL)
6149         *bits = loc != NULL ? loc->bits : 0;
6150       if (type != NULL)
6151         *type = DW_ATE_unsigned;
6152       set = "??? unrecognized";
6153     }
6154   else
6155     {
6156       if (bits != NULL && *bits <= 0)
6157         *bits = loc != NULL ? loc->bits : 0;
6158       if (type != NULL && *type == DW_ATE_void)
6159         *type = DW_ATE_unsigned;
6160
6161     }
6162   return set;
6163 }
6164
6165 static const unsigned char *
6166 read_encoded (unsigned int encoding, const unsigned char *readp,
6167               const unsigned char *const endp, uint64_t *res, Dwarf *dbg)
6168 {
6169   if ((encoding & 0xf) == DW_EH_PE_absptr)
6170     encoding = gelf_getclass (dbg->elf) == ELFCLASS32
6171       ? DW_EH_PE_udata4 : DW_EH_PE_udata8;
6172
6173   switch (encoding & 0xf)
6174     {
6175     case DW_EH_PE_uleb128:
6176       get_uleb128 (*res, readp, endp);
6177       break;
6178     case DW_EH_PE_sleb128:
6179       get_sleb128 (*res, readp, endp);
6180       break;
6181     case DW_EH_PE_udata2:
6182       if (readp + 2 > endp)
6183         goto invalid;
6184       *res = read_2ubyte_unaligned_inc (dbg, readp);
6185       break;
6186     case DW_EH_PE_udata4:
6187       if (readp + 4 > endp)
6188         goto invalid;
6189       *res = read_4ubyte_unaligned_inc (dbg, readp);
6190       break;
6191     case DW_EH_PE_udata8:
6192       if (readp + 8 > endp)
6193         goto invalid;
6194       *res = read_8ubyte_unaligned_inc (dbg, readp);
6195       break;
6196     case DW_EH_PE_sdata2:
6197       if (readp + 2 > endp)
6198         goto invalid;
6199       *res = read_2sbyte_unaligned_inc (dbg, readp);
6200       break;
6201     case DW_EH_PE_sdata4:
6202       if (readp + 4 > endp)
6203         goto invalid;
6204       *res = read_4sbyte_unaligned_inc (dbg, readp);
6205       break;
6206     case DW_EH_PE_sdata8:
6207       if (readp + 8 > endp)
6208         goto invalid;
6209       *res = read_8sbyte_unaligned_inc (dbg, readp);
6210       break;
6211     default:
6212     invalid:
6213       error (1, 0,
6214              _("invalid encoding"));
6215     }
6216
6217   return readp;
6218 }
6219
6220 static const char *
6221 regname (Ebl *ebl, unsigned int regno, char *regnamebuf)
6222 {
6223   register_info (ebl, regno, NULL, regnamebuf, NULL, NULL);
6224
6225   return regnamebuf;
6226 }
6227
6228 static void
6229 print_cfa_program (const unsigned char *readp, const unsigned char *const endp,
6230                    Dwarf_Word vma_base, unsigned int code_align,
6231                    int data_align,
6232                    unsigned int version, unsigned int ptr_size,
6233                    unsigned int encoding,
6234                    Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr, Dwarf *dbg)
6235 {
6236   char regnamebuf[REGNAMESZ];
6237
6238   puts ("\n   Program:");
6239   Dwarf_Word pc = vma_base;
6240   while (readp < endp)
6241     {
6242       unsigned int opcode = *readp++;
6243
6244       if (opcode < DW_CFA_advance_loc)
6245         /* Extended opcode.  */
6246         switch (opcode)
6247           {
6248             uint64_t op1;
6249             int64_t sop1;
6250             uint64_t op2;
6251             int64_t sop2;
6252
6253           case DW_CFA_nop:
6254             puts ("     nop");
6255             break;
6256           case DW_CFA_set_loc:
6257             if ((uint64_t) (endp - readp) < 1)
6258               goto invalid;
6259             readp = read_encoded (encoding, readp, endp, &op1, dbg);
6260             printf ("     set_loc %#" PRIx64 " to %#" PRIx64 "\n",
6261                     op1, pc = vma_base + op1);
6262             break;
6263           case DW_CFA_advance_loc1:
6264             if ((uint64_t) (endp - readp) < 1)
6265               goto invalid;
6266             printf ("     advance_loc1 %u to %#" PRIx64 "\n",
6267                     *readp, pc += *readp * code_align);
6268             ++readp;
6269             break;
6270           case DW_CFA_advance_loc2:
6271             if ((uint64_t) (endp - readp) < 2)
6272               goto invalid;
6273             op1 = read_2ubyte_unaligned_inc (dbg, readp);
6274             printf ("     advance_loc2 %" PRIu64 " to %#" PRIx64 "\n",
6275                     op1, pc += op1 * code_align);
6276             break;
6277           case DW_CFA_advance_loc4:
6278             if ((uint64_t) (endp - readp) < 4)
6279               goto invalid;
6280             op1 = read_4ubyte_unaligned_inc (dbg, readp);
6281             printf ("     advance_loc4 %" PRIu64 " to %#" PRIx64 "\n",
6282                     op1, pc += op1 * code_align);
6283             break;
6284           case DW_CFA_offset_extended:
6285             if ((uint64_t) (endp - readp) < 1)
6286               goto invalid;
6287             get_uleb128 (op1, readp, endp);
6288             if ((uint64_t) (endp - readp) < 1)
6289               goto invalid;
6290             get_uleb128 (op2, readp, endp);
6291             printf ("     offset_extended r%" PRIu64 " (%s) at cfa%+" PRId64
6292                     "\n",
6293                     op1, regname (ebl, op1, regnamebuf), op2 * data_align);
6294             break;
6295           case DW_CFA_restore_extended:
6296             if ((uint64_t) (endp - readp) < 1)
6297               goto invalid;
6298             get_uleb128 (op1, readp, endp);
6299             printf ("     restore_extended r%" PRIu64 " (%s)\n",
6300                     op1, regname (ebl, op1, regnamebuf));
6301             break;
6302           case DW_CFA_undefined:
6303             if ((uint64_t) (endp - readp) < 1)
6304               goto invalid;
6305             get_uleb128 (op1, readp, endp);
6306             printf ("     undefined r%" PRIu64 " (%s)\n", op1,
6307                     regname (ebl, op1, regnamebuf));
6308             break;
6309           case DW_CFA_same_value:
6310             if ((uint64_t) (endp - readp) < 1)
6311               goto invalid;
6312             get_uleb128 (op1, readp, endp);
6313             printf ("     same_value r%" PRIu64 " (%s)\n", op1,
6314                     regname (ebl, op1, regnamebuf));
6315             break;
6316           case DW_CFA_register:
6317             if ((uint64_t) (endp - readp) < 1)
6318               goto invalid;
6319             get_uleb128 (op1, readp, endp);
6320             if ((uint64_t) (endp - readp) < 1)
6321               goto invalid;
6322             get_uleb128 (op2, readp, endp);
6323             printf ("     register r%" PRIu64 " (%s) in r%" PRIu64 " (%s)\n",
6324                     op1, regname (ebl, op1, regnamebuf), op2,
6325                     regname (ebl, op2, regnamebuf));
6326             break;
6327           case DW_CFA_remember_state:
6328             puts ("     remember_state");
6329             break;
6330           case DW_CFA_restore_state:
6331             puts ("     restore_state");
6332             break;
6333           case DW_CFA_def_cfa:
6334             if ((uint64_t) (endp - readp) < 1)
6335               goto invalid;
6336             get_uleb128 (op1, readp, endp);
6337             if ((uint64_t) (endp - readp) < 1)
6338               goto invalid;
6339             get_uleb128 (op2, readp, endp);
6340             printf ("     def_cfa r%" PRIu64 " (%s) at offset %" PRIu64 "\n",
6341                     op1, regname (ebl, op1, regnamebuf), op2);
6342             break;
6343           case DW_CFA_def_cfa_register:
6344             if ((uint64_t) (endp - readp) < 1)
6345               goto invalid;
6346             get_uleb128 (op1, readp, endp);
6347             printf ("     def_cfa_register r%" PRIu64 " (%s)\n",
6348                     op1, regname (ebl, op1, regnamebuf));
6349             break;
6350           case DW_CFA_def_cfa_offset:
6351             if ((uint64_t) (endp - readp) < 1)
6352               goto invalid;
6353             get_uleb128 (op1, readp, endp);
6354             printf ("     def_cfa_offset %" PRIu64 "\n", op1);
6355             break;
6356           case DW_CFA_def_cfa_expression:
6357             if ((uint64_t) (endp - readp) < 1)
6358               goto invalid;
6359             get_uleb128 (op1, readp, endp);     /* Length of DW_FORM_block.  */
6360             printf ("     def_cfa_expression %" PRIu64 "\n", op1);
6361             if ((uint64_t) (endp - readp) < op1)
6362               {
6363             invalid:
6364                 fputs (_("         <INVALID DATA>\n"), stdout);
6365                 return;
6366               }
6367             print_ops (dwflmod, dbg, 10, 10, version, ptr_size, 0, NULL,
6368                        op1, readp);
6369             readp += op1;
6370             break;
6371           case DW_CFA_expression:
6372             if ((uint64_t) (endp - readp) < 1)
6373               goto invalid;
6374             get_uleb128 (op1, readp, endp);
6375             if ((uint64_t) (endp - readp) < 1)
6376               goto invalid;
6377             get_uleb128 (op2, readp, endp);     /* Length of DW_FORM_block.  */
6378             printf ("     expression r%" PRIu64 " (%s) \n",
6379                     op1, regname (ebl, op1, regnamebuf));
6380             if ((uint64_t) (endp - readp) < op2)
6381               goto invalid;
6382             print_ops (dwflmod, dbg, 10, 10, version, ptr_size, 0, NULL,
6383                        op2, readp);
6384             readp += op2;
6385             break;
6386           case DW_CFA_offset_extended_sf:
6387             if ((uint64_t) (endp - readp) < 1)
6388               goto invalid;
6389             get_uleb128 (op1, readp, endp);
6390             if ((uint64_t) (endp - readp) < 1)
6391               goto invalid;
6392             get_sleb128 (sop2, readp, endp);
6393             printf ("     offset_extended_sf r%" PRIu64 " (%s) at cfa%+"
6394                     PRId64 "\n",
6395                     op1, regname (ebl, op1, regnamebuf), sop2 * data_align);
6396             break;
6397           case DW_CFA_def_cfa_sf:
6398             if ((uint64_t) (endp - readp) < 1)
6399               goto invalid;
6400             get_uleb128 (op1, readp, endp);
6401             if ((uint64_t) (endp - readp) < 1)
6402               goto invalid;
6403             get_sleb128 (sop2, readp, endp);
6404             printf ("     def_cfa_sf r%" PRIu64 " (%s) at offset %" PRId64 "\n",
6405                     op1, regname (ebl, op1, regnamebuf), sop2 * data_align);
6406             break;
6407           case DW_CFA_def_cfa_offset_sf:
6408             if ((uint64_t) (endp - readp) < 1)
6409               goto invalid;
6410             get_sleb128 (sop1, readp, endp);
6411             printf ("     def_cfa_offset_sf %" PRId64 "\n", sop1 * data_align);
6412             break;
6413           case DW_CFA_val_offset:
6414             if ((uint64_t) (endp - readp) < 1)
6415               goto invalid;
6416             get_uleb128 (op1, readp, endp);
6417             if ((uint64_t) (endp - readp) < 1)
6418               goto invalid;
6419             get_uleb128 (op2, readp, endp);
6420             printf ("     val_offset %" PRIu64 " at offset %" PRIu64 "\n",
6421                     op1, op2 * data_align);
6422             break;
6423           case DW_CFA_val_offset_sf:
6424             if ((uint64_t) (endp - readp) < 1)
6425               goto invalid;
6426             get_uleb128 (op1, readp, endp);
6427             if ((uint64_t) (endp - readp) < 1)
6428               goto invalid;
6429             get_sleb128 (sop2, readp, endp);
6430             printf ("     val_offset_sf %" PRIu64 " at offset %" PRId64 "\n",
6431                     op1, sop2 * data_align);
6432             break;
6433           case DW_CFA_val_expression:
6434             if ((uint64_t) (endp - readp) < 1)
6435               goto invalid;
6436             get_uleb128 (op1, readp, endp);
6437             if ((uint64_t) (endp - readp) < 1)
6438               goto invalid;
6439             get_uleb128 (op2, readp, endp);     /* Length of DW_FORM_block.  */
6440             printf ("     val_expression r%" PRIu64 " (%s)\n",
6441                     op1, regname (ebl, op1, regnamebuf));
6442             if ((uint64_t) (endp - readp) < op2)
6443               goto invalid;
6444             print_ops (dwflmod, dbg, 10, 10, version, ptr_size, 0,
6445                        NULL, op2, readp);
6446             readp += op2;
6447             break;
6448           case DW_CFA_MIPS_advance_loc8:
6449             if ((uint64_t) (endp - readp) < 8)
6450               goto invalid;
6451             op1 = read_8ubyte_unaligned_inc (dbg, readp);
6452             printf ("     MIPS_advance_loc8 %" PRIu64 " to %#" PRIx64 "\n",
6453                     op1, pc += op1 * code_align);
6454             break;
6455           case DW_CFA_GNU_window_save:  /* DW_CFA_AARCH64_negate_ra_state  */
6456             if (ehdr->e_machine == EM_AARCH64)
6457               puts ("     AARCH64_negate_ra_state");
6458             else
6459               puts ("     GNU_window_save");
6460             break;
6461           case DW_CFA_GNU_args_size:
6462             if ((uint64_t) (endp - readp) < 1)
6463               goto invalid;
6464             get_uleb128 (op1, readp, endp);
6465             printf ("     args_size %" PRIu64 "\n", op1);
6466             break;
6467           default:
6468             printf ("     ??? (%u)\n", opcode);
6469             break;
6470           }
6471       else if (opcode < DW_CFA_offset)
6472         printf ("     advance_loc %u to %#" PRIx64 "\n",
6473                 opcode & 0x3f, pc += (opcode & 0x3f) * code_align);
6474       else if (opcode < DW_CFA_restore)
6475         {
6476           uint64_t offset;
6477           if ((uint64_t) (endp - readp) < 1)
6478             goto invalid;
6479           get_uleb128 (offset, readp, endp);
6480           printf ("     offset r%u (%s) at cfa%+" PRId64 "\n",
6481                   opcode & 0x3f, regname (ebl, opcode & 0x3f, regnamebuf),
6482                   offset * data_align);
6483         }
6484       else
6485         printf ("     restore r%u (%s)\n",
6486                 opcode & 0x3f, regname (ebl, opcode & 0x3f, regnamebuf));
6487     }
6488 }
6489
6490
6491 static unsigned int
6492 encoded_ptr_size (int encoding, unsigned int ptr_size)
6493 {
6494   switch (encoding & 7)
6495     {
6496     case DW_EH_PE_udata4:
6497       return 4;
6498     case DW_EH_PE_udata8:
6499       return 8;
6500     case 0:
6501       return ptr_size;
6502     }
6503
6504   fprintf (stderr, "Unsupported pointer encoding: %#x, "
6505            "assuming pointer size of %d.\n", encoding, ptr_size);
6506   return ptr_size;
6507 }
6508
6509
6510 static unsigned int
6511 print_encoding (unsigned int val)
6512 {
6513   switch (val & 0xf)
6514     {
6515     case DW_EH_PE_absptr:
6516       fputs ("absptr", stdout);
6517       break;
6518     case DW_EH_PE_uleb128:
6519       fputs ("uleb128", stdout);
6520       break;
6521     case DW_EH_PE_udata2:
6522       fputs ("udata2", stdout);
6523       break;
6524     case DW_EH_PE_udata4:
6525       fputs ("udata4", stdout);
6526       break;
6527     case DW_EH_PE_udata8:
6528       fputs ("udata8", stdout);
6529       break;
6530     case DW_EH_PE_sleb128:
6531       fputs ("sleb128", stdout);
6532       break;
6533     case DW_EH_PE_sdata2:
6534       fputs ("sdata2", stdout);
6535       break;
6536     case DW_EH_PE_sdata4:
6537       fputs ("sdata4", stdout);
6538       break;
6539     case DW_EH_PE_sdata8:
6540       fputs ("sdata8", stdout);
6541       break;
6542     default:
6543       /* We did not use any of the bits after all.  */
6544       return val;
6545     }
6546
6547   return val & ~0xf;
6548 }
6549
6550
6551 static unsigned int
6552 print_relinfo (unsigned int val)
6553 {
6554   switch (val & 0x70)
6555     {
6556     case DW_EH_PE_pcrel:
6557       fputs ("pcrel", stdout);
6558       break;
6559     case DW_EH_PE_textrel:
6560       fputs ("textrel", stdout);
6561       break;
6562     case DW_EH_PE_datarel:
6563       fputs ("datarel", stdout);
6564       break;
6565     case DW_EH_PE_funcrel:
6566       fputs ("funcrel", stdout);
6567       break;
6568     case DW_EH_PE_aligned:
6569       fputs ("aligned", stdout);
6570       break;
6571     default:
6572       return val;
6573     }
6574
6575   return val & ~0x70;
6576 }
6577
6578
6579 static void
6580 print_encoding_base (const char *pfx, unsigned int fde_encoding)
6581 {
6582   printf ("(%s", pfx);
6583
6584   if (fde_encoding == DW_EH_PE_omit)
6585     puts ("omit)");
6586   else
6587     {
6588       unsigned int w = fde_encoding;
6589
6590       w = print_encoding (w);
6591
6592       if (w & 0x70)
6593         {
6594           if (w != fde_encoding)
6595             fputc_unlocked (' ', stdout);
6596
6597           w = print_relinfo (w);
6598         }
6599
6600       if (w != 0)
6601         printf ("%s%x", w != fde_encoding ? " " : "", w);
6602
6603       puts (")");
6604     }
6605 }
6606
6607
6608 static void
6609 print_debug_frame_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
6610                            Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
6611 {
6612   size_t shstrndx;
6613   /* We know this call will succeed since it did in the caller.  */
6614   (void) elf_getshdrstrndx (ebl->elf, &shstrndx);
6615   const char *scnname = elf_strptr (ebl->elf, shstrndx, shdr->sh_name);
6616
6617   /* Needed if we find PC-relative addresses.  */
6618   GElf_Addr bias;
6619   if (dwfl_module_getelf (dwflmod, &bias) == NULL)
6620     {
6621       error (0, 0, _("cannot get ELF: %s"), dwfl_errmsg (-1));
6622       return;
6623     }
6624
6625   bool is_eh_frame = strcmp (scnname, ".eh_frame") == 0;
6626   Elf_Data *data = (is_eh_frame
6627                     ? elf_rawdata (scn, NULL)
6628                     : (dbg->sectiondata[IDX_debug_frame]
6629                        ?: elf_rawdata (scn, NULL)));
6630
6631   if (unlikely (data == NULL))
6632     {
6633       error (0, 0, _("cannot get %s content: %s"),
6634              scnname, elf_errmsg (-1));
6635       return;
6636     }
6637
6638   if (is_eh_frame)
6639     printf (_("\
6640 \nCall frame information section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
6641             elf_ndxscn (scn), scnname, (uint64_t) shdr->sh_offset);
6642   else
6643     printf (_("\
6644 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
6645             elf_ndxscn (scn), scnname, (uint64_t) shdr->sh_offset);
6646
6647   struct cieinfo
6648   {
6649     ptrdiff_t cie_offset;
6650     const char *augmentation;
6651     unsigned int code_alignment_factor;
6652     unsigned int data_alignment_factor;
6653     uint8_t address_size;
6654     uint8_t fde_encoding;
6655     uint8_t lsda_encoding;
6656     struct cieinfo *next;
6657   } *cies = NULL;
6658
6659   const unsigned char *readp = data->d_buf;
6660   const unsigned char *const dataend = ((unsigned char *) data->d_buf
6661                                         + data->d_size);
6662   while (readp < dataend)
6663     {
6664       if (unlikely (readp + 4 > dataend))
6665         {
6666         invalid_data:
6667           error (0, 0, _("invalid data in section [%zu] '%s'"),
6668                      elf_ndxscn (scn), scnname);
6669               return;
6670         }
6671
6672       /* At the beginning there must be a CIE.  There can be multiple,
6673          hence we test tis in a loop.  */
6674       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
6675
6676       Dwarf_Word unit_length = read_4ubyte_unaligned_inc (dbg, readp);
6677       unsigned int length = 4;
6678       if (unlikely (unit_length == 0xffffffff))
6679         {
6680           if (unlikely (readp + 8 > dataend))
6681             goto invalid_data;
6682
6683           unit_length = read_8ubyte_unaligned_inc (dbg, readp);
6684           length = 8;
6685         }
6686
6687       if (unlikely (unit_length == 0))
6688         {
6689           printf (_("\n [%6tx] Zero terminator\n"), offset);
6690           continue;
6691         }
6692
6693       Dwarf_Word maxsize = dataend - readp;
6694       if (unlikely (unit_length > maxsize))
6695         goto invalid_data;
6696
6697       unsigned int ptr_size = ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
6698
6699       ptrdiff_t start = readp - (unsigned char *) data->d_buf;
6700       const unsigned char *const cieend = readp + unit_length;
6701       if (unlikely (cieend > dataend))
6702         goto invalid_data;
6703
6704       Dwarf_Off cie_id;
6705       if (length == 4)
6706         {
6707           if (unlikely (cieend - readp < 4))
6708             goto invalid_data;
6709           cie_id = read_4ubyte_unaligned_inc (dbg, readp);
6710           if (!is_eh_frame && cie_id == DW_CIE_ID_32)
6711             cie_id = DW_CIE_ID_64;
6712         }
6713       else
6714         {
6715           if (unlikely (cieend - readp < 8))
6716             goto invalid_data;
6717           cie_id = read_8ubyte_unaligned_inc (dbg, readp);
6718         }
6719
6720       uint_fast8_t version = 2;
6721       unsigned int code_alignment_factor;
6722       int data_alignment_factor;
6723       unsigned int fde_encoding = 0;
6724       unsigned int lsda_encoding = 0;
6725       Dwarf_Word initial_location = 0;
6726       Dwarf_Word vma_base = 0;
6727
6728       if (cie_id == (is_eh_frame ? 0 : DW_CIE_ID_64))
6729         {
6730           if (unlikely (cieend - readp < 2))
6731             goto invalid_data;
6732           version = *readp++;
6733           const char *const augmentation = (const char *) readp;
6734           readp = memchr (readp, '\0', cieend - readp);
6735           if (unlikely (readp == NULL))
6736             goto invalid_data;
6737           ++readp;
6738
6739           uint_fast8_t segment_size = 0;
6740           if (version >= 4)
6741             {
6742               if (cieend - readp < 5)
6743                 goto invalid_data;
6744               ptr_size = *readp++;
6745               segment_size = *readp++;
6746             }
6747
6748           if (cieend - readp < 1)
6749             goto invalid_data;
6750           get_uleb128 (code_alignment_factor, readp, cieend);
6751           if (cieend - readp < 1)
6752             goto invalid_data;
6753           get_sleb128 (data_alignment_factor, readp, cieend);
6754
6755           /* In some variant for unwind data there is another field.  */
6756           if (strcmp (augmentation, "eh") == 0)
6757             readp += ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
6758
6759           unsigned int return_address_register;
6760           if (cieend - readp < 1)
6761             goto invalid_data;
6762           if (unlikely (version == 1))
6763             return_address_register = *readp++;
6764           else
6765             get_uleb128 (return_address_register, readp, cieend);
6766
6767           printf ("\n [%6tx] CIE length=%" PRIu64 "\n"
6768                   "   CIE_id:                   %" PRIu64 "\n"
6769                   "   version:                  %u\n"
6770                   "   augmentation:             \"%s\"\n",
6771                   offset, (uint64_t) unit_length, (uint64_t) cie_id,
6772                   version, augmentation);
6773           if (version >= 4)
6774             printf ("   address_size:             %u\n"
6775                     "   segment_size:             %u\n",
6776                     ptr_size, segment_size);
6777           printf ("   code_alignment_factor:    %u\n"
6778                   "   data_alignment_factor:    %d\n"
6779                   "   return_address_register:  %u\n",
6780                   code_alignment_factor,
6781                   data_alignment_factor, return_address_register);
6782
6783           if (augmentation[0] == 'z')
6784             {
6785               unsigned int augmentationlen;
6786               get_uleb128 (augmentationlen, readp, cieend);
6787
6788               if (augmentationlen > (size_t) (cieend - readp))
6789                 {
6790                   error (0, 0, _("invalid augmentation length"));
6791                   readp = cieend;
6792                   continue;
6793                 }
6794
6795               const char *hdr = "Augmentation data:";
6796               const char *cp = augmentation + 1;
6797               while (*cp != '\0' && cp < augmentation + augmentationlen + 1)
6798                 {
6799                   printf ("   %-26s%#x ", hdr, *readp);
6800                   hdr = "";
6801
6802                   if (*cp == 'R')
6803                     {
6804                       fde_encoding = *readp++;
6805                       print_encoding_base (_("FDE address encoding: "),
6806                                            fde_encoding);
6807                     }
6808                   else if (*cp == 'L')
6809                     {
6810                       lsda_encoding = *readp++;
6811                       print_encoding_base (_("LSDA pointer encoding: "),
6812                                            lsda_encoding);
6813                     }
6814                   else if (*cp == 'P')
6815                     {
6816                       /* Personality.  This field usually has a relocation
6817                          attached pointing to __gcc_personality_v0.  */
6818                       const unsigned char *startp = readp;
6819                       unsigned int encoding = *readp++;
6820                       uint64_t val = 0;
6821                       readp = read_encoded (encoding, readp,
6822                                             readp - 1 + augmentationlen,
6823                                             &val, dbg);
6824
6825                       while (++startp < readp)
6826                         printf ("%#x ", *startp);
6827
6828                       putchar ('(');
6829                       print_encoding (encoding);
6830                       putchar (' ');
6831                       switch (encoding & 0xf)
6832                         {
6833                         case DW_EH_PE_sleb128:
6834                         case DW_EH_PE_sdata2:
6835                         case DW_EH_PE_sdata4:
6836                           printf ("%" PRId64 ")\n", val);
6837                           break;
6838                         default:
6839                           printf ("%#" PRIx64 ")\n", val);
6840                           break;
6841                         }
6842                     }
6843                   else
6844                     printf ("(%x)\n", *readp++);
6845
6846                   ++cp;
6847                 }
6848             }
6849
6850           if (likely (ptr_size == 4 || ptr_size == 8))
6851             {
6852               struct cieinfo *newp = alloca (sizeof (*newp));
6853               newp->cie_offset = offset;
6854               newp->augmentation = augmentation;
6855               newp->fde_encoding = fde_encoding;
6856               newp->lsda_encoding = lsda_encoding;
6857               newp->address_size = ptr_size;
6858               newp->code_alignment_factor = code_alignment_factor;
6859               newp->data_alignment_factor = data_alignment_factor;
6860               newp->next = cies;
6861               cies = newp;
6862             }
6863         }
6864       else
6865         {
6866           struct cieinfo *cie = cies;
6867           while (cie != NULL)
6868             if (is_eh_frame
6869                 ? ((Dwarf_Off) start - cie_id) == (Dwarf_Off) cie->cie_offset
6870                 : cie_id == (Dwarf_Off) cie->cie_offset)
6871               break;
6872             else
6873               cie = cie->next;
6874           if (unlikely (cie == NULL))
6875             {
6876               puts ("invalid CIE reference in FDE");
6877               return;
6878             }
6879
6880           /* Initialize from CIE data.  */
6881           fde_encoding = cie->fde_encoding;
6882           lsda_encoding = cie->lsda_encoding;
6883           ptr_size = encoded_ptr_size (fde_encoding, cie->address_size);
6884           code_alignment_factor = cie->code_alignment_factor;
6885           data_alignment_factor = cie->data_alignment_factor;
6886
6887           const unsigned char *base = readp;
6888           // XXX There are sometimes relocations for this value
6889           initial_location = read_addr_unaligned_inc (ptr_size, dbg, readp);
6890           Dwarf_Word address_range
6891             = read_addr_unaligned_inc (ptr_size, dbg, readp);
6892
6893           /* pcrel for an FDE address is relative to the runtime
6894              address of the start_address field itself.  Sign extend
6895              if necessary to make sure the calculation is done on the
6896              full 64 bit address even when initial_location only holds
6897              the lower 32 bits.  */
6898           Dwarf_Addr pc_start = initial_location;
6899           if (ptr_size == 4)
6900             pc_start = (uint64_t) (int32_t) pc_start;
6901           if ((fde_encoding & 0x70) == DW_EH_PE_pcrel)
6902             pc_start += ((uint64_t) shdr->sh_addr
6903                          + (base - (const unsigned char *) data->d_buf)
6904                          - bias);
6905
6906           printf ("\n [%6tx] FDE length=%" PRIu64 " cie=[%6tx]\n"
6907                   "   CIE_pointer:              %" PRIu64 "\n"
6908                   "   initial_location:         ",
6909                   offset, (uint64_t) unit_length,
6910                   cie->cie_offset, (uint64_t) cie_id);
6911           print_dwarf_addr (dwflmod, cie->address_size,
6912                             pc_start, initial_location);
6913           if ((fde_encoding & 0x70) == DW_EH_PE_pcrel)
6914             {
6915               vma_base = (((uint64_t) shdr->sh_offset
6916                            + (base - (const unsigned char *) data->d_buf)
6917                            + (uint64_t) initial_location)
6918                           & (ptr_size == 4
6919                              ? UINT64_C (0xffffffff)
6920                              : UINT64_C (0xffffffffffffffff)));
6921               printf (_(" (offset: %#" PRIx64 ")"),
6922                       (uint64_t) vma_base);
6923             }
6924
6925           printf ("\n   address_range:            %#" PRIx64,
6926                   (uint64_t) address_range);
6927           if ((fde_encoding & 0x70) == DW_EH_PE_pcrel)
6928             printf (_(" (end offset: %#" PRIx64 ")"),
6929                     ((uint64_t) vma_base + (uint64_t) address_range)
6930                     & (ptr_size == 4
6931                        ? UINT64_C (0xffffffff)
6932                        : UINT64_C (0xffffffffffffffff)));
6933           putchar ('\n');
6934
6935           if (cie->augmentation[0] == 'z')
6936             {
6937               unsigned int augmentationlen;
6938               if (cieend - readp < 1)
6939                 goto invalid_data;
6940               get_uleb128 (augmentationlen, readp, cieend);
6941
6942               if (augmentationlen > (size_t) (cieend - readp))
6943                 {
6944                   error (0, 0, _("invalid augmentation length"));
6945                   readp = cieend;
6946                   continue;
6947                 }
6948
6949               if (augmentationlen > 0)
6950                 {
6951                   const char *hdr = "Augmentation data:";
6952                   const char *cp = cie->augmentation + 1;
6953                   unsigned int u = 0;
6954                   while (*cp != '\0'
6955                          && cp < cie->augmentation + augmentationlen + 1)
6956                     {
6957                       if (*cp == 'L')
6958                         {
6959                           uint64_t lsda_pointer;
6960                           const unsigned char *p
6961                             = read_encoded (lsda_encoding, &readp[u],
6962                                             &readp[augmentationlen],
6963                                             &lsda_pointer, dbg);
6964                           u = p - readp;
6965                           printf (_("\
6966    %-26sLSDA pointer: %#" PRIx64 "\n"),
6967                                   hdr, lsda_pointer);
6968                           hdr = "";
6969                         }
6970                       ++cp;
6971                     }
6972
6973                   while (u < augmentationlen)
6974                     {
6975                       printf ("   %-26s%#x\n", hdr, readp[u++]);
6976                       hdr = "";
6977                     }
6978                 }
6979
6980               readp += augmentationlen;
6981             }
6982         }
6983
6984       /* Handle the initialization instructions.  */
6985       if (ptr_size != 4 && ptr_size !=8)
6986         printf ("invalid CIE pointer size (%u), must be 4 or 8.\n", ptr_size);
6987       else
6988         print_cfa_program (readp, cieend, vma_base, code_alignment_factor,
6989                            data_alignment_factor, version, ptr_size,
6990                            fde_encoding, dwflmod, ebl, ehdr, dbg);
6991       readp = cieend;
6992     }
6993 }
6994
6995
6996 /* Returns the signedness (or false if it cannot be determined) and
6997    the byte size (or zero if it cannot be gotten) of the given DIE
6998    DW_AT_type attribute.  Uses dwarf_peel_type and dwarf_aggregate_size.  */
6999 static void
7000 die_type_sign_bytes (Dwarf_Die *die, bool *is_signed, int *bytes)
7001 {
7002   Dwarf_Attribute attr;
7003   Dwarf_Die type;
7004
7005   *bytes = 0;
7006   *is_signed = false;
7007
7008   if (dwarf_peel_type (dwarf_formref_die (dwarf_attr_integrate (die,
7009                                                                 DW_AT_type,
7010                                                                 &attr), &type),
7011                        &type) == 0)
7012     {
7013       Dwarf_Word val;
7014       *is_signed = (dwarf_formudata (dwarf_attr (&type, DW_AT_encoding,
7015                                                  &attr), &val) == 0
7016                     && (val == DW_ATE_signed || val == DW_ATE_signed_char));
7017
7018       if (dwarf_aggregate_size (&type, &val) == 0)
7019         *bytes = val;
7020     }
7021 }
7022
7023 struct attrcb_args
7024 {
7025   Dwfl_Module *dwflmod;
7026   Dwarf *dbg;
7027   Dwarf_Die *dies;
7028   int level;
7029   bool silent;
7030   bool is_split;
7031   unsigned int version;
7032   unsigned int addrsize;
7033   unsigned int offset_size;
7034   struct Dwarf_CU *cu;
7035 };
7036
7037
7038 static int
7039 attr_callback (Dwarf_Attribute *attrp, void *arg)
7040 {
7041   struct attrcb_args *cbargs = (struct attrcb_args *) arg;
7042   const int level = cbargs->level;
7043   Dwarf_Die *die = &cbargs->dies[level];
7044   bool is_split = cbargs->is_split;
7045
7046   unsigned int attr = dwarf_whatattr (attrp);
7047   if (unlikely (attr == 0))
7048     {
7049       if (!cbargs->silent)
7050         error (0, 0, _("DIE [%" PRIx64 "] "
7051                               "cannot get attribute code: %s"),
7052                dwarf_dieoffset (die), dwarf_errmsg (-1));
7053       return DWARF_CB_ABORT;
7054     }
7055
7056   unsigned int form = dwarf_whatform (attrp);
7057   if (unlikely (form == 0))
7058     {
7059       if (!cbargs->silent)
7060         error (0, 0, _("DIE [%" PRIx64 "] "
7061                               "cannot get attribute form: %s"),
7062                dwarf_dieoffset (die), dwarf_errmsg (-1));
7063       return DWARF_CB_ABORT;
7064     }
7065
7066   switch (form)
7067     {
7068     case DW_FORM_addr:
7069     case DW_FORM_addrx:
7070     case DW_FORM_addrx1:
7071     case DW_FORM_addrx2:
7072     case DW_FORM_addrx3:
7073     case DW_FORM_addrx4:
7074     case DW_FORM_GNU_addr_index:
7075       if (!cbargs->silent)
7076         {
7077           Dwarf_Addr addr;
7078           if (unlikely (dwarf_formaddr (attrp, &addr) != 0))
7079             {
7080             attrval_out:
7081               if (!cbargs->silent)
7082                 error (0, 0, _("DIE [%" PRIx64 "] "
7083                                       "cannot get attribute '%s' (%s) value: "
7084                                       "%s"),
7085                        dwarf_dieoffset (die),
7086                        dwarf_attr_name (attr),
7087                        dwarf_form_name (form),
7088                        dwarf_errmsg (-1));
7089               /* Don't ABORT, it might be other attributes can be resolved.  */
7090               return DWARF_CB_OK;
7091             }
7092           if (form != DW_FORM_addr )
7093             {
7094               Dwarf_Word word;
7095               if (dwarf_formudata (attrp, &word) != 0)
7096                 goto attrval_out;
7097               printf ("           %*s%-20s (%s) [%" PRIx64 "] ",
7098                       (int) (level * 2), "", dwarf_attr_name (attr),
7099                       dwarf_form_name (form), word);
7100             }
7101           else
7102             printf ("           %*s%-20s (%s) ",
7103                     (int) (level * 2), "", dwarf_attr_name (attr),
7104                     dwarf_form_name (form));
7105           print_dwarf_addr (cbargs->dwflmod, cbargs->addrsize, addr, addr);
7106           printf ("\n");
7107         }
7108       break;
7109
7110     case DW_FORM_indirect:
7111     case DW_FORM_strp:
7112     case DW_FORM_line_strp:
7113     case DW_FORM_strx:
7114     case DW_FORM_strx1:
7115     case DW_FORM_strx2:
7116     case DW_FORM_strx3:
7117     case DW_FORM_strx4:
7118     case DW_FORM_string:
7119     case DW_FORM_GNU_strp_alt:
7120     case DW_FORM_GNU_str_index:
7121       if (cbargs->silent)
7122         break;
7123       const char *str = dwarf_formstring (attrp);
7124       if (unlikely (str == NULL))
7125         goto attrval_out;
7126       printf ("           %*s%-20s (%s) \"%s\"\n",
7127               (int) (level * 2), "", dwarf_attr_name (attr),
7128               dwarf_form_name (form), str);
7129       break;
7130
7131     case DW_FORM_ref_addr:
7132     case DW_FORM_ref_udata:
7133     case DW_FORM_ref8:
7134     case DW_FORM_ref4:
7135     case DW_FORM_ref2:
7136     case DW_FORM_ref1:
7137     case DW_FORM_GNU_ref_alt:
7138     case DW_FORM_ref_sup4:
7139     case DW_FORM_ref_sup8:
7140       if (cbargs->silent)
7141         break;
7142       Dwarf_Die ref;
7143       if (unlikely (dwarf_formref_die (attrp, &ref) == NULL))
7144         goto attrval_out;
7145
7146       printf ("           %*s%-20s (%s) ",
7147               (int) (level * 2), "", dwarf_attr_name (attr),
7148               dwarf_form_name (form));
7149       if (is_split)
7150         printf ("{%6" PRIxMAX "}\n", (uintmax_t) dwarf_dieoffset (&ref));
7151       else
7152         printf ("[%6" PRIxMAX "]\n", (uintmax_t) dwarf_dieoffset (&ref));
7153       break;
7154
7155     case DW_FORM_ref_sig8:
7156       if (cbargs->silent)
7157         break;
7158       printf ("           %*s%-20s (%s) {%6" PRIx64 "}\n",
7159               (int) (level * 2), "", dwarf_attr_name (attr),
7160               dwarf_form_name (form),
7161               (uint64_t) read_8ubyte_unaligned (attrp->cu->dbg, attrp->valp));
7162       break;
7163
7164     case DW_FORM_sec_offset:
7165     case DW_FORM_rnglistx:
7166     case DW_FORM_loclistx:
7167     case DW_FORM_implicit_const:
7168     case DW_FORM_udata:
7169     case DW_FORM_sdata:
7170     case DW_FORM_data8: /* Note no data16 here, we see that as block. */
7171     case DW_FORM_data4:
7172     case DW_FORM_data2:
7173     case DW_FORM_data1:;
7174       Dwarf_Word num;
7175       if (unlikely (dwarf_formudata (attrp, &num) != 0))
7176         goto attrval_out;
7177
7178       const char *valuestr = NULL;
7179       bool as_hex_id = false;
7180       switch (attr)
7181         {
7182           /* This case can take either a constant or a loclistptr.  */
7183         case DW_AT_data_member_location:
7184           if (form != DW_FORM_sec_offset
7185               && (cbargs->version >= 4
7186                   || (form != DW_FORM_data4 && form != DW_FORM_data8)))
7187             {
7188               if (!cbargs->silent)
7189                 printf ("           %*s%-20s (%s) %" PRIuMAX "\n",
7190                         (int) (level * 2), "", dwarf_attr_name (attr),
7191                         dwarf_form_name (form), (uintmax_t) num);
7192               return DWARF_CB_OK;
7193             }
7194           FALLTHROUGH;
7195
7196         /* These cases always take a loclist[ptr] and no constant. */
7197         case DW_AT_location:
7198         case DW_AT_data_location:
7199         case DW_AT_vtable_elem_location:
7200         case DW_AT_string_length:
7201         case DW_AT_use_location:
7202         case DW_AT_frame_base:
7203         case DW_AT_return_addr:
7204         case DW_AT_static_link:
7205         case DW_AT_segment:
7206         case DW_AT_GNU_call_site_value:
7207         case DW_AT_GNU_call_site_data_value:
7208         case DW_AT_GNU_call_site_target:
7209         case DW_AT_GNU_call_site_target_clobbered:
7210         case DW_AT_GNU_locviews:
7211           {
7212             bool nlpt;
7213             if (cbargs->cu->version < 5)
7214               {
7215                 if (! cbargs->is_split)
7216                   {
7217                     nlpt = notice_listptr (section_loc, &known_locsptr,
7218                                            cbargs->addrsize,
7219                                            cbargs->offset_size,
7220                                            cbargs->cu, num, attr);
7221                   }
7222                 else
7223                   nlpt = true;
7224               }
7225             else
7226               {
7227                 /* Only register for a real section offset.  Otherwise
7228                    it is a DW_FORM_loclistx which is just an index
7229                    number and we should already have registered the
7230                    section offset for the index when we saw the
7231                    DW_AT_loclists_base CU attribute.  */
7232                 if (form == DW_FORM_sec_offset)
7233                   nlpt = notice_listptr (section_loc, &known_loclistsptr,
7234                                          cbargs->addrsize, cbargs->offset_size,
7235                                          cbargs->cu, num, attr);
7236                 else
7237                   nlpt = true;
7238
7239               }
7240
7241             if (!cbargs->silent)
7242               {
7243                 if (cbargs->cu->version < 5 || form == DW_FORM_sec_offset)
7244                   printf ("           %*s%-20s (%s) location list [%6"
7245                           PRIxMAX "]%s\n",
7246                           (int) (level * 2), "", dwarf_attr_name (attr),
7247                           dwarf_form_name (form), (uintmax_t) num,
7248                           nlpt ? "" : " <WARNING offset too big>");
7249                 else
7250                   printf ("           %*s%-20s (%s) location index [%6"
7251                           PRIxMAX "]\n",
7252                           (int) (level * 2), "", dwarf_attr_name (attr),
7253                           dwarf_form_name (form), (uintmax_t) num);
7254               }
7255           }
7256           return DWARF_CB_OK;
7257
7258         case DW_AT_loclists_base:
7259           {
7260             bool nlpt = notice_listptr (section_loc, &known_loclistsptr,
7261                                         cbargs->addrsize, cbargs->offset_size,
7262                                         cbargs->cu, num, attr);
7263
7264             if (!cbargs->silent)
7265               printf ("           %*s%-20s (%s) location list [%6" PRIxMAX "]%s\n",
7266                       (int) (level * 2), "", dwarf_attr_name (attr),
7267                       dwarf_form_name (form), (uintmax_t) num,
7268                       nlpt ? "" : " <WARNING offset too big>");
7269           }
7270           return DWARF_CB_OK;
7271
7272         case DW_AT_ranges:
7273         case DW_AT_start_scope:
7274           {
7275             bool nlpt;
7276             if (cbargs->cu->version < 5)
7277               nlpt = notice_listptr (section_ranges, &known_rangelistptr,
7278                                      cbargs->addrsize, cbargs->offset_size,
7279                                      cbargs->cu, num, attr);
7280             else
7281               {
7282                 /* Only register for a real section offset.  Otherwise
7283                    it is a DW_FORM_rangelistx which is just an index
7284                    number and we should already have registered the
7285                    section offset for the index when we saw the
7286                    DW_AT_rnglists_base CU attribute.  */
7287                 if (form == DW_FORM_sec_offset)
7288                   nlpt = notice_listptr (section_ranges, &known_rnglistptr,
7289                                          cbargs->addrsize, cbargs->offset_size,
7290                                          cbargs->cu, num, attr);
7291                 else
7292                   nlpt = true;
7293               }
7294
7295             if (!cbargs->silent)
7296               {
7297                 if (cbargs->cu->version < 5 || form == DW_FORM_sec_offset)
7298                   printf ("           %*s%-20s (%s) range list [%6"
7299                           PRIxMAX "]%s\n",
7300                           (int) (level * 2), "", dwarf_attr_name (attr),
7301                           dwarf_form_name (form), (uintmax_t) num,
7302                           nlpt ? "" : " <WARNING offset too big>");
7303                 else
7304                   printf ("           %*s%-20s (%s) range index [%6"
7305                           PRIxMAX "]\n",
7306                           (int) (level * 2), "", dwarf_attr_name (attr),
7307                           dwarf_form_name (form), (uintmax_t) num);
7308               }
7309           }
7310           return DWARF_CB_OK;
7311
7312         case DW_AT_rnglists_base:
7313           {
7314             bool nlpt = notice_listptr (section_ranges, &known_rnglistptr,
7315                                         cbargs->addrsize, cbargs->offset_size,
7316                                         cbargs->cu, num, attr);
7317             if (!cbargs->silent)
7318               printf ("           %*s%-20s (%s) range list [%6"
7319                       PRIxMAX "]%s\n",
7320                       (int) (level * 2), "", dwarf_attr_name (attr),
7321                       dwarf_form_name (form), (uintmax_t) num,
7322                       nlpt ? "" : " <WARNING offset too big>");
7323           }
7324           return DWARF_CB_OK;
7325
7326         case DW_AT_addr_base:
7327         case DW_AT_GNU_addr_base:
7328           {
7329             bool addrbase = notice_listptr (section_addr, &known_addrbases,
7330                                             cbargs->addrsize,
7331                                             cbargs->offset_size,
7332                                             cbargs->cu, num, attr);
7333             if (!cbargs->silent)
7334               printf ("           %*s%-20s (%s) address base [%6"
7335                       PRIxMAX "]%s\n",
7336                       (int) (level * 2), "", dwarf_attr_name (attr),
7337                       dwarf_form_name (form), (uintmax_t) num,
7338                       addrbase ? "" : " <WARNING offset too big>");
7339           }
7340           return DWARF_CB_OK;
7341
7342         case DW_AT_str_offsets_base:
7343           {
7344             bool stroffbase = notice_listptr (section_str, &known_stroffbases,
7345                                               cbargs->addrsize,
7346                                               cbargs->offset_size,
7347                                               cbargs->cu, num, attr);
7348             if (!cbargs->silent)
7349               printf ("           %*s%-20s (%s) str offsets base [%6"
7350                       PRIxMAX "]%s\n",
7351                       (int) (level * 2), "", dwarf_attr_name (attr),
7352                       dwarf_form_name (form), (uintmax_t) num,
7353                       stroffbase ? "" : " <WARNING offset too big>");
7354           }
7355           return DWARF_CB_OK;
7356
7357         case DW_AT_language:
7358           valuestr = dwarf_lang_name (num);
7359           break;
7360         case DW_AT_encoding:
7361           valuestr = dwarf_encoding_name (num);
7362           break;
7363         case DW_AT_accessibility:
7364           valuestr = dwarf_access_name (num);
7365           break;
7366         case DW_AT_defaulted:
7367           valuestr = dwarf_defaulted_name (num);
7368           break;
7369         case DW_AT_visibility:
7370           valuestr = dwarf_visibility_name (num);
7371           break;
7372         case DW_AT_virtuality:
7373           valuestr = dwarf_virtuality_name (num);
7374           break;
7375         case DW_AT_identifier_case:
7376           valuestr = dwarf_identifier_case_name (num);
7377           break;
7378         case DW_AT_calling_convention:
7379           valuestr = dwarf_calling_convention_name (num);
7380           break;
7381         case DW_AT_inline:
7382           valuestr = dwarf_inline_name (num);
7383           break;
7384         case DW_AT_ordering:
7385           valuestr = dwarf_ordering_name (num);
7386           break;
7387         case DW_AT_decl_file:
7388         case DW_AT_call_file:
7389           {
7390             if (cbargs->silent)
7391               break;
7392
7393             /* Try to get the actual file, the current interface only
7394                gives us full paths, but we only want to show the file
7395                name for now.  */
7396             Dwarf_Die cudie;
7397             if (dwarf_cu_die (cbargs->cu, &cudie,
7398                               NULL, NULL, NULL, NULL, NULL, NULL) != NULL)
7399               {
7400                 Dwarf_Files *files;
7401                 size_t nfiles;
7402                 if (dwarf_getsrcfiles (&cudie, &files, &nfiles) == 0)
7403                   {
7404                     valuestr = dwarf_filesrc (files, num, NULL, NULL);
7405                     if (valuestr != NULL)
7406                       {
7407                         char *filename = strrchr (valuestr, '/');
7408                         if (filename != NULL)
7409                           valuestr = filename + 1;
7410                       }
7411                     else
7412                       error (0, 0, _("invalid file (%" PRId64 "): %s"),
7413                              num, dwarf_errmsg (-1));
7414                   }
7415                 else
7416                   error (0, 0, _("no srcfiles for CU [%" PRIx64 "]"),
7417                          dwarf_dieoffset (&cudie));
7418               }
7419             else
7420              error (0, 0, _("couldn't get DWARF CU: %s"),
7421                     dwarf_errmsg (-1));
7422             if (valuestr == NULL)
7423               valuestr = "???";
7424           }
7425           break;
7426         case DW_AT_GNU_dwo_id:
7427           as_hex_id = true;
7428           break;
7429
7430         default:
7431           /* Nothing.  */
7432           break;
7433         }
7434
7435       if (cbargs->silent)
7436         break;
7437
7438       /* When highpc is in constant form it is relative to lowpc.
7439          In that case also show the address.  */
7440       Dwarf_Addr highpc;
7441       if (attr == DW_AT_high_pc && dwarf_highpc (die, &highpc) == 0)
7442         {
7443           printf ("           %*s%-20s (%s) %" PRIuMAX " (",
7444                   (int) (level * 2), "", dwarf_attr_name (attr),
7445                   dwarf_form_name (form), (uintmax_t) num);
7446           print_dwarf_addr (cbargs->dwflmod, cbargs->addrsize, highpc, highpc);
7447           printf (")\n");
7448         }
7449       else
7450         {
7451           if (as_hex_id)
7452             {
7453               printf ("           %*s%-20s (%s) 0x%.16" PRIx64 "\n",
7454                       (int) (level * 2), "", dwarf_attr_name (attr),
7455                       dwarf_form_name (form), num);
7456             }
7457           else
7458             {
7459               Dwarf_Sword snum = 0;
7460               bool is_signed;
7461               int bytes = 0;
7462               if (attr == DW_AT_const_value)
7463                 die_type_sign_bytes (die, &is_signed, &bytes);
7464               else
7465                 is_signed = (form == DW_FORM_sdata
7466                              || form == DW_FORM_implicit_const);
7467
7468               if (is_signed)
7469                 if (unlikely (dwarf_formsdata (attrp, &snum) != 0))
7470                   goto attrval_out;
7471
7472               if (valuestr == NULL)
7473                 {
7474                   printf ("           %*s%-20s (%s) ",
7475                           (int) (level * 2), "", dwarf_attr_name (attr),
7476                           dwarf_form_name (form));
7477                 }
7478               else
7479                 {
7480                   printf ("           %*s%-20s (%s) %s (",
7481                           (int) (level * 2), "", dwarf_attr_name (attr),
7482                           dwarf_form_name (form), valuestr);
7483                 }
7484
7485               switch (bytes)
7486                 {
7487                 case 1:
7488                   if (is_signed)
7489                     printf ("%" PRId8, (int8_t) snum);
7490                   else
7491                     printf ("%" PRIu8, (uint8_t) num);
7492                   break;
7493
7494                 case 2:
7495                   if (is_signed)
7496                     printf ("%" PRId16, (int16_t) snum);
7497                   else
7498                     printf ("%" PRIu16, (uint16_t) num);
7499                   break;
7500
7501                 case 4:
7502                   if (is_signed)
7503                     printf ("%" PRId32, (int32_t) snum);
7504                   else
7505                     printf ("%" PRIu32, (uint32_t) num);
7506                   break;
7507
7508                 case 8:
7509                   if (is_signed)
7510                     printf ("%" PRId64, (int64_t) snum);
7511                   else
7512                     printf ("%" PRIu64, (uint64_t) num);
7513                   break;
7514
7515                 default:
7516                   if (is_signed)
7517                     printf ("%" PRIdMAX, (intmax_t) snum);
7518                   else
7519                     printf ("%" PRIuMAX, (uintmax_t) num);
7520                   break;
7521                 }
7522
7523               /* Make clear if we switched from a signed encoding to
7524                  an unsigned value.  */
7525               if (attr == DW_AT_const_value
7526                   && (form == DW_FORM_sdata || form == DW_FORM_implicit_const)
7527                   && !is_signed)
7528                 printf (" (%" PRIdMAX ")", (intmax_t) num);
7529
7530               if (valuestr == NULL)
7531                 printf ("\n");
7532               else
7533                 printf (")\n");
7534             }
7535         }
7536       break;
7537
7538     case DW_FORM_flag:
7539       if (cbargs->silent)
7540         break;
7541       bool flag;
7542       if (unlikely (dwarf_formflag (attrp, &flag) != 0))
7543         goto attrval_out;
7544
7545       printf ("           %*s%-20s (%s) %s\n",
7546               (int) (level * 2), "", dwarf_attr_name (attr),
7547               dwarf_form_name (form), flag ? yes_str : no_str);
7548       break;
7549
7550     case DW_FORM_flag_present:
7551       if (cbargs->silent)
7552         break;
7553       printf ("           %*s%-20s (%s) %s\n",
7554               (int) (level * 2), "", dwarf_attr_name (attr),
7555               dwarf_form_name (form), yes_str);
7556       break;
7557
7558     case DW_FORM_exprloc:
7559     case DW_FORM_block4:
7560     case DW_FORM_block2:
7561     case DW_FORM_block1:
7562     case DW_FORM_block:
7563     case DW_FORM_data16: /* DWARF5 calls this a constant class.  */
7564       if (cbargs->silent)
7565         break;
7566       Dwarf_Block block;
7567       if (unlikely (dwarf_formblock (attrp, &block) != 0))
7568         goto attrval_out;
7569
7570       printf ("           %*s%-20s (%s) ",
7571               (int) (level * 2), "", dwarf_attr_name (attr),
7572               dwarf_form_name (form));
7573
7574       switch (attr)
7575         {
7576         default:
7577           if (form != DW_FORM_exprloc)
7578             {
7579               print_block (block.length, block.data);
7580               break;
7581             }
7582           FALLTHROUGH;
7583
7584         case DW_AT_location:
7585         case DW_AT_data_location:
7586         case DW_AT_data_member_location:
7587         case DW_AT_vtable_elem_location:
7588         case DW_AT_string_length:
7589         case DW_AT_use_location:
7590         case DW_AT_frame_base:
7591         case DW_AT_return_addr:
7592         case DW_AT_static_link:
7593         case DW_AT_allocated:
7594         case DW_AT_associated:
7595         case DW_AT_bit_size:
7596         case DW_AT_bit_offset:
7597         case DW_AT_bit_stride:
7598         case DW_AT_byte_size:
7599         case DW_AT_byte_stride:
7600         case DW_AT_count:
7601         case DW_AT_lower_bound:
7602         case DW_AT_upper_bound:
7603         case DW_AT_GNU_call_site_value:
7604         case DW_AT_GNU_call_site_data_value:
7605         case DW_AT_GNU_call_site_target:
7606         case DW_AT_GNU_call_site_target_clobbered:
7607           if (form == DW_FORM_exprloc
7608               || (form != DW_FORM_data16
7609                   && attrp->cu->version < 4)) /* blocks were expressions.  */
7610             {
7611               putchar ('\n');
7612               print_ops (cbargs->dwflmod, cbargs->dbg,
7613                          12 + level * 2, 12 + level * 2,
7614                          cbargs->version, cbargs->addrsize, cbargs->offset_size,
7615                          attrp->cu, block.length, block.data);
7616             }
7617           else
7618             print_block (block.length, block.data);
7619           break;
7620
7621         case DW_AT_discr_list:
7622           if (block.length == 0)
7623             puts ("<default>");
7624           else if (form != DW_FORM_data16)
7625             {
7626               const unsigned char *readp = block.data;
7627               const unsigned char *readendp = readp + block.length;
7628
7629               /* See if we are dealing with a signed or unsigned
7630                  values.  If the parent of this variant DIE is a
7631                  variant_part then it will either have a discriminant
7632                  which points to the member which type is the
7633                  discriminant type.  Or the variant_part itself has a
7634                  type representing the discriminant.  */
7635               bool is_signed = false;
7636               if (level > 0)
7637                 {
7638                   Dwarf_Die *parent = &cbargs->dies[level - 1];
7639                   if (dwarf_tag (die) == DW_TAG_variant
7640                       && dwarf_tag (parent) == DW_TAG_variant_part)
7641                     {
7642                       Dwarf_Die member;
7643                       Dwarf_Attribute discr_attr;
7644                       int bytes;
7645                       if (dwarf_formref_die (dwarf_attr (parent,
7646                                                          DW_AT_discr,
7647                                                          &discr_attr),
7648                                              &member) != NULL)
7649                         die_type_sign_bytes (&member, &is_signed, &bytes);
7650                       else
7651                         die_type_sign_bytes (parent, &is_signed, &bytes);
7652                     }
7653                 }
7654               while (readp < readendp)
7655                 {
7656                   int d = (int) *readp++;
7657                   printf ("%s ", dwarf_discr_list_name (d));
7658                   if (readp >= readendp)
7659                     goto attrval_out;
7660
7661                   Dwarf_Word val;
7662                   Dwarf_Sword sval;
7663                   if (d == DW_DSC_label)
7664                     {
7665                       if (is_signed)
7666                         {
7667                           get_sleb128 (sval, readp, readendp);
7668                           printf ("%" PRId64 "", sval);
7669                         }
7670                       else
7671                         {
7672                           get_uleb128 (val, readp, readendp);
7673                           printf ("%" PRIu64 "", val);
7674                         }
7675                     }
7676                   else if (d == DW_DSC_range)
7677                     {
7678                       if (is_signed)
7679                         {
7680                           get_sleb128 (sval, readp, readendp);
7681                           printf ("%" PRId64 "..", sval);
7682                           if (readp >= readendp)
7683                             goto attrval_out;
7684                           get_sleb128 (sval, readp, readendp);
7685                           printf ("%" PRId64 "", sval);
7686                         }
7687                       else
7688                         {
7689                           get_uleb128 (val, readp, readendp);
7690                           printf ("%" PRIu64 "..", val);
7691                           if (readp >= readendp)
7692                             goto attrval_out;
7693                           get_uleb128 (val, readp, readendp);
7694                           printf ("%" PRIu64 "", val);
7695                         }
7696                     }
7697                   else
7698                     {
7699                       print_block (readendp - readp, readp);
7700                       break;
7701                     }
7702                   if (readp < readendp)
7703                     printf (", ");
7704                 }
7705               putchar ('\n');
7706             }
7707           else
7708             print_block (block.length, block.data);
7709           break;
7710         }
7711       break;
7712
7713     default:
7714       if (cbargs->silent)
7715         break;
7716       printf ("           %*s%-20s (%s) ???\n",
7717               (int) (level * 2), "", dwarf_attr_name (attr),
7718               dwarf_form_name (form));
7719       break;
7720     }
7721
7722   return DWARF_CB_OK;
7723 }
7724
7725 static void
7726 print_debug_units (Dwfl_Module *dwflmod,
7727                    Ebl *ebl, GElf_Ehdr *ehdr __attribute__ ((unused)),
7728                    Elf_Scn *scn, GElf_Shdr *shdr,
7729                    Dwarf *dbg, bool debug_types)
7730 {
7731   const bool silent = !(print_debug_sections & section_info) && !debug_types;
7732   const char *secname = section_name (ebl, shdr);
7733
7734   if (!silent)
7735     printf (_("\
7736 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n [Offset]\n"),
7737             elf_ndxscn (scn), secname, (uint64_t) shdr->sh_offset);
7738
7739   /* If the section is empty we don't have to do anything.  */
7740   if (!silent && shdr->sh_size == 0)
7741     return;
7742
7743   int maxdies = 20;
7744   Dwarf_Die *dies = xmalloc (maxdies * sizeof (Dwarf_Die));
7745
7746   /* New compilation unit.  */
7747   Dwarf_Half version;
7748
7749   Dwarf_Die result;
7750   Dwarf_Off abbroffset;
7751   uint8_t addrsize;
7752   uint8_t offsize;
7753   uint64_t unit_id;
7754   Dwarf_Off subdie_off;
7755
7756   int unit_res;
7757   Dwarf_CU *cu;
7758   Dwarf_CU cu_mem;
7759   uint8_t unit_type;
7760   Dwarf_Die cudie;
7761
7762   /* We cheat a little because we want to see only the CUs from .debug_info
7763      or .debug_types.  We know the Dwarf_CU struct layout.  Set it up at
7764      the end of .debug_info if we want .debug_types only.  Check the returned
7765      Dwarf_CU is still in the expected section.  */
7766   if (debug_types)
7767     {
7768       cu_mem.dbg = dbg;
7769       cu_mem.end = dbg->sectiondata[IDX_debug_info]->d_size;
7770       cu_mem.sec_idx = IDX_debug_info;
7771       cu = &cu_mem;
7772     }
7773   else
7774     cu = NULL;
7775
7776  next_cu:
7777   unit_res = dwarf_get_units (dbg, cu, &cu, &version, &unit_type,
7778                               &cudie, NULL);
7779   if (unit_res == 1)
7780     goto do_return;
7781
7782   if (unit_res == -1)
7783     {
7784       if (!silent)
7785         error (0, 0, _("cannot get next unit: %s"), dwarf_errmsg (-1));
7786       goto do_return;
7787     }
7788
7789   if (cu->sec_idx != (size_t) (debug_types ? IDX_debug_types : IDX_debug_info))
7790     goto do_return;
7791
7792   dwarf_cu_die (cu, &result, NULL, &abbroffset, &addrsize, &offsize,
7793                 &unit_id, &subdie_off);
7794
7795   if (!silent)
7796     {
7797       Dwarf_Off offset = cu->start;
7798       if (debug_types && version < 5)
7799         {
7800           Dwarf_Die typedie;
7801           Dwarf_Off dieoffset;
7802           dieoffset = dwarf_dieoffset (dwarf_offdie_types (dbg, cu->start
7803                                                            + subdie_off,
7804                                                            &typedie));
7805           printf (_(" Type unit at offset %" PRIu64 ":\n"
7806                            " Version: %" PRIu16
7807                            ", Abbreviation section offset: %" PRIu64
7808                            ", Address size: %" PRIu8
7809                            ", Offset size: %" PRIu8
7810                            "\n Type signature: %#" PRIx64
7811                            ", Type offset: %#" PRIx64 " [%" PRIx64 "]\n"),
7812                   (uint64_t) offset, version, abbroffset, addrsize, offsize,
7813                   unit_id, (uint64_t) subdie_off, dieoffset);
7814         }
7815       else
7816         {
7817           printf (_(" Compilation unit at offset %" PRIu64 ":\n"
7818                            " Version: %" PRIu16
7819                            ", Abbreviation section offset: %" PRIu64
7820                            ", Address size: %" PRIu8
7821                            ", Offset size: %" PRIu8 "\n"),
7822                   (uint64_t) offset, version, abbroffset, addrsize, offsize);
7823
7824           if (version >= 5 || (unit_type != DW_UT_compile
7825                                && unit_type != DW_UT_partial))
7826             {
7827               printf (_(" Unit type: %s (%" PRIu8 ")"),
7828                                dwarf_unit_name (unit_type), unit_type);
7829               if (unit_type == DW_UT_type
7830                   || unit_type == DW_UT_skeleton
7831                   || unit_type == DW_UT_split_compile
7832                   || unit_type == DW_UT_split_type)
7833                 printf (", Unit id: 0x%.16" PRIx64 "", unit_id);
7834               if (unit_type == DW_UT_type
7835                   || unit_type == DW_UT_split_type)
7836                 {
7837                   Dwarf_Die typedie;
7838                   Dwarf_Off dieoffset;
7839                   dwarf_cu_info (cu, NULL, NULL, NULL, &typedie,
7840                                  NULL, NULL, NULL);
7841                   dieoffset = dwarf_dieoffset (&typedie);
7842                   printf (", Unit DIE off: %#" PRIx64 " [%" PRIx64 "]",
7843                           subdie_off, dieoffset);
7844                 }
7845               printf ("\n");
7846             }
7847         }
7848     }
7849
7850   if (version < 2 || version > 5
7851       || unit_type < DW_UT_compile || unit_type > DW_UT_split_type)
7852     {
7853       if (!silent)
7854         error (0, 0, _("unknown version (%d) or unit type (%d)"),
7855                version, unit_type);
7856       goto next_cu;
7857     }
7858
7859   struct attrcb_args args =
7860     {
7861       .dwflmod = dwflmod,
7862       .silent = silent,
7863       .version = version,
7864       .addrsize = addrsize,
7865       .offset_size = offsize
7866     };
7867
7868   bool is_split = false;
7869   int level = 0;
7870   dies[0] = cudie;
7871   args.cu = dies[0].cu;
7872   args.dbg = dbg;
7873   args.is_split = is_split;
7874
7875   /* We might return here again for the split CU subdie.  */
7876   do_cu:
7877   do
7878     {
7879       Dwarf_Off offset = dwarf_dieoffset (&dies[level]);
7880       if (unlikely (offset == (Dwarf_Off) -1))
7881         {
7882           if (!silent)
7883             error (0, 0, _("cannot get DIE offset: %s"),
7884                    dwarf_errmsg (-1));
7885           goto do_return;
7886         }
7887
7888       int tag = dwarf_tag (&dies[level]);
7889       if (unlikely (tag == DW_TAG_invalid))
7890         {
7891           if (!silent)
7892             error (0, 0, _("cannot get tag of DIE at offset [%" PRIx64
7893                                   "] in section '%s': %s"),
7894                    (uint64_t) offset, secname, dwarf_errmsg (-1));
7895           goto do_return;
7896         }
7897
7898       if (!silent)
7899         {
7900           unsigned int code = dwarf_getabbrevcode (dies[level].abbrev);
7901           if (is_split)
7902             printf (" {%6" PRIx64 "}  ", (uint64_t) offset);
7903           else
7904             printf (" [%6" PRIx64 "]  ", (uint64_t) offset);
7905           printf ("%*s%-20s abbrev: %u\n", (int) (level * 2), "",
7906                   dwarf_tag_name (tag), code);
7907         }
7908
7909       /* Print the attribute values.  */
7910       args.level = level;
7911       args.dies = dies;
7912       (void) dwarf_getattrs (&dies[level], attr_callback, &args, 0);
7913
7914       /* Make room for the next level's DIE.  */
7915       if (level + 1 == maxdies)
7916         dies = xrealloc (dies, (maxdies += 10) * sizeof (Dwarf_Die));
7917
7918       int res = dwarf_child (&dies[level], &dies[level + 1]);
7919       if (res > 0)
7920         {
7921           while ((res = dwarf_siblingof (&dies[level], &dies[level])) == 1)
7922             if (level-- == 0)
7923               break;
7924
7925           if (unlikely (res == -1))
7926             {
7927               if (!silent)
7928                 error (0, 0, _("cannot get next DIE: %s\n"),
7929                        dwarf_errmsg (-1));
7930               goto do_return;
7931             }
7932         }
7933       else if (unlikely (res < 0))
7934         {
7935           if (!silent)
7936             error (0, 0, _("cannot get next DIE: %s"),
7937                    dwarf_errmsg (-1));
7938           goto do_return;
7939         }
7940       else
7941         ++level;
7942     }
7943   while (level >= 0);
7944
7945   /* We might want to show the split compile unit if this was a skeleton.
7946      We need to scan it if we are requesting printing .debug_ranges for
7947      DWARF4 since GNU DebugFission uses "offsets" into the main ranges
7948      section.  */
7949   if (unit_type == DW_UT_skeleton
7950       && ((!silent && show_split_units)
7951           || (version < 5 && (print_debug_sections & section_ranges) != 0)))
7952     {
7953       Dwarf_Die subdie;
7954       if (dwarf_cu_info (cu, NULL, NULL, NULL, &subdie, NULL, NULL, NULL) != 0
7955           || dwarf_tag (&subdie) == DW_TAG_invalid)
7956         {
7957           if (!silent)
7958             {
7959               Dwarf_Attribute dwo_at;
7960               const char *dwo_name =
7961                 (dwarf_formstring (dwarf_attr (&cudie, DW_AT_dwo_name,
7962                                                &dwo_at))
7963                  ?: (dwarf_formstring (dwarf_attr (&cudie, DW_AT_GNU_dwo_name,
7964                                                    &dwo_at))
7965                      ?: "<unknown>"));
7966               fprintf (stderr,
7967                        "Could not find split unit '%s', id: %" PRIx64 "\n",
7968                        dwo_name, unit_id);
7969             }
7970         }
7971       else
7972         {
7973           Dwarf_CU *split_cu = subdie.cu;
7974           dwarf_cu_die (split_cu, &result, NULL, &abbroffset,
7975                         &addrsize, &offsize, &unit_id, &subdie_off);
7976           Dwarf_Off offset = cu->start;
7977
7978           if (!silent)
7979             {
7980               printf (_(" Split compilation unit at offset %"
7981                                PRIu64 ":\n"
7982                                " Version: %" PRIu16
7983                                ", Abbreviation section offset: %" PRIu64
7984                                ", Address size: %" PRIu8
7985                                ", Offset size: %" PRIu8 "\n"),
7986                       (uint64_t) offset, version, abbroffset,
7987                       addrsize, offsize);
7988               printf (_(" Unit type: %s (%" PRIu8 ")"),
7989                       dwarf_unit_name (unit_type), unit_type);
7990               printf (", Unit id: 0x%.16" PRIx64 "", unit_id);
7991               printf ("\n");
7992             }
7993
7994           unit_type = DW_UT_split_compile;
7995           is_split = true;
7996           level = 0;
7997           dies[0] = subdie;
7998           args.cu = dies[0].cu;
7999           args.dbg = split_cu->dbg;
8000           args.is_split = is_split;
8001           goto do_cu;
8002         }
8003     }
8004
8005   /* And again... */
8006   goto next_cu;
8007
8008  do_return:
8009   free (dies);
8010 }
8011
8012 static void
8013 print_debug_info_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
8014                           Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
8015 {
8016   print_debug_units (dwflmod, ebl, ehdr, scn, shdr, dbg, false);
8017 }
8018
8019 static void
8020 print_debug_types_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
8021                            Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
8022 {
8023   print_debug_units (dwflmod, ebl, ehdr, scn, shdr, dbg, true);
8024 }
8025
8026
8027 static void
8028 print_decoded_line_section (Dwfl_Module *dwflmod, Ebl *ebl,
8029                             GElf_Ehdr *ehdr __attribute__ ((unused)),
8030                             Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
8031 {
8032   printf (_("\
8033 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n\n"),
8034           elf_ndxscn (scn), section_name (ebl, shdr),
8035           (uint64_t) shdr->sh_offset);
8036
8037   size_t address_size
8038     = elf_getident (ebl->elf, NULL)[EI_CLASS] == ELFCLASS32 ? 4 : 8;
8039
8040   Dwarf_Lines *lines;
8041   size_t nlines;
8042   Dwarf_Off off, next_off = 0;
8043   Dwarf_CU *cu = NULL;
8044   while (dwarf_next_lines (dbg, off = next_off, &next_off, &cu, NULL, NULL,
8045                            &lines, &nlines) == 0)
8046     {
8047       Dwarf_Die cudie;
8048       if (cu != NULL && dwarf_cu_info (cu, NULL, NULL, &cudie,
8049                                        NULL, NULL, NULL, NULL) == 0)
8050         printf (" CU [%" PRIx64 "] %s\n",
8051                 dwarf_dieoffset (&cudie), dwarf_diename (&cudie));
8052       else
8053         {
8054           /* DWARF5 lines can be independent of any CU, but they probably
8055              are used by some CU.  Determine the CU this block is for.  */
8056           Dwarf_Off cuoffset;
8057           Dwarf_Off ncuoffset = 0;
8058           size_t hsize;
8059           while (dwarf_nextcu (dbg, cuoffset = ncuoffset, &ncuoffset, &hsize,
8060                                NULL, NULL, NULL) == 0)
8061             {
8062               if (dwarf_offdie (dbg, cuoffset + hsize, &cudie) == NULL)
8063                 continue;
8064               Dwarf_Attribute stmt_list;
8065               if (dwarf_attr (&cudie, DW_AT_stmt_list, &stmt_list) == NULL)
8066                 continue;
8067               Dwarf_Word lineoff;
8068               if (dwarf_formudata (&stmt_list, &lineoff) != 0)
8069                 continue;
8070               if (lineoff == off)
8071                 {
8072                   /* Found the CU.  */
8073                   cu = cudie.cu;
8074                   break;
8075                 }
8076             }
8077
8078           if (cu != NULL)
8079             printf (" CU [%" PRIx64 "] %s\n",
8080                     dwarf_dieoffset (&cudie), dwarf_diename (&cudie));
8081           else
8082             printf (" No CU\n");
8083         }
8084
8085       printf ("  line:col SBPE* disc isa op address"
8086               " (Statement Block Prologue Epilogue *End)\n");
8087       const char *last_file = "";
8088       for (size_t n = 0; n < nlines; n++)
8089         {
8090           Dwarf_Line *line = dwarf_onesrcline (lines, n);
8091           if (line == NULL)
8092             {
8093               printf ("  dwarf_onesrcline: %s\n", dwarf_errmsg (-1));
8094               continue;
8095             }
8096           Dwarf_Word mtime, length;
8097           const char *file = dwarf_linesrc (line, &mtime, &length);
8098           if (file == NULL)
8099             {
8100               printf ("  <%s> (mtime: ?, length: ?)\n", dwarf_errmsg (-1));
8101               last_file = "";
8102             }
8103           else if (strcmp (last_file, file) != 0)
8104             {
8105               printf ("  %s (mtime: %" PRIu64 ", length: %" PRIu64 ")\n",
8106                       file, mtime, length);
8107               last_file = file;
8108             }
8109
8110           int lineno, colno;
8111           bool statement, endseq, block, prologue_end, epilogue_begin;
8112           unsigned int lineop, isa, disc;
8113           Dwarf_Addr address;
8114           dwarf_lineaddr (line, &address);
8115           dwarf_lineno (line, &lineno);
8116           dwarf_linecol (line, &colno);
8117           dwarf_lineop_index (line, &lineop);
8118           dwarf_linebeginstatement (line, &statement);
8119           dwarf_lineendsequence (line, &endseq);
8120           dwarf_lineblock (line, &block);
8121           dwarf_lineprologueend (line, &prologue_end);
8122           dwarf_lineepiloguebegin (line, &epilogue_begin);
8123           dwarf_lineisa (line, &isa);
8124           dwarf_linediscriminator (line, &disc);
8125
8126           /* End sequence is special, it is one byte past.  */
8127           printf ("  %4d:%-3d %c%c%c%c%c %4d %3d %2d ",
8128                   lineno, colno,
8129                   (statement ? 'S' : ' '),
8130                   (block ? 'B' : ' '),
8131                   (prologue_end ? 'P' : ' '),
8132                   (epilogue_begin ? 'E' : ' '),
8133                   (endseq ? '*' : ' '),
8134                   disc, isa, lineop);
8135           print_dwarf_addr (dwflmod, address_size,
8136                             address - (endseq ? 1 : 0), address);
8137           printf ("\n");
8138
8139           if (endseq)
8140             printf("\n");
8141         }
8142     }
8143 }
8144
8145
8146 /* Print the value of a form.
8147    Returns new value of readp, or readendp on failure.  */
8148 static const unsigned char *
8149 print_form_data (Dwarf *dbg, int form, const unsigned char *readp,
8150                  const unsigned char *readendp, unsigned int offset_len,
8151                  Dwarf_Off str_offsets_base)
8152 {
8153   Dwarf_Word val;
8154   unsigned char *endp;
8155   Elf_Data *data;
8156   char *str;
8157   switch (form)
8158     {
8159     case DW_FORM_data1:
8160       if (readendp - readp < 1)
8161         {
8162         invalid_data:
8163           error (0, 0, "invalid data");
8164           return readendp;
8165         }
8166       val = *readp++;
8167       printf (" %" PRIx8, (unsigned int) val);
8168       break;
8169
8170     case DW_FORM_data2:
8171       if (readendp - readp < 2)
8172         goto invalid_data;
8173       val = read_2ubyte_unaligned_inc (dbg, readp);
8174       printf(" %" PRIx16, (unsigned int) val);
8175       break;
8176
8177     case DW_FORM_data4:
8178       if (readendp - readp < 4)
8179         goto invalid_data;
8180       val = read_4ubyte_unaligned_inc (dbg, readp);
8181       printf (" %" PRIx32, (unsigned int) val);
8182       break;
8183
8184     case DW_FORM_data8:
8185       if (readendp - readp < 8)
8186         goto invalid_data;
8187       val = read_8ubyte_unaligned_inc (dbg, readp);
8188       printf (" %" PRIx64, val);
8189       break;
8190
8191     case DW_FORM_sdata:
8192       if (readendp - readp < 1)
8193         goto invalid_data;
8194       get_sleb128 (val, readp, readendp);
8195       printf (" %" PRIx64, val);
8196       break;
8197
8198     case DW_FORM_udata:
8199       if (readendp - readp < 1)
8200         goto invalid_data;
8201       get_uleb128 (val, readp, readendp);
8202       printf (" %" PRIx64, val);
8203       break;
8204
8205     case DW_FORM_block:
8206       if (readendp - readp < 1)
8207         goto invalid_data;
8208       get_uleb128 (val, readp, readendp);
8209       if ((size_t) (readendp - readp) < val)
8210         goto invalid_data;
8211       print_bytes (val, readp);
8212       readp += val;
8213       break;
8214
8215     case DW_FORM_block1:
8216       if (readendp - readp < 1)
8217         goto invalid_data;
8218       val = *readp++;
8219       if ((size_t) (readendp - readp) < val)
8220         goto invalid_data;
8221       print_bytes (val, readp);
8222       readp += val;
8223       break;
8224
8225     case DW_FORM_block2:
8226       if (readendp - readp < 2)
8227         goto invalid_data;
8228       val = read_2ubyte_unaligned_inc (dbg, readp);
8229       if ((size_t) (readendp - readp) < val)
8230         goto invalid_data;
8231       print_bytes (val, readp);
8232       readp += val;
8233       break;
8234
8235     case DW_FORM_block4:
8236       if (readendp - readp < 4)
8237         goto invalid_data;
8238       val = read_4ubyte_unaligned_inc (dbg, readp);
8239       if ((size_t) (readendp - readp) < val)
8240         goto invalid_data;
8241       print_bytes (val, readp);
8242       readp += val;
8243       break;
8244
8245     case DW_FORM_data16:
8246       if (readendp - readp < 16)
8247         goto invalid_data;
8248       print_bytes (16, readp);
8249       readp += 16;
8250       break;
8251
8252     case DW_FORM_flag:
8253       if (readendp - readp < 1)
8254         goto invalid_data;
8255       val = *readp++;
8256       printf ("%s", val != 0 ? yes_str : no_str);
8257       break;
8258
8259     case DW_FORM_string:
8260       endp = memchr (readp, '\0', readendp - readp);
8261       if (endp == NULL)
8262         goto invalid_data;
8263       printf ("%s", readp);
8264       readp = endp + 1;
8265       break;
8266
8267     case DW_FORM_strp:
8268     case DW_FORM_line_strp:
8269     case DW_FORM_strp_sup:
8270       if ((size_t) (readendp - readp) < offset_len)
8271         goto invalid_data;
8272       if (offset_len == 8)
8273         val = read_8ubyte_unaligned_inc (dbg, readp);
8274       else
8275         val = read_4ubyte_unaligned_inc (dbg, readp);
8276       if (form == DW_FORM_strp)
8277         data = dbg->sectiondata[IDX_debug_str];
8278       else if (form == DW_FORM_line_strp)
8279         data = dbg->sectiondata[IDX_debug_line_str];
8280       else /* form == DW_FORM_strp_sup */
8281         {
8282           Dwarf *alt = dwarf_getalt (dbg);
8283           data = alt != NULL ? alt->sectiondata[IDX_debug_str] : NULL;
8284         }
8285       if (data == NULL || val >= data->d_size
8286           || memchr (data->d_buf + val, '\0', data->d_size - val) == NULL)
8287         str = "???";
8288       else
8289         str = (char *) data->d_buf + val;
8290       printf ("%s (%" PRIu64 ")", str, val);
8291       break;
8292
8293     case DW_FORM_sec_offset:
8294       if ((size_t) (readendp - readp) < offset_len)
8295         goto invalid_data;
8296       if (offset_len == 8)
8297         val = read_8ubyte_unaligned_inc (dbg, readp);
8298       else
8299         val = read_4ubyte_unaligned_inc (dbg, readp);
8300       printf ("[%" PRIx64 "]", val);
8301       break;
8302
8303     case DW_FORM_strx:
8304     case DW_FORM_GNU_str_index:
8305       if (readendp - readp < 1)
8306         goto invalid_data;
8307       get_uleb128 (val, readp, readendp);
8308     strx_val:
8309       data = dbg->sectiondata[IDX_debug_str_offsets];
8310       if (data == NULL
8311           || data->d_size - str_offsets_base < val)
8312         str = "???";
8313       else
8314         {
8315           const unsigned char *strreadp = data->d_buf + str_offsets_base + val;
8316           const unsigned char *strreadendp = data->d_buf + data->d_size;
8317           if ((size_t) (strreadendp - strreadp) < offset_len)
8318             str = "???";
8319           else
8320             {
8321               Dwarf_Off idx;
8322               if (offset_len == 8)
8323                 idx = read_8ubyte_unaligned (dbg, strreadp);
8324               else
8325                 idx = read_4ubyte_unaligned (dbg, strreadp);
8326
8327               data = dbg->sectiondata[IDX_debug_str];
8328               if (data == NULL || idx >= data->d_size
8329                   || memchr (data->d_buf + idx, '\0',
8330                              data->d_size - idx) == NULL)
8331                 str = "???";
8332               else
8333                 str = (char *) data->d_buf + idx;
8334             }
8335         }
8336       printf ("%s (%" PRIu64 ")", str, val);
8337       break;
8338
8339     case DW_FORM_strx1:
8340       if (readendp - readp < 1)
8341         goto invalid_data;
8342       val = *readp++;
8343       goto strx_val;
8344
8345     case DW_FORM_strx2:
8346       if (readendp - readp < 2)
8347         goto invalid_data;
8348       val = read_2ubyte_unaligned_inc (dbg, readp);
8349       goto strx_val;
8350
8351     case DW_FORM_strx3:
8352       if (readendp - readp < 3)
8353         goto invalid_data;
8354       val = read_3ubyte_unaligned_inc (dbg, readp);
8355       goto strx_val;
8356
8357     case DW_FORM_strx4:
8358       if (readendp - readp < 4)
8359         goto invalid_data;
8360       val = read_4ubyte_unaligned_inc (dbg, readp);
8361       goto strx_val;
8362
8363     default:
8364       error (0, 0, _("unknown form: %s"), dwarf_form_name (form));
8365       return readendp;
8366     }
8367
8368   return readp;
8369 }
8370
8371 /* Only used via run_advance_pc() macro */
8372 static inline void
8373 run_advance_pc (unsigned int op_advance,
8374                 unsigned int minimum_instr_len,
8375                 unsigned int max_ops_per_instr,
8376                 unsigned int *op_addr_advance,
8377                 Dwarf_Word *address,
8378                 unsigned int *op_index)
8379 {
8380   const unsigned int advanced_op_index = (*op_index) + op_advance;
8381
8382   *op_addr_advance = minimum_instr_len * (advanced_op_index
8383                                          / max_ops_per_instr);
8384   *address = *address + *op_addr_advance;
8385   *op_index = advanced_op_index % max_ops_per_instr;
8386 }
8387
8388 static void
8389 print_debug_line_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
8390                           Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
8391 {
8392   if (decodedline)
8393     {
8394       print_decoded_line_section (dwflmod, ebl, ehdr, scn, shdr, dbg);
8395       return;
8396     }
8397
8398   printf (_("\
8399 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
8400           elf_ndxscn (scn), section_name (ebl, shdr),
8401           (uint64_t) shdr->sh_offset);
8402
8403   if (shdr->sh_size == 0)
8404     return;
8405
8406   /* There is no functionality in libdw to read the information in the
8407      way it is represented here.  Hardcode the decoder.  */
8408   Elf_Data *data = (dbg->sectiondata[IDX_debug_line]
8409                     ?: elf_rawdata (scn, NULL));
8410   if (unlikely (data == NULL))
8411     {
8412       error (0, 0, _("cannot get line data section data: %s"),
8413              elf_errmsg (-1));
8414       return;
8415     }
8416
8417   const unsigned char *linep = (const unsigned char *) data->d_buf;
8418   const unsigned char *lineendp;
8419
8420   while (linep
8421          < (lineendp = (const unsigned char *) data->d_buf + data->d_size))
8422     {
8423       size_t start_offset = linep - (const unsigned char *) data->d_buf;
8424
8425       printf (_("\nTable at offset %zu:\n"), start_offset);
8426
8427       if (unlikely (linep + 4 > lineendp))
8428         goto invalid_data;
8429       Dwarf_Word unit_length = read_4ubyte_unaligned_inc (dbg, linep);
8430       unsigned int length = 4;
8431       if (unlikely (unit_length == 0xffffffff))
8432         {
8433           if (unlikely (linep + 8 > lineendp))
8434             {
8435             invalid_data:
8436               error (0, 0, _("invalid data in section [%zu] '%s'"),
8437                      elf_ndxscn (scn), section_name (ebl, shdr));
8438               return;
8439             }
8440           unit_length = read_8ubyte_unaligned_inc (dbg, linep);
8441           length = 8;
8442         }
8443
8444       /* Check whether we have enough room in the section.  */
8445       if (unlikely (unit_length > (size_t) (lineendp - linep)))
8446         goto invalid_data;
8447       lineendp = linep + unit_length;
8448
8449       /* The next element of the header is the version identifier.  */
8450       if ((size_t) (lineendp - linep) < 2)
8451         goto invalid_data;
8452       uint_fast16_t version = read_2ubyte_unaligned_inc (dbg, linep);
8453
8454       size_t address_size
8455         = elf_getident (ebl->elf, NULL)[EI_CLASS] == ELFCLASS32 ? 4 : 8;
8456       unsigned char segment_selector_size = 0;
8457       if (version > 4)
8458         {
8459           if ((size_t) (lineendp - linep) < 2)
8460             goto invalid_data;
8461           address_size = *linep++;
8462           segment_selector_size = *linep++;
8463         }
8464
8465       /* Next comes the header length.  */
8466       Dwarf_Word header_length;
8467       if (length == 4)
8468         {
8469           if ((size_t) (lineendp - linep) < 4)
8470             goto invalid_data;
8471           header_length = read_4ubyte_unaligned_inc (dbg, linep);
8472         }
8473       else
8474         {
8475           if ((size_t) (lineendp - linep) < 8)
8476             goto invalid_data;
8477           header_length = read_8ubyte_unaligned_inc (dbg, linep);
8478         }
8479
8480       const unsigned char *header_start = linep;
8481
8482       /* Next the minimum instruction length.  */
8483       if ((size_t) (lineendp - linep) < 1)
8484         goto invalid_data;
8485       uint_fast8_t minimum_instr_len = *linep++;
8486
8487       /* Next the maximum operations per instruction, in version 4 format.  */
8488       uint_fast8_t max_ops_per_instr;
8489       if (version < 4)
8490         max_ops_per_instr = 1;
8491       else
8492         {
8493           if ((size_t) (lineendp - linep) < 1)
8494             goto invalid_data;
8495           max_ops_per_instr = *linep++;
8496         }
8497
8498       /* We need at least 4 more bytes.  */
8499       if ((size_t) (lineendp - linep) < 4)
8500         goto invalid_data;
8501
8502       /* Then the flag determining the default value of the is_stmt
8503          register.  */
8504       uint_fast8_t default_is_stmt = *linep++;
8505
8506       /* Now the line base.  */
8507       int_fast8_t line_base = *linep++;
8508
8509       /* And the line range.  */
8510       uint_fast8_t line_range = *linep++;
8511
8512       /* The opcode base.  */
8513       uint_fast8_t opcode_base = *linep++;
8514
8515       /* Print what we got so far.  */
8516       printf (_("\n"
8517                        " Length:                         %" PRIu64 "\n"
8518                        " DWARF version:                  %" PRIuFAST16 "\n"
8519                        " Prologue length:                %" PRIu64 "\n"
8520                        " Address size:                   %zd\n"
8521                        " Segment selector size:          %zd\n"
8522                        " Min instruction length:         %" PRIuFAST8 "\n"
8523                        " Max operations per instruction: %" PRIuFAST8 "\n"
8524                        " Initial value if 'is_stmt':     %" PRIuFAST8 "\n"
8525                        " Line base:                      %" PRIdFAST8 "\n"
8526                        " Line range:                     %" PRIuFAST8 "\n"
8527                        " Opcode base:                    %" PRIuFAST8 "\n"
8528                        "\n"
8529                        "Opcodes:\n"),
8530               (uint64_t) unit_length, version, (uint64_t) header_length,
8531               address_size, (size_t) segment_selector_size,
8532               minimum_instr_len, max_ops_per_instr,
8533               default_is_stmt, line_base,
8534               line_range, opcode_base);
8535
8536       if (version < 2 || version > 5)
8537         {
8538           error (0, 0, _("cannot handle .debug_line version: %u\n"),
8539                  (unsigned int) version);
8540           linep = lineendp;
8541           continue;
8542         }
8543
8544       if (address_size != 4 && address_size != 8)
8545         {
8546           error (0, 0, _("cannot handle address size: %u\n"),
8547                  (unsigned int) address_size);
8548           linep = lineendp;
8549           continue;
8550         }
8551
8552       if (segment_selector_size != 0)
8553         {
8554           error (0, 0, _("cannot handle segment selector size: %u\n"),
8555                  (unsigned int) segment_selector_size);
8556           linep = lineendp;
8557           continue;
8558         }
8559
8560       if (unlikely (linep + opcode_base - 1 >= lineendp))
8561         {
8562         invalid_unit:
8563           error (0, 0,
8564                  _("invalid data at offset %tu in section [%zu] '%s'"),
8565                  linep - (const unsigned char *) data->d_buf,
8566                  elf_ndxscn (scn), section_name (ebl, shdr));
8567           linep = lineendp;
8568           continue;
8569         }
8570       int opcode_base_l10 = 1;
8571       unsigned int tmp = opcode_base;
8572       while (tmp > 10)
8573         {
8574           tmp /= 10;
8575           ++opcode_base_l10;
8576         }
8577       const uint8_t *standard_opcode_lengths = linep - 1;
8578       for (uint_fast8_t cnt = 1; cnt < opcode_base; ++cnt)
8579         printf (ngettext ("  [%*" PRIuFAST8 "]  %hhu argument\n",
8580                           "  [%*" PRIuFAST8 "]  %hhu arguments\n",
8581                           (int) linep[cnt - 1]),
8582                 opcode_base_l10, cnt, linep[cnt - 1]);
8583       linep += opcode_base - 1;
8584
8585       if (unlikely (linep >= lineendp))
8586         goto invalid_unit;
8587
8588       Dwarf_Off str_offsets_base = str_offsets_base_off (dbg, NULL);
8589
8590       puts (_("\nDirectory table:"));
8591       if (version > 4)
8592         {
8593           struct encpair { uint16_t desc; uint16_t form; };
8594           struct encpair enc[256];
8595
8596           printf (_("      ["));
8597           if ((size_t) (lineendp - linep) < 1)
8598             goto invalid_data;
8599           unsigned char directory_entry_format_count = *linep++;
8600           for (int i = 0; i < directory_entry_format_count; i++)
8601             {
8602               uint16_t desc, form;
8603               if ((size_t) (lineendp - linep) < 1)
8604                 goto invalid_data;
8605               get_uleb128 (desc, linep, lineendp);
8606               if ((size_t) (lineendp - linep) < 1)
8607                 goto invalid_data;
8608               get_uleb128 (form, linep, lineendp);
8609
8610               enc[i].desc = desc;
8611               enc[i].form = form;
8612
8613               printf ("%s(%s)",
8614                       dwarf_line_content_description_name (desc),
8615                       dwarf_form_name (form));
8616               if (i + 1 < directory_entry_format_count)
8617                 printf (", ");
8618             }
8619           printf ("]\n");
8620
8621           uint64_t directories_count;
8622           if ((size_t) (lineendp - linep) < 1)
8623             goto invalid_data;
8624           get_uleb128 (directories_count, linep, lineendp);
8625
8626           if (directory_entry_format_count == 0
8627               && directories_count != 0)
8628             goto invalid_data;
8629
8630           for (uint64_t i = 0; i < directories_count; i++)
8631             {
8632               printf (" %-5" PRIu64 " ", i);
8633               for (int j = 0; j < directory_entry_format_count; j++)
8634                 {
8635                   linep = print_form_data (dbg, enc[j].form,
8636                                            linep, lineendp, length,
8637                                            str_offsets_base);
8638                   if (j + 1 < directory_entry_format_count)
8639                     printf (", ");
8640                 }
8641               printf ("\n");
8642               if (linep >= lineendp)
8643                 goto invalid_unit;
8644             }
8645         }
8646       else
8647         {
8648           while (linep < lineendp && *linep != 0)
8649             {
8650               unsigned char *endp = memchr (linep, '\0', lineendp - linep);
8651               if (unlikely (endp == NULL))
8652                 goto invalid_unit;
8653
8654               printf (" %s\n", (char *) linep);
8655
8656               linep = endp + 1;
8657             }
8658           if (linep >= lineendp || *linep != 0)
8659             goto invalid_unit;
8660           /* Skip the final NUL byte.  */
8661           ++linep;
8662         }
8663
8664       if (unlikely (linep >= lineendp))
8665         goto invalid_unit;
8666
8667       puts (_("\nFile name table:"));
8668       if (version > 4)
8669         {
8670           struct encpair { uint16_t desc; uint16_t form; };
8671           struct encpair enc[256];
8672
8673           printf (_("      ["));
8674           if ((size_t) (lineendp - linep) < 1)
8675             goto invalid_data;
8676           unsigned char file_name_format_count = *linep++;
8677           for (int i = 0; i < file_name_format_count; i++)
8678             {
8679               uint64_t desc, form;
8680               if ((size_t) (lineendp - linep) < 1)
8681                 goto invalid_data;
8682               get_uleb128 (desc, linep, lineendp);
8683               if ((size_t) (lineendp - linep) < 1)
8684                 goto invalid_data;
8685               get_uleb128 (form, linep, lineendp);
8686
8687               if (! libdw_valid_user_form (form))
8688                 goto invalid_data;
8689
8690               enc[i].desc = desc;
8691               enc[i].form = form;
8692
8693               printf ("%s(%s)",
8694                       dwarf_line_content_description_name (desc),
8695                       dwarf_form_name (form));
8696               if (i + 1 < file_name_format_count)
8697                 printf (", ");
8698             }
8699           printf ("]\n");
8700
8701           uint64_t file_name_count;
8702           if ((size_t) (lineendp - linep) < 1)
8703             goto invalid_data;
8704           get_uleb128 (file_name_count, linep, lineendp);
8705
8706           if (file_name_format_count == 0
8707               && file_name_count != 0)
8708             goto invalid_data;
8709
8710           for (uint64_t i = 0; i < file_name_count; i++)
8711             {
8712               printf (" %-5" PRIu64 " ", i);
8713               for (int j = 0; j < file_name_format_count; j++)
8714                 {
8715                   linep = print_form_data (dbg, enc[j].form,
8716                                            linep, lineendp, length,
8717                                            str_offsets_base);
8718                   if (j + 1 < file_name_format_count)
8719                     printf (", ");
8720                 }
8721               printf ("\n");
8722               if (linep > lineendp)
8723                 goto invalid_unit;
8724             }
8725         }
8726       else
8727         {
8728           puts (_(" Entry Dir   Time      Size      Name"));
8729           for (unsigned int cnt = 1; linep < lineendp && *linep != 0; ++cnt)
8730             {
8731               /* First comes the file name.  */
8732               char *fname = (char *) linep;
8733               unsigned char *endp = memchr (fname, '\0', lineendp - linep);
8734               if (unlikely (endp == NULL))
8735                 goto invalid_unit;
8736               linep = endp + 1;
8737
8738               /* Then the index.  */
8739               unsigned int diridx;
8740               if (lineendp - linep < 1)
8741                 goto invalid_unit;
8742               get_uleb128 (diridx, linep, lineendp);
8743
8744               /* Next comes the modification time.  */
8745               unsigned int mtime;
8746               if (lineendp - linep < 1)
8747                 goto invalid_unit;
8748               get_uleb128 (mtime, linep, lineendp);
8749
8750               /* Finally the length of the file.  */
8751               unsigned int fsize;
8752               if (lineendp - linep < 1)
8753                 goto invalid_unit;
8754               get_uleb128 (fsize, linep, lineendp);
8755
8756               printf (" %-5u %-5u %-9u %-9u %s\n",
8757                       cnt, diridx, mtime, fsize, fname);
8758             }
8759           if (linep >= lineendp || *linep != '\0')
8760             goto invalid_unit;
8761           /* Skip the final NUL byte.  */
8762           ++linep;
8763         }
8764
8765       unsigned int debug_str_offset = 0;
8766       if (unlikely (linep == header_start + header_length - 4))
8767         {
8768           /* CUBINs contain an unsigned 4-byte offset */
8769           debug_str_offset = read_4ubyte_unaligned_inc (dbg, linep);
8770         }
8771
8772       if (linep == lineendp)
8773         {
8774           puts (_("\nNo line number statements."));
8775           continue;
8776         }
8777
8778       puts (_("\nLine number statements:"));
8779       Dwarf_Word address = 0;
8780       unsigned int op_index = 0;
8781       size_t line = 1;
8782       uint_fast8_t is_stmt = default_is_stmt;
8783
8784       /* Apply the "operation advance" from a special opcode
8785          or DW_LNS_advance_pc (as per DWARF4 6.2.5.1).  */
8786       unsigned int op_addr_advance;
8787 #define advance_pc(op_advance) run_advance_pc(op_advance, minimum_instr_len, \
8788                       max_ops_per_instr, &op_addr_advance, &address, &op_index)
8789
8790       if (max_ops_per_instr == 0)
8791         {
8792           error (0, 0,
8793                  _("invalid maximum operations per instruction is zero"));
8794           linep = lineendp;
8795           continue;
8796         }
8797
8798       while (linep < lineendp)
8799         {
8800           size_t offset = linep - (const unsigned char *) data->d_buf;
8801           unsigned int u128;
8802           int s128;
8803
8804           /* Read the opcode.  */
8805           unsigned int opcode = *linep++;
8806
8807           printf (" [%6" PRIx64 "]", (uint64_t)offset);
8808           /* Is this a special opcode?  */
8809           if (likely (opcode >= opcode_base))
8810             {
8811               if (unlikely (line_range == 0))
8812                 goto invalid_unit;
8813
8814               /* Yes.  Handling this is quite easy since the opcode value
8815                  is computed with
8816
8817                  opcode = (desired line increment - line_base)
8818                            + (line_range * address advance) + opcode_base
8819               */
8820               int line_increment = (line_base
8821                                     + (opcode - opcode_base) % line_range);
8822
8823               /* Perform the increments.  */
8824               line += line_increment;
8825               advance_pc ((opcode - opcode_base) / line_range);
8826
8827               printf (_(" special opcode %u: address+%u = "),
8828                       opcode, op_addr_advance);
8829               print_dwarf_addr (dwflmod, 0, address, address);
8830               if (op_index > 0)
8831                 printf (_(", op_index = %u, line%+d = %zu\n"),
8832                         op_index, line_increment, line);
8833               else
8834                 printf (_(", line%+d = %zu\n"),
8835                         line_increment, line);
8836             }
8837           else if (opcode == 0)
8838             {
8839               /* This an extended opcode.  */
8840               if (unlikely (linep + 2 > lineendp))
8841                 goto invalid_unit;
8842
8843               /* The length.  */
8844               unsigned int len = *linep++;
8845
8846               if (unlikely (linep + len > lineendp))
8847                 goto invalid_unit;
8848
8849               /* The sub-opcode.  */
8850               opcode = *linep++;
8851
8852               printf (_(" extended opcode %u: "), opcode);
8853
8854               switch (opcode)
8855                 {
8856                 case DW_LNE_end_sequence:
8857                   puts (_(" end of sequence"));
8858
8859                   /* Reset the registers we care about.  */
8860                   address = 0;
8861                   op_index = 0;
8862                   line = 1;
8863                   is_stmt = default_is_stmt;
8864                   break;
8865
8866                 case DW_LNE_set_address:
8867                   op_index = 0;
8868                   if (unlikely ((size_t) (lineendp - linep) < address_size))
8869                     goto invalid_unit;
8870                   if (address_size == 4)
8871                     address = read_4ubyte_unaligned_inc (dbg, linep);
8872                   else
8873                     address = read_8ubyte_unaligned_inc (dbg, linep);
8874                   {
8875                     printf (_(" set address to "));
8876                     print_dwarf_addr (dwflmod, 0, address, address);
8877                     printf ("\n");
8878                   }
8879                   break;
8880
8881                 case DW_LNE_define_file:
8882                   {
8883                     char *fname = (char *) linep;
8884                     unsigned char *endp = memchr (linep, '\0',
8885                                                   lineendp - linep);
8886                     if (unlikely (endp == NULL))
8887                       goto invalid_unit;
8888                     linep = endp + 1;
8889
8890                     unsigned int diridx;
8891                     if (lineendp - linep < 1)
8892                       goto invalid_unit;
8893                     get_uleb128 (diridx, linep, lineendp);
8894                     Dwarf_Word mtime;
8895                     if (lineendp - linep < 1)
8896                       goto invalid_unit;
8897                     get_uleb128 (mtime, linep, lineendp);
8898                     Dwarf_Word filelength;
8899                     if (lineendp - linep < 1)
8900                       goto invalid_unit;
8901                     get_uleb128 (filelength, linep, lineendp);
8902
8903                     printf (_("\
8904  define new file: dir=%u, mtime=%" PRIu64 ", length=%" PRIu64 ", name=%s\n"),
8905                             diridx, (uint64_t) mtime, (uint64_t) filelength,
8906                             fname);
8907                   }
8908                   break;
8909
8910                 case DW_LNE_set_discriminator:
8911                   /* Takes one ULEB128 parameter, the discriminator.  */
8912                   if (unlikely (standard_opcode_lengths[opcode] != 1
8913                                 || lineendp - linep < 1))
8914                     goto invalid_unit;
8915
8916                   get_uleb128 (u128, linep, lineendp);
8917                   printf (_(" set discriminator to %u\n"), u128);
8918                   break;
8919
8920                 case DW_LNE_NVIDIA_inlined_call:
8921                   {
8922                     if (unlikely (linep >= lineendp))
8923                       goto invalid_data;
8924
8925                     unsigned int context;
8926                     get_uleb128 (context, linep, lineendp);
8927
8928                     if (unlikely (linep >= lineendp))
8929                       goto invalid_data;
8930
8931                     unsigned int function_name;
8932                     get_uleb128 (function_name, linep, lineendp);
8933                     function_name += debug_str_offset;
8934
8935                     Elf_Data *str_data = dbg->sectiondata[IDX_debug_str];
8936                     char *function_str;
8937                     if (str_data == NULL || function_name >= str_data->d_size
8938                         || memchr (str_data->d_buf + function_name, '\0',
8939                                    str_data->d_size - function_name) == NULL)
8940                       function_str = "???";
8941                     else
8942                       function_str = (char *) str_data->d_buf + function_name;
8943
8944                     printf (_(" set inlined context %u,"
8945                               " function name %s (0x%x)\n"),
8946                             context, function_str, function_name);
8947                     break;
8948                   }
8949
8950                 case DW_LNE_NVIDIA_set_function_name:
8951                   {
8952                     if (unlikely (linep >= lineendp))
8953                       goto invalid_data;
8954
8955                     unsigned int function_name;
8956                     get_uleb128 (function_name, linep, lineendp);
8957                     function_name += debug_str_offset;
8958
8959                     Elf_Data *str_data = dbg->sectiondata[IDX_debug_str];
8960                     char *function_str;
8961                     if (str_data == NULL || function_name >= str_data->d_size
8962                         || memchr (str_data->d_buf + function_name, '\0',
8963                                    str_data->d_size - function_name) == NULL)
8964                       function_str = "???";
8965                     else
8966                       function_str = (char *) str_data->d_buf + function_name;
8967
8968                     printf (_(" set function name %s (0x%x)\n"),
8969                             function_str, function_name);
8970                   }
8971                   break;
8972
8973                 default:
8974                   /* Unknown, ignore it.  */
8975                   puts (_(" unknown opcode"));
8976                   linep += len - 1;
8977                   break;
8978                 }
8979             }
8980           else if (opcode <= DW_LNS_set_isa)
8981             {
8982               /* This is a known standard opcode.  */
8983               switch (opcode)
8984                 {
8985                 case DW_LNS_copy:
8986                   /* Takes no argument.  */
8987                   puts (_(" copy"));
8988                   break;
8989
8990                 case DW_LNS_advance_pc:
8991                   /* Takes one uleb128 parameter which is added to the
8992                      address.  */
8993                   if (lineendp - linep < 1)
8994                     goto invalid_unit;
8995                   get_uleb128 (u128, linep, lineendp);
8996                   advance_pc (u128);
8997                   {
8998                     printf (_(" advance address by %u to "),
8999                             op_addr_advance);
9000                     print_dwarf_addr (dwflmod, 0, address, address);
9001                     if (op_index > 0)
9002                       printf (_(", op_index to %u"), op_index);
9003                     printf ("\n");
9004                   }
9005                   break;
9006
9007                 case DW_LNS_advance_line:
9008                   /* Takes one sleb128 parameter which is added to the
9009                      line.  */
9010                   if (lineendp - linep < 1)
9011                     goto invalid_unit;
9012                   get_sleb128 (s128, linep, lineendp);
9013                   line += s128;
9014                   printf (_("\
9015  advance line by constant %d to %" PRId64 "\n"),
9016                           s128, (int64_t) line);
9017                   break;
9018
9019                 case DW_LNS_set_file:
9020                   /* Takes one uleb128 parameter which is stored in file.  */
9021                   if (lineendp - linep < 1)
9022                     goto invalid_unit;
9023                   get_uleb128 (u128, linep, lineendp);
9024                   printf (_(" set file to %" PRIu64 "\n"),
9025                           (uint64_t) u128);
9026                   break;
9027
9028                 case DW_LNS_set_column:
9029                   /* Takes one uleb128 parameter which is stored in column.  */
9030                   if (unlikely (standard_opcode_lengths[opcode] != 1
9031                                 || lineendp - linep < 1))
9032                     goto invalid_unit;
9033
9034                   get_uleb128 (u128, linep, lineendp);
9035                   printf (_(" set column to %" PRIu64 "\n"),
9036                           (uint64_t) u128);
9037                   break;
9038
9039                 case DW_LNS_negate_stmt:
9040                   /* Takes no argument.  */
9041                   is_stmt = 1 - is_stmt;
9042                   printf (_(" set '%s' to %" PRIuFAST8 "\n"),
9043                           "is_stmt", is_stmt);
9044                   break;
9045
9046                 case DW_LNS_set_basic_block:
9047                   /* Takes no argument.  */
9048                   puts (_(" set basic block flag"));
9049                   break;
9050
9051                 case DW_LNS_const_add_pc:
9052                   /* Takes no argument.  */
9053
9054                   if (unlikely (line_range == 0))
9055                     goto invalid_unit;
9056
9057                   advance_pc ((255 - opcode_base) / line_range);
9058                   {
9059                     printf (_(" advance address by constant %u to "),
9060                             op_addr_advance);
9061                     print_dwarf_addr (dwflmod, 0, address, address);
9062                     if (op_index > 0)
9063                       printf (_(", op_index to %u"), op_index);
9064                     printf ("\n");
9065                   }
9066                   break;
9067
9068                 case DW_LNS_fixed_advance_pc:
9069                   /* Takes one 16 bit parameter which is added to the
9070                      address.  */
9071                   if (unlikely (standard_opcode_lengths[opcode] != 1
9072                                 || lineendp - linep < 2))
9073                     goto invalid_unit;
9074
9075                   u128 = read_2ubyte_unaligned_inc (dbg, linep);
9076                   address += u128;
9077                   op_index = 0;
9078                   {
9079                     printf (_("\
9080  advance address by fixed value %u to \n"),
9081                             u128);
9082                     print_dwarf_addr (dwflmod, 0, address, address);
9083                     printf ("\n");
9084                   }
9085                   break;
9086
9087                 case DW_LNS_set_prologue_end:
9088                   /* Takes no argument.  */
9089                   puts (_(" set prologue end flag"));
9090                   break;
9091
9092                 case DW_LNS_set_epilogue_begin:
9093                   /* Takes no argument.  */
9094                   puts (_(" set epilogue begin flag"));
9095                   break;
9096
9097                 case DW_LNS_set_isa:
9098                   /* Takes one uleb128 parameter which is stored in isa.  */
9099                   if (unlikely (standard_opcode_lengths[opcode] != 1
9100                                 || lineendp - linep < 1))
9101                     goto invalid_unit;
9102
9103                   get_uleb128 (u128, linep, lineendp);
9104                   printf (_(" set isa to %u\n"), u128);
9105                   break;
9106                 }
9107             }
9108           else
9109             {
9110               /* This is a new opcode the generator but not we know about.
9111                  Read the parameters associated with it but then discard
9112                  everything.  Read all the parameters for this opcode.  */
9113               printf (ngettext (" unknown opcode with %" PRIu8 " parameter:",
9114                                 " unknown opcode with %" PRIu8 " parameters:",
9115                                 standard_opcode_lengths[opcode]),
9116                       standard_opcode_lengths[opcode]);
9117               for (int n = standard_opcode_lengths[opcode];
9118                    n > 0 && linep < lineendp; --n)
9119                 {
9120                   get_uleb128 (u128, linep, lineendp);
9121                   if (n != standard_opcode_lengths[opcode])
9122                     putc_unlocked (',', stdout);
9123                   printf (" %u", u128);
9124                 }
9125
9126               /* Next round, ignore this opcode.  */
9127               continue;
9128             }
9129         }
9130     }
9131
9132   /* There must only be one data block.  */
9133   assert (elf_getdata (scn, data) == NULL);
9134 }
9135
9136
9137 static void
9138 print_debug_loclists_section (Dwfl_Module *dwflmod,
9139                               Ebl *ebl,
9140                               GElf_Ehdr *ehdr __attribute__ ((unused)),
9141                               Elf_Scn *scn, GElf_Shdr *shdr,
9142                               Dwarf *dbg)
9143 {
9144   printf (_("\
9145 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
9146           elf_ndxscn (scn), section_name (ebl, shdr),
9147           (uint64_t) shdr->sh_offset);
9148
9149   Elf_Data *data = (dbg->sectiondata[IDX_debug_loclists]
9150                     ?: elf_rawdata (scn, NULL));
9151   if (unlikely (data == NULL))
9152     {
9153       error (0, 0, _("cannot get .debug_loclists content: %s"),
9154              elf_errmsg (-1));
9155       return;
9156     }
9157
9158   /* For the listptr to get the base address/CU.  */
9159   sort_listptr (&known_loclistsptr, "loclistsptr");
9160   size_t listptr_idx = 0;
9161
9162   const unsigned char *readp = data->d_buf;
9163   const unsigned char *const dataend = ((unsigned char *) data->d_buf
9164                                         + data->d_size);
9165   while (readp < dataend)
9166     {
9167       if (unlikely (readp > dataend - 4))
9168         {
9169         invalid_data:
9170           error (0, 0, _("invalid data in section [%zu] '%s'"),
9171                  elf_ndxscn (scn), section_name (ebl, shdr));
9172           return;
9173         }
9174
9175       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
9176       printf (_("Table at Offset 0x%" PRIx64 ":\n\n"),
9177               (uint64_t) offset);
9178
9179       uint64_t unit_length = read_4ubyte_unaligned_inc (dbg, readp);
9180       unsigned int offset_size = 4;
9181       if (unlikely (unit_length == 0xffffffff))
9182         {
9183           if (unlikely (readp > dataend - 8))
9184             goto invalid_data;
9185
9186           unit_length = read_8ubyte_unaligned_inc (dbg, readp);
9187           offset_size = 8;
9188         }
9189       printf (_(" Length:         %8" PRIu64 "\n"), unit_length);
9190
9191       /* We need at least 2-bytes + 1-byte + 1-byte + 4-bytes = 8
9192          bytes to complete the header.  And this unit cannot go beyond
9193          the section data.  */
9194       if (readp > dataend - 8
9195           || unit_length < 8
9196           || unit_length > (uint64_t) (dataend - readp))
9197         goto invalid_data;
9198
9199       const unsigned char *nexthdr = readp + unit_length;
9200
9201       uint16_t version = read_2ubyte_unaligned_inc (dbg, readp);
9202       printf (_(" DWARF version:  %8" PRIu16 "\n"), version);
9203
9204       if (version != 5)
9205         {
9206           error (0, 0, _("Unknown version"));
9207           goto next_table;
9208         }
9209
9210       uint8_t address_size = *readp++;
9211       printf (_(" Address size:   %8" PRIu64 "\n"),
9212               (uint64_t) address_size);
9213
9214       if (address_size != 4 && address_size != 8)
9215         {
9216           error (0, 0, _("unsupported address size"));
9217           goto next_table;
9218         }
9219
9220       uint8_t segment_size = *readp++;
9221       printf (_(" Segment size:   %8" PRIu64 "\n"),
9222               (uint64_t) segment_size);
9223
9224       if (segment_size != 0)
9225         {
9226           error (0, 0, _("unsupported segment size"));
9227           goto next_table;
9228         }
9229
9230       uint32_t offset_entry_count = read_4ubyte_unaligned_inc (dbg, readp);
9231       printf (_(" Offset entries: %8" PRIu64 "\n"),
9232               (uint64_t) offset_entry_count);
9233
9234       /* We need the CU that uses this unit to get the initial base address. */
9235       Dwarf_Addr cu_base = 0;
9236       struct Dwarf_CU *cu = NULL;
9237       if (listptr_cu (&known_loclistsptr, &listptr_idx,
9238                       (Dwarf_Off) offset,
9239                       (Dwarf_Off) (nexthdr - (unsigned char *) data->d_buf),
9240                       &cu_base, &cu)
9241           || split_dwarf_cu_base (dbg, &cu, &cu_base))
9242         {
9243           Dwarf_Die cudie;
9244           if (dwarf_cu_die (cu, &cudie,
9245                             NULL, NULL, NULL, NULL,
9246                             NULL, NULL) == NULL)
9247             printf (_(" Unknown CU base: "));
9248           else
9249             printf (_(" CU [%6" PRIx64 "] base: "),
9250                     dwarf_dieoffset (&cudie));
9251           print_dwarf_addr (dwflmod, address_size, cu_base, cu_base);
9252           printf ("\n");
9253         }
9254       else
9255         printf (_(" Not associated with a CU.\n"));
9256
9257       printf ("\n");
9258
9259       const unsigned char *offset_array_start = readp;
9260       if (offset_entry_count > 0)
9261         {
9262           uint64_t max_entries = (unit_length - 8) / offset_size;
9263           if (offset_entry_count > max_entries)
9264             {
9265               error (0, 0,
9266                      _("too many offset entries for unit length"));
9267               offset_entry_count = max_entries;
9268             }
9269
9270           printf (_("  Offsets starting at 0x%" PRIx64 ":\n"),
9271                   (uint64_t) (offset_array_start
9272                               - (unsigned char *) data->d_buf));
9273           for (uint32_t idx = 0; idx < offset_entry_count; idx++)
9274             {
9275               printf ("   [%6" PRIu32 "] ", idx);
9276               if (offset_size == 4)
9277                 {
9278                   uint32_t off = read_4ubyte_unaligned_inc (dbg, readp);
9279                   printf ("0x%" PRIx32 "\n", off);
9280                 }
9281               else
9282                 {
9283                   uint64_t off = read_8ubyte_unaligned_inc (dbg, readp);
9284                   printf ("0x%" PRIx64 "\n", off);
9285                 }
9286             }
9287           printf ("\n");
9288         }
9289
9290       Dwarf_Addr base = cu_base;
9291       bool start_of_list = true;
9292       while (readp < nexthdr)
9293         {
9294           Dwarf_Off off = (Dwarf_Off) (readp - (unsigned char *) data->d_buf);
9295           if (listptr_attr (&known_loclistsptr, listptr_idx, off,
9296                             DW_AT_GNU_locviews))
9297             {
9298               Dwarf_Off next_off = next_listptr_offset (&known_loclistsptr,
9299                                                         &listptr_idx, off);
9300               const unsigned char *locp = readp;
9301               const unsigned char *locendp;
9302               if (next_off == 0
9303                   || next_off > (size_t) (nexthdr - ((const unsigned char *)
9304                                                      data->d_buf)))
9305                 locendp = nexthdr;
9306               else
9307                 locendp = (const unsigned char *) data->d_buf + next_off;
9308
9309               printf ("  Offset: %" PRIx64 ", Index: %" PRIx64 "\n",
9310                       (uint64_t) (readp - (unsigned char *) data->d_buf),
9311                       (uint64_t) (readp - offset_array_start));
9312
9313               while (locp < locendp)
9314                 {
9315                   uint64_t v1, v2;
9316                   get_uleb128 (v1, locp, locendp);
9317                   if (locp >= locendp)
9318                     {
9319                       printf (_("    <INVALID DATA>\n"));
9320                       break;
9321                     }
9322                   get_uleb128 (v2, locp, locendp);
9323                   printf ("    view pair %" PRId64 ", %" PRId64 "\n", v1, v2);
9324                 }
9325
9326               printf ("\n");
9327               readp = (unsigned char *) locendp;
9328               continue;
9329             }
9330
9331           uint8_t kind = *readp++;
9332           uint64_t op1, op2, len;
9333
9334           /* Skip padding.  */
9335           if (start_of_list && kind == DW_LLE_end_of_list)
9336             continue;
9337
9338           if (start_of_list)
9339             {
9340               base = cu_base;
9341               printf ("  Offset: %" PRIx64 ", Index: %" PRIx64 "\n",
9342                       (uint64_t) (readp - (unsigned char *) data->d_buf - 1),
9343                       (uint64_t) (readp - offset_array_start - 1));
9344               start_of_list = false;
9345             }
9346
9347           printf ("    %s", dwarf_loc_list_encoding_name (kind));
9348           switch (kind)
9349             {
9350             case DW_LLE_end_of_list:
9351               start_of_list = true;
9352               printf ("\n\n");
9353               break;
9354
9355             case DW_LLE_base_addressx:
9356               if ((uint64_t) (nexthdr - readp) < 1)
9357                 {
9358                 invalid_entry:
9359                   error (0, 0, _("invalid loclists data"));
9360                   goto next_table;
9361                 }
9362               get_uleb128 (op1, readp, nexthdr);
9363               printf (" %" PRIx64 "\n", op1);
9364               if (! print_unresolved_addresses)
9365                 {
9366                   Dwarf_Addr addr;
9367                   if (get_indexed_addr (cu, op1, &addr) != 0)
9368                     printf ("      ???\n");
9369                   else
9370                     {
9371                       printf ("      ");
9372                       print_dwarf_addr (dwflmod, address_size, addr, addr);
9373                       printf ("\n");
9374                     }
9375                 }
9376               break;
9377
9378             case DW_LLE_startx_endx:
9379               if ((uint64_t) (nexthdr - readp) < 1)
9380                 goto invalid_entry;
9381               get_uleb128 (op1, readp, nexthdr);
9382               if ((uint64_t) (nexthdr - readp) < 1)
9383                 goto invalid_entry;
9384               get_uleb128 (op2, readp, nexthdr);
9385               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
9386               if (! print_unresolved_addresses)
9387                 {
9388                   Dwarf_Addr addr1;
9389                   Dwarf_Addr addr2;
9390                   if (get_indexed_addr (cu, op1, &addr1) != 0
9391                       || get_indexed_addr (cu, op2, &addr2) != 0)
9392                     {
9393                       printf ("      ???..\n");
9394                       printf ("      ???\n");
9395                     }
9396                   else
9397                     {
9398                       printf ("      ");
9399                       print_dwarf_addr (dwflmod, address_size, addr1, addr1);
9400                       printf ("..\n      ");
9401                       print_dwarf_addr (dwflmod, address_size,
9402                                         addr2 - 1, addr2);
9403                       printf ("\n");
9404                     }
9405                 }
9406               if ((uint64_t) (nexthdr - readp) < 1)
9407                 goto invalid_entry;
9408               get_uleb128 (len, readp, nexthdr);
9409               if ((uint64_t) (nexthdr - readp) < len)
9410                 goto invalid_entry;
9411               print_ops (dwflmod, dbg, 8, 8, version,
9412                          address_size, offset_size, cu, len, readp);
9413               readp += len;
9414               break;
9415
9416             case DW_LLE_startx_length:
9417               if ((uint64_t) (nexthdr - readp) < 1)
9418                 goto invalid_entry;
9419               get_uleb128 (op1, readp, nexthdr);
9420               if ((uint64_t) (nexthdr - readp) < 1)
9421                 goto invalid_entry;
9422               get_uleb128 (op2, readp, nexthdr);
9423               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
9424               if (! print_unresolved_addresses)
9425                 {
9426                   Dwarf_Addr addr1;
9427                   Dwarf_Addr addr2;
9428                   if (get_indexed_addr (cu, op1, &addr1) != 0)
9429                     {
9430                       printf ("      ???..\n");
9431                       printf ("      ???\n");
9432                     }
9433                   else
9434                     {
9435                       addr2 = addr1 + op2;
9436                       printf ("      ");
9437                       print_dwarf_addr (dwflmod, address_size, addr1, addr1);
9438                       printf ("..\n      ");
9439                       print_dwarf_addr (dwflmod, address_size,
9440                                         addr2 - 1, addr2);
9441                       printf ("\n");
9442                     }
9443                 }
9444               if ((uint64_t) (nexthdr - readp) < 1)
9445                 goto invalid_entry;
9446               get_uleb128 (len, readp, nexthdr);
9447               if ((uint64_t) (nexthdr - readp) < len)
9448                 goto invalid_entry;
9449               print_ops (dwflmod, dbg, 8, 8, version,
9450                          address_size, offset_size, cu, len, readp);
9451               readp += len;
9452               break;
9453
9454             case DW_LLE_offset_pair:
9455               if ((uint64_t) (nexthdr - readp) < 1)
9456                 goto invalid_entry;
9457               get_uleb128 (op1, readp, nexthdr);
9458               if ((uint64_t) (nexthdr - readp) < 1)
9459                 goto invalid_entry;
9460               get_uleb128 (op2, readp, nexthdr);
9461               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
9462               if (! print_unresolved_addresses)
9463                 {
9464                   op1 += base;
9465                   op2 += base;
9466                   printf ("      ");
9467                   print_dwarf_addr (dwflmod, address_size, op1, op1);
9468                   printf ("..\n      ");
9469                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
9470                   printf ("\n");
9471                 }
9472               if ((uint64_t) (nexthdr - readp) < 1)
9473                 goto invalid_entry;
9474               get_uleb128 (len, readp, nexthdr);
9475               if ((uint64_t) (nexthdr - readp) < len)
9476                 goto invalid_entry;
9477               print_ops (dwflmod, dbg, 8, 8, version,
9478                          address_size, offset_size, cu, len, readp);
9479               readp += len;
9480               break;
9481
9482             case DW_LLE_default_location:
9483               if ((uint64_t) (nexthdr - readp) < 1)
9484                 goto invalid_entry;
9485               get_uleb128 (len, readp, nexthdr);
9486               if ((uint64_t) (nexthdr - readp) < len)
9487                 goto invalid_entry;
9488               print_ops (dwflmod, dbg, 8, 8, version,
9489                          address_size, offset_size, cu, len, readp);
9490               readp += len;
9491               break;
9492
9493             case DW_LLE_base_address:
9494               if (address_size == 4)
9495                 {
9496                   if ((uint64_t) (nexthdr - readp) < 4)
9497                     goto invalid_entry;
9498                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
9499                 }
9500               else
9501                 {
9502                   if ((uint64_t) (nexthdr - readp) < 8)
9503                     goto invalid_entry;
9504                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
9505                 }
9506               base = op1;
9507               printf (" 0x%" PRIx64 "\n", base);
9508               if (! print_unresolved_addresses)
9509                 {
9510                   printf ("      ");
9511                   print_dwarf_addr (dwflmod, address_size, base, base);
9512                   printf ("\n");
9513                 }
9514               break;
9515
9516             case DW_LLE_start_end:
9517               if (address_size == 4)
9518                 {
9519                   if ((uint64_t) (nexthdr - readp) < 8)
9520                     goto invalid_entry;
9521                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
9522                   op2 = read_4ubyte_unaligned_inc (dbg, readp);
9523                 }
9524               else
9525                 {
9526                   if ((uint64_t) (nexthdr - readp) < 16)
9527                     goto invalid_entry;
9528                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
9529                   op2 = read_8ubyte_unaligned_inc (dbg, readp);
9530                 }
9531               printf (" 0x%" PRIx64 "..0x%" PRIx64 "\n", op1, op2);
9532               if (! print_unresolved_addresses)
9533                 {
9534                   printf ("      ");
9535                   print_dwarf_addr (dwflmod, address_size, op1, op1);
9536                   printf ("..\n      ");
9537                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
9538                   printf ("\n");
9539                 }
9540               if ((uint64_t) (nexthdr - readp) < 1)
9541                 goto invalid_entry;
9542               get_uleb128 (len, readp, nexthdr);
9543               if ((uint64_t) (nexthdr - readp) < len)
9544                 goto invalid_entry;
9545               print_ops (dwflmod, dbg, 8, 8, version,
9546                          address_size, offset_size, cu, len, readp);
9547               readp += len;
9548               break;
9549
9550             case DW_LLE_start_length:
9551               if (address_size == 4)
9552                 {
9553                   if ((uint64_t) (nexthdr - readp) < 4)
9554                     goto invalid_entry;
9555                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
9556                 }
9557               else
9558                 {
9559                   if ((uint64_t) (nexthdr - readp) < 8)
9560                     goto invalid_entry;
9561                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
9562                 }
9563               if ((uint64_t) (nexthdr - readp) < 1)
9564                 goto invalid_entry;
9565               get_uleb128 (op2, readp, nexthdr);
9566               printf (" 0x%" PRIx64 ", %" PRIx64 "\n", op1, op2);
9567               if (! print_unresolved_addresses)
9568                 {
9569                   op2 = op1 + op2;
9570                   printf ("      ");
9571                   print_dwarf_addr (dwflmod, address_size, op1, op1);
9572                   printf ("..\n      ");
9573                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
9574                   printf ("\n");
9575                 }
9576               if ((uint64_t) (nexthdr - readp) < 1)
9577                 goto invalid_entry;
9578               get_uleb128 (len, readp, nexthdr);
9579               if ((uint64_t) (nexthdr - readp) < len)
9580                 goto invalid_entry;
9581               print_ops (dwflmod, dbg, 8, 8, version,
9582                          address_size, offset_size, cu, len, readp);
9583               readp += len;
9584               break;
9585
9586             default:
9587               goto invalid_entry;
9588             }
9589         }
9590
9591     next_table:
9592       if (readp != nexthdr)
9593         {
9594           size_t padding = nexthdr - readp;
9595           printf (_("   %zu padding bytes\n\n"), padding);
9596           readp = nexthdr;
9597         }
9598     }
9599 }
9600
9601
9602 static void
9603 print_debug_loc_section (Dwfl_Module *dwflmod,
9604                          Ebl *ebl, GElf_Ehdr *ehdr,
9605                          Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
9606 {
9607   Elf_Data *data = (dbg->sectiondata[IDX_debug_loc]
9608                     ?: elf_rawdata (scn, NULL));
9609
9610   if (unlikely (data == NULL))
9611     {
9612       error (0, 0, _("cannot get .debug_loc content: %s"),
9613              elf_errmsg (-1));
9614       return;
9615     }
9616
9617   printf (_("\
9618 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
9619           elf_ndxscn (scn), section_name (ebl, shdr),
9620           (uint64_t) shdr->sh_offset);
9621
9622   sort_listptr (&known_locsptr, "loclistptr");
9623   size_t listptr_idx = 0;
9624
9625   uint_fast8_t address_size = ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
9626   uint_fast8_t offset_size = 4;
9627
9628   bool first = true;
9629   Dwarf_Addr base = 0;
9630   unsigned char *readp = data->d_buf;
9631   unsigned char *const endp = (unsigned char *) data->d_buf + data->d_size;
9632   Dwarf_CU *last_cu = NULL;
9633   while (readp < endp)
9634     {
9635       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
9636       Dwarf_CU *cu = last_cu;
9637       unsigned int attr = 0;
9638
9639       if (first && skip_listptr_hole (&known_locsptr, &listptr_idx,
9640                                       &address_size, &offset_size, &base,
9641                                       &cu, offset, &readp, endp, &attr))
9642         continue;
9643
9644       if (last_cu != cu)
9645        {
9646         Dwarf_Die cudie;
9647         if (dwarf_cu_die (cu, &cudie,
9648                           NULL, NULL, NULL, NULL,
9649                           NULL, NULL) == NULL)
9650           printf (_("\n Unknown CU base: "));
9651         else
9652           printf (_("\n CU [%6" PRIx64 "] base: "),
9653                   dwarf_dieoffset (&cudie));
9654         print_dwarf_addr (dwflmod, address_size, base, base);
9655         printf ("\n");
9656        }
9657       last_cu = cu;
9658
9659       if (attr == DW_AT_GNU_locviews)
9660         {
9661           Dwarf_Off next_off = next_listptr_offset (&known_locsptr,
9662                                                     &listptr_idx, offset);
9663           const unsigned char *locp = readp;
9664           const unsigned char *locendp;
9665           if (next_off == 0
9666               || next_off > (size_t) (endp
9667                                       - (const unsigned char *) data->d_buf))
9668             locendp = endp;
9669           else
9670             locendp = (const unsigned char *) data->d_buf + next_off;
9671
9672           while (locp < locendp)
9673             {
9674               uint64_t v1, v2;
9675               get_uleb128 (v1, locp, locendp);
9676               if (locp >= locendp)
9677                 {
9678                   printf (_(" [%6tx]  <INVALID DATA>\n"), offset);
9679                   break;
9680                 }
9681               get_uleb128 (v2, locp, locendp);
9682               if (first)                /* First view pair in a list.  */
9683                 printf (" [%6tx] ", offset);
9684               else
9685                 printf ("          ");
9686               printf ("view pair %" PRId64 ", %" PRId64 "\n", v1, v2);
9687               first = false;
9688             }
9689
9690           first = true;
9691           readp = (unsigned char *) locendp;
9692           continue;
9693         }
9694
9695       /* GNU DebugFission encoded addresses as addrx.  */
9696       bool is_debugfission = ((cu != NULL
9697                                || split_dwarf_cu_base (dbg, &cu, &base))
9698                               && (cu->version < 5
9699                                   && cu->unit_type == DW_UT_split_compile));
9700       if (!is_debugfission
9701           && unlikely (data->d_size - offset < (size_t) address_size * 2))
9702         {
9703         invalid_data:
9704           printf (_(" [%6tx]  <INVALID DATA>\n"), offset);
9705           break;
9706         }
9707
9708       Dwarf_Addr begin;
9709       Dwarf_Addr end;
9710       bool use_base = true;
9711       if (is_debugfission)
9712         {
9713           const unsigned char *locp = readp;
9714           const unsigned char *locendp = readp + data->d_size;
9715           if (locp >= locendp)
9716             goto invalid_data;
9717
9718           Dwarf_Word idx;
9719           unsigned char code = *locp++;
9720           switch (code)
9721             {
9722             case DW_LLE_GNU_end_of_list_entry:
9723               begin = 0;
9724               end = 0;
9725               break;
9726
9727             case DW_LLE_GNU_base_address_selection_entry:
9728               if (locp >= locendp)
9729                 goto invalid_data;
9730               begin = (Dwarf_Addr) -1;
9731               get_uleb128 (idx, locp, locendp);
9732               if (get_indexed_addr (cu, idx, &end) != 0)
9733                 end = idx; /* ... */
9734               break;
9735
9736             case DW_LLE_GNU_start_end_entry:
9737               if (locp >= locendp)
9738                 goto invalid_data;
9739               get_uleb128 (idx, locp, locendp);
9740               if (get_indexed_addr (cu, idx, &begin) != 0)
9741                 begin = idx; /* ... */
9742               if (locp >= locendp)
9743                 goto invalid_data;
9744               get_uleb128 (idx, locp, locendp);
9745               if (get_indexed_addr (cu, idx, &end) != 0)
9746                 end = idx; /* ... */
9747               use_base = false;
9748               break;
9749
9750             case DW_LLE_GNU_start_length_entry:
9751               if (locp >= locendp)
9752                 goto invalid_data;
9753               get_uleb128 (idx, locp, locendp);
9754               if (get_indexed_addr (cu, idx, &begin) != 0)
9755                 begin = idx; /* ... */
9756               if (locendp - locp < 4)
9757                 goto invalid_data;
9758               end = read_4ubyte_unaligned_inc (dbg, locp);
9759               end += begin;
9760               use_base = false;
9761               break;
9762
9763             default:
9764                 goto invalid_data;
9765             }
9766
9767           readp = (unsigned char *) locp;
9768         }
9769       else if (address_size == 8)
9770         {
9771           begin = read_8ubyte_unaligned_inc (dbg, readp);
9772           end = read_8ubyte_unaligned_inc (dbg, readp);
9773         }
9774       else
9775         {
9776           begin = read_4ubyte_unaligned_inc (dbg, readp);
9777           end = read_4ubyte_unaligned_inc (dbg, readp);
9778           if (begin == (Dwarf_Addr) (uint32_t) -1)
9779             begin = (Dwarf_Addr) -1l;
9780         }
9781
9782       if (begin == (Dwarf_Addr) -1l) /* Base address entry.  */
9783         {
9784           if (first)
9785             printf (" [%6tx] ", offset);
9786           else
9787             printf ("          ");
9788           puts (_("base address"));
9789           printf ("          ");
9790           print_dwarf_addr (dwflmod, address_size, end, end);
9791           printf ("\n");
9792           base = end;
9793           first = false;
9794         }
9795       else if (begin == 0 && end == 0) /* End of list entry.  */
9796         {
9797           if (first)
9798             printf (_(" [%6tx] empty list\n"), offset);
9799           first = true;
9800         }
9801       else
9802         {
9803           /* We have a location expression entry.  */
9804           uint_fast16_t len = read_2ubyte_unaligned_inc (dbg, readp);
9805
9806           if (first)            /* First entry in a list.  */
9807             printf (" [%6tx] ", offset);
9808           else
9809             printf ("          ");
9810
9811           printf ("range %" PRIx64 ", %" PRIx64 "\n", begin, end);
9812           if (! print_unresolved_addresses)
9813             {
9814               Dwarf_Addr dab = use_base ? base + begin : begin;
9815               Dwarf_Addr dae = use_base ? base + end : end;
9816               printf ("          ");
9817               print_dwarf_addr (dwflmod, address_size, dab, dab);
9818               printf ("..\n          ");
9819               print_dwarf_addr (dwflmod, address_size, dae - 1, dae);
9820               printf ("\n");
9821             }
9822
9823           if (endp - readp <= (ptrdiff_t) len)
9824             {
9825               fputs (_("   <INVALID DATA>\n"), stdout);
9826               break;
9827             }
9828
9829           print_ops (dwflmod, dbg, 11, 11,
9830                      cu != NULL ? cu->version : 3,
9831                      address_size, offset_size, cu, len, readp);
9832
9833           first = false;
9834           readp += len;
9835         }
9836     }
9837 }
9838
9839 struct mac_culist
9840 {
9841   Dwarf_Die die;
9842   Dwarf_Off offset;
9843   Dwarf_Files *files;
9844   struct mac_culist *next;
9845 };
9846
9847
9848 static int
9849 mac_compare (const void *p1, const void *p2)
9850 {
9851   struct mac_culist *m1 = (struct mac_culist *) p1;
9852   struct mac_culist *m2 = (struct mac_culist *) p2;
9853
9854   if (m1->offset < m2->offset)
9855     return -1;
9856   if (m1->offset > m2->offset)
9857     return 1;
9858   return 0;
9859 }
9860
9861
9862 static void
9863 print_debug_macinfo_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
9864                              Ebl *ebl,
9865                              GElf_Ehdr *ehdr __attribute__ ((unused)),
9866                              Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
9867 {
9868   printf (_("\
9869 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
9870           elf_ndxscn (scn), section_name (ebl, shdr),
9871           (uint64_t) shdr->sh_offset);
9872   putc_unlocked ('\n', stdout);
9873
9874   /* There is no function in libdw to iterate over the raw content of
9875      the section but it is easy enough to do.  */
9876   Elf_Data *data = (dbg->sectiondata[IDX_debug_macinfo]
9877                     ?: elf_rawdata (scn, NULL));
9878   if (unlikely (data == NULL))
9879     {
9880       error (0, 0, _("cannot get macro information section data: %s"),
9881              elf_errmsg (-1));
9882       return;
9883     }
9884
9885   /* Get the source file information for all CUs.  */
9886   Dwarf_Off offset;
9887   Dwarf_Off ncu = 0;
9888   size_t hsize;
9889   struct mac_culist *culist = NULL;
9890   size_t nculist = 0;
9891   while (dwarf_nextcu (dbg, offset = ncu, &ncu, &hsize, NULL, NULL, NULL) == 0)
9892     {
9893       Dwarf_Die cudie;
9894       if (dwarf_offdie (dbg, offset + hsize, &cudie) == NULL)
9895         continue;
9896
9897       Dwarf_Attribute attr;
9898       if (dwarf_attr (&cudie, DW_AT_macro_info, &attr) == NULL)
9899         continue;
9900
9901       Dwarf_Word macoff;
9902       if (dwarf_formudata (&attr, &macoff) != 0)
9903         continue;
9904
9905       struct mac_culist *newp = (struct mac_culist *) alloca (sizeof (*newp));
9906       newp->die = cudie;
9907       newp->offset = macoff;
9908       newp->files = NULL;
9909       newp->next = culist;
9910       culist = newp;
9911       ++nculist;
9912     }
9913
9914   /* Convert the list into an array for easier consumption.  */
9915   struct mac_culist *cus = (struct mac_culist *) alloca ((nculist + 1)
9916                                                          * sizeof (*cus));
9917   /* Add sentinel.  */
9918   cus[nculist].offset = data->d_size;
9919   cus[nculist].files = (Dwarf_Files *) -1l;
9920   if (nculist > 0)
9921     {
9922       for (size_t cnt = nculist - 1; culist != NULL; --cnt)
9923         {
9924           assert (cnt < nculist);
9925           cus[cnt] = *culist;
9926           culist = culist->next;
9927         }
9928
9929       /* Sort the array according to the offset in the .debug_macinfo
9930          section.  Note we keep the sentinel at the end.  */
9931       qsort (cus, nculist, sizeof (*cus), mac_compare);
9932     }
9933
9934   const unsigned char *readp = (const unsigned char *) data->d_buf;
9935   const unsigned char *readendp = readp + data->d_size;
9936   int level = 1;
9937
9938   while (readp < readendp)
9939     {
9940       unsigned int opcode = *readp++;
9941       unsigned int u128;
9942       unsigned int u128_2;
9943       const unsigned char *endp;
9944
9945       switch (opcode)
9946         {
9947         case DW_MACINFO_define:
9948         case DW_MACINFO_undef:
9949         case DW_MACINFO_vendor_ext:
9950           /*  For the first two opcodes the parameters are
9951                 line, string
9952               For the latter
9953                 number, string.
9954               We can treat these cases together.  */
9955           get_uleb128 (u128, readp, readendp);
9956
9957           endp = memchr (readp, '\0', readendp - readp);
9958           if (unlikely (endp == NULL))
9959             {
9960               printf (_("\
9961 %*s*** non-terminated string at end of section"),
9962                       level, "");
9963               return;
9964             }
9965
9966           if (opcode == DW_MACINFO_define)
9967             printf ("%*s#define %s, line %u\n",
9968                     level, "", (char *) readp, u128);
9969           else if (opcode == DW_MACINFO_undef)
9970             printf ("%*s#undef %s, line %u\n",
9971                     level, "", (char *) readp, u128);
9972           else
9973             printf (" #vendor-ext %s, number %u\n", (char *) readp, u128);
9974
9975           readp = endp + 1;
9976           break;
9977
9978         case DW_MACINFO_start_file:
9979           /* The two parameters are line and file index, in this order.  */
9980           get_uleb128 (u128, readp, readendp);
9981           if (readendp - readp < 1)
9982             {
9983               printf (_("\
9984 %*s*** missing DW_MACINFO_start_file argument at end of section"),
9985                       level, "");
9986               return;
9987             }
9988           get_uleb128 (u128_2, readp, readendp);
9989
9990           /* Find the CU DIE for this file.  */
9991           size_t macoff = readp - (const unsigned char *) data->d_buf;
9992           const char *fname = "???";
9993           if (macoff >= cus[0].offset && cus[0].offset != data->d_size)
9994             {
9995               while (macoff >= cus[1].offset && cus[1].offset != data->d_size)
9996                 ++cus;
9997
9998               if (cus[0].files == NULL
9999                   && dwarf_getsrcfiles (&cus[0].die, &cus[0].files, NULL) != 0)
10000                 cus[0].files = (Dwarf_Files *) -1l;
10001
10002               if (cus[0].files != (Dwarf_Files *) -1l)
10003                 fname = (dwarf_filesrc (cus[0].files, u128_2, NULL, NULL)
10004                          ?: "???");
10005             }
10006
10007           printf ("%*sstart_file %u, [%u] %s\n",
10008                   level, "", u128, u128_2, fname);
10009           ++level;
10010           break;
10011
10012         case DW_MACINFO_end_file:
10013           --level;
10014           printf ("%*send_file\n", level, "");
10015           /* Nothing more to do.  */
10016           break;
10017
10018         default:
10019           // XXX gcc seems to generate files with a trailing zero.
10020           if (unlikely (opcode != 0 || readp != readendp))
10021             printf ("%*s*** invalid opcode %u\n", level, "", opcode);
10022           break;
10023         }
10024     }
10025 }
10026
10027
10028 static void
10029 print_debug_macro_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
10030                            Ebl *ebl,
10031                            GElf_Ehdr *ehdr __attribute__ ((unused)),
10032                            Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
10033 {
10034   printf (_("\
10035 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
10036           elf_ndxscn (scn), section_name (ebl, shdr),
10037           (uint64_t) shdr->sh_offset);
10038   putc_unlocked ('\n', stdout);
10039
10040   Elf_Data *data =  elf_getdata (scn, NULL);
10041   if (unlikely (data == NULL))
10042     {
10043       error (0, 0, _("cannot get macro information section data: %s"),
10044              elf_errmsg (-1));
10045       return;
10046     }
10047
10048   /* Get the source file information for all CUs.  Uses same
10049      datastructure as macinfo.  But uses offset field to directly
10050      match .debug_line offset.  And just stored in a list.  */
10051   Dwarf_Off offset;
10052   Dwarf_Off ncu = 0;
10053   size_t hsize;
10054   struct mac_culist *culist = NULL;
10055   size_t nculist = 0;
10056   while (dwarf_nextcu (dbg, offset = ncu, &ncu, &hsize, NULL, NULL, NULL) == 0)
10057     {
10058       Dwarf_Die cudie;
10059       if (dwarf_offdie (dbg, offset + hsize, &cudie) == NULL)
10060         continue;
10061
10062       Dwarf_Attribute attr;
10063       if (dwarf_attr (&cudie, DW_AT_stmt_list, &attr) == NULL)
10064         continue;
10065
10066       Dwarf_Word lineoff;
10067       if (dwarf_formudata (&attr, &lineoff) != 0)
10068         continue;
10069
10070       struct mac_culist *newp = (struct mac_culist *) alloca (sizeof (*newp));
10071       newp->die = cudie;
10072       newp->offset = lineoff;
10073       newp->files = NULL;
10074       newp->next = culist;
10075       culist = newp;
10076       ++nculist;
10077     }
10078
10079   const unsigned char *readp = (const unsigned char *) data->d_buf;
10080   const unsigned char *readendp = readp + data->d_size;
10081
10082   while (readp < readendp)
10083     {
10084       printf (_(" Offset:             0x%" PRIx64 "\n"),
10085               (uint64_t) (readp - (const unsigned char *) data->d_buf));
10086
10087       // Header, 2 byte version, 1 byte flag, optional .debug_line offset,
10088       // optional vendor extension macro entry table.
10089       if (readp + 2 > readendp)
10090         {
10091         invalid_data:
10092           error (0, 0, _("invalid data"));
10093           return;
10094         }
10095       const uint16_t vers = read_2ubyte_unaligned_inc (dbg, readp);
10096       printf (_(" Version:            %" PRIu16 "\n"), vers);
10097
10098       // Version 4 is the GNU extension for DWARF4.  DWARF5 will use version
10099       // 5 when it gets standardized.
10100       if (vers != 4 && vers != 5)
10101         {
10102           printf (_("  unknown version, cannot parse section\n"));
10103           return;
10104         }
10105
10106       if (readp + 1 > readendp)
10107         goto invalid_data;
10108       const unsigned char flag = *readp++;
10109       printf (_(" Flag:               0x%" PRIx8), flag);
10110       if (flag != 0)
10111         {
10112           printf (" (");
10113           if ((flag & 0x01) != 0)
10114             {
10115               printf ("offset_size");
10116               if ((flag & 0xFE) !=  0)
10117                 printf (", ");
10118             }
10119           if ((flag & 0x02) != 0)
10120             {
10121               printf ("debug_line_offset");
10122               if ((flag & 0xFC) !=  0)
10123                 printf (", ");
10124             }
10125           if ((flag & 0x04) != 0)
10126             {
10127               printf ("operands_table");
10128               if ((flag & 0xF8) !=  0)
10129                 printf (", ");
10130             }
10131           if ((flag & 0xF8) != 0)
10132             printf ("unknown");
10133           printf (")");
10134         }
10135       printf ("\n");
10136
10137       unsigned int offset_len = (flag & 0x01) ? 8 : 4;
10138       printf (_(" Offset length:      %" PRIu8 "\n"), offset_len);
10139       Dwarf_Off line_offset = -1;
10140       if (flag & 0x02)
10141         {
10142           if (offset_len == 8)
10143             line_offset = read_8ubyte_unaligned_inc (dbg, readp);
10144           else
10145             line_offset = read_4ubyte_unaligned_inc (dbg, readp);
10146           printf (_(" .debug_line offset: 0x%" PRIx64 "\n"),
10147                   line_offset);
10148         }
10149
10150       struct mac_culist *cu = NULL;
10151       if (line_offset != (Dwarf_Off) -1)
10152         {
10153           cu = culist;
10154           while (cu != NULL && line_offset != cu->offset)
10155             cu = cu->next;
10156         }
10157
10158       Dwarf_Off str_offsets_base = str_offsets_base_off (dbg, (cu != NULL
10159                                                                ? cu->die.cu
10160                                                                : NULL));
10161
10162       const unsigned char *vendor[DW_MACRO_hi_user - DW_MACRO_lo_user + 1];
10163       memset (vendor, 0, sizeof vendor);
10164       if (flag & 0x04)
10165         {
10166           // 1 byte length, for each item, 1 byte opcode, uleb128 number
10167           // of arguments, for each argument 1 byte form code.
10168           if (readp + 1 > readendp)
10169             goto invalid_data;
10170           unsigned int tlen = *readp++;
10171           printf (_("  extension opcode table, %" PRIu8 " items:\n"),
10172                   tlen);
10173           for (unsigned int i = 0; i < tlen; i++)
10174             {
10175               if (readp + 1 > readendp)
10176                 goto invalid_data;
10177               unsigned int opcode = *readp++;
10178               printf (_("    [%" PRIx8 "]"), opcode);
10179               if (opcode < DW_MACRO_lo_user
10180                   || opcode > DW_MACRO_hi_user)
10181                 goto invalid_data;
10182               // Record the start of description for this vendor opcode.
10183               // uleb128 nr args, 1 byte per arg form.
10184               vendor[opcode - DW_MACRO_lo_user] = readp;
10185               if (readp + 1 > readendp)
10186                 goto invalid_data;
10187               unsigned int args = *readp++;
10188               if (args > 0)
10189                 {
10190                   printf (_(" %" PRIu8 " arguments:"), args);
10191                   while (args > 0)
10192                     {
10193                       if (readp + 1 > readendp)
10194                         goto invalid_data;
10195                       unsigned int form = *readp++;
10196                       printf (" %s", dwarf_form_name (form));
10197                       if (! libdw_valid_user_form (form))
10198                         goto invalid_data;
10199                       args--;
10200                       if (args > 0)
10201                         putchar_unlocked (',');
10202                     }
10203                 }
10204               else
10205                 printf (_(" no arguments."));
10206               putchar_unlocked ('\n');
10207             }
10208         }
10209       putchar_unlocked ('\n');
10210
10211       int level = 1;
10212       if (readp + 1 > readendp)
10213         goto invalid_data;
10214       unsigned int opcode = *readp++;
10215       while (opcode != 0)
10216         {
10217           unsigned int u128;
10218           unsigned int u128_2;
10219           const unsigned char *endp;
10220           uint64_t off;
10221
10222           switch (opcode)
10223             {
10224             case DW_MACRO_start_file:
10225               get_uleb128 (u128, readp, readendp);
10226               if (readp >= readendp)
10227                 goto invalid_data;
10228               get_uleb128 (u128_2, readp, readendp);
10229
10230               /* Find the CU DIE that matches this line offset.  */
10231               const char *fname = "???";
10232               if (cu != NULL)
10233                 {
10234                   if (cu->files == NULL
10235                       && dwarf_getsrcfiles (&cu->die, &cu->files,
10236                                             NULL) != 0)
10237                     cu->files = (Dwarf_Files *) -1l;
10238
10239                   if (cu->files != (Dwarf_Files *) -1l)
10240                     fname = (dwarf_filesrc (cu->files, u128_2,
10241                                             NULL, NULL) ?: "???");
10242                 }
10243               printf ("%*sstart_file %u, [%u] %s\n",
10244                       level, "", u128, u128_2, fname);
10245               ++level;
10246               break;
10247
10248             case DW_MACRO_end_file:
10249               --level;
10250               printf ("%*send_file\n", level, "");
10251               break;
10252
10253             case DW_MACRO_define:
10254               get_uleb128 (u128, readp, readendp);
10255               endp = memchr (readp, '\0', readendp - readp);
10256               if (endp == NULL)
10257                 goto invalid_data;
10258               printf ("%*s#define %s, line %u\n",
10259                       level, "", readp, u128);
10260               readp = endp + 1;
10261               break;
10262
10263             case DW_MACRO_undef:
10264               get_uleb128 (u128, readp, readendp);
10265               endp = memchr (readp, '\0', readendp - readp);
10266               if (endp == NULL)
10267                 goto invalid_data;
10268               printf ("%*s#undef %s, line %u\n",
10269                       level, "", readp, u128);
10270               readp = endp + 1;
10271               break;
10272
10273             case DW_MACRO_define_strp:
10274               get_uleb128 (u128, readp, readendp);
10275               if (readp + offset_len > readendp)
10276                 goto invalid_data;
10277               if (offset_len == 8)
10278                 off = read_8ubyte_unaligned_inc (dbg, readp);
10279               else
10280                 off = read_4ubyte_unaligned_inc (dbg, readp);
10281               printf ("%*s#define %s, line %u (indirect)\n",
10282                       level, "", dwarf_getstring (dbg, off, NULL), u128);
10283               break;
10284
10285             case DW_MACRO_undef_strp:
10286               get_uleb128 (u128, readp, readendp);
10287               if (readp + offset_len > readendp)
10288                 goto invalid_data;
10289               if (offset_len == 8)
10290                 off = read_8ubyte_unaligned_inc (dbg, readp);
10291               else
10292                 off = read_4ubyte_unaligned_inc (dbg, readp);
10293               printf ("%*s#undef %s, line %u (indirect)\n",
10294                       level, "", dwarf_getstring (dbg, off, NULL), u128);
10295               break;
10296
10297             case DW_MACRO_import:
10298               if (readp + offset_len > readendp)
10299                 goto invalid_data;
10300               if (offset_len == 8)
10301                 off = read_8ubyte_unaligned_inc (dbg, readp);
10302               else
10303                 off = read_4ubyte_unaligned_inc (dbg, readp);
10304               printf ("%*s#include offset 0x%" PRIx64 "\n",
10305                       level, "", off);
10306               break;
10307
10308             case DW_MACRO_define_sup:
10309               get_uleb128 (u128, readp, readendp);
10310               if (readp + offset_len > readendp)
10311                 goto invalid_data;
10312               printf ("%*s#define ", level, "");
10313               readp =  print_form_data (dbg, DW_FORM_strp_sup,
10314                                         readp, readendp, offset_len,
10315                                         str_offsets_base);
10316               printf (", line %u (sup)\n", u128);
10317               break;
10318
10319             case DW_MACRO_undef_sup:
10320               get_uleb128 (u128, readp, readendp);
10321               if (readp + offset_len > readendp)
10322                 goto invalid_data;
10323               printf ("%*s#undef ", level, "");
10324               readp =  print_form_data (dbg, DW_FORM_strp_sup,
10325                                         readp, readendp, offset_len,
10326                                         str_offsets_base);
10327               printf (", line %u (sup)\n", u128);
10328               break;
10329
10330             case DW_MACRO_import_sup:
10331               if (readp + offset_len > readendp)
10332                 goto invalid_data;
10333               if (offset_len == 8)
10334                 off = read_8ubyte_unaligned_inc (dbg, readp);
10335               else
10336                 off = read_4ubyte_unaligned_inc (dbg, readp);
10337               // XXX Needs support for reading from supplementary object file.
10338               printf ("%*s#include offset 0x%" PRIx64 " (sup)\n",
10339                       level, "", off);
10340               break;
10341
10342             case DW_MACRO_define_strx:
10343               get_uleb128 (u128, readp, readendp);
10344               if (readp + offset_len > readendp)
10345                 goto invalid_data;
10346               printf ("%*s#define ", level, "");
10347               readp =  print_form_data (dbg, DW_FORM_strx,
10348                                         readp, readendp, offset_len,
10349                                         str_offsets_base);
10350               printf (", line %u (strx)\n", u128);
10351               break;
10352
10353             case DW_MACRO_undef_strx:
10354               get_uleb128 (u128, readp, readendp);
10355               if (readp + offset_len > readendp)
10356                 goto invalid_data;
10357               printf ("%*s#undef ", level, "");
10358               readp =  print_form_data (dbg, DW_FORM_strx,
10359                                         readp, readendp, offset_len,
10360                                         str_offsets_base);
10361               printf (", line %u (strx)\n", u128);
10362               break;
10363
10364             default:
10365               printf ("%*svendor opcode 0x%" PRIx8, level, "", opcode);
10366               if (opcode < DW_MACRO_lo_user
10367                   || opcode > DW_MACRO_lo_user
10368                   || vendor[opcode - DW_MACRO_lo_user] == NULL)
10369                 goto invalid_data;
10370
10371               const unsigned char *op_desc;
10372               op_desc = vendor[opcode - DW_MACRO_lo_user];
10373
10374               // Just skip the arguments, we cannot really interpret them,
10375               // but print as much as we can.
10376               unsigned int args = *op_desc++;
10377               while (args > 0 && readp < readendp)
10378                 {
10379                   unsigned int form = *op_desc++;
10380                   readp = print_form_data (dbg, form, readp, readendp,
10381                                            offset_len, str_offsets_base);
10382                   args--;
10383                   if (args > 0)
10384                     printf (", ");
10385                 }
10386               putchar_unlocked ('\n');
10387             }
10388
10389           if (readp + 1 > readendp)
10390             goto invalid_data;
10391           opcode = *readp++;
10392           if (opcode == 0)
10393             putchar_unlocked ('\n');
10394         }
10395     }
10396 }
10397
10398
10399 /* Callback for printing global names.  */
10400 static int
10401 print_pubnames (Dwarf *dbg __attribute__ ((unused)), Dwarf_Global *global,
10402                 void *arg)
10403 {
10404   int *np = (int *) arg;
10405
10406   printf (_(" [%5d] DIE offset: %6" PRId64
10407                    ", CU DIE offset: %6" PRId64 ", name: %s\n"),
10408           (*np)++, global->die_offset, global->cu_offset, global->name);
10409
10410   return 0;
10411 }
10412
10413
10414 /* Print the known exported symbols in the DWARF section '.debug_pubnames'.  */
10415 static void
10416 print_debug_pubnames_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
10417                               Ebl *ebl,
10418                               GElf_Ehdr *ehdr __attribute__ ((unused)),
10419                               Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
10420 {
10421   printf (_("\nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
10422           elf_ndxscn (scn), section_name (ebl, shdr),
10423           (uint64_t) shdr->sh_offset);
10424
10425   int n = 0;
10426   (void) dwarf_getpubnames (dbg, print_pubnames, &n, 0);
10427 }
10428
10429 /* Print the content of the DWARF string section '.debug_str'.  */
10430 static void
10431 print_debug_str_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
10432                          Ebl *ebl,
10433                          GElf_Ehdr *ehdr __attribute__ ((unused)),
10434                          Elf_Scn *scn, GElf_Shdr *shdr,
10435                          Dwarf *dbg __attribute__ ((unused)))
10436 {
10437   Elf_Data *data = elf_rawdata (scn, NULL);
10438   const size_t sh_size = data ? data->d_size : 0;
10439
10440   /* Compute floor(log16(shdr->sh_size)).  */
10441   GElf_Addr tmp = sh_size;
10442   int digits = 1;
10443   while (tmp >= 16)
10444     {
10445       ++digits;
10446       tmp >>= 4;
10447     }
10448   digits = MAX (4, digits);
10449
10450   printf (_("\nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"
10451                    " %*s  String\n"),
10452           elf_ndxscn (scn),
10453           section_name (ebl, shdr), (uint64_t) shdr->sh_offset,
10454           /* TRANS: the debugstr| prefix makes the string unique.  */
10455           digits + 2, sgettext ("debugstr|Offset"));
10456
10457   Dwarf_Off offset = 0;
10458   while (offset < sh_size)
10459     {
10460       size_t len;
10461       const char *str = (const char *) data->d_buf + offset;
10462       const char *endp = memchr (str, '\0', sh_size - offset);
10463       if (unlikely (endp == NULL))
10464         {
10465           printf (_(" *** error, missing string terminator\n"));
10466           break;
10467         }
10468
10469       printf (" [%*" PRIx64 "]  \"%s\"\n", digits, (uint64_t) offset, str);
10470       len = endp - str;
10471       offset += len + 1;
10472     }
10473 }
10474
10475 static void
10476 print_debug_str_offsets_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
10477                                  Ebl *ebl,
10478                                  GElf_Ehdr *ehdr __attribute__ ((unused)),
10479                                  Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
10480 {
10481   printf (_("\
10482 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
10483           elf_ndxscn (scn), section_name (ebl, shdr),
10484           (uint64_t) shdr->sh_offset);
10485
10486   if (shdr->sh_size == 0)
10487     return;
10488
10489   /* We like to get the section from libdw to make sure they are relocated.  */
10490   Elf_Data *data = (dbg->sectiondata[IDX_debug_str_offsets]
10491                     ?: elf_rawdata (scn, NULL));
10492   if (unlikely (data == NULL))
10493     {
10494       error (0, 0, _("cannot get .debug_str_offsets section data: %s"),
10495              elf_errmsg (-1));
10496       return;
10497     }
10498
10499   size_t idx = 0;
10500   sort_listptr (&known_stroffbases, "str_offsets");
10501
10502   const unsigned char *start = (const unsigned char *) data->d_buf;
10503   const unsigned char *readp = start;
10504   const unsigned char *readendp = ((const unsigned char *) data->d_buf
10505                                    + data->d_size);
10506
10507   while (readp < readendp)
10508     {
10509       /* Most string offset tables will have a header.  For split
10510          dwarf unit GNU DebugFission didn't add one.  But they were
10511          also only defined for split units (main or skeleton units
10512          didn't have indirect strings).  So if we don't have a
10513          DW_AT_str_offsets_base at all and this is offset zero, then
10514          just start printing offsets immediately, if this is a .dwo
10515          section.  */
10516       Dwarf_Off off = (Dwarf_Off) (readp
10517                                    - (const unsigned char *) data->d_buf);
10518
10519       printf ("Table at offset %" PRIx64 " ", off);
10520
10521       struct listptr *listptr = get_listptr (&known_stroffbases, idx++);
10522       const unsigned char *next_unitp = readendp;
10523       uint8_t offset_size;
10524       bool has_header;
10525       if (listptr == NULL)
10526         {
10527           /* This can happen for .dwo files.  There is only an header
10528              in the case this is a version 5 split DWARF file.  */
10529           Dwarf_CU *cu;
10530           uint8_t unit_type;
10531           if (dwarf_get_units (dbg, NULL, &cu, NULL, &unit_type,
10532                                NULL, NULL) != 0)
10533             {
10534               error (0, 0, "Warning: Cannot find any DWARF unit.");
10535               /* Just guess some values.  */
10536               has_header = false;
10537               offset_size = 4;
10538             }
10539           else if (off == 0
10540                    && (unit_type == DW_UT_split_type
10541                        || unit_type == DW_UT_split_compile))
10542             {
10543               has_header = cu->version > 4;
10544               offset_size = cu->offset_size;
10545             }
10546           else
10547             {
10548               error (0, 0,
10549                      "Warning: No CU references .debug_str_offsets after %"
10550                      PRIx64, off);
10551               has_header = cu->version > 4;
10552               offset_size = cu->offset_size;
10553             }
10554           printf ("\n");
10555         }
10556       else
10557         {
10558           /* This must be DWARF5, since GNU DebugFission didn't define
10559              DW_AT_str_offsets_base.  */
10560           has_header = true;
10561
10562           Dwarf_Die cudie;
10563           if (dwarf_cu_die (listptr->cu, &cudie,
10564                             NULL, NULL, NULL, NULL,
10565                             NULL, NULL) == NULL)
10566             printf ("Unknown CU (%s):\n", dwarf_errmsg (-1));
10567           else
10568             printf ("for CU [%6" PRIx64 "]:\n", dwarf_dieoffset (&cudie));
10569         }
10570
10571       if (has_header)
10572         {
10573           uint64_t unit_length;
10574           uint16_t version;
10575           uint16_t padding;
10576
10577           unit_length = read_4ubyte_unaligned_inc (dbg, readp);
10578           if (unlikely (unit_length == 0xffffffff))
10579             {
10580               if (unlikely (readp > readendp - 8))
10581                 {
10582                 invalid_data:
10583                   error (0, 0, "Invalid data");
10584                   return;
10585                 }
10586               unit_length = read_8ubyte_unaligned_inc (dbg, readp);
10587               offset_size = 8;
10588             }
10589           else
10590             offset_size = 4;
10591
10592           printf ("\n");
10593           printf (_(" Length:        %8" PRIu64 "\n"),
10594                   unit_length);
10595           printf (_(" Offset size:   %8" PRIu8 "\n"),
10596                   offset_size);
10597
10598           /* We need at least 2-bytes (version) + 2-bytes (padding) =
10599              4 bytes to complete the header.  And this unit cannot go
10600              beyond the section data.  */
10601           if (readp > readendp - 4
10602               || unit_length < 4
10603               || unit_length > (uint64_t) (readendp - readp))
10604             goto invalid_data;
10605
10606           next_unitp = readp + unit_length;
10607
10608           version = read_2ubyte_unaligned_inc (dbg, readp);
10609           printf (_(" DWARF version: %8" PRIu16 "\n"), version);
10610
10611           if (version != 5)
10612             {
10613               error (0, 0, _("Unknown version"));
10614               goto next_unit;
10615             }
10616
10617           padding = read_2ubyte_unaligned_inc (dbg, readp);
10618           printf (_(" Padding:       %8" PRIx16 "\n"), padding);
10619
10620           if (listptr != NULL
10621               && listptr->offset != (Dwarf_Off) (readp - start))
10622             {
10623               error (0, 0, "String offsets index doesn't start after header");
10624               goto next_unit;
10625             }
10626
10627           printf ("\n");
10628         }
10629
10630       int digits = 1;
10631       size_t offsets = (next_unitp - readp) / offset_size;
10632       while (offsets >= 10)
10633         {
10634           ++digits;
10635           offsets /= 10;
10636         }
10637
10638       unsigned int uidx = 0;
10639       size_t index_offset =  readp - (const unsigned char *) data->d_buf;
10640       printf (" Offsets start at 0x%zx:\n", index_offset);
10641       while (readp <= next_unitp - offset_size)
10642         {
10643           Dwarf_Word offset;
10644           if (offset_size == 4)
10645             offset = read_4ubyte_unaligned_inc (dbg, readp);
10646           else
10647             offset = read_8ubyte_unaligned_inc (dbg, readp);
10648           const char *str = dwarf_getstring (dbg, offset, NULL);
10649           printf (" [%*u] [%*" PRIx64 "]  \"%s\"\n",
10650                   digits, uidx++, (int) offset_size * 2, offset, str ?: "???");
10651         }
10652       printf ("\n");
10653
10654       if (readp != next_unitp)
10655         error (0, 0, "extra %zd bytes at end of unit",
10656                (size_t) (next_unitp - readp));
10657
10658     next_unit:
10659       readp = next_unitp;
10660     }
10661 }
10662
10663
10664 /* Print the content of the call frame search table section
10665    '.eh_frame_hdr'.  */
10666 static void
10667 print_debug_frame_hdr_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
10668                                Ebl *ebl __attribute__ ((unused)),
10669                                GElf_Ehdr *ehdr __attribute__ ((unused)),
10670                                Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
10671 {
10672   printf (_("\
10673 \nCall frame search table section [%2zu] '.eh_frame_hdr':\n"),
10674           elf_ndxscn (scn));
10675
10676   Elf_Data *data = elf_rawdata (scn, NULL);
10677
10678   if (unlikely (data == NULL))
10679     {
10680       error (0, 0, _("cannot get %s content: %s"),
10681              ".eh_frame_hdr", elf_errmsg (-1));
10682       return;
10683     }
10684
10685   const unsigned char *readp = data->d_buf;
10686   const unsigned char *const dataend = ((unsigned char *) data->d_buf
10687                                         + data->d_size);
10688
10689   if (unlikely (readp + 4 > dataend))
10690     {
10691     invalid_data:
10692       error (0, 0, _("invalid data"));
10693       return;
10694     }
10695
10696   unsigned int version = *readp++;
10697   unsigned int eh_frame_ptr_enc = *readp++;
10698   unsigned int fde_count_enc = *readp++;
10699   unsigned int table_enc = *readp++;
10700
10701   printf (" version:          %u\n"
10702           " eh_frame_ptr_enc: %#x ",
10703           version, eh_frame_ptr_enc);
10704   print_encoding_base ("", eh_frame_ptr_enc);
10705   printf (" fde_count_enc:    %#x ", fde_count_enc);
10706   print_encoding_base ("", fde_count_enc);
10707   printf (" table_enc:        %#x ", table_enc);
10708   print_encoding_base ("", table_enc);
10709
10710   uint64_t eh_frame_ptr = 0;
10711   if (eh_frame_ptr_enc != DW_EH_PE_omit)
10712     {
10713       readp = read_encoded (eh_frame_ptr_enc, readp, dataend, &eh_frame_ptr,
10714                             dbg);
10715       if (unlikely (readp == NULL))
10716         goto invalid_data;
10717
10718       printf (" eh_frame_ptr:     %#" PRIx64, eh_frame_ptr);
10719       if ((eh_frame_ptr_enc & 0x70) == DW_EH_PE_pcrel)
10720         printf (" (offset: %#" PRIx64 ")",
10721                 /* +4 because of the 4 byte header of the section.  */
10722                 (uint64_t) shdr->sh_offset + 4 + eh_frame_ptr);
10723
10724       putchar_unlocked ('\n');
10725     }
10726
10727   uint64_t fde_count = 0;
10728   if (fde_count_enc != DW_EH_PE_omit)
10729     {
10730       readp = read_encoded (fde_count_enc, readp, dataend, &fde_count, dbg);
10731       if (unlikely (readp == NULL))
10732         goto invalid_data;
10733
10734       printf (" fde_count:        %" PRIu64 "\n", fde_count);
10735     }
10736
10737   if (fde_count == 0 || table_enc == DW_EH_PE_omit)
10738     return;
10739
10740   puts (" Table:");
10741
10742   /* Optimize for the most common case.  */
10743   if (table_enc == (DW_EH_PE_datarel | DW_EH_PE_sdata4))
10744     while (fde_count > 0 && readp + 8 <= dataend)
10745       {
10746         int32_t initial_location = read_4sbyte_unaligned_inc (dbg, readp);
10747         uint64_t initial_offset = ((uint64_t) shdr->sh_offset
10748                                    + (int64_t) initial_location);
10749         int32_t address = read_4sbyte_unaligned_inc (dbg, readp);
10750         // XXX Possibly print symbol name or section offset for initial_offset
10751         printf ("  %#" PRIx32 " (offset: %#6" PRIx64 ") -> %#" PRIx32
10752                 " fde=[%6" PRIx64 "]\n",
10753                 initial_location, initial_offset,
10754                 address, address - (eh_frame_ptr + 4));
10755       }
10756   else
10757     while (0 && readp < dataend)
10758       {
10759
10760       }
10761 }
10762
10763
10764 /* Print the content of the exception handling table section
10765    '.eh_frame_hdr'.  */
10766 static void
10767 print_debug_exception_table (Dwfl_Module *dwflmod __attribute__ ((unused)),
10768                              Ebl *ebl __attribute__ ((unused)),
10769                              GElf_Ehdr *ehdr __attribute__ ((unused)),
10770                              Elf_Scn *scn,
10771                              GElf_Shdr *shdr __attribute__ ((unused)),
10772                              Dwarf *dbg __attribute__ ((unused)))
10773 {
10774   printf (_("\
10775 \nException handling table section [%2zu] '.gcc_except_table':\n"),
10776           elf_ndxscn (scn));
10777
10778   Elf_Data *data = elf_rawdata (scn, NULL);
10779
10780   if (unlikely (data == NULL))
10781     {
10782       error (0, 0, _("cannot get %s content: %s"),
10783              ".gcc_except_table", elf_errmsg (-1));
10784       return;
10785     }
10786
10787   const unsigned char *readp = data->d_buf;
10788   const unsigned char *const dataend = readp + data->d_size;
10789
10790   if (unlikely (readp + 1 > dataend))
10791     {
10792     invalid_data:
10793       error (0, 0, _("invalid data"));
10794       return;
10795     }
10796   unsigned int lpstart_encoding = *readp++;
10797   printf (_(" LPStart encoding:    %#x "), lpstart_encoding);
10798   print_encoding_base ("", lpstart_encoding);
10799   if (lpstart_encoding != DW_EH_PE_omit)
10800     {
10801       uint64_t lpstart;
10802       readp = read_encoded (lpstart_encoding, readp, dataend, &lpstart, dbg);
10803       printf (" LPStart:             %#" PRIx64 "\n", lpstart);
10804     }
10805
10806   if (unlikely (readp + 1 > dataend))
10807     goto invalid_data;
10808   unsigned int ttype_encoding = *readp++;
10809   printf (_(" TType encoding:      %#x "), ttype_encoding);
10810   print_encoding_base ("", ttype_encoding);
10811   const unsigned char *ttype_base = NULL;
10812   if (ttype_encoding != DW_EH_PE_omit)
10813     {
10814       unsigned int ttype_base_offset;
10815       get_uleb128 (ttype_base_offset, readp, dataend);
10816       printf (" TType base offset:   %#x\n", ttype_base_offset);
10817       if ((size_t) (dataend - readp) > ttype_base_offset)
10818         ttype_base = readp + ttype_base_offset;
10819     }
10820
10821   if (unlikely (readp + 1 > dataend))
10822     goto invalid_data;
10823   unsigned int call_site_encoding = *readp++;
10824   printf (_(" Call site encoding:  %#x "), call_site_encoding);
10825   print_encoding_base ("", call_site_encoding);
10826   unsigned int call_site_table_len;
10827   get_uleb128 (call_site_table_len, readp, dataend);
10828
10829   const unsigned char *const action_table = readp + call_site_table_len;
10830   if (unlikely (action_table > dataend))
10831     goto invalid_data;
10832   unsigned int u = 0;
10833   unsigned int max_action = 0;
10834   while (readp < action_table)
10835     {
10836       if (u == 0)
10837         puts (_("\n Call site table:"));
10838
10839       uint64_t call_site_start;
10840       readp = read_encoded (call_site_encoding, readp, dataend,
10841                             &call_site_start, dbg);
10842       uint64_t call_site_length;
10843       readp = read_encoded (call_site_encoding, readp, dataend,
10844                             &call_site_length, dbg);
10845       uint64_t landing_pad;
10846       readp = read_encoded (call_site_encoding, readp, dataend,
10847                             &landing_pad, dbg);
10848       unsigned int action;
10849       get_uleb128 (action, readp, dataend);
10850       max_action = MAX (action, max_action);
10851       printf (_(" [%4u] Call site start:   %#" PRIx64 "\n"
10852                        "        Call site length:  %" PRIu64 "\n"
10853                        "        Landing pad:       %#" PRIx64 "\n"
10854                        "        Action:            %u\n"),
10855               u++, call_site_start, call_site_length, landing_pad, action);
10856     }
10857   if (readp != action_table)
10858     goto invalid_data;
10859
10860   unsigned int max_ar_filter = 0;
10861   if (max_action > 0)
10862     {
10863       puts ("\n Action table:");
10864
10865       size_t maxdata = (size_t) (dataend - action_table);
10866       if (max_action > maxdata || maxdata - max_action < 1)
10867         {
10868         invalid_action_table:
10869           fputs (_("   <INVALID DATA>\n"), stdout);
10870           return;
10871         }
10872
10873       const unsigned char *const action_table_end
10874         = action_table + max_action + 1;
10875
10876       u = 0;
10877       do
10878         {
10879           int ar_filter;
10880           get_sleb128 (ar_filter, readp, action_table_end);
10881           if (ar_filter > 0 && (unsigned int) ar_filter > max_ar_filter)
10882             max_ar_filter = ar_filter;
10883           int ar_disp;
10884           if (readp >= action_table_end)
10885             goto invalid_action_table;
10886           get_sleb128 (ar_disp, readp, action_table_end);
10887
10888           printf (" [%4u] ar_filter:  % d\n"
10889                   "        ar_disp:    % -5d",
10890                   u, ar_filter, ar_disp);
10891           if (abs (ar_disp) & 1)
10892             printf (" -> [%4u]\n", u + (ar_disp + 1) / 2);
10893           else if (ar_disp != 0)
10894             puts (" -> ???");
10895           else
10896             putchar_unlocked ('\n');
10897           ++u;
10898         }
10899       while (readp < action_table_end);
10900     }
10901
10902   if (max_ar_filter > 0 && ttype_base != NULL)
10903     {
10904       unsigned char dsize;
10905       puts ("\n TType table:");
10906
10907       // XXX Not *4, size of encoding;
10908       switch (ttype_encoding & 7)
10909         {
10910         case DW_EH_PE_udata2:
10911         case DW_EH_PE_sdata2:
10912           dsize = 2;
10913           break;
10914         case DW_EH_PE_udata4:
10915         case DW_EH_PE_sdata4:
10916           dsize = 4;
10917           break;
10918         case DW_EH_PE_udata8:
10919         case DW_EH_PE_sdata8:
10920           dsize = 8;
10921           break;
10922         default:
10923           dsize = 0;
10924           error (1, 0, _("invalid TType encoding"));
10925         }
10926
10927       if (max_ar_filter
10928           > (size_t) (ttype_base - (const unsigned char *) data->d_buf) / dsize)
10929         goto invalid_data;
10930
10931       readp = ttype_base - max_ar_filter * dsize;
10932       do
10933         {
10934           uint64_t ttype;
10935           readp = read_encoded (ttype_encoding, readp, ttype_base, &ttype,
10936                                 dbg);
10937           printf (" [%4u] %#" PRIx64 "\n", max_ar_filter--, ttype);
10938         }
10939       while (readp < ttype_base);
10940     }
10941 }
10942
10943 /* Print the content of the '.gdb_index' section.
10944    http://sourceware.org/gdb/current/onlinedocs/gdb/Index-Section-Format.html
10945 */
10946 static void
10947 print_gdb_index_section (Dwfl_Module *dwflmod, Ebl *ebl,
10948                          GElf_Ehdr *ehdr __attribute__ ((unused)),
10949                          Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
10950 {
10951   printf (_("\nGDB section [%2zu] '%s' at offset %#" PRIx64
10952                    " contains %" PRId64 " bytes :\n"),
10953           elf_ndxscn (scn), section_name (ebl, shdr),
10954           (uint64_t) shdr->sh_offset, (uint64_t) shdr->sh_size);
10955
10956   Elf_Data *data = elf_rawdata (scn, NULL);
10957
10958   if (unlikely (data == NULL))
10959     {
10960       error (0, 0, _("cannot get %s content: %s"),
10961              ".gdb_index", elf_errmsg (-1));
10962       return;
10963     }
10964
10965   // .gdb_index is always in little endian.
10966   Dwarf dummy_dbg = { .other_byte_order = MY_ELFDATA != ELFDATA2LSB };
10967   dbg = &dummy_dbg;
10968
10969   const unsigned char *readp = data->d_buf;
10970   const unsigned char *const dataend = readp + data->d_size;
10971
10972   if (unlikely (readp + 4 > dataend))
10973     {
10974     invalid_data:
10975       error (0, 0, _("invalid data"));
10976       return;
10977     }
10978
10979   int32_t vers = read_4ubyte_unaligned (dbg, readp);
10980   printf (_(" Version:         %" PRId32 "\n"), vers);
10981
10982   // The only difference between version 4 and version 5 is the
10983   // hash used for generating the table.  Version 6 contains symbols
10984   // for inlined functions, older versions didn't.  Version 7 adds
10985   // symbol kinds.  Version 8 just indicates that it correctly includes
10986   // TUs for symbols.
10987   if (vers < 4 || vers > 8)
10988     {
10989       printf (_("  unknown version, cannot parse section\n"));
10990       return;
10991     }
10992
10993   readp += 4;
10994   if (unlikely (readp + 4 > dataend))
10995     goto invalid_data;
10996
10997   uint32_t cu_off = read_4ubyte_unaligned (dbg, readp);
10998   printf (_(" CU offset:       %#" PRIx32 "\n"), cu_off);
10999
11000   readp += 4;
11001   if (unlikely (readp + 4 > dataend))
11002     goto invalid_data;
11003
11004   uint32_t tu_off = read_4ubyte_unaligned (dbg, readp);
11005   printf (_(" TU offset:       %#" PRIx32 "\n"), tu_off);
11006
11007   readp += 4;
11008   if (unlikely (readp + 4 > dataend))
11009     goto invalid_data;
11010
11011   uint32_t addr_off = read_4ubyte_unaligned (dbg, readp);
11012   printf (_(" address offset:  %#" PRIx32 "\n"), addr_off);
11013
11014   readp += 4;
11015   if (unlikely (readp + 4 > dataend))
11016     goto invalid_data;
11017
11018   uint32_t sym_off = read_4ubyte_unaligned (dbg, readp);
11019   printf (_(" symbol offset:   %#" PRIx32 "\n"), sym_off);
11020
11021   readp += 4;
11022   if (unlikely (readp + 4 > dataend))
11023     goto invalid_data;
11024
11025   uint32_t const_off = read_4ubyte_unaligned (dbg, readp);
11026   printf (_(" constant offset: %#" PRIx32 "\n"), const_off);
11027
11028   if (unlikely ((size_t) (dataend - (const unsigned char *) data->d_buf)
11029                 < const_off))
11030     goto invalid_data;
11031
11032   readp = data->d_buf + cu_off;
11033
11034   const unsigned char *nextp = data->d_buf + tu_off;
11035   if (tu_off >= data->d_size)
11036     goto invalid_data;
11037
11038   size_t cu_nr = (nextp - readp) / 16;
11039
11040   printf (_("\n CU list at offset %#" PRIx32
11041                    " contains %zu entries:\n"),
11042           cu_off, cu_nr);
11043
11044   size_t n = 0;
11045   while (dataend - readp >= 16 && n < cu_nr)
11046     {
11047       uint64_t off = read_8ubyte_unaligned (dbg, readp);
11048       readp += 8;
11049
11050       uint64_t len = read_8ubyte_unaligned (dbg, readp);
11051       readp += 8;
11052
11053       printf (" [%4zu] start: %0#8" PRIx64
11054               ", length: %5" PRIu64 "\n", n, off, len);
11055       n++;
11056     }
11057
11058   readp = data->d_buf + tu_off;
11059   nextp = data->d_buf + addr_off;
11060   if (addr_off >= data->d_size)
11061     goto invalid_data;
11062
11063   size_t tu_nr = (nextp - readp) / 24;
11064
11065   printf (_("\n TU list at offset %#" PRIx32
11066                    " contains %zu entries:\n"),
11067           tu_off, tu_nr);
11068
11069   n = 0;
11070   while (dataend - readp >= 24 && n < tu_nr)
11071     {
11072       uint64_t off = read_8ubyte_unaligned (dbg, readp);
11073       readp += 8;
11074
11075       uint64_t type = read_8ubyte_unaligned (dbg, readp);
11076       readp += 8;
11077
11078       uint64_t sig = read_8ubyte_unaligned (dbg, readp);
11079       readp += 8;
11080
11081       printf (" [%4zu] CU offset: %5" PRId64
11082               ", type offset: %5" PRId64
11083               ", signature: %0#8" PRIx64 "\n", n, off, type, sig);
11084       n++;
11085     }
11086
11087   readp = data->d_buf + addr_off;
11088   nextp = data->d_buf + sym_off;
11089   if (sym_off >= data->d_size)
11090     goto invalid_data;
11091
11092   size_t addr_nr = (nextp - readp) / 20;
11093
11094   printf (_("\n Address list at offset %#" PRIx32
11095                    " contains %zu entries:\n"),
11096           addr_off, addr_nr);
11097
11098   n = 0;
11099   while (dataend - readp >= 20 && n < addr_nr)
11100     {
11101       uint64_t low = read_8ubyte_unaligned (dbg, readp);
11102       readp += 8;
11103
11104       uint64_t high = read_8ubyte_unaligned (dbg, readp);
11105       readp += 8;
11106
11107       uint32_t idx = read_4ubyte_unaligned (dbg, readp);
11108       readp += 4;
11109
11110       printf (" [%4zu] ", n);
11111       print_dwarf_addr (dwflmod, 8, low, low);
11112       printf ("..");
11113       print_dwarf_addr (dwflmod, 8, high - 1, high);
11114       printf (", CU index: %5" PRId32 "\n", idx);
11115       n++;
11116     }
11117
11118   const unsigned char *const_start = data->d_buf + const_off;
11119   if (const_off >= data->d_size)
11120     goto invalid_data;
11121
11122   readp = data->d_buf + sym_off;
11123   nextp = const_start;
11124   size_t sym_nr = (nextp - readp) / 8;
11125
11126   printf (_("\n Symbol table at offset %#" PRIx32
11127                    " contains %zu slots:\n"),
11128           addr_off, sym_nr);
11129
11130   n = 0;
11131   while (dataend - readp >= 8 && n < sym_nr)
11132     {
11133       uint32_t name = read_4ubyte_unaligned (dbg, readp);
11134       readp += 4;
11135
11136       uint32_t vector = read_4ubyte_unaligned (dbg, readp);
11137       readp += 4;
11138
11139       if (name != 0 || vector != 0)
11140         {
11141           const unsigned char *sym = const_start + name;
11142           if (unlikely ((size_t) (dataend - const_start) < name
11143                         || memchr (sym, '\0', dataend - sym) == NULL))
11144             goto invalid_data;
11145
11146           printf (" [%4zu] symbol: %s, CUs: ", n, sym);
11147
11148           const unsigned char *readcus = const_start + vector;
11149           if (unlikely ((size_t) (dataend - const_start) < vector))
11150             goto invalid_data;
11151           uint32_t cus = read_4ubyte_unaligned (dbg, readcus);
11152           while (cus--)
11153             {
11154               uint32_t cu_kind, cu, kind;
11155               bool is_static;
11156               readcus += 4;
11157               if (unlikely (readcus + 4 > dataend))
11158                 goto invalid_data;
11159               cu_kind = read_4ubyte_unaligned (dbg, readcus);
11160               cu = cu_kind & ((1 << 24) - 1);
11161               kind = (cu_kind >> 28) & 7;
11162               is_static = cu_kind & (1U << 31);
11163               if (cu > cu_nr - 1)
11164                 printf ("%" PRId32 "T", cu - (uint32_t) cu_nr);
11165               else
11166                 printf ("%" PRId32, cu);
11167               if (kind != 0)
11168                 {
11169                   printf (" (");
11170                   switch (kind)
11171                     {
11172                     case 1:
11173                       printf ("type");
11174                       break;
11175                     case 2:
11176                       printf ("var");
11177                       break;
11178                     case 3:
11179                       printf ("func");
11180                       break;
11181                     case 4:
11182                       printf ("other");
11183                       break;
11184                     default:
11185                       printf ("unknown-0x%" PRIx32, kind);
11186                       break;
11187                     }
11188                   printf (":%c)", (is_static ? 'S' : 'G'));
11189                 }
11190               if (cus > 0)
11191                 printf (", ");
11192             }
11193           printf ("\n");
11194         }
11195       n++;
11196     }
11197 }
11198
11199 /* Returns true and sets split DWARF CU id if there is a split compile
11200    unit in the given Dwarf, and no non-split units are found (before it).  */
11201 static bool
11202 is_split_dwarf (Dwarf *dbg, uint64_t *id, Dwarf_CU **split_cu)
11203 {
11204   Dwarf_CU *cu = NULL;
11205   while (dwarf_get_units (dbg, cu, &cu, NULL, NULL, NULL, NULL) == 0)
11206     {
11207       uint8_t unit_type;
11208       if (dwarf_cu_info (cu, NULL, &unit_type, NULL, NULL,
11209                          id, NULL, NULL) != 0)
11210         return false;
11211
11212       if (unit_type != DW_UT_split_compile && unit_type != DW_UT_split_type)
11213         return false;
11214
11215       /* We really only care about the split compile unit, the types
11216          should be fine and self sufficient.  Also they don't have an
11217          id that we can match with a skeleton unit.  */
11218       if (unit_type == DW_UT_split_compile)
11219         {
11220           *split_cu = cu;
11221           return true;
11222         }
11223     }
11224
11225   return false;
11226 }
11227
11228 /* Check that there is one and only one Dwfl_Module, return in arg.  */
11229 static int
11230 getone_dwflmod (Dwfl_Module *dwflmod,
11231                void **userdata __attribute__ ((unused)),
11232                const char *name __attribute__ ((unused)),
11233                Dwarf_Addr base __attribute__ ((unused)),
11234                void *arg)
11235 {
11236   Dwfl_Module **m = (Dwfl_Module **) arg;
11237   if (*m != NULL)
11238     return DWARF_CB_ABORT;
11239   *m = dwflmod;
11240   return DWARF_CB_OK;
11241 }
11242
11243 static void
11244 print_debug (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr)
11245 {
11246   /* Used for skeleton file, if necessary for split DWARF.  */
11247   Dwfl *skel_dwfl = NULL;
11248   Dwfl_Module *skel_mod = NULL;
11249   char *skel_name = NULL;
11250   Dwarf *split_dbg = NULL;
11251   Dwarf_CU *split_cu = NULL;
11252
11253   /* Before we start the real work get a debug context descriptor.  */
11254   Dwarf_Addr dwbias;
11255   Dwarf *dbg = dwfl_module_getdwarf (dwflmod, &dwbias);
11256   Dwarf dummy_dbg =
11257     {
11258       .elf = ebl->elf,
11259       .other_byte_order = MY_ELFDATA != ehdr->e_ident[EI_DATA]
11260     };
11261   if (dbg == NULL)
11262     {
11263       if ((print_debug_sections & ~(section_exception|section_frame)) != 0)
11264         error (0, 0, _("cannot get debug context descriptor: %s"),
11265                dwfl_errmsg (-1));
11266       dbg = &dummy_dbg;
11267     }
11268   else
11269     {
11270       /* If we are asked about a split dwarf (.dwo) file, use the user
11271          provided, or find the corresponding skeleton file. If we got
11272          a skeleton file, replace the given dwflmod and dbg, with one
11273          derived from the skeleton file to provide enough context.  */
11274       uint64_t split_id;
11275       if (is_split_dwarf (dbg, &split_id, &split_cu))
11276         {
11277           if (dwarf_skeleton != NULL)
11278             skel_name = strdup (dwarf_skeleton);
11279           else
11280             {
11281               /* Replace file.dwo with file.o and see if that matches. */
11282               const char *fname;
11283               dwfl_module_info (dwflmod, NULL, NULL, NULL, NULL, NULL,
11284                                 &fname, NULL);
11285               if (fname != NULL)
11286                 {
11287                   size_t flen = strlen (fname);
11288                   if (flen > 4 && strcmp (".dwo", fname + flen - 4) == 0)
11289                     {
11290                       skel_name = strdup (fname);
11291                       if (skel_name != NULL)
11292                         {
11293                           skel_name[flen - 3] = 'o';
11294                           skel_name[flen - 2] = '\0';
11295                         }
11296                     }
11297                 }
11298             }
11299
11300           if (skel_name != NULL)
11301             {
11302               int skel_fd = open (skel_name, O_RDONLY);
11303               if (skel_fd == -1)
11304                 fprintf (stderr, "Warning: Couldn't open DWARF skeleton file"
11305                          " '%s'\n", skel_name);
11306               else
11307                 skel_dwfl = create_dwfl (skel_fd, skel_name);
11308
11309               if (skel_dwfl != NULL)
11310                 {
11311                   if (dwfl_getmodules (skel_dwfl, &getone_dwflmod,
11312                                        &skel_mod, 0) != 0)
11313                     {
11314                       fprintf (stderr, "Warning: Bad DWARF skeleton,"
11315                                " multiple modules '%s'\n", skel_name);
11316                       dwfl_end (skel_dwfl);
11317                       skel_mod = NULL;
11318                     }
11319                 }
11320               else if (skel_fd != -1)
11321                 fprintf (stderr, "Warning: Couldn't create skeleton dwfl for"
11322                          " '%s': %s\n", skel_name, dwfl_errmsg (-1));
11323
11324               if (skel_mod != NULL)
11325                 {
11326                   Dwarf *skel_dbg = dwfl_module_getdwarf (skel_mod, &dwbias);
11327                   if (skel_dbg != NULL)
11328                     {
11329                       /* First check the skeleton CU DIE, only fetch
11330                          the split DIE if we know the id matches to
11331                          not unnecessary search for any split DIEs we
11332                          don't need. */
11333                       Dwarf_CU *cu = NULL;
11334                       while (dwarf_get_units (skel_dbg, cu, &cu,
11335                                               NULL, NULL, NULL, NULL) == 0)
11336                         {
11337                           uint8_t unit_type;
11338                           uint64_t skel_id;
11339                           if (dwarf_cu_info (cu, NULL, &unit_type, NULL, NULL,
11340                                              &skel_id, NULL, NULL) == 0
11341                               && unit_type == DW_UT_skeleton
11342                               && split_id == skel_id)
11343                             {
11344                               Dwarf_Die subdie;
11345                               if (dwarf_cu_info (cu, NULL, NULL, NULL,
11346                                                  &subdie,
11347                                                  NULL, NULL, NULL) == 0
11348                                   && dwarf_tag (&subdie) != DW_TAG_invalid)
11349                                 {
11350                                   split_dbg = dwarf_cu_getdwarf (subdie.cu);
11351                                   if (split_dbg == NULL)
11352                                     fprintf (stderr,
11353                                              "Warning: Couldn't get split_dbg:"
11354                                              " %s\n", dwarf_errmsg (-1));
11355                                   break;
11356                                 }
11357                               else
11358                                 {
11359                                   /* Everything matches up, but not
11360                                      according to libdw. Which means
11361                                      the user knew better.  So...
11362                                      Terrible hack... We can never
11363                                      destroy the underlying dwfl
11364                                      because it would free the wrong
11365                                      Dwarfs... So we leak memory...*/
11366                                   if (cu->split == NULL
11367                                       && dwarf_skeleton != NULL)
11368                                     {
11369                                       do_not_close_dwfl = true;
11370                                       __libdw_link_skel_split (cu, split_cu);
11371                                       split_dbg = dwarf_cu_getdwarf (split_cu);
11372                                       break;
11373                                     }
11374                                   else
11375                                     fprintf (stderr, "Warning: Couldn't get"
11376                                              " skeleton subdie: %s\n",
11377                                              dwarf_errmsg (-1));
11378                                 }
11379                             }
11380                         }
11381                       if (split_dbg == NULL)
11382                         fprintf (stderr, "Warning: '%s' didn't contain a skeleton for split id %" PRIx64 "\n", skel_name, split_id);
11383                     }
11384                   else
11385                     fprintf (stderr, "Warning: Couldn't get skeleton DWARF:"
11386                              " %s\n", dwfl_errmsg (-1));
11387                 }
11388             }
11389
11390           if (split_dbg != NULL)
11391             {
11392               dbg = split_dbg;
11393               dwflmod = skel_mod;
11394             }
11395           else if (skel_name == NULL)
11396             fprintf (stderr,
11397                      "Warning: split DWARF file, but no skeleton found.\n");
11398         }
11399       else if (dwarf_skeleton != NULL)
11400         fprintf (stderr, "Warning: DWARF skeleton given,"
11401                  " but not a split DWARF file\n");
11402     }
11403
11404   /* Get the section header string table index.  */
11405   size_t shstrndx;
11406   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
11407     error_exit (0, _("cannot get section header string table index"));
11408
11409   /* If the .debug_info section is listed as implicitly required then
11410      we must make sure to handle it before handling any other debug
11411      section.  Various other sections depend on the CU DIEs being
11412      scanned (silently) first.  */
11413   bool implicit_info = (implicit_debug_sections & section_info) != 0;
11414   bool explicit_info = (print_debug_sections & section_info) != 0;
11415   if (implicit_info)
11416     {
11417       Elf_Scn *scn = NULL;
11418       while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
11419         {
11420           GElf_Shdr shdr_mem;
11421           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
11422
11423           if (shdr != NULL && shdr->sh_type == SHT_PROGBITS)
11424             {
11425               const char *name = elf_strptr (ebl->elf, shstrndx,
11426                                              shdr->sh_name);
11427               if (name == NULL)
11428                 continue;
11429
11430               if (strcmp (name, ".debug_info") == 0
11431                   || strcmp (name, ".debug_info.dwo") == 0
11432                   || strcmp (name, ".zdebug_info") == 0
11433                   || strcmp (name, ".zdebug_info.dwo") == 0
11434                   || strcmp (name, ".gnu.debuglto_.debug_info") == 0)
11435                 {
11436                   print_debug_info_section (dwflmod, ebl, ehdr,
11437                                             scn, shdr, dbg);
11438                   break;
11439                 }
11440             }
11441         }
11442       print_debug_sections &= ~section_info;
11443       implicit_debug_sections &= ~section_info;
11444     }
11445
11446   /* Look through all the sections for the debugging sections to print.  */
11447   Elf_Scn *scn = NULL;
11448   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
11449     {
11450       GElf_Shdr shdr_mem;
11451       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
11452
11453       if (shdr != NULL && shdr->sh_type == SHT_PROGBITS)
11454         {
11455           static const struct
11456           {
11457             const char *name;
11458             enum section_e bitmask;
11459             void (*fp) (Dwfl_Module *, Ebl *,
11460                         GElf_Ehdr *, Elf_Scn *, GElf_Shdr *, Dwarf *);
11461           } debug_sections[] =
11462             {
11463 #define NEW_SECTION(name) \
11464               { ".debug_" #name, section_##name, print_debug_##name##_section }
11465               NEW_SECTION (abbrev),
11466               NEW_SECTION (addr),
11467               NEW_SECTION (aranges),
11468               NEW_SECTION (frame),
11469               NEW_SECTION (info),
11470               NEW_SECTION (types),
11471               NEW_SECTION (line),
11472               NEW_SECTION (loc),
11473               /* loclists is loc for DWARF5.  */
11474               { ".debug_loclists", section_loc,
11475                 print_debug_loclists_section },
11476               NEW_SECTION (pubnames),
11477               NEW_SECTION (str),
11478               /* A DWARF5 specialised debug string section.  */
11479               { ".debug_line_str", section_str,
11480                 print_debug_str_section },
11481               /* DWARF5 string offsets table.  */
11482               { ".debug_str_offsets", section_str,
11483                 print_debug_str_offsets_section },
11484               NEW_SECTION (macinfo),
11485               NEW_SECTION (macro),
11486               NEW_SECTION (ranges),
11487               /* rnglists is ranges for DWARF5.  */
11488               { ".debug_rnglists", section_ranges,
11489                 print_debug_rnglists_section },
11490               { ".eh_frame", section_frame | section_exception,
11491                 print_debug_frame_section },
11492               { ".eh_frame_hdr", section_frame | section_exception,
11493                 print_debug_frame_hdr_section },
11494               { ".gcc_except_table", section_frame | section_exception,
11495                 print_debug_exception_table },
11496               { ".gdb_index", section_gdb_index, print_gdb_index_section }
11497             };
11498           const int ndebug_sections = (sizeof (debug_sections)
11499                                        / sizeof (debug_sections[0]));
11500           const char *name = elf_strptr (ebl->elf, shstrndx,
11501                                          shdr->sh_name);
11502           if (name == NULL)
11503             continue;
11504
11505           int n;
11506           for (n = 0; n < ndebug_sections; ++n)
11507             {
11508               size_t dbglen = strlen (debug_sections[n].name);
11509               size_t scnlen = strlen (name);
11510               if ((strncmp (name, debug_sections[n].name, dbglen) == 0
11511                    && (dbglen == scnlen
11512                        || (scnlen == dbglen + 4
11513                            && strstr (name, ".dwo") == name + dbglen)))
11514                   || (name[0] == '.' && name[1] == 'z'
11515                       && debug_sections[n].name[1] == 'd'
11516                       && strncmp (&name[2], &debug_sections[n].name[1],
11517                                   dbglen - 1) == 0
11518                       && (scnlen == dbglen + 1
11519                           || (scnlen == dbglen + 5
11520                               && strstr (name, ".dwo") == name + dbglen + 1)))
11521                   || (scnlen > 14 /* .gnu.debuglto_ prefix. */
11522                       && startswith (name, ".gnu.debuglto_")
11523                       && strcmp (&name[14], debug_sections[n].name) == 0)
11524 )
11525                 {
11526                   if ((print_debug_sections | implicit_debug_sections)
11527                       & debug_sections[n].bitmask)
11528                     debug_sections[n].fp (dwflmod, ebl, ehdr, scn, shdr, dbg);
11529                   break;
11530                 }
11531             }
11532         }
11533     }
11534
11535   dwfl_end (skel_dwfl);
11536   free (skel_name);
11537
11538   /* Turn implicit and/or explicit back on in case we go over another file.  */
11539   if (implicit_info)
11540     implicit_debug_sections |= section_info;
11541   if (explicit_info)
11542     print_debug_sections |= section_info;
11543
11544   reset_listptr (&known_locsptr);
11545   reset_listptr (&known_loclistsptr);
11546   reset_listptr (&known_rangelistptr);
11547   reset_listptr (&known_rnglistptr);
11548   reset_listptr (&known_addrbases);
11549   reset_listptr (&known_stroffbases);
11550 }
11551
11552
11553 #define ITEM_INDENT             4
11554 #define WRAP_COLUMN             75
11555
11556 /* Print "NAME: FORMAT", wrapping when output text would make the line
11557    exceed WRAP_COLUMN.  Unpadded numbers look better for the core items
11558    but this function is also used for registers which should be printed
11559    aligned.  Fortunately registers output uses fixed fields width (such
11560    as %11d) for the alignment.
11561
11562    Line breaks should not depend on the particular values although that
11563    may happen in some cases of the core items.  */
11564
11565 static unsigned int
11566 __attribute__ ((format (printf, 6, 7)))
11567 print_core_item (unsigned int colno, char sep, unsigned int wrap,
11568                  size_t name_width, const char *name, const char *format, ...)
11569 {
11570   size_t len = strlen (name);
11571   if (name_width < len)
11572     name_width = len;
11573
11574   char *out;
11575   va_list ap;
11576   va_start (ap, format);
11577   int out_len = vasprintf (&out, format, ap);
11578   va_end (ap);
11579   if (out_len == -1)
11580     error_exit (0, _("memory exhausted"));
11581
11582   size_t n = name_width + sizeof ": " - 1 + out_len;
11583
11584   if (colno == 0)
11585     {
11586       printf ("%*s", ITEM_INDENT, "");
11587       colno = ITEM_INDENT + n;
11588     }
11589   else if (colno + 2 + n < wrap)
11590     {
11591       printf ("%c ", sep);
11592       colno += 2 + n;
11593     }
11594   else
11595     {
11596       printf ("\n%*s", ITEM_INDENT, "");
11597       colno = ITEM_INDENT + n;
11598     }
11599
11600   printf ("%s: %*s%s", name, (int) (name_width - len), "", out);
11601
11602   free (out);
11603
11604   return colno;
11605 }
11606
11607 static const void *
11608 convert (Elf *core, Elf_Type type, uint_fast16_t count,
11609          void *value, const void *data, size_t size)
11610 {
11611   Elf_Data valuedata =
11612     {
11613       .d_type = type,
11614       .d_buf = value,
11615       .d_size = size ?: gelf_fsize (core, type, count, EV_CURRENT),
11616       .d_version = EV_CURRENT,
11617     };
11618   Elf_Data indata =
11619     {
11620       .d_type = type,
11621       .d_buf = (void *) data,
11622       .d_size = valuedata.d_size,
11623       .d_version = EV_CURRENT,
11624     };
11625
11626   Elf_Data *d = (gelf_getclass (core) == ELFCLASS32
11627                  ? elf32_xlatetom : elf64_xlatetom)
11628     (&valuedata, &indata, elf_getident (core, NULL)[EI_DATA]);
11629   if (d == NULL)
11630     error_exit (0, _("cannot convert core note data: %s"),
11631                 elf_errmsg (-1));
11632
11633   return data + indata.d_size;
11634 }
11635
11636 typedef uint8_t GElf_Byte;
11637
11638 static unsigned int
11639 handle_core_item (Elf *core, const Ebl_Core_Item *item, const void *desc,
11640                   unsigned int colno, size_t *repeated_size)
11641 {
11642   uint_fast16_t count = item->count ?: 1;
11643   /* Ebl_Core_Item count is always a small number.
11644      Make sure the backend didn't put in some large bogus value.  */
11645   assert (count < 128);
11646
11647 #define TYPES                                                                 \
11648   DO_TYPE (BYTE, Byte, "0x%.2" PRIx8, "%" PRId8);                             \
11649   DO_TYPE (HALF, Half, "0x%.4" PRIx16, "%" PRId16);                           \
11650   DO_TYPE (WORD, Word, "0x%.8" PRIx32, "%" PRId32);                           \
11651   DO_TYPE (SWORD, Sword, "%" PRId32, "%" PRId32);                             \
11652   DO_TYPE (XWORD, Xword, "0x%.16" PRIx64, "%" PRId64);                        \
11653   DO_TYPE (SXWORD, Sxword, "%" PRId64, "%" PRId64)
11654
11655 #define DO_TYPE(NAME, Name, hex, dec) GElf_##Name Name
11656   typedef union { TYPES; } value_t;
11657   void *data = alloca (count * sizeof (value_t));
11658 #undef DO_TYPE
11659
11660 #define DO_TYPE(NAME, Name, hex, dec) \
11661     GElf_##Name *value_##Name __attribute__((unused)) = data
11662   TYPES;
11663 #undef DO_TYPE
11664
11665   size_t size = gelf_fsize (core, item->type, count, EV_CURRENT);
11666   size_t convsize = size;
11667   if (repeated_size != NULL)
11668     {
11669       if (*repeated_size > size && (item->format == 'b' || item->format == 'B'))
11670         {
11671           data = alloca (*repeated_size);
11672           count *= *repeated_size / size;
11673           convsize = count * size;
11674           *repeated_size -= convsize;
11675         }
11676       else if (item->count != 0 || item->format != '\n')
11677         *repeated_size -= size;
11678     }
11679
11680   convert (core, item->type, count, data, desc + item->offset, convsize);
11681
11682   Elf_Type type = item->type;
11683   if (type == ELF_T_ADDR)
11684     type = gelf_getclass (core) == ELFCLASS32 ? ELF_T_WORD : ELF_T_XWORD;
11685
11686   switch (item->format)
11687     {
11688     case 'd':
11689       assert (count == 1);
11690       switch (type)
11691         {
11692 #define DO_TYPE(NAME, Name, hex, dec)                                         \
11693           case ELF_T_##NAME:                                                  \
11694             colno = print_core_item (colno, ',', WRAP_COLUMN,                 \
11695                                      0, item->name, dec, value_##Name[0]); \
11696             break
11697           TYPES;
11698 #undef DO_TYPE
11699         default:
11700           abort ();
11701         }
11702       break;
11703
11704     case 'x':
11705       assert (count == 1);
11706       switch (type)
11707         {
11708 #define DO_TYPE(NAME, Name, hex, dec)                                         \
11709           case ELF_T_##NAME:                                                  \
11710             colno = print_core_item (colno, ',', WRAP_COLUMN,                 \
11711                                      0, item->name, hex, value_##Name[0]);      \
11712             break
11713           TYPES;
11714 #undef DO_TYPE
11715         default:
11716           abort ();
11717         }
11718       break;
11719
11720     case 'b':
11721     case 'B':
11722       assert (size % sizeof (unsigned int) == 0);
11723       unsigned int nbits = count * size * 8;
11724       unsigned int pop = 0;
11725       for (const unsigned int *i = data; (void *) i < data + count * size; ++i)
11726         pop += __builtin_popcount (*i);
11727       bool negate = pop > nbits / 2;
11728       const unsigned int bias = item->format == 'b';
11729
11730       {
11731         char printed[(negate ? nbits - pop : pop) * 16 + 1];
11732         char *p = printed;
11733         *p = '\0';
11734
11735         if (BYTE_ORDER != LITTLE_ENDIAN && size > sizeof (unsigned int))
11736           {
11737             assert (size == sizeof (unsigned int) * 2);
11738             for (unsigned int *i = data;
11739                  (void *) i < data + count * size; i += 2)
11740               {
11741                 unsigned int w = i[1];
11742                 i[1] = i[0];
11743                 i[0] = w;
11744               }
11745           }
11746
11747         unsigned int lastbit = 0;
11748         unsigned int run = 0;
11749         for (const unsigned int *i = data;
11750              (void *) i < data + count * size; ++i)
11751           {
11752             unsigned int bit = ((void *) i - data) * 8;
11753             unsigned int w = negate ? ~*i : *i;
11754             while (w != 0)
11755               {
11756                 /* Note that a right shift equal to (or greater than)
11757                    the number of bits of w is undefined behaviour.  In
11758                    particular when the least significant bit is bit 32
11759                    (w = 0x8000000) then w >>= n is undefined.  So
11760                    explicitly handle that case separately.  */
11761                 unsigned int n = ffs (w);
11762                 if (n < sizeof (w) * 8)
11763                   w >>= n;
11764                 else
11765                   w = 0;
11766                 bit += n;
11767
11768                 if (lastbit != 0 && lastbit + 1 == bit)
11769                   ++run;
11770                 else
11771                   {
11772                     if (lastbit == 0)
11773                       p += sprintf (p, "%u", bit - bias);
11774                     else if (run == 0)
11775                       p += sprintf (p, ",%u", bit - bias);
11776                     else
11777                       p += sprintf (p, "-%u,%u", lastbit - bias, bit - bias);
11778                     run = 0;
11779                   }
11780
11781                 lastbit = bit;
11782               }
11783           }
11784         if (lastbit > 0 && run > 0 && lastbit + 1 != nbits)
11785           p += sprintf (p, "-%u", lastbit - bias);
11786
11787         colno = print_core_item (colno, ',', WRAP_COLUMN, 0, item->name,
11788                                  negate ? "~<%s>" : "<%s>", printed);
11789       }
11790       break;
11791
11792     case 'T':
11793     case (char) ('T'|0x80):
11794       assert (count == 2);
11795       Dwarf_Word sec;
11796       Dwarf_Word usec;
11797       switch (type)
11798         {
11799 #define DO_TYPE(NAME, Name, hex, dec)                                         \
11800           case ELF_T_##NAME:                                                  \
11801             sec = value_##Name[0];                                            \
11802             usec = value_##Name[1];                                           \
11803             break
11804           TYPES;
11805 #undef DO_TYPE
11806         default:
11807           abort ();
11808         }
11809       if (unlikely (item->format == (char) ('T'|0x80)))
11810         {
11811           /* This is a hack for an ill-considered 64-bit ABI where
11812              tv_usec is actually a 32-bit field with 32 bits of padding
11813              rounding out struct timeval.  We've already converted it as
11814              a 64-bit field.  For little-endian, this just means the
11815              high half is the padding; it's presumably zero, but should
11816              be ignored anyway.  For big-endian, it means the 32-bit
11817              field went into the high half of USEC.  */
11818           GElf_Ehdr ehdr_mem;
11819           GElf_Ehdr *ehdr = gelf_getehdr (core, &ehdr_mem);
11820           if (likely (ehdr->e_ident[EI_DATA] == ELFDATA2MSB))
11821             usec >>= 32;
11822           else
11823             usec &= UINT32_MAX;
11824         }
11825       colno = print_core_item (colno, ',', WRAP_COLUMN, 0, item->name,
11826                                "%" PRIu64 ".%.6" PRIu64, sec, usec);
11827       break;
11828
11829     case 'c':
11830       assert (count == 1);
11831       colno = print_core_item (colno, ',', WRAP_COLUMN, 0, item->name,
11832                                "%c", value_Byte[0]);
11833       break;
11834
11835     case 's':
11836       colno = print_core_item (colno, ',', WRAP_COLUMN, 0, item->name,
11837                                "%.*s", (int) count, value_Byte);
11838       break;
11839
11840     case '\n':
11841       /* This is a list of strings separated by '\n'.  */
11842       assert (item->count == 0);
11843       assert (repeated_size != NULL);
11844       assert (item->name == NULL);
11845       if (unlikely (item->offset >= *repeated_size))
11846         break;
11847
11848       const char *s = desc + item->offset;
11849       size = *repeated_size - item->offset;
11850       *repeated_size = 0;
11851       while (size > 0)
11852         {
11853           const char *eol = memchr (s, '\n', size);
11854           int len = size;
11855           if (eol != NULL)
11856             len = eol - s;
11857           printf ("%*s%.*s\n", ITEM_INDENT, "", len, s);
11858           if (eol == NULL)
11859             break;
11860           size -= eol + 1 - s;
11861           s = eol + 1;
11862         }
11863
11864       colno = WRAP_COLUMN;
11865       break;
11866
11867     case 'h':
11868       break;
11869
11870     default:
11871       error (0, 0, "XXX not handling format '%c' for %s",
11872              item->format, item->name);
11873       break;
11874     }
11875
11876 #undef TYPES
11877
11878   return colno;
11879 }
11880
11881
11882 /* Sort items by group, and by layout offset within each group.  */
11883 static int
11884 compare_core_items (const void *a, const void *b)
11885 {
11886   const Ebl_Core_Item *const *p1 = a;
11887   const Ebl_Core_Item *const *p2 = b;
11888   const Ebl_Core_Item *item1 = *p1;
11889   const Ebl_Core_Item *item2 = *p2;
11890
11891   return ((item1->group == item2->group ? 0
11892            : strcmp (item1->group, item2->group))
11893           ?: (int) item1->offset - (int) item2->offset);
11894 }
11895
11896 /* Sort item groups by layout offset of the first item in the group.  */
11897 static int
11898 compare_core_item_groups (const void *a, const void *b)
11899 {
11900   const Ebl_Core_Item *const *const *p1 = a;
11901   const Ebl_Core_Item *const *const *p2 = b;
11902   const Ebl_Core_Item *const *group1 = *p1;
11903   const Ebl_Core_Item *const *group2 = *p2;
11904   const Ebl_Core_Item *item1 = *group1;
11905   const Ebl_Core_Item *item2 = *group2;
11906
11907   return (int) item1->offset - (int) item2->offset;
11908 }
11909
11910 static unsigned int
11911 handle_core_items (Elf *core, const void *desc, size_t descsz,
11912                    const Ebl_Core_Item *items, size_t nitems)
11913 {
11914   if (nitems == 0)
11915     return 0;
11916   unsigned int colno = 0;
11917
11918   /* FORMAT '\n' makes sense to be present only as a single item as it
11919      processes all the data of a note.  FORMATs 'b' and 'B' have a special case
11920      if present as a single item but they can be also processed with other
11921      items below.  */
11922   if (nitems == 1 && (items[0].format == '\n' || items[0].format == 'b'
11923                       || items[0].format == 'B'))
11924     {
11925       assert (items[0].offset == 0);
11926       size_t size = descsz;
11927       colno = handle_core_item (core, items, desc, colno, &size);
11928       /* If SIZE is not zero here there is some remaining data.  But we do not
11929          know how to process it anyway.  */
11930       return colno;
11931     }
11932   for (size_t i = 0; i < nitems; ++i)
11933     assert (items[i].format != '\n');
11934
11935   /* Sort to collect the groups together.  */
11936   const Ebl_Core_Item *sorted_items[nitems];
11937   for (size_t i = 0; i < nitems; ++i)
11938     sorted_items[i] = &items[i];
11939   qsort (sorted_items, nitems, sizeof sorted_items[0], &compare_core_items);
11940
11941   /* Collect the unique groups and sort them.  */
11942   const Ebl_Core_Item **groups[nitems];
11943   groups[0] = &sorted_items[0];
11944   size_t ngroups = 1;
11945   for (size_t i = 1; i < nitems; ++i)
11946     if (sorted_items[i]->group != sorted_items[i - 1]->group
11947         && strcmp (sorted_items[i]->group, sorted_items[i - 1]->group))
11948       groups[ngroups++] = &sorted_items[i];
11949   qsort (groups, ngroups, sizeof groups[0], &compare_core_item_groups);
11950
11951   /* Write out all the groups.  */
11952   const void *last = desc;
11953   do
11954     {
11955       for (size_t i = 0; i < ngroups; ++i)
11956         {
11957           for (const Ebl_Core_Item **item = groups[i];
11958                (item < &sorted_items[nitems]
11959                 && ((*item)->group == groups[i][0]->group
11960                     || !strcmp ((*item)->group, groups[i][0]->group)));
11961                ++item)
11962             colno = handle_core_item (core, *item, desc, colno, NULL);
11963
11964           /* Force a line break at the end of the group.  */
11965           colno = WRAP_COLUMN;
11966         }
11967
11968       if (descsz == 0)
11969         break;
11970
11971       /* This set of items consumed a certain amount of the note's data.
11972          If there is more data there, we have another unit of the same size.
11973          Loop to print that out too.  */
11974       const Ebl_Core_Item *item = &items[nitems - 1];
11975       size_t eltsz = item->offset + gelf_fsize (core, item->type,
11976                                                 item->count ?: 1, EV_CURRENT);
11977
11978       int reps = -1;
11979       do
11980         {
11981           ++reps;
11982           desc += eltsz;
11983           descsz -= eltsz;
11984         }
11985       while (descsz >= eltsz && !memcmp (desc, last, eltsz));
11986
11987       if (reps == 1)
11988         {
11989           /* For just one repeat, print it unabridged twice.  */
11990           desc -= eltsz;
11991           descsz += eltsz;
11992         }
11993       else if (reps > 1)
11994         printf (_("\n%*s... <repeats %u more times> ..."),
11995                 ITEM_INDENT, "", reps);
11996
11997       last = desc;
11998     }
11999   while (descsz > 0);
12000
12001   return colno;
12002 }
12003
12004 static unsigned int
12005 handle_bit_registers (const Ebl_Register_Location *regloc, const void *desc,
12006                       unsigned int colno)
12007 {
12008   desc += regloc->offset;
12009
12010   abort ();                     /* XXX */
12011   return colno;
12012 }
12013
12014
12015 static unsigned int
12016 handle_core_register (Ebl *ebl, Elf *core, int maxregname,
12017                       const Ebl_Register_Location *regloc, const void *desc,
12018                       unsigned int colno)
12019 {
12020   if (regloc->bits % 8 != 0)
12021     return handle_bit_registers (regloc, desc, colno);
12022
12023   desc += regloc->offset;
12024
12025   for (int reg = regloc->regno; reg < regloc->regno + regloc->count; ++reg)
12026     {
12027       char name[REGNAMESZ];
12028       int bits;
12029       int type;
12030       register_info (ebl, reg, regloc, name, &bits, &type);
12031
12032 #define TYPES                                                                 \
12033       BITS (8, BYTE, "%4" PRId8, "0x%.2" PRIx8);                              \
12034       BITS (16, HALF, "%6" PRId16, "0x%.4" PRIx16);                           \
12035       BITS (32, WORD, "%11" PRId32, " 0x%.8" PRIx32);                         \
12036       BITS (64, XWORD, "%20" PRId64, "  0x%.16" PRIx64)
12037
12038 #define BITS(bits, xtype, sfmt, ufmt)                           \
12039       uint##bits##_t b##bits; int##bits##_t b##bits##s
12040       union { TYPES; uint64_t b128[2]; } value;
12041 #undef  BITS
12042
12043       switch (type)
12044         {
12045         case DW_ATE_unsigned:
12046         case DW_ATE_signed:
12047         case DW_ATE_address:
12048           switch (bits)
12049             {
12050 #define BITS(bits, xtype, sfmt, ufmt)                                         \
12051             case bits:                                                        \
12052               desc = convert (core, ELF_T_##xtype, 1, &value, desc, 0);       \
12053               if (type == DW_ATE_signed)                                      \
12054                 colno = print_core_item (colno, ' ', WRAP_COLUMN,             \
12055                                          maxregname, name,                    \
12056                                          sfmt, value.b##bits##s);             \
12057               else                                                            \
12058                 colno = print_core_item (colno, ' ', WRAP_COLUMN,             \
12059                                          maxregname, name,                    \
12060                                          ufmt, value.b##bits);                \
12061               break
12062
12063             TYPES;
12064
12065             case 128:
12066               assert (type == DW_ATE_unsigned);
12067               desc = convert (core, ELF_T_XWORD, 2, &value, desc, 0);
12068               int be = elf_getident (core, NULL)[EI_DATA] == ELFDATA2MSB;
12069               colno = print_core_item (colno, ' ', WRAP_COLUMN,
12070                                        maxregname, name,
12071                                        "0x%.16" PRIx64 "%.16" PRIx64,
12072                                        value.b128[!be], value.b128[be]);
12073               break;
12074
12075             default:
12076               abort ();
12077 #undef  BITS
12078             }
12079           break;
12080
12081         default:
12082           /* Print each byte in hex, the whole thing in native byte order.  */
12083           assert (bits % 8 == 0);
12084           const uint8_t *bytes = desc;
12085           desc += bits / 8;
12086           char hex[bits / 4 + 1];
12087           hex[bits / 4] = '\0';
12088           int incr = 1;
12089           if (elf_getident (core, NULL)[EI_DATA] == ELFDATA2LSB)
12090             {
12091               bytes += bits / 8 - 1;
12092               incr = -1;
12093             }
12094           size_t idx = 0;
12095           for (char *h = hex; bits > 0; bits -= 8, idx += incr)
12096             {
12097               *h++ = "0123456789abcdef"[bytes[idx] >> 4];
12098               *h++ = "0123456789abcdef"[bytes[idx] & 0xf];
12099             }
12100           colno = print_core_item (colno, ' ', WRAP_COLUMN,
12101                                    maxregname, name, "0x%s", hex);
12102           break;
12103         }
12104       desc += regloc->pad;
12105
12106 #undef TYPES
12107     }
12108
12109   return colno;
12110 }
12111
12112
12113 struct register_info
12114 {
12115   const Ebl_Register_Location *regloc;
12116   const char *set;
12117   char name[REGNAMESZ];
12118   int regno;
12119   int bits;
12120   int type;
12121 };
12122
12123 static int
12124 register_bitpos (const struct register_info *r)
12125 {
12126   return (r->regloc->offset * 8
12127           + ((r->regno - r->regloc->regno)
12128              * (r->regloc->bits + r->regloc->pad * 8)));
12129 }
12130
12131 static int
12132 compare_sets_by_info (const struct register_info *r1,
12133                       const struct register_info *r2)
12134 {
12135   return ((int) r2->bits - (int) r1->bits
12136           ?: register_bitpos (r1) - register_bitpos (r2));
12137 }
12138
12139 /* Sort registers by set, and by size and layout offset within each set.  */
12140 static int
12141 compare_registers (const void *a, const void *b)
12142 {
12143   const struct register_info *r1 = a;
12144   const struct register_info *r2 = b;
12145
12146   /* Unused elements sort last.  */
12147   if (r1->regloc == NULL)
12148     return r2->regloc == NULL ? 0 : 1;
12149   if (r2->regloc == NULL)
12150     return -1;
12151
12152   return ((r1->set == r2->set ? 0 : strcmp (r1->set, r2->set))
12153           ?: compare_sets_by_info (r1, r2));
12154 }
12155
12156 /* Sort register sets by layout offset of the first register in the set.  */
12157 static int
12158 compare_register_sets (const void *a, const void *b)
12159 {
12160   const struct register_info *const *p1 = a;
12161   const struct register_info *const *p2 = b;
12162   return compare_sets_by_info (*p1, *p2);
12163 }
12164
12165 static inline bool
12166 same_set (const struct register_info *a,
12167           const struct register_info *b,
12168           const struct register_info *regs,
12169           size_t maxnreg)
12170 {
12171   return (a < &regs[maxnreg] && a->regloc != NULL
12172           && b < &regs[maxnreg] && b->regloc != NULL
12173           && a->bits == b->bits
12174           && (a->set == b->set || !strcmp (a->set, b->set)));
12175 }
12176
12177 static unsigned int
12178 handle_core_registers (Ebl *ebl, Elf *core, const void *desc,
12179                        const Ebl_Register_Location *reglocs, size_t nregloc)
12180 {
12181   if (nregloc == 0)
12182     return 0;
12183
12184   ssize_t maxnreg = ebl_register_info (ebl, 0, NULL, 0, NULL, NULL, NULL, NULL);
12185   if (maxnreg <= 0)
12186     {
12187       for (size_t i = 0; i < nregloc; ++i)
12188         if (maxnreg < reglocs[i].regno + reglocs[i].count)
12189           maxnreg = reglocs[i].regno + reglocs[i].count;
12190       assert (maxnreg > 0);
12191     }
12192
12193   struct register_info regs[maxnreg];
12194   memset (regs, 0, sizeof regs);
12195
12196   /* Sort to collect the sets together.  */
12197   int maxreg = 0;
12198   for (size_t i = 0; i < nregloc; ++i)
12199     for (int reg = reglocs[i].regno;
12200          reg < reglocs[i].regno + reglocs[i].count;
12201          ++reg)
12202       {
12203         assert (reg < maxnreg);
12204         if (reg > maxreg)
12205           maxreg = reg;
12206         struct register_info *info = &regs[reg];
12207         info->regloc = &reglocs[i];
12208         info->regno = reg;
12209         info->set = register_info (ebl, reg, &reglocs[i],
12210                                    info->name, &info->bits, &info->type);
12211       }
12212   qsort (regs, maxreg + 1, sizeof regs[0], &compare_registers);
12213
12214   /* Collect the unique sets and sort them.  */
12215   struct register_info *sets[maxreg + 1];
12216   sets[0] = &regs[0];
12217   size_t nsets = 1;
12218   for (int i = 1; i <= maxreg; ++i)
12219     if (regs[i].regloc != NULL
12220         && !same_set (&regs[i], &regs[i - 1], regs, maxnreg))
12221       sets[nsets++] = &regs[i];
12222   qsort (sets, nsets, sizeof sets[0], &compare_register_sets);
12223
12224   /* Write out all the sets.  */
12225   unsigned int colno = 0;
12226   for (size_t i = 0; i < nsets; ++i)
12227     {
12228       /* Find the longest name of a register in this set.  */
12229       size_t maxname = 0;
12230       const struct register_info *end;
12231       for (end = sets[i]; same_set (sets[i], end, regs, maxnreg); ++end)
12232         {
12233           size_t len = strlen (end->name);
12234           if (len > maxname)
12235             maxname = len;
12236         }
12237
12238       for (const struct register_info *reg = sets[i];
12239            reg < end;
12240            reg += reg->regloc->count ?: 1)
12241         colno = handle_core_register (ebl, core, maxname,
12242                                       reg->regloc, desc, colno);
12243
12244       /* Force a line break at the end of the group.  */
12245       colno = WRAP_COLUMN;
12246     }
12247
12248   return colno;
12249 }
12250
12251 static void
12252 handle_auxv_note (Ebl *ebl, Elf *core, GElf_Word descsz, GElf_Off desc_pos)
12253 {
12254   Elf_Data *data = elf_getdata_rawchunk (core, desc_pos, descsz, ELF_T_AUXV);
12255   if (data == NULL)
12256   elf_error:
12257     error_exit (0, _("cannot convert core note data: %s"), elf_errmsg (-1));
12258
12259   const size_t nauxv = descsz / gelf_fsize (core, ELF_T_AUXV, 1, EV_CURRENT);
12260   for (size_t i = 0; i < nauxv; ++i)
12261     {
12262       GElf_auxv_t av_mem;
12263       GElf_auxv_t *av = gelf_getauxv (data, i, &av_mem);
12264       if (av == NULL)
12265         goto elf_error;
12266
12267       const char *name;
12268       const char *fmt;
12269       if (ebl_auxv_info (ebl, av->a_type, &name, &fmt) == 0)
12270         {
12271           /* Unknown type.  */
12272           if (av->a_un.a_val == 0)
12273             printf ("    %" PRIu64 "\n", av->a_type);
12274           else
12275             printf ("    %" PRIu64 ": %#" PRIx64 "\n",
12276                     av->a_type, av->a_un.a_val);
12277         }
12278       else
12279         switch (fmt[0])
12280           {
12281           case '\0':            /* Normally zero.  */
12282             if (av->a_un.a_val == 0)
12283               {
12284                 printf ("    %s\n", name);
12285                 break;
12286               }
12287             FALLTHROUGH;
12288           case 'x':             /* hex */
12289           case 'p':             /* address */
12290           case 's':             /* address of string */
12291             printf ("    %s: %#" PRIx64 "\n", name, av->a_un.a_val);
12292             break;
12293           case 'u':
12294             printf ("    %s: %" PRIu64 "\n", name, av->a_un.a_val);
12295             break;
12296           case 'd':
12297             printf ("    %s: %" PRId64 "\n", name, av->a_un.a_val);
12298             break;
12299
12300           case 'b':
12301             printf ("    %s: %#" PRIx64 "  ", name, av->a_un.a_val);
12302             GElf_Xword bit = 1;
12303             const char *pfx = "<";
12304             for (const char *p = fmt + 1; *p != 0; p = strchr (p, '\0') + 1)
12305               {
12306                 if (av->a_un.a_val & bit)
12307                   {
12308                     printf ("%s%s", pfx, p);
12309                     pfx = " ";
12310                   }
12311                 bit <<= 1;
12312               }
12313             printf (">\n");
12314             break;
12315
12316           default:
12317             abort ();
12318           }
12319     }
12320 }
12321
12322 static bool
12323 buf_has_data (unsigned char const *ptr, unsigned char const *end, size_t sz)
12324 {
12325   return ptr < end && (size_t) (end - ptr) >= sz;
12326 }
12327
12328 static bool
12329 buf_read_int (Elf *core, unsigned char const **ptrp, unsigned char const *end,
12330               int *retp)
12331 {
12332   if (! buf_has_data (*ptrp, end, 4))
12333     return false;
12334
12335   *ptrp = convert (core, ELF_T_WORD, 1, retp, *ptrp, 4);
12336   return true;
12337 }
12338
12339 static bool
12340 buf_read_ulong (Elf *core, unsigned char const **ptrp, unsigned char const *end,
12341                 uint64_t *retp)
12342 {
12343   size_t sz = gelf_fsize (core, ELF_T_ADDR, 1, EV_CURRENT);
12344   if (! buf_has_data (*ptrp, end, sz))
12345     return false;
12346
12347   union
12348   {
12349     uint64_t u64;
12350     uint32_t u32;
12351   } u;
12352
12353   *ptrp = convert (core, ELF_T_ADDR, 1, &u, *ptrp, sz);
12354
12355   if (sz == 4)
12356     *retp = u.u32;
12357   else
12358     *retp = u.u64;
12359   return true;
12360 }
12361
12362 static void
12363 handle_siginfo_note (Elf *core, GElf_Word descsz, GElf_Off desc_pos)
12364 {
12365   Elf_Data *data = elf_getdata_rawchunk (core, desc_pos, descsz, ELF_T_BYTE);
12366   if (data == NULL)
12367     error_exit (0, _("cannot convert core note data: %s"), elf_errmsg (-1));
12368
12369   unsigned char const *ptr = data->d_buf;
12370   unsigned char const *const end = data->d_buf + data->d_size;
12371
12372   /* Siginfo head is three ints: signal number, error number, origin
12373      code.  */
12374   int si_signo, si_errno, si_code;
12375   if (! buf_read_int (core, &ptr, end, &si_signo)
12376       || ! buf_read_int (core, &ptr, end, &si_errno)
12377       || ! buf_read_int (core, &ptr, end, &si_code))
12378     {
12379     fail:
12380       printf ("    Not enough data in NT_SIGINFO note.\n");
12381       return;
12382     }
12383
12384   /* Next is a pointer-aligned union of structures.  On 64-bit
12385      machines, that implies a word of padding.  */
12386   if (gelf_getclass (core) == ELFCLASS64)
12387     ptr += 4;
12388
12389   printf ("    si_signo: %d, si_errno: %d, si_code: %d\n",
12390           si_signo, si_errno, si_code);
12391
12392   if (si_code > 0)
12393     switch (si_signo)
12394       {
12395       case CORE_SIGILL:
12396       case CORE_SIGFPE:
12397       case CORE_SIGSEGV:
12398       case CORE_SIGBUS:
12399         {
12400           uint64_t addr;
12401           if (! buf_read_ulong (core, &ptr, end, &addr))
12402             goto fail;
12403           printf ("    fault address: %#" PRIx64 "\n", addr);
12404           break;
12405         }
12406       default:
12407         ;
12408       }
12409   else if (si_code == CORE_SI_USER)
12410     {
12411       int pid, uid;
12412       if (! buf_read_int (core, &ptr, end, &pid)
12413           || ! buf_read_int (core, &ptr, end, &uid))
12414         goto fail;
12415       printf ("    sender PID: %d, sender UID: %d\n", pid, uid);
12416     }
12417 }
12418
12419 static void
12420 handle_file_note (Elf *core, GElf_Word descsz, GElf_Off desc_pos)
12421 {
12422   Elf_Data *data = elf_getdata_rawchunk (core, desc_pos, descsz, ELF_T_BYTE);
12423   if (data == NULL)
12424     error_exit (0, _("cannot convert core note data: %s"), elf_errmsg (-1));
12425
12426   unsigned char const *ptr = data->d_buf;
12427   unsigned char const *const end = data->d_buf + data->d_size;
12428
12429   uint64_t count, page_size;
12430   if (! buf_read_ulong (core, &ptr, end, &count)
12431       || ! buf_read_ulong (core, &ptr, end, &page_size))
12432     {
12433     fail:
12434       printf ("    Not enough data in NT_FILE note.\n");
12435       return;
12436     }
12437
12438   size_t addrsize = gelf_fsize (core, ELF_T_ADDR, 1, EV_CURRENT);
12439   uint64_t maxcount = (size_t) (end - ptr) / (3 * addrsize);
12440   if (count > maxcount)
12441     goto fail;
12442
12443   /* Where file names are stored.  */
12444   unsigned char const *const fstart = ptr + 3 * count * addrsize;
12445   char const *fptr = (char *) fstart;
12446
12447   printf ("    %" PRId64 " files:\n", count);
12448   for (uint64_t i = 0; i < count; ++i)
12449     {
12450       uint64_t mstart, mend, moffset;
12451       if (! buf_read_ulong (core, &ptr, fstart, &mstart)
12452           || ! buf_read_ulong (core, &ptr, fstart, &mend)
12453           || ! buf_read_ulong (core, &ptr, fstart, &moffset))
12454         goto fail;
12455
12456       const char *fnext = memchr (fptr, '\0', (char *) end - fptr);
12457       if (fnext == NULL)
12458         goto fail;
12459
12460       int ct = printf ("      %08" PRIx64 "-%08" PRIx64
12461                        " %08" PRIx64 " %" PRId64,
12462                        mstart, mend, moffset * page_size, mend - mstart);
12463       printf ("%*s%s\n", ct > 50 ? 3 : 53 - ct, "", fptr);
12464
12465       fptr = fnext + 1;
12466     }
12467 }
12468
12469 static void
12470 handle_core_note (Ebl *ebl, const GElf_Nhdr *nhdr,
12471                   const char *name, const void *desc)
12472 {
12473   GElf_Word regs_offset;
12474   size_t nregloc;
12475   const Ebl_Register_Location *reglocs;
12476   size_t nitems;
12477   const Ebl_Core_Item *items;
12478
12479   if (! ebl_core_note (ebl, nhdr, name, desc,
12480                        &regs_offset, &nregloc, &reglocs, &nitems, &items))
12481     return;
12482
12483   /* Pass 0 for DESCSZ when there are registers in the note,
12484      so that the ITEMS array does not describe the whole thing.
12485      For non-register notes, the actual descsz might be a multiple
12486      of the unit size, not just exactly the unit size.  */
12487   unsigned int colno = handle_core_items (ebl->elf, desc,
12488                                           nregloc == 0 ? nhdr->n_descsz : 0,
12489                                           items, nitems);
12490   if (colno != 0)
12491     putchar_unlocked ('\n');
12492
12493   colno = handle_core_registers (ebl, ebl->elf, desc + regs_offset,
12494                                  reglocs, nregloc);
12495   if (colno != 0)
12496     putchar_unlocked ('\n');
12497 }
12498
12499 static void
12500 handle_notes_data (Ebl *ebl, const GElf_Ehdr *ehdr,
12501                    GElf_Off start, Elf_Data *data)
12502 {
12503   fputs_unlocked (_("  Owner          Data size  Type\n"), stdout);
12504
12505   if (data == NULL)
12506     goto bad_note;
12507
12508   size_t offset = 0;
12509   GElf_Nhdr nhdr;
12510   size_t name_offset;
12511   size_t desc_offset;
12512   while (offset < data->d_size
12513          && (offset = gelf_getnote (data, offset,
12514                                     &nhdr, &name_offset, &desc_offset)) > 0)
12515     {
12516       const char *name = nhdr.n_namesz == 0 ? "" : data->d_buf + name_offset;
12517       const char *desc = data->d_buf + desc_offset;
12518
12519       /* GNU Build Attributes are weird, they store most of their data
12520          into the owner name field.  Extract just the owner name
12521          prefix here, then use the rest later as data.  */
12522       bool is_gnu_build_attr
12523         = startswith (name, ELF_NOTE_GNU_BUILD_ATTRIBUTE_PREFIX);
12524       const char *print_name = (is_gnu_build_attr
12525                                 ? ELF_NOTE_GNU_BUILD_ATTRIBUTE_PREFIX : name);
12526       size_t print_namesz = (is_gnu_build_attr
12527                              ? strlen (print_name) : nhdr.n_namesz);
12528
12529       char buf[100];
12530       char buf2[100];
12531       printf (_("  %-13.*s  %9" PRId32 "  %s\n"),
12532               (int) print_namesz, print_name, nhdr.n_descsz,
12533               ehdr->e_type == ET_CORE
12534               ? ebl_core_note_type_name (ebl, nhdr.n_type,
12535                                          buf, sizeof (buf))
12536               : ebl_object_note_type_name (ebl, name, nhdr.n_type,
12537                                            nhdr.n_descsz,
12538                                            buf2, sizeof (buf2)));
12539
12540       /* Filter out invalid entries.  */
12541       if (memchr (name, '\0', nhdr.n_namesz) != NULL
12542           /* XXX For now help broken Linux kernels.  */
12543           || 1)
12544         {
12545           if (ehdr->e_type == ET_CORE)
12546             {
12547               if (nhdr.n_type == NT_AUXV
12548                   && (nhdr.n_namesz == 4 /* Broken old Linux kernels.  */
12549                       || (nhdr.n_namesz == 5 && name[4] == '\0'))
12550                   && !memcmp (name, "CORE", 4))
12551                 handle_auxv_note (ebl, ebl->elf, nhdr.n_descsz,
12552                                   start + desc_offset);
12553               else if (nhdr.n_namesz == 5 && strcmp (name, "CORE") == 0)
12554                 switch (nhdr.n_type)
12555                   {
12556                   case NT_SIGINFO:
12557                     handle_siginfo_note (ebl->elf, nhdr.n_descsz,
12558                                          start + desc_offset);
12559                     break;
12560
12561                   case NT_FILE:
12562                     handle_file_note (ebl->elf, nhdr.n_descsz,
12563                                       start + desc_offset);
12564                     break;
12565
12566                   default:
12567                     handle_core_note (ebl, &nhdr, name, desc);
12568                   }
12569               else
12570                 handle_core_note (ebl, &nhdr, name, desc);
12571             }
12572           else
12573             ebl_object_note (ebl, nhdr.n_namesz, name, nhdr.n_type,
12574                              nhdr.n_descsz, desc);
12575         }
12576     }
12577
12578   if (offset == data->d_size)
12579     return;
12580
12581  bad_note:
12582   error (0, 0,
12583          _("cannot get content of note: %s"),
12584          data != NULL ? "garbage data" : elf_errmsg (-1));
12585 }
12586
12587 static void
12588 handle_notes (Ebl *ebl, GElf_Ehdr *ehdr)
12589 {
12590   /* If we have section headers, just look for SHT_NOTE sections.
12591      In a debuginfo file, the program headers are not reliable.  */
12592   if (shnum != 0)
12593     {
12594       /* Get the section header string table index.  */
12595       size_t shstrndx;
12596       if (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0)
12597         error_exit (0, _("cannot get section header string table index"));
12598
12599       Elf_Scn *scn = NULL;
12600       while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
12601         {
12602           GElf_Shdr shdr_mem;
12603           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
12604
12605           if (shdr == NULL || shdr->sh_type != SHT_NOTE)
12606             /* Not what we are looking for.  */
12607             continue;
12608
12609           if (notes_section != NULL)
12610             {
12611               char *sname = elf_strptr (ebl->elf, shstrndx, shdr->sh_name);
12612               if (sname == NULL || strcmp (sname, notes_section) != 0)
12613                 continue;
12614             }
12615
12616           printf (_("\
12617 \nNote section [%2zu] '%s' of %" PRIu64 " bytes at offset %#0" PRIx64 ":\n"),
12618                   elf_ndxscn (scn),
12619                   elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
12620                   shdr->sh_size, shdr->sh_offset);
12621
12622           handle_notes_data (ebl, ehdr, shdr->sh_offset,
12623                              elf_getdata (scn, NULL));
12624         }
12625       return;
12626     }
12627
12628   /* We have to look through the program header to find the note
12629      sections.  There can be more than one.  */
12630   for (size_t cnt = 0; cnt < phnum; ++cnt)
12631     {
12632       GElf_Phdr mem;
12633       GElf_Phdr *phdr = gelf_getphdr (ebl->elf, cnt, &mem);
12634
12635       if (phdr == NULL || phdr->p_type != PT_NOTE)
12636         /* Not what we are looking for.  */
12637         continue;
12638
12639       printf (_("\
12640 \nNote segment of %" PRIu64 " bytes at offset %#0" PRIx64 ":\n"),
12641               phdr->p_filesz, phdr->p_offset);
12642
12643       handle_notes_data (ebl, ehdr, phdr->p_offset,
12644                          elf_getdata_rawchunk (ebl->elf,
12645                                                phdr->p_offset, phdr->p_filesz,
12646                                                (phdr->p_align == 8
12647                                                 ? ELF_T_NHDR8 : ELF_T_NHDR)));
12648     }
12649 }
12650
12651
12652 static void
12653 hex_dump (const uint8_t *data, size_t len)
12654 {
12655   size_t pos = 0;
12656   while (pos < len)
12657     {
12658       printf ("  0x%08zx ", pos);
12659
12660       const size_t chunk = MIN (len - pos, 16);
12661
12662       for (size_t i = 0; i < chunk; ++i)
12663         if (i % 4 == 3)
12664           printf ("%02x ", data[pos + i]);
12665         else
12666           printf ("%02x", data[pos + i]);
12667
12668       if (chunk < 16)
12669         printf ("%*s", (int) ((16 - chunk) * 2 + (16 - chunk + 3) / 4), "");
12670
12671       for (size_t i = 0; i < chunk; ++i)
12672         {
12673           unsigned char b = data[pos + i];
12674           printf ("%c", isprint (b) ? b : '.');
12675         }
12676
12677       putchar ('\n');
12678       pos += chunk;
12679     }
12680 }
12681
12682 static void
12683 dump_data_section (Elf_Scn *scn, const GElf_Shdr *shdr, const char *name)
12684 {
12685   if (shdr->sh_size == 0 || shdr->sh_type == SHT_NOBITS)
12686     printf (_("\nSection [%zu] '%s' has no data to dump.\n"),
12687             elf_ndxscn (scn), name);
12688   else
12689     {
12690       if (print_decompress)
12691         {
12692           /* We try to decompress the section, but keep the old shdr around
12693              so we can show both the original shdr size and the uncompressed
12694              data size.   */
12695           if ((shdr->sh_flags & SHF_COMPRESSED) != 0)
12696             {
12697               if (elf_compress (scn, 0, 0) < 0)
12698                 printf ("WARNING: %s [%zd]\n",
12699                         _("Couldn't uncompress section"),
12700                         elf_ndxscn (scn));
12701             }
12702           else if (startswith (name, ".zdebug"))
12703             {
12704               if (elf_compress_gnu (scn, 0, 0) < 0)
12705                 printf ("WARNING: %s [%zd]\n",
12706                         _("Couldn't uncompress section"),
12707                         elf_ndxscn (scn));
12708             }
12709         }
12710
12711       Elf_Data *data = elf_rawdata (scn, NULL);
12712       if (data == NULL)
12713         error (0, 0, _("cannot get data for section [%zu] '%s': %s"),
12714                elf_ndxscn (scn), name, elf_errmsg (-1));
12715       else
12716         {
12717           if (data->d_size == shdr->sh_size)
12718             printf (_("\nHex dump of section [%zu] '%s', %" PRIu64
12719                              " bytes at offset %#0" PRIx64 ":\n"),
12720                     elf_ndxscn (scn), name,
12721                     shdr->sh_size, shdr->sh_offset);
12722           else
12723             printf (_("\nHex dump of section [%zu] '%s', %" PRIu64
12724                              " bytes (%zd uncompressed) at offset %#0"
12725                              PRIx64 ":\n"),
12726                     elf_ndxscn (scn), name,
12727                     shdr->sh_size, data->d_size, shdr->sh_offset);
12728           hex_dump (data->d_buf, data->d_size);
12729         }
12730     }
12731 }
12732
12733 static void
12734 print_string_section (Elf_Scn *scn, const GElf_Shdr *shdr, const char *name)
12735 {
12736   if (shdr->sh_size == 0 || shdr->sh_type == SHT_NOBITS)
12737     printf (_("\nSection [%zu] '%s' has no strings to dump.\n"),
12738             elf_ndxscn (scn), name);
12739   else
12740     {
12741       if (print_decompress)
12742         {
12743           /* We try to decompress the section, but keep the old shdr around
12744              so we can show both the original shdr size and the uncompressed
12745              data size.  */
12746           if ((shdr->sh_flags & SHF_COMPRESSED) != 0)
12747             {
12748               if (elf_compress (scn, 0, 0) < 0)
12749                 printf ("WARNING: %s [%zd]\n",
12750                         _("Couldn't uncompress section"),
12751                         elf_ndxscn (scn));
12752             }
12753           else if (startswith (name, ".zdebug"))
12754             {
12755               if (elf_compress_gnu (scn, 0, 0) < 0)
12756                 printf ("WARNING: %s [%zd]\n",
12757                         _("Couldn't uncompress section"),
12758                         elf_ndxscn (scn));
12759             }
12760         }
12761
12762       Elf_Data *data = elf_rawdata (scn, NULL);
12763       if (data == NULL)
12764         error (0, 0, _("cannot get data for section [%zu] '%s': %s"),
12765                elf_ndxscn (scn), name, elf_errmsg (-1));
12766       else
12767         {
12768           if (data->d_size == shdr->sh_size)
12769             printf (_("\nString section [%zu] '%s' contains %" PRIu64
12770                              " bytes at offset %#0" PRIx64 ":\n"),
12771                     elf_ndxscn (scn), name,
12772                     shdr->sh_size, shdr->sh_offset);
12773           else
12774             printf (_("\nString section [%zu] '%s' contains %" PRIu64
12775                              " bytes (%zd uncompressed) at offset %#0"
12776                              PRIx64 ":\n"),
12777                     elf_ndxscn (scn), name,
12778                     shdr->sh_size, data->d_size, shdr->sh_offset);
12779
12780           const char *start = data->d_buf;
12781           const char *const limit = start + data->d_size;
12782           do
12783             {
12784               const char *end = memchr (start, '\0', limit - start);
12785               const size_t pos = start - (const char *) data->d_buf;
12786               if (unlikely (end == NULL))
12787                 {
12788                   printf ("  [%6zx]- %.*s\n",
12789                           pos, (int) (limit - start), start);
12790                   break;
12791                 }
12792               printf ("  [%6zx]  %s\n", pos, start);
12793               start = end + 1;
12794             } while (start < limit);
12795         }
12796     }
12797 }
12798
12799 static void
12800 for_each_section_argument (Elf *elf, const struct section_argument *list,
12801                            void (*dump) (Elf_Scn *scn, const GElf_Shdr *shdr,
12802                                          const char *name))
12803 {
12804   /* Get the section header string table index.  */
12805   size_t shstrndx;
12806   if (elf_getshdrstrndx (elf, &shstrndx) < 0)
12807     error_exit (0, _("cannot get section header string table index"));
12808
12809   for (const struct section_argument *a = list; a != NULL; a = a->next)
12810     {
12811       Elf_Scn *scn;
12812       GElf_Shdr shdr_mem;
12813       const char *name = NULL;
12814
12815       char *endp = NULL;
12816       unsigned long int shndx = strtoul (a->arg, &endp, 0);
12817       if (endp != a->arg && *endp == '\0')
12818         {
12819           scn = elf_getscn (elf, shndx);
12820           if (scn == NULL)
12821             {
12822               error (0, 0, _("\nsection [%lu] does not exist"), shndx);
12823               continue;
12824             }
12825
12826           if (gelf_getshdr (scn, &shdr_mem) == NULL)
12827             error_exit (0, _("cannot get section header: %s"),
12828                         elf_errmsg (-1));
12829           name = elf_strptr (elf, shstrndx, shdr_mem.sh_name);
12830           (*dump) (scn, &shdr_mem, name);
12831         }
12832       else
12833         {
12834           /* Need to look up the section by name.  */
12835           scn = NULL;
12836           bool found = false;
12837           while ((scn = elf_nextscn (elf, scn)) != NULL)
12838             {
12839               if (gelf_getshdr (scn, &shdr_mem) == NULL)
12840                 continue;
12841               name = elf_strptr (elf, shstrndx, shdr_mem.sh_name);
12842               if (name == NULL)
12843                 continue;
12844               if (!strcmp (name, a->arg))
12845                 {
12846                   found = true;
12847                   (*dump) (scn, &shdr_mem, name);
12848                 }
12849             }
12850
12851           if (unlikely (!found) && !a->implicit)
12852             error (0, 0, _("\nsection '%s' does not exist"), a->arg);
12853         }
12854     }
12855 }
12856
12857 static void
12858 dump_data (Ebl *ebl)
12859 {
12860   for_each_section_argument (ebl->elf, dump_data_sections, &dump_data_section);
12861 }
12862
12863 static void
12864 dump_strings (Ebl *ebl)
12865 {
12866   for_each_section_argument (ebl->elf, string_sections, &print_string_section);
12867 }
12868
12869 static void
12870 print_strings (Ebl *ebl)
12871 {
12872   /* Get the section header string table index.  */
12873   size_t shstrndx;
12874   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
12875     error_exit (0, _("cannot get section header string table index"));
12876
12877   Elf_Scn *scn;
12878   GElf_Shdr shdr_mem;
12879   const char *name;
12880   scn = NULL;
12881   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
12882     {
12883       if (gelf_getshdr (scn, &shdr_mem) == NULL)
12884         continue;
12885
12886       if (shdr_mem.sh_type != SHT_PROGBITS
12887           || !(shdr_mem.sh_flags & SHF_STRINGS))
12888         continue;
12889
12890       name = elf_strptr (ebl->elf, shstrndx, shdr_mem.sh_name);
12891       if (name == NULL)
12892         continue;
12893
12894       print_string_section (scn, &shdr_mem, name);
12895     }
12896 }
12897
12898 static void
12899 dump_archive_index (Elf *elf, const char *fname)
12900 {
12901   size_t narsym;
12902   const Elf_Arsym *arsym = elf_getarsym (elf, &narsym);
12903   if (arsym == NULL)
12904     {
12905       int result = elf_errno ();
12906       if (unlikely (result != ELF_E_NO_INDEX))
12907         error_exit (0, _("cannot get symbol index of archive '%s': %s"),
12908                     fname, elf_errmsg (result));
12909       else
12910         printf (_("\nArchive '%s' has no symbol index\n"), fname);
12911       return;
12912     }
12913
12914   printf (_("\nIndex of archive '%s' has %zu entries:\n"),
12915           fname, narsym);
12916
12917   size_t as_off = 0;
12918   for (const Elf_Arsym *s = arsym; s < &arsym[narsym - 1]; ++s)
12919     {
12920       if (s->as_off != as_off)
12921         {
12922           as_off = s->as_off;
12923
12924           Elf *subelf = NULL;
12925           if (unlikely (elf_rand (elf, as_off) == 0)
12926               || unlikely ((subelf = elf_begin (-1, ELF_C_READ_MMAP, elf))
12927                            == NULL))
12928 #if __GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 7)
12929             while (1)
12930 #endif
12931               error_exit (0,
12932                           _("cannot extract member at offset %zu in '%s': %s"),
12933                           as_off, fname, elf_errmsg (-1));
12934
12935           const Elf_Arhdr *h = elf_getarhdr (subelf);
12936
12937           printf (_("Archive member '%s' contains:\n"), h->ar_name);
12938
12939           elf_end (subelf);
12940         }
12941
12942       printf ("\t%s\n", s->as_name);
12943     }
12944 }
12945
12946 #include "debugpred.h"