support ZSTD compression algorithm
[platform/upstream/elfutils.git] / src / readelf.c
1 /* Print information from ELF file in human-readable form.
2    Copyright (C) 1999-2018 Red Hat, Inc.
3    This file is part of elfutils.
4
5    This file is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    elfutils is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 #ifdef HAVE_CONFIG_H
19 # include <config.h>
20 #endif
21
22 #include <argp.h>
23 #include <assert.h>
24 #include <ctype.h>
25 #include <dwarf.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <gelf.h>
29 #include <inttypes.h>
30 #include <langinfo.h>
31 #include <libdw.h>
32 #include <libdwfl.h>
33 #include <locale.h>
34 #include <stdarg.h>
35 #include <stdbool.h>
36 #include <stdio.h>
37 #include <stdio_ext.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <strings.h>
41 #include <time.h>
42 #include <unistd.h>
43 #include <sys/stat.h>
44 #include <signal.h>
45
46 #include <libeu.h>
47 #include <system.h>
48 #include <printversion.h>
49 #include "../libelf/libelfP.h"
50 #include "../libelf/common.h"
51 #include "../libebl/libeblP.h"
52 #include "../libdwelf/libdwelf.h"
53 #include "../libdw/libdwP.h"
54 #include "../libdwfl/libdwflP.h"
55 #include "../libdw/memory-access.h"
56
57 #include "../libdw/known-dwarf.h"
58
59 #ifdef __linux__
60 #define CORE_SIGILL  SIGILL
61 #define CORE_SIGBUS  SIGBUS
62 #define CORE_SIGFPE  SIGFPE
63 #define CORE_SIGSEGV SIGSEGV
64 #define CORE_SI_USER SI_USER
65 #else
66 /* We want the linux version of those as that is what shows up in the core files. */
67 #define CORE_SIGILL  4  /* Illegal instruction (ANSI).  */
68 #define CORE_SIGBUS  7  /* BUS error (4.2 BSD).  */
69 #define CORE_SIGFPE  8  /* Floating-point exception (ANSI).  */
70 #define CORE_SIGSEGV 11 /* Segmentation violation (ANSI).  */
71 #define CORE_SI_USER 0  /* Sent by kill, sigsend.  */
72 #endif
73
74 /* Name and version of program.  */
75 ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
76
77 /* Bug report address.  */
78 ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
79
80 /* argp key value for --elf-section, non-ascii.  */
81 #define ELF_INPUT_SECTION 256
82
83 /* argp key value for --dwarf-skeleton, non-ascii.  */
84 #define DWARF_SKELETON 257
85
86 /* argp key value for --dyn-syms, non-ascii.  */
87 #define PRINT_DYNSYM_TABLE 258
88
89 /* Terrible hack for hooking unrelated skeleton/split compile units,
90    see __libdw_link_skel_split in print_debug.  */
91 static bool do_not_close_dwfl = false;
92
93 /* Definitions of arguments for argp functions.  */
94 static const struct argp_option options[] =
95 {
96   { NULL, 0, NULL, 0, N_("ELF input selection:"), 0 },
97   { "elf-section", ELF_INPUT_SECTION, "SECTION", OPTION_ARG_OPTIONAL,
98     N_("Use the named SECTION (default .gnu_debugdata) as (compressed) ELF "
99        "input data"), 0 },
100   { "dwarf-skeleton", DWARF_SKELETON, "FILE", 0,
101     N_("Used with -w to find the skeleton Compile Units in FILE associated "
102        "with the Split Compile units in a .dwo input file"), 0 },
103   { NULL, 0, NULL, 0, N_("ELF output selection:"), 0 },
104   { "all", 'a', NULL, 0,
105     N_("All these plus -p .strtab -p .dynstr -p .comment"), 0 },
106   { "dynamic", 'd', NULL, 0, N_("Display the dynamic segment"), 0 },
107   { "file-header", 'h', NULL, 0, N_("Display the ELF file header"), 0 },
108   { "histogram", 'I', NULL, 0,
109     N_("Display histogram of bucket list lengths"), 0 },
110   { "program-headers", 'l', NULL, 0, N_("Display the program headers"), 0 },
111   { "segments", 'l', NULL, OPTION_ALIAS | OPTION_HIDDEN, NULL, 0 },
112   { "relocs", 'r', NULL, 0, N_("Display relocations"), 0 },
113   { "section-groups", 'g', NULL, 0, N_("Display the section groups"), 0 },
114   { "section-headers", 'S', NULL, 0, N_("Display the sections' headers"), 0 },
115   { "sections", 'S', NULL, OPTION_ALIAS | OPTION_HIDDEN, NULL, 0 },
116   { "symbols", 's', "SECTION", OPTION_ARG_OPTIONAL,
117     N_("Display the symbol table sections"), 0 },
118   { "syms", 's', NULL, OPTION_ALIAS | OPTION_HIDDEN, NULL, 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   { "use-dynamic", 'D', NULL, 0,
141     N_("Use the dynamic segment when possible for displaying info"), 0 },
142
143   { NULL, 0, NULL, 0, N_("Output control:"), 0 },
144   { "numeric-addresses", 'N', NULL, 0,
145     N_("Do not find symbol names for addresses in DWARF data"), 0 },
146   { "unresolved-address-offsets", 'U', NULL, 0,
147     N_("Display just offsets instead of resolving values to addresses in DWARF data"), 0 },
148   { "wide", 'W', NULL, 0,
149     N_("Ignored for compatibility (lines always wide)"), 0 },
150   { "decompress", 'z', NULL, 0,
151     N_("Show compression information for compressed sections (when used with -S); decompress section before dumping data (when used with -p or -x)"), 0 },
152   { NULL, 0, NULL, 0, NULL, 0 }
153 };
154
155 /* Short description of program.  */
156 static const char doc[] = N_("\
157 Print information from ELF file in human-readable form.");
158
159 /* Strings for arguments in help texts.  */
160 static const char args_doc[] = N_("FILE...");
161
162 /* Prototype for option handler.  */
163 static error_t parse_opt (int key, char *arg, struct argp_state *state);
164
165 /* Data structure to communicate with argp functions.  */
166 static struct argp argp =
167 {
168   options, parse_opt, args_doc, doc, NULL, NULL, NULL
169 };
170
171 /* If non-null, the section from which we should read to (compressed) ELF.  */
172 static const char *elf_input_section = NULL;
173
174 /* If non-null, the file that contains the skeleton CUs.  */
175 static const char *dwarf_skeleton = NULL;
176
177 /* Flags set by the option controlling the output.  */
178
179 /* True if dynamic segment should be printed.  */
180 static bool print_dynamic_table;
181
182 /* True if the file header should be printed.  */
183 static bool print_file_header;
184
185 /* True if the program headers should be printed.  */
186 static bool print_program_header;
187
188 /* True if relocations should be printed.  */
189 static bool print_relocations;
190
191 /* True if the section headers should be printed.  */
192 static bool print_section_header;
193
194 /* True if the symbol table should be printed.  */
195 static bool print_symbol_table;
196
197 /* True if (only) the dynsym table should be printed.  */
198 static bool print_dynsym_table;
199
200 /* True if reconstruct dynamic symbol table from the PT_DYNAMIC segment.  */
201 static bool use_dynamic_segment;
202
203 /* A specific section name, or NULL to print all symbol tables.  */
204 static char *symbol_table_section;
205
206 /* A specific section name, or NULL to print all ELF notes.  */
207 static char *notes_section;
208
209 /* True if the version information should be printed.  */
210 static bool print_version_info;
211
212 /* True if section groups should be printed.  */
213 static bool print_section_groups;
214
215 /* True if bucket list length histogram should be printed.  */
216 static bool print_histogram;
217
218 /* True if the architecture specific data should be printed.  */
219 static bool print_arch;
220
221 /* True if note section content should be printed.  */
222 static bool print_notes;
223
224 /* True if SHF_STRINGS section content should be printed.  */
225 static bool print_string_sections;
226
227 /* True if archive index should be printed.  */
228 static bool print_archive_index;
229
230 /* True if any of the control options except print_archive_index is set.  */
231 static bool any_control_option;
232
233 /* True if we should print addresses from DWARF in symbolic form.  */
234 static bool print_address_names = true;
235
236 /* True if we should print raw values instead of relativized addresses.  */
237 static bool print_unresolved_addresses = false;
238
239 /* True if we should print the .debug_aranges section using libdw.  */
240 static bool decodedaranges = false;
241
242 /* True if we should print the .debug_aranges section using libdw.  */
243 static bool decodedline = false;
244
245 /* True if we want to show more information about compressed sections.  */
246 static bool print_decompress = false;
247
248 /* True if we want to show split compile units for debug_info skeletons.  */
249 static bool show_split_units = false;
250
251 /* Select printing of debugging sections.  */
252 static enum section_e
253 {
254   section_abbrev = 1,           /* .debug_abbrev  */
255   section_aranges = 2,          /* .debug_aranges  */
256   section_frame = 4,            /* .debug_frame or .eh_frame & al.  */
257   section_info = 8,             /* .debug_info, (implies .debug_types)  */
258   section_line = 16,            /* .debug_line  */
259   section_loc = 32,             /* .debug_loc  */
260   section_pubnames = 64,        /* .debug_pubnames  */
261   section_str = 128,            /* .debug_str  */
262   section_macinfo = 256,        /* .debug_macinfo  */
263   section_ranges = 512,         /* .debug_ranges  */
264   section_exception = 1024,     /* .eh_frame & al.  */
265   section_gdb_index = 2048,     /* .gdb_index  */
266   section_macro = 4096,         /* .debug_macro  */
267   section_addr = 8192,          /* .debug_addr  */
268   section_types = 16384,        /* .debug_types (implied by .debug_info)  */
269   section_all = (section_abbrev | section_aranges | section_frame
270                  | section_info | section_line | section_loc
271                  | section_pubnames | section_str | section_macinfo
272                  | section_ranges | section_exception | section_gdb_index
273                  | section_macro | section_addr | section_types)
274 } print_debug_sections, implicit_debug_sections;
275
276 /* Select hex dumping of sections.  */
277 static struct section_argument *dump_data_sections;
278 static struct section_argument **dump_data_sections_tail = &dump_data_sections;
279
280 /* Select string dumping of sections.  */
281 static struct section_argument *string_sections;
282 static struct section_argument **string_sections_tail = &string_sections;
283
284 struct section_argument
285 {
286   struct section_argument *next;
287   const char *arg;
288   bool implicit;
289 };
290
291 /* Numbers of sections and program headers in the file.  */
292 static size_t shnum;
293 static size_t phnum;
294
295
296 /* Declarations of local functions.  */
297 static void process_file (int fd, const char *fname, bool only_one);
298 static void process_elf_file (Dwfl_Module *dwflmod, int fd);
299 static void print_ehdr (Ebl *ebl, GElf_Ehdr *ehdr);
300 static void print_shdr (Ebl *ebl, GElf_Ehdr *ehdr);
301 static void print_phdr (Ebl *ebl, GElf_Ehdr *ehdr);
302 static void print_scngrp (Ebl *ebl);
303 static void print_dynamic (Ebl *ebl);
304 static void print_relocs (Ebl *ebl, GElf_Ehdr *ehdr);
305 static void handle_relocs_rel (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn,
306                                GElf_Shdr *shdr);
307 static void handle_relocs_rela (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn,
308                                 GElf_Shdr *shdr);
309 static bool print_symtab (Ebl *ebl, int type);
310 static void handle_symtab (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr);
311 static void print_verinfo (Ebl *ebl);
312 static void handle_verneed (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr);
313 static void handle_verdef (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr);
314 static void handle_versym (Ebl *ebl, Elf_Scn *scn,
315                            GElf_Shdr *shdr);
316 static void print_debug (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr);
317 static void handle_hash (Ebl *ebl);
318 static void handle_notes (Ebl *ebl, GElf_Ehdr *ehdr);
319 static void print_liblist (Ebl *ebl);
320 static void print_attributes (Ebl *ebl, const GElf_Ehdr *ehdr);
321 static void dump_data (Ebl *ebl);
322 static void dump_strings (Ebl *ebl);
323 static void print_strings (Ebl *ebl);
324 static void dump_archive_index (Elf *, const char *);
325
326 enum dyn_idx
327 {
328   i_strsz,
329   i_verneed,
330   i_verdef,
331   i_versym,
332   i_symtab,
333   i_strtab,
334   i_hash,
335   i_gnu_hash,
336   i_max
337 };
338
339 /* Declarations of local functions for use-dynamic.  */
340 static Elf_Data *get_dynscn_strtab (Elf *elf, GElf_Phdr *phdr);
341 static void get_dynscn_addrs (Elf *elf, GElf_Phdr *phdr, GElf_Addr addrs[i_max]);
342 static void find_offsets (Elf *elf, GElf_Addr main_bias, size_t n,
343                           GElf_Addr addrs[n], GElf_Off offs[n]);
344
345 /* Looked up once with gettext in main.  */
346 static char *yes_str;
347 static char *no_str;
348
349 static void
350 cleanup_list (struct section_argument *list)
351 {
352   while (list != NULL)
353     {
354       struct section_argument *a = list;
355       list = a->next;
356       free (a);
357     }
358 }
359
360 int
361 main (int argc, char *argv[])
362 {
363   /* We use no threads here which can interfere with handling a stream.  */
364   (void) __fsetlocking (stdout, FSETLOCKING_BYCALLER);
365
366   /* Set locale.  */
367   setlocale (LC_ALL, "");
368
369   /* Initialize the message catalog.  */
370   textdomain (PACKAGE_TARNAME);
371
372   /* Look up once.  */
373   yes_str = _("yes");
374   no_str = _("no");
375
376   /* Parse and process arguments.  */
377   int remaining;
378   argp_parse (&argp, argc, argv, 0, &remaining, NULL);
379
380   /* Before we start tell the ELF library which version we are using.  */
381   elf_version (EV_CURRENT);
382
383   /* Now process all the files given at the command line.  */
384   bool only_one = remaining + 1 == argc;
385   do
386     {
387       /* Open the file.  */
388       int fd = open (argv[remaining], O_RDONLY);
389       if (fd == -1)
390         {
391           error (0, errno, _("cannot open input file '%s'"), argv[remaining]);
392           continue;
393         }
394
395       process_file (fd, argv[remaining], only_one);
396
397       close (fd);
398     }
399   while (++remaining < argc);
400
401   cleanup_list (dump_data_sections);
402   cleanup_list (string_sections);
403
404   return error_message_count != 0;
405 }
406
407 static void
408 add_dump_section (const char *name,
409                   int key,
410                   bool implicit)
411 {
412   struct section_argument *a = xmalloc (sizeof *a);
413   a->arg = name;
414   a->next = NULL;
415   a->implicit = implicit;
416   struct section_argument ***tailp
417     = key == 'x' ? &dump_data_sections_tail : &string_sections_tail;
418   **tailp = a;
419   *tailp = &a->next;
420 }
421
422 /* Handle program arguments.  */
423 static error_t
424 parse_opt (int key, char *arg,
425            struct argp_state *state __attribute__ ((unused)))
426 {
427   switch (key)
428     {
429     case 'a':
430       print_file_header = true;
431       print_program_header = true;
432       print_relocations = true;
433       print_section_header = true;
434       print_symbol_table = true;
435       print_version_info = true;
436       print_dynamic_table = true;
437       print_section_groups = true;
438       print_histogram = true;
439       print_arch = true;
440       print_notes = true;
441       implicit_debug_sections |= section_exception;
442       add_dump_section (".strtab", key, true);
443       add_dump_section (".dynstr", key, true);
444       add_dump_section (".comment", key, true);
445       any_control_option = true;
446       break;
447     case 'A':
448       print_arch = true;
449       any_control_option = true;
450       break;
451     case 'd':
452       print_dynamic_table = true;
453       any_control_option = true;
454       break;
455     case 'D':
456       use_dynamic_segment = true;
457       break;
458     case 'e':
459       print_debug_sections |= section_exception;
460       any_control_option = true;
461       break;
462     case 'g':
463       print_section_groups = true;
464       any_control_option = true;
465       break;
466     case 'h':
467       print_file_header = true;
468       any_control_option = true;
469       break;
470     case 'I':
471       print_histogram = true;
472       any_control_option = true;
473       break;
474     case 'l':
475       print_program_header = true;
476       any_control_option = true;
477       break;
478     case 'n':
479       print_notes = true;
480       any_control_option = true;
481       notes_section = arg;
482       break;
483     case 'r':
484       print_relocations = true;
485       any_control_option = true;
486      break;
487     case 'S':
488       print_section_header = true;
489       any_control_option = true;
490       break;
491     case 's':
492       print_symbol_table = true;
493       any_control_option = true;
494       symbol_table_section = arg;
495       break;
496     case PRINT_DYNSYM_TABLE:
497       print_dynsym_table = true;
498       any_control_option = true;
499       break;
500     case 'V':
501       print_version_info = true;
502       any_control_option = true;
503       break;
504     case 'c':
505       print_archive_index = true;
506       break;
507     case 'w':
508       if (arg == NULL)
509         {
510           print_debug_sections = section_all;
511           implicit_debug_sections = section_info;
512           show_split_units = true;
513         }
514       else if (strcmp (arg, "abbrev") == 0)
515         print_debug_sections |= section_abbrev;
516       else if (strcmp (arg, "addr") == 0)
517         {
518           print_debug_sections |= section_addr;
519           implicit_debug_sections |= section_info;
520         }
521       else if (strcmp (arg, "aranges") == 0)
522         print_debug_sections |= section_aranges;
523       else if (strcmp (arg, "decodedaranges") == 0)
524         {
525           print_debug_sections |= section_aranges;
526           decodedaranges = true;
527         }
528       else if (strcmp (arg, "ranges") == 0)
529         {
530           print_debug_sections |= section_ranges;
531           implicit_debug_sections |= section_info;
532         }
533       else if (strcmp (arg, "frame") == 0 || strcmp (arg, "frames") == 0)
534         print_debug_sections |= section_frame;
535       else if (strcmp (arg, "info") == 0)
536         {
537           print_debug_sections |= section_info;
538           print_debug_sections |= section_types;
539         }
540       else if (strcmp (arg, "info+") == 0)
541         {
542           print_debug_sections |= section_info;
543           print_debug_sections |= section_types;
544           show_split_units = true;
545         }
546       else if (strcmp (arg, "loc") == 0)
547         {
548           print_debug_sections |= section_loc;
549           implicit_debug_sections |= section_info;
550         }
551       else if (strcmp (arg, "line") == 0)
552         print_debug_sections |= section_line;
553       else if (strcmp (arg, "decodedline") == 0)
554         {
555           print_debug_sections |= section_line;
556           decodedline = true;
557         }
558       else if (strcmp (arg, "pubnames") == 0)
559         print_debug_sections |= section_pubnames;
560       else if (strcmp (arg, "str") == 0)
561         {
562           print_debug_sections |= section_str;
563           /* For mapping string offset tables to CUs.  */
564           implicit_debug_sections |= section_info;
565         }
566       else if (strcmp (arg, "macinfo") == 0)
567         print_debug_sections |= section_macinfo;
568       else if (strcmp (arg, "macro") == 0)
569         print_debug_sections |= section_macro;
570       else if (strcmp (arg, "exception") == 0)
571         print_debug_sections |= section_exception;
572       else if (strcmp (arg, "gdb_index") == 0)
573         print_debug_sections |= section_gdb_index;
574       else
575         {
576           fprintf (stderr, _("Unknown DWARF debug section `%s'.\n"),
577                    arg);
578           argp_help (&argp, stderr, ARGP_HELP_SEE,
579                      program_invocation_short_name);
580           exit (1);
581         }
582       any_control_option = true;
583       break;
584     case 'p':
585       any_control_option = true;
586       if (arg == NULL)
587         {
588           print_string_sections = true;
589           break;
590         }
591       FALLTHROUGH;
592     case 'x':
593       add_dump_section (arg, key, false);
594       any_control_option = true;
595       break;
596     case 'N':
597       print_address_names = false;
598       break;
599     case 'U':
600       print_unresolved_addresses = true;
601       break;
602     case ARGP_KEY_NO_ARGS:
603       fputs (_("Missing file name.\n"), stderr);
604       goto do_argp_help;
605     case ARGP_KEY_FINI:
606       if (! any_control_option && ! print_archive_index)
607         {
608           fputs (_("No operation specified.\n"), stderr);
609         do_argp_help:
610           argp_help (&argp, stderr, ARGP_HELP_SEE,
611                      program_invocation_short_name);
612           exit (EXIT_FAILURE);
613         }
614       break;
615     case 'W':                   /* Ignored.  */
616       break;
617     case 'z':
618       print_decompress = true;
619       break;
620     case ELF_INPUT_SECTION:
621       if (arg == NULL)
622         elf_input_section = ".gnu_debugdata";
623       else
624         elf_input_section = arg;
625       break;
626     case DWARF_SKELETON:
627       dwarf_skeleton = arg;
628       break;
629     default:
630       return ARGP_ERR_UNKNOWN;
631     }
632   return 0;
633 }
634
635
636 /* Create a file descriptor to read the data from the
637    elf_input_section given a file descriptor to an ELF file.  */
638 static int
639 open_input_section (int fd)
640 {
641   size_t shnums;
642   size_t cnt;
643   size_t shstrndx;
644   Elf *elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
645   if (elf == NULL)
646     {
647       error (0, 0, _("cannot generate Elf descriptor: %s"),
648              elf_errmsg (-1));
649       return -1;
650     }
651
652   if (elf_getshdrnum (elf, &shnums) < 0)
653     {
654       error (0, 0, _("cannot determine number of sections: %s"),
655              elf_errmsg (-1));
656     open_error:
657       elf_end (elf);
658       return -1;
659     }
660
661   if (elf_getshdrstrndx (elf, &shstrndx) < 0)
662     {
663       error (0, 0, _("cannot get section header string table index"));
664       goto open_error;
665     }
666
667   for (cnt = 0; cnt < shnums; ++cnt)
668     {
669       Elf_Scn *scn = elf_getscn (elf, cnt);
670       if (scn == NULL)
671         {
672           error (0, 0, _("cannot get section: %s"),
673                  elf_errmsg (-1));
674           goto open_error;
675         }
676
677       GElf_Shdr shdr_mem;
678       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
679       if (unlikely (shdr == NULL))
680         {
681           error (0, 0, _("cannot get section header: %s"),
682                  elf_errmsg (-1));
683           goto open_error;
684         }
685
686       const char *sname = elf_strptr (elf, shstrndx, shdr->sh_name);
687       if (sname == NULL)
688         {
689           error (0, 0, _("cannot get section name"));
690           goto open_error;
691         }
692
693       if (strcmp (sname, elf_input_section) == 0)
694         {
695           Elf_Data *data = elf_rawdata (scn, NULL);
696           if (data == NULL)
697             {
698               error (0, 0, _("cannot get %s content: %s"),
699                      sname, elf_errmsg (-1));
700               goto open_error;
701             }
702
703           /* Create (and immediately unlink) a temporary file to store
704              section data in to create a file descriptor for it.  */
705           const char *tmpdir = getenv ("TMPDIR") ?: P_tmpdir;
706           static const char suffix[] = "/readelfXXXXXX";
707           int tmplen = strlen (tmpdir) + sizeof (suffix);
708           char *tempname = alloca (tmplen);
709           sprintf (tempname, "%s%s", tmpdir, suffix);
710
711           int sfd = mkstemp (tempname);
712           if (sfd == -1)
713             {
714               error (0, 0, _("cannot create temp file '%s'"),
715                      tempname);
716               goto open_error;
717             }
718           unlink (tempname);
719
720           ssize_t size = data->d_size;
721           if (write_retry (sfd, data->d_buf, size) != size)
722             {
723               error (0, 0, _("cannot write section data"));
724               goto open_error;
725             }
726
727           if (elf_end (elf) != 0)
728             {
729               error (0, 0, _("error while closing Elf descriptor: %s"),
730                      elf_errmsg (-1));
731               return -1;
732             }
733
734           if (lseek (sfd, 0, SEEK_SET) == -1)
735             {
736               error (0, 0, _("error while rewinding file descriptor"));
737               return -1;
738             }
739
740           return sfd;
741         }
742     }
743
744   /* Named section not found.  */
745   if (elf_end (elf) != 0)
746     error (0, 0, _("error while closing Elf descriptor: %s"),
747            elf_errmsg (-1));
748   return -1;
749 }
750
751 /* Check if the file is an archive, and if so dump its index.  */
752 static void
753 check_archive_index (int fd, const char *fname, bool only_one)
754 {
755   /* Create an `Elf' descriptor.  */
756   Elf *elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
757   if (elf == NULL)
758     error (0, 0, _("cannot generate Elf descriptor: %s"),
759            elf_errmsg (-1));
760   else
761     {
762       if (elf_kind (elf) == ELF_K_AR)
763         {
764           if (!only_one)
765             printf ("\n%s:\n\n", fname);
766           dump_archive_index (elf, fname);
767         }
768       else
769         error (0, 0,
770                _("'%s' is not an archive, cannot print archive index"),
771                fname);
772
773       /* Now we can close the descriptor.  */
774       if (elf_end (elf) != 0)
775         error (0, 0, _("error while closing Elf descriptor: %s"),
776                elf_errmsg (-1));
777     }
778 }
779
780 /* Trivial callback used for checking if we opened an archive.  */
781 static int
782 count_dwflmod (Dwfl_Module *dwflmod __attribute__ ((unused)),
783                void **userdata __attribute__ ((unused)),
784                const char *name __attribute__ ((unused)),
785                Dwarf_Addr base __attribute__ ((unused)),
786                void *arg)
787 {
788   if (*(bool *) arg)
789     return DWARF_CB_ABORT;
790   *(bool *) arg = true;
791   return DWARF_CB_OK;
792 }
793
794 struct process_dwflmod_args
795 {
796   int fd;
797   bool only_one;
798 };
799
800 static int
801 process_dwflmod (Dwfl_Module *dwflmod,
802                  void **userdata __attribute__ ((unused)),
803                  const char *name __attribute__ ((unused)),
804                  Dwarf_Addr base __attribute__ ((unused)),
805                  void *arg)
806 {
807   const struct process_dwflmod_args *a = arg;
808
809   /* Print the file name.  */
810   if (!a->only_one)
811     {
812       const char *fname;
813       dwfl_module_info (dwflmod, NULL, NULL, NULL, NULL, NULL, &fname, NULL);
814
815       printf ("\n%s:\n\n", fname);
816     }
817
818   process_elf_file (dwflmod, a->fd);
819
820   return DWARF_CB_OK;
821 }
822
823 /* Stub libdwfl callback, only the ELF handle already open is ever used.
824    Only used for finding the alternate debug file if the Dwarf comes from
825    the main file.  We are not interested in separate debuginfo.  */
826 static int
827 find_no_debuginfo (Dwfl_Module *mod,
828                    void **userdata,
829                    const char *modname,
830                    Dwarf_Addr base,
831                    const char *file_name,
832                    const char *debuglink_file,
833                    GElf_Word debuglink_crc,
834                    char **debuginfo_file_name)
835 {
836   Dwarf_Addr dwbias;
837   dwfl_module_info (mod, NULL, NULL, NULL, &dwbias, NULL, NULL, NULL);
838
839   /* We are only interested if the Dwarf has been setup on the main
840      elf file but is only missing the alternate debug link.  If dwbias
841      hasn't even been setup, this is searching for separate debuginfo
842      for the main elf.  We don't care in that case.  */
843   if (dwbias == (Dwarf_Addr) -1)
844     return -1;
845
846   return dwfl_standard_find_debuginfo (mod, userdata, modname, base,
847                                        file_name, debuglink_file,
848                                        debuglink_crc, debuginfo_file_name);
849 }
850
851 static Dwfl *
852 create_dwfl (int fd, const char *fname)
853 {
854   /* Duplicate an fd for dwfl_report_offline to swallow.  */
855   int dwfl_fd = dup (fd);
856   if (unlikely (dwfl_fd < 0))
857     error_exit (errno, "dup");
858
859   /* Use libdwfl in a trivial way to open the libdw handle for us.
860      This takes care of applying relocations to DWARF data in ET_REL files.  */
861   static const Dwfl_Callbacks callbacks =
862     {
863       .section_address = dwfl_offline_section_address,
864       .find_debuginfo = find_no_debuginfo
865     };
866   Dwfl *dwfl = dwfl_begin (&callbacks);
867   if (likely (dwfl != NULL))
868     /* Let 0 be the logical address of the file (or first in archive).  */
869     dwfl->offline_next_address = 0;
870   if (dwfl_report_offline (dwfl, fname, fname, dwfl_fd) == NULL)
871     {
872       struct stat st;
873       if (fstat (dwfl_fd, &st) != 0)
874         error (0, errno, _("cannot stat input file"));
875       else if (unlikely (st.st_size == 0))
876         error (0, 0, _("input file is empty"));
877       else
878         error (0, 0, _("failed reading '%s': %s"),
879                fname, dwfl_errmsg (-1));
880       close (dwfl_fd);          /* Consumed on success, not on failure.  */
881       dwfl = NULL;
882     }
883   else
884     dwfl_report_end (dwfl, NULL, NULL);
885
886   return dwfl;
887 }
888
889 /* Process one input file.  */
890 static void
891 process_file (int fd, const char *fname, bool only_one)
892 {
893   if (print_archive_index)
894     check_archive_index (fd, fname, only_one);
895
896   if (!any_control_option)
897     return;
898
899   if (elf_input_section != NULL)
900     {
901       /* Replace fname and fd with section content. */
902       char *fnname = alloca (strlen (fname) + strlen (elf_input_section) + 2);
903       sprintf (fnname, "%s:%s", fname, elf_input_section);
904       fd = open_input_section (fd);
905       if (fd == -1)
906         {
907           error (0, 0, _("No such section '%s' in '%s'"),
908                  elf_input_section, fname);
909           return;
910         }
911       fname = fnname;
912     }
913
914   Dwfl *dwfl = create_dwfl (fd, fname);
915   if (dwfl != NULL)
916     {
917       if (only_one)
918         {
919           /* Clear ONLY_ONE if we have multiple modules, from an archive.  */
920           bool seen = false;
921           only_one = dwfl_getmodules (dwfl, &count_dwflmod, &seen, 0) == 0;
922         }
923
924       /* Process the one or more modules gleaned from this file.  */
925       struct process_dwflmod_args a = { .fd = fd, .only_one = only_one };
926       dwfl_getmodules (dwfl, &process_dwflmod, &a, 0);
927     }
928   /* Terrible hack for hooking unrelated skeleton/split compile units,
929      see __libdw_link_skel_split in print_debug.  */
930   if (! do_not_close_dwfl)
931     dwfl_end (dwfl);
932
933   /* Need to close the replaced fd if we created it.  Caller takes
934      care of original.  */
935   if (elf_input_section != NULL)
936     close (fd);
937 }
938
939 /* Check whether there are any compressed sections in the ELF file.  */
940 static bool
941 elf_contains_chdrs (Elf *elf)
942 {
943   Elf_Scn *scn = NULL;
944   while ((scn = elf_nextscn (elf, scn)) != NULL)
945     {
946       GElf_Shdr shdr_mem;
947       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
948       if (shdr != NULL && (shdr->sh_flags & SHF_COMPRESSED) != 0)
949         return true;
950     }
951   return false;
952 }
953
954 /* Process one ELF file.  */
955 static void
956 process_elf_file (Dwfl_Module *dwflmod, int fd)
957 {
958   GElf_Addr dwflbias;
959   Elf *elf = dwfl_module_getelf (dwflmod, &dwflbias);
960
961   GElf_Ehdr ehdr_mem;
962   GElf_Ehdr *ehdr = gelf_getehdr (elf, &ehdr_mem);
963
964   if (ehdr == NULL)
965     {
966       error (0, 0, _("cannot read ELF header: %s"), elf_errmsg (-1));
967       return;
968     }
969
970   Ebl *ebl = ebl_openbackend (elf);
971   if (unlikely (ebl == NULL))
972     {
973     ebl_error:
974       error (0, errno, _("cannot create EBL handle"));
975       return;
976     }
977
978   /* Determine the number of sections.  */
979   if (unlikely (elf_getshdrnum (ebl->elf, &shnum) < 0))
980     error_exit (0, _("cannot determine number of sections: %s"),
981                 elf_errmsg (-1));
982
983   /* Determine the number of phdrs.  */
984   if (unlikely (elf_getphdrnum (ebl->elf, &phnum) < 0))
985     error_exit (0, _("cannot determine number of program headers: %s"),
986                 elf_errmsg (-1));
987
988   /* For an ET_REL file, libdwfl has adjusted the in-core shdrs and
989      may have applied relocation to some sections.  If there are any
990      compressed sections, any pass (or libdw/libdwfl) might have
991      uncompressed them.  So we need to get a fresh Elf handle on the
992      file to display those.  */
993   bool print_unchanged = ((print_section_header
994                            || print_relocations
995                            || dump_data_sections != NULL
996                            || print_notes)
997                           && (ehdr->e_type == ET_REL
998                               || elf_contains_chdrs (ebl->elf)));
999
1000   Elf *pure_elf = NULL;
1001   Ebl *pure_ebl = ebl;
1002   if (print_unchanged)
1003     {
1004       /* Read the file afresh.  */
1005       off_t aroff = elf_getaroff (elf);
1006       pure_elf = dwelf_elf_begin (fd);
1007       if (aroff > 0)
1008         {
1009           /* Archive member.  */
1010           (void) elf_rand (pure_elf, aroff);
1011           Elf *armem = elf_begin (-1, ELF_C_READ_MMAP, pure_elf);
1012           elf_end (pure_elf);
1013           pure_elf = armem;
1014         }
1015       if (pure_elf == NULL)
1016         {
1017           error (0, 0, _("cannot read ELF: %s"), elf_errmsg (-1));
1018           return;
1019         }
1020       pure_ebl = ebl_openbackend (pure_elf);
1021       if (pure_ebl == NULL)
1022         goto ebl_error;
1023     }
1024
1025   bool symtab_printed = false;
1026
1027   if (print_file_header)
1028     print_ehdr (ebl, ehdr);
1029   if (print_section_header)
1030     print_shdr (pure_ebl, ehdr);
1031   if (print_program_header)
1032     print_phdr (ebl, ehdr);
1033   if (print_section_groups)
1034     print_scngrp (ebl);
1035   if (print_dynamic_table)
1036     print_dynamic (ebl);
1037   if (print_relocations)
1038     print_relocs (pure_ebl, ehdr);
1039   if (print_histogram)
1040     handle_hash (ebl);
1041   if (print_symbol_table || print_dynsym_table)
1042     symtab_printed |= print_symtab (ebl, SHT_DYNSYM);
1043   if (print_version_info)
1044     print_verinfo (ebl);
1045   if (print_symbol_table)
1046     symtab_printed |= print_symtab (ebl, SHT_SYMTAB);
1047
1048   if ((print_symbol_table || print_dynsym_table)
1049       && !symtab_printed && symbol_table_section != NULL)
1050     printf ("WARNING: %s: '%s'\n", _("cannot find section"),
1051         symbol_table_section);
1052
1053   if (print_arch)
1054     print_liblist (ebl);
1055   if (print_arch)
1056     print_attributes (ebl, ehdr);
1057   if (dump_data_sections != NULL)
1058     dump_data (pure_ebl);
1059   if (string_sections != NULL)
1060     dump_strings (ebl);
1061   if ((print_debug_sections | implicit_debug_sections) != 0)
1062     print_debug (dwflmod, ebl, ehdr);
1063   if (print_notes)
1064     handle_notes (pure_ebl, ehdr);
1065   if (print_string_sections)
1066     print_strings (ebl);
1067
1068   ebl_closebackend (ebl);
1069
1070   if (pure_ebl != ebl)
1071     {
1072       ebl_closebackend (pure_ebl);
1073       elf_end (pure_elf);
1074     }
1075 }
1076
1077
1078 /* Print file type.  */
1079 static void
1080 print_file_type (unsigned short int e_type)
1081 {
1082   if (likely (e_type <= ET_CORE))
1083     {
1084       static const char *const knowntypes[] =
1085       {
1086         N_("NONE (None)"),
1087         N_("REL (Relocatable file)"),
1088         N_("EXEC (Executable file)"),
1089         N_("DYN (Shared object file)"),
1090         N_("CORE (Core file)")
1091       };
1092       puts (_(knowntypes[e_type]));
1093     }
1094   else if (e_type >= ET_LOOS && e_type <= ET_HIOS)
1095     printf (_("OS Specific: (%x)\n"),  e_type);
1096   else if (e_type >= ET_LOPROC /* && e_type <= ET_HIPROC always true */)
1097     printf (_("Processor Specific: (%x)\n"),  e_type);
1098   else
1099     puts ("???");
1100 }
1101
1102
1103 /* Print ELF header.  */
1104 static void
1105 print_ehdr (Ebl *ebl, GElf_Ehdr *ehdr)
1106 {
1107   fputs_unlocked (_("ELF Header:\n  Magic:  "), stdout);
1108   for (size_t cnt = 0; cnt < EI_NIDENT; ++cnt)
1109     printf (" %02hhx", ehdr->e_ident[cnt]);
1110
1111   printf (_("\n  Class:                             %s\n"),
1112           ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? "ELF32"
1113           : ehdr->e_ident[EI_CLASS] == ELFCLASS64 ? "ELF64"
1114           : "\?\?\?");
1115
1116   printf (_("  Data:                              %s\n"),
1117           ehdr->e_ident[EI_DATA] == ELFDATA2LSB
1118           ? "2's complement, little endian"
1119           : ehdr->e_ident[EI_DATA] == ELFDATA2MSB
1120           ? "2's complement, big endian" : "\?\?\?");
1121
1122   printf (_("  Ident Version:                     %hhd %s\n"),
1123           ehdr->e_ident[EI_VERSION],
1124           ehdr->e_ident[EI_VERSION] == EV_CURRENT ? _("(current)")
1125           : "(\?\?\?)");
1126
1127   char buf[512];
1128   printf (_("  OS/ABI:                            %s\n"),
1129           ebl_osabi_name (ebl, ehdr->e_ident[EI_OSABI], buf, sizeof (buf)));
1130
1131   printf (_("  ABI Version:                       %hhd\n"),
1132           ehdr->e_ident[EI_ABIVERSION]);
1133
1134   fputs_unlocked (_("  Type:                              "), stdout);
1135   print_file_type (ehdr->e_type);
1136
1137   const char *machine = dwelf_elf_e_machine_string (ehdr->e_machine);
1138   if (machine != NULL)
1139     printf (_("  Machine:                           %s\n"), machine);
1140   else
1141     printf (_("  Machine:                           <unknown>: 0x%x\n"),
1142             ehdr->e_machine);
1143
1144   printf (_("  Version:                           %d %s\n"),
1145           ehdr->e_version,
1146           ehdr->e_version  == EV_CURRENT ? _("(current)") : "(\?\?\?)");
1147
1148   printf (_("  Entry point address:               %#" PRIx64 "\n"),
1149           ehdr->e_entry);
1150
1151   printf (_("  Start of program headers:          %" PRId64 " %s\n"),
1152           ehdr->e_phoff, _("(bytes into file)"));
1153
1154   printf (_("  Start of section headers:          %" PRId64 " %s\n"),
1155           ehdr->e_shoff, _("(bytes into file)"));
1156
1157   printf (_("  Flags:                             %s\n"),
1158           ebl_machine_flag_name (ebl, ehdr->e_flags, buf, sizeof (buf)));
1159
1160   printf (_("  Size of this header:               %" PRId16 " %s\n"),
1161           ehdr->e_ehsize, _("(bytes)"));
1162
1163   printf (_("  Size of program header entries:    %" PRId16 " %s\n"),
1164           ehdr->e_phentsize, _("(bytes)"));
1165
1166   printf (_("  Number of program headers entries: %" PRId16),
1167           ehdr->e_phnum);
1168   if (ehdr->e_phnum == PN_XNUM)
1169     {
1170       GElf_Shdr shdr_mem;
1171       GElf_Shdr *shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
1172       if (shdr != NULL)
1173         printf (_(" (%" PRIu32 " in [0].sh_info)"),
1174                 (uint32_t) shdr->sh_info);
1175       else
1176         fputs_unlocked (_(" ([0] not available)"), stdout);
1177     }
1178   fputc_unlocked ('\n', stdout);
1179
1180   printf (_("  Size of section header entries:    %" PRId16 " %s\n"),
1181           ehdr->e_shentsize, _("(bytes)"));
1182
1183   printf (_("  Number of section headers entries: %" PRId16),
1184           ehdr->e_shnum);
1185   if (ehdr->e_shnum == 0)
1186     {
1187       GElf_Shdr shdr_mem;
1188       GElf_Shdr *shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
1189       if (shdr != NULL)
1190         printf (_(" (%" PRIu32 " in [0].sh_size)"),
1191                 (uint32_t) shdr->sh_size);
1192       else
1193         fputs_unlocked (_(" ([0] not available)"), stdout);
1194     }
1195   fputc_unlocked ('\n', stdout);
1196
1197   if (unlikely (ehdr->e_shstrndx == SHN_XINDEX))
1198     {
1199       GElf_Shdr shdr_mem;
1200       GElf_Shdr *shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
1201       if (shdr != NULL)
1202         /* We managed to get the zeroth section.  */
1203         snprintf (buf, sizeof (buf), _(" (%" PRIu32 " in [0].sh_link)"),
1204                   (uint32_t) shdr->sh_link);
1205       else
1206         {
1207           strncpy (buf, _(" ([0] not available)"), sizeof (buf) - 1);
1208           buf[sizeof (buf) - 1] = '\0';
1209         }
1210
1211       printf (_("  Section header string table index: XINDEX%s\n\n"),
1212               buf);
1213     }
1214   else
1215     printf (_("  Section header string table index: %" PRId16 "\n\n"),
1216             ehdr->e_shstrndx);
1217 }
1218
1219
1220 static const char *
1221 get_visibility_type (int value)
1222 {
1223   switch (value)
1224     {
1225     case STV_DEFAULT:
1226       return "DEFAULT";
1227     case STV_INTERNAL:
1228       return "INTERNAL";
1229     case STV_HIDDEN:
1230       return "HIDDEN";
1231     case STV_PROTECTED:
1232       return "PROTECTED";
1233     default:
1234       return "???";
1235     }
1236 }
1237
1238 static const char *
1239 elf_ch_type_name (unsigned int code)
1240 {
1241   switch (code)
1242     {
1243     case 0:
1244       return "NONE";
1245     case ELFCOMPRESS_ZLIB:
1246       return "ZLIB";
1247     case ELFCOMPRESS_ZSTD:
1248       return "ZSTD";
1249     default:
1250       return "UNKNOWN";
1251     }
1252 }
1253
1254 /* Print the section headers.  */
1255 static void
1256 print_shdr (Ebl *ebl, GElf_Ehdr *ehdr)
1257 {
1258   size_t cnt;
1259   size_t shstrndx;
1260
1261   if (! print_file_header)
1262     {
1263       size_t sections;
1264       if (unlikely (elf_getshdrnum (ebl->elf, &sections) < 0))
1265         error_exit (0, _("cannot get number of sections: %s"),
1266                     elf_errmsg (-1));
1267
1268       printf (_("\
1269 There are %zd section headers, starting at offset %#" PRIx64 ":\n\
1270 \n"),
1271               sections, ehdr->e_shoff);
1272     }
1273
1274   /* Get the section header string table index.  */
1275   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1276     error_exit (0, _("cannot get section header string table index: %s"),
1277                 elf_errmsg (-1));
1278
1279   puts (_("Section Headers:"));
1280
1281   if (ehdr->e_ident[EI_CLASS] == ELFCLASS32)
1282     puts (_("[Nr] Name                 Type         Addr     Off    Size   ES Flags Lk Inf Al"));
1283   else
1284     puts (_("[Nr] Name                 Type         Addr             Off      Size     ES Flags Lk Inf Al"));
1285
1286   if (print_decompress)
1287     {
1288       if (ehdr->e_ident[EI_CLASS] == ELFCLASS32)
1289         puts (_("     [Compression  Size   Al]"));
1290       else
1291         puts (_("     [Compression  Size     Al]"));
1292     }
1293
1294   for (cnt = 0; cnt < shnum; ++cnt)
1295     {
1296       Elf_Scn *scn = elf_getscn (ebl->elf, cnt);
1297
1298       if (unlikely (scn == NULL))
1299         error_exit (0, _("cannot get section: %s"),
1300                     elf_errmsg (-1));
1301
1302       /* Get the section header.  */
1303       GElf_Shdr shdr_mem;
1304       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1305       if (unlikely (shdr == NULL))
1306         error_exit (0, _("cannot get section header: %s"),
1307                     elf_errmsg (-1));
1308
1309       char flagbuf[20];
1310       char *cp = flagbuf;
1311       if (shdr->sh_flags & SHF_WRITE)
1312         *cp++ = 'W';
1313       if (shdr->sh_flags & SHF_ALLOC)
1314         *cp++ = 'A';
1315       if (shdr->sh_flags & SHF_EXECINSTR)
1316         *cp++ = 'X';
1317       if (shdr->sh_flags & SHF_MERGE)
1318         *cp++ = 'M';
1319       if (shdr->sh_flags & SHF_STRINGS)
1320         *cp++ = 'S';
1321       if (shdr->sh_flags & SHF_INFO_LINK)
1322         *cp++ = 'I';
1323       if (shdr->sh_flags & SHF_LINK_ORDER)
1324         *cp++ = 'L';
1325       if (shdr->sh_flags & SHF_OS_NONCONFORMING)
1326         *cp++ = 'N';
1327       if (shdr->sh_flags & SHF_GROUP)
1328         *cp++ = 'G';
1329       if (shdr->sh_flags & SHF_TLS)
1330         *cp++ = 'T';
1331       if (shdr->sh_flags & SHF_COMPRESSED)
1332         *cp++ = 'C';
1333       if (shdr->sh_flags & SHF_ORDERED)
1334         *cp++ = 'O';
1335       if (shdr->sh_flags & SHF_EXCLUDE)
1336         *cp++ = 'E';
1337       if (shdr->sh_flags & SHF_GNU_RETAIN)
1338         *cp++ = 'R';
1339       *cp = '\0';
1340
1341       const char *sname;
1342       char buf[128];
1343       sname = elf_strptr (ebl->elf, shstrndx, shdr->sh_name) ?: "<corrupt>";
1344       printf ("[%2zu] %-20s %-12s %0*" PRIx64 " %0*" PRIx64 " %0*" PRIx64
1345               " %2" PRId64 " %-5s %2" PRId32 " %3" PRId32
1346               " %2" PRId64 "\n",
1347               cnt, sname,
1348               ebl_section_type_name (ebl, shdr->sh_type, buf, sizeof (buf)),
1349               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 8 : 16, shdr->sh_addr,
1350               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 6 : 8, shdr->sh_offset,
1351               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 6 : 8, shdr->sh_size,
1352               shdr->sh_entsize, flagbuf, shdr->sh_link, shdr->sh_info,
1353               shdr->sh_addralign);
1354
1355       if (print_decompress)
1356         {
1357           if ((shdr->sh_flags & SHF_COMPRESSED) != 0)
1358             {
1359               GElf_Chdr chdr;
1360               if (gelf_getchdr (scn, &chdr) != NULL)
1361                 printf ("     [ELF %s (%" PRId32 ") %0*" PRIx64
1362                         " %2" PRId64 "]\n",
1363                         elf_ch_type_name (chdr.ch_type),
1364                         chdr.ch_type,
1365                         ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 6 : 8,
1366                         chdr.ch_size, chdr.ch_addralign);
1367               else
1368                 error (0, 0,
1369                        _("bad compression header for section %zd: %s"),
1370                        elf_ndxscn (scn), elf_errmsg (-1));
1371             }
1372           else if (startswith (sname, ".zdebug"))
1373             {
1374               ssize_t size;
1375               if ((size = dwelf_scn_gnu_compressed_size (scn)) >= 0)
1376                 printf ("     [GNU ZLIB     %0*zx   ]\n",
1377                         ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 6 : 8, size);
1378               else
1379                 error (0, 0,
1380                        _("bad gnu compressed size for section %zd: %s"),
1381                        elf_ndxscn (scn), elf_errmsg (-1));
1382             }
1383         }
1384     }
1385
1386   fputc_unlocked ('\n', stdout);
1387 }
1388
1389
1390 /* Print the program header.  */
1391 static void
1392 print_phdr (Ebl *ebl, GElf_Ehdr *ehdr)
1393 {
1394   if (phnum == 0)
1395     /* No program header, this is OK in relocatable objects.  */
1396     return;
1397
1398   puts (_("Program Headers:"));
1399   if (ehdr->e_ident[EI_CLASS] == ELFCLASS32)
1400     puts (_("\
1401   Type           Offset   VirtAddr   PhysAddr   FileSiz  MemSiz   Flg Align"));
1402   else
1403     puts (_("\
1404   Type           Offset   VirtAddr           PhysAddr           FileSiz  MemSiz   Flg Align"));
1405
1406   /* Process all program headers.  */
1407   bool has_relro = false;
1408   GElf_Addr relro_from = 0;
1409   GElf_Addr relro_to = 0;
1410   for (size_t cnt = 0; cnt < phnum; ++cnt)
1411     {
1412       char buf[128];
1413       GElf_Phdr mem;
1414       GElf_Phdr *phdr = gelf_getphdr (ebl->elf, cnt, &mem);
1415
1416       /* If for some reason the header cannot be returned show this.  */
1417       if (unlikely (phdr == NULL))
1418         {
1419           puts ("  ???");
1420           continue;
1421         }
1422
1423       printf ("  %-14s 0x%06" PRIx64 " 0x%0*" PRIx64 " 0x%0*" PRIx64
1424               " 0x%06" PRIx64 " 0x%06" PRIx64 " %c%c%c 0x%" PRIx64 "\n",
1425               ebl_segment_type_name (ebl, phdr->p_type, buf, sizeof (buf)),
1426               phdr->p_offset,
1427               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 8 : 16, phdr->p_vaddr,
1428               ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 8 : 16, phdr->p_paddr,
1429               phdr->p_filesz,
1430               phdr->p_memsz,
1431               phdr->p_flags & PF_R ? 'R' : ' ',
1432               phdr->p_flags & PF_W ? 'W' : ' ',
1433               phdr->p_flags & PF_X ? 'E' : ' ',
1434               phdr->p_align);
1435
1436       if (phdr->p_type == PT_INTERP)
1437         {
1438           /* If we are sure the file offset is valid then we can show
1439              the user the name of the interpreter.  We check whether
1440              there is a section at the file offset.  Normally there
1441              would be a section called ".interp".  But in separate
1442              .debug files it is a NOBITS section (and so doesn't match
1443              with gelf_offscn).  Which probably means the offset is
1444              not valid another reason could be because the ELF file
1445              just doesn't contain any section headers, in that case
1446              just play it safe and don't display anything.  */
1447
1448           Elf_Scn *scn = gelf_offscn (ebl->elf, phdr->p_offset);
1449           GElf_Shdr shdr_mem;
1450           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1451
1452           size_t maxsize;
1453           char *filedata = elf_rawfile (ebl->elf, &maxsize);
1454
1455           if (shdr != NULL && shdr->sh_type == SHT_PROGBITS
1456               && filedata != NULL && phdr->p_offset < maxsize
1457               && phdr->p_filesz <= maxsize - phdr->p_offset
1458               && memchr (filedata + phdr->p_offset, '\0',
1459                          phdr->p_filesz) != NULL)
1460             printf (_("\t[Requesting program interpreter: %s]\n"),
1461                     filedata + phdr->p_offset);
1462         }
1463       else if (phdr->p_type == PT_GNU_RELRO)
1464         {
1465           has_relro = true;
1466           relro_from = phdr->p_vaddr;
1467           relro_to = relro_from + phdr->p_memsz;
1468         }
1469     }
1470
1471   size_t sections;
1472   if (unlikely (elf_getshdrnum (ebl->elf, &sections) < 0))
1473     error_exit (0, _("cannot get number of sections: %s"),
1474                 elf_errmsg (-1));
1475
1476   if (sections == 0)
1477     /* No sections in the file.  Punt.  */
1478     return;
1479
1480   /* Get the section header string table index.  */
1481   size_t shstrndx;
1482   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1483     error_exit (0, _("cannot get section header string table index"));
1484
1485   puts (_("\n Section to Segment mapping:\n  Segment Sections..."));
1486
1487   for (size_t cnt = 0; cnt < phnum; ++cnt)
1488     {
1489       /* Print the segment number.  */
1490       printf ("   %2.2zu     ", cnt);
1491
1492       GElf_Phdr phdr_mem;
1493       GElf_Phdr *phdr = gelf_getphdr (ebl->elf, cnt, &phdr_mem);
1494       /* This must not happen.  */
1495       if (unlikely (phdr == NULL))
1496         error_exit (0, _("cannot get program header: %s"),
1497                     elf_errmsg (-1));
1498
1499       /* Iterate over the sections.  */
1500       bool in_relro = false;
1501       bool in_ro = false;
1502       for (size_t inner = 1; inner < shnum; ++inner)
1503         {
1504           Elf_Scn *scn = elf_getscn (ebl->elf, inner);
1505           /* This should not happen.  */
1506           if (unlikely (scn == NULL))
1507             error_exit (0, _("cannot get section: %s"),
1508                         elf_errmsg (-1));
1509
1510           /* Get the section header.  */
1511           GElf_Shdr shdr_mem;
1512           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1513           if (unlikely (shdr == NULL))
1514             error_exit (0, _("cannot get section header: %s"),
1515                         elf_errmsg (-1));
1516
1517           if (shdr->sh_size > 0
1518               /* Compare allocated sections by VMA, unallocated
1519                  sections by file offset.  */
1520               && (shdr->sh_flags & SHF_ALLOC
1521                   ? (shdr->sh_addr >= phdr->p_vaddr
1522                      && (shdr->sh_addr + shdr->sh_size
1523                          <= phdr->p_vaddr + phdr->p_memsz))
1524                   : (shdr->sh_offset >= phdr->p_offset
1525                      && (shdr->sh_offset + shdr->sh_size
1526                          <= phdr->p_offset + phdr->p_filesz))))
1527             {
1528               if (has_relro && !in_relro
1529                   && shdr->sh_addr >= relro_from
1530                   && shdr->sh_addr + shdr->sh_size <= relro_to)
1531                 {
1532                   fputs_unlocked (" [RELRO:", stdout);
1533                   in_relro = true;
1534                 }
1535               else if (has_relro && in_relro && shdr->sh_addr >= relro_to)
1536                 {
1537                   fputs_unlocked ("]", stdout);
1538                   in_relro =  false;
1539                 }
1540               else if (has_relro && in_relro
1541                        && shdr->sh_addr + shdr->sh_size > relro_to)
1542                 fputs_unlocked ("] <RELRO:", stdout);
1543               else if (phdr->p_type == PT_LOAD && (phdr->p_flags & PF_W) == 0)
1544                 {
1545                   if (!in_ro)
1546                     {
1547                       fputs_unlocked (" [RO:", stdout);
1548                       in_ro = true;
1549                     }
1550                 }
1551               else
1552                 {
1553                   /* Determine the segment this section is part of.  */
1554                   size_t cnt2;
1555                   GElf_Phdr phdr2_mem;
1556                   GElf_Phdr *phdr2 = NULL;
1557                   for (cnt2 = 0; cnt2 < phnum; ++cnt2)
1558                     {
1559                       phdr2 = gelf_getphdr (ebl->elf, cnt2, &phdr2_mem);
1560
1561                       if (phdr2 != NULL && phdr2->p_type == PT_LOAD
1562                           && shdr->sh_addr >= phdr2->p_vaddr
1563                           && (shdr->sh_addr + shdr->sh_size
1564                               <= phdr2->p_vaddr + phdr2->p_memsz))
1565                         break;
1566                     }
1567
1568                   if (cnt2 < phnum)
1569                     {
1570                       if ((phdr2->p_flags & PF_W) == 0 && !in_ro)
1571                         {
1572                           fputs_unlocked (" [RO:", stdout);
1573                           in_ro = true;
1574                         }
1575                       else if ((phdr2->p_flags & PF_W) != 0 && in_ro)
1576                         {
1577                           fputs_unlocked ("]", stdout);
1578                           in_ro = false;
1579                         }
1580                     }
1581                 }
1582
1583               printf (" %s",
1584                       elf_strptr (ebl->elf, shstrndx, shdr->sh_name));
1585
1586               /* Signal that this section is only partially covered.  */
1587               if (has_relro && in_relro
1588                        && shdr->sh_addr + shdr->sh_size > relro_to)
1589                 {
1590                   fputs_unlocked (">", stdout);
1591                   in_relro =  false;
1592                 }
1593             }
1594         }
1595       if (in_relro || in_ro)
1596         fputs_unlocked ("]", stdout);
1597
1598       /* Finish the line.  */
1599       fputc_unlocked ('\n', stdout);
1600     }
1601 }
1602
1603
1604 static const char *
1605 section_name (Ebl *ebl, GElf_Shdr *shdr)
1606 {
1607   size_t shstrndx;
1608   if (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0)
1609     return "???";
1610   return elf_strptr (ebl->elf, shstrndx, shdr->sh_name) ?: "???";
1611 }
1612
1613
1614 static void
1615 handle_scngrp (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
1616 {
1617   /* Get the data of the section.  */
1618   Elf_Data *data = elf_getdata (scn, NULL);
1619
1620   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
1621   GElf_Shdr symshdr_mem;
1622   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
1623   Elf_Data *symdata = elf_getdata (symscn, NULL);
1624
1625   if (data == NULL || data->d_size < sizeof (Elf32_Word) || symshdr == NULL
1626       || symdata == NULL)
1627     return;
1628
1629   /* Get the section header string table index.  */
1630   size_t shstrndx;
1631   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1632     error_exit (0, _("cannot get section header string table index"));
1633
1634   Elf32_Word *grpref = (Elf32_Word *) data->d_buf;
1635
1636   GElf_Sym sym_mem;
1637   GElf_Sym *sym = gelf_getsym (symdata, shdr->sh_info, &sym_mem);
1638
1639   printf ((grpref[0] & GRP_COMDAT)
1640           ? ngettext ("\
1641 \nCOMDAT section group [%2zu] '%s' with signature '%s' contains %zu entry:\n",
1642                       "\
1643 \nCOMDAT section group [%2zu] '%s' with signature '%s' contains %zu entries:\n",
1644                       data->d_size / sizeof (Elf32_Word) - 1)
1645           : ngettext ("\
1646 \nSection group [%2zu] '%s' with signature '%s' contains %zu entry:\n", "\
1647 \nSection group [%2zu] '%s' with signature '%s' contains %zu entries:\n",
1648                       data->d_size / sizeof (Elf32_Word) - 1),
1649           elf_ndxscn (scn),
1650           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
1651           (sym == NULL ? NULL
1652            : elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name))
1653           ?: _("<INVALID SYMBOL>"),
1654           data->d_size / sizeof (Elf32_Word) - 1);
1655
1656   for (size_t cnt = 1; cnt < data->d_size / sizeof (Elf32_Word); ++cnt)
1657     {
1658       GElf_Shdr grpshdr_mem;
1659       GElf_Shdr *grpshdr = gelf_getshdr (elf_getscn (ebl->elf, grpref[cnt]),
1660                                          &grpshdr_mem);
1661
1662       const char *str;
1663       printf ("  [%2u] %s\n",
1664               grpref[cnt],
1665               grpshdr != NULL
1666               && (str = elf_strptr (ebl->elf, shstrndx, grpshdr->sh_name))
1667               ? str : _("<INVALID SECTION>"));
1668     }
1669 }
1670
1671
1672 static void
1673 print_scngrp (Ebl *ebl)
1674 {
1675   /* Find all relocation sections and handle them.  */
1676   Elf_Scn *scn = NULL;
1677
1678   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
1679     {
1680        /* Handle the section if it is a symbol table.  */
1681       GElf_Shdr shdr_mem;
1682       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1683
1684       if (shdr != NULL && shdr->sh_type == SHT_GROUP)
1685         {
1686           if ((shdr->sh_flags & SHF_COMPRESSED) != 0)
1687             {
1688               if (elf_compress (scn, 0, 0) < 0)
1689                 printf ("WARNING: %s [%zd]\n",
1690                         _("Couldn't uncompress section"),
1691                         elf_ndxscn (scn));
1692               shdr = gelf_getshdr (scn, &shdr_mem);
1693               if (unlikely (shdr == NULL))
1694                 error_exit (0, _("cannot get section [%zd] header: %s"),
1695                             elf_ndxscn (scn),
1696                             elf_errmsg (-1));
1697             }
1698           handle_scngrp (ebl, scn, shdr);
1699         }
1700     }
1701 }
1702
1703
1704 static const struct flags
1705 {
1706   int mask;
1707   const char *str;
1708 } dt_flags[] =
1709   {
1710     { DF_ORIGIN, "ORIGIN" },
1711     { DF_SYMBOLIC, "SYMBOLIC" },
1712     { DF_TEXTREL, "TEXTREL" },
1713     { DF_BIND_NOW, "BIND_NOW" },
1714     { DF_STATIC_TLS, "STATIC_TLS" }
1715   };
1716 static const int ndt_flags = sizeof (dt_flags) / sizeof (dt_flags[0]);
1717
1718 static const struct flags dt_flags_1[] =
1719   {
1720     { DF_1_NOW, "NOW" },
1721     { DF_1_GLOBAL, "GLOBAL" },
1722     { DF_1_GROUP, "GROUP" },
1723     { DF_1_NODELETE, "NODELETE" },
1724     { DF_1_LOADFLTR, "LOADFLTR" },
1725     { DF_1_INITFIRST, "INITFIRST" },
1726     { DF_1_NOOPEN, "NOOPEN" },
1727     { DF_1_ORIGIN, "ORIGIN" },
1728     { DF_1_DIRECT, "DIRECT" },
1729     { DF_1_TRANS, "TRANS" },
1730     { DF_1_INTERPOSE, "INTERPOSE" },
1731     { DF_1_NODEFLIB, "NODEFLIB" },
1732     { DF_1_NODUMP, "NODUMP" },
1733     { DF_1_CONFALT, "CONFALT" },
1734     { DF_1_ENDFILTEE, "ENDFILTEE" },
1735     { DF_1_DISPRELDNE, "DISPRELDNE" },
1736     { DF_1_DISPRELPND, "DISPRELPND" },
1737   };
1738 static const int ndt_flags_1 = sizeof (dt_flags_1) / sizeof (dt_flags_1[0]);
1739
1740 static const struct flags dt_feature_1[] =
1741   {
1742     { DTF_1_PARINIT, "PARINIT" },
1743     { DTF_1_CONFEXP, "CONFEXP" }
1744   };
1745 static const int ndt_feature_1 = (sizeof (dt_feature_1)
1746                                   / sizeof (dt_feature_1[0]));
1747
1748 static const struct flags dt_posflag_1[] =
1749   {
1750     { DF_P1_LAZYLOAD, "LAZYLOAD" },
1751     { DF_P1_GROUPPERM, "GROUPPERM" }
1752   };
1753 static const int ndt_posflag_1 = (sizeof (dt_posflag_1)
1754                                   / sizeof (dt_posflag_1[0]));
1755
1756
1757 static void
1758 print_flags (int class, GElf_Xword d_val, const struct flags *flags,
1759                 int nflags)
1760 {
1761   bool first = true;
1762   int cnt;
1763
1764   for (cnt = 0; cnt < nflags; ++cnt)
1765     if (d_val & flags[cnt].mask)
1766       {
1767         if (!first)
1768           putchar_unlocked (' ');
1769         fputs_unlocked (flags[cnt].str, stdout);
1770         d_val &= ~flags[cnt].mask;
1771         first = false;
1772       }
1773
1774   if (d_val != 0)
1775     {
1776       if (!first)
1777         putchar_unlocked (' ');
1778       printf ("%#0*" PRIx64, class == ELFCLASS32 ? 10 : 18, d_val);
1779     }
1780
1781   putchar_unlocked ('\n');
1782 }
1783
1784
1785 static void
1786 print_dt_flags (int class, GElf_Xword d_val)
1787 {
1788   print_flags (class, d_val, dt_flags, ndt_flags);
1789 }
1790
1791
1792 static void
1793 print_dt_flags_1 (int class, GElf_Xword d_val)
1794 {
1795   print_flags (class, d_val, dt_flags_1, ndt_flags_1);
1796 }
1797
1798
1799 static void
1800 print_dt_feature_1 (int class, GElf_Xword d_val)
1801 {
1802   print_flags (class, d_val, dt_feature_1, ndt_feature_1);
1803 }
1804
1805
1806 static void
1807 print_dt_posflag_1 (int class, GElf_Xword d_val)
1808 {
1809   print_flags (class, d_val, dt_posflag_1, ndt_posflag_1);
1810 }
1811
1812
1813 static size_t
1814 get_dyn_ents (Elf_Data * dyn_data)
1815 {
1816   GElf_Dyn *dyn;
1817   GElf_Dyn dyn_mem;
1818   size_t dyn_idx = 0;
1819   do
1820     {
1821       dyn = gelf_getdyn(dyn_data, dyn_idx, &dyn_mem);
1822       if (dyn != NULL)
1823         ++dyn_idx;
1824     }
1825   while (dyn != NULL && dyn->d_tag != DT_NULL);
1826
1827   return dyn_idx;
1828 }
1829
1830
1831 static void
1832 handle_dynamic (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, GElf_Phdr *phdr)
1833 {
1834   int class = gelf_getclass (ebl->elf);
1835   GElf_Shdr glink_mem;
1836   GElf_Shdr *glink;
1837   Elf_Data *data;
1838   size_t cnt;
1839   size_t shstrndx;
1840   size_t dyn_ents;
1841
1842   /* Get the data of the section.  */
1843   if (use_dynamic_segment && phdr != NULL)
1844     data = elf_getdata_rawchunk(ebl->elf, phdr->p_offset,
1845                                 phdr->p_filesz, ELF_T_DYN);
1846   else
1847     data = elf_getdata (scn, NULL);
1848
1849   if (data == NULL)
1850     return;
1851
1852   /* Get the dynamic section entry number */
1853   dyn_ents = get_dyn_ents (data);
1854
1855   if (!use_dynamic_segment && shdr != NULL)
1856     {
1857       /* Get the section header string table index.  */
1858       if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
1859         error_exit (0, _("cannot get section header string table index"));
1860
1861       glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link), &glink_mem);
1862       if (glink == NULL)
1863         error_exit (0, _("invalid sh_link value in section %zu"),
1864                     elf_ndxscn (scn));
1865
1866       printf (ngettext ("\
1867 \nDynamic segment contains %lu entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
1868                     "\
1869 \nDynamic segment contains %lu entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
1870                         dyn_ents),
1871               (unsigned long int) dyn_ents,
1872               class == ELFCLASS32 ? 10 : 18, shdr->sh_addr,
1873               shdr->sh_offset,
1874               (int) shdr->sh_link,
1875               elf_strptr (ebl->elf, shstrndx, glink->sh_name));
1876     }
1877   else if (phdr != NULL)
1878     {
1879       printf (ngettext ("\
1880 \nDynamic segment contains %lu entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "\n",
1881                     "\
1882 \nDynamic segment contains %lu entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "\n",
1883                         dyn_ents),
1884               (unsigned long int) dyn_ents,
1885               class == ELFCLASS32 ? 10 : 18, phdr->p_paddr,
1886               phdr->p_offset);
1887     }
1888
1889   fputs_unlocked (_("  Type              Value\n"), stdout);
1890
1891   /* if --use-dynamic option is enabled,
1892      use the string table to get the related library info.  */
1893   Elf_Data *strtab_data = NULL;
1894   if (use_dynamic_segment && phdr != NULL)
1895     {
1896       strtab_data = get_dynscn_strtab(ebl->elf, phdr);
1897       if (strtab_data == NULL)
1898         error_exit (0, _("cannot get string table by using dynamic segment"));
1899     }
1900
1901   for (cnt = 0; cnt < dyn_ents; ++cnt)
1902     {
1903       GElf_Dyn dynmem;
1904       GElf_Dyn *dyn = gelf_getdyn (data, cnt, &dynmem);
1905       if (dyn == NULL)
1906         break;
1907
1908       char buf[64];
1909       printf ("  %-17s ",
1910               ebl_dynamic_tag_name (ebl, dyn->d_tag, buf, sizeof (buf)));
1911
1912       char *name = NULL;
1913       if (dyn->d_tag == DT_NEEDED
1914           || dyn->d_tag == DT_SONAME
1915           || dyn->d_tag == DT_RPATH
1916           || dyn->d_tag == DT_RUNPATH)
1917         {
1918           if (! use_dynamic_segment && shdr != NULL)
1919             name = elf_strptr (ebl->elf, shdr->sh_link, dyn->d_un.d_val);
1920           else if (dyn->d_un.d_val < strtab_data->d_size
1921                    && memrchr (strtab_data->d_buf + dyn->d_un.d_val, '\0',
1922                                strtab_data->d_size - 1 - dyn->d_un.d_val) != NULL)
1923             name = ((char *) strtab_data->d_buf) + dyn->d_un.d_val;
1924         }
1925
1926       switch (dyn->d_tag)
1927         {
1928         case DT_NULL:
1929         case DT_DEBUG:
1930         case DT_BIND_NOW:
1931         case DT_TEXTREL:
1932           /* No further output.  */
1933           fputc_unlocked ('\n', stdout);
1934           break;
1935
1936         case DT_NEEDED:
1937           printf (_("Shared library: [%s]\n"), name);
1938           break;
1939
1940         case DT_SONAME:
1941           printf (_("Library soname: [%s]\n"), name);
1942           break;
1943
1944         case DT_RPATH:
1945           printf (_("Library rpath: [%s]\n"), name);
1946           break;
1947
1948         case DT_RUNPATH:
1949           printf (_("Library runpath: [%s]\n"), name);
1950           break;
1951
1952         case DT_PLTRELSZ:
1953         case DT_RELASZ:
1954         case DT_STRSZ:
1955         case DT_RELSZ:
1956         case DT_RELAENT:
1957         case DT_SYMENT:
1958         case DT_RELENT:
1959         case DT_PLTPADSZ:
1960         case DT_MOVEENT:
1961         case DT_MOVESZ:
1962         case DT_INIT_ARRAYSZ:
1963         case DT_FINI_ARRAYSZ:
1964         case DT_SYMINSZ:
1965         case DT_SYMINENT:
1966         case DT_GNU_CONFLICTSZ:
1967         case DT_GNU_LIBLISTSZ:
1968           printf (_("%" PRId64 " (bytes)\n"), dyn->d_un.d_val);
1969           break;
1970
1971         case DT_VERDEFNUM:
1972         case DT_VERNEEDNUM:
1973         case DT_RELACOUNT:
1974         case DT_RELCOUNT:
1975           printf ("%" PRId64 "\n", dyn->d_un.d_val);
1976           break;
1977
1978         case DT_PLTREL:;
1979           const char *tagname = ebl_dynamic_tag_name (ebl, dyn->d_un.d_val,
1980                                                       NULL, 0);
1981           puts (tagname ?: "???");
1982           break;
1983
1984         case DT_FLAGS:
1985           print_dt_flags (class, dyn->d_un.d_val);
1986           break;
1987
1988         case DT_FLAGS_1:
1989           print_dt_flags_1 (class, dyn->d_un.d_val);
1990           break;
1991
1992         case DT_FEATURE_1:
1993           print_dt_feature_1 (class, dyn->d_un.d_val);
1994           break;
1995
1996         case DT_POSFLAG_1:
1997           print_dt_posflag_1 (class, dyn->d_un.d_val);
1998           break;
1999
2000         default:
2001           printf ("%#0*" PRIx64 "\n",
2002                   class == ELFCLASS32 ? 10 : 18, dyn->d_un.d_val);
2003           break;
2004         }
2005     }
2006 }
2007
2008
2009 /* Print the dynamic segment.  */
2010 static void
2011 print_dynamic (Ebl *ebl)
2012 {
2013   for (size_t i = 0; i < phnum; ++i)
2014     {
2015       GElf_Phdr phdr_mem;
2016       GElf_Phdr *phdr = gelf_getphdr (ebl->elf, i, &phdr_mem);
2017
2018       if (phdr != NULL && phdr->p_type == PT_DYNAMIC)
2019         {
2020           Elf_Scn *scn = gelf_offscn (ebl->elf, phdr->p_offset);
2021           GElf_Shdr shdr_mem;
2022           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
2023           if ((use_dynamic_segment && phdr != NULL)
2024               || (shdr != NULL && shdr->sh_type == SHT_DYNAMIC))
2025             handle_dynamic (ebl, scn, shdr, phdr);
2026           break;
2027         }
2028     }
2029 }
2030
2031
2032 /* Print relocations.  */
2033 static void
2034 print_relocs (Ebl *ebl, GElf_Ehdr *ehdr)
2035 {
2036   /* Find all relocation sections and handle them.  */
2037   Elf_Scn *scn = NULL;
2038
2039   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
2040     {
2041        /* Handle the section if it is a symbol table.  */
2042       GElf_Shdr shdr_mem;
2043       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
2044
2045       if (likely (shdr != NULL))
2046         {
2047           if (shdr->sh_type == SHT_REL)
2048             handle_relocs_rel (ebl, ehdr, scn, shdr);
2049           else if (shdr->sh_type == SHT_RELA)
2050             handle_relocs_rela (ebl, ehdr, scn, shdr);
2051         }
2052     }
2053 }
2054
2055
2056 /* Handle a relocation section.  */
2057 static void
2058 handle_relocs_rel (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn, GElf_Shdr *shdr)
2059 {
2060   int class = gelf_getclass (ebl->elf);
2061   size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_REL, 1, EV_CURRENT);
2062   int nentries = shdr->sh_size / sh_entsize;
2063
2064   /* Get the data of the section.  */
2065   Elf_Data *data = elf_getdata (scn, NULL);
2066   if (data == NULL)
2067     return;
2068
2069   /* Get the symbol table information.  */
2070   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
2071   GElf_Shdr symshdr_mem;
2072   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
2073   Elf_Data *symdata = elf_getdata (symscn, NULL);
2074
2075   /* Get the section header of the section the relocations are for.  */
2076   GElf_Shdr destshdr_mem;
2077   GElf_Shdr *destshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_info),
2078                                       &destshdr_mem);
2079
2080   if (unlikely (symshdr == NULL || symdata == NULL || destshdr == NULL))
2081     {
2082       printf (_("\nInvalid symbol table at offset %#0" PRIx64 "\n"),
2083               shdr->sh_offset);
2084       return;
2085     }
2086
2087   /* Search for the optional extended section index table.  */
2088   Elf_Data *xndxdata = NULL;
2089   int xndxscnidx = elf_scnshndx (scn);
2090   if (unlikely (xndxscnidx > 0))
2091     xndxdata = elf_getdata (elf_getscn (ebl->elf, xndxscnidx), NULL);
2092
2093   /* Get the section header string table index.  */
2094   size_t shstrndx;
2095   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2096     error_exit (0, _("cannot get section header string table index"));
2097
2098   if (shdr->sh_info != 0)
2099     printf (ngettext ("\
2100 \nRelocation section [%2zu] '%s' for section [%2u] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
2101                     "\
2102 \nRelocation section [%2zu] '%s' for section [%2u] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
2103                       nentries),
2104             elf_ndxscn (scn),
2105             elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2106             (unsigned int) shdr->sh_info,
2107             elf_strptr (ebl->elf, shstrndx, destshdr->sh_name),
2108             shdr->sh_offset,
2109             nentries);
2110   else
2111     /* The .rel.dyn section does not refer to a specific section but
2112        instead of section index zero.  Do not try to print a section
2113        name.  */
2114     printf (ngettext ("\
2115 \nRelocation section [%2u] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
2116                     "\
2117 \nRelocation section [%2u] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
2118                       nentries),
2119             (unsigned int) elf_ndxscn (scn),
2120             elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2121             shdr->sh_offset,
2122             nentries);
2123   fputs_unlocked (class == ELFCLASS32
2124                   ? _("\
2125   Offset      Type                 Value       Name\n")
2126                   : _("\
2127   Offset              Type                 Value               Name\n"),
2128          stdout);
2129
2130   int is_statically_linked = 0;
2131   for (int cnt = 0; cnt < nentries; ++cnt)
2132     {
2133       GElf_Rel relmem;
2134       GElf_Rel *rel = gelf_getrel (data, cnt, &relmem);
2135       if (likely (rel != NULL))
2136         {
2137           char buf[128];
2138           GElf_Sym symmem;
2139           Elf32_Word xndx;
2140           GElf_Sym *sym = gelf_getsymshndx (symdata, xndxdata,
2141                                             GELF_R_SYM (rel->r_info),
2142                                             &symmem, &xndx);
2143           if (unlikely (sym == NULL))
2144             {
2145               /* As a special case we have to handle relocations in static
2146                  executables.  This only happens for IRELATIVE relocations
2147                  (so far).  There is no symbol table.  */
2148               if (is_statically_linked == 0)
2149                 {
2150                   /* Find the program header and look for a PT_INTERP entry. */
2151                   is_statically_linked = -1;
2152                   if (ehdr->e_type == ET_EXEC)
2153                     {
2154                       is_statically_linked = 1;
2155
2156                       for (size_t inner = 0; inner < phnum; ++inner)
2157                         {
2158                           GElf_Phdr phdr_mem;
2159                           GElf_Phdr *phdr = gelf_getphdr (ebl->elf, inner,
2160                                                           &phdr_mem);
2161                           if (phdr != NULL && phdr->p_type == PT_INTERP)
2162                             {
2163                               is_statically_linked = -1;
2164                               break;
2165                             }
2166                         }
2167                     }
2168                 }
2169
2170               if (is_statically_linked > 0 && shdr->sh_link == 0)
2171                 printf ("\
2172   %#0*" PRIx64 "  %-20s %*s  %s\n",
2173                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2174                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2175                         /* Avoid the leading R_ which isn't carrying any
2176                            information.  */
2177                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2178                                                buf, sizeof (buf)) + 2
2179                         : _("<INVALID RELOC>"),
2180                         class == ELFCLASS32 ? 10 : 18, "",
2181                         elf_strptr (ebl->elf, shstrndx, destshdr->sh_name));
2182               else
2183                 printf ("  %#0*" PRIx64 "  %-20s <%s %ld>\n",
2184                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2185                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2186                         /* Avoid the leading R_ which isn't carrying any
2187                            information.  */
2188                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2189                                                buf, sizeof (buf)) + 2
2190                         : _("<INVALID RELOC>"),
2191                         _("INVALID SYMBOL"),
2192                         (long int) GELF_R_SYM (rel->r_info));
2193             }
2194           else if (GELF_ST_TYPE (sym->st_info) != STT_SECTION)
2195             printf ("  %#0*" PRIx64 "  %-20s %#0*" PRIx64 "  %s\n",
2196                     class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2197                     likely (ebl_reloc_type_check (ebl,
2198                                                   GELF_R_TYPE (rel->r_info)))
2199                     /* Avoid the leading R_ which isn't carrying any
2200                        information.  */
2201                     ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2202                                            buf, sizeof (buf)) + 2
2203                     : _("<INVALID RELOC>"),
2204                     class == ELFCLASS32 ? 10 : 18, sym->st_value,
2205                     elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name));
2206           else
2207             {
2208               /* This is a relocation against a STT_SECTION symbol.  */
2209               GElf_Shdr secshdr_mem;
2210               GElf_Shdr *secshdr;
2211               secshdr = gelf_getshdr (elf_getscn (ebl->elf,
2212                                                   sym->st_shndx == SHN_XINDEX
2213                                                   ? xndx : sym->st_shndx),
2214                                       &secshdr_mem);
2215
2216               if (unlikely (secshdr == NULL))
2217                 printf ("  %#0*" PRIx64 "  %-20s <%s %ld>\n",
2218                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2219                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2220                         /* Avoid the leading R_ which isn't carrying any
2221                            information.  */
2222                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2223                                                buf, sizeof (buf)) + 2
2224                         : _("<INVALID RELOC>"),
2225                         _("INVALID SECTION"),
2226                         (long int) (sym->st_shndx == SHN_XINDEX
2227                                     ? xndx : sym->st_shndx));
2228               else
2229                 printf ("  %#0*" PRIx64 "  %-20s %#0*" PRIx64 "  %s\n",
2230                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2231                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2232                         /* Avoid the leading R_ which isn't carrying any
2233                            information.  */
2234                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2235                                                buf, sizeof (buf)) + 2
2236                         : _("<INVALID RELOC>"),
2237                         class == ELFCLASS32 ? 10 : 18, sym->st_value,
2238                         elf_strptr (ebl->elf, shstrndx, secshdr->sh_name));
2239             }
2240         }
2241     }
2242 }
2243
2244
2245 /* Handle a relocation section.  */
2246 static void
2247 handle_relocs_rela (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn, GElf_Shdr *shdr)
2248 {
2249   int class = gelf_getclass (ebl->elf);
2250   size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_RELA, 1, EV_CURRENT);
2251   int nentries = shdr->sh_size / sh_entsize;
2252
2253   /* Get the data of the section.  */
2254   Elf_Data *data = elf_getdata (scn, NULL);
2255   if (data == NULL)
2256     return;
2257
2258   /* Get the symbol table information.  */
2259   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
2260   GElf_Shdr symshdr_mem;
2261   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
2262   Elf_Data *symdata = elf_getdata (symscn, NULL);
2263
2264   /* Get the section header of the section the relocations are for.  */
2265   GElf_Shdr destshdr_mem;
2266   GElf_Shdr *destshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_info),
2267                                       &destshdr_mem);
2268
2269   if (unlikely (symshdr == NULL || symdata == NULL || destshdr == NULL))
2270     {
2271       printf (_("\nInvalid symbol table at offset %#0" PRIx64 "\n"),
2272               shdr->sh_offset);
2273       return;
2274     }
2275
2276   /* Search for the optional extended section index table.  */
2277   Elf_Data *xndxdata = NULL;
2278   int xndxscnidx = elf_scnshndx (scn);
2279   if (unlikely (xndxscnidx > 0))
2280     xndxdata = elf_getdata (elf_getscn (ebl->elf, xndxscnidx), NULL);
2281
2282   /* Get the section header string table index.  */
2283   size_t shstrndx;
2284   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2285     error_exit (0, _("cannot get section header string table index"));
2286
2287   if (shdr->sh_info != 0)
2288     printf (ngettext ("\
2289 \nRelocation section [%2zu] '%s' for section [%2u] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
2290                     "\
2291 \nRelocation section [%2zu] '%s' for section [%2u] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
2292                     nentries),
2293           elf_ndxscn (scn),
2294           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2295           (unsigned int) shdr->sh_info,
2296           elf_strptr (ebl->elf, shstrndx, destshdr->sh_name),
2297           shdr->sh_offset,
2298           nentries);
2299   else
2300     /* The .rela.dyn section does not refer to a specific section but
2301        instead of section index zero.  Do not try to print a section
2302        name.  */
2303     printf (ngettext ("\
2304 \nRelocation section [%2u] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
2305                     "\
2306 \nRelocation section [%2u] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
2307                       nentries),
2308             (unsigned int) elf_ndxscn (scn),
2309             elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2310             shdr->sh_offset,
2311             nentries);
2312   fputs_unlocked (class == ELFCLASS32
2313                   ? _("\
2314   Offset      Type            Value       Addend Name\n")
2315                   : _("\
2316   Offset              Type            Value               Addend Name\n"),
2317                   stdout);
2318
2319   int is_statically_linked = 0;
2320   for (int cnt = 0; cnt < nentries; ++cnt)
2321     {
2322       GElf_Rela relmem;
2323       GElf_Rela *rel = gelf_getrela (data, cnt, &relmem);
2324       if (likely (rel != NULL))
2325         {
2326           char buf[64];
2327           GElf_Sym symmem;
2328           Elf32_Word xndx;
2329           GElf_Sym *sym = gelf_getsymshndx (symdata, xndxdata,
2330                                             GELF_R_SYM (rel->r_info),
2331                                             &symmem, &xndx);
2332
2333           if (unlikely (sym == NULL))
2334             {
2335               /* As a special case we have to handle relocations in static
2336                  executables.  This only happens for IRELATIVE relocations
2337                  (so far).  There is no symbol table.  */
2338               if (is_statically_linked == 0)
2339                 {
2340                   /* Find the program header and look for a PT_INTERP entry. */
2341                   is_statically_linked = -1;
2342                   if (ehdr->e_type == ET_EXEC)
2343                     {
2344                       is_statically_linked = 1;
2345
2346                       for (size_t inner = 0; inner < phnum; ++inner)
2347                         {
2348                           GElf_Phdr phdr_mem;
2349                           GElf_Phdr *phdr = gelf_getphdr (ebl->elf, inner,
2350                                                           &phdr_mem);
2351                           if (phdr != NULL && phdr->p_type == PT_INTERP)
2352                             {
2353                               is_statically_linked = -1;
2354                               break;
2355                             }
2356                         }
2357                     }
2358                 }
2359
2360               if (is_statically_linked > 0 && shdr->sh_link == 0)
2361                 printf ("\
2362   %#0*" PRIx64 "  %-15s %*s  %#6" PRIx64 " %s\n",
2363                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2364                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2365                         /* Avoid the leading R_ which isn't carrying any
2366                            information.  */
2367                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2368                                                buf, sizeof (buf)) + 2
2369                         : _("<INVALID RELOC>"),
2370                         class == ELFCLASS32 ? 10 : 18, "",
2371                         rel->r_addend,
2372                         elf_strptr (ebl->elf, shstrndx, destshdr->sh_name));
2373               else
2374                 printf ("  %#0*" PRIx64 "  %-15s <%s %ld>\n",
2375                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2376                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2377                         /* Avoid the leading R_ which isn't carrying any
2378                            information.  */
2379                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2380                                                buf, sizeof (buf)) + 2
2381                         : _("<INVALID RELOC>"),
2382                         _("INVALID SYMBOL"),
2383                         (long int) GELF_R_SYM (rel->r_info));
2384             }
2385           else if (GELF_ST_TYPE (sym->st_info) != STT_SECTION)
2386             printf ("\
2387   %#0*" PRIx64 "  %-15s %#0*" PRIx64 "  %+6" PRId64 " %s\n",
2388                     class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2389                     likely (ebl_reloc_type_check (ebl,
2390                                                   GELF_R_TYPE (rel->r_info)))
2391                     /* Avoid the leading R_ which isn't carrying any
2392                        information.  */
2393                     ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2394                                            buf, sizeof (buf)) + 2
2395                     : _("<INVALID RELOC>"),
2396                     class == ELFCLASS32 ? 10 : 18, sym->st_value,
2397                     rel->r_addend,
2398                     elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name));
2399           else
2400             {
2401               /* This is a relocation against a STT_SECTION symbol.  */
2402               GElf_Shdr secshdr_mem;
2403               GElf_Shdr *secshdr;
2404               secshdr = gelf_getshdr (elf_getscn (ebl->elf,
2405                                                   sym->st_shndx == SHN_XINDEX
2406                                                   ? xndx : sym->st_shndx),
2407                                       &secshdr_mem);
2408
2409               if (unlikely (secshdr == NULL))
2410                 printf ("  %#0*" PRIx64 "  %-15s <%s %ld>\n",
2411                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2412                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2413                         /* Avoid the leading R_ which isn't carrying any
2414                            information.  */
2415                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2416                                                buf, sizeof (buf)) + 2
2417                         : _("<INVALID RELOC>"),
2418                         _("INVALID SECTION"),
2419                         (long int) (sym->st_shndx == SHN_XINDEX
2420                                     ? xndx : sym->st_shndx));
2421               else
2422                 printf ("\
2423   %#0*" PRIx64 "  %-15s %#0*" PRIx64 "  %+6" PRId64 " %s\n",
2424                         class == ELFCLASS32 ? 10 : 18, rel->r_offset,
2425                         ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info))
2426                         /* Avoid the leading R_ which isn't carrying any
2427                            information.  */
2428                         ? ebl_reloc_type_name (ebl, GELF_R_TYPE (rel->r_info),
2429                                                buf, sizeof (buf)) + 2
2430                         : _("<INVALID RELOC>"),
2431                         class == ELFCLASS32 ? 10 : 18, sym->st_value,
2432                         rel->r_addend,
2433                         elf_strptr (ebl->elf, shstrndx, secshdr->sh_name));
2434             }
2435         }
2436     }
2437 }
2438
2439
2440 /* Print the program header.  Return true if a symtab is printed,
2441    false otherwise.  */
2442 static bool
2443 print_symtab (Ebl *ebl, int type)
2444 {
2445   /* Find the symbol table(s).  For this we have to search through the
2446      section table.  */
2447   Elf_Scn *scn = NULL;
2448   bool symtab_printed = false;
2449
2450   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
2451     {
2452       /* Handle the section if it is a symbol table.  */
2453       GElf_Shdr shdr_mem;
2454       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
2455
2456       if (shdr != NULL && shdr->sh_type == (GElf_Word) type)
2457         {
2458           if (symbol_table_section != NULL)
2459             {
2460               /* Get the section header string table index.  */
2461               size_t shstrndx;
2462               const char *sname;
2463               if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2464                 error_exit (0,
2465                             _("cannot get section header string table index"));
2466               sname = elf_strptr (ebl->elf, shstrndx, shdr->sh_name);
2467               if (sname == NULL || strcmp (sname, symbol_table_section) != 0)
2468                 continue;
2469             }
2470
2471           if ((shdr->sh_flags & SHF_COMPRESSED) != 0)
2472             {
2473               if (elf_compress (scn, 0, 0) < 0)
2474                 printf ("WARNING: %s [%zd]\n",
2475                         _("Couldn't uncompress section"),
2476                         elf_ndxscn (scn));
2477               shdr = gelf_getshdr (scn, &shdr_mem);
2478               if (unlikely (shdr == NULL))
2479                 error_exit (0,
2480                             _("cannot get section [%zd] header: %s"),
2481                             elf_ndxscn (scn), elf_errmsg (-1));
2482             }
2483           handle_symtab (ebl, scn, shdr);
2484           symtab_printed = true;
2485         }
2486     }
2487
2488   return symtab_printed;
2489 }
2490
2491
2492 static void
2493 handle_symtab (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
2494 {
2495   Elf_Data *versym_data = NULL;
2496   Elf_Data *verneed_data = NULL;
2497   Elf_Data *verdef_data = NULL;
2498   Elf_Data *xndx_data = NULL;
2499   int class = gelf_getclass (ebl->elf);
2500   Elf32_Word verneed_stridx = 0;
2501   Elf32_Word verdef_stridx = 0;
2502
2503   /* Get the data of the section.  */
2504   Elf_Data *data = elf_getdata (scn, NULL);
2505   if (data == NULL)
2506     return;
2507
2508   /* Find out whether we have other sections we might need.  */
2509   Elf_Scn *runscn = NULL;
2510   while ((runscn = elf_nextscn (ebl->elf, runscn)) != NULL)
2511     {
2512       GElf_Shdr runshdr_mem;
2513       GElf_Shdr *runshdr = gelf_getshdr (runscn, &runshdr_mem);
2514
2515       if (likely (runshdr != NULL))
2516         {
2517           if (runshdr->sh_type == SHT_GNU_versym
2518               && runshdr->sh_link == elf_ndxscn (scn))
2519             /* Bingo, found the version information.  Now get the data.  */
2520             versym_data = elf_getdata (runscn, NULL);
2521           else if (runshdr->sh_type == SHT_GNU_verneed)
2522             {
2523               /* This is the information about the needed versions.  */
2524               verneed_data = elf_getdata (runscn, NULL);
2525               verneed_stridx = runshdr->sh_link;
2526             }
2527           else if (runshdr->sh_type == SHT_GNU_verdef)
2528             {
2529               /* This is the information about the defined versions.  */
2530               verdef_data = elf_getdata (runscn, NULL);
2531               verdef_stridx = runshdr->sh_link;
2532             }
2533           else if (runshdr->sh_type == SHT_SYMTAB_SHNDX
2534               && runshdr->sh_link == elf_ndxscn (scn))
2535             /* Extended section index.  */
2536             xndx_data = elf_getdata (runscn, NULL);
2537         }
2538     }
2539
2540   /* Get the section header string table index.  */
2541   size_t shstrndx;
2542   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2543     error_exit (0, _("cannot get section header string table index"));
2544
2545   GElf_Shdr glink_mem;
2546   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
2547                                    &glink_mem);
2548   if (glink == NULL)
2549     error_exit (0, _("invalid sh_link value in section %zu"),
2550                 elf_ndxscn (scn));
2551
2552   /* Now we can compute the number of entries in the section.  */
2553   unsigned int nsyms = data->d_size / (class == ELFCLASS32
2554                                        ? sizeof (Elf32_Sym)
2555                                        : sizeof (Elf64_Sym));
2556
2557   printf (ngettext ("\nSymbol table [%2u] '%s' contains %u entry:\n",
2558                     "\nSymbol table [%2u] '%s' contains %u entries:\n",
2559                     nsyms),
2560           (unsigned int) elf_ndxscn (scn),
2561           elf_strptr (ebl->elf, shstrndx, shdr->sh_name), nsyms);
2562   printf (ngettext (" %lu local symbol  String table: [%2u] '%s'\n",
2563                     " %lu local symbols  String table: [%2u] '%s'\n",
2564                     shdr->sh_info),
2565           (unsigned long int) shdr->sh_info,
2566           (unsigned int) shdr->sh_link,
2567           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
2568
2569   fputs_unlocked (class == ELFCLASS32
2570                   ? _("\
2571   Num:    Value   Size Type    Bind   Vis          Ndx Name\n")
2572                   : _("\
2573   Num:            Value   Size Type    Bind   Vis          Ndx Name\n"),
2574                   stdout);
2575
2576   for (unsigned int cnt = 0; cnt < nsyms; ++cnt)
2577     {
2578       char typebuf[64];
2579       char bindbuf[64];
2580       char scnbuf[64];
2581       Elf32_Word xndx;
2582       GElf_Sym sym_mem;
2583       GElf_Sym *sym = gelf_getsymshndx (data, xndx_data, cnt, &sym_mem, &xndx);
2584
2585       if (unlikely (sym == NULL))
2586         continue;
2587
2588       /* Determine the real section index.  */
2589       if (likely (sym->st_shndx != SHN_XINDEX))
2590         xndx = sym->st_shndx;
2591
2592       printf (_("\
2593 %5u: %0*" PRIx64 " %6" PRId64 " %-7s %-6s %-9s %6s %s"),
2594               cnt,
2595               class == ELFCLASS32 ? 8 : 16,
2596               sym->st_value,
2597               sym->st_size,
2598               ebl_symbol_type_name (ebl, GELF_ST_TYPE (sym->st_info),
2599                                     typebuf, sizeof (typebuf)),
2600               ebl_symbol_binding_name (ebl, GELF_ST_BIND (sym->st_info),
2601                                        bindbuf, sizeof (bindbuf)),
2602               get_visibility_type (GELF_ST_VISIBILITY (sym->st_other)),
2603               ebl_section_name (ebl, sym->st_shndx, xndx, scnbuf,
2604                                 sizeof (scnbuf), NULL, shnum),
2605               elf_strptr (ebl->elf, shdr->sh_link, sym->st_name));
2606
2607       if (versym_data != NULL)
2608         {
2609           /* Get the version information.  */
2610           GElf_Versym versym_mem;
2611           GElf_Versym *versym = gelf_getversym (versym_data, cnt, &versym_mem);
2612
2613           if (versym != NULL && ((*versym & 0x8000) != 0 || *versym > 1))
2614             {
2615               bool is_nobits = false;
2616               bool check_def = xndx != SHN_UNDEF;
2617
2618               if (xndx < SHN_LORESERVE || sym->st_shndx == SHN_XINDEX)
2619                 {
2620                   GElf_Shdr symshdr_mem;
2621                   GElf_Shdr *symshdr =
2622                     gelf_getshdr (elf_getscn (ebl->elf, xndx), &symshdr_mem);
2623
2624                   is_nobits = (symshdr != NULL
2625                                && symshdr->sh_type == SHT_NOBITS);
2626                 }
2627
2628               if (is_nobits || ! check_def)
2629                 {
2630                   /* We must test both.  */
2631                   GElf_Vernaux vernaux_mem;
2632                   GElf_Vernaux *vernaux = NULL;
2633                   size_t vn_offset = 0;
2634
2635                   GElf_Verneed verneed_mem;
2636                   GElf_Verneed *verneed = gelf_getverneed (verneed_data, 0,
2637                                                            &verneed_mem);
2638                   while (verneed != NULL)
2639                     {
2640                       size_t vna_offset = vn_offset;
2641
2642                       vernaux = gelf_getvernaux (verneed_data,
2643                                                  vna_offset += verneed->vn_aux,
2644                                                  &vernaux_mem);
2645                       while (vernaux != NULL
2646                              && vernaux->vna_other != *versym
2647                              && vernaux->vna_next != 0
2648                              && (verneed_data->d_size - vna_offset
2649                                  >= vernaux->vna_next))
2650                         {
2651                           /* Update the offset.  */
2652                           vna_offset += vernaux->vna_next;
2653
2654                           vernaux = (vernaux->vna_next == 0
2655                                      ? NULL
2656                                      : gelf_getvernaux (verneed_data,
2657                                                         vna_offset,
2658                                                         &vernaux_mem));
2659                         }
2660
2661                       /* Check whether we found the version.  */
2662                       if (vernaux != NULL && vernaux->vna_other == *versym)
2663                         /* Found it.  */
2664                         break;
2665
2666                       if (verneed_data->d_size - vn_offset < verneed->vn_next)
2667                         break;
2668
2669                       vn_offset += verneed->vn_next;
2670                       verneed = (verneed->vn_next == 0
2671                                  ? NULL
2672                                  : gelf_getverneed (verneed_data, vn_offset,
2673                                                     &verneed_mem));
2674                     }
2675
2676                   if (vernaux != NULL && vernaux->vna_other == *versym)
2677                     {
2678                       printf ("@%s (%u)",
2679                               elf_strptr (ebl->elf, verneed_stridx,
2680                                           vernaux->vna_name),
2681                               (unsigned int) vernaux->vna_other);
2682                       check_def = 0;
2683                     }
2684                   else if (unlikely (! is_nobits))
2685                     error (0, 0, _("bad dynamic symbol"));
2686                   else
2687                     check_def = 1;
2688                 }
2689
2690               if (check_def && *versym != 0x8001)
2691                 {
2692                   /* We must test both.  */
2693                   size_t vd_offset = 0;
2694
2695                   GElf_Verdef verdef_mem;
2696                   GElf_Verdef *verdef = gelf_getverdef (verdef_data, 0,
2697                                                         &verdef_mem);
2698                   while (verdef != NULL)
2699                     {
2700                       if (verdef->vd_ndx == (*versym & 0x7fff))
2701                         /* Found the definition.  */
2702                         break;
2703
2704                       if (verdef_data->d_size - vd_offset < verdef->vd_next)
2705                         break;
2706
2707                       vd_offset += verdef->vd_next;
2708                       verdef = (verdef->vd_next == 0
2709                                 ? NULL
2710                                 : gelf_getverdef (verdef_data, vd_offset,
2711                                                   &verdef_mem));
2712                     }
2713
2714                   if (verdef != NULL)
2715                     {
2716                       GElf_Verdaux verdaux_mem;
2717                       GElf_Verdaux *verdaux
2718                         = gelf_getverdaux (verdef_data,
2719                                            vd_offset + verdef->vd_aux,
2720                                            &verdaux_mem);
2721
2722                       if (verdaux != NULL)
2723                         printf ((*versym & 0x8000) ? "@%s" : "@@%s",
2724                                 elf_strptr (ebl->elf, verdef_stridx,
2725                                             verdaux->vda_name));
2726                     }
2727                 }
2728             }
2729         }
2730
2731       putchar_unlocked ('\n');
2732     }
2733 }
2734
2735
2736 /* Print version information.  */
2737 static void
2738 print_verinfo (Ebl *ebl)
2739 {
2740   /* Find the version information sections.  For this we have to
2741      search through the section table.  */
2742   Elf_Scn *scn = NULL;
2743
2744   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
2745     {
2746       /* Handle the section if it is part of the versioning handling.  */
2747       GElf_Shdr shdr_mem;
2748       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
2749
2750       if (likely (shdr != NULL))
2751         {
2752           if (shdr->sh_type == SHT_GNU_verneed)
2753             handle_verneed (ebl, scn, shdr);
2754           else if (shdr->sh_type == SHT_GNU_verdef)
2755             handle_verdef (ebl, scn, shdr);
2756           else if (shdr->sh_type == SHT_GNU_versym)
2757             handle_versym (ebl, scn, shdr);
2758         }
2759     }
2760 }
2761
2762
2763 static const char *
2764 get_ver_flags (unsigned int flags)
2765 {
2766   static char buf[32];
2767   char *endp;
2768
2769   if (flags == 0)
2770     return _("none");
2771
2772   if (flags & VER_FLG_BASE)
2773     endp = stpcpy (buf, "BASE ");
2774   else
2775     endp = buf;
2776
2777   if (flags & VER_FLG_WEAK)
2778     {
2779       if (endp != buf)
2780         endp = stpcpy (endp, "| ");
2781
2782       endp = stpcpy (endp, "WEAK ");
2783     }
2784
2785   if (unlikely (flags & ~(VER_FLG_BASE | VER_FLG_WEAK)))
2786     {
2787       strncpy (endp, _("| <unknown>"), buf + sizeof (buf) - endp);
2788       buf[sizeof (buf) - 1] = '\0';
2789     }
2790
2791   return buf;
2792 }
2793
2794
2795 static void
2796 handle_verneed (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
2797 {
2798   int class = gelf_getclass (ebl->elf);
2799
2800   /* Get the data of the section.  */
2801   Elf_Data *data = elf_getdata (scn, NULL);
2802   if (data == NULL)
2803     return;
2804
2805   /* Get the section header string table index.  */
2806   size_t shstrndx;
2807   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2808     error_exit (0, _("cannot get section header string table index"));
2809
2810   GElf_Shdr glink_mem;
2811   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
2812                                    &glink_mem);
2813   if (glink == NULL)
2814     error_exit (0, _("invalid sh_link value in section %zu"),
2815                 elf_ndxscn (scn));
2816
2817   printf (ngettext ("\
2818 \nVersion needs section [%2u] '%s' contains %d entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2819                     "\
2820 \nVersion needs section [%2u] '%s' contains %d entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2821                     shdr->sh_info),
2822           (unsigned int) elf_ndxscn (scn),
2823           elf_strptr (ebl->elf, shstrndx, shdr->sh_name), shdr->sh_info,
2824           class == ELFCLASS32 ? 10 : 18, shdr->sh_addr,
2825           shdr->sh_offset,
2826           (unsigned int) shdr->sh_link,
2827           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
2828
2829   unsigned int offset = 0;
2830   for (int cnt = shdr->sh_info; --cnt >= 0; )
2831     {
2832       /* Get the data at the next offset.  */
2833       GElf_Verneed needmem;
2834       GElf_Verneed *need = gelf_getverneed (data, offset, &needmem);
2835       if (unlikely (need == NULL))
2836         break;
2837
2838       printf (_("  %#06x: Version: %hu  File: %s  Cnt: %hu\n"),
2839               offset, (unsigned short int) need->vn_version,
2840               elf_strptr (ebl->elf, shdr->sh_link, need->vn_file),
2841               (unsigned short int) need->vn_cnt);
2842
2843       unsigned int auxoffset = offset + need->vn_aux;
2844       for (int cnt2 = need->vn_cnt; --cnt2 >= 0; )
2845         {
2846           GElf_Vernaux auxmem;
2847           GElf_Vernaux *aux = gelf_getvernaux (data, auxoffset, &auxmem);
2848           if (unlikely (aux == NULL))
2849             break;
2850
2851           printf (_("  %#06x: Name: %s  Flags: %s  Version: %hu\n"),
2852                   auxoffset,
2853                   elf_strptr (ebl->elf, shdr->sh_link, aux->vna_name),
2854                   get_ver_flags (aux->vna_flags),
2855                   (unsigned short int) aux->vna_other);
2856
2857           if (aux->vna_next == 0)
2858             break;
2859
2860           auxoffset += aux->vna_next;
2861         }
2862
2863       /* Find the next offset.  */
2864       if (need->vn_next == 0)
2865         break;
2866
2867       offset += need->vn_next;
2868     }
2869 }
2870
2871
2872 static void
2873 handle_verdef (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
2874 {
2875   /* Get the data of the section.  */
2876   Elf_Data *data = elf_getdata (scn, NULL);
2877   if (data == NULL)
2878     return;
2879
2880   /* Get the section header string table index.  */
2881   size_t shstrndx;
2882   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2883     error_exit (0, _("cannot get section header string table index"));
2884
2885   GElf_Shdr glink_mem;
2886   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
2887                                    &glink_mem);
2888   if (glink == NULL)
2889     error_exit (0, _("invalid sh_link value in section %zu"),
2890                 elf_ndxscn (scn));
2891
2892   int class = gelf_getclass (ebl->elf);
2893   printf (ngettext ("\
2894 \nVersion definition section [%2u] '%s' contains %d entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2895                     "\
2896 \nVersion definition section [%2u] '%s' contains %d entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'\n",
2897                     shdr->sh_info),
2898           (unsigned int) elf_ndxscn (scn),
2899           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
2900           shdr->sh_info,
2901           class == ELFCLASS32 ? 10 : 18, shdr->sh_addr,
2902           shdr->sh_offset,
2903           (unsigned int) shdr->sh_link,
2904           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
2905
2906   unsigned int offset = 0;
2907   for (int cnt = shdr->sh_info; --cnt >= 0; )
2908     {
2909       /* Get the data at the next offset.  */
2910       GElf_Verdef defmem;
2911       GElf_Verdef *def = gelf_getverdef (data, offset, &defmem);
2912       if (unlikely (def == NULL))
2913         break;
2914
2915       unsigned int auxoffset = offset + def->vd_aux;
2916       GElf_Verdaux auxmem;
2917       GElf_Verdaux *aux = gelf_getverdaux (data, auxoffset, &auxmem);
2918       if (unlikely (aux == NULL))
2919         break;
2920
2921       printf (_("\
2922   %#06x: Version: %hd  Flags: %s  Index: %hd  Cnt: %hd  Name: %s\n"),
2923               offset, def->vd_version,
2924               get_ver_flags (def->vd_flags),
2925               def->vd_ndx,
2926               def->vd_cnt,
2927               elf_strptr (ebl->elf, shdr->sh_link, aux->vda_name));
2928
2929       auxoffset += aux->vda_next;
2930       for (int cnt2 = 1; cnt2 < def->vd_cnt; ++cnt2)
2931         {
2932           aux = gelf_getverdaux (data, auxoffset, &auxmem);
2933           if (unlikely (aux == NULL))
2934             break;
2935
2936           printf (_("  %#06x: Parent %d: %s\n"),
2937                   auxoffset, cnt2,
2938                   elf_strptr (ebl->elf, shdr->sh_link, aux->vda_name));
2939
2940           if (aux->vda_next == 0)
2941             break;
2942
2943           auxoffset += aux->vda_next;
2944         }
2945
2946       /* Find the next offset.  */
2947       if (def->vd_next == 0)
2948         break;
2949       offset += def->vd_next;
2950     }
2951 }
2952
2953
2954 static void
2955 handle_versym (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr)
2956 {
2957   int class = gelf_getclass (ebl->elf);
2958   const char **vername;
2959   const char **filename;
2960
2961   /* Get the data of the section.  */
2962   Elf_Data *data = elf_getdata (scn, NULL);
2963   if (data == NULL)
2964     return;
2965
2966   /* Get the section header string table index.  */
2967   size_t shstrndx;
2968   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
2969     error_exit (0, _("cannot get section header string table index"));
2970
2971   /* We have to find the version definition section and extract the
2972      version names.  */
2973   Elf_Scn *defscn = NULL;
2974   Elf_Scn *needscn = NULL;
2975
2976   Elf_Scn *verscn = NULL;
2977   while ((verscn = elf_nextscn (ebl->elf, verscn)) != NULL)
2978     {
2979       GElf_Shdr vershdr_mem;
2980       GElf_Shdr *vershdr = gelf_getshdr (verscn, &vershdr_mem);
2981
2982       if (likely (vershdr != NULL))
2983         {
2984           if (vershdr->sh_type == SHT_GNU_verdef)
2985             defscn = verscn;
2986           else if (vershdr->sh_type == SHT_GNU_verneed)
2987             needscn = verscn;
2988         }
2989     }
2990
2991   size_t nvername;
2992   if (defscn != NULL || needscn != NULL)
2993     {
2994       /* We have a version information (better should have).  Now get
2995          the version names.  First find the maximum version number.  */
2996       nvername = 0;
2997       if (defscn != NULL)
2998         {
2999           /* Run through the version definitions and find the highest
3000              index.  */
3001           unsigned int offset = 0;
3002           Elf_Data *defdata;
3003           GElf_Shdr defshdrmem;
3004           GElf_Shdr *defshdr;
3005
3006           defdata = elf_getdata (defscn, NULL);
3007           if (unlikely (defdata == NULL))
3008             return;
3009
3010           defshdr = gelf_getshdr (defscn, &defshdrmem);
3011           if (unlikely (defshdr == NULL))
3012             return;
3013
3014           for (unsigned int cnt = 0; cnt < defshdr->sh_info; ++cnt)
3015             {
3016               GElf_Verdef defmem;
3017               GElf_Verdef *def;
3018
3019               /* Get the data at the next offset.  */
3020               def = gelf_getverdef (defdata, offset, &defmem);
3021               if (unlikely (def == NULL))
3022                 break;
3023
3024               nvername = MAX (nvername, (size_t) (def->vd_ndx & 0x7fff));
3025
3026               if (def->vd_next == 0)
3027                 break;
3028               offset += def->vd_next;
3029             }
3030         }
3031       if (needscn != NULL)
3032         {
3033           unsigned int offset = 0;
3034           Elf_Data *needdata;
3035           GElf_Shdr needshdrmem;
3036           GElf_Shdr *needshdr;
3037
3038           needdata = elf_getdata (needscn, NULL);
3039           if (unlikely (needdata == NULL))
3040             return;
3041
3042           needshdr = gelf_getshdr (needscn, &needshdrmem);
3043           if (unlikely (needshdr == NULL))
3044             return;
3045
3046           for (unsigned int cnt = 0; cnt < needshdr->sh_info; ++cnt)
3047             {
3048               GElf_Verneed needmem;
3049               GElf_Verneed *need;
3050               unsigned int auxoffset;
3051               int cnt2;
3052
3053               /* Get the data at the next offset.  */
3054               need = gelf_getverneed (needdata, offset, &needmem);
3055               if (unlikely (need == NULL))
3056                 break;
3057
3058               /* Run through the auxiliary entries.  */
3059               auxoffset = offset + need->vn_aux;
3060               for (cnt2 = need->vn_cnt; --cnt2 >= 0; )
3061                 {
3062                   GElf_Vernaux auxmem;
3063                   GElf_Vernaux *aux;
3064
3065                   aux = gelf_getvernaux (needdata, auxoffset, &auxmem);
3066                   if (unlikely (aux == NULL))
3067                     break;
3068
3069                   nvername = MAX (nvername,
3070                                   (size_t) (aux->vna_other & 0x7fff));
3071
3072                   if (aux->vna_next == 0)
3073                     break;
3074                   auxoffset += aux->vna_next;
3075                 }
3076
3077               if (need->vn_next == 0)
3078                 break;
3079               offset += need->vn_next;
3080             }
3081         }
3082
3083       /* This is the number of versions we know about.  */
3084       ++nvername;
3085
3086       /* Allocate the array.  */
3087       vername = (const char **) alloca (nvername * sizeof (const char *));
3088       memset(vername, 0, nvername * sizeof (const char *));
3089       filename = (const char **) alloca (nvername * sizeof (const char *));
3090       memset(filename, 0, nvername * sizeof (const char *));
3091
3092       /* Run through the data structures again and collect the strings.  */
3093       if (defscn != NULL)
3094         {
3095           /* Run through the version definitions and find the highest
3096              index.  */
3097           unsigned int offset = 0;
3098           Elf_Data *defdata;
3099           GElf_Shdr defshdrmem;
3100           GElf_Shdr *defshdr;
3101
3102           defdata = elf_getdata (defscn, NULL);
3103           if (unlikely (defdata == NULL))
3104             return;
3105
3106           defshdr = gelf_getshdr (defscn, &defshdrmem);
3107           if (unlikely (defshdr == NULL))
3108             return;
3109
3110           for (unsigned int cnt = 0; cnt < defshdr->sh_info; ++cnt)
3111             {
3112
3113               /* Get the data at the next offset.  */
3114               GElf_Verdef defmem;
3115               GElf_Verdef *def = gelf_getverdef (defdata, offset, &defmem);
3116               if (unlikely (def == NULL))
3117                 break;
3118
3119               GElf_Verdaux auxmem;
3120               GElf_Verdaux *aux = gelf_getverdaux (defdata,
3121                                                    offset + def->vd_aux,
3122                                                    &auxmem);
3123               if (unlikely (aux == NULL))
3124                 break;
3125
3126               vername[def->vd_ndx & 0x7fff]
3127                 = elf_strptr (ebl->elf, defshdr->sh_link, aux->vda_name);
3128               filename[def->vd_ndx & 0x7fff] = NULL;
3129
3130               if (def->vd_next == 0)
3131                 break;
3132               offset += def->vd_next;
3133             }
3134         }
3135       if (needscn != NULL)
3136         {
3137           unsigned int offset = 0;
3138
3139           Elf_Data *needdata = elf_getdata (needscn, NULL);
3140           GElf_Shdr needshdrmem;
3141           GElf_Shdr *needshdr = gelf_getshdr (needscn, &needshdrmem);
3142           if (unlikely (needdata == NULL || needshdr == NULL))
3143             return;
3144
3145           for (unsigned int cnt = 0; cnt < needshdr->sh_info; ++cnt)
3146             {
3147               /* Get the data at the next offset.  */
3148               GElf_Verneed needmem;
3149               GElf_Verneed *need = gelf_getverneed (needdata, offset,
3150                                                     &needmem);
3151               if (unlikely (need == NULL))
3152                 break;
3153
3154               /* Run through the auxiliary entries.  */
3155               unsigned int auxoffset = offset + need->vn_aux;
3156               for (int cnt2 = need->vn_cnt; --cnt2 >= 0; )
3157                 {
3158                   GElf_Vernaux auxmem;
3159                   GElf_Vernaux *aux = gelf_getvernaux (needdata, auxoffset,
3160                                                        &auxmem);
3161                   if (unlikely (aux == NULL))
3162                     break;
3163
3164                   vername[aux->vna_other & 0x7fff]
3165                     = elf_strptr (ebl->elf, needshdr->sh_link, aux->vna_name);
3166                   filename[aux->vna_other & 0x7fff]
3167                     = elf_strptr (ebl->elf, needshdr->sh_link, need->vn_file);
3168
3169                   if (aux->vna_next == 0)
3170                     break;
3171                   auxoffset += aux->vna_next;
3172                 }
3173
3174               if (need->vn_next == 0)
3175                 break;
3176               offset += need->vn_next;
3177             }
3178         }
3179     }
3180   else
3181     {
3182       vername = NULL;
3183       nvername = 1;
3184       filename = NULL;
3185     }
3186
3187   GElf_Shdr glink_mem;
3188   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
3189                                    &glink_mem);
3190   size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_HALF, 1, EV_CURRENT);
3191   if (glink == NULL)
3192     error_exit (0, _("invalid sh_link value in section %zu"),
3193                 elf_ndxscn (scn));
3194
3195   /* Print the header.  */
3196   printf (ngettext ("\
3197 \nVersion symbols section [%2u] '%s' contains %d entry:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'",
3198                     "\
3199 \nVersion symbols section [%2u] '%s' contains %d entries:\n Addr: %#0*" PRIx64 "  Offset: %#08" PRIx64 "  Link to section: [%2u] '%s'",
3200                     shdr->sh_size / sh_entsize),
3201           (unsigned int) elf_ndxscn (scn),
3202           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
3203           (int) (shdr->sh_size / sh_entsize),
3204           class == ELFCLASS32 ? 10 : 18, shdr->sh_addr,
3205           shdr->sh_offset,
3206           (unsigned int) shdr->sh_link,
3207           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
3208
3209   /* Now we can finally look at the actual contents of this section.  */
3210   for (unsigned int cnt = 0; cnt < shdr->sh_size / sh_entsize; ++cnt)
3211     {
3212       if (cnt % 2 == 0)
3213         printf ("\n %4d:", cnt);
3214
3215       GElf_Versym symmem;
3216       GElf_Versym *sym = gelf_getversym (data, cnt, &symmem);
3217       if (sym == NULL)
3218         break;
3219
3220       switch (*sym)
3221         {
3222           ssize_t n;
3223         case 0:
3224           fputs_unlocked (_("   0 *local*                     "),
3225                           stdout);
3226           break;
3227
3228         case 1:
3229           fputs_unlocked (_("   1 *global*                    "),
3230                           stdout);
3231           break;
3232
3233         default:
3234           n = printf ("%4d%c%s",
3235                       *sym & 0x7fff, *sym & 0x8000 ? 'h' : ' ',
3236                       (vername != NULL
3237                        && (unsigned int) (*sym & 0x7fff) < nvername)
3238                       ? vername[*sym & 0x7fff] : "???");
3239           if ((unsigned int) (*sym & 0x7fff) < nvername
3240               && filename != NULL && filename[*sym & 0x7fff] != NULL)
3241             n += printf ("(%s)", filename[*sym & 0x7fff]);
3242           printf ("%*s", MAX (0, 33 - (int) n), " ");
3243           break;
3244         }
3245     }
3246   putchar_unlocked ('\n');
3247 }
3248
3249
3250 static void
3251 print_hash_info (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, size_t shstrndx,
3252                  uint_fast32_t maxlength, Elf32_Word nbucket,
3253                  uint_fast32_t nsyms, uint32_t *lengths, const char *extrastr)
3254 {
3255   uint32_t *counts = xcalloc (maxlength + 1, sizeof (uint32_t));
3256
3257   for (Elf32_Word cnt = 0; cnt < nbucket; ++cnt)
3258     ++counts[lengths[cnt]];
3259
3260   GElf_Shdr glink_mem;
3261   GElf_Shdr *glink = gelf_getshdr (elf_getscn (ebl->elf,
3262                                                shdr->sh_link),
3263                                    &glink_mem);
3264   if (glink == NULL)
3265     {
3266       error (0, 0, _("invalid sh_link value in section %zu"),
3267              elf_ndxscn (scn));
3268       return;
3269     }
3270
3271   printf (ngettext ("\
3272 \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",
3273                     "\
3274 \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",
3275                     nbucket),
3276           (unsigned int) elf_ndxscn (scn),
3277           elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
3278           (int) nbucket,
3279           gelf_getclass (ebl->elf) == ELFCLASS32 ? 10 : 18,
3280           shdr->sh_addr,
3281           shdr->sh_offset,
3282           (unsigned int) shdr->sh_link,
3283           elf_strptr (ebl->elf, shstrndx, glink->sh_name));
3284
3285   if (extrastr != NULL)
3286     fputs (extrastr, stdout);
3287
3288   if (likely (nbucket > 0))
3289     {
3290       uint64_t success = 0;
3291
3292       /* xgettext:no-c-format */
3293       fputs_unlocked (_("\
3294  Length  Number  % of total  Coverage\n"), stdout);
3295       printf (_("      0  %6" PRIu32 "      %5.1f%%\n"),
3296               counts[0], (counts[0] * 100.0) / nbucket);
3297
3298       uint64_t nzero_counts = 0;
3299       for (Elf32_Word cnt = 1; cnt <= maxlength; ++cnt)
3300         {
3301           nzero_counts += counts[cnt] * cnt;
3302           printf (_("\
3303 %7d  %6" PRIu32 "      %5.1f%%    %5.1f%%\n"),
3304                   (int) cnt, counts[cnt], (counts[cnt] * 100.0) / nbucket,
3305                   (nzero_counts * 100.0) / nsyms);
3306         }
3307
3308       Elf32_Word acc = 0;
3309       for (Elf32_Word cnt = 1; cnt <= maxlength; ++cnt)
3310         {
3311           acc += cnt;
3312           success += counts[cnt] * acc;
3313         }
3314
3315       printf (_("\
3316  Average number of tests:   successful lookup: %f\n\
3317                           unsuccessful lookup: %f\n"),
3318               (double) success / (double) nzero_counts,
3319               (double) nzero_counts / (double) nbucket);
3320     }
3321
3322   free (counts);
3323 }
3324
3325
3326 /* This function handles the traditional System V-style hash table format.  */
3327 static void
3328 handle_sysv_hash (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, size_t shstrndx)
3329 {
3330   Elf_Data *data = elf_getdata (scn, NULL);
3331   if (unlikely (data == NULL))
3332     {
3333       error (0, 0, _("cannot get data for section %d: %s"),
3334              (int) elf_ndxscn (scn), elf_errmsg (-1));
3335       return;
3336     }
3337
3338   if (unlikely (data->d_size < 2 * sizeof (Elf32_Word)))
3339     {
3340     invalid_data:
3341       error (0, 0, _("invalid data in sysv.hash section %d"),
3342              (int) elf_ndxscn (scn));
3343       return;
3344     }
3345
3346   Elf32_Word nbucket = ((Elf32_Word *) data->d_buf)[0];
3347   Elf32_Word nchain = ((Elf32_Word *) data->d_buf)[1];
3348
3349   uint64_t used_buf = (2ULL + nchain + nbucket) * sizeof (Elf32_Word);
3350   if (used_buf > data->d_size)
3351     goto invalid_data;
3352
3353   Elf32_Word *bucket = &((Elf32_Word *) data->d_buf)[2];
3354   Elf32_Word *chain = &((Elf32_Word *) data->d_buf)[2 + nbucket];
3355
3356   uint32_t *lengths = xcalloc (nbucket, sizeof (uint32_t));
3357
3358   uint_fast32_t maxlength = 0;
3359   uint_fast32_t nsyms = 0;
3360   for (Elf32_Word cnt = 0; cnt < nbucket; ++cnt)
3361     {
3362       Elf32_Word inner = bucket[cnt];
3363       Elf32_Word chain_len = 0;
3364       while (inner > 0 && inner < nchain)
3365         {
3366           ++nsyms;
3367           ++chain_len;
3368           if (chain_len > nchain)
3369             {
3370               error (0, 0, _("invalid chain in sysv.hash section %d"),
3371                      (int) elf_ndxscn (scn));
3372               free (lengths);
3373               return;
3374             }
3375           if (maxlength < ++lengths[cnt])
3376             ++maxlength;
3377
3378           inner = chain[inner];
3379         }
3380     }
3381
3382   print_hash_info (ebl, scn, shdr, shstrndx, maxlength, nbucket, nsyms,
3383                    lengths, NULL);
3384
3385   free (lengths);
3386 }
3387
3388
3389 /* This function handles the incorrect, System V-style hash table
3390    format some 64-bit architectures use.  */
3391 static void
3392 handle_sysv_hash64 (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, size_t shstrndx)
3393 {
3394   Elf_Data *data = elf_getdata (scn, NULL);
3395   if (unlikely (data == NULL))
3396     {
3397       error (0, 0, _("cannot get data for section %d: %s"),
3398              (int) elf_ndxscn (scn), elf_errmsg (-1));
3399       return;
3400     }
3401
3402   if (unlikely (data->d_size < 2 * sizeof (Elf64_Xword)))
3403     {
3404     invalid_data:
3405       error (0, 0, _("invalid data in sysv.hash64 section %d"),
3406              (int) elf_ndxscn (scn));
3407       return;
3408     }
3409
3410   Elf64_Xword nbucket = ((Elf64_Xword *) data->d_buf)[0];
3411   Elf64_Xword nchain = ((Elf64_Xword *) data->d_buf)[1];
3412
3413   uint64_t maxwords = data->d_size / sizeof (Elf64_Xword);
3414   if (maxwords < 2
3415       || maxwords - 2 < nbucket
3416       || maxwords - 2 - nbucket < nchain)
3417     goto invalid_data;
3418
3419   Elf64_Xword *bucket = &((Elf64_Xword *) data->d_buf)[2];
3420   Elf64_Xword *chain = &((Elf64_Xword *) data->d_buf)[2 + nbucket];
3421
3422   uint32_t *lengths = xcalloc (nbucket, sizeof (uint32_t));
3423
3424   uint_fast32_t maxlength = 0;
3425   uint_fast32_t nsyms = 0;
3426   for (Elf64_Xword cnt = 0; cnt < nbucket; ++cnt)
3427     {
3428       Elf64_Xword inner = bucket[cnt];
3429       Elf64_Xword chain_len = 0;
3430       while (inner > 0 && inner < nchain)
3431         {
3432           ++nsyms;
3433           ++chain_len;
3434           if (chain_len > nchain)
3435             {
3436               error (0, 0, _("invalid chain in sysv.hash64 section %d"),
3437                      (int) elf_ndxscn (scn));
3438               free (lengths);
3439               return;
3440             }
3441           if (maxlength < ++lengths[cnt])
3442             ++maxlength;
3443
3444           inner = chain[inner];
3445         }
3446     }
3447
3448   print_hash_info (ebl, scn, shdr, shstrndx, maxlength, nbucket, nsyms,
3449                    lengths, NULL);
3450
3451   free (lengths);
3452 }
3453
3454
3455 /* This function handles the GNU-style hash table format.  */
3456 static void
3457 handle_gnu_hash (Ebl *ebl, Elf_Scn *scn, GElf_Shdr *shdr, size_t shstrndx)
3458 {
3459   uint32_t *lengths = NULL;
3460   Elf_Data *data = elf_getdata (scn, NULL);
3461   if (unlikely (data == NULL))
3462     {
3463       error (0, 0, _("cannot get data for section %d: %s"),
3464              (int) elf_ndxscn (scn), elf_errmsg (-1));
3465       return;
3466     }
3467
3468   if (unlikely (data->d_size < 4 * sizeof (Elf32_Word)))
3469     {
3470     invalid_data:
3471       free (lengths);
3472       error (0, 0, _("invalid data in gnu.hash section %d"),
3473              (int) elf_ndxscn (scn));
3474       return;
3475     }
3476
3477   Elf32_Word nbucket = ((Elf32_Word *) data->d_buf)[0];
3478   Elf32_Word symbias = ((Elf32_Word *) data->d_buf)[1];
3479
3480   /* Next comes the size of the bitmap.  It's measured in words for
3481      the architecture.  It's 32 bits for 32 bit archs, and 64 bits for
3482      64 bit archs.  There is always a bloom filter present, so zero is
3483      an invalid value.  */
3484   Elf32_Word bitmask_words = ((Elf32_Word *) data->d_buf)[2];
3485   if (gelf_getclass (ebl->elf) == ELFCLASS64)
3486     bitmask_words *= 2;
3487
3488   if (bitmask_words == 0)
3489     goto invalid_data;
3490
3491   Elf32_Word shift = ((Elf32_Word *) data->d_buf)[3];
3492
3493   /* Is there still room for the sym chain?
3494      Use uint64_t calculation to prevent 32bit overflow.  */
3495   uint64_t used_buf = (4ULL + bitmask_words + nbucket) * sizeof (Elf32_Word);
3496   uint32_t max_nsyms = (data->d_size - used_buf) / sizeof (Elf32_Word);
3497   if (used_buf > data->d_size)
3498     goto invalid_data;
3499
3500   lengths = xcalloc (nbucket, sizeof (uint32_t));
3501
3502   Elf32_Word *bitmask = &((Elf32_Word *) data->d_buf)[4];
3503   Elf32_Word *bucket = &((Elf32_Word *) data->d_buf)[4 + bitmask_words];
3504   Elf32_Word *chain = &((Elf32_Word *) data->d_buf)[4 + bitmask_words
3505                                                     + nbucket];
3506
3507   /* Compute distribution of chain lengths.  */
3508   uint_fast32_t maxlength = 0;
3509   uint_fast32_t nsyms = 0;
3510   for (Elf32_Word cnt = 0; cnt < nbucket; ++cnt)
3511     if (bucket[cnt] != 0)
3512       {
3513         Elf32_Word inner = bucket[cnt] - symbias;
3514         do
3515           {
3516             ++nsyms;
3517             if (maxlength < ++lengths[cnt])
3518               ++maxlength;
3519             if (inner >= max_nsyms)
3520               goto invalid_data;
3521           }
3522         while ((chain[inner++] & 1) == 0);
3523       }
3524
3525   /* Count bits in bitmask.  */
3526   uint_fast32_t nbits = 0;
3527   for (Elf32_Word cnt = 0; cnt < bitmask_words; ++cnt)
3528     {
3529       uint_fast32_t word = bitmask[cnt];
3530
3531       word = (word & 0x55555555) + ((word >> 1) & 0x55555555);
3532       word = (word & 0x33333333) + ((word >> 2) & 0x33333333);
3533       word = (word & 0x0f0f0f0f) + ((word >> 4) & 0x0f0f0f0f);
3534       word = (word & 0x00ff00ff) + ((word >> 8) & 0x00ff00ff);
3535       nbits += (word & 0x0000ffff) + ((word >> 16) & 0x0000ffff);
3536     }
3537
3538   char *str = xasprintf (_("\
3539  Symbol Bias: %u\n\
3540  Bitmask Size: %zu bytes  %" PRIuFAST32 "%% bits set  2nd hash shift: %u\n"),
3541                          (unsigned int) symbias,
3542                          bitmask_words * sizeof (Elf32_Word),
3543                          ((nbits * 100 + 50)
3544                           / (uint_fast32_t) (bitmask_words
3545                                               * sizeof (Elf32_Word) * 8)),
3546                           (unsigned int) shift);
3547
3548   print_hash_info (ebl, scn, shdr, shstrndx, maxlength, nbucket, nsyms,
3549                    lengths, str);
3550
3551   free (str);
3552   free (lengths);
3553 }
3554
3555
3556 /* Find the symbol table(s).  For this we have to search through the
3557    section table.  */
3558 static void
3559 handle_hash (Ebl *ebl)
3560 {
3561   /* Get the section header string table index.  */
3562   size_t shstrndx;
3563   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
3564     error_exit (0, _("cannot get section header string table index"));
3565
3566   Elf_Scn *scn = NULL;
3567   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
3568     {
3569       /* Handle the section if it is a symbol table.  */
3570       GElf_Shdr shdr_mem;
3571       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
3572
3573       if (likely (shdr != NULL))
3574         {
3575           if ((shdr->sh_type == SHT_HASH || shdr->sh_type == SHT_GNU_HASH)
3576               && (shdr->sh_flags & SHF_COMPRESSED) != 0)
3577             {
3578               if (elf_compress (scn, 0, 0) < 0)
3579                 printf ("WARNING: %s [%zd]\n",
3580                         _("Couldn't uncompress section"),
3581                         elf_ndxscn (scn));
3582               shdr = gelf_getshdr (scn, &shdr_mem);
3583               if (unlikely (shdr == NULL))
3584                 error_exit (0, _("cannot get section [%zd] header: %s"),
3585                             elf_ndxscn (scn), elf_errmsg (-1));
3586             }
3587
3588           if (shdr->sh_type == SHT_HASH)
3589             {
3590               if (ebl_sysvhash_entrysize (ebl) == sizeof (Elf64_Xword))
3591                 handle_sysv_hash64 (ebl, scn, shdr, shstrndx);
3592               else
3593                 handle_sysv_hash (ebl, scn, shdr, shstrndx);
3594             }
3595           else if (shdr->sh_type == SHT_GNU_HASH)
3596             handle_gnu_hash (ebl, scn, shdr, shstrndx);
3597         }
3598     }
3599 }
3600
3601
3602 static void
3603 print_liblist (Ebl *ebl)
3604 {
3605   /* Find the library list sections.  For this we have to search
3606      through the section table.  */
3607   Elf_Scn *scn = NULL;
3608
3609   /* Get the section header string table index.  */
3610   size_t shstrndx;
3611   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
3612     error_exit (0, _("cannot get section header string table index"));
3613
3614   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
3615     {
3616       GElf_Shdr shdr_mem;
3617       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
3618
3619       if (shdr != NULL && shdr->sh_type == SHT_GNU_LIBLIST)
3620         {
3621           size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_LIB, 1, EV_CURRENT);
3622           int nentries = shdr->sh_size / sh_entsize;
3623           printf (ngettext ("\
3624 \nLibrary list section [%2zu] '%s' at offset %#0" PRIx64 " contains %d entry:\n",
3625                             "\
3626 \nLibrary list section [%2zu] '%s' at offset %#0" PRIx64 " contains %d entries:\n",
3627                             nentries),
3628                   elf_ndxscn (scn),
3629                   elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
3630                   shdr->sh_offset,
3631                   nentries);
3632
3633           Elf_Data *data = elf_getdata (scn, NULL);
3634           if (data == NULL)
3635             return;
3636
3637           puts (_("\
3638        Library                       Time Stamp          Checksum Version Flags"));
3639
3640           for (int cnt = 0; cnt < nentries; ++cnt)
3641             {
3642               GElf_Lib lib_mem;
3643               GElf_Lib *lib = gelf_getlib (data, cnt, &lib_mem);
3644               if (unlikely (lib == NULL))
3645                 continue;
3646
3647               time_t t = (time_t) lib->l_time_stamp;
3648               struct tm *tm = gmtime (&t);
3649               if (unlikely (tm == NULL))
3650                 continue;
3651
3652               printf ("  [%2d] %-29s %04u-%02u-%02uT%02u:%02u:%02u %08x %-7u %u\n",
3653                       cnt, elf_strptr (ebl->elf, shdr->sh_link, lib->l_name),
3654                       tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
3655                       tm->tm_hour, tm->tm_min, tm->tm_sec,
3656                       (unsigned int) lib->l_checksum,
3657                       (unsigned int) lib->l_version,
3658                       (unsigned int) lib->l_flags);
3659             }
3660         }
3661     }
3662 }
3663
3664 static inline size_t
3665 left (Elf_Data *data,
3666       const unsigned char *p)
3667 {
3668   return (const unsigned char *) data->d_buf + data->d_size - p;
3669 }
3670
3671 static void
3672 print_attributes (Ebl *ebl, const GElf_Ehdr *ehdr)
3673 {
3674   /* Find the object attributes sections.  For this we have to search
3675      through the section table.  */
3676   Elf_Scn *scn = NULL;
3677
3678   /* Get the section header string table index.  */
3679   size_t shstrndx;
3680   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
3681     error_exit (0, _("cannot get section header string table index"));
3682
3683   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
3684     {
3685       GElf_Shdr shdr_mem;
3686       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
3687
3688       if (shdr == NULL || (shdr->sh_type != SHT_GNU_ATTRIBUTES
3689                            && (shdr->sh_type != SHT_ARM_ATTRIBUTES
3690                                || ehdr->e_machine != EM_ARM)
3691                            && (shdr->sh_type != SHT_CSKY_ATTRIBUTES
3692                                || ehdr->e_machine != EM_CSKY)
3693                            && (shdr->sh_type != SHT_RISCV_ATTRIBUTES
3694                                || ehdr->e_machine != EM_RISCV)))
3695         continue;
3696
3697       printf (_("\
3698 \nObject attributes section [%2zu] '%s' of %" PRIu64
3699                        " bytes at offset %#0" PRIx64 ":\n"),
3700               elf_ndxscn (scn),
3701               elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
3702               shdr->sh_size, shdr->sh_offset);
3703
3704       Elf_Data *data = elf_rawdata (scn, NULL);
3705       if (unlikely (data == NULL || data->d_size == 0))
3706         return;
3707
3708       const unsigned char *p = data->d_buf;
3709
3710       /* There is only one 'version', A.  */
3711       if (unlikely (*p++ != 'A'))
3712         return;
3713
3714       fputs_unlocked (_("  Owner          Size\n"), stdout);
3715
3716       /* Loop over the sections.  */
3717       while (left (data, p) >= 4)
3718         {
3719           /* Section length.  */
3720           uint32_t len;
3721           memcpy (&len, p, sizeof len);
3722
3723           if (MY_ELFDATA != ehdr->e_ident[EI_DATA])
3724             CONVERT (len);
3725
3726           if (unlikely (len > left (data, p)))
3727             break;
3728
3729           /* Section vendor name.  */
3730           const unsigned char *name = p + sizeof len;
3731           p += len;
3732
3733           unsigned const char *q = memchr (name, '\0', len);
3734           if (unlikely (q == NULL))
3735             break;
3736           ++q;
3737
3738           printf (_("  %-13s  %4" PRIu32 "\n"), name, len);
3739
3740           bool gnu_vendor = (q - name == sizeof "gnu"
3741                              && !memcmp (name, "gnu", sizeof "gnu"));
3742
3743           /* Loop over subsections.  */
3744           if (shdr->sh_type != SHT_GNU_ATTRIBUTES
3745               || gnu_vendor)
3746             while (q < p)
3747               {
3748                 const unsigned char *const sub = q;
3749
3750                 unsigned int subsection_tag;
3751                 get_uleb128 (subsection_tag, q, p);
3752                 if (unlikely (q >= p))
3753                   break;
3754
3755                 uint32_t subsection_len;
3756                 if (unlikely (p - sub < (ptrdiff_t) sizeof subsection_len))
3757                   break;
3758
3759                 memcpy (&subsection_len, q, sizeof subsection_len);
3760
3761                 if (MY_ELFDATA != ehdr->e_ident[EI_DATA])
3762                   CONVERT (subsection_len);
3763
3764                 /* Don't overflow, ptrdiff_t might be 32bits, but signed.  */
3765                 if (unlikely (subsection_len == 0
3766                               || subsection_len >= (uint32_t) PTRDIFF_MAX
3767                               || p - sub < (ptrdiff_t) subsection_len))
3768                   break;
3769
3770                 const unsigned char *r = q + sizeof subsection_len;
3771                 q = sub + subsection_len;
3772
3773                 switch (subsection_tag)
3774                   {
3775                   default:
3776                     /* Unknown subsection, print and skip.  */
3777                     printf (_("    %-4u %12" PRIu32 "\n"),
3778                             subsection_tag, subsection_len);
3779                     break;
3780
3781                   case 1:       /* Tag_File */
3782                     printf (_("    File: %11" PRIu32 "\n"),
3783                             subsection_len);
3784
3785                     while (r < q)
3786                       {
3787                         unsigned int tag;
3788                         get_uleb128 (tag, r, q);
3789                         if (unlikely (r >= q))
3790                           break;
3791
3792                         /* GNU style tags have either a uleb128 value,
3793                            when lowest bit is not set, or a string
3794                            when the lowest bit is set.
3795                            "compatibility" (32) is special.  It has
3796                            both a string and a uleb128 value.  For
3797                            non-gnu we assume 6 till 31 only take ints.
3798                            XXX see arm backend, do we need a separate
3799                            hook?  */
3800                         uint64_t value = 0;
3801                         const char *string = NULL;
3802                         if (tag == 32 || (tag & 1) == 0
3803                             || (! gnu_vendor && (tag > 5 && tag < 32)))
3804                           {
3805                             get_uleb128 (value, r, q);
3806                             if (r > q)
3807                               break;
3808                           }
3809                         if (tag == 32
3810                             || ((tag & 1) != 0
3811                                 && (gnu_vendor
3812                                     || (! gnu_vendor && tag > 32)))
3813                             || (! gnu_vendor && tag > 3 && tag < 6))
3814                           {
3815                             string = (const char *) r;
3816                             r = memchr (r, '\0', q - r);
3817                             if (r == NULL)
3818                               break;
3819                             ++r;
3820                           }
3821
3822                         const char *tag_name = NULL;
3823                         const char *value_name = NULL;
3824                         ebl_check_object_attribute (ebl, (const char *) name,
3825                                                     tag, value,
3826                                                     &tag_name, &value_name);
3827
3828                         if (tag_name != NULL)
3829                           {
3830                             if (tag == 32)
3831                               printf (_("      %s: %" PRId64 ", %s\n"),
3832                                       tag_name, value, string);
3833                             else if (string == NULL && value_name == NULL)
3834                               printf (_("      %s: %" PRId64 "\n"),
3835                                       tag_name, value);
3836                             else
3837                               printf (_("      %s: %s\n"),
3838                                       tag_name, string ?: value_name);
3839                           }
3840                         else
3841                           {
3842                             /* For "gnu" vendor 32 "compatibility" has
3843                                already been handled above.  */
3844                             assert (tag != 32
3845                                     || strcmp ((const char *) name, "gnu"));
3846                             if (string == NULL)
3847                               printf (_("      %u: %" PRId64 "\n"),
3848                                       tag, value);
3849                             else
3850                               printf (_("      %u: %s\n"),
3851                                       tag, string);
3852                           }
3853                       }
3854                   }
3855               }
3856         }
3857     }
3858 }
3859
3860
3861 void
3862 print_dwarf_addr (Dwfl_Module *dwflmod,
3863                   int address_size, Dwarf_Addr address, Dwarf_Addr raw)
3864 {
3865   /* See if there is a name we can give for this address.  */
3866   GElf_Sym sym;
3867   GElf_Off off = 0;
3868   const char *name = (print_address_names && ! print_unresolved_addresses)
3869     ? dwfl_module_addrinfo (dwflmod, address, &off, &sym, NULL, NULL, NULL)
3870     : NULL;
3871
3872   const char *scn;
3873   if (print_unresolved_addresses)
3874     {
3875       address = raw;
3876       scn = NULL;
3877     }
3878   else
3879     {
3880       /* Relativize the address.  */
3881       int n = dwfl_module_relocations (dwflmod);
3882       int i = n < 1 ? -1 : dwfl_module_relocate_address (dwflmod, &address);
3883
3884       /* In an ET_REL file there is a section name to refer to.  */
3885       scn = (i < 0 ? NULL
3886              : dwfl_module_relocation_info (dwflmod, i, NULL));
3887     }
3888
3889   if ((name != NULL
3890        ? (off != 0
3891           ? (scn != NULL
3892              ? (address_size == 0
3893                 ? printf ("%s+%#" PRIx64 " <%s+%#" PRIx64 ">",
3894                           scn, address, name, off)
3895                 : printf ("%s+%#0*" PRIx64 " <%s+%#" PRIx64 ">",
3896                           scn, 2 + address_size * 2, address,
3897                           name, off))
3898              : (address_size == 0
3899                 ? printf ("%#" PRIx64 " <%s+%#" PRIx64 ">",
3900                           address, name, off)
3901                 : printf ("%#0*" PRIx64 " <%s+%#" PRIx64 ">",
3902                           2 + address_size * 2, address,
3903                           name, off)))
3904           : (scn != NULL
3905              ? (address_size == 0
3906                 ? printf ("%s+%#" PRIx64 " <%s>", scn, address, name)
3907                 : printf ("%s+%#0*" PRIx64 " <%s>",
3908                            scn, 2 + address_size * 2, address, name))
3909              : (address_size == 0
3910                 ? printf ("%#" PRIx64 " <%s>", address, name)
3911                 : printf ("%#0*" PRIx64 " <%s>",
3912                           2 + address_size * 2, address, name))))
3913        : (scn != NULL
3914           ? (address_size == 0
3915              ? printf ("%s+%#" PRIx64, scn, address)
3916              : printf ("%s+%#0*" PRIx64, scn, 2 + address_size * 2, address))
3917           : (address_size == 0
3918              ? printf ("%#" PRIx64, address)
3919              : printf ("%#0*" PRIx64, 2 + address_size * 2, address)))) < 0)
3920     error_exit (0, _("sprintf failure"));
3921 }
3922
3923
3924 static const char *
3925 dwarf_tag_string (unsigned int tag)
3926 {
3927   switch (tag)
3928     {
3929 #define DWARF_ONE_KNOWN_DW_TAG(NAME, CODE) case CODE: return #NAME;
3930       DWARF_ALL_KNOWN_DW_TAG
3931 #undef DWARF_ONE_KNOWN_DW_TAG
3932     default:
3933       return NULL;
3934     }
3935 }
3936
3937
3938 static const char *
3939 dwarf_attr_string (unsigned int attrnum)
3940 {
3941   switch (attrnum)
3942     {
3943 #define DWARF_ONE_KNOWN_DW_AT(NAME, CODE) case CODE: return #NAME;
3944       DWARF_ALL_KNOWN_DW_AT
3945 #undef DWARF_ONE_KNOWN_DW_AT
3946     default:
3947       return NULL;
3948     }
3949 }
3950
3951
3952 static const char *
3953 dwarf_form_string (unsigned int form)
3954 {
3955   switch (form)
3956     {
3957 #define DWARF_ONE_KNOWN_DW_FORM(NAME, CODE) case CODE: return #NAME;
3958       DWARF_ALL_KNOWN_DW_FORM
3959 #undef DWARF_ONE_KNOWN_DW_FORM
3960     default:
3961       return NULL;
3962     }
3963 }
3964
3965
3966 static const char *
3967 dwarf_lang_string (unsigned int lang)
3968 {
3969   switch (lang)
3970     {
3971 #define DWARF_ONE_KNOWN_DW_LANG(NAME, CODE) case CODE: return #NAME;
3972       DWARF_ALL_KNOWN_DW_LANG
3973 #undef DWARF_ONE_KNOWN_DW_LANG
3974     default:
3975       return NULL;
3976     }
3977 }
3978
3979
3980 static const char *
3981 dwarf_inline_string (unsigned int code)
3982 {
3983   static const char *const known[] =
3984     {
3985 #define DWARF_ONE_KNOWN_DW_INL(NAME, CODE) [CODE] = #NAME,
3986       DWARF_ALL_KNOWN_DW_INL
3987 #undef DWARF_ONE_KNOWN_DW_INL
3988     };
3989
3990   if (likely (code < sizeof (known) / sizeof (known[0])))
3991     return known[code];
3992
3993   return NULL;
3994 }
3995
3996
3997 static const char *
3998 dwarf_encoding_string (unsigned int code)
3999 {
4000   static const char *const known[] =
4001     {
4002 #define DWARF_ONE_KNOWN_DW_ATE(NAME, CODE) [CODE] = #NAME,
4003       DWARF_ALL_KNOWN_DW_ATE
4004 #undef DWARF_ONE_KNOWN_DW_ATE
4005     };
4006
4007   if (likely (code < sizeof (known) / sizeof (known[0])))
4008     return known[code];
4009
4010   return NULL;
4011 }
4012
4013
4014 static const char *
4015 dwarf_access_string (unsigned int code)
4016 {
4017   static const char *const known[] =
4018     {
4019 #define DWARF_ONE_KNOWN_DW_ACCESS(NAME, CODE) [CODE] = #NAME,
4020       DWARF_ALL_KNOWN_DW_ACCESS
4021 #undef DWARF_ONE_KNOWN_DW_ACCESS
4022     };
4023
4024   if (likely (code < sizeof (known) / sizeof (known[0])))
4025     return known[code];
4026
4027   return NULL;
4028 }
4029
4030
4031 static const char *
4032 dwarf_defaulted_string (unsigned int code)
4033 {
4034   static const char *const known[] =
4035     {
4036 #define DWARF_ONE_KNOWN_DW_DEFAULTED(NAME, CODE) [CODE] = #NAME,
4037       DWARF_ALL_KNOWN_DW_DEFAULTED
4038 #undef DWARF_ONE_KNOWN_DW_DEFAULTED
4039     };
4040
4041   if (likely (code < sizeof (known) / sizeof (known[0])))
4042     return known[code];
4043
4044   return NULL;
4045 }
4046
4047
4048 static const char *
4049 dwarf_visibility_string (unsigned int code)
4050 {
4051   static const char *const known[] =
4052     {
4053 #define DWARF_ONE_KNOWN_DW_VIS(NAME, CODE) [CODE] = #NAME,
4054       DWARF_ALL_KNOWN_DW_VIS
4055 #undef DWARF_ONE_KNOWN_DW_VIS
4056     };
4057
4058   if (likely (code < sizeof (known) / sizeof (known[0])))
4059     return known[code];
4060
4061   return NULL;
4062 }
4063
4064
4065 static const char *
4066 dwarf_virtuality_string (unsigned int code)
4067 {
4068   static const char *const known[] =
4069     {
4070 #define DWARF_ONE_KNOWN_DW_VIRTUALITY(NAME, CODE) [CODE] = #NAME,
4071       DWARF_ALL_KNOWN_DW_VIRTUALITY
4072 #undef DWARF_ONE_KNOWN_DW_VIRTUALITY
4073     };
4074
4075   if (likely (code < sizeof (known) / sizeof (known[0])))
4076     return known[code];
4077
4078   return NULL;
4079 }
4080
4081
4082 static const char *
4083 dwarf_identifier_case_string (unsigned int code)
4084 {
4085   static const char *const known[] =
4086     {
4087 #define DWARF_ONE_KNOWN_DW_ID(NAME, CODE) [CODE] = #NAME,
4088       DWARF_ALL_KNOWN_DW_ID
4089 #undef DWARF_ONE_KNOWN_DW_ID
4090     };
4091
4092   if (likely (code < sizeof (known) / sizeof (known[0])))
4093     return known[code];
4094
4095   return NULL;
4096 }
4097
4098
4099 static const char *
4100 dwarf_calling_convention_string (unsigned int code)
4101 {
4102   static const char *const known[] =
4103     {
4104 #define DWARF_ONE_KNOWN_DW_CC(NAME, CODE) [CODE] = #NAME,
4105       DWARF_ALL_KNOWN_DW_CC
4106 #undef DWARF_ONE_KNOWN_DW_CC
4107     };
4108
4109   if (likely (code < sizeof (known) / sizeof (known[0])))
4110     return known[code];
4111
4112   return NULL;
4113 }
4114
4115
4116 static const char *
4117 dwarf_ordering_string (unsigned int code)
4118 {
4119   static const char *const known[] =
4120     {
4121 #define DWARF_ONE_KNOWN_DW_ORD(NAME, CODE) [CODE] = #NAME,
4122       DWARF_ALL_KNOWN_DW_ORD
4123 #undef DWARF_ONE_KNOWN_DW_ORD
4124     };
4125
4126   if (likely (code < sizeof (known) / sizeof (known[0])))
4127     return known[code];
4128
4129   return NULL;
4130 }
4131
4132
4133 static const char *
4134 dwarf_discr_list_string (unsigned int code)
4135 {
4136   static const char *const known[] =
4137     {
4138 #define DWARF_ONE_KNOWN_DW_DSC(NAME, CODE) [CODE] = #NAME,
4139       DWARF_ALL_KNOWN_DW_DSC
4140 #undef DWARF_ONE_KNOWN_DW_DSC
4141     };
4142
4143   if (likely (code < sizeof (known) / sizeof (known[0])))
4144     return known[code];
4145
4146   return NULL;
4147 }
4148
4149
4150 static const char *
4151 dwarf_locexpr_opcode_string (unsigned int code)
4152 {
4153   static const char *const known[] =
4154     {
4155       /* Normally we can't afford building huge table of 64K entries,
4156          most of them zero, just because there are a couple defined
4157          values at the far end.  In case of opcodes, it's OK.  */
4158 #define DWARF_ONE_KNOWN_DW_OP(NAME, CODE) [CODE] = #NAME,
4159       DWARF_ALL_KNOWN_DW_OP
4160 #undef DWARF_ONE_KNOWN_DW_OP
4161     };
4162
4163   if (likely (code < sizeof (known) / sizeof (known[0])))
4164     return known[code];
4165
4166   return NULL;
4167 }
4168
4169
4170 static const char *
4171 dwarf_unit_string (unsigned int type)
4172 {
4173   switch (type)
4174     {
4175 #define DWARF_ONE_KNOWN_DW_UT(NAME, CODE) case CODE: return #NAME;
4176       DWARF_ALL_KNOWN_DW_UT
4177 #undef DWARF_ONE_KNOWN_DW_UT
4178     default:
4179       return NULL;
4180     }
4181 }
4182
4183
4184 static const char *
4185 dwarf_range_list_encoding_string (unsigned int kind)
4186 {
4187   switch (kind)
4188     {
4189 #define DWARF_ONE_KNOWN_DW_RLE(NAME, CODE) case CODE: return #NAME;
4190       DWARF_ALL_KNOWN_DW_RLE
4191 #undef DWARF_ONE_KNOWN_DW_RLE
4192     default:
4193       return NULL;
4194     }
4195 }
4196
4197
4198 static const char *
4199 dwarf_loc_list_encoding_string (unsigned int kind)
4200 {
4201   switch (kind)
4202     {
4203 #define DWARF_ONE_KNOWN_DW_LLE(NAME, CODE) case CODE: return #NAME;
4204       DWARF_ALL_KNOWN_DW_LLE
4205 #undef DWARF_ONE_KNOWN_DW_LLE
4206     /* DW_LLE_GNU_view_pair is special/incompatible with default codes.  */
4207     case DW_LLE_GNU_view_pair: return "GNU_view_pair";
4208     default:
4209       return NULL;
4210     }
4211 }
4212
4213
4214 static const char *
4215 dwarf_line_content_description_string (unsigned int kind)
4216 {
4217   switch (kind)
4218     {
4219 #define DWARF_ONE_KNOWN_DW_LNCT(NAME, CODE) case CODE: return #NAME;
4220       DWARF_ALL_KNOWN_DW_LNCT
4221 #undef DWARF_ONE_KNOWN_DW_LNCT
4222     default:
4223       return NULL;
4224     }
4225 }
4226
4227
4228 /* Used by all dwarf_foo_name functions.  */
4229 static const char *
4230 string_or_unknown (const char *known, unsigned int code,
4231                    unsigned int lo_user, unsigned int hi_user,
4232                    bool print_unknown_num)
4233 {
4234   static char unknown_buf[20];
4235
4236   if (likely (known != NULL))
4237     return known;
4238
4239   if (lo_user != 0 && code >= lo_user && code <= hi_user)
4240     {
4241       snprintf (unknown_buf, sizeof unknown_buf, "lo_user+%#x",
4242                 code - lo_user);
4243       return unknown_buf;
4244     }
4245
4246   if (print_unknown_num)
4247     {
4248       snprintf (unknown_buf, sizeof unknown_buf, "??? (%#x)", code);
4249       return unknown_buf;
4250     }
4251
4252   return "???";
4253 }
4254
4255
4256 static const char *
4257 dwarf_tag_name (unsigned int tag)
4258 {
4259   const char *ret = dwarf_tag_string (tag);
4260   return string_or_unknown (ret, tag, DW_TAG_lo_user, DW_TAG_hi_user, true);
4261 }
4262
4263 static const char *
4264 dwarf_attr_name (unsigned int attr)
4265 {
4266   const char *ret = dwarf_attr_string (attr);
4267   return string_or_unknown (ret, attr, DW_AT_lo_user, DW_AT_hi_user, true);
4268 }
4269
4270
4271 static const char *
4272 dwarf_form_name (unsigned int form)
4273 {
4274   const char *ret = dwarf_form_string (form);
4275   return string_or_unknown (ret, form, 0, 0, true);
4276 }
4277
4278
4279 static const char *
4280 dwarf_lang_name (unsigned int lang)
4281 {
4282   const char *ret = dwarf_lang_string (lang);
4283   return string_or_unknown (ret, lang, DW_LANG_lo_user, DW_LANG_hi_user, false);
4284 }
4285
4286
4287 static const char *
4288 dwarf_inline_name (unsigned int code)
4289 {
4290   const char *ret = dwarf_inline_string (code);
4291   return string_or_unknown (ret, code, 0, 0, false);
4292 }
4293
4294
4295 static const char *
4296 dwarf_encoding_name (unsigned int code)
4297 {
4298   const char *ret = dwarf_encoding_string (code);
4299   return string_or_unknown (ret, code, DW_ATE_lo_user, DW_ATE_hi_user, false);
4300 }
4301
4302
4303 static const char *
4304 dwarf_access_name (unsigned int code)
4305 {
4306   const char *ret = dwarf_access_string (code);
4307   return string_or_unknown (ret, code, 0, 0, false);
4308 }
4309
4310
4311 static const char *
4312 dwarf_defaulted_name (unsigned int code)
4313 {
4314   const char *ret = dwarf_defaulted_string (code);
4315   return string_or_unknown (ret, code, 0, 0, false);
4316 }
4317
4318
4319 static const char *
4320 dwarf_visibility_name (unsigned int code)
4321 {
4322   const char *ret = dwarf_visibility_string (code);
4323   return string_or_unknown (ret, code, 0, 0, false);
4324 }
4325
4326
4327 static const char *
4328 dwarf_virtuality_name (unsigned int code)
4329 {
4330   const char *ret = dwarf_virtuality_string (code);
4331   return string_or_unknown (ret, code, 0, 0, false);
4332 }
4333
4334
4335 static const char *
4336 dwarf_identifier_case_name (unsigned int code)
4337 {
4338   const char *ret = dwarf_identifier_case_string (code);
4339   return string_or_unknown (ret, code, 0, 0, false);
4340 }
4341
4342
4343 static const char *
4344 dwarf_calling_convention_name (unsigned int code)
4345 {
4346   const char *ret = dwarf_calling_convention_string (code);
4347   return string_or_unknown (ret, code, DW_CC_lo_user, DW_CC_hi_user, false);
4348 }
4349
4350
4351 static const char *
4352 dwarf_ordering_name (unsigned int code)
4353 {
4354   const char *ret = dwarf_ordering_string (code);
4355   return string_or_unknown (ret, code, 0, 0, false);
4356 }
4357
4358
4359 static const char *
4360 dwarf_discr_list_name (unsigned int code)
4361 {
4362   const char *ret = dwarf_discr_list_string (code);
4363   return string_or_unknown (ret, code, 0, 0, false);
4364 }
4365
4366
4367 static const char *
4368 dwarf_unit_name (unsigned int type)
4369 {
4370   const char *ret = dwarf_unit_string (type);
4371   return string_or_unknown (ret, type, DW_UT_lo_user, DW_UT_hi_user, true);
4372 }
4373
4374
4375 static const char *
4376 dwarf_range_list_encoding_name (unsigned int kind)
4377 {
4378   const char *ret = dwarf_range_list_encoding_string (kind);
4379   return string_or_unknown (ret, kind, 0, 0, false);
4380 }
4381
4382
4383 static const char *
4384 dwarf_loc_list_encoding_name (unsigned int kind)
4385 {
4386   const char *ret = dwarf_loc_list_encoding_string (kind);
4387   return string_or_unknown (ret, kind, 0, 0, false);
4388 }
4389
4390
4391 static const char *
4392 dwarf_line_content_description_name (unsigned int kind)
4393 {
4394   const char *ret = dwarf_line_content_description_string (kind);
4395   return string_or_unknown (ret, kind, DW_LNCT_lo_user, DW_LNCT_hi_user,
4396                             false);
4397 }
4398
4399
4400 static void
4401 print_block (size_t n, const void *block)
4402 {
4403   if (n == 0)
4404     puts (_("empty block"));
4405   else
4406     {
4407       printf (_("%zu byte block:"), n);
4408       const unsigned char *data = block;
4409       do
4410         printf (" %02x", *data++);
4411       while (--n > 0);
4412       putchar ('\n');
4413     }
4414 }
4415
4416 static void
4417 print_bytes (size_t n, const unsigned char *bytes)
4418 {
4419   while (n-- > 0)
4420     {
4421       printf ("%02x", *bytes++);
4422       if (n > 0)
4423         printf (" ");
4424     }
4425 }
4426
4427 static int
4428 get_indexed_addr (Dwarf_CU *cu, Dwarf_Word idx, Dwarf_Addr *addr)
4429 {
4430   if (cu == NULL)
4431     return -1;
4432
4433   Elf_Data *debug_addr = cu->dbg->sectiondata[IDX_debug_addr];
4434   if (debug_addr == NULL)
4435     return -1;
4436
4437   Dwarf_Off base = __libdw_cu_addr_base (cu);
4438   Dwarf_Word off = idx * cu->address_size;
4439   if (base > debug_addr->d_size
4440       || off > debug_addr->d_size - base
4441       || cu->address_size > debug_addr->d_size - base - off)
4442     return -1;
4443
4444   const unsigned char *addrp = debug_addr->d_buf + base + off;
4445   if (cu->address_size == 4)
4446     *addr = read_4ubyte_unaligned (cu->dbg, addrp);
4447   else
4448     *addr = read_8ubyte_unaligned (cu->dbg, addrp);
4449
4450   return 0;
4451 }
4452
4453 static void
4454 print_ops (Dwfl_Module *dwflmod, Dwarf *dbg, int indent, int indentrest,
4455            unsigned int vers, unsigned int addrsize, unsigned int offset_size,
4456            struct Dwarf_CU *cu, Dwarf_Word len, const unsigned char *data)
4457 {
4458   const unsigned int ref_size = vers < 3 ? addrsize : offset_size;
4459
4460   if (len == 0)
4461     {
4462       printf ("%*s(empty)\n", indent, "");
4463       return;
4464     }
4465
4466 #define NEED(n)         if (len < (Dwarf_Word) (n)) goto invalid
4467 #define CONSUME(n)      NEED (n); else len -= (n)
4468
4469   Dwarf_Word offset = 0;
4470   while (len-- > 0)
4471     {
4472       uint_fast8_t op = *data++;
4473
4474       const char *op_name = dwarf_locexpr_opcode_string (op);
4475       if (unlikely (op_name == NULL))
4476         {
4477           static char buf[20];
4478           if (op >= DW_OP_lo_user)
4479             snprintf (buf, sizeof buf, "lo_user+%#x", op - DW_OP_lo_user);
4480           else
4481             snprintf (buf, sizeof buf, "??? (%#x)", op);
4482           op_name = buf;
4483         }
4484
4485       switch (op)
4486         {
4487         case DW_OP_addr:;
4488           /* Address operand.  */
4489           Dwarf_Word addr;
4490           NEED (addrsize);
4491           if (addrsize == 4)
4492             addr = read_4ubyte_unaligned (dbg, data);
4493           else if (addrsize == 8)
4494             addr = read_8ubyte_unaligned (dbg, data);
4495           else
4496             goto invalid;
4497           data += addrsize;
4498           CONSUME (addrsize);
4499
4500           printf ("%*s[%2" PRIuMAX "] %s ",
4501                   indent, "", (uintmax_t) offset, op_name);
4502           print_dwarf_addr (dwflmod, 0, addr, addr);
4503           printf ("\n");
4504
4505           offset += 1 + addrsize;
4506           break;
4507
4508         case DW_OP_call_ref:
4509         case DW_OP_GNU_variable_value:
4510           /* Offset operand.  */
4511           if (ref_size != 4 && ref_size != 8)
4512             goto invalid; /* Cannot be used in CFA.  */
4513           NEED (ref_size);
4514           if (ref_size == 4)
4515             addr = read_4ubyte_unaligned (dbg, data);
4516           else
4517             addr = read_8ubyte_unaligned (dbg, data);
4518           data += ref_size;
4519           CONSUME (ref_size);
4520           /* addr is a DIE offset, so format it as one.  */
4521           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIxMAX "]\n",
4522                   indent, "", (uintmax_t) offset,
4523                   op_name, (uintmax_t) addr);
4524           offset += 1 + ref_size;
4525           break;
4526
4527         case DW_OP_deref_size:
4528         case DW_OP_xderef_size:
4529         case DW_OP_pick:
4530         case DW_OP_const1u:
4531           // XXX value might be modified by relocation
4532           NEED (1);
4533           printf ("%*s[%2" PRIuMAX "] %s %" PRIu8 "\n",
4534                   indent, "", (uintmax_t) offset,
4535                   op_name, *((uint8_t *) data));
4536           ++data;
4537           --len;
4538           offset += 2;
4539           break;
4540
4541         case DW_OP_const2u:
4542           NEED (2);
4543           // XXX value might be modified by relocation
4544           printf ("%*s[%2" PRIuMAX "] %s %" PRIu16 "\n",
4545                   indent, "", (uintmax_t) offset,
4546                   op_name, read_2ubyte_unaligned (dbg, data));
4547           CONSUME (2);
4548           data += 2;
4549           offset += 3;
4550           break;
4551
4552         case DW_OP_const4u:
4553           NEED (4);
4554           // XXX value might be modified by relocation
4555           printf ("%*s[%2" PRIuMAX "] %s %" PRIu32 "\n",
4556                   indent, "", (uintmax_t) offset,
4557                   op_name, read_4ubyte_unaligned (dbg, data));
4558           CONSUME (4);
4559           data += 4;
4560           offset += 5;
4561           break;
4562
4563         case DW_OP_const8u:
4564           NEED (8);
4565           // XXX value might be modified by relocation
4566           printf ("%*s[%2" PRIuMAX "] %s %" PRIu64 "\n",
4567                   indent, "", (uintmax_t) offset,
4568                   op_name, (uint64_t) read_8ubyte_unaligned (dbg, data));
4569           CONSUME (8);
4570           data += 8;
4571           offset += 9;
4572           break;
4573
4574         case DW_OP_const1s:
4575           NEED (1);
4576           // XXX value might be modified by relocation
4577           printf ("%*s[%2" PRIuMAX "] %s %" PRId8 "\n",
4578                   indent, "", (uintmax_t) offset,
4579                   op_name, *((int8_t *) data));
4580           ++data;
4581           --len;
4582           offset += 2;
4583           break;
4584
4585         case DW_OP_const2s:
4586           NEED (2);
4587           // XXX value might be modified by relocation
4588           printf ("%*s[%2" PRIuMAX "] %s %" PRId16 "\n",
4589                   indent, "", (uintmax_t) offset,
4590                   op_name, read_2sbyte_unaligned (dbg, data));
4591           CONSUME (2);
4592           data += 2;
4593           offset += 3;
4594           break;
4595
4596         case DW_OP_const4s:
4597           NEED (4);
4598           // XXX value might be modified by relocation
4599           printf ("%*s[%2" PRIuMAX "] %s %" PRId32 "\n",
4600                   indent, "", (uintmax_t) offset,
4601                   op_name, read_4sbyte_unaligned (dbg, data));
4602           CONSUME (4);
4603           data += 4;
4604           offset += 5;
4605           break;
4606
4607         case DW_OP_const8s:
4608           NEED (8);
4609           // XXX value might be modified by relocation
4610           printf ("%*s[%2" PRIuMAX "] %s %" PRId64 "\n",
4611                   indent, "", (uintmax_t) offset,
4612                   op_name, read_8sbyte_unaligned (dbg, data));
4613           CONSUME (8);
4614           data += 8;
4615           offset += 9;
4616           break;
4617
4618         case DW_OP_piece:
4619         case DW_OP_regx:
4620         case DW_OP_plus_uconst:
4621         case DW_OP_constu:;
4622           const unsigned char *start = data;
4623           uint64_t uleb;
4624           NEED (1);
4625           get_uleb128 (uleb, data, data + len);
4626           printf ("%*s[%2" PRIuMAX "] %s %" PRIu64 "\n",
4627                   indent, "", (uintmax_t) offset, op_name, uleb);
4628           CONSUME (data - start);
4629           offset += 1 + (data - start);
4630           break;
4631
4632         case DW_OP_addrx:
4633         case DW_OP_GNU_addr_index:
4634         case DW_OP_constx:
4635         case DW_OP_GNU_const_index:;
4636           start = data;
4637           NEED (1);
4638           get_uleb128 (uleb, data, data + len);
4639           printf ("%*s[%2" PRIuMAX "] %s [%" PRIu64 "] ",
4640                   indent, "", (uintmax_t) offset, op_name, uleb);
4641           CONSUME (data - start);
4642           offset += 1 + (data - start);
4643           if (get_indexed_addr (cu, uleb, &addr) != 0)
4644             printf ("???\n");
4645           else
4646             {
4647               print_dwarf_addr (dwflmod, 0, addr, addr);
4648               printf ("\n");
4649             }
4650           break;
4651
4652         case DW_OP_bit_piece:
4653           start = data;
4654           uint64_t uleb2;
4655           NEED (1);
4656           get_uleb128 (uleb, data, data + len);
4657           NEED (1);
4658           get_uleb128 (uleb2, data, data + len);
4659           printf ("%*s[%2" PRIuMAX "] %s %" PRIu64 ", %" PRIu64 "\n",
4660                   indent, "", (uintmax_t) offset, op_name, uleb, uleb2);
4661           CONSUME (data - start);
4662           offset += 1 + (data - start);
4663           break;
4664
4665         case DW_OP_fbreg:
4666         case DW_OP_breg0 ... DW_OP_breg31:
4667         case DW_OP_consts:
4668           start = data;
4669           int64_t sleb;
4670           NEED (1);
4671           get_sleb128 (sleb, data, data + len);
4672           printf ("%*s[%2" PRIuMAX "] %s %" PRId64 "\n",
4673                   indent, "", (uintmax_t) offset, op_name, sleb);
4674           CONSUME (data - start);
4675           offset += 1 + (data - start);
4676           break;
4677
4678         case DW_OP_bregx:
4679           start = data;
4680           NEED (1);
4681           get_uleb128 (uleb, data, data + len);
4682           NEED (1);
4683           get_sleb128 (sleb, data, data + len);
4684           printf ("%*s[%2" PRIuMAX "] %s %" PRIu64 " %" PRId64 "\n",
4685                   indent, "", (uintmax_t) offset, op_name, uleb, sleb);
4686           CONSUME (data - start);
4687           offset += 1 + (data - start);
4688           break;
4689
4690         case DW_OP_call2:
4691           NEED (2);
4692           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIx16 "]\n",
4693                   indent, "", (uintmax_t) offset, op_name,
4694                   read_2ubyte_unaligned (dbg, data));
4695           CONSUME (2);
4696           data += 2;
4697           offset += 3;
4698           break;
4699
4700         case DW_OP_call4:
4701           NEED (4);
4702           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIx32 "]\n",
4703                   indent, "", (uintmax_t) offset, op_name,
4704                   read_4ubyte_unaligned (dbg, data));
4705           CONSUME (4);
4706           data += 4;
4707           offset += 5;
4708           break;
4709
4710         case DW_OP_skip:
4711         case DW_OP_bra:
4712           NEED (2);
4713           printf ("%*s[%2" PRIuMAX "] %s %" PRIuMAX "\n",
4714                   indent, "", (uintmax_t) offset, op_name,
4715                   (uintmax_t) (offset + read_2sbyte_unaligned (dbg, data) + 3));
4716           CONSUME (2);
4717           data += 2;
4718           offset += 3;
4719           break;
4720
4721         case DW_OP_implicit_value:
4722           start = data;
4723           NEED (1);
4724           get_uleb128 (uleb, data, data + len);
4725           printf ("%*s[%2" PRIuMAX "] %s: ",
4726                   indent, "", (uintmax_t) offset, op_name);
4727           NEED (uleb);
4728           print_block (uleb, data);
4729           data += uleb;
4730           CONSUME (data - start);
4731           offset += 1 + (data - start);
4732           break;
4733
4734         case DW_OP_implicit_pointer:
4735         case DW_OP_GNU_implicit_pointer:
4736           /* DIE offset operand.  */
4737           start = data;
4738           NEED (ref_size);
4739           if (ref_size != 4 && ref_size != 8)
4740             goto invalid; /* Cannot be used in CFA.  */
4741           if (ref_size == 4)
4742             addr = read_4ubyte_unaligned (dbg, data);
4743           else
4744             addr = read_8ubyte_unaligned (dbg, data);
4745           data += ref_size;
4746           /* Byte offset operand.  */
4747           NEED (1);
4748           get_sleb128 (sleb, data, data + len);
4749
4750           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIxMAX "] %+" PRId64 "\n",
4751                   indent, "", (intmax_t) offset,
4752                   op_name, (uintmax_t) addr, sleb);
4753           CONSUME (data - start);
4754           offset += 1 + (data - start);
4755           break;
4756
4757         case DW_OP_entry_value:
4758         case DW_OP_GNU_entry_value:
4759           /* Size plus expression block.  */
4760           start = data;
4761           NEED (1);
4762           get_uleb128 (uleb, data, data + len);
4763           printf ("%*s[%2" PRIuMAX "] %s:\n",
4764                   indent, "", (uintmax_t) offset, op_name);
4765           NEED (uleb);
4766           print_ops (dwflmod, dbg, indent + 5, indent + 5, vers,
4767                      addrsize, offset_size, cu, uleb, data);
4768           data += uleb;
4769           CONSUME (data - start);
4770           offset += 1 + (data - start);
4771           break;
4772
4773         case DW_OP_const_type:
4774         case DW_OP_GNU_const_type:
4775           /* uleb128 CU relative DW_TAG_base_type DIE offset, 1-byte
4776              unsigned size plus block.  */
4777           start = data;
4778           NEED (1);
4779           get_uleb128 (uleb, data, data + len);
4780           if (! print_unresolved_addresses && cu != NULL)
4781             uleb += cu->start;
4782           NEED (1);
4783           uint8_t usize = *(uint8_t *) data++;
4784           NEED (usize);
4785           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIxMAX "] ",
4786                   indent, "", (uintmax_t) offset, op_name, uleb);
4787           print_block (usize, data);
4788           data += usize;
4789           CONSUME (data - start);
4790           offset += 1 + (data - start);
4791           break;
4792
4793         case DW_OP_regval_type:
4794         case DW_OP_GNU_regval_type:
4795           /* uleb128 register number, uleb128 CU relative
4796              DW_TAG_base_type DIE offset.  */
4797           start = data;
4798           NEED (1);
4799           get_uleb128 (uleb, data, data + len);
4800           NEED (1);
4801           get_uleb128 (uleb2, data, data + len);
4802           if (! print_unresolved_addresses && cu != NULL)
4803             uleb2 += cu->start;
4804           printf ("%*s[%2" PRIuMAX "] %s %" PRIu64 " [%6" PRIx64 "]\n",
4805                   indent, "", (uintmax_t) offset, op_name, uleb, uleb2);
4806           CONSUME (data - start);
4807           offset += 1 + (data - start);
4808           break;
4809
4810         case DW_OP_deref_type:
4811         case DW_OP_GNU_deref_type:
4812           /* 1-byte unsigned size of value, uleb128 CU relative
4813              DW_TAG_base_type DIE offset.  */
4814           start = data;
4815           NEED (1);
4816           usize = *(uint8_t *) data++;
4817           NEED (1);
4818           get_uleb128 (uleb, data, data + len);
4819           if (! print_unresolved_addresses && cu != NULL)
4820             uleb += cu->start;
4821           printf ("%*s[%2" PRIuMAX "] %s %" PRIu8 " [%6" PRIxMAX "]\n",
4822                   indent, "", (uintmax_t) offset,
4823                   op_name, usize, uleb);
4824           CONSUME (data - start);
4825           offset += 1 + (data - start);
4826           break;
4827
4828         case DW_OP_xderef_type:
4829           /* 1-byte unsigned size of value, uleb128 base_type DIE offset.  */
4830           start = data;
4831           NEED (1);
4832           usize = *(uint8_t *) data++;
4833           NEED (1);
4834           get_uleb128 (uleb, data, data + len);
4835           printf ("%*s[%4" PRIuMAX "] %s %" PRIu8 " [%6" PRIxMAX "]\n",
4836                   indent, "", (uintmax_t) offset,
4837                   op_name, usize, uleb);
4838           CONSUME (data - start);
4839           offset += 1 + (data - start);
4840           break;
4841
4842         case DW_OP_convert:
4843         case DW_OP_GNU_convert:
4844         case DW_OP_reinterpret:
4845         case DW_OP_GNU_reinterpret:
4846           /* uleb128 CU relative offset to DW_TAG_base_type, or zero
4847              for conversion to untyped.  */
4848           start = data;
4849           NEED (1);
4850           get_uleb128 (uleb, data, data + len);
4851           if (uleb != 0 && ! print_unresolved_addresses && cu != NULL)
4852             uleb += cu->start;
4853           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIxMAX "]\n",
4854                   indent, "", (uintmax_t) offset, op_name, uleb);
4855           CONSUME (data - start);
4856           offset += 1 + (data - start);
4857           break;
4858
4859         case DW_OP_GNU_parameter_ref:
4860           /* 4 byte CU relative reference to the abstract optimized away
4861              DW_TAG_formal_parameter.  */
4862           NEED (4);
4863           uintmax_t param_off = (uintmax_t) read_4ubyte_unaligned (dbg, data);
4864           if (! print_unresolved_addresses && cu != NULL)
4865             param_off += cu->start;
4866           printf ("%*s[%2" PRIuMAX "] %s [%6" PRIxMAX "]\n",
4867                   indent, "", (uintmax_t) offset, op_name, param_off);
4868           CONSUME (4);
4869           data += 4;
4870           offset += 5;
4871           break;
4872
4873         default:
4874           /* No Operand.  */
4875           printf ("%*s[%2" PRIuMAX "] %s\n",
4876                   indent, "", (uintmax_t) offset, op_name);
4877           ++offset;
4878           break;
4879         }
4880
4881       indent = indentrest;
4882       continue;
4883
4884     invalid:
4885       printf (_("%*s[%2" PRIuMAX "] %s  <TRUNCATED>\n"),
4886               indent, "", (uintmax_t) offset, op_name);
4887       break;
4888     }
4889 }
4890
4891
4892 /* Turn the addresses into file offsets by using the phdrs.  */
4893 static void
4894 find_offsets(Elf *elf, GElf_Addr main_bias, size_t n,
4895                   GElf_Addr addrs[n], GElf_Off offs[n])
4896 {
4897   size_t unsolved = n;
4898   for (size_t i = 0; i < phnum; ++i) {
4899     GElf_Phdr phdr_mem;
4900     GElf_Phdr *phdr = gelf_getphdr(elf, i, &phdr_mem);
4901     if (phdr != NULL && phdr->p_type == PT_LOAD && phdr->p_memsz > 0)
4902       for (size_t j = 0; j < n; ++j)
4903         if (offs[j] == 0 && addrs[j] >= phdr->p_vaddr + main_bias &&
4904             addrs[j] - (phdr->p_vaddr + main_bias) < phdr->p_filesz) {
4905           offs[j] = addrs[j] - (phdr->p_vaddr + main_bias) + phdr->p_offset;
4906           if (--unsolved == 0)
4907             break;
4908         }
4909   }
4910 }
4911
4912 /* The dynamic segment (type PT_DYNAMIC), contains the .dynamic section.
4913    And .dynamic section contains an array of the dynamic structures.
4914    We use the array to get:
4915     DT_STRTAB: the address of the string table
4916     DT_SYMTAB: the address of the symbol table
4917     DT_STRSZ: the size, in bytes, of the string table
4918     ...  */
4919 static void
4920 get_dynscn_addrs(Elf *elf, GElf_Phdr *phdr, GElf_Addr addrs[i_max])
4921 {
4922   Elf_Data *data = elf_getdata_rawchunk(
4923     elf, phdr->p_offset, phdr->p_filesz, ELF_T_DYN);
4924
4925   int dyn_idx = 0;
4926   for (;; ++dyn_idx) {
4927     GElf_Dyn dyn_mem;
4928     GElf_Dyn *dyn = gelf_getdyn(data, dyn_idx, &dyn_mem);
4929     /* DT_NULL Marks end of dynamic section.  */
4930     if (dyn == NULL || dyn->d_tag == DT_NULL)
4931       break;
4932
4933     switch (dyn->d_tag) {
4934     case DT_SYMTAB:
4935       addrs[i_symtab] = dyn->d_un.d_ptr;
4936       break;
4937
4938     case DT_HASH:
4939       addrs[i_hash] = dyn->d_un.d_ptr;
4940       break;
4941
4942     case DT_GNU_HASH:
4943       addrs[i_gnu_hash] = dyn->d_un.d_ptr;
4944       break;
4945
4946     case DT_STRTAB:
4947       addrs[i_strtab] = dyn->d_un.d_ptr;
4948       break;
4949
4950     case DT_VERSYM:
4951       addrs[i_versym] = dyn->d_un.d_ptr;
4952       break;
4953
4954     case DT_VERDEF:
4955       addrs[i_verdef] = dyn->d_un.d_ptr;
4956       break;
4957
4958     case DT_VERNEED:
4959       addrs[i_verneed] = dyn->d_un.d_ptr;
4960       break;
4961
4962     case DT_STRSZ:
4963       addrs[i_strsz] = dyn->d_un.d_val;
4964       break;
4965     }
4966   }
4967 }
4968
4969
4970 /* Use dynamic segment to get data for the string table section.  */
4971 static Elf_Data *
4972 get_dynscn_strtab(Elf *elf, GElf_Phdr *phdr)
4973 {
4974   Elf_Data *strtab_data;
4975   GElf_Addr addrs[i_max] = {0,};
4976   GElf_Off offs[i_max] = {0,};
4977   get_dynscn_addrs(elf, phdr, addrs);
4978   find_offsets(elf, 0, i_max, addrs, offs);
4979   strtab_data = elf_getdata_rawchunk(
4980           elf, offs[i_strtab], addrs[i_strsz], ELF_T_BYTE);
4981   return strtab_data;
4982 }
4983
4984
4985 struct listptr
4986 {
4987   Dwarf_Off offset:(64 - 3);
4988   bool addr64:1;
4989   bool dwarf64:1;
4990   bool warned:1;
4991   struct Dwarf_CU *cu;
4992   unsigned int attr;
4993 };
4994
4995 #define listptr_offset_size(p)  ((p)->dwarf64 ? 8 : 4)
4996 #define listptr_address_size(p) ((p)->addr64 ? 8 : 4)
4997
4998 static Dwarf_Addr
4999 cudie_base (Dwarf_Die *cudie)
5000 {
5001   Dwarf_Addr base;
5002   /* Find the base address of the compilation unit.  It will normally
5003      be specified by DW_AT_low_pc.  In DWARF-3 draft 4, the base
5004      address could be overridden by DW_AT_entry_pc.  It's been
5005      removed, but GCC emits DW_AT_entry_pc and not DW_AT_lowpc for
5006      compilation units with discontinuous ranges.  */
5007   if (unlikely (dwarf_lowpc (cudie, &base) != 0))
5008     {
5009       Dwarf_Attribute attr_mem;
5010       if (dwarf_formaddr (dwarf_attr (cudie, DW_AT_entry_pc, &attr_mem),
5011                           &base) != 0)
5012         base = 0;
5013     }
5014   return base;
5015 }
5016
5017 static Dwarf_Addr
5018 listptr_base (struct listptr *p)
5019 {
5020   Dwarf_Die cu = CUDIE (p->cu);
5021   return cudie_base (&cu);
5022 }
5023
5024 /* To store the name used in compare_listptr */
5025 static const char *sort_listptr_name;
5026
5027 static int
5028 compare_listptr (const void *a, const void *b)
5029 {
5030   const char *name = sort_listptr_name;
5031   struct listptr *p1 = (void *) a;
5032   struct listptr *p2 = (void *) b;
5033
5034   if (p1->offset < p2->offset)
5035     return -1;
5036   if (p1->offset > p2->offset)
5037     return 1;
5038
5039   if (!p1->warned && !p2->warned)
5040     {
5041       if (p1->addr64 != p2->addr64)
5042         {
5043           p1->warned = p2->warned = true;
5044           error (0, 0,
5045                  _("%s %#" PRIx64 " used with different address sizes"),
5046                  name, (uint64_t) p1->offset);
5047         }
5048       if (p1->dwarf64 != p2->dwarf64)
5049         {
5050           p1->warned = p2->warned = true;
5051           error (0, 0,
5052                  _("%s %#" PRIx64 " used with different offset sizes"),
5053                  name, (uint64_t) p1->offset);
5054         }
5055       if (listptr_base (p1) != listptr_base (p2))
5056         {
5057           p1->warned = p2->warned = true;
5058           error (0, 0,
5059                  _("%s %#" PRIx64 " used with different base addresses"),
5060                  name, (uint64_t) p1->offset);
5061         }
5062       if (p1->attr != p2 ->attr)
5063         {
5064           p1->warned = p2->warned = true;
5065           error (0, 0,
5066                  _("%s %#" PRIx64
5067                           " used with different attribute %s and %s"),
5068                  name, (uint64_t) p1->offset, dwarf_attr_name (p1->attr),
5069                  dwarf_attr_name (p2->attr));
5070         }
5071     }
5072
5073   return 0;
5074 }
5075
5076 struct listptr_table
5077 {
5078   size_t n;
5079   size_t alloc;
5080   struct listptr *table;
5081 };
5082
5083 static struct listptr_table known_locsptr;
5084 static struct listptr_table known_loclistsptr;
5085 static struct listptr_table known_rangelistptr;
5086 static struct listptr_table known_rnglistptr;
5087 static struct listptr_table known_addrbases;
5088 static struct listptr_table known_stroffbases;
5089
5090 static void
5091 reset_listptr (struct listptr_table *table)
5092 {
5093   free (table->table);
5094   table->table = NULL;
5095   table->n = table->alloc = 0;
5096 }
5097
5098 /* Returns false if offset doesn't fit.  See struct listptr.  */
5099 static bool
5100 notice_listptr (enum section_e section, struct listptr_table *table,
5101                 uint_fast8_t address_size, uint_fast8_t offset_size,
5102                 struct Dwarf_CU *cu, Dwarf_Off offset, unsigned int attr)
5103 {
5104   if (print_debug_sections & section)
5105     {
5106       if (table->n == table->alloc)
5107         {
5108           if (table->alloc == 0)
5109             table->alloc = 128;
5110           else
5111             table->alloc *= 2;
5112           table->table = xrealloc (table->table,
5113                                    table->alloc * sizeof table->table[0]);
5114         }
5115
5116       struct listptr *p = &table->table[table->n++];
5117
5118       *p = (struct listptr)
5119         {
5120           .addr64 = address_size == 8,
5121           .dwarf64 = offset_size == 8,
5122           .offset = offset,
5123           .cu = cu,
5124           .attr = attr
5125         };
5126
5127       if (p->offset != offset)
5128         {
5129           table->n--;
5130           return false;
5131         }
5132     }
5133   return true;
5134 }
5135
5136 static void
5137 sort_listptr (struct listptr_table *table, const char *name)
5138 {
5139   if (table->n > 0)
5140     {
5141       sort_listptr_name = name;
5142       qsort (table->table, table->n, sizeof table->table[0],
5143              &compare_listptr);
5144     }
5145 }
5146
5147 static bool
5148 skip_listptr_hole (struct listptr_table *table, size_t *idxp,
5149                    uint_fast8_t *address_sizep, uint_fast8_t *offset_sizep,
5150                    Dwarf_Addr *base, struct Dwarf_CU **cu, ptrdiff_t offset,
5151                    unsigned char **readp, unsigned char *endp,
5152                    unsigned int *attr)
5153 {
5154   if (table->n == 0)
5155     return false;
5156
5157   while (*idxp < table->n && table->table[*idxp].offset < (Dwarf_Off) offset)
5158     ++*idxp;
5159
5160   struct listptr *p = &table->table[*idxp];
5161
5162   if (*idxp == table->n
5163       || p->offset >= (Dwarf_Off) (endp - *readp + offset))
5164     {
5165       *readp = endp;
5166       printf (_(" [%6tx]  <UNUSED GARBAGE IN REST OF SECTION>\n"),
5167               offset);
5168       return true;
5169     }
5170
5171   if (p->offset != (Dwarf_Off) offset)
5172     {
5173       *readp += p->offset - offset;
5174       printf (_(" [%6tx]  <UNUSED GARBAGE> ... %" PRIu64 " bytes ...\n"),
5175               offset, (Dwarf_Off) p->offset - offset);
5176       return true;
5177     }
5178
5179   if (address_sizep != NULL)
5180     *address_sizep = listptr_address_size (p);
5181   if (offset_sizep != NULL)
5182     *offset_sizep = listptr_offset_size (p);
5183   if (base != NULL)
5184     *base = listptr_base (p);
5185   if (cu != NULL)
5186     *cu = p->cu;
5187   if (attr != NULL)
5188     *attr = p->attr;
5189
5190   return false;
5191 }
5192
5193 static Dwarf_Off
5194 next_listptr_offset (struct listptr_table *table, size_t *idxp, Dwarf_Off off)
5195 {
5196   /* Note that multiple attributes could in theory point to the same loclist
5197      offset, so make sure we pick one that is bigger than the current one.
5198      The table is sorted on offset.  */
5199   if (*idxp < table->n)
5200     {
5201       while (++*idxp < table->n)
5202         {
5203           Dwarf_Off next = table->table[*idxp].offset;
5204           if (next > off)
5205             return next;
5206         }
5207     }
5208   return 0;
5209 }
5210
5211 /* Returns the listptr associated with the given index, or NULL.  */
5212 static struct listptr *
5213 get_listptr (struct listptr_table *table, size_t idx)
5214 {
5215   if (idx >= table->n)
5216     return NULL;
5217   return &table->table[idx];
5218 }
5219
5220 /* Returns the next index, base address and CU associated with the
5221    list unit offsets.  If there is none false is returned, otherwise
5222    true.  Assumes the table has been sorted.  */
5223 static bool
5224 listptr_cu (struct listptr_table *table, size_t *idxp,
5225             Dwarf_Off start, Dwarf_Off end,
5226             Dwarf_Addr *base, struct Dwarf_CU **cu)
5227 {
5228   while (*idxp < table->n
5229          && table->table[*idxp].offset < start)
5230     ++*idxp;
5231
5232   if (*idxp < table->n
5233       && table->table[*idxp].offset >= start
5234       && table->table[*idxp].offset < end)
5235     {
5236       struct listptr *p = &table->table[*idxp];
5237       *base = listptr_base (p);
5238       *cu = p->cu;
5239       return true;
5240     }
5241
5242   return false;
5243 }
5244
5245 /* Returns the next index with the current CU for the given attribute.
5246    If there is none false is returned, otherwise true.  Assumes the
5247    table has been sorted.  */
5248 static bool
5249 listptr_attr (struct listptr_table *table, size_t idxp,
5250               Dwarf_Off offset, unsigned int attr)
5251 {
5252   struct listptr *listptr;
5253   do
5254     {
5255       listptr = get_listptr (table, idxp);
5256       if (listptr == NULL)
5257         return false;
5258
5259       if (listptr->offset == offset && listptr->attr == attr)
5260         return true;
5261
5262       idxp++;
5263     }
5264   while (listptr->offset <= offset);
5265
5266   return false;
5267 }
5268
5269 static void
5270 print_debug_abbrev_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
5271                             Ebl *ebl, GElf_Ehdr *ehdr __attribute__ ((unused)),
5272                             Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
5273 {
5274   const size_t sh_size = (dbg->sectiondata[IDX_debug_abbrev] ?
5275                           dbg->sectiondata[IDX_debug_abbrev]->d_size : 0);
5276
5277   printf (_("\nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"
5278                    " [ Code]\n"),
5279           elf_ndxscn (scn), section_name (ebl, shdr),
5280           (uint64_t) shdr->sh_offset);
5281
5282   Dwarf_Off offset = 0;
5283   while (offset < sh_size)
5284     {
5285       printf (_("\nAbbreviation section at offset %" PRIu64 ":\n"),
5286               offset);
5287
5288       while (1)
5289         {
5290           size_t length;
5291           Dwarf_Abbrev abbrev;
5292
5293           int res = dwarf_offabbrev (dbg, offset, &length, &abbrev);
5294           if (res != 0)
5295             {
5296               if (unlikely (res < 0))
5297                 {
5298                   printf (_("\
5299  *** error while reading abbreviation: %s\n"),
5300                           dwarf_errmsg (-1));
5301                   return;
5302                 }
5303
5304               /* This is the NUL byte at the end of the section.  */
5305               ++offset;
5306               break;
5307             }
5308
5309           /* We know these calls can never fail.  */
5310           unsigned int code = dwarf_getabbrevcode (&abbrev);
5311           unsigned int tag = dwarf_getabbrevtag (&abbrev);
5312           int has_children = dwarf_abbrevhaschildren (&abbrev);
5313
5314           printf (_(" [%5u] offset: %" PRId64
5315                            ", children: %s, tag: %s\n"),
5316                   code, (int64_t) offset,
5317                   has_children ? yes_str : no_str,
5318                   dwarf_tag_name (tag));
5319
5320           size_t cnt = 0;
5321           unsigned int name;
5322           unsigned int form;
5323           Dwarf_Sword data;
5324           Dwarf_Off enoffset;
5325           while (dwarf_getabbrevattr_data (&abbrev, cnt, &name, &form,
5326                                            &data, &enoffset) == 0)
5327             {
5328               printf ("          attr: %s, form: %s",
5329                       dwarf_attr_name (name), dwarf_form_name (form));
5330               if (form == DW_FORM_implicit_const)
5331                 printf (" (%" PRId64 ")", data);
5332               printf (", offset: %#" PRIx64 "\n", (uint64_t) enoffset);
5333               ++cnt;
5334             }
5335
5336           offset += length;
5337         }
5338     }
5339 }
5340
5341
5342 static void
5343 print_debug_addr_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
5344                           Ebl *ebl, GElf_Ehdr *ehdr,
5345                           Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
5346 {
5347   printf (_("\
5348 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
5349           elf_ndxscn (scn), section_name (ebl, shdr),
5350           (uint64_t) shdr->sh_offset);
5351
5352   if (shdr->sh_size == 0)
5353     return;
5354
5355   /* We like to get the section from libdw to make sure they are relocated.  */
5356   Elf_Data *data = (dbg->sectiondata[IDX_debug_addr]
5357                     ?: elf_rawdata (scn, NULL));
5358   if (unlikely (data == NULL))
5359     {
5360       error (0, 0, _("cannot get .debug_addr section data: %s"),
5361              elf_errmsg (-1));
5362       return;
5363     }
5364
5365   size_t idx = 0;
5366   sort_listptr (&known_addrbases, "addr_base");
5367
5368   const unsigned char *start = (const unsigned char *) data->d_buf;
5369   const unsigned char *readp = start;
5370   const unsigned char *readendp = ((const unsigned char *) data->d_buf
5371                                    + data->d_size);
5372
5373   while (readp < readendp)
5374     {
5375       /* We cannot really know whether or not there is an header.  The
5376          DebugFission extension to DWARF4 doesn't add one.  The DWARF5
5377          .debug_addr variant does.  Whether or not we have an header,
5378          DW_AT_[GNU_]addr_base points at "index 0".  So if the current
5379          offset equals the CU addr_base then we can just start
5380          printing addresses.  If there is no CU with an exact match
5381          then we'll try to parse the header first.  */
5382       Dwarf_Off off = (Dwarf_Off) (readp
5383                                    - (const unsigned char *) data->d_buf);
5384
5385       printf ("Table at offset %" PRIx64 " ", off);
5386
5387       struct listptr *listptr = get_listptr (&known_addrbases, idx++);
5388       const unsigned char *next_unitp;
5389
5390       uint64_t unit_length;
5391       uint16_t version;
5392       uint8_t address_size;
5393       uint8_t segment_size;
5394       if (listptr == NULL)
5395         {
5396           error (0, 0, "Warning: No CU references .debug_addr after %" PRIx64,
5397                  off);
5398
5399           /* We will have to assume it is just addresses to the end... */
5400           address_size = ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
5401           next_unitp = readendp;
5402           printf ("Unknown CU:\n");
5403         }
5404       else
5405         {
5406           Dwarf_Die cudie;
5407           if (dwarf_cu_die (listptr->cu, &cudie,
5408                             NULL, NULL, NULL, NULL,
5409                             NULL, NULL) == NULL)
5410             printf ("Unknown CU (%s):\n", dwarf_errmsg (-1));
5411           else
5412             printf ("for CU [%6" PRIx64 "]:\n", dwarf_dieoffset (&cudie));
5413
5414           if (listptr->offset == off)
5415             {
5416               address_size = listptr_address_size (listptr);
5417               segment_size = 0;
5418               version = 4;
5419
5420               /* The addresses start here, but where do they end?  */
5421               listptr = get_listptr (&known_addrbases, idx);
5422               if (listptr == NULL)
5423                 next_unitp = readendp;
5424               else if (listptr->cu->version < 5)
5425                 {
5426                   next_unitp = start + listptr->offset;
5427                   if (listptr->offset < off || listptr->offset > data->d_size)
5428                     {
5429                       error (0, 0,
5430                              "Warning: Bad address base for next unit at %"
5431                              PRIx64, off);
5432                       next_unitp = readendp;
5433                     }
5434                 }
5435               else
5436                 {
5437                   /* Tricky, we don't have a header for this unit, but
5438                      there is one for the next.  We will have to
5439                      "guess" how big it is and subtract it from the
5440                      offset (because that points after the header).  */
5441                   unsigned int offset_size = listptr_offset_size (listptr);
5442                   Dwarf_Off next_off = (listptr->offset
5443                                         - (offset_size == 4 ? 4 : 12) /* len */
5444                                         - 2 /* version */
5445                                         - 1 /* address size */
5446                                         - 1); /* segment selector size */
5447                   next_unitp = start + next_off;
5448                   if (next_off < off || next_off > data->d_size)
5449                     {
5450                       error (0, 0,
5451                              "Warning: Couldn't calculate .debug_addr "
5452                              " unit length at %" PRIx64, off);
5453                       next_unitp = readendp;
5454                     }
5455                 }
5456               unit_length = (uint64_t) (next_unitp - readp);
5457
5458               /* Pretend we have a header.  */
5459               printf ("\n");
5460               printf (_(" Length:         %8" PRIu64 "\n"),
5461                       unit_length);
5462               printf (_(" DWARF version:  %8" PRIu16 "\n"), version);
5463               printf (_(" Address size:   %8" PRIu64 "\n"),
5464                       (uint64_t) address_size);
5465               printf (_(" Segment size:   %8" PRIu64 "\n"),
5466                       (uint64_t) segment_size);
5467               printf ("\n");
5468             }
5469           else
5470             {
5471               /* OK, we have to parse an header first.  */
5472               unit_length = read_4ubyte_unaligned_inc (dbg, readp);
5473               if (unlikely (unit_length == 0xffffffff))
5474                 {
5475                   if (unlikely (readp > readendp - 8))
5476                     {
5477                     invalid_data:
5478                       error (0, 0, "Invalid data");
5479                       return;
5480                     }
5481                   unit_length = read_8ubyte_unaligned_inc (dbg, readp);
5482                 }
5483               printf ("\n");
5484               printf (_(" Length:         %8" PRIu64 "\n"),
5485                       unit_length);
5486
5487               /* We need at least 2-bytes (version) + 1-byte
5488                  (addr_size) + 1-byte (segment_size) = 4 bytes to
5489                  complete the header.  And this unit cannot go beyond
5490                  the section data.  */
5491               if (readp > readendp - 4
5492                   || unit_length < 4
5493                   || unit_length > (uint64_t) (readendp - readp))
5494                 goto invalid_data;
5495
5496               next_unitp = readp + unit_length;
5497
5498               version = read_2ubyte_unaligned_inc (dbg, readp);
5499               printf (_(" DWARF version:  %8" PRIu16 "\n"), version);
5500
5501               if (version != 5)
5502                 {
5503                   error (0, 0, _("Unknown version"));
5504                   goto next_unit;
5505                 }
5506
5507               address_size = *readp++;
5508               printf (_(" Address size:   %8" PRIu64 "\n"),
5509                       (uint64_t) address_size);
5510
5511               if (address_size != 4 && address_size != 8)
5512                 {
5513                   error (0, 0, _("unsupported address size"));
5514                   goto next_unit;
5515                 }
5516
5517               segment_size = *readp++;
5518               printf (_(" Segment size:   %8" PRIu64 "\n"),
5519                       (uint64_t) segment_size);
5520               printf ("\n");
5521
5522               if (segment_size != 0)
5523                 {
5524                   error (0, 0, _("unsupported segment size"));
5525                   goto next_unit;
5526                 }
5527
5528               if (listptr->offset != (Dwarf_Off) (readp - start))
5529                 {
5530                   error (0, 0, "Address index doesn't start after header");
5531                   goto next_unit;
5532                 }
5533             }
5534         }
5535
5536       int digits = 1;
5537       size_t addresses = (next_unitp - readp) / address_size;
5538       while (addresses >= 10)
5539         {
5540           ++digits;
5541           addresses /= 10;
5542         }
5543
5544       unsigned int uidx = 0;
5545       size_t index_offset =  readp - (const unsigned char *) data->d_buf;
5546       printf (" Addresses start at offset 0x%zx:\n", index_offset);
5547       while (readp <= next_unitp - address_size)
5548         {
5549           Dwarf_Addr addr = read_addr_unaligned_inc (address_size, dbg,
5550                                                      readp);
5551           printf (" [%*u] ", digits, uidx++);
5552           print_dwarf_addr (dwflmod, address_size, addr, addr);
5553           printf ("\n");
5554         }
5555       printf ("\n");
5556
5557       if (readp != next_unitp)
5558         error (0, 0, "extra %zd bytes at end of unit",
5559                (size_t) (next_unitp - readp));
5560
5561     next_unit:
5562       readp = next_unitp;
5563     }
5564 }
5565
5566 /* Print content of DWARF .debug_aranges section.  We fortunately do
5567    not have to know a bit about the structure of the section, libdwarf
5568    takes care of it.  */
5569 static void
5570 print_decoded_aranges_section (Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn,
5571                                GElf_Shdr *shdr, Dwarf *dbg)
5572 {
5573   Dwarf_Aranges *aranges;
5574   size_t cnt;
5575   if (unlikely (dwarf_getaranges (dbg, &aranges, &cnt) != 0))
5576     {
5577       error (0, 0, _("cannot get .debug_aranges content: %s"),
5578              dwarf_errmsg (-1));
5579       return;
5580     }
5581
5582   GElf_Shdr glink_mem;
5583   GElf_Shdr *glink;
5584   glink = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link), &glink_mem);
5585   if (glink == NULL)
5586     {
5587       error (0, 0, _("invalid sh_link value in section %zu"),
5588              elf_ndxscn (scn));
5589       return;
5590     }
5591
5592   printf (ngettext ("\
5593 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 " contains %zu entry:\n",
5594                     "\
5595 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 " contains %zu entries:\n",
5596                     cnt),
5597           elf_ndxscn (scn), section_name (ebl, shdr),
5598           (uint64_t) shdr->sh_offset, cnt);
5599
5600   /* Compute floor(log16(cnt)).  */
5601   size_t tmp = cnt;
5602   int digits = 1;
5603   while (tmp >= 16)
5604     {
5605       ++digits;
5606       tmp >>= 4;
5607     }
5608
5609   for (size_t n = 0; n < cnt; ++n)
5610     {
5611       Dwarf_Arange *runp = dwarf_onearange (aranges, n);
5612       if (unlikely (runp == NULL))
5613         {
5614           printf ("cannot get arange %zu: %s\n", n, dwarf_errmsg (-1));
5615           return;
5616         }
5617
5618       Dwarf_Addr start;
5619       Dwarf_Word length;
5620       Dwarf_Off offset;
5621
5622       if (unlikely (dwarf_getarangeinfo (runp, &start, &length, &offset) != 0))
5623         printf (_(" [%*zu] ???\n"), digits, n);
5624       else
5625         printf (_(" [%*zu] start: %0#*" PRIx64
5626                          ", length: %5" PRIu64 ", CU DIE offset: %6"
5627                          PRId64 "\n"),
5628                 digits, n, ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 10 : 18,
5629                 (uint64_t) start, (uint64_t) length, (int64_t) offset);
5630     }
5631 }
5632
5633
5634 /* Print content of DWARF .debug_aranges section.  */
5635 static void
5636 print_debug_aranges_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
5637                              Ebl *ebl, GElf_Ehdr *ehdr, Elf_Scn *scn,
5638                              GElf_Shdr *shdr, Dwarf *dbg)
5639 {
5640   if (decodedaranges)
5641     {
5642       print_decoded_aranges_section (ebl, ehdr, scn, shdr, dbg);
5643       return;
5644     }
5645
5646   Elf_Data *data = (dbg->sectiondata[IDX_debug_aranges]
5647                     ?: elf_rawdata (scn, NULL));
5648
5649   if (unlikely (data == NULL))
5650     {
5651       error (0, 0, _("cannot get .debug_aranges content: %s"),
5652              elf_errmsg (-1));
5653       return;
5654     }
5655
5656   printf (_("\
5657 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
5658           elf_ndxscn (scn), section_name (ebl, shdr),
5659           (uint64_t) shdr->sh_offset);
5660
5661   const unsigned char *readp = data->d_buf;
5662   const unsigned char *readendp = readp + data->d_size;
5663
5664   while (readp < readendp)
5665     {
5666       const unsigned char *hdrstart = readp;
5667       size_t start_offset = hdrstart - (const unsigned char *) data->d_buf;
5668
5669       printf (_("\nTable at offset %zu:\n"), start_offset);
5670       if (readp + 4 > readendp)
5671         {
5672         invalid_data:
5673           error (0, 0, _("invalid data in section [%zu] '%s'"),
5674                  elf_ndxscn (scn), section_name (ebl, shdr));
5675           return;
5676         }
5677
5678       Dwarf_Word length = read_4ubyte_unaligned_inc (dbg, readp);
5679       unsigned int length_bytes = 4;
5680       if (length == DWARF3_LENGTH_64_BIT)
5681         {
5682           if (readp + 8 > readendp)
5683             goto invalid_data;
5684           length = read_8ubyte_unaligned_inc (dbg, readp);
5685           length_bytes = 8;
5686         }
5687
5688       const unsigned char *nexthdr = readp + length;
5689       printf (_("\n Length:        %6" PRIu64 "\n"),
5690               (uint64_t) length);
5691
5692       if (unlikely (length > (size_t) (readendp - readp)))
5693         goto invalid_data;
5694
5695       if (length == 0)
5696         continue;
5697
5698       if (readp + 2 > readendp)
5699         goto invalid_data;
5700       uint_fast16_t version = read_2ubyte_unaligned_inc (dbg, readp);
5701       printf (_(" DWARF version: %6" PRIuFAST16 "\n"),
5702               version);
5703       if (version != 2)
5704         {
5705           error (0, 0, _("unsupported aranges version"));
5706           goto next_table;
5707         }
5708
5709       Dwarf_Word offset;
5710       if (readp + length_bytes > readendp)
5711         goto invalid_data;
5712       if (length_bytes == 8)
5713         offset = read_8ubyte_unaligned_inc (dbg, readp);
5714       else
5715         offset = read_4ubyte_unaligned_inc (dbg, readp);
5716       printf (_(" CU offset:     %6" PRIx64 "\n"),
5717               (uint64_t) offset);
5718
5719       if (readp + 1 > readendp)
5720         goto invalid_data;
5721       unsigned int address_size = *readp++;
5722       printf (_(" Address size:  %6" PRIu64 "\n"),
5723               (uint64_t) address_size);
5724       if (address_size != 4 && address_size != 8)
5725         {
5726           error (0, 0, _("unsupported address size"));
5727           goto next_table;
5728         }
5729
5730       if (readp + 1 > readendp)
5731         goto invalid_data;
5732       unsigned int segment_size = *readp++;
5733       printf (_(" Segment size:  %6" PRIu64 "\n\n"),
5734               (uint64_t) segment_size);
5735       if (segment_size != 0 && segment_size != 4 && segment_size != 8)
5736         {
5737           error (0, 0, _("unsupported segment size"));
5738           goto next_table;
5739         }
5740
5741       /* Round the address to the next multiple of 2*address_size.  */
5742       readp += ((2 * address_size - ((readp - hdrstart) % (2 * address_size)))
5743                 % (2 * address_size));
5744
5745       while (readp < nexthdr)
5746         {
5747           Dwarf_Word range_address;
5748           Dwarf_Word range_length;
5749           Dwarf_Word segment = 0;
5750           if (readp + 2 * address_size + segment_size > readendp)
5751             goto invalid_data;
5752           if (address_size == 4)
5753             {
5754               range_address = read_4ubyte_unaligned_inc (dbg, readp);
5755               range_length = read_4ubyte_unaligned_inc (dbg, readp);
5756             }
5757           else
5758             {
5759               range_address = read_8ubyte_unaligned_inc (dbg, readp);
5760               range_length = read_8ubyte_unaligned_inc (dbg, readp);
5761             }
5762
5763           if (segment_size == 4)
5764             segment = read_4ubyte_unaligned_inc (dbg, readp);
5765           else if (segment_size == 8)
5766             segment = read_8ubyte_unaligned_inc (dbg, readp);
5767
5768           if (range_address == 0 && range_length == 0 && segment == 0)
5769             break;
5770
5771           printf ("   ");
5772           print_dwarf_addr (dwflmod, address_size, range_address,
5773                             range_address);
5774           printf ("..");
5775           print_dwarf_addr (dwflmod, address_size,
5776                             range_address + range_length - 1,
5777                             range_length);
5778           if (segment_size != 0)
5779             printf (" (%" PRIx64 ")\n", (uint64_t) segment);
5780           else
5781             printf ("\n");
5782         }
5783
5784     next_table:
5785       if (readp != nexthdr)
5786         {
5787           size_t padding = nexthdr - readp;
5788           printf (_("   %zu padding bytes\n"), padding);
5789           readp = nexthdr;
5790         }
5791     }
5792 }
5793
5794
5795 static bool is_split_dwarf (Dwarf *dbg, uint64_t *id, Dwarf_CU **split_cu);
5796
5797 /* Returns true and sets cu and cu_base if the given Dwarf is a split
5798    DWARF (.dwo) file.  */
5799 static bool
5800 split_dwarf_cu_base (Dwarf *dbg, Dwarf_CU **cu, Dwarf_Addr *cu_base)
5801 {
5802   uint64_t id;
5803   if (is_split_dwarf (dbg, &id, cu))
5804     {
5805       Dwarf_Die cudie;
5806       if (dwarf_cu_info (*cu, NULL, NULL, &cudie, NULL, NULL, NULL, NULL) == 0)
5807         {
5808           *cu_base = cudie_base (&cudie);
5809           return true;
5810         }
5811     }
5812   return false;
5813 }
5814
5815 /* Print content of DWARF .debug_rnglists section.  */
5816 static void
5817 print_debug_rnglists_section (Dwfl_Module *dwflmod,
5818                               Ebl *ebl,
5819                               GElf_Ehdr *ehdr __attribute__ ((unused)),
5820                               Elf_Scn *scn, GElf_Shdr *shdr,
5821                               Dwarf *dbg __attribute__((unused)))
5822 {
5823   printf (_("\
5824 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
5825           elf_ndxscn (scn), section_name (ebl, shdr),
5826           (uint64_t) shdr->sh_offset);
5827
5828   Elf_Data *data =(dbg->sectiondata[IDX_debug_rnglists]
5829                    ?: elf_rawdata (scn, NULL));
5830   if (unlikely (data == NULL))
5831     {
5832       error (0, 0, _("cannot get .debug_rnglists content: %s"),
5833              elf_errmsg (-1));
5834       return;
5835     }
5836
5837   /* For the listptr to get the base address/CU.  */
5838   sort_listptr (&known_rnglistptr, "rnglistptr");
5839   size_t listptr_idx = 0;
5840
5841   const unsigned char *readp = data->d_buf;
5842   const unsigned char *const dataend = ((unsigned char *) data->d_buf
5843                                         + data->d_size);
5844   while (readp < dataend)
5845     {
5846       if (unlikely (readp > dataend - 4))
5847         {
5848         invalid_data:
5849           error (0, 0, _("invalid data in section [%zu] '%s'"),
5850                  elf_ndxscn (scn), section_name (ebl, shdr));
5851           return;
5852         }
5853
5854       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
5855       printf (_("Table at Offset 0x%" PRIx64 ":\n\n"),
5856               (uint64_t) offset);
5857
5858       uint64_t unit_length = read_4ubyte_unaligned_inc (dbg, readp);
5859       unsigned int offset_size = 4;
5860       if (unlikely (unit_length == 0xffffffff))
5861         {
5862           if (unlikely (readp > dataend - 8))
5863             goto invalid_data;
5864
5865           unit_length = read_8ubyte_unaligned_inc (dbg, readp);
5866           offset_size = 8;
5867         }
5868       printf (_(" Length:         %8" PRIu64 "\n"), unit_length);
5869
5870       /* We need at least 2-bytes + 1-byte + 1-byte + 4-bytes = 8
5871          bytes to complete the header.  And this unit cannot go beyond
5872          the section data.  */
5873       if (readp > dataend - 8
5874           || unit_length < 8
5875           || unit_length > (uint64_t) (dataend - readp))
5876         goto invalid_data;
5877
5878       const unsigned char *nexthdr = readp + unit_length;
5879
5880       uint16_t version = read_2ubyte_unaligned_inc (dbg, readp);
5881       printf (_(" DWARF version:  %8" PRIu16 "\n"), version);
5882
5883       if (version != 5)
5884         {
5885           error (0, 0, _("Unknown version"));
5886           goto next_table;
5887         }
5888
5889       uint8_t address_size = *readp++;
5890       printf (_(" Address size:   %8" PRIu64 "\n"),
5891               (uint64_t) address_size);
5892
5893       if (address_size != 4 && address_size != 8)
5894         {
5895           error (0, 0, _("unsupported address size"));
5896           goto next_table;
5897         }
5898
5899       uint8_t segment_size = *readp++;
5900       printf (_(" Segment size:   %8" PRIu64 "\n"),
5901               (uint64_t) segment_size);
5902
5903       if (segment_size != 0 && segment_size != 4 && segment_size != 8)
5904         {
5905           error (0, 0, _("unsupported segment size"));
5906           goto next_table;
5907         }
5908
5909       uint32_t offset_entry_count = read_4ubyte_unaligned_inc (dbg, readp);
5910       printf (_(" Offset entries: %8" PRIu64 "\n"),
5911               (uint64_t) offset_entry_count);
5912
5913       /* We need the CU that uses this unit to get the initial base address. */
5914       Dwarf_Addr cu_base = 0;
5915       struct Dwarf_CU *cu = NULL;
5916       if (listptr_cu (&known_rnglistptr, &listptr_idx,
5917                       (Dwarf_Off) offset,
5918                       (Dwarf_Off) (nexthdr - (unsigned char *) data->d_buf),
5919                       &cu_base, &cu)
5920           || split_dwarf_cu_base (dbg, &cu, &cu_base))
5921         {
5922           Dwarf_Die cudie;
5923           if (dwarf_cu_die (cu, &cudie,
5924                             NULL, NULL, NULL, NULL,
5925                             NULL, NULL) == NULL)
5926             printf (_(" Unknown CU base: "));
5927           else
5928             printf (_(" CU [%6" PRIx64 "] base: "),
5929                     dwarf_dieoffset (&cudie));
5930           print_dwarf_addr (dwflmod, address_size, cu_base, cu_base);
5931           printf ("\n");
5932         }
5933       else
5934         printf (_(" Not associated with a CU.\n"));
5935
5936       printf ("\n");
5937
5938       const unsigned char *offset_array_start = readp;
5939       if (offset_entry_count > 0)
5940         {
5941           uint64_t max_entries = (unit_length - 8) / offset_size;
5942           if (offset_entry_count > max_entries)
5943             {
5944               error (0, 0,
5945                      _("too many offset entries for unit length"));
5946               offset_entry_count = max_entries;
5947             }
5948
5949           printf (_("  Offsets starting at 0x%" PRIx64 ":\n"),
5950                   (uint64_t) (offset_array_start
5951                               - (unsigned char *) data->d_buf));
5952           for (uint32_t idx = 0; idx < offset_entry_count; idx++)
5953             {
5954               printf ("   [%6" PRIu32 "] ", idx);
5955               if (offset_size == 4)
5956                 {
5957                   uint32_t off = read_4ubyte_unaligned_inc (dbg, readp);
5958                   printf ("0x%" PRIx32 "\n", off);
5959                 }
5960               else
5961                 {
5962                   uint64_t off = read_8ubyte_unaligned_inc (dbg, readp);
5963                   printf ("0x%" PRIx64 "\n", off);
5964                 }
5965             }
5966           printf ("\n");
5967         }
5968
5969       Dwarf_Addr base = cu_base;
5970       bool start_of_list = true;
5971       while (readp < nexthdr)
5972         {
5973           uint8_t kind = *readp++;
5974           uint64_t op1, op2;
5975
5976           /* Skip padding.  */
5977           if (start_of_list && kind == DW_RLE_end_of_list)
5978             continue;
5979
5980           if (start_of_list)
5981             {
5982               base = cu_base;
5983               printf ("  Offset: %" PRIx64 ", Index: %" PRIx64 "\n",
5984                       (uint64_t) (readp - (unsigned char *) data->d_buf - 1),
5985                       (uint64_t) (readp - offset_array_start - 1));
5986               start_of_list = false;
5987             }
5988
5989           printf ("    %s", dwarf_range_list_encoding_name (kind));
5990           switch (kind)
5991             {
5992             case DW_RLE_end_of_list:
5993               start_of_list = true;
5994               printf ("\n\n");
5995               break;
5996
5997             case DW_RLE_base_addressx:
5998               if ((uint64_t) (nexthdr - readp) < 1)
5999                 {
6000                 invalid_range:
6001                   error (0, 0, _("invalid range list data"));
6002                   goto next_table;
6003                 }
6004               get_uleb128 (op1, readp, nexthdr);
6005               printf (" %" PRIx64 "\n", op1);
6006               if (! print_unresolved_addresses)
6007                 {
6008                   Dwarf_Addr addr;
6009                   if (get_indexed_addr (cu, op1, &addr) != 0)
6010                     printf ("      ???\n");
6011                   else
6012                     {
6013                       printf ("      ");
6014                       print_dwarf_addr (dwflmod, address_size, addr, addr);
6015                       printf ("\n");
6016                     }
6017                 }
6018               break;
6019
6020             case DW_RLE_startx_endx:
6021               if ((uint64_t) (nexthdr - readp) < 1)
6022                 goto invalid_range;
6023               get_uleb128 (op1, readp, nexthdr);
6024               if ((uint64_t) (nexthdr - readp) < 1)
6025                 goto invalid_range;
6026               get_uleb128 (op2, readp, nexthdr);
6027               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
6028               if (! print_unresolved_addresses)
6029                 {
6030                   Dwarf_Addr addr1;
6031                   Dwarf_Addr addr2;
6032                   if (get_indexed_addr (cu, op1, &addr1) != 0
6033                       || get_indexed_addr (cu, op2, &addr2) != 0)
6034                     {
6035                       printf ("      ???..\n");
6036                       printf ("      ???\n");
6037                     }
6038                   else
6039                     {
6040                       printf ("      ");
6041                       print_dwarf_addr (dwflmod, address_size, addr1, addr1);
6042                       printf ("..\n      ");
6043                       print_dwarf_addr (dwflmod, address_size,
6044                                         addr2 - 1, addr2);
6045                       printf ("\n");
6046                     }
6047                 }
6048               break;
6049
6050             case DW_RLE_startx_length:
6051               if ((uint64_t) (nexthdr - readp) < 1)
6052                 goto invalid_range;
6053               get_uleb128 (op1, readp, nexthdr);
6054               if ((uint64_t) (nexthdr - readp) < 1)
6055                 goto invalid_range;
6056               get_uleb128 (op2, readp, nexthdr);
6057               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
6058               if (! print_unresolved_addresses)
6059                 {
6060                   Dwarf_Addr addr1;
6061                   Dwarf_Addr addr2;
6062                   if (get_indexed_addr (cu, op1, &addr1) != 0)
6063                     {
6064                       printf ("      ???..\n");
6065                       printf ("      ???\n");
6066                     }
6067                   else
6068                     {
6069                       addr2 = addr1 + op2;
6070                       printf ("      ");
6071                       print_dwarf_addr (dwflmod, address_size, addr1, addr1);
6072                       printf ("..\n      ");
6073                       print_dwarf_addr (dwflmod, address_size,
6074                                         addr2 - 1, addr2);
6075                       printf ("\n");
6076                     }
6077                 }
6078               break;
6079
6080             case DW_RLE_offset_pair:
6081               if ((uint64_t) (nexthdr - readp) < 1)
6082                 goto invalid_range;
6083               get_uleb128 (op1, readp, nexthdr);
6084               if ((uint64_t) (nexthdr - readp) < 1)
6085                 goto invalid_range;
6086               get_uleb128 (op2, readp, nexthdr);
6087               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
6088               if (! print_unresolved_addresses)
6089                 {
6090                   op1 += base;
6091                   op2 += base;
6092                   printf ("      ");
6093                   print_dwarf_addr (dwflmod, address_size, op1, op1);
6094                   printf ("..\n      ");
6095                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
6096                   printf ("\n");
6097                 }
6098               break;
6099
6100             case DW_RLE_base_address:
6101               if (address_size == 4)
6102                 {
6103                   if ((uint64_t) (nexthdr - readp) < 4)
6104                     goto invalid_range;
6105                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
6106                 }
6107               else
6108                 {
6109                   if ((uint64_t) (nexthdr - readp) < 8)
6110                     goto invalid_range;
6111                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
6112                 }
6113               base = op1;
6114               printf (" 0x%" PRIx64 "\n", base);
6115               if (! print_unresolved_addresses)
6116                 {
6117                   printf ("      ");
6118                   print_dwarf_addr (dwflmod, address_size, base, base);
6119                   printf ("\n");
6120                 }
6121               break;
6122
6123             case DW_RLE_start_end:
6124               if (address_size == 4)
6125                 {
6126                   if ((uint64_t) (nexthdr - readp) < 8)
6127                     goto invalid_range;
6128                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
6129                   op2 = read_4ubyte_unaligned_inc (dbg, readp);
6130                 }
6131               else
6132                 {
6133                   if ((uint64_t) (nexthdr - readp) < 16)
6134                     goto invalid_range;
6135                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
6136                   op2 = read_8ubyte_unaligned_inc (dbg, readp);
6137                 }
6138               printf (" 0x%" PRIx64 "..0x%" PRIx64 "\n", op1, op2);
6139               if (! print_unresolved_addresses)
6140                 {
6141                   printf ("      ");
6142                   print_dwarf_addr (dwflmod, address_size, op1, op1);
6143                   printf ("..\n      ");
6144                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
6145                   printf ("\n");
6146                 }
6147               break;
6148
6149             case DW_RLE_start_length:
6150               if (address_size == 4)
6151                 {
6152                   if ((uint64_t) (nexthdr - readp) < 4)
6153                     goto invalid_range;
6154                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
6155                 }
6156               else
6157                 {
6158                   if ((uint64_t) (nexthdr - readp) < 8)
6159                     goto invalid_range;
6160                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
6161                 }
6162               if ((uint64_t) (nexthdr - readp) < 1)
6163                 goto invalid_range;
6164               get_uleb128 (op2, readp, nexthdr);
6165               printf (" 0x%" PRIx64 ", %" PRIx64 "\n", op1, op2);
6166               if (! print_unresolved_addresses)
6167                 {
6168                   op2 = op1 + op2;
6169                   printf ("      ");
6170                   print_dwarf_addr (dwflmod, address_size, op1, op1);
6171                   printf ("..\n      ");
6172                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
6173                   printf ("\n");
6174                 }
6175               break;
6176
6177             default:
6178               goto invalid_range;
6179             }
6180         }
6181
6182     next_table:
6183       if (readp != nexthdr)
6184         {
6185           size_t padding = nexthdr - readp;
6186           printf (_("   %zu padding bytes\n\n"), padding);
6187           readp = nexthdr;
6188         }
6189     }
6190 }
6191
6192 /* Print content of DWARF .debug_ranges section.  */
6193 static void
6194 print_debug_ranges_section (Dwfl_Module *dwflmod,
6195                             Ebl *ebl, GElf_Ehdr *ehdr,
6196                             Elf_Scn *scn, GElf_Shdr *shdr,
6197                             Dwarf *dbg)
6198 {
6199   Elf_Data *data = (dbg->sectiondata[IDX_debug_ranges]
6200                     ?: elf_rawdata (scn, NULL));
6201   if (unlikely (data == NULL))
6202     {
6203       error (0, 0, _("cannot get .debug_ranges content: %s"),
6204              elf_errmsg (-1));
6205       return;
6206     }
6207
6208   printf (_("\
6209 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
6210           elf_ndxscn (scn), section_name (ebl, shdr),
6211           (uint64_t) shdr->sh_offset);
6212
6213   sort_listptr (&known_rangelistptr, "rangelistptr");
6214   size_t listptr_idx = 0;
6215
6216   uint_fast8_t address_size = ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
6217
6218   bool first = true;
6219   Dwarf_Addr base = 0;
6220   unsigned char *const endp = (unsigned char *) data->d_buf + data->d_size;
6221   unsigned char *readp = data->d_buf;
6222   Dwarf_CU *last_cu = NULL;
6223   while (readp < endp)
6224     {
6225       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
6226       Dwarf_CU *cu = last_cu;
6227
6228       if (first && skip_listptr_hole (&known_rangelistptr, &listptr_idx,
6229                                       &address_size, NULL, &base, &cu,
6230                                       offset, &readp, endp, NULL))
6231         continue;
6232
6233       if (last_cu != cu)
6234         {
6235           Dwarf_Die cudie;
6236           if (dwarf_cu_die (cu, &cudie,
6237                             NULL, NULL, NULL, NULL,
6238                             NULL, NULL) == NULL)
6239             printf (_("\n Unknown CU base: "));
6240           else
6241             printf (_("\n CU [%6" PRIx64 "] base: "),
6242                     dwarf_dieoffset (&cudie));
6243           print_dwarf_addr (dwflmod, address_size, base, base);
6244           printf ("\n");
6245         }
6246       last_cu = cu;
6247
6248       if (unlikely (data->d_size - offset < (size_t) address_size * 2))
6249         {
6250           printf (_(" [%6tx]  <INVALID DATA>\n"), offset);
6251           break;
6252         }
6253
6254       Dwarf_Addr begin;
6255       Dwarf_Addr end;
6256       if (address_size == 8)
6257         {
6258           begin = read_8ubyte_unaligned_inc (dbg, readp);
6259           end = read_8ubyte_unaligned_inc (dbg, readp);
6260         }
6261       else
6262         {
6263           begin = read_4ubyte_unaligned_inc (dbg, readp);
6264           end = read_4ubyte_unaligned_inc (dbg, readp);
6265           if (begin == (Dwarf_Addr) (uint32_t) -1)
6266             begin = (Dwarf_Addr) -1l;
6267         }
6268
6269       if (begin == (Dwarf_Addr) -1l) /* Base address entry.  */
6270         {
6271           if (first)
6272             printf (" [%6tx] ", offset);
6273           else
6274             printf ("          ");
6275           puts (_("base address"));
6276           printf ("          ");
6277           print_dwarf_addr (dwflmod, address_size, end, end);
6278           printf ("\n");
6279           base = end;
6280           first = false;
6281         }
6282       else if (begin == 0 && end == 0) /* End of list entry.  */
6283         {
6284           if (first)
6285             printf (_(" [%6tx] empty list\n"), offset);
6286           first = true;
6287         }
6288       else
6289         {
6290           /* We have an address range entry.  */
6291           if (first)            /* First address range entry in a list.  */
6292             printf (" [%6tx] ", offset);
6293           else
6294             printf ("          ");
6295
6296           printf ("range %" PRIx64 ", %" PRIx64 "\n", begin, end);
6297           if (! print_unresolved_addresses)
6298             {
6299               printf ("          ");
6300               print_dwarf_addr (dwflmod, address_size, base + begin,
6301                                 base + begin);
6302               printf ("..\n          ");
6303               print_dwarf_addr (dwflmod, address_size,
6304                                 base + end - 1, base + end);
6305               printf ("\n");
6306             }
6307
6308           first = false;
6309         }
6310     }
6311 }
6312
6313 #define REGNAMESZ 16
6314 static const char *
6315 register_info (Ebl *ebl, unsigned int regno, const Ebl_Register_Location *loc,
6316                char name[REGNAMESZ], int *bits, int *type)
6317 {
6318   const char *set;
6319   const char *pfx;
6320   int ignore;
6321   ssize_t n = ebl_register_info (ebl, regno, name, REGNAMESZ, &pfx, &set,
6322                                  bits ?: &ignore, type ?: &ignore);
6323   if (n <= 0)
6324     {
6325       if (loc != NULL)
6326         snprintf (name, REGNAMESZ, "reg%u", loc->regno);
6327       else
6328         snprintf (name, REGNAMESZ, "??? 0x%x", regno);
6329       if (bits != NULL)
6330         *bits = loc != NULL ? loc->bits : 0;
6331       if (type != NULL)
6332         *type = DW_ATE_unsigned;
6333       set = "??? unrecognized";
6334     }
6335   else
6336     {
6337       if (bits != NULL && *bits <= 0)
6338         *bits = loc != NULL ? loc->bits : 0;
6339       if (type != NULL && *type == DW_ATE_void)
6340         *type = DW_ATE_unsigned;
6341
6342     }
6343   return set;
6344 }
6345
6346 static const unsigned char *
6347 read_encoded (unsigned int encoding, const unsigned char *readp,
6348               const unsigned char *const endp, uint64_t *res, Dwarf *dbg)
6349 {
6350   if ((encoding & 0xf) == DW_EH_PE_absptr)
6351     encoding = gelf_getclass (dbg->elf) == ELFCLASS32
6352       ? DW_EH_PE_udata4 : DW_EH_PE_udata8;
6353
6354   switch (encoding & 0xf)
6355     {
6356     case DW_EH_PE_uleb128:
6357       get_uleb128 (*res, readp, endp);
6358       break;
6359     case DW_EH_PE_sleb128:
6360       get_sleb128 (*res, readp, endp);
6361       break;
6362     case DW_EH_PE_udata2:
6363       if (readp + 2 > endp)
6364         goto invalid;
6365       *res = read_2ubyte_unaligned_inc (dbg, readp);
6366       break;
6367     case DW_EH_PE_udata4:
6368       if (readp + 4 > endp)
6369         goto invalid;
6370       *res = read_4ubyte_unaligned_inc (dbg, readp);
6371       break;
6372     case DW_EH_PE_udata8:
6373       if (readp + 8 > endp)
6374         goto invalid;
6375       *res = read_8ubyte_unaligned_inc (dbg, readp);
6376       break;
6377     case DW_EH_PE_sdata2:
6378       if (readp + 2 > endp)
6379         goto invalid;
6380       *res = read_2sbyte_unaligned_inc (dbg, readp);
6381       break;
6382     case DW_EH_PE_sdata4:
6383       if (readp + 4 > endp)
6384         goto invalid;
6385       *res = read_4sbyte_unaligned_inc (dbg, readp);
6386       break;
6387     case DW_EH_PE_sdata8:
6388       if (readp + 8 > endp)
6389         goto invalid;
6390       *res = read_8sbyte_unaligned_inc (dbg, readp);
6391       break;
6392     default:
6393     invalid:
6394       error (1, 0,
6395              _("invalid encoding"));
6396     }
6397
6398   return readp;
6399 }
6400
6401 static const char *
6402 regname (Ebl *ebl, unsigned int regno, char *regnamebuf)
6403 {
6404   register_info (ebl, regno, NULL, regnamebuf, NULL, NULL);
6405
6406   return regnamebuf;
6407 }
6408
6409 static void
6410 print_cfa_program (const unsigned char *readp, const unsigned char *const endp,
6411                    Dwarf_Word vma_base, unsigned int code_align,
6412                    int data_align,
6413                    unsigned int version, unsigned int ptr_size,
6414                    unsigned int encoding,
6415                    Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr, Dwarf *dbg)
6416 {
6417   char regnamebuf[REGNAMESZ];
6418
6419   puts ("\n   Program:");
6420   Dwarf_Word pc = vma_base;
6421   while (readp < endp)
6422     {
6423       unsigned int opcode = *readp++;
6424
6425       if (opcode < DW_CFA_advance_loc)
6426         /* Extended opcode.  */
6427         switch (opcode)
6428           {
6429             uint64_t op1;
6430             int64_t sop1;
6431             uint64_t op2;
6432             int64_t sop2;
6433
6434           case DW_CFA_nop:
6435             puts ("     nop");
6436             break;
6437           case DW_CFA_set_loc:
6438             if ((uint64_t) (endp - readp) < 1)
6439               goto invalid;
6440             readp = read_encoded (encoding, readp, endp, &op1, dbg);
6441             printf ("     set_loc %#" PRIx64 " to %#" PRIx64 "\n",
6442                     op1, pc = vma_base + op1);
6443             break;
6444           case DW_CFA_advance_loc1:
6445             if ((uint64_t) (endp - readp) < 1)
6446               goto invalid;
6447             printf ("     advance_loc1 %u to %#" PRIx64 "\n",
6448                     *readp, pc += *readp * code_align);
6449             ++readp;
6450             break;
6451           case DW_CFA_advance_loc2:
6452             if ((uint64_t) (endp - readp) < 2)
6453               goto invalid;
6454             op1 = read_2ubyte_unaligned_inc (dbg, readp);
6455             printf ("     advance_loc2 %" PRIu64 " to %#" PRIx64 "\n",
6456                     op1, pc += op1 * code_align);
6457             break;
6458           case DW_CFA_advance_loc4:
6459             if ((uint64_t) (endp - readp) < 4)
6460               goto invalid;
6461             op1 = read_4ubyte_unaligned_inc (dbg, readp);
6462             printf ("     advance_loc4 %" PRIu64 " to %#" PRIx64 "\n",
6463                     op1, pc += op1 * code_align);
6464             break;
6465           case DW_CFA_offset_extended:
6466             if ((uint64_t) (endp - readp) < 1)
6467               goto invalid;
6468             get_uleb128 (op1, readp, endp);
6469             if ((uint64_t) (endp - readp) < 1)
6470               goto invalid;
6471             get_uleb128 (op2, readp, endp);
6472             printf ("     offset_extended r%" PRIu64 " (%s) at cfa%+" PRId64
6473                     "\n",
6474                     op1, regname (ebl, op1, regnamebuf), op2 * data_align);
6475             break;
6476           case DW_CFA_restore_extended:
6477             if ((uint64_t) (endp - readp) < 1)
6478               goto invalid;
6479             get_uleb128 (op1, readp, endp);
6480             printf ("     restore_extended r%" PRIu64 " (%s)\n",
6481                     op1, regname (ebl, op1, regnamebuf));
6482             break;
6483           case DW_CFA_undefined:
6484             if ((uint64_t) (endp - readp) < 1)
6485               goto invalid;
6486             get_uleb128 (op1, readp, endp);
6487             printf ("     undefined r%" PRIu64 " (%s)\n", op1,
6488                     regname (ebl, op1, regnamebuf));
6489             break;
6490           case DW_CFA_same_value:
6491             if ((uint64_t) (endp - readp) < 1)
6492               goto invalid;
6493             get_uleb128 (op1, readp, endp);
6494             printf ("     same_value r%" PRIu64 " (%s)\n", op1,
6495                     regname (ebl, op1, regnamebuf));
6496             break;
6497           case DW_CFA_register:
6498             if ((uint64_t) (endp - readp) < 1)
6499               goto invalid;
6500             get_uleb128 (op1, readp, endp);
6501             if ((uint64_t) (endp - readp) < 1)
6502               goto invalid;
6503             get_uleb128 (op2, readp, endp);
6504             printf ("     register r%" PRIu64 " (%s) in r%" PRIu64 " (%s)\n",
6505                     op1, regname (ebl, op1, regnamebuf), op2,
6506                     regname (ebl, op2, regnamebuf));
6507             break;
6508           case DW_CFA_remember_state:
6509             puts ("     remember_state");
6510             break;
6511           case DW_CFA_restore_state:
6512             puts ("     restore_state");
6513             break;
6514           case DW_CFA_def_cfa:
6515             if ((uint64_t) (endp - readp) < 1)
6516               goto invalid;
6517             get_uleb128 (op1, readp, endp);
6518             if ((uint64_t) (endp - readp) < 1)
6519               goto invalid;
6520             get_uleb128 (op2, readp, endp);
6521             printf ("     def_cfa r%" PRIu64 " (%s) at offset %" PRIu64 "\n",
6522                     op1, regname (ebl, op1, regnamebuf), op2);
6523             break;
6524           case DW_CFA_def_cfa_register:
6525             if ((uint64_t) (endp - readp) < 1)
6526               goto invalid;
6527             get_uleb128 (op1, readp, endp);
6528             printf ("     def_cfa_register r%" PRIu64 " (%s)\n",
6529                     op1, regname (ebl, op1, regnamebuf));
6530             break;
6531           case DW_CFA_def_cfa_offset:
6532             if ((uint64_t) (endp - readp) < 1)
6533               goto invalid;
6534             get_uleb128 (op1, readp, endp);
6535             printf ("     def_cfa_offset %" PRIu64 "\n", op1);
6536             break;
6537           case DW_CFA_def_cfa_expression:
6538             if ((uint64_t) (endp - readp) < 1)
6539               goto invalid;
6540             get_uleb128 (op1, readp, endp);     /* Length of DW_FORM_block.  */
6541             printf ("     def_cfa_expression %" PRIu64 "\n", op1);
6542             if ((uint64_t) (endp - readp) < op1)
6543               {
6544             invalid:
6545                 fputs (_("         <INVALID DATA>\n"), stdout);
6546                 return;
6547               }
6548             print_ops (dwflmod, dbg, 10, 10, version, ptr_size, 0, NULL,
6549                        op1, readp);
6550             readp += op1;
6551             break;
6552           case DW_CFA_expression:
6553             if ((uint64_t) (endp - readp) < 1)
6554               goto invalid;
6555             get_uleb128 (op1, readp, endp);
6556             if ((uint64_t) (endp - readp) < 1)
6557               goto invalid;
6558             get_uleb128 (op2, readp, endp);     /* Length of DW_FORM_block.  */
6559             printf ("     expression r%" PRIu64 " (%s) \n",
6560                     op1, regname (ebl, op1, regnamebuf));
6561             if ((uint64_t) (endp - readp) < op2)
6562               goto invalid;
6563             print_ops (dwflmod, dbg, 10, 10, version, ptr_size, 0, NULL,
6564                        op2, readp);
6565             readp += op2;
6566             break;
6567           case DW_CFA_offset_extended_sf:
6568             if ((uint64_t) (endp - readp) < 1)
6569               goto invalid;
6570             get_uleb128 (op1, readp, endp);
6571             if ((uint64_t) (endp - readp) < 1)
6572               goto invalid;
6573             get_sleb128 (sop2, readp, endp);
6574             printf ("     offset_extended_sf r%" PRIu64 " (%s) at cfa%+"
6575                     PRId64 "\n",
6576                     op1, regname (ebl, op1, regnamebuf), sop2 * data_align);
6577             break;
6578           case DW_CFA_def_cfa_sf:
6579             if ((uint64_t) (endp - readp) < 1)
6580               goto invalid;
6581             get_uleb128 (op1, readp, endp);
6582             if ((uint64_t) (endp - readp) < 1)
6583               goto invalid;
6584             get_sleb128 (sop2, readp, endp);
6585             printf ("     def_cfa_sf r%" PRIu64 " (%s) at offset %" PRId64 "\n",
6586                     op1, regname (ebl, op1, regnamebuf), sop2 * data_align);
6587             break;
6588           case DW_CFA_def_cfa_offset_sf:
6589             if ((uint64_t) (endp - readp) < 1)
6590               goto invalid;
6591             get_sleb128 (sop1, readp, endp);
6592             printf ("     def_cfa_offset_sf %" PRId64 "\n", sop1 * data_align);
6593             break;
6594           case DW_CFA_val_offset:
6595             if ((uint64_t) (endp - readp) < 1)
6596               goto invalid;
6597             get_uleb128 (op1, readp, endp);
6598             if ((uint64_t) (endp - readp) < 1)
6599               goto invalid;
6600             get_uleb128 (op2, readp, endp);
6601             printf ("     val_offset %" PRIu64 " at offset %" PRIu64 "\n",
6602                     op1, op2 * data_align);
6603             break;
6604           case DW_CFA_val_offset_sf:
6605             if ((uint64_t) (endp - readp) < 1)
6606               goto invalid;
6607             get_uleb128 (op1, readp, endp);
6608             if ((uint64_t) (endp - readp) < 1)
6609               goto invalid;
6610             get_sleb128 (sop2, readp, endp);
6611             printf ("     val_offset_sf %" PRIu64 " at offset %" PRId64 "\n",
6612                     op1, sop2 * data_align);
6613             break;
6614           case DW_CFA_val_expression:
6615             if ((uint64_t) (endp - readp) < 1)
6616               goto invalid;
6617             get_uleb128 (op1, readp, endp);
6618             if ((uint64_t) (endp - readp) < 1)
6619               goto invalid;
6620             get_uleb128 (op2, readp, endp);     /* Length of DW_FORM_block.  */
6621             printf ("     val_expression r%" PRIu64 " (%s)\n",
6622                     op1, regname (ebl, op1, regnamebuf));
6623             if ((uint64_t) (endp - readp) < op2)
6624               goto invalid;
6625             print_ops (dwflmod, dbg, 10, 10, version, ptr_size, 0,
6626                        NULL, op2, readp);
6627             readp += op2;
6628             break;
6629           case DW_CFA_MIPS_advance_loc8:
6630             if ((uint64_t) (endp - readp) < 8)
6631               goto invalid;
6632             op1 = read_8ubyte_unaligned_inc (dbg, readp);
6633             printf ("     MIPS_advance_loc8 %" PRIu64 " to %#" PRIx64 "\n",
6634                     op1, pc += op1 * code_align);
6635             break;
6636           case DW_CFA_GNU_window_save:  /* DW_CFA_AARCH64_negate_ra_state  */
6637             if (ehdr->e_machine == EM_AARCH64)
6638               puts ("     AARCH64_negate_ra_state");
6639             else
6640               puts ("     GNU_window_save");
6641             break;
6642           case DW_CFA_GNU_args_size:
6643             if ((uint64_t) (endp - readp) < 1)
6644               goto invalid;
6645             get_uleb128 (op1, readp, endp);
6646             printf ("     args_size %" PRIu64 "\n", op1);
6647             break;
6648           default:
6649             printf ("     ??? (%u)\n", opcode);
6650             break;
6651           }
6652       else if (opcode < DW_CFA_offset)
6653         printf ("     advance_loc %u to %#" PRIx64 "\n",
6654                 opcode & 0x3f, pc += (opcode & 0x3f) * code_align);
6655       else if (opcode < DW_CFA_restore)
6656         {
6657           uint64_t offset;
6658           if ((uint64_t) (endp - readp) < 1)
6659             goto invalid;
6660           get_uleb128 (offset, readp, endp);
6661           printf ("     offset r%u (%s) at cfa%+" PRId64 "\n",
6662                   opcode & 0x3f, regname (ebl, opcode & 0x3f, regnamebuf),
6663                   offset * data_align);
6664         }
6665       else
6666         printf ("     restore r%u (%s)\n",
6667                 opcode & 0x3f, regname (ebl, opcode & 0x3f, regnamebuf));
6668     }
6669 }
6670
6671
6672 static unsigned int
6673 encoded_ptr_size (int encoding, unsigned int ptr_size)
6674 {
6675   switch (encoding & 7)
6676     {
6677     case DW_EH_PE_udata4:
6678       return 4;
6679     case DW_EH_PE_udata8:
6680       return 8;
6681     case 0:
6682       return ptr_size;
6683     }
6684
6685   fprintf (stderr, "Unsupported pointer encoding: %#x, "
6686            "assuming pointer size of %d.\n", encoding, ptr_size);
6687   return ptr_size;
6688 }
6689
6690
6691 static unsigned int
6692 print_encoding (unsigned int val)
6693 {
6694   switch (val & 0xf)
6695     {
6696     case DW_EH_PE_absptr:
6697       fputs ("absptr", stdout);
6698       break;
6699     case DW_EH_PE_uleb128:
6700       fputs ("uleb128", stdout);
6701       break;
6702     case DW_EH_PE_udata2:
6703       fputs ("udata2", stdout);
6704       break;
6705     case DW_EH_PE_udata4:
6706       fputs ("udata4", stdout);
6707       break;
6708     case DW_EH_PE_udata8:
6709       fputs ("udata8", stdout);
6710       break;
6711     case DW_EH_PE_sleb128:
6712       fputs ("sleb128", stdout);
6713       break;
6714     case DW_EH_PE_sdata2:
6715       fputs ("sdata2", stdout);
6716       break;
6717     case DW_EH_PE_sdata4:
6718       fputs ("sdata4", stdout);
6719       break;
6720     case DW_EH_PE_sdata8:
6721       fputs ("sdata8", stdout);
6722       break;
6723     default:
6724       /* We did not use any of the bits after all.  */
6725       return val;
6726     }
6727
6728   return val & ~0xf;
6729 }
6730
6731
6732 static unsigned int
6733 print_relinfo (unsigned int val)
6734 {
6735   switch (val & 0x70)
6736     {
6737     case DW_EH_PE_pcrel:
6738       fputs ("pcrel", stdout);
6739       break;
6740     case DW_EH_PE_textrel:
6741       fputs ("textrel", stdout);
6742       break;
6743     case DW_EH_PE_datarel:
6744       fputs ("datarel", stdout);
6745       break;
6746     case DW_EH_PE_funcrel:
6747       fputs ("funcrel", stdout);
6748       break;
6749     case DW_EH_PE_aligned:
6750       fputs ("aligned", stdout);
6751       break;
6752     default:
6753       return val;
6754     }
6755
6756   return val & ~0x70;
6757 }
6758
6759
6760 static void
6761 print_encoding_base (const char *pfx, unsigned int fde_encoding)
6762 {
6763   printf ("(%s", pfx);
6764
6765   if (fde_encoding == DW_EH_PE_omit)
6766     puts ("omit)");
6767   else
6768     {
6769       unsigned int w = fde_encoding;
6770
6771       w = print_encoding (w);
6772
6773       if (w & 0x70)
6774         {
6775           if (w != fde_encoding)
6776             fputc_unlocked (' ', stdout);
6777
6778           w = print_relinfo (w);
6779         }
6780
6781       if (w != 0)
6782         printf ("%s%x", w != fde_encoding ? " " : "", w);
6783
6784       puts (")");
6785     }
6786 }
6787
6788
6789 static void
6790 print_debug_frame_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
6791                            Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
6792 {
6793   size_t shstrndx;
6794   /* We know this call will succeed since it did in the caller.  */
6795   (void) elf_getshdrstrndx (ebl->elf, &shstrndx);
6796   const char *scnname = elf_strptr (ebl->elf, shstrndx, shdr->sh_name);
6797
6798   /* Needed if we find PC-relative addresses.  */
6799   GElf_Addr bias;
6800   if (dwfl_module_getelf (dwflmod, &bias) == NULL)
6801     {
6802       error (0, 0, _("cannot get ELF: %s"), dwfl_errmsg (-1));
6803       return;
6804     }
6805
6806   bool is_eh_frame = strcmp (scnname, ".eh_frame") == 0;
6807   Elf_Data *data = (is_eh_frame
6808                     ? elf_rawdata (scn, NULL)
6809                     : (dbg->sectiondata[IDX_debug_frame]
6810                        ?: elf_rawdata (scn, NULL)));
6811
6812   if (unlikely (data == NULL))
6813     {
6814       error (0, 0, _("cannot get %s content: %s"),
6815              scnname, elf_errmsg (-1));
6816       return;
6817     }
6818
6819   if (is_eh_frame)
6820     printf (_("\
6821 \nCall frame information section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
6822             elf_ndxscn (scn), scnname, (uint64_t) shdr->sh_offset);
6823   else
6824     printf (_("\
6825 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
6826             elf_ndxscn (scn), scnname, (uint64_t) shdr->sh_offset);
6827
6828   struct cieinfo
6829   {
6830     ptrdiff_t cie_offset;
6831     const char *augmentation;
6832     unsigned int code_alignment_factor;
6833     unsigned int data_alignment_factor;
6834     uint8_t address_size;
6835     uint8_t fde_encoding;
6836     uint8_t lsda_encoding;
6837     struct cieinfo *next;
6838   } *cies = NULL;
6839
6840   const unsigned char *readp = data->d_buf;
6841   const unsigned char *const dataend = ((unsigned char *) data->d_buf
6842                                         + data->d_size);
6843   while (readp < dataend)
6844     {
6845       if (unlikely (readp + 4 > dataend))
6846         {
6847         invalid_data:
6848           error (0, 0, _("invalid data in section [%zu] '%s'"),
6849                      elf_ndxscn (scn), scnname);
6850               return;
6851         }
6852
6853       /* At the beginning there must be a CIE.  There can be multiple,
6854          hence we test tis in a loop.  */
6855       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
6856
6857       Dwarf_Word unit_length = read_4ubyte_unaligned_inc (dbg, readp);
6858       unsigned int length = 4;
6859       if (unlikely (unit_length == 0xffffffff))
6860         {
6861           if (unlikely (readp + 8 > dataend))
6862             goto invalid_data;
6863
6864           unit_length = read_8ubyte_unaligned_inc (dbg, readp);
6865           length = 8;
6866         }
6867
6868       if (unlikely (unit_length == 0))
6869         {
6870           printf (_("\n [%6tx] Zero terminator\n"), offset);
6871           continue;
6872         }
6873
6874       Dwarf_Word maxsize = dataend - readp;
6875       if (unlikely (unit_length > maxsize))
6876         goto invalid_data;
6877
6878       unsigned int ptr_size = ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
6879
6880       ptrdiff_t start = readp - (unsigned char *) data->d_buf;
6881       const unsigned char *const cieend = readp + unit_length;
6882       if (unlikely (cieend > dataend))
6883         goto invalid_data;
6884
6885       Dwarf_Off cie_id;
6886       if (length == 4)
6887         {
6888           if (unlikely (cieend - readp < 4))
6889             goto invalid_data;
6890           cie_id = read_4ubyte_unaligned_inc (dbg, readp);
6891           if (!is_eh_frame && cie_id == DW_CIE_ID_32)
6892             cie_id = DW_CIE_ID_64;
6893         }
6894       else
6895         {
6896           if (unlikely (cieend - readp < 8))
6897             goto invalid_data;
6898           cie_id = read_8ubyte_unaligned_inc (dbg, readp);
6899         }
6900
6901       uint_fast8_t version = 2;
6902       unsigned int code_alignment_factor;
6903       int data_alignment_factor;
6904       unsigned int fde_encoding = 0;
6905       unsigned int lsda_encoding = 0;
6906       Dwarf_Word initial_location = 0;
6907       Dwarf_Word vma_base = 0;
6908
6909       if (cie_id == (is_eh_frame ? 0 : DW_CIE_ID_64))
6910         {
6911           if (unlikely (cieend - readp < 2))
6912             goto invalid_data;
6913           version = *readp++;
6914           const char *const augmentation = (const char *) readp;
6915           readp = memchr (readp, '\0', cieend - readp);
6916           if (unlikely (readp == NULL))
6917             goto invalid_data;
6918           ++readp;
6919
6920           uint_fast8_t segment_size = 0;
6921           if (version >= 4)
6922             {
6923               if (cieend - readp < 5)
6924                 goto invalid_data;
6925               ptr_size = *readp++;
6926               segment_size = *readp++;
6927             }
6928
6929           if (cieend - readp < 1)
6930             goto invalid_data;
6931           get_uleb128 (code_alignment_factor, readp, cieend);
6932           if (cieend - readp < 1)
6933             goto invalid_data;
6934           get_sleb128 (data_alignment_factor, readp, cieend);
6935
6936           /* In some variant for unwind data there is another field.  */
6937           if (strcmp (augmentation, "eh") == 0)
6938             readp += ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
6939
6940           unsigned int return_address_register;
6941           if (cieend - readp < 1)
6942             goto invalid_data;
6943           if (unlikely (version == 1))
6944             return_address_register = *readp++;
6945           else
6946             get_uleb128 (return_address_register, readp, cieend);
6947
6948           printf ("\n [%6tx] CIE length=%" PRIu64 "\n"
6949                   "   CIE_id:                   %" PRIu64 "\n"
6950                   "   version:                  %u\n"
6951                   "   augmentation:             \"%s\"\n",
6952                   offset, (uint64_t) unit_length, (uint64_t) cie_id,
6953                   version, augmentation);
6954           if (version >= 4)
6955             printf ("   address_size:             %u\n"
6956                     "   segment_size:             %u\n",
6957                     ptr_size, segment_size);
6958           printf ("   code_alignment_factor:    %u\n"
6959                   "   data_alignment_factor:    %d\n"
6960                   "   return_address_register:  %u\n",
6961                   code_alignment_factor,
6962                   data_alignment_factor, return_address_register);
6963
6964           if (augmentation[0] == 'z')
6965             {
6966               unsigned int augmentationlen;
6967               get_uleb128 (augmentationlen, readp, cieend);
6968
6969               if (augmentationlen > (size_t) (cieend - readp))
6970                 {
6971                   error (0, 0, _("invalid augmentation length"));
6972                   readp = cieend;
6973                   continue;
6974                 }
6975
6976               const char *hdr = "Augmentation data:";
6977               const char *cp = augmentation + 1;
6978               while (*cp != '\0' && cp < augmentation + augmentationlen + 1)
6979                 {
6980                   printf ("   %-26s%#x ", hdr, *readp);
6981                   hdr = "";
6982
6983                   if (*cp == 'R')
6984                     {
6985                       fde_encoding = *readp++;
6986                       print_encoding_base (_("FDE address encoding: "),
6987                                            fde_encoding);
6988                     }
6989                   else if (*cp == 'L')
6990                     {
6991                       lsda_encoding = *readp++;
6992                       print_encoding_base (_("LSDA pointer encoding: "),
6993                                            lsda_encoding);
6994                     }
6995                   else if (*cp == 'P')
6996                     {
6997                       /* Personality.  This field usually has a relocation
6998                          attached pointing to __gcc_personality_v0.  */
6999                       const unsigned char *startp = readp;
7000                       unsigned int encoding = *readp++;
7001                       uint64_t val = 0;
7002                       readp = read_encoded (encoding, readp,
7003                                             readp - 1 + augmentationlen,
7004                                             &val, dbg);
7005
7006                       while (++startp < readp)
7007                         printf ("%#x ", *startp);
7008
7009                       putchar ('(');
7010                       print_encoding (encoding);
7011                       putchar (' ');
7012                       switch (encoding & 0xf)
7013                         {
7014                         case DW_EH_PE_sleb128:
7015                         case DW_EH_PE_sdata2:
7016                         case DW_EH_PE_sdata4:
7017                           printf ("%" PRId64 ")\n", val);
7018                           break;
7019                         default:
7020                           printf ("%#" PRIx64 ")\n", val);
7021                           break;
7022                         }
7023                     }
7024                   else
7025                     printf ("(%x)\n", *readp++);
7026
7027                   ++cp;
7028                 }
7029             }
7030
7031           if (likely (ptr_size == 4 || ptr_size == 8))
7032             {
7033               struct cieinfo *newp = alloca (sizeof (*newp));
7034               newp->cie_offset = offset;
7035               newp->augmentation = augmentation;
7036               newp->fde_encoding = fde_encoding;
7037               newp->lsda_encoding = lsda_encoding;
7038               newp->address_size = ptr_size;
7039               newp->code_alignment_factor = code_alignment_factor;
7040               newp->data_alignment_factor = data_alignment_factor;
7041               newp->next = cies;
7042               cies = newp;
7043             }
7044         }
7045       else
7046         {
7047           struct cieinfo *cie = cies;
7048           while (cie != NULL)
7049             if (is_eh_frame
7050                 ? ((Dwarf_Off) start - cie_id) == (Dwarf_Off) cie->cie_offset
7051                 : cie_id == (Dwarf_Off) cie->cie_offset)
7052               break;
7053             else
7054               cie = cie->next;
7055           if (unlikely (cie == NULL))
7056             {
7057               puts ("invalid CIE reference in FDE");
7058               return;
7059             }
7060
7061           /* Initialize from CIE data.  */
7062           fde_encoding = cie->fde_encoding;
7063           lsda_encoding = cie->lsda_encoding;
7064           ptr_size = encoded_ptr_size (fde_encoding, cie->address_size);
7065           code_alignment_factor = cie->code_alignment_factor;
7066           data_alignment_factor = cie->data_alignment_factor;
7067
7068           const unsigned char *base = readp;
7069           // XXX There are sometimes relocations for this value
7070           initial_location = read_addr_unaligned_inc (ptr_size, dbg, readp);
7071           Dwarf_Word address_range
7072             = read_addr_unaligned_inc (ptr_size, dbg, readp);
7073
7074           /* pcrel for an FDE address is relative to the runtime
7075              address of the start_address field itself.  Sign extend
7076              if necessary to make sure the calculation is done on the
7077              full 64 bit address even when initial_location only holds
7078              the lower 32 bits.  */
7079           Dwarf_Addr pc_start = initial_location;
7080           if (ptr_size == 4)
7081             pc_start = (uint64_t) (int32_t) pc_start;
7082           if ((fde_encoding & 0x70) == DW_EH_PE_pcrel)
7083             pc_start += ((uint64_t) shdr->sh_addr
7084                          + (base - (const unsigned char *) data->d_buf)
7085                          - bias);
7086
7087           printf ("\n [%6tx] FDE length=%" PRIu64 " cie=[%6tx]\n"
7088                   "   CIE_pointer:              %" PRIu64 "\n"
7089                   "   initial_location:         ",
7090                   offset, (uint64_t) unit_length,
7091                   cie->cie_offset, (uint64_t) cie_id);
7092           print_dwarf_addr (dwflmod, cie->address_size,
7093                             pc_start, initial_location);
7094           if ((fde_encoding & 0x70) == DW_EH_PE_pcrel)
7095             {
7096               vma_base = (((uint64_t) shdr->sh_offset
7097                            + (base - (const unsigned char *) data->d_buf)
7098                            + (uint64_t) initial_location)
7099                           & (ptr_size == 4
7100                              ? UINT64_C (0xffffffff)
7101                              : UINT64_C (0xffffffffffffffff)));
7102               printf (_(" (offset: %#" PRIx64 ")"),
7103                       (uint64_t) vma_base);
7104             }
7105
7106           printf ("\n   address_range:            %#" PRIx64,
7107                   (uint64_t) address_range);
7108           if ((fde_encoding & 0x70) == DW_EH_PE_pcrel)
7109             printf (_(" (end offset: %#" PRIx64 ")"),
7110                     ((uint64_t) vma_base + (uint64_t) address_range)
7111                     & (ptr_size == 4
7112                        ? UINT64_C (0xffffffff)
7113                        : UINT64_C (0xffffffffffffffff)));
7114           putchar ('\n');
7115
7116           if (cie->augmentation[0] == 'z')
7117             {
7118               unsigned int augmentationlen;
7119               if (cieend - readp < 1)
7120                 goto invalid_data;
7121               get_uleb128 (augmentationlen, readp, cieend);
7122
7123               if (augmentationlen > (size_t) (cieend - readp))
7124                 {
7125                   error (0, 0, _("invalid augmentation length"));
7126                   readp = cieend;
7127                   continue;
7128                 }
7129
7130               if (augmentationlen > 0)
7131                 {
7132                   const char *hdr = "Augmentation data:";
7133                   const char *cp = cie->augmentation + 1;
7134                   unsigned int u = 0;
7135                   while (*cp != '\0'
7136                          && cp < cie->augmentation + augmentationlen + 1)
7137                     {
7138                       if (*cp == 'L')
7139                         {
7140                           uint64_t lsda_pointer;
7141                           const unsigned char *p
7142                             = read_encoded (lsda_encoding, &readp[u],
7143                                             &readp[augmentationlen],
7144                                             &lsda_pointer, dbg);
7145                           u = p - readp;
7146                           printf (_("\
7147    %-26sLSDA pointer: %#" PRIx64 "\n"),
7148                                   hdr, lsda_pointer);
7149                           hdr = "";
7150                         }
7151                       ++cp;
7152                     }
7153
7154                   while (u < augmentationlen)
7155                     {
7156                       printf ("   %-26s%#x\n", hdr, readp[u++]);
7157                       hdr = "";
7158                     }
7159                 }
7160
7161               readp += augmentationlen;
7162             }
7163         }
7164
7165       /* Handle the initialization instructions.  */
7166       if (ptr_size != 4 && ptr_size !=8)
7167         printf ("invalid CIE pointer size (%u), must be 4 or 8.\n", ptr_size);
7168       else
7169         print_cfa_program (readp, cieend, vma_base, code_alignment_factor,
7170                            data_alignment_factor, version, ptr_size,
7171                            fde_encoding, dwflmod, ebl, ehdr, dbg);
7172       readp = cieend;
7173     }
7174 }
7175
7176
7177 /* Returns the signedness (or false if it cannot be determined) and
7178    the byte size (or zero if it cannot be gotten) of the given DIE
7179    DW_AT_type attribute.  Uses dwarf_peel_type and dwarf_aggregate_size.  */
7180 static void
7181 die_type_sign_bytes (Dwarf_Die *die, bool *is_signed, int *bytes)
7182 {
7183   Dwarf_Attribute attr;
7184   Dwarf_Die type;
7185
7186   *bytes = 0;
7187   *is_signed = false;
7188
7189   if (dwarf_peel_type (dwarf_formref_die (dwarf_attr_integrate (die,
7190                                                                 DW_AT_type,
7191                                                                 &attr), &type),
7192                        &type) == 0)
7193     {
7194       Dwarf_Word val;
7195       *is_signed = (dwarf_formudata (dwarf_attr (&type, DW_AT_encoding,
7196                                                  &attr), &val) == 0
7197                     && (val == DW_ATE_signed || val == DW_ATE_signed_char));
7198
7199       if (dwarf_aggregate_size (&type, &val) == 0)
7200         *bytes = val;
7201     }
7202 }
7203
7204 struct attrcb_args
7205 {
7206   Dwfl_Module *dwflmod;
7207   Dwarf *dbg;
7208   Dwarf_Die *dies;
7209   int level;
7210   bool silent;
7211   bool is_split;
7212   unsigned int version;
7213   unsigned int addrsize;
7214   unsigned int offset_size;
7215   struct Dwarf_CU *cu;
7216 };
7217
7218
7219 static int
7220 attr_callback (Dwarf_Attribute *attrp, void *arg)
7221 {
7222   struct attrcb_args *cbargs = (struct attrcb_args *) arg;
7223   const int level = cbargs->level;
7224   Dwarf_Die *die = &cbargs->dies[level];
7225   bool is_split = cbargs->is_split;
7226
7227   unsigned int attr = dwarf_whatattr (attrp);
7228   if (unlikely (attr == 0))
7229     {
7230       if (!cbargs->silent)
7231         error (0, 0, _("DIE [%" PRIx64 "] "
7232                               "cannot get attribute code: %s"),
7233                dwarf_dieoffset (die), dwarf_errmsg (-1));
7234       return DWARF_CB_ABORT;
7235     }
7236
7237   unsigned int form = dwarf_whatform (attrp);
7238   if (unlikely (form == 0))
7239     {
7240       if (!cbargs->silent)
7241         error (0, 0, _("DIE [%" PRIx64 "] "
7242                               "cannot get attribute form: %s"),
7243                dwarf_dieoffset (die), dwarf_errmsg (-1));
7244       return DWARF_CB_ABORT;
7245     }
7246
7247   switch (form)
7248     {
7249     case DW_FORM_addr:
7250     case DW_FORM_addrx:
7251     case DW_FORM_addrx1:
7252     case DW_FORM_addrx2:
7253     case DW_FORM_addrx3:
7254     case DW_FORM_addrx4:
7255     case DW_FORM_GNU_addr_index:
7256       if (!cbargs->silent)
7257         {
7258           Dwarf_Addr addr;
7259           if (unlikely (dwarf_formaddr (attrp, &addr) != 0))
7260             {
7261             attrval_out:
7262               if (!cbargs->silent)
7263                 error (0, 0, _("DIE [%" PRIx64 "] "
7264                                       "cannot get attribute '%s' (%s) value: "
7265                                       "%s"),
7266                        dwarf_dieoffset (die),
7267                        dwarf_attr_name (attr),
7268                        dwarf_form_name (form),
7269                        dwarf_errmsg (-1));
7270               /* Don't ABORT, it might be other attributes can be resolved.  */
7271               return DWARF_CB_OK;
7272             }
7273           if (form != DW_FORM_addr )
7274             {
7275               Dwarf_Word word;
7276               if (dwarf_formudata (attrp, &word) != 0)
7277                 goto attrval_out;
7278               printf ("           %*s%-20s (%s) [%" PRIx64 "] ",
7279                       (int) (level * 2), "", dwarf_attr_name (attr),
7280                       dwarf_form_name (form), word);
7281             }
7282           else
7283             printf ("           %*s%-20s (%s) ",
7284                     (int) (level * 2), "", dwarf_attr_name (attr),
7285                     dwarf_form_name (form));
7286           print_dwarf_addr (cbargs->dwflmod, cbargs->addrsize, addr, addr);
7287           printf ("\n");
7288         }
7289       break;
7290
7291     case DW_FORM_indirect:
7292     case DW_FORM_strp:
7293     case DW_FORM_line_strp:
7294     case DW_FORM_strx:
7295     case DW_FORM_strx1:
7296     case DW_FORM_strx2:
7297     case DW_FORM_strx3:
7298     case DW_FORM_strx4:
7299     case DW_FORM_string:
7300     case DW_FORM_GNU_strp_alt:
7301     case DW_FORM_GNU_str_index:
7302       if (cbargs->silent)
7303         break;
7304       const char *str = dwarf_formstring (attrp);
7305       if (unlikely (str == NULL))
7306         goto attrval_out;
7307       printf ("           %*s%-20s (%s) \"%s\"\n",
7308               (int) (level * 2), "", dwarf_attr_name (attr),
7309               dwarf_form_name (form), str);
7310       break;
7311
7312     case DW_FORM_ref_addr:
7313     case DW_FORM_ref_udata:
7314     case DW_FORM_ref8:
7315     case DW_FORM_ref4:
7316     case DW_FORM_ref2:
7317     case DW_FORM_ref1:
7318     case DW_FORM_GNU_ref_alt:
7319     case DW_FORM_ref_sup4:
7320     case DW_FORM_ref_sup8:
7321       if (cbargs->silent)
7322         break;
7323       Dwarf_Die ref;
7324       if (unlikely (dwarf_formref_die (attrp, &ref) == NULL))
7325         goto attrval_out;
7326
7327       printf ("           %*s%-20s (%s) ",
7328               (int) (level * 2), "", dwarf_attr_name (attr),
7329               dwarf_form_name (form));
7330       if (is_split)
7331         printf ("{%6" PRIxMAX "}\n", (uintmax_t) dwarf_dieoffset (&ref));
7332       else
7333         printf ("[%6" PRIxMAX "]\n", (uintmax_t) dwarf_dieoffset (&ref));
7334       break;
7335
7336     case DW_FORM_ref_sig8:
7337       if (cbargs->silent)
7338         break;
7339       printf ("           %*s%-20s (%s) {%6" PRIx64 "}\n",
7340               (int) (level * 2), "", dwarf_attr_name (attr),
7341               dwarf_form_name (form),
7342               (uint64_t) read_8ubyte_unaligned (attrp->cu->dbg, attrp->valp));
7343       break;
7344
7345     case DW_FORM_sec_offset:
7346     case DW_FORM_rnglistx:
7347     case DW_FORM_loclistx:
7348     case DW_FORM_implicit_const:
7349     case DW_FORM_udata:
7350     case DW_FORM_sdata:
7351     case DW_FORM_data8: /* Note no data16 here, we see that as block. */
7352     case DW_FORM_data4:
7353     case DW_FORM_data2:
7354     case DW_FORM_data1:;
7355       Dwarf_Word num;
7356       if (unlikely (dwarf_formudata (attrp, &num) != 0))
7357         goto attrval_out;
7358
7359       const char *valuestr = NULL;
7360       bool as_hex_id = false;
7361       switch (attr)
7362         {
7363           /* This case can take either a constant or a loclistptr.  */
7364         case DW_AT_data_member_location:
7365           if (form != DW_FORM_sec_offset
7366               && (cbargs->version >= 4
7367                   || (form != DW_FORM_data4 && form != DW_FORM_data8)))
7368             {
7369               if (!cbargs->silent)
7370                 printf ("           %*s%-20s (%s) %" PRIuMAX "\n",
7371                         (int) (level * 2), "", dwarf_attr_name (attr),
7372                         dwarf_form_name (form), (uintmax_t) num);
7373               return DWARF_CB_OK;
7374             }
7375           FALLTHROUGH;
7376
7377         /* These cases always take a loclist[ptr] and no constant. */
7378         case DW_AT_location:
7379         case DW_AT_data_location:
7380         case DW_AT_vtable_elem_location:
7381         case DW_AT_string_length:
7382         case DW_AT_use_location:
7383         case DW_AT_frame_base:
7384         case DW_AT_return_addr:
7385         case DW_AT_static_link:
7386         case DW_AT_segment:
7387         case DW_AT_GNU_call_site_value:
7388         case DW_AT_GNU_call_site_data_value:
7389         case DW_AT_GNU_call_site_target:
7390         case DW_AT_GNU_call_site_target_clobbered:
7391         case DW_AT_GNU_locviews:
7392           {
7393             bool nlpt;
7394             if (cbargs->cu->version < 5)
7395               {
7396                 if (! cbargs->is_split)
7397                   {
7398                     nlpt = notice_listptr (section_loc, &known_locsptr,
7399                                            cbargs->addrsize,
7400                                            cbargs->offset_size,
7401                                            cbargs->cu, num, attr);
7402                   }
7403                 else
7404                   nlpt = true;
7405               }
7406             else
7407               {
7408                 /* Only register for a real section offset.  Otherwise
7409                    it is a DW_FORM_loclistx which is just an index
7410                    number and we should already have registered the
7411                    section offset for the index when we saw the
7412                    DW_AT_loclists_base CU attribute.  */
7413                 if (form == DW_FORM_sec_offset)
7414                   nlpt = notice_listptr (section_loc, &known_loclistsptr,
7415                                          cbargs->addrsize, cbargs->offset_size,
7416                                          cbargs->cu, num, attr);
7417                 else
7418                   nlpt = true;
7419
7420               }
7421
7422             if (!cbargs->silent)
7423               {
7424                 if (cbargs->cu->version < 5 || form == DW_FORM_sec_offset)
7425                   printf ("           %*s%-20s (%s) location list [%6"
7426                           PRIxMAX "]%s\n",
7427                           (int) (level * 2), "", dwarf_attr_name (attr),
7428                           dwarf_form_name (form), (uintmax_t) num,
7429                           nlpt ? "" : " <WARNING offset too big>");
7430                 else
7431                   printf ("           %*s%-20s (%s) location index [%6"
7432                           PRIxMAX "]\n",
7433                           (int) (level * 2), "", dwarf_attr_name (attr),
7434                           dwarf_form_name (form), (uintmax_t) num);
7435               }
7436           }
7437           return DWARF_CB_OK;
7438
7439         case DW_AT_loclists_base:
7440           {
7441             bool nlpt = notice_listptr (section_loc, &known_loclistsptr,
7442                                         cbargs->addrsize, cbargs->offset_size,
7443                                         cbargs->cu, num, attr);
7444
7445             if (!cbargs->silent)
7446               printf ("           %*s%-20s (%s) location list [%6" PRIxMAX "]%s\n",
7447                       (int) (level * 2), "", dwarf_attr_name (attr),
7448                       dwarf_form_name (form), (uintmax_t) num,
7449                       nlpt ? "" : " <WARNING offset too big>");
7450           }
7451           return DWARF_CB_OK;
7452
7453         case DW_AT_ranges:
7454         case DW_AT_start_scope:
7455           {
7456             bool nlpt;
7457             if (cbargs->cu->version < 5)
7458               nlpt = notice_listptr (section_ranges, &known_rangelistptr,
7459                                      cbargs->addrsize, cbargs->offset_size,
7460                                      cbargs->cu, num, attr);
7461             else
7462               {
7463                 /* Only register for a real section offset.  Otherwise
7464                    it is a DW_FORM_rangelistx which is just an index
7465                    number and we should already have registered the
7466                    section offset for the index when we saw the
7467                    DW_AT_rnglists_base CU attribute.  */
7468                 if (form == DW_FORM_sec_offset)
7469                   nlpt = notice_listptr (section_ranges, &known_rnglistptr,
7470                                          cbargs->addrsize, cbargs->offset_size,
7471                                          cbargs->cu, num, attr);
7472                 else
7473                   nlpt = true;
7474               }
7475
7476             if (!cbargs->silent)
7477               {
7478                 if (cbargs->cu->version < 5 || form == DW_FORM_sec_offset)
7479                   printf ("           %*s%-20s (%s) range list [%6"
7480                           PRIxMAX "]%s\n",
7481                           (int) (level * 2), "", dwarf_attr_name (attr),
7482                           dwarf_form_name (form), (uintmax_t) num,
7483                           nlpt ? "" : " <WARNING offset too big>");
7484                 else
7485                   printf ("           %*s%-20s (%s) range index [%6"
7486                           PRIxMAX "]\n",
7487                           (int) (level * 2), "", dwarf_attr_name (attr),
7488                           dwarf_form_name (form), (uintmax_t) num);
7489               }
7490           }
7491           return DWARF_CB_OK;
7492
7493         case DW_AT_rnglists_base:
7494           {
7495             bool nlpt = notice_listptr (section_ranges, &known_rnglistptr,
7496                                         cbargs->addrsize, cbargs->offset_size,
7497                                         cbargs->cu, num, attr);
7498             if (!cbargs->silent)
7499               printf ("           %*s%-20s (%s) range list [%6"
7500                       PRIxMAX "]%s\n",
7501                       (int) (level * 2), "", dwarf_attr_name (attr),
7502                       dwarf_form_name (form), (uintmax_t) num,
7503                       nlpt ? "" : " <WARNING offset too big>");
7504           }
7505           return DWARF_CB_OK;
7506
7507         case DW_AT_addr_base:
7508         case DW_AT_GNU_addr_base:
7509           {
7510             bool addrbase = notice_listptr (section_addr, &known_addrbases,
7511                                             cbargs->addrsize,
7512                                             cbargs->offset_size,
7513                                             cbargs->cu, num, attr);
7514             if (!cbargs->silent)
7515               printf ("           %*s%-20s (%s) address base [%6"
7516                       PRIxMAX "]%s\n",
7517                       (int) (level * 2), "", dwarf_attr_name (attr),
7518                       dwarf_form_name (form), (uintmax_t) num,
7519                       addrbase ? "" : " <WARNING offset too big>");
7520           }
7521           return DWARF_CB_OK;
7522
7523         case DW_AT_str_offsets_base:
7524           {
7525             bool stroffbase = notice_listptr (section_str, &known_stroffbases,
7526                                               cbargs->addrsize,
7527                                               cbargs->offset_size,
7528                                               cbargs->cu, num, attr);
7529             if (!cbargs->silent)
7530               printf ("           %*s%-20s (%s) str offsets base [%6"
7531                       PRIxMAX "]%s\n",
7532                       (int) (level * 2), "", dwarf_attr_name (attr),
7533                       dwarf_form_name (form), (uintmax_t) num,
7534                       stroffbase ? "" : " <WARNING offset too big>");
7535           }
7536           return DWARF_CB_OK;
7537
7538         case DW_AT_language:
7539           valuestr = dwarf_lang_name (num);
7540           break;
7541         case DW_AT_encoding:
7542           valuestr = dwarf_encoding_name (num);
7543           break;
7544         case DW_AT_accessibility:
7545           valuestr = dwarf_access_name (num);
7546           break;
7547         case DW_AT_defaulted:
7548           valuestr = dwarf_defaulted_name (num);
7549           break;
7550         case DW_AT_visibility:
7551           valuestr = dwarf_visibility_name (num);
7552           break;
7553         case DW_AT_virtuality:
7554           valuestr = dwarf_virtuality_name (num);
7555           break;
7556         case DW_AT_identifier_case:
7557           valuestr = dwarf_identifier_case_name (num);
7558           break;
7559         case DW_AT_calling_convention:
7560           valuestr = dwarf_calling_convention_name (num);
7561           break;
7562         case DW_AT_inline:
7563           valuestr = dwarf_inline_name (num);
7564           break;
7565         case DW_AT_ordering:
7566           valuestr = dwarf_ordering_name (num);
7567           break;
7568         case DW_AT_decl_file:
7569         case DW_AT_call_file:
7570           {
7571             if (cbargs->silent)
7572               break;
7573
7574             /* Try to get the actual file, the current interface only
7575                gives us full paths, but we only want to show the file
7576                name for now.  */
7577             Dwarf_Die cudie;
7578             if (dwarf_cu_die (cbargs->cu, &cudie,
7579                               NULL, NULL, NULL, NULL, NULL, NULL) != NULL)
7580               {
7581                 Dwarf_Files *files;
7582                 size_t nfiles;
7583                 if (dwarf_getsrcfiles (&cudie, &files, &nfiles) == 0)
7584                   {
7585                     valuestr = dwarf_filesrc (files, num, NULL, NULL);
7586                     if (valuestr != NULL)
7587                       {
7588                         char *filename = strrchr (valuestr, '/');
7589                         if (filename != NULL)
7590                           valuestr = filename + 1;
7591                       }
7592                     else
7593                       error (0, 0, _("invalid file (%" PRId64 "): %s"),
7594                              num, dwarf_errmsg (-1));
7595                   }
7596                 else
7597                   error (0, 0, _("no srcfiles for CU [%" PRIx64 "]"),
7598                          dwarf_dieoffset (&cudie));
7599               }
7600             else
7601              error (0, 0, _("couldn't get DWARF CU: %s"),
7602                     dwarf_errmsg (-1));
7603             if (valuestr == NULL)
7604               valuestr = "???";
7605           }
7606           break;
7607         case DW_AT_GNU_dwo_id:
7608           as_hex_id = true;
7609           break;
7610
7611         default:
7612           /* Nothing.  */
7613           break;
7614         }
7615
7616       if (cbargs->silent)
7617         break;
7618
7619       /* When highpc is in constant form it is relative to lowpc.
7620          In that case also show the address.  */
7621       Dwarf_Addr highpc;
7622       if (attr == DW_AT_high_pc && dwarf_highpc (die, &highpc) == 0)
7623         {
7624           printf ("           %*s%-20s (%s) %" PRIuMAX " (",
7625                   (int) (level * 2), "", dwarf_attr_name (attr),
7626                   dwarf_form_name (form), (uintmax_t) num);
7627           print_dwarf_addr (cbargs->dwflmod, cbargs->addrsize, highpc, highpc);
7628           printf (")\n");
7629         }
7630       else
7631         {
7632           if (as_hex_id)
7633             {
7634               printf ("           %*s%-20s (%s) 0x%.16" PRIx64 "\n",
7635                       (int) (level * 2), "", dwarf_attr_name (attr),
7636                       dwarf_form_name (form), num);
7637             }
7638           else
7639             {
7640               Dwarf_Sword snum = 0;
7641               bool is_signed;
7642               int bytes = 0;
7643               if (attr == DW_AT_const_value)
7644                 die_type_sign_bytes (die, &is_signed, &bytes);
7645               else
7646                 is_signed = (form == DW_FORM_sdata
7647                              || form == DW_FORM_implicit_const);
7648
7649               if (is_signed)
7650                 if (unlikely (dwarf_formsdata (attrp, &snum) != 0))
7651                   goto attrval_out;
7652
7653               if (valuestr == NULL)
7654                 {
7655                   printf ("           %*s%-20s (%s) ",
7656                           (int) (level * 2), "", dwarf_attr_name (attr),
7657                           dwarf_form_name (form));
7658                 }
7659               else
7660                 {
7661                   printf ("           %*s%-20s (%s) %s (",
7662                           (int) (level * 2), "", dwarf_attr_name (attr),
7663                           dwarf_form_name (form), valuestr);
7664                 }
7665
7666               switch (bytes)
7667                 {
7668                 case 1:
7669                   if (is_signed)
7670                     printf ("%" PRId8, (int8_t) snum);
7671                   else
7672                     printf ("%" PRIu8, (uint8_t) num);
7673                   break;
7674
7675                 case 2:
7676                   if (is_signed)
7677                     printf ("%" PRId16, (int16_t) snum);
7678                   else
7679                     printf ("%" PRIu16, (uint16_t) num);
7680                   break;
7681
7682                 case 4:
7683                   if (is_signed)
7684                     printf ("%" PRId32, (int32_t) snum);
7685                   else
7686                     printf ("%" PRIu32, (uint32_t) num);
7687                   break;
7688
7689                 case 8:
7690                   if (is_signed)
7691                     printf ("%" PRId64, (int64_t) snum);
7692                   else
7693                     printf ("%" PRIu64, (uint64_t) num);
7694                   break;
7695
7696                 default:
7697                   if (is_signed)
7698                     printf ("%" PRIdMAX, (intmax_t) snum);
7699                   else
7700                     printf ("%" PRIuMAX, (uintmax_t) num);
7701                   break;
7702                 }
7703
7704               /* Make clear if we switched from a signed encoding to
7705                  an unsigned value.  */
7706               if (attr == DW_AT_const_value
7707                   && (form == DW_FORM_sdata || form == DW_FORM_implicit_const)
7708                   && !is_signed)
7709                 printf (" (%" PRIdMAX ")", (intmax_t) num);
7710
7711               if (valuestr == NULL)
7712                 printf ("\n");
7713               else
7714                 printf (")\n");
7715             }
7716         }
7717       break;
7718
7719     case DW_FORM_flag:
7720       if (cbargs->silent)
7721         break;
7722       bool flag;
7723       if (unlikely (dwarf_formflag (attrp, &flag) != 0))
7724         goto attrval_out;
7725
7726       printf ("           %*s%-20s (%s) %s\n",
7727               (int) (level * 2), "", dwarf_attr_name (attr),
7728               dwarf_form_name (form), flag ? yes_str : no_str);
7729       break;
7730
7731     case DW_FORM_flag_present:
7732       if (cbargs->silent)
7733         break;
7734       printf ("           %*s%-20s (%s) %s\n",
7735               (int) (level * 2), "", dwarf_attr_name (attr),
7736               dwarf_form_name (form), yes_str);
7737       break;
7738
7739     case DW_FORM_exprloc:
7740     case DW_FORM_block4:
7741     case DW_FORM_block2:
7742     case DW_FORM_block1:
7743     case DW_FORM_block:
7744     case DW_FORM_data16: /* DWARF5 calls this a constant class.  */
7745       if (cbargs->silent)
7746         break;
7747       Dwarf_Block block;
7748       if (unlikely (dwarf_formblock (attrp, &block) != 0))
7749         goto attrval_out;
7750
7751       printf ("           %*s%-20s (%s) ",
7752               (int) (level * 2), "", dwarf_attr_name (attr),
7753               dwarf_form_name (form));
7754
7755       switch (attr)
7756         {
7757         default:
7758           if (form != DW_FORM_exprloc)
7759             {
7760               print_block (block.length, block.data);
7761               break;
7762             }
7763           FALLTHROUGH;
7764
7765         case DW_AT_location:
7766         case DW_AT_data_location:
7767         case DW_AT_data_member_location:
7768         case DW_AT_vtable_elem_location:
7769         case DW_AT_string_length:
7770         case DW_AT_use_location:
7771         case DW_AT_frame_base:
7772         case DW_AT_return_addr:
7773         case DW_AT_static_link:
7774         case DW_AT_allocated:
7775         case DW_AT_associated:
7776         case DW_AT_bit_size:
7777         case DW_AT_bit_offset:
7778         case DW_AT_bit_stride:
7779         case DW_AT_byte_size:
7780         case DW_AT_byte_stride:
7781         case DW_AT_count:
7782         case DW_AT_lower_bound:
7783         case DW_AT_upper_bound:
7784         case DW_AT_GNU_call_site_value:
7785         case DW_AT_GNU_call_site_data_value:
7786         case DW_AT_GNU_call_site_target:
7787         case DW_AT_GNU_call_site_target_clobbered:
7788           if (form == DW_FORM_exprloc
7789               || (form != DW_FORM_data16
7790                   && attrp->cu->version < 4)) /* blocks were expressions.  */
7791             {
7792               putchar ('\n');
7793               print_ops (cbargs->dwflmod, cbargs->dbg,
7794                          12 + level * 2, 12 + level * 2,
7795                          cbargs->version, cbargs->addrsize, cbargs->offset_size,
7796                          attrp->cu, block.length, block.data);
7797             }
7798           else
7799             print_block (block.length, block.data);
7800           break;
7801
7802         case DW_AT_discr_list:
7803           if (block.length == 0)
7804             puts ("<default>");
7805           else if (form != DW_FORM_data16)
7806             {
7807               const unsigned char *readp = block.data;
7808               const unsigned char *readendp = readp + block.length;
7809
7810               /* See if we are dealing with a signed or unsigned
7811                  values.  If the parent of this variant DIE is a
7812                  variant_part then it will either have a discriminant
7813                  which points to the member which type is the
7814                  discriminant type.  Or the variant_part itself has a
7815                  type representing the discriminant.  */
7816               bool is_signed = false;
7817               if (level > 0)
7818                 {
7819                   Dwarf_Die *parent = &cbargs->dies[level - 1];
7820                   if (dwarf_tag (die) == DW_TAG_variant
7821                       && dwarf_tag (parent) == DW_TAG_variant_part)
7822                     {
7823                       Dwarf_Die member;
7824                       Dwarf_Attribute discr_attr;
7825                       int bytes;
7826                       if (dwarf_formref_die (dwarf_attr (parent,
7827                                                          DW_AT_discr,
7828                                                          &discr_attr),
7829                                              &member) != NULL)
7830                         die_type_sign_bytes (&member, &is_signed, &bytes);
7831                       else
7832                         die_type_sign_bytes (parent, &is_signed, &bytes);
7833                     }
7834                 }
7835               while (readp < readendp)
7836                 {
7837                   int d = (int) *readp++;
7838                   printf ("%s ", dwarf_discr_list_name (d));
7839                   if (readp >= readendp)
7840                     goto attrval_out;
7841
7842                   Dwarf_Word val;
7843                   Dwarf_Sword sval;
7844                   if (d == DW_DSC_label)
7845                     {
7846                       if (is_signed)
7847                         {
7848                           get_sleb128 (sval, readp, readendp);
7849                           printf ("%" PRId64 "", sval);
7850                         }
7851                       else
7852                         {
7853                           get_uleb128 (val, readp, readendp);
7854                           printf ("%" PRIu64 "", val);
7855                         }
7856                     }
7857                   else if (d == DW_DSC_range)
7858                     {
7859                       if (is_signed)
7860                         {
7861                           get_sleb128 (sval, readp, readendp);
7862                           printf ("%" PRId64 "..", sval);
7863                           if (readp >= readendp)
7864                             goto attrval_out;
7865                           get_sleb128 (sval, readp, readendp);
7866                           printf ("%" PRId64 "", sval);
7867                         }
7868                       else
7869                         {
7870                           get_uleb128 (val, readp, readendp);
7871                           printf ("%" PRIu64 "..", val);
7872                           if (readp >= readendp)
7873                             goto attrval_out;
7874                           get_uleb128 (val, readp, readendp);
7875                           printf ("%" PRIu64 "", val);
7876                         }
7877                     }
7878                   else
7879                     {
7880                       print_block (readendp - readp, readp);
7881                       break;
7882                     }
7883                   if (readp < readendp)
7884                     printf (", ");
7885                 }
7886               putchar ('\n');
7887             }
7888           else
7889             print_block (block.length, block.data);
7890           break;
7891         }
7892       break;
7893
7894     default:
7895       if (cbargs->silent)
7896         break;
7897       printf ("           %*s%-20s (%s) ???\n",
7898               (int) (level * 2), "", dwarf_attr_name (attr),
7899               dwarf_form_name (form));
7900       break;
7901     }
7902
7903   return DWARF_CB_OK;
7904 }
7905
7906 static void
7907 print_debug_units (Dwfl_Module *dwflmod,
7908                    Ebl *ebl, GElf_Ehdr *ehdr __attribute__ ((unused)),
7909                    Elf_Scn *scn, GElf_Shdr *shdr,
7910                    Dwarf *dbg, bool debug_types)
7911 {
7912   const bool silent = !(print_debug_sections & section_info) && !debug_types;
7913   const char *secname = section_name (ebl, shdr);
7914
7915   if (!silent)
7916     printf (_("\
7917 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n [Offset]\n"),
7918             elf_ndxscn (scn), secname, (uint64_t) shdr->sh_offset);
7919
7920   /* If the section is empty we don't have to do anything.  */
7921   if (!silent && shdr->sh_size == 0)
7922     return;
7923
7924   int maxdies = 20;
7925   Dwarf_Die *dies = xmalloc (maxdies * sizeof (Dwarf_Die));
7926
7927   /* New compilation unit.  */
7928   Dwarf_Half version;
7929
7930   Dwarf_Die result;
7931   Dwarf_Off abbroffset;
7932   uint8_t addrsize;
7933   uint8_t offsize;
7934   uint64_t unit_id;
7935   Dwarf_Off subdie_off;
7936
7937   int unit_res;
7938   Dwarf_CU *cu;
7939   Dwarf_CU cu_mem;
7940   uint8_t unit_type;
7941   Dwarf_Die cudie;
7942
7943   /* We cheat a little because we want to see only the CUs from .debug_info
7944      or .debug_types.  We know the Dwarf_CU struct layout.  Set it up at
7945      the end of .debug_info if we want .debug_types only.  Check the returned
7946      Dwarf_CU is still in the expected section.  */
7947   if (debug_types)
7948     {
7949       cu_mem.dbg = dbg;
7950       cu_mem.end = dbg->sectiondata[IDX_debug_info]->d_size;
7951       cu_mem.sec_idx = IDX_debug_info;
7952       cu = &cu_mem;
7953     }
7954   else
7955     cu = NULL;
7956
7957  next_cu:
7958   unit_res = dwarf_get_units (dbg, cu, &cu, &version, &unit_type,
7959                               &cudie, NULL);
7960   if (unit_res == 1)
7961     goto do_return;
7962
7963   if (unit_res == -1)
7964     {
7965       if (!silent)
7966         error (0, 0, _("cannot get next unit: %s"), dwarf_errmsg (-1));
7967       goto do_return;
7968     }
7969
7970   if (cu->sec_idx != (size_t) (debug_types ? IDX_debug_types : IDX_debug_info))
7971     goto do_return;
7972
7973   dwarf_cu_die (cu, &result, NULL, &abbroffset, &addrsize, &offsize,
7974                 &unit_id, &subdie_off);
7975
7976   if (!silent)
7977     {
7978       Dwarf_Off offset = cu->start;
7979       if (debug_types && version < 5)
7980         {
7981           Dwarf_Die typedie;
7982           Dwarf_Off dieoffset;
7983           dieoffset = dwarf_dieoffset (dwarf_offdie_types (dbg, cu->start
7984                                                            + subdie_off,
7985                                                            &typedie));
7986           printf (_(" Type unit at offset %" PRIu64 ":\n"
7987                            " Version: %" PRIu16
7988                            ", Abbreviation section offset: %" PRIu64
7989                            ", Address size: %" PRIu8
7990                            ", Offset size: %" PRIu8
7991                            "\n Type signature: %#" PRIx64
7992                            ", Type offset: %#" PRIx64 " [%" PRIx64 "]\n"),
7993                   (uint64_t) offset, version, abbroffset, addrsize, offsize,
7994                   unit_id, (uint64_t) subdie_off, dieoffset);
7995         }
7996       else
7997         {
7998           printf (_(" Compilation unit at offset %" PRIu64 ":\n"
7999                            " Version: %" PRIu16
8000                            ", Abbreviation section offset: %" PRIu64
8001                            ", Address size: %" PRIu8
8002                            ", Offset size: %" PRIu8 "\n"),
8003                   (uint64_t) offset, version, abbroffset, addrsize, offsize);
8004
8005           if (version >= 5 || (unit_type != DW_UT_compile
8006                                && unit_type != DW_UT_partial))
8007             {
8008               printf (_(" Unit type: %s (%" PRIu8 ")"),
8009                                dwarf_unit_name (unit_type), unit_type);
8010               if (unit_type == DW_UT_type
8011                   || unit_type == DW_UT_skeleton
8012                   || unit_type == DW_UT_split_compile
8013                   || unit_type == DW_UT_split_type)
8014                 printf (", Unit id: 0x%.16" PRIx64 "", unit_id);
8015               if (unit_type == DW_UT_type
8016                   || unit_type == DW_UT_split_type)
8017                 {
8018                   Dwarf_Die typedie;
8019                   Dwarf_Off dieoffset;
8020                   dwarf_cu_info (cu, NULL, NULL, NULL, &typedie,
8021                                  NULL, NULL, NULL);
8022                   dieoffset = dwarf_dieoffset (&typedie);
8023                   printf (", Unit DIE off: %#" PRIx64 " [%" PRIx64 "]",
8024                           subdie_off, dieoffset);
8025                 }
8026               printf ("\n");
8027             }
8028         }
8029     }
8030
8031   if (version < 2 || version > 5
8032       || unit_type < DW_UT_compile || unit_type > DW_UT_split_type)
8033     {
8034       if (!silent)
8035         error (0, 0, _("unknown version (%d) or unit type (%d)"),
8036                version, unit_type);
8037       goto next_cu;
8038     }
8039
8040   struct attrcb_args args =
8041     {
8042       .dwflmod = dwflmod,
8043       .silent = silent,
8044       .version = version,
8045       .addrsize = addrsize,
8046       .offset_size = offsize
8047     };
8048
8049   bool is_split = false;
8050   int level = 0;
8051   dies[0] = cudie;
8052   args.cu = dies[0].cu;
8053   args.dbg = dbg;
8054   args.is_split = is_split;
8055
8056   /* We might return here again for the split CU subdie.  */
8057   do_cu:
8058   do
8059     {
8060       Dwarf_Off offset = dwarf_dieoffset (&dies[level]);
8061       if (unlikely (offset == (Dwarf_Off) -1))
8062         {
8063           if (!silent)
8064             error (0, 0, _("cannot get DIE offset: %s"),
8065                    dwarf_errmsg (-1));
8066           goto do_return;
8067         }
8068
8069       int tag = dwarf_tag (&dies[level]);
8070       if (unlikely (tag == DW_TAG_invalid))
8071         {
8072           if (!silent)
8073             error (0, 0, _("cannot get tag of DIE at offset [%" PRIx64
8074                                   "] in section '%s': %s"),
8075                    (uint64_t) offset, secname, dwarf_errmsg (-1));
8076           goto do_return;
8077         }
8078
8079       if (!silent)
8080         {
8081           unsigned int code = dwarf_getabbrevcode (dies[level].abbrev);
8082           if (is_split)
8083             printf (" {%6" PRIx64 "}  ", (uint64_t) offset);
8084           else
8085             printf (" [%6" PRIx64 "]  ", (uint64_t) offset);
8086           printf ("%*s%-20s abbrev: %u\n", (int) (level * 2), "",
8087                   dwarf_tag_name (tag), code);
8088         }
8089
8090       /* Print the attribute values.  */
8091       args.level = level;
8092       args.dies = dies;
8093       (void) dwarf_getattrs (&dies[level], attr_callback, &args, 0);
8094
8095       /* Make room for the next level's DIE.  */
8096       if (level + 1 == maxdies)
8097         dies = xrealloc (dies, (maxdies += 10) * sizeof (Dwarf_Die));
8098
8099       int res = dwarf_child (&dies[level], &dies[level + 1]);
8100       if (res > 0)
8101         {
8102           while ((res = dwarf_siblingof (&dies[level], &dies[level])) == 1)
8103             if (level-- == 0)
8104               break;
8105
8106           if (unlikely (res == -1))
8107             {
8108               if (!silent)
8109                 error (0, 0, _("cannot get next DIE: %s\n"),
8110                        dwarf_errmsg (-1));
8111               goto do_return;
8112             }
8113         }
8114       else if (unlikely (res < 0))
8115         {
8116           if (!silent)
8117             error (0, 0, _("cannot get next DIE: %s"),
8118                    dwarf_errmsg (-1));
8119           goto do_return;
8120         }
8121       else
8122         ++level;
8123     }
8124   while (level >= 0);
8125
8126   /* We might want to show the split compile unit if this was a skeleton.
8127      We need to scan it if we are requesting printing .debug_ranges for
8128      DWARF4 since GNU DebugFission uses "offsets" into the main ranges
8129      section.  */
8130   if (unit_type == DW_UT_skeleton
8131       && ((!silent && show_split_units)
8132           || (version < 5 && (print_debug_sections & section_ranges) != 0)))
8133     {
8134       Dwarf_Die subdie;
8135       if (dwarf_cu_info (cu, NULL, NULL, NULL, &subdie, NULL, NULL, NULL) != 0
8136           || dwarf_tag (&subdie) == DW_TAG_invalid)
8137         {
8138           if (!silent)
8139             {
8140               Dwarf_Attribute dwo_at;
8141               const char *dwo_name =
8142                 (dwarf_formstring (dwarf_attr (&cudie, DW_AT_dwo_name,
8143                                                &dwo_at))
8144                  ?: (dwarf_formstring (dwarf_attr (&cudie, DW_AT_GNU_dwo_name,
8145                                                    &dwo_at))
8146                      ?: "<unknown>"));
8147               fprintf (stderr,
8148                        "Could not find split unit '%s', id: %" PRIx64 "\n",
8149                        dwo_name, unit_id);
8150             }
8151         }
8152       else
8153         {
8154           Dwarf_CU *split_cu = subdie.cu;
8155           dwarf_cu_die (split_cu, &result, NULL, &abbroffset,
8156                         &addrsize, &offsize, &unit_id, &subdie_off);
8157           Dwarf_Off offset = cu->start;
8158
8159           if (!silent)
8160             {
8161               printf (_(" Split compilation unit at offset %"
8162                                PRIu64 ":\n"
8163                                " Version: %" PRIu16
8164                                ", Abbreviation section offset: %" PRIu64
8165                                ", Address size: %" PRIu8
8166                                ", Offset size: %" PRIu8 "\n"),
8167                       (uint64_t) offset, version, abbroffset,
8168                       addrsize, offsize);
8169               printf (_(" Unit type: %s (%" PRIu8 ")"),
8170                       dwarf_unit_name (unit_type), unit_type);
8171               printf (", Unit id: 0x%.16" PRIx64 "", unit_id);
8172               printf ("\n");
8173             }
8174
8175           unit_type = DW_UT_split_compile;
8176           is_split = true;
8177           level = 0;
8178           dies[0] = subdie;
8179           args.cu = dies[0].cu;
8180           args.dbg = split_cu->dbg;
8181           args.is_split = is_split;
8182           goto do_cu;
8183         }
8184     }
8185
8186   /* And again... */
8187   goto next_cu;
8188
8189  do_return:
8190   free (dies);
8191 }
8192
8193 static void
8194 print_debug_info_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
8195                           Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
8196 {
8197   print_debug_units (dwflmod, ebl, ehdr, scn, shdr, dbg, false);
8198 }
8199
8200 static void
8201 print_debug_types_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
8202                            Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
8203 {
8204   print_debug_units (dwflmod, ebl, ehdr, scn, shdr, dbg, true);
8205 }
8206
8207
8208 static void
8209 print_decoded_line_section (Dwfl_Module *dwflmod, Ebl *ebl,
8210                             GElf_Ehdr *ehdr __attribute__ ((unused)),
8211                             Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
8212 {
8213   printf (_("\
8214 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n\n"),
8215           elf_ndxscn (scn), section_name (ebl, shdr),
8216           (uint64_t) shdr->sh_offset);
8217
8218   size_t address_size
8219     = elf_getident (ebl->elf, NULL)[EI_CLASS] == ELFCLASS32 ? 4 : 8;
8220
8221   Dwarf_Lines *lines;
8222   size_t nlines;
8223   Dwarf_Off off, next_off = 0;
8224   Dwarf_CU *cu = NULL;
8225   while (dwarf_next_lines (dbg, off = next_off, &next_off, &cu, NULL, NULL,
8226                            &lines, &nlines) == 0)
8227     {
8228       Dwarf_Die cudie;
8229       if (cu != NULL && dwarf_cu_info (cu, NULL, NULL, &cudie,
8230                                        NULL, NULL, NULL, NULL) == 0)
8231         printf (" CU [%" PRIx64 "] %s\n",
8232                 dwarf_dieoffset (&cudie), dwarf_diename (&cudie));
8233       else
8234         {
8235           /* DWARF5 lines can be independent of any CU, but they probably
8236              are used by some CU.  Determine the CU this block is for.  */
8237           Dwarf_Off cuoffset;
8238           Dwarf_Off ncuoffset = 0;
8239           size_t hsize;
8240           while (dwarf_nextcu (dbg, cuoffset = ncuoffset, &ncuoffset, &hsize,
8241                                NULL, NULL, NULL) == 0)
8242             {
8243               if (dwarf_offdie (dbg, cuoffset + hsize, &cudie) == NULL)
8244                 continue;
8245               Dwarf_Attribute stmt_list;
8246               if (dwarf_attr (&cudie, DW_AT_stmt_list, &stmt_list) == NULL)
8247                 continue;
8248               Dwarf_Word lineoff;
8249               if (dwarf_formudata (&stmt_list, &lineoff) != 0)
8250                 continue;
8251               if (lineoff == off)
8252                 {
8253                   /* Found the CU.  */
8254                   cu = cudie.cu;
8255                   break;
8256                 }
8257             }
8258
8259           if (cu != NULL)
8260             printf (" CU [%" PRIx64 "] %s\n",
8261                     dwarf_dieoffset (&cudie), dwarf_diename (&cudie));
8262           else
8263             printf (" No CU\n");
8264         }
8265
8266       printf ("  line:col SBPE* disc isa op address"
8267               " (Statement Block Prologue Epilogue *End)\n");
8268       const char *last_file = "";
8269       for (size_t n = 0; n < nlines; n++)
8270         {
8271           Dwarf_Line *line = dwarf_onesrcline (lines, n);
8272           if (line == NULL)
8273             {
8274               printf ("  dwarf_onesrcline: %s\n", dwarf_errmsg (-1));
8275               continue;
8276             }
8277           Dwarf_Word mtime, length;
8278           const char *file = dwarf_linesrc (line, &mtime, &length);
8279           if (file == NULL)
8280             {
8281               printf ("  <%s> (mtime: ?, length: ?)\n", dwarf_errmsg (-1));
8282               last_file = "";
8283             }
8284           else if (strcmp (last_file, file) != 0)
8285             {
8286               printf ("  %s (mtime: %" PRIu64 ", length: %" PRIu64 ")\n",
8287                       file, mtime, length);
8288               last_file = file;
8289             }
8290
8291           int lineno, colno;
8292           bool statement, endseq, block, prologue_end, epilogue_begin;
8293           unsigned int lineop, isa, disc;
8294           Dwarf_Addr address;
8295           dwarf_lineaddr (line, &address);
8296           dwarf_lineno (line, &lineno);
8297           dwarf_linecol (line, &colno);
8298           dwarf_lineop_index (line, &lineop);
8299           dwarf_linebeginstatement (line, &statement);
8300           dwarf_lineendsequence (line, &endseq);
8301           dwarf_lineblock (line, &block);
8302           dwarf_lineprologueend (line, &prologue_end);
8303           dwarf_lineepiloguebegin (line, &epilogue_begin);
8304           dwarf_lineisa (line, &isa);
8305           dwarf_linediscriminator (line, &disc);
8306
8307           /* End sequence is special, it is one byte past.  */
8308           printf ("  %4d:%-3d %c%c%c%c%c %4d %3d %2d ",
8309                   lineno, colno,
8310                   (statement ? 'S' : ' '),
8311                   (block ? 'B' : ' '),
8312                   (prologue_end ? 'P' : ' '),
8313                   (epilogue_begin ? 'E' : ' '),
8314                   (endseq ? '*' : ' '),
8315                   disc, isa, lineop);
8316           print_dwarf_addr (dwflmod, address_size,
8317                             address - (endseq ? 1 : 0), address);
8318           printf ("\n");
8319
8320           if (endseq)
8321             printf("\n");
8322         }
8323     }
8324 }
8325
8326
8327 /* Print the value of a form.
8328    Returns new value of readp, or readendp on failure.  */
8329 static const unsigned char *
8330 print_form_data (Dwarf *dbg, int form, const unsigned char *readp,
8331                  const unsigned char *readendp, unsigned int offset_len,
8332                  Dwarf_Off str_offsets_base)
8333 {
8334   Dwarf_Word val;
8335   unsigned char *endp;
8336   Elf_Data *data;
8337   char *str;
8338   switch (form)
8339     {
8340     case DW_FORM_data1:
8341       if (readendp - readp < 1)
8342         {
8343         invalid_data:
8344           error (0, 0, "invalid data");
8345           return readendp;
8346         }
8347       val = *readp++;
8348       printf (" %" PRIx8, (unsigned int) val);
8349       break;
8350
8351     case DW_FORM_data2:
8352       if (readendp - readp < 2)
8353         goto invalid_data;
8354       val = read_2ubyte_unaligned_inc (dbg, readp);
8355       printf(" %" PRIx16, (unsigned int) val);
8356       break;
8357
8358     case DW_FORM_data4:
8359       if (readendp - readp < 4)
8360         goto invalid_data;
8361       val = read_4ubyte_unaligned_inc (dbg, readp);
8362       printf (" %" PRIx32, (unsigned int) val);
8363       break;
8364
8365     case DW_FORM_data8:
8366       if (readendp - readp < 8)
8367         goto invalid_data;
8368       val = read_8ubyte_unaligned_inc (dbg, readp);
8369       printf (" %" PRIx64, val);
8370       break;
8371
8372     case DW_FORM_sdata:
8373       if (readendp - readp < 1)
8374         goto invalid_data;
8375       get_sleb128 (val, readp, readendp);
8376       printf (" %" PRIx64, val);
8377       break;
8378
8379     case DW_FORM_udata:
8380       if (readendp - readp < 1)
8381         goto invalid_data;
8382       get_uleb128 (val, readp, readendp);
8383       printf (" %" PRIx64, val);
8384       break;
8385
8386     case DW_FORM_block:
8387       if (readendp - readp < 1)
8388         goto invalid_data;
8389       get_uleb128 (val, readp, readendp);
8390       if ((size_t) (readendp - readp) < val)
8391         goto invalid_data;
8392       print_bytes (val, readp);
8393       readp += val;
8394       break;
8395
8396     case DW_FORM_block1:
8397       if (readendp - readp < 1)
8398         goto invalid_data;
8399       val = *readp++;
8400       if ((size_t) (readendp - readp) < val)
8401         goto invalid_data;
8402       print_bytes (val, readp);
8403       readp += val;
8404       break;
8405
8406     case DW_FORM_block2:
8407       if (readendp - readp < 2)
8408         goto invalid_data;
8409       val = read_2ubyte_unaligned_inc (dbg, readp);
8410       if ((size_t) (readendp - readp) < val)
8411         goto invalid_data;
8412       print_bytes (val, readp);
8413       readp += val;
8414       break;
8415
8416     case DW_FORM_block4:
8417       if (readendp - readp < 4)
8418         goto invalid_data;
8419       val = read_4ubyte_unaligned_inc (dbg, readp);
8420       if ((size_t) (readendp - readp) < val)
8421         goto invalid_data;
8422       print_bytes (val, readp);
8423       readp += val;
8424       break;
8425
8426     case DW_FORM_data16:
8427       if (readendp - readp < 16)
8428         goto invalid_data;
8429       print_bytes (16, readp);
8430       readp += 16;
8431       break;
8432
8433     case DW_FORM_flag:
8434       if (readendp - readp < 1)
8435         goto invalid_data;
8436       val = *readp++;
8437       printf ("%s", val != 0 ? yes_str : no_str);
8438       break;
8439
8440     case DW_FORM_string:
8441       endp = memchr (readp, '\0', readendp - readp);
8442       if (endp == NULL)
8443         goto invalid_data;
8444       printf ("%s", readp);
8445       readp = endp + 1;
8446       break;
8447
8448     case DW_FORM_strp:
8449     case DW_FORM_line_strp:
8450     case DW_FORM_strp_sup:
8451       if ((size_t) (readendp - readp) < offset_len)
8452         goto invalid_data;
8453       if (offset_len == 8)
8454         val = read_8ubyte_unaligned_inc (dbg, readp);
8455       else
8456         val = read_4ubyte_unaligned_inc (dbg, readp);
8457       if (form == DW_FORM_strp)
8458         data = dbg->sectiondata[IDX_debug_str];
8459       else if (form == DW_FORM_line_strp)
8460         data = dbg->sectiondata[IDX_debug_line_str];
8461       else /* form == DW_FORM_strp_sup */
8462         {
8463           Dwarf *alt = dwarf_getalt (dbg);
8464           data = alt != NULL ? alt->sectiondata[IDX_debug_str] : NULL;
8465         }
8466       if (data == NULL || val >= data->d_size
8467           || memchr (data->d_buf + val, '\0', data->d_size - val) == NULL)
8468         str = "???";
8469       else
8470         str = (char *) data->d_buf + val;
8471       printf ("%s (%" PRIu64 ")", str, val);
8472       break;
8473
8474     case DW_FORM_sec_offset:
8475       if ((size_t) (readendp - readp) < offset_len)
8476         goto invalid_data;
8477       if (offset_len == 8)
8478         val = read_8ubyte_unaligned_inc (dbg, readp);
8479       else
8480         val = read_4ubyte_unaligned_inc (dbg, readp);
8481       printf ("[%" PRIx64 "]", val);
8482       break;
8483
8484     case DW_FORM_strx:
8485     case DW_FORM_GNU_str_index:
8486       if (readendp - readp < 1)
8487         goto invalid_data;
8488       get_uleb128 (val, readp, readendp);
8489     strx_val:
8490       data = dbg->sectiondata[IDX_debug_str_offsets];
8491       if (data == NULL
8492           || data->d_size - str_offsets_base < val)
8493         str = "???";
8494       else
8495         {
8496           const unsigned char *strreadp = data->d_buf + str_offsets_base + val;
8497           const unsigned char *strreadendp = data->d_buf + data->d_size;
8498           if ((size_t) (strreadendp - strreadp) < offset_len)
8499             str = "???";
8500           else
8501             {
8502               Dwarf_Off idx;
8503               if (offset_len == 8)
8504                 idx = read_8ubyte_unaligned (dbg, strreadp);
8505               else
8506                 idx = read_4ubyte_unaligned (dbg, strreadp);
8507
8508               data = dbg->sectiondata[IDX_debug_str];
8509               if (data == NULL || idx >= data->d_size
8510                   || memchr (data->d_buf + idx, '\0',
8511                              data->d_size - idx) == NULL)
8512                 str = "???";
8513               else
8514                 str = (char *) data->d_buf + idx;
8515             }
8516         }
8517       printf ("%s (%" PRIu64 ")", str, val);
8518       break;
8519
8520     case DW_FORM_strx1:
8521       if (readendp - readp < 1)
8522         goto invalid_data;
8523       val = *readp++;
8524       goto strx_val;
8525
8526     case DW_FORM_strx2:
8527       if (readendp - readp < 2)
8528         goto invalid_data;
8529       val = read_2ubyte_unaligned_inc (dbg, readp);
8530       goto strx_val;
8531
8532     case DW_FORM_strx3:
8533       if (readendp - readp < 3)
8534         goto invalid_data;
8535       val = read_3ubyte_unaligned_inc (dbg, readp);
8536       goto strx_val;
8537
8538     case DW_FORM_strx4:
8539       if (readendp - readp < 4)
8540         goto invalid_data;
8541       val = read_4ubyte_unaligned_inc (dbg, readp);
8542       goto strx_val;
8543
8544     default:
8545       error (0, 0, _("unknown form: %s"), dwarf_form_name (form));
8546       return readendp;
8547     }
8548
8549   return readp;
8550 }
8551
8552 /* Only used via run_advance_pc() macro */
8553 static inline void
8554 run_advance_pc (unsigned int op_advance,
8555                 unsigned int minimum_instr_len,
8556                 unsigned int max_ops_per_instr,
8557                 unsigned int *op_addr_advance,
8558                 Dwarf_Word *address,
8559                 unsigned int *op_index)
8560 {
8561   const unsigned int advanced_op_index = (*op_index) + op_advance;
8562
8563   *op_addr_advance = minimum_instr_len * (advanced_op_index
8564                                          / max_ops_per_instr);
8565   *address = *address + *op_addr_advance;
8566   *op_index = advanced_op_index % max_ops_per_instr;
8567 }
8568
8569 static void
8570 print_debug_line_section (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr,
8571                           Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
8572 {
8573   if (decodedline)
8574     {
8575       print_decoded_line_section (dwflmod, ebl, ehdr, scn, shdr, dbg);
8576       return;
8577     }
8578
8579   printf (_("\
8580 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
8581           elf_ndxscn (scn), section_name (ebl, shdr),
8582           (uint64_t) shdr->sh_offset);
8583
8584   if (shdr->sh_size == 0)
8585     return;
8586
8587   /* There is no functionality in libdw to read the information in the
8588      way it is represented here.  Hardcode the decoder.  */
8589   Elf_Data *data = (dbg->sectiondata[IDX_debug_line]
8590                     ?: elf_rawdata (scn, NULL));
8591   if (unlikely (data == NULL))
8592     {
8593       error (0, 0, _("cannot get line data section data: %s"),
8594              elf_errmsg (-1));
8595       return;
8596     }
8597
8598   const unsigned char *linep = (const unsigned char *) data->d_buf;
8599   const unsigned char *lineendp;
8600
8601   while (linep
8602          < (lineendp = (const unsigned char *) data->d_buf + data->d_size))
8603     {
8604       size_t start_offset = linep - (const unsigned char *) data->d_buf;
8605
8606       printf (_("\nTable at offset %zu:\n"), start_offset);
8607
8608       if (unlikely (linep + 4 > lineendp))
8609         goto invalid_data;
8610       Dwarf_Word unit_length = read_4ubyte_unaligned_inc (dbg, linep);
8611       unsigned int length = 4;
8612       if (unlikely (unit_length == 0xffffffff))
8613         {
8614           if (unlikely (linep + 8 > lineendp))
8615             {
8616             invalid_data:
8617               error (0, 0, _("invalid data in section [%zu] '%s'"),
8618                      elf_ndxscn (scn), section_name (ebl, shdr));
8619               return;
8620             }
8621           unit_length = read_8ubyte_unaligned_inc (dbg, linep);
8622           length = 8;
8623         }
8624
8625       /* Check whether we have enough room in the section.  */
8626       if (unlikely (unit_length > (size_t) (lineendp - linep)))
8627         goto invalid_data;
8628       lineendp = linep + unit_length;
8629
8630       /* The next element of the header is the version identifier.  */
8631       if ((size_t) (lineendp - linep) < 2)
8632         goto invalid_data;
8633       uint_fast16_t version = read_2ubyte_unaligned_inc (dbg, linep);
8634
8635       size_t address_size
8636         = elf_getident (ebl->elf, NULL)[EI_CLASS] == ELFCLASS32 ? 4 : 8;
8637       unsigned char segment_selector_size = 0;
8638       if (version > 4)
8639         {
8640           if ((size_t) (lineendp - linep) < 2)
8641             goto invalid_data;
8642           address_size = *linep++;
8643           segment_selector_size = *linep++;
8644         }
8645
8646       /* Next comes the header length.  */
8647       Dwarf_Word header_length;
8648       if (length == 4)
8649         {
8650           if ((size_t) (lineendp - linep) < 4)
8651             goto invalid_data;
8652           header_length = read_4ubyte_unaligned_inc (dbg, linep);
8653         }
8654       else
8655         {
8656           if ((size_t) (lineendp - linep) < 8)
8657             goto invalid_data;
8658           header_length = read_8ubyte_unaligned_inc (dbg, linep);
8659         }
8660
8661       const unsigned char *header_start = linep;
8662
8663       /* Next the minimum instruction length.  */
8664       if ((size_t) (lineendp - linep) < 1)
8665         goto invalid_data;
8666       uint_fast8_t minimum_instr_len = *linep++;
8667
8668       /* Next the maximum operations per instruction, in version 4 format.  */
8669       uint_fast8_t max_ops_per_instr;
8670       if (version < 4)
8671         max_ops_per_instr = 1;
8672       else
8673         {
8674           if ((size_t) (lineendp - linep) < 1)
8675             goto invalid_data;
8676           max_ops_per_instr = *linep++;
8677         }
8678
8679       /* We need at least 4 more bytes.  */
8680       if ((size_t) (lineendp - linep) < 4)
8681         goto invalid_data;
8682
8683       /* Then the flag determining the default value of the is_stmt
8684          register.  */
8685       uint_fast8_t default_is_stmt = *linep++;
8686
8687       /* Now the line base.  */
8688       int_fast8_t line_base = *linep++;
8689
8690       /* And the line range.  */
8691       uint_fast8_t line_range = *linep++;
8692
8693       /* The opcode base.  */
8694       uint_fast8_t opcode_base = *linep++;
8695
8696       /* Print what we got so far.  */
8697       printf (_("\n"
8698                        " Length:                         %" PRIu64 "\n"
8699                        " DWARF version:                  %" PRIuFAST16 "\n"
8700                        " Prologue length:                %" PRIu64 "\n"
8701                        " Address size:                   %zd\n"
8702                        " Segment selector size:          %zd\n"
8703                        " Min instruction length:         %" PRIuFAST8 "\n"
8704                        " Max operations per instruction: %" PRIuFAST8 "\n"
8705                        " Initial value if 'is_stmt':     %" PRIuFAST8 "\n"
8706                        " Line base:                      %" PRIdFAST8 "\n"
8707                        " Line range:                     %" PRIuFAST8 "\n"
8708                        " Opcode base:                    %" PRIuFAST8 "\n"
8709                        "\n"
8710                        "Opcodes:\n"),
8711               (uint64_t) unit_length, version, (uint64_t) header_length,
8712               address_size, (size_t) segment_selector_size,
8713               minimum_instr_len, max_ops_per_instr,
8714               default_is_stmt, line_base,
8715               line_range, opcode_base);
8716
8717       if (version < 2 || version > 5)
8718         {
8719           error (0, 0, _("cannot handle .debug_line version: %u\n"),
8720                  (unsigned int) version);
8721           linep = lineendp;
8722           continue;
8723         }
8724
8725       if (address_size != 4 && address_size != 8)
8726         {
8727           error (0, 0, _("cannot handle address size: %u\n"),
8728                  (unsigned int) address_size);
8729           linep = lineendp;
8730           continue;
8731         }
8732
8733       if (segment_selector_size != 0)
8734         {
8735           error (0, 0, _("cannot handle segment selector size: %u\n"),
8736                  (unsigned int) segment_selector_size);
8737           linep = lineendp;
8738           continue;
8739         }
8740
8741       if (unlikely (linep + opcode_base - 1 >= lineendp))
8742         {
8743         invalid_unit:
8744           error (0, 0,
8745                  _("invalid data at offset %tu in section [%zu] '%s'"),
8746                  linep - (const unsigned char *) data->d_buf,
8747                  elf_ndxscn (scn), section_name (ebl, shdr));
8748           linep = lineendp;
8749           continue;
8750         }
8751       int opcode_base_l10 = 1;
8752       unsigned int tmp = opcode_base;
8753       while (tmp > 10)
8754         {
8755           tmp /= 10;
8756           ++opcode_base_l10;
8757         }
8758       const uint8_t *standard_opcode_lengths = linep - 1;
8759       for (uint_fast8_t cnt = 1; cnt < opcode_base; ++cnt)
8760         printf (ngettext ("  [%*" PRIuFAST8 "]  %hhu argument\n",
8761                           "  [%*" PRIuFAST8 "]  %hhu arguments\n",
8762                           (int) linep[cnt - 1]),
8763                 opcode_base_l10, cnt, linep[cnt - 1]);
8764       linep += opcode_base - 1;
8765
8766       if (unlikely (linep >= lineendp))
8767         goto invalid_unit;
8768
8769       Dwarf_Off str_offsets_base = str_offsets_base_off (dbg, NULL);
8770
8771       puts (_("\nDirectory table:"));
8772       if (version > 4)
8773         {
8774           struct encpair { uint16_t desc; uint16_t form; };
8775           struct encpair enc[256];
8776
8777           printf (_("      ["));
8778           if ((size_t) (lineendp - linep) < 1)
8779             goto invalid_data;
8780           unsigned char directory_entry_format_count = *linep++;
8781           for (int i = 0; i < directory_entry_format_count; i++)
8782             {
8783               uint16_t desc, form;
8784               if ((size_t) (lineendp - linep) < 1)
8785                 goto invalid_data;
8786               get_uleb128 (desc, linep, lineendp);
8787               if ((size_t) (lineendp - linep) < 1)
8788                 goto invalid_data;
8789               get_uleb128 (form, linep, lineendp);
8790
8791               enc[i].desc = desc;
8792               enc[i].form = form;
8793
8794               printf ("%s(%s)",
8795                       dwarf_line_content_description_name (desc),
8796                       dwarf_form_name (form));
8797               if (i + 1 < directory_entry_format_count)
8798                 printf (", ");
8799             }
8800           printf ("]\n");
8801
8802           uint64_t directories_count;
8803           if ((size_t) (lineendp - linep) < 1)
8804             goto invalid_data;
8805           get_uleb128 (directories_count, linep, lineendp);
8806
8807           if (directory_entry_format_count == 0
8808               && directories_count != 0)
8809             goto invalid_data;
8810
8811           for (uint64_t i = 0; i < directories_count; i++)
8812             {
8813               printf (" %-5" PRIu64 " ", i);
8814               for (int j = 0; j < directory_entry_format_count; j++)
8815                 {
8816                   linep = print_form_data (dbg, enc[j].form,
8817                                            linep, lineendp, length,
8818                                            str_offsets_base);
8819                   if (j + 1 < directory_entry_format_count)
8820                     printf (", ");
8821                 }
8822               printf ("\n");
8823               if (linep >= lineendp)
8824                 goto invalid_unit;
8825             }
8826         }
8827       else
8828         {
8829           while (linep < lineendp && *linep != 0)
8830             {
8831               unsigned char *endp = memchr (linep, '\0', lineendp - linep);
8832               if (unlikely (endp == NULL))
8833                 goto invalid_unit;
8834
8835               printf (" %s\n", (char *) linep);
8836
8837               linep = endp + 1;
8838             }
8839           if (linep >= lineendp || *linep != 0)
8840             goto invalid_unit;
8841           /* Skip the final NUL byte.  */
8842           ++linep;
8843         }
8844
8845       if (unlikely (linep >= lineendp))
8846         goto invalid_unit;
8847
8848       puts (_("\nFile name table:"));
8849       if (version > 4)
8850         {
8851           struct encpair { uint16_t desc; uint16_t form; };
8852           struct encpair enc[256];
8853
8854           printf (_("      ["));
8855           if ((size_t) (lineendp - linep) < 1)
8856             goto invalid_data;
8857           unsigned char file_name_format_count = *linep++;
8858           for (int i = 0; i < file_name_format_count; i++)
8859             {
8860               uint64_t desc, form;
8861               if ((size_t) (lineendp - linep) < 1)
8862                 goto invalid_data;
8863               get_uleb128 (desc, linep, lineendp);
8864               if ((size_t) (lineendp - linep) < 1)
8865                 goto invalid_data;
8866               get_uleb128 (form, linep, lineendp);
8867
8868               if (! libdw_valid_user_form (form))
8869                 goto invalid_data;
8870
8871               enc[i].desc = desc;
8872               enc[i].form = form;
8873
8874               printf ("%s(%s)",
8875                       dwarf_line_content_description_name (desc),
8876                       dwarf_form_name (form));
8877               if (i + 1 < file_name_format_count)
8878                 printf (", ");
8879             }
8880           printf ("]\n");
8881
8882           uint64_t file_name_count;
8883           if ((size_t) (lineendp - linep) < 1)
8884             goto invalid_data;
8885           get_uleb128 (file_name_count, linep, lineendp);
8886
8887           if (file_name_format_count == 0
8888               && file_name_count != 0)
8889             goto invalid_data;
8890
8891           for (uint64_t i = 0; i < file_name_count; i++)
8892             {
8893               printf (" %-5" PRIu64 " ", i);
8894               for (int j = 0; j < file_name_format_count; j++)
8895                 {
8896                   linep = print_form_data (dbg, enc[j].form,
8897                                            linep, lineendp, length,
8898                                            str_offsets_base);
8899                   if (j + 1 < file_name_format_count)
8900                     printf (", ");
8901                 }
8902               printf ("\n");
8903               if (linep > lineendp)
8904                 goto invalid_unit;
8905             }
8906         }
8907       else
8908         {
8909           puts (_(" Entry Dir   Time      Size      Name"));
8910           for (unsigned int cnt = 1; linep < lineendp && *linep != 0; ++cnt)
8911             {
8912               /* First comes the file name.  */
8913               char *fname = (char *) linep;
8914               unsigned char *endp = memchr (fname, '\0', lineendp - linep);
8915               if (unlikely (endp == NULL))
8916                 goto invalid_unit;
8917               linep = endp + 1;
8918
8919               /* Then the index.  */
8920               unsigned int diridx;
8921               if (lineendp - linep < 1)
8922                 goto invalid_unit;
8923               get_uleb128 (diridx, linep, lineendp);
8924
8925               /* Next comes the modification time.  */
8926               unsigned int mtime;
8927               if (lineendp - linep < 1)
8928                 goto invalid_unit;
8929               get_uleb128 (mtime, linep, lineendp);
8930
8931               /* Finally the length of the file.  */
8932               unsigned int fsize;
8933               if (lineendp - linep < 1)
8934                 goto invalid_unit;
8935               get_uleb128 (fsize, linep, lineendp);
8936
8937               printf (" %-5u %-5u %-9u %-9u %s\n",
8938                       cnt, diridx, mtime, fsize, fname);
8939             }
8940           if (linep >= lineendp || *linep != '\0')
8941             goto invalid_unit;
8942           /* Skip the final NUL byte.  */
8943           ++linep;
8944         }
8945
8946       unsigned int debug_str_offset = 0;
8947       if (unlikely (linep == header_start + header_length - 4))
8948         {
8949           /* CUBINs contain an unsigned 4-byte offset */
8950           debug_str_offset = read_4ubyte_unaligned_inc (dbg, linep);
8951         }
8952
8953       if (linep == lineendp)
8954         {
8955           puts (_("\nNo line number statements."));
8956           continue;
8957         }
8958
8959       puts (_("\nLine number statements:"));
8960       Dwarf_Word address = 0;
8961       unsigned int op_index = 0;
8962       size_t line = 1;
8963       uint_fast8_t is_stmt = default_is_stmt;
8964
8965       /* Apply the "operation advance" from a special opcode
8966          or DW_LNS_advance_pc (as per DWARF4 6.2.5.1).  */
8967       unsigned int op_addr_advance;
8968 #define advance_pc(op_advance) run_advance_pc(op_advance, minimum_instr_len, \
8969                       max_ops_per_instr, &op_addr_advance, &address, &op_index)
8970
8971       if (max_ops_per_instr == 0)
8972         {
8973           error (0, 0,
8974                  _("invalid maximum operations per instruction is zero"));
8975           linep = lineendp;
8976           continue;
8977         }
8978
8979       while (linep < lineendp)
8980         {
8981           size_t offset = linep - (const unsigned char *) data->d_buf;
8982           unsigned int u128;
8983           int s128;
8984
8985           /* Read the opcode.  */
8986           unsigned int opcode = *linep++;
8987
8988           printf (" [%6" PRIx64 "]", (uint64_t)offset);
8989           /* Is this a special opcode?  */
8990           if (likely (opcode >= opcode_base))
8991             {
8992               if (unlikely (line_range == 0))
8993                 goto invalid_unit;
8994
8995               /* Yes.  Handling this is quite easy since the opcode value
8996                  is computed with
8997
8998                  opcode = (desired line increment - line_base)
8999                            + (line_range * address advance) + opcode_base
9000               */
9001               int line_increment = (line_base
9002                                     + (opcode - opcode_base) % line_range);
9003
9004               /* Perform the increments.  */
9005               line += line_increment;
9006               advance_pc ((opcode - opcode_base) / line_range);
9007
9008               printf (_(" special opcode %u: address+%u = "),
9009                       opcode, op_addr_advance);
9010               print_dwarf_addr (dwflmod, 0, address, address);
9011               if (op_index > 0)
9012                 printf (_(", op_index = %u, line%+d = %zu\n"),
9013                         op_index, line_increment, line);
9014               else
9015                 printf (_(", line%+d = %zu\n"),
9016                         line_increment, line);
9017             }
9018           else if (opcode == 0)
9019             {
9020               /* This an extended opcode.  */
9021               if (unlikely (linep + 2 > lineendp))
9022                 goto invalid_unit;
9023
9024               /* The length.  */
9025               unsigned int len = *linep++;
9026
9027               if (unlikely (linep + len > lineendp))
9028                 goto invalid_unit;
9029
9030               /* The sub-opcode.  */
9031               opcode = *linep++;
9032
9033               printf (_(" extended opcode %u: "), opcode);
9034
9035               switch (opcode)
9036                 {
9037                 case DW_LNE_end_sequence:
9038                   puts (_(" end of sequence"));
9039
9040                   /* Reset the registers we care about.  */
9041                   address = 0;
9042                   op_index = 0;
9043                   line = 1;
9044                   is_stmt = default_is_stmt;
9045                   break;
9046
9047                 case DW_LNE_set_address:
9048                   op_index = 0;
9049                   if (unlikely ((size_t) (lineendp - linep) < address_size))
9050                     goto invalid_unit;
9051                   if (address_size == 4)
9052                     address = read_4ubyte_unaligned_inc (dbg, linep);
9053                   else
9054                     address = read_8ubyte_unaligned_inc (dbg, linep);
9055                   {
9056                     printf (_(" set address to "));
9057                     print_dwarf_addr (dwflmod, 0, address, address);
9058                     printf ("\n");
9059                   }
9060                   break;
9061
9062                 case DW_LNE_define_file:
9063                   {
9064                     char *fname = (char *) linep;
9065                     unsigned char *endp = memchr (linep, '\0',
9066                                                   lineendp - linep);
9067                     if (unlikely (endp == NULL))
9068                       goto invalid_unit;
9069                     linep = endp + 1;
9070
9071                     unsigned int diridx;
9072                     if (lineendp - linep < 1)
9073                       goto invalid_unit;
9074                     get_uleb128 (diridx, linep, lineendp);
9075                     Dwarf_Word mtime;
9076                     if (lineendp - linep < 1)
9077                       goto invalid_unit;
9078                     get_uleb128 (mtime, linep, lineendp);
9079                     Dwarf_Word filelength;
9080                     if (lineendp - linep < 1)
9081                       goto invalid_unit;
9082                     get_uleb128 (filelength, linep, lineendp);
9083
9084                     printf (_("\
9085  define new file: dir=%u, mtime=%" PRIu64 ", length=%" PRIu64 ", name=%s\n"),
9086                             diridx, (uint64_t) mtime, (uint64_t) filelength,
9087                             fname);
9088                   }
9089                   break;
9090
9091                 case DW_LNE_set_discriminator:
9092                   /* Takes one ULEB128 parameter, the discriminator.  */
9093                   if (unlikely (standard_opcode_lengths[opcode] != 1
9094                                 || lineendp - linep < 1))
9095                     goto invalid_unit;
9096
9097                   get_uleb128 (u128, linep, lineendp);
9098                   printf (_(" set discriminator to %u\n"), u128);
9099                   break;
9100
9101                 case DW_LNE_NVIDIA_inlined_call:
9102                   {
9103                     if (unlikely (linep >= lineendp))
9104                       goto invalid_data;
9105
9106                     unsigned int context;
9107                     get_uleb128 (context, linep, lineendp);
9108
9109                     if (unlikely (linep >= lineendp))
9110                       goto invalid_data;
9111
9112                     unsigned int function_name;
9113                     get_uleb128 (function_name, linep, lineendp);
9114                     function_name += debug_str_offset;
9115
9116                     Elf_Data *str_data = dbg->sectiondata[IDX_debug_str];
9117                     char *function_str;
9118                     if (str_data == NULL || function_name >= str_data->d_size
9119                         || memchr (str_data->d_buf + function_name, '\0',
9120                                    str_data->d_size - function_name) == NULL)
9121                       function_str = "???";
9122                     else
9123                       function_str = (char *) str_data->d_buf + function_name;
9124
9125                     printf (_(" set inlined context %u,"
9126                               " function name %s (0x%x)\n"),
9127                             context, function_str, function_name);
9128                     break;
9129                   }
9130
9131                 case DW_LNE_NVIDIA_set_function_name:
9132                   {
9133                     if (unlikely (linep >= lineendp))
9134                       goto invalid_data;
9135
9136                     unsigned int function_name;
9137                     get_uleb128 (function_name, linep, lineendp);
9138                     function_name += debug_str_offset;
9139
9140                     Elf_Data *str_data = dbg->sectiondata[IDX_debug_str];
9141                     char *function_str;
9142                     if (str_data == NULL || function_name >= str_data->d_size
9143                         || memchr (str_data->d_buf + function_name, '\0',
9144                                    str_data->d_size - function_name) == NULL)
9145                       function_str = "???";
9146                     else
9147                       function_str = (char *) str_data->d_buf + function_name;
9148
9149                     printf (_(" set function name %s (0x%x)\n"),
9150                             function_str, function_name);
9151                   }
9152                   break;
9153
9154                 default:
9155                   /* Unknown, ignore it.  */
9156                   puts (_(" unknown opcode"));
9157                   linep += len - 1;
9158                   break;
9159                 }
9160             }
9161           else if (opcode <= DW_LNS_set_isa)
9162             {
9163               /* This is a known standard opcode.  */
9164               switch (opcode)
9165                 {
9166                 case DW_LNS_copy:
9167                   /* Takes no argument.  */
9168                   puts (_(" copy"));
9169                   break;
9170
9171                 case DW_LNS_advance_pc:
9172                   /* Takes one uleb128 parameter which is added to the
9173                      address.  */
9174                   if (lineendp - linep < 1)
9175                     goto invalid_unit;
9176                   get_uleb128 (u128, linep, lineendp);
9177                   advance_pc (u128);
9178                   {
9179                     printf (_(" advance address by %u to "),
9180                             op_addr_advance);
9181                     print_dwarf_addr (dwflmod, 0, address, address);
9182                     if (op_index > 0)
9183                       printf (_(", op_index to %u"), op_index);
9184                     printf ("\n");
9185                   }
9186                   break;
9187
9188                 case DW_LNS_advance_line:
9189                   /* Takes one sleb128 parameter which is added to the
9190                      line.  */
9191                   if (lineendp - linep < 1)
9192                     goto invalid_unit;
9193                   get_sleb128 (s128, linep, lineendp);
9194                   line += s128;
9195                   printf (_("\
9196  advance line by constant %d to %" PRId64 "\n"),
9197                           s128, (int64_t) line);
9198                   break;
9199
9200                 case DW_LNS_set_file:
9201                   /* Takes one uleb128 parameter which is stored in file.  */
9202                   if (lineendp - linep < 1)
9203                     goto invalid_unit;
9204                   get_uleb128 (u128, linep, lineendp);
9205                   printf (_(" set file to %" PRIu64 "\n"),
9206                           (uint64_t) u128);
9207                   break;
9208
9209                 case DW_LNS_set_column:
9210                   /* Takes one uleb128 parameter which is stored in column.  */
9211                   if (unlikely (standard_opcode_lengths[opcode] != 1
9212                                 || lineendp - linep < 1))
9213                     goto invalid_unit;
9214
9215                   get_uleb128 (u128, linep, lineendp);
9216                   printf (_(" set column to %" PRIu64 "\n"),
9217                           (uint64_t) u128);
9218                   break;
9219
9220                 case DW_LNS_negate_stmt:
9221                   /* Takes no argument.  */
9222                   is_stmt = 1 - is_stmt;
9223                   printf (_(" set '%s' to %" PRIuFAST8 "\n"),
9224                           "is_stmt", is_stmt);
9225                   break;
9226
9227                 case DW_LNS_set_basic_block:
9228                   /* Takes no argument.  */
9229                   puts (_(" set basic block flag"));
9230                   break;
9231
9232                 case DW_LNS_const_add_pc:
9233                   /* Takes no argument.  */
9234
9235                   if (unlikely (line_range == 0))
9236                     goto invalid_unit;
9237
9238                   advance_pc ((255 - opcode_base) / line_range);
9239                   {
9240                     printf (_(" advance address by constant %u to "),
9241                             op_addr_advance);
9242                     print_dwarf_addr (dwflmod, 0, address, address);
9243                     if (op_index > 0)
9244                       printf (_(", op_index to %u"), op_index);
9245                     printf ("\n");
9246                   }
9247                   break;
9248
9249                 case DW_LNS_fixed_advance_pc:
9250                   /* Takes one 16 bit parameter which is added to the
9251                      address.  */
9252                   if (unlikely (standard_opcode_lengths[opcode] != 1
9253                                 || lineendp - linep < 2))
9254                     goto invalid_unit;
9255
9256                   u128 = read_2ubyte_unaligned_inc (dbg, linep);
9257                   address += u128;
9258                   op_index = 0;
9259                   {
9260                     printf (_("\
9261  advance address by fixed value %u to \n"),
9262                             u128);
9263                     print_dwarf_addr (dwflmod, 0, address, address);
9264                     printf ("\n");
9265                   }
9266                   break;
9267
9268                 case DW_LNS_set_prologue_end:
9269                   /* Takes no argument.  */
9270                   puts (_(" set prologue end flag"));
9271                   break;
9272
9273                 case DW_LNS_set_epilogue_begin:
9274                   /* Takes no argument.  */
9275                   puts (_(" set epilogue begin flag"));
9276                   break;
9277
9278                 case DW_LNS_set_isa:
9279                   /* Takes one uleb128 parameter which is stored in isa.  */
9280                   if (unlikely (standard_opcode_lengths[opcode] != 1
9281                                 || lineendp - linep < 1))
9282                     goto invalid_unit;
9283
9284                   get_uleb128 (u128, linep, lineendp);
9285                   printf (_(" set isa to %u\n"), u128);
9286                   break;
9287                 }
9288             }
9289           else
9290             {
9291               /* This is a new opcode the generator but not we know about.
9292                  Read the parameters associated with it but then discard
9293                  everything.  Read all the parameters for this opcode.  */
9294               printf (ngettext (" unknown opcode with %" PRIu8 " parameter:",
9295                                 " unknown opcode with %" PRIu8 " parameters:",
9296                                 standard_opcode_lengths[opcode]),
9297                       standard_opcode_lengths[opcode]);
9298               for (int n = standard_opcode_lengths[opcode];
9299                    n > 0 && linep < lineendp; --n)
9300                 {
9301                   get_uleb128 (u128, linep, lineendp);
9302                   if (n != standard_opcode_lengths[opcode])
9303                     putc_unlocked (',', stdout);
9304                   printf (" %u", u128);
9305                 }
9306
9307               /* Next round, ignore this opcode.  */
9308               continue;
9309             }
9310         }
9311     }
9312
9313   /* There must only be one data block.  */
9314   assert (elf_getdata (scn, data) == NULL);
9315 }
9316
9317
9318 static void
9319 print_debug_loclists_section (Dwfl_Module *dwflmod,
9320                               Ebl *ebl,
9321                               GElf_Ehdr *ehdr __attribute__ ((unused)),
9322                               Elf_Scn *scn, GElf_Shdr *shdr,
9323                               Dwarf *dbg)
9324 {
9325   printf (_("\
9326 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
9327           elf_ndxscn (scn), section_name (ebl, shdr),
9328           (uint64_t) shdr->sh_offset);
9329
9330   Elf_Data *data = (dbg->sectiondata[IDX_debug_loclists]
9331                     ?: elf_rawdata (scn, NULL));
9332   if (unlikely (data == NULL))
9333     {
9334       error (0, 0, _("cannot get .debug_loclists content: %s"),
9335              elf_errmsg (-1));
9336       return;
9337     }
9338
9339   /* For the listptr to get the base address/CU.  */
9340   sort_listptr (&known_loclistsptr, "loclistsptr");
9341   size_t listptr_idx = 0;
9342
9343   const unsigned char *readp = data->d_buf;
9344   const unsigned char *const dataend = ((unsigned char *) data->d_buf
9345                                         + data->d_size);
9346   while (readp < dataend)
9347     {
9348       if (unlikely (readp > dataend - 4))
9349         {
9350         invalid_data:
9351           error (0, 0, _("invalid data in section [%zu] '%s'"),
9352                  elf_ndxscn (scn), section_name (ebl, shdr));
9353           return;
9354         }
9355
9356       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
9357       printf (_("Table at Offset 0x%" PRIx64 ":\n\n"),
9358               (uint64_t) offset);
9359
9360       uint64_t unit_length = read_4ubyte_unaligned_inc (dbg, readp);
9361       unsigned int offset_size = 4;
9362       if (unlikely (unit_length == 0xffffffff))
9363         {
9364           if (unlikely (readp > dataend - 8))
9365             goto invalid_data;
9366
9367           unit_length = read_8ubyte_unaligned_inc (dbg, readp);
9368           offset_size = 8;
9369         }
9370       printf (_(" Length:         %8" PRIu64 "\n"), unit_length);
9371
9372       /* We need at least 2-bytes + 1-byte + 1-byte + 4-bytes = 8
9373          bytes to complete the header.  And this unit cannot go beyond
9374          the section data.  */
9375       if (readp > dataend - 8
9376           || unit_length < 8
9377           || unit_length > (uint64_t) (dataend - readp))
9378         goto invalid_data;
9379
9380       const unsigned char *nexthdr = readp + unit_length;
9381
9382       uint16_t version = read_2ubyte_unaligned_inc (dbg, readp);
9383       printf (_(" DWARF version:  %8" PRIu16 "\n"), version);
9384
9385       if (version != 5)
9386         {
9387           error (0, 0, _("Unknown version"));
9388           goto next_table;
9389         }
9390
9391       uint8_t address_size = *readp++;
9392       printf (_(" Address size:   %8" PRIu64 "\n"),
9393               (uint64_t) address_size);
9394
9395       if (address_size != 4 && address_size != 8)
9396         {
9397           error (0, 0, _("unsupported address size"));
9398           goto next_table;
9399         }
9400
9401       uint8_t segment_size = *readp++;
9402       printf (_(" Segment size:   %8" PRIu64 "\n"),
9403               (uint64_t) segment_size);
9404
9405       if (segment_size != 0)
9406         {
9407           error (0, 0, _("unsupported segment size"));
9408           goto next_table;
9409         }
9410
9411       uint32_t offset_entry_count = read_4ubyte_unaligned_inc (dbg, readp);
9412       printf (_(" Offset entries: %8" PRIu64 "\n"),
9413               (uint64_t) offset_entry_count);
9414
9415       /* We need the CU that uses this unit to get the initial base address. */
9416       Dwarf_Addr cu_base = 0;
9417       struct Dwarf_CU *cu = NULL;
9418       if (listptr_cu (&known_loclistsptr, &listptr_idx,
9419                       (Dwarf_Off) offset,
9420                       (Dwarf_Off) (nexthdr - (unsigned char *) data->d_buf),
9421                       &cu_base, &cu)
9422           || split_dwarf_cu_base (dbg, &cu, &cu_base))
9423         {
9424           Dwarf_Die cudie;
9425           if (dwarf_cu_die (cu, &cudie,
9426                             NULL, NULL, NULL, NULL,
9427                             NULL, NULL) == NULL)
9428             printf (_(" Unknown CU base: "));
9429           else
9430             printf (_(" CU [%6" PRIx64 "] base: "),
9431                     dwarf_dieoffset (&cudie));
9432           print_dwarf_addr (dwflmod, address_size, cu_base, cu_base);
9433           printf ("\n");
9434         }
9435       else
9436         printf (_(" Not associated with a CU.\n"));
9437
9438       printf ("\n");
9439
9440       const unsigned char *offset_array_start = readp;
9441       if (offset_entry_count > 0)
9442         {
9443           uint64_t max_entries = (unit_length - 8) / offset_size;
9444           if (offset_entry_count > max_entries)
9445             {
9446               error (0, 0,
9447                      _("too many offset entries for unit length"));
9448               offset_entry_count = max_entries;
9449             }
9450
9451           printf (_("  Offsets starting at 0x%" PRIx64 ":\n"),
9452                   (uint64_t) (offset_array_start
9453                               - (unsigned char *) data->d_buf));
9454           for (uint32_t idx = 0; idx < offset_entry_count; idx++)
9455             {
9456               printf ("   [%6" PRIu32 "] ", idx);
9457               if (offset_size == 4)
9458                 {
9459                   uint32_t off = read_4ubyte_unaligned_inc (dbg, readp);
9460                   printf ("0x%" PRIx32 "\n", off);
9461                 }
9462               else
9463                 {
9464                   uint64_t off = read_8ubyte_unaligned_inc (dbg, readp);
9465                   printf ("0x%" PRIx64 "\n", off);
9466                 }
9467             }
9468           printf ("\n");
9469         }
9470
9471       Dwarf_Addr base = cu_base;
9472       bool start_of_list = true;
9473       while (readp < nexthdr)
9474         {
9475           Dwarf_Off off = (Dwarf_Off) (readp - (unsigned char *) data->d_buf);
9476           if (listptr_attr (&known_loclistsptr, listptr_idx, off,
9477                             DW_AT_GNU_locviews))
9478             {
9479               Dwarf_Off next_off = next_listptr_offset (&known_loclistsptr,
9480                                                         &listptr_idx, off);
9481               const unsigned char *locp = readp;
9482               const unsigned char *locendp;
9483               if (next_off == 0
9484                   || next_off > (size_t) (nexthdr - ((const unsigned char *)
9485                                                      data->d_buf)))
9486                 locendp = nexthdr;
9487               else
9488                 locendp = (const unsigned char *) data->d_buf + next_off;
9489
9490               printf ("  Offset: %" PRIx64 ", Index: %" PRIx64 "\n",
9491                       (uint64_t) (readp - (unsigned char *) data->d_buf),
9492                       (uint64_t) (readp - offset_array_start));
9493
9494               while (locp < locendp)
9495                 {
9496                   uint64_t v1, v2;
9497                   get_uleb128 (v1, locp, locendp);
9498                   if (locp >= locendp)
9499                     {
9500                       printf (_("    <INVALID DATA>\n"));
9501                       break;
9502                     }
9503                   get_uleb128 (v2, locp, locendp);
9504                   printf ("    view pair %" PRId64 ", %" PRId64 "\n", v1, v2);
9505                 }
9506
9507               printf ("\n");
9508               readp = (unsigned char *) locendp;
9509               continue;
9510             }
9511
9512           uint8_t kind = *readp++;
9513           uint64_t op1, op2, len;
9514
9515           /* Skip padding.  */
9516           if (start_of_list && kind == DW_LLE_end_of_list)
9517             continue;
9518
9519           if (start_of_list)
9520             {
9521               base = cu_base;
9522               printf ("  Offset: %" PRIx64 ", Index: %" PRIx64 "\n",
9523                       (uint64_t) (readp - (unsigned char *) data->d_buf - 1),
9524                       (uint64_t) (readp - offset_array_start - 1));
9525               start_of_list = false;
9526             }
9527
9528           printf ("    %s", dwarf_loc_list_encoding_name (kind));
9529           switch (kind)
9530             {
9531             case DW_LLE_end_of_list:
9532               start_of_list = true;
9533               printf ("\n\n");
9534               break;
9535
9536             case DW_LLE_base_addressx:
9537               if ((uint64_t) (nexthdr - readp) < 1)
9538                 {
9539                 invalid_entry:
9540                   error (0, 0, _("invalid loclists data"));
9541                   goto next_table;
9542                 }
9543               get_uleb128 (op1, readp, nexthdr);
9544               printf (" %" PRIx64 "\n", op1);
9545               if (! print_unresolved_addresses)
9546                 {
9547                   Dwarf_Addr addr;
9548                   if (get_indexed_addr (cu, op1, &addr) != 0)
9549                     printf ("      ???\n");
9550                   else
9551                     {
9552                       printf ("      ");
9553                       print_dwarf_addr (dwflmod, address_size, addr, addr);
9554                       printf ("\n");
9555                     }
9556                 }
9557               break;
9558
9559             case DW_LLE_startx_endx:
9560               if ((uint64_t) (nexthdr - readp) < 1)
9561                 goto invalid_entry;
9562               get_uleb128 (op1, readp, nexthdr);
9563               if ((uint64_t) (nexthdr - readp) < 1)
9564                 goto invalid_entry;
9565               get_uleb128 (op2, readp, nexthdr);
9566               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
9567               if (! print_unresolved_addresses)
9568                 {
9569                   Dwarf_Addr addr1;
9570                   Dwarf_Addr addr2;
9571                   if (get_indexed_addr (cu, op1, &addr1) != 0
9572                       || get_indexed_addr (cu, op2, &addr2) != 0)
9573                     {
9574                       printf ("      ???..\n");
9575                       printf ("      ???\n");
9576                     }
9577                   else
9578                     {
9579                       printf ("      ");
9580                       print_dwarf_addr (dwflmod, address_size, addr1, addr1);
9581                       printf ("..\n      ");
9582                       print_dwarf_addr (dwflmod, address_size,
9583                                         addr2 - 1, addr2);
9584                       printf ("\n");
9585                     }
9586                 }
9587               if ((uint64_t) (nexthdr - readp) < 1)
9588                 goto invalid_entry;
9589               get_uleb128 (len, readp, nexthdr);
9590               if ((uint64_t) (nexthdr - readp) < len)
9591                 goto invalid_entry;
9592               print_ops (dwflmod, dbg, 8, 8, version,
9593                          address_size, offset_size, cu, len, readp);
9594               readp += len;
9595               break;
9596
9597             case DW_LLE_startx_length:
9598               if ((uint64_t) (nexthdr - readp) < 1)
9599                 goto invalid_entry;
9600               get_uleb128 (op1, readp, nexthdr);
9601               if ((uint64_t) (nexthdr - readp) < 1)
9602                 goto invalid_entry;
9603               get_uleb128 (op2, readp, nexthdr);
9604               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
9605               if (! print_unresolved_addresses)
9606                 {
9607                   Dwarf_Addr addr1;
9608                   Dwarf_Addr addr2;
9609                   if (get_indexed_addr (cu, op1, &addr1) != 0)
9610                     {
9611                       printf ("      ???..\n");
9612                       printf ("      ???\n");
9613                     }
9614                   else
9615                     {
9616                       addr2 = addr1 + op2;
9617                       printf ("      ");
9618                       print_dwarf_addr (dwflmod, address_size, addr1, addr1);
9619                       printf ("..\n      ");
9620                       print_dwarf_addr (dwflmod, address_size,
9621                                         addr2 - 1, addr2);
9622                       printf ("\n");
9623                     }
9624                 }
9625               if ((uint64_t) (nexthdr - readp) < 1)
9626                 goto invalid_entry;
9627               get_uleb128 (len, readp, nexthdr);
9628               if ((uint64_t) (nexthdr - readp) < len)
9629                 goto invalid_entry;
9630               print_ops (dwflmod, dbg, 8, 8, version,
9631                          address_size, offset_size, cu, len, readp);
9632               readp += len;
9633               break;
9634
9635             case DW_LLE_offset_pair:
9636               if ((uint64_t) (nexthdr - readp) < 1)
9637                 goto invalid_entry;
9638               get_uleb128 (op1, readp, nexthdr);
9639               if ((uint64_t) (nexthdr - readp) < 1)
9640                 goto invalid_entry;
9641               get_uleb128 (op2, readp, nexthdr);
9642               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
9643               if (! print_unresolved_addresses)
9644                 {
9645                   op1 += base;
9646                   op2 += base;
9647                   printf ("      ");
9648                   print_dwarf_addr (dwflmod, address_size, op1, op1);
9649                   printf ("..\n      ");
9650                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
9651                   printf ("\n");
9652                 }
9653               if ((uint64_t) (nexthdr - readp) < 1)
9654                 goto invalid_entry;
9655               get_uleb128 (len, readp, nexthdr);
9656               if ((uint64_t) (nexthdr - readp) < len)
9657                 goto invalid_entry;
9658               print_ops (dwflmod, dbg, 8, 8, version,
9659                          address_size, offset_size, cu, len, readp);
9660               readp += len;
9661               break;
9662
9663             case DW_LLE_default_location:
9664               if ((uint64_t) (nexthdr - readp) < 1)
9665                 goto invalid_entry;
9666               get_uleb128 (len, readp, nexthdr);
9667               if ((uint64_t) (nexthdr - readp) < len)
9668                 goto invalid_entry;
9669               print_ops (dwflmod, dbg, 8, 8, version,
9670                          address_size, offset_size, cu, len, readp);
9671               readp += len;
9672               break;
9673
9674             case DW_LLE_base_address:
9675               if (address_size == 4)
9676                 {
9677                   if ((uint64_t) (nexthdr - readp) < 4)
9678                     goto invalid_entry;
9679                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
9680                 }
9681               else
9682                 {
9683                   if ((uint64_t) (nexthdr - readp) < 8)
9684                     goto invalid_entry;
9685                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
9686                 }
9687               base = op1;
9688               printf (" 0x%" PRIx64 "\n", base);
9689               if (! print_unresolved_addresses)
9690                 {
9691                   printf ("      ");
9692                   print_dwarf_addr (dwflmod, address_size, base, base);
9693                   printf ("\n");
9694                 }
9695               break;
9696
9697             case DW_LLE_start_end:
9698               if (address_size == 4)
9699                 {
9700                   if ((uint64_t) (nexthdr - readp) < 8)
9701                     goto invalid_entry;
9702                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
9703                   op2 = read_4ubyte_unaligned_inc (dbg, readp);
9704                 }
9705               else
9706                 {
9707                   if ((uint64_t) (nexthdr - readp) < 16)
9708                     goto invalid_entry;
9709                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
9710                   op2 = read_8ubyte_unaligned_inc (dbg, readp);
9711                 }
9712               printf (" 0x%" PRIx64 "..0x%" PRIx64 "\n", op1, op2);
9713               if (! print_unresolved_addresses)
9714                 {
9715                   printf ("      ");
9716                   print_dwarf_addr (dwflmod, address_size, op1, op1);
9717                   printf ("..\n      ");
9718                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
9719                   printf ("\n");
9720                 }
9721               if ((uint64_t) (nexthdr - readp) < 1)
9722                 goto invalid_entry;
9723               get_uleb128 (len, readp, nexthdr);
9724               if ((uint64_t) (nexthdr - readp) < len)
9725                 goto invalid_entry;
9726               print_ops (dwflmod, dbg, 8, 8, version,
9727                          address_size, offset_size, cu, len, readp);
9728               readp += len;
9729               break;
9730
9731             case DW_LLE_start_length:
9732               if (address_size == 4)
9733                 {
9734                   if ((uint64_t) (nexthdr - readp) < 4)
9735                     goto invalid_entry;
9736                   op1 = read_4ubyte_unaligned_inc (dbg, readp);
9737                 }
9738               else
9739                 {
9740                   if ((uint64_t) (nexthdr - readp) < 8)
9741                     goto invalid_entry;
9742                   op1 = read_8ubyte_unaligned_inc (dbg, readp);
9743                 }
9744               if ((uint64_t) (nexthdr - readp) < 1)
9745                 goto invalid_entry;
9746               get_uleb128 (op2, readp, nexthdr);
9747               printf (" 0x%" PRIx64 ", %" PRIx64 "\n", op1, op2);
9748               if (! print_unresolved_addresses)
9749                 {
9750                   op2 = op1 + op2;
9751                   printf ("      ");
9752                   print_dwarf_addr (dwflmod, address_size, op1, op1);
9753                   printf ("..\n      ");
9754                   print_dwarf_addr (dwflmod, address_size, op2 - 1, op2);
9755                   printf ("\n");
9756                 }
9757               if ((uint64_t) (nexthdr - readp) < 1)
9758                 goto invalid_entry;
9759               get_uleb128 (len, readp, nexthdr);
9760               if ((uint64_t) (nexthdr - readp) < len)
9761                 goto invalid_entry;
9762               print_ops (dwflmod, dbg, 8, 8, version,
9763                          address_size, offset_size, cu, len, readp);
9764               readp += len;
9765               break;
9766
9767             case DW_LLE_GNU_view_pair:
9768               if ((uint64_t) (nexthdr - readp) < 1)
9769                 goto invalid_entry;
9770               get_uleb128 (op1, readp, nexthdr);
9771               if ((uint64_t) (nexthdr - readp) < 1)
9772                 goto invalid_entry;
9773               get_uleb128 (op2, readp, nexthdr);
9774               printf (" %" PRIx64 ", %" PRIx64 "\n", op1, op2);
9775               break;
9776
9777             default:
9778               goto invalid_entry;
9779             }
9780         }
9781
9782     next_table:
9783       if (readp != nexthdr)
9784         {
9785           size_t padding = nexthdr - readp;
9786           printf (_("   %zu padding bytes\n\n"), padding);
9787           readp = nexthdr;
9788         }
9789     }
9790 }
9791
9792
9793 static void
9794 print_debug_loc_section (Dwfl_Module *dwflmod,
9795                          Ebl *ebl, GElf_Ehdr *ehdr,
9796                          Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
9797 {
9798   Elf_Data *data = (dbg->sectiondata[IDX_debug_loc]
9799                     ?: elf_rawdata (scn, NULL));
9800
9801   if (unlikely (data == NULL))
9802     {
9803       error (0, 0, _("cannot get .debug_loc content: %s"),
9804              elf_errmsg (-1));
9805       return;
9806     }
9807
9808   printf (_("\
9809 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
9810           elf_ndxscn (scn), section_name (ebl, shdr),
9811           (uint64_t) shdr->sh_offset);
9812
9813   sort_listptr (&known_locsptr, "loclistptr");
9814   size_t listptr_idx = 0;
9815
9816   uint_fast8_t address_size = ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 4 : 8;
9817   uint_fast8_t offset_size = 4;
9818
9819   bool first = true;
9820   Dwarf_Addr base = 0;
9821   unsigned char *readp = data->d_buf;
9822   unsigned char *const endp = (unsigned char *) data->d_buf + data->d_size;
9823   Dwarf_CU *last_cu = NULL;
9824   while (readp < endp)
9825     {
9826       ptrdiff_t offset = readp - (unsigned char *) data->d_buf;
9827       Dwarf_CU *cu = last_cu;
9828       unsigned int attr = 0;
9829
9830       if (first && skip_listptr_hole (&known_locsptr, &listptr_idx,
9831                                       &address_size, &offset_size, &base,
9832                                       &cu, offset, &readp, endp, &attr))
9833         continue;
9834
9835       if (last_cu != cu)
9836        {
9837         Dwarf_Die cudie;
9838         if (dwarf_cu_die (cu, &cudie,
9839                           NULL, NULL, NULL, NULL,
9840                           NULL, NULL) == NULL)
9841           printf (_("\n Unknown CU base: "));
9842         else
9843           printf (_("\n CU [%6" PRIx64 "] base: "),
9844                   dwarf_dieoffset (&cudie));
9845         print_dwarf_addr (dwflmod, address_size, base, base);
9846         printf ("\n");
9847        }
9848       last_cu = cu;
9849
9850       if (attr == DW_AT_GNU_locviews)
9851         {
9852           Dwarf_Off next_off = next_listptr_offset (&known_locsptr,
9853                                                     &listptr_idx, offset);
9854           const unsigned char *locp = readp;
9855           const unsigned char *locendp;
9856           if (next_off == 0
9857               || next_off > (size_t) (endp
9858                                       - (const unsigned char *) data->d_buf))
9859             locendp = endp;
9860           else
9861             locendp = (const unsigned char *) data->d_buf + next_off;
9862
9863           while (locp < locendp)
9864             {
9865               uint64_t v1, v2;
9866               get_uleb128 (v1, locp, locendp);
9867               if (locp >= locendp)
9868                 {
9869                   printf (_(" [%6tx]  <INVALID DATA>\n"), offset);
9870                   break;
9871                 }
9872               get_uleb128 (v2, locp, locendp);
9873               if (first)                /* First view pair in a list.  */
9874                 printf (" [%6tx] ", offset);
9875               else
9876                 printf ("          ");
9877               printf ("view pair %" PRId64 ", %" PRId64 "\n", v1, v2);
9878               first = false;
9879             }
9880
9881           first = true;
9882           readp = (unsigned char *) locendp;
9883           continue;
9884         }
9885
9886       /* GNU DebugFission encoded addresses as addrx.  */
9887       bool is_debugfission = ((cu != NULL
9888                                || split_dwarf_cu_base (dbg, &cu, &base))
9889                               && (cu->version < 5
9890                                   && cu->unit_type == DW_UT_split_compile));
9891       if (!is_debugfission
9892           && unlikely (data->d_size - offset < (size_t) address_size * 2))
9893         {
9894         invalid_data:
9895           printf (_(" [%6tx]  <INVALID DATA>\n"), offset);
9896           break;
9897         }
9898
9899       Dwarf_Addr begin;
9900       Dwarf_Addr end;
9901       bool use_base = true;
9902       if (is_debugfission)
9903         {
9904           const unsigned char *locp = readp;
9905           const unsigned char *locendp = readp + data->d_size;
9906           if (locp >= locendp)
9907             goto invalid_data;
9908
9909           Dwarf_Word idx;
9910           unsigned char code = *locp++;
9911           switch (code)
9912             {
9913             case DW_LLE_GNU_end_of_list_entry:
9914               begin = 0;
9915               end = 0;
9916               break;
9917
9918             case DW_LLE_GNU_base_address_selection_entry:
9919               if (locp >= locendp)
9920                 goto invalid_data;
9921               begin = (Dwarf_Addr) -1;
9922               get_uleb128 (idx, locp, locendp);
9923               if (get_indexed_addr (cu, idx, &end) != 0)
9924                 end = idx; /* ... */
9925               break;
9926
9927             case DW_LLE_GNU_start_end_entry:
9928               if (locp >= locendp)
9929                 goto invalid_data;
9930               get_uleb128 (idx, locp, locendp);
9931               if (get_indexed_addr (cu, idx, &begin) != 0)
9932                 begin = idx; /* ... */
9933               if (locp >= locendp)
9934                 goto invalid_data;
9935               get_uleb128 (idx, locp, locendp);
9936               if (get_indexed_addr (cu, idx, &end) != 0)
9937                 end = idx; /* ... */
9938               use_base = false;
9939               break;
9940
9941             case DW_LLE_GNU_start_length_entry:
9942               if (locp >= locendp)
9943                 goto invalid_data;
9944               get_uleb128 (idx, locp, locendp);
9945               if (get_indexed_addr (cu, idx, &begin) != 0)
9946                 begin = idx; /* ... */
9947               if (locendp - locp < 4)
9948                 goto invalid_data;
9949               end = read_4ubyte_unaligned_inc (dbg, locp);
9950               end += begin;
9951               use_base = false;
9952               break;
9953
9954             default:
9955                 goto invalid_data;
9956             }
9957
9958           readp = (unsigned char *) locp;
9959         }
9960       else if (address_size == 8)
9961         {
9962           begin = read_8ubyte_unaligned_inc (dbg, readp);
9963           end = read_8ubyte_unaligned_inc (dbg, readp);
9964         }
9965       else
9966         {
9967           begin = read_4ubyte_unaligned_inc (dbg, readp);
9968           end = read_4ubyte_unaligned_inc (dbg, readp);
9969           if (begin == (Dwarf_Addr) (uint32_t) -1)
9970             begin = (Dwarf_Addr) -1l;
9971         }
9972
9973       if (begin == (Dwarf_Addr) -1l) /* Base address entry.  */
9974         {
9975           if (first)
9976             printf (" [%6tx] ", offset);
9977           else
9978             printf ("          ");
9979           puts (_("base address"));
9980           printf ("          ");
9981           print_dwarf_addr (dwflmod, address_size, end, end);
9982           printf ("\n");
9983           base = end;
9984           first = false;
9985         }
9986       else if (begin == 0 && end == 0) /* End of list entry.  */
9987         {
9988           if (first)
9989             printf (_(" [%6tx] empty list\n"), offset);
9990           first = true;
9991         }
9992       else
9993         {
9994           /* We have a location expression entry.  */
9995           uint_fast16_t len = read_2ubyte_unaligned_inc (dbg, readp);
9996
9997           if (first)            /* First entry in a list.  */
9998             printf (" [%6tx] ", offset);
9999           else
10000             printf ("          ");
10001
10002           printf ("range %" PRIx64 ", %" PRIx64 "\n", begin, end);
10003           if (! print_unresolved_addresses)
10004             {
10005               Dwarf_Addr dab = use_base ? base + begin : begin;
10006               Dwarf_Addr dae = use_base ? base + end : end;
10007               printf ("          ");
10008               print_dwarf_addr (dwflmod, address_size, dab, dab);
10009               printf ("..\n          ");
10010               print_dwarf_addr (dwflmod, address_size, dae - 1, dae);
10011               printf ("\n");
10012             }
10013
10014           if (endp - readp <= (ptrdiff_t) len)
10015             {
10016               fputs (_("   <INVALID DATA>\n"), stdout);
10017               break;
10018             }
10019
10020           print_ops (dwflmod, dbg, 11, 11,
10021                      cu != NULL ? cu->version : 3,
10022                      address_size, offset_size, cu, len, readp);
10023
10024           first = false;
10025           readp += len;
10026         }
10027     }
10028 }
10029
10030 struct mac_culist
10031 {
10032   Dwarf_Die die;
10033   Dwarf_Off offset;
10034   Dwarf_Files *files;
10035   struct mac_culist *next;
10036 };
10037
10038
10039 static int
10040 mac_compare (const void *p1, const void *p2)
10041 {
10042   struct mac_culist *m1 = (struct mac_culist *) p1;
10043   struct mac_culist *m2 = (struct mac_culist *) p2;
10044
10045   if (m1->offset < m2->offset)
10046     return -1;
10047   if (m1->offset > m2->offset)
10048     return 1;
10049   return 0;
10050 }
10051
10052
10053 static void
10054 print_debug_macinfo_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
10055                              Ebl *ebl,
10056                              GElf_Ehdr *ehdr __attribute__ ((unused)),
10057                              Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
10058 {
10059   printf (_("\
10060 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
10061           elf_ndxscn (scn), section_name (ebl, shdr),
10062           (uint64_t) shdr->sh_offset);
10063   putc_unlocked ('\n', stdout);
10064
10065   /* There is no function in libdw to iterate over the raw content of
10066      the section but it is easy enough to do.  */
10067   Elf_Data *data = (dbg->sectiondata[IDX_debug_macinfo]
10068                     ?: elf_rawdata (scn, NULL));
10069   if (unlikely (data == NULL))
10070     {
10071       error (0, 0, _("cannot get macro information section data: %s"),
10072              elf_errmsg (-1));
10073       return;
10074     }
10075
10076   /* Get the source file information for all CUs.  */
10077   Dwarf_Off offset;
10078   Dwarf_Off ncu = 0;
10079   size_t hsize;
10080   struct mac_culist *culist = NULL;
10081   size_t nculist = 0;
10082   while (dwarf_nextcu (dbg, offset = ncu, &ncu, &hsize, NULL, NULL, NULL) == 0)
10083     {
10084       Dwarf_Die cudie;
10085       if (dwarf_offdie (dbg, offset + hsize, &cudie) == NULL)
10086         continue;
10087
10088       Dwarf_Attribute attr;
10089       if (dwarf_attr (&cudie, DW_AT_macro_info, &attr) == NULL)
10090         continue;
10091
10092       Dwarf_Word macoff;
10093       if (dwarf_formudata (&attr, &macoff) != 0)
10094         continue;
10095
10096       struct mac_culist *newp = (struct mac_culist *) alloca (sizeof (*newp));
10097       newp->die = cudie;
10098       newp->offset = macoff;
10099       newp->files = NULL;
10100       newp->next = culist;
10101       culist = newp;
10102       ++nculist;
10103     }
10104
10105   /* Convert the list into an array for easier consumption.  */
10106   struct mac_culist *cus = (struct mac_culist *) alloca ((nculist + 1)
10107                                                          * sizeof (*cus));
10108   /* Add sentinel.  */
10109   cus[nculist].offset = data->d_size;
10110   cus[nculist].files = (Dwarf_Files *) -1l;
10111   if (nculist > 0)
10112     {
10113       for (size_t cnt = nculist - 1; culist != NULL; --cnt)
10114         {
10115           assert (cnt < nculist);
10116           cus[cnt] = *culist;
10117           culist = culist->next;
10118         }
10119
10120       /* Sort the array according to the offset in the .debug_macinfo
10121          section.  Note we keep the sentinel at the end.  */
10122       qsort (cus, nculist, sizeof (*cus), mac_compare);
10123     }
10124
10125   const unsigned char *readp = (const unsigned char *) data->d_buf;
10126   const unsigned char *readendp = readp + data->d_size;
10127   int level = 1;
10128
10129   while (readp < readendp)
10130     {
10131       unsigned int opcode = *readp++;
10132       unsigned int u128;
10133       unsigned int u128_2;
10134       const unsigned char *endp;
10135
10136       switch (opcode)
10137         {
10138         case DW_MACINFO_define:
10139         case DW_MACINFO_undef:
10140         case DW_MACINFO_vendor_ext:
10141           /*  For the first two opcodes the parameters are
10142                 line, string
10143               For the latter
10144                 number, string.
10145               We can treat these cases together.  */
10146           get_uleb128 (u128, readp, readendp);
10147
10148           endp = memchr (readp, '\0', readendp - readp);
10149           if (unlikely (endp == NULL))
10150             {
10151               printf (_("\
10152 %*s*** non-terminated string at end of section"),
10153                       level, "");
10154               return;
10155             }
10156
10157           if (opcode == DW_MACINFO_define)
10158             printf ("%*s#define %s, line %u\n",
10159                     level, "", (char *) readp, u128);
10160           else if (opcode == DW_MACINFO_undef)
10161             printf ("%*s#undef %s, line %u\n",
10162                     level, "", (char *) readp, u128);
10163           else
10164             printf (" #vendor-ext %s, number %u\n", (char *) readp, u128);
10165
10166           readp = endp + 1;
10167           break;
10168
10169         case DW_MACINFO_start_file:
10170           /* The two parameters are line and file index, in this order.  */
10171           get_uleb128 (u128, readp, readendp);
10172           if (readendp - readp < 1)
10173             {
10174               printf (_("\
10175 %*s*** missing DW_MACINFO_start_file argument at end of section"),
10176                       level, "");
10177               return;
10178             }
10179           get_uleb128 (u128_2, readp, readendp);
10180
10181           /* Find the CU DIE for this file.  */
10182           size_t macoff = readp - (const unsigned char *) data->d_buf;
10183           const char *fname = "???";
10184           if (macoff >= cus[0].offset && cus[0].offset != data->d_size)
10185             {
10186               while (macoff >= cus[1].offset && cus[1].offset != data->d_size)
10187                 ++cus;
10188
10189               if (cus[0].files == NULL
10190                   && dwarf_getsrcfiles (&cus[0].die, &cus[0].files, NULL) != 0)
10191                 cus[0].files = (Dwarf_Files *) -1l;
10192
10193               if (cus[0].files != (Dwarf_Files *) -1l)
10194                 fname = (dwarf_filesrc (cus[0].files, u128_2, NULL, NULL)
10195                          ?: "???");
10196             }
10197
10198           printf ("%*sstart_file %u, [%u] %s\n",
10199                   level, "", u128, u128_2, fname);
10200           ++level;
10201           break;
10202
10203         case DW_MACINFO_end_file:
10204           --level;
10205           printf ("%*send_file\n", level, "");
10206           /* Nothing more to do.  */
10207           break;
10208
10209         default:
10210           // XXX gcc seems to generate files with a trailing zero.
10211           if (unlikely (opcode != 0 || readp != readendp))
10212             printf ("%*s*** invalid opcode %u\n", level, "", opcode);
10213           break;
10214         }
10215     }
10216 }
10217
10218
10219 static void
10220 print_debug_macro_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
10221                            Ebl *ebl,
10222                            GElf_Ehdr *ehdr __attribute__ ((unused)),
10223                            Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
10224 {
10225   printf (_("\
10226 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
10227           elf_ndxscn (scn), section_name (ebl, shdr),
10228           (uint64_t) shdr->sh_offset);
10229   putc_unlocked ('\n', stdout);
10230
10231   Elf_Data *data =  elf_getdata (scn, NULL);
10232   if (unlikely (data == NULL))
10233     {
10234       error (0, 0, _("cannot get macro information section data: %s"),
10235              elf_errmsg (-1));
10236       return;
10237     }
10238
10239   /* Get the source file information for all CUs.  Uses same
10240      datastructure as macinfo.  But uses offset field to directly
10241      match .debug_line offset.  And just stored in a list.  */
10242   Dwarf_Off offset;
10243   Dwarf_Off ncu = 0;
10244   size_t hsize;
10245   struct mac_culist *culist = NULL;
10246   size_t nculist = 0;
10247   while (dwarf_nextcu (dbg, offset = ncu, &ncu, &hsize, NULL, NULL, NULL) == 0)
10248     {
10249       Dwarf_Die cudie;
10250       if (dwarf_offdie (dbg, offset + hsize, &cudie) == NULL)
10251         continue;
10252
10253       Dwarf_Attribute attr;
10254       if (dwarf_attr (&cudie, DW_AT_stmt_list, &attr) == NULL)
10255         continue;
10256
10257       Dwarf_Word lineoff;
10258       if (dwarf_formudata (&attr, &lineoff) != 0)
10259         continue;
10260
10261       struct mac_culist *newp = (struct mac_culist *) alloca (sizeof (*newp));
10262       newp->die = cudie;
10263       newp->offset = lineoff;
10264       newp->files = NULL;
10265       newp->next = culist;
10266       culist = newp;
10267       ++nculist;
10268     }
10269
10270   const unsigned char *readp = (const unsigned char *) data->d_buf;
10271   const unsigned char *readendp = readp + data->d_size;
10272
10273   while (readp < readendp)
10274     {
10275       printf (_(" Offset:             0x%" PRIx64 "\n"),
10276               (uint64_t) (readp - (const unsigned char *) data->d_buf));
10277
10278       // Header, 2 byte version, 1 byte flag, optional .debug_line offset,
10279       // optional vendor extension macro entry table.
10280       if (readp + 2 > readendp)
10281         {
10282         invalid_data:
10283           error (0, 0, _("invalid data"));
10284           return;
10285         }
10286       const uint16_t vers = read_2ubyte_unaligned_inc (dbg, readp);
10287       printf (_(" Version:            %" PRIu16 "\n"), vers);
10288
10289       // Version 4 is the GNU extension for DWARF4.  DWARF5 will use version
10290       // 5 when it gets standardized.
10291       if (vers != 4 && vers != 5)
10292         {
10293           printf (_("  unknown version, cannot parse section\n"));
10294           return;
10295         }
10296
10297       if (readp + 1 > readendp)
10298         goto invalid_data;
10299       const unsigned char flag = *readp++;
10300       printf (_(" Flag:               0x%" PRIx8), flag);
10301       if (flag != 0)
10302         {
10303           printf (" (");
10304           if ((flag & 0x01) != 0)
10305             {
10306               printf ("offset_size");
10307               if ((flag & 0xFE) !=  0)
10308                 printf (", ");
10309             }
10310           if ((flag & 0x02) != 0)
10311             {
10312               printf ("debug_line_offset");
10313               if ((flag & 0xFC) !=  0)
10314                 printf (", ");
10315             }
10316           if ((flag & 0x04) != 0)
10317             {
10318               printf ("operands_table");
10319               if ((flag & 0xF8) !=  0)
10320                 printf (", ");
10321             }
10322           if ((flag & 0xF8) != 0)
10323             printf ("unknown");
10324           printf (")");
10325         }
10326       printf ("\n");
10327
10328       unsigned int offset_len = (flag & 0x01) ? 8 : 4;
10329       printf (_(" Offset length:      %" PRIu8 "\n"), offset_len);
10330       Dwarf_Off line_offset = -1;
10331       if (flag & 0x02)
10332         {
10333           if (offset_len == 8)
10334             line_offset = read_8ubyte_unaligned_inc (dbg, readp);
10335           else
10336             line_offset = read_4ubyte_unaligned_inc (dbg, readp);
10337           printf (_(" .debug_line offset: 0x%" PRIx64 "\n"),
10338                   line_offset);
10339         }
10340
10341       struct mac_culist *cu = NULL;
10342       if (line_offset != (Dwarf_Off) -1)
10343         {
10344           cu = culist;
10345           while (cu != NULL && line_offset != cu->offset)
10346             cu = cu->next;
10347         }
10348
10349       Dwarf_Off str_offsets_base = str_offsets_base_off (dbg, (cu != NULL
10350                                                                ? cu->die.cu
10351                                                                : NULL));
10352
10353       const unsigned char *vendor[DW_MACRO_hi_user - DW_MACRO_lo_user + 1];
10354       memset (vendor, 0, sizeof vendor);
10355       if (flag & 0x04)
10356         {
10357           // 1 byte length, for each item, 1 byte opcode, uleb128 number
10358           // of arguments, for each argument 1 byte form code.
10359           if (readp + 1 > readendp)
10360             goto invalid_data;
10361           unsigned int tlen = *readp++;
10362           printf (_("  extension opcode table, %" PRIu8 " items:\n"),
10363                   tlen);
10364           for (unsigned int i = 0; i < tlen; i++)
10365             {
10366               if (readp + 1 > readendp)
10367                 goto invalid_data;
10368               unsigned int opcode = *readp++;
10369               printf (_("    [%" PRIx8 "]"), opcode);
10370               if (opcode < DW_MACRO_lo_user
10371                   || opcode > DW_MACRO_hi_user)
10372                 goto invalid_data;
10373               // Record the start of description for this vendor opcode.
10374               // uleb128 nr args, 1 byte per arg form.
10375               vendor[opcode - DW_MACRO_lo_user] = readp;
10376               if (readp + 1 > readendp)
10377                 goto invalid_data;
10378               unsigned int args = *readp++;
10379               if (args > 0)
10380                 {
10381                   printf (_(" %" PRIu8 " arguments:"), args);
10382                   while (args > 0)
10383                     {
10384                       if (readp + 1 > readendp)
10385                         goto invalid_data;
10386                       unsigned int form = *readp++;
10387                       printf (" %s", dwarf_form_name (form));
10388                       if (! libdw_valid_user_form (form))
10389                         goto invalid_data;
10390                       args--;
10391                       if (args > 0)
10392                         putchar_unlocked (',');
10393                     }
10394                 }
10395               else
10396                 printf (_(" no arguments."));
10397               putchar_unlocked ('\n');
10398             }
10399         }
10400       putchar_unlocked ('\n');
10401
10402       int level = 1;
10403       if (readp + 1 > readendp)
10404         goto invalid_data;
10405       unsigned int opcode = *readp++;
10406       while (opcode != 0)
10407         {
10408           unsigned int u128;
10409           unsigned int u128_2;
10410           const unsigned char *endp;
10411           uint64_t off;
10412
10413           switch (opcode)
10414             {
10415             case DW_MACRO_start_file:
10416               get_uleb128 (u128, readp, readendp);
10417               if (readp >= readendp)
10418                 goto invalid_data;
10419               get_uleb128 (u128_2, readp, readendp);
10420
10421               /* Find the CU DIE that matches this line offset.  */
10422               const char *fname = "???";
10423               if (cu != NULL)
10424                 {
10425                   if (cu->files == NULL
10426                       && dwarf_getsrcfiles (&cu->die, &cu->files,
10427                                             NULL) != 0)
10428                     cu->files = (Dwarf_Files *) -1l;
10429
10430                   if (cu->files != (Dwarf_Files *) -1l)
10431                     fname = (dwarf_filesrc (cu->files, u128_2,
10432                                             NULL, NULL) ?: "???");
10433                 }
10434               printf ("%*sstart_file %u, [%u] %s\n",
10435                       level, "", u128, u128_2, fname);
10436               ++level;
10437               break;
10438
10439             case DW_MACRO_end_file:
10440               --level;
10441               printf ("%*send_file\n", level, "");
10442               break;
10443
10444             case DW_MACRO_define:
10445               get_uleb128 (u128, readp, readendp);
10446               endp = memchr (readp, '\0', readendp - readp);
10447               if (endp == NULL)
10448                 goto invalid_data;
10449               printf ("%*s#define %s, line %u\n",
10450                       level, "", readp, u128);
10451               readp = endp + 1;
10452               break;
10453
10454             case DW_MACRO_undef:
10455               get_uleb128 (u128, readp, readendp);
10456               endp = memchr (readp, '\0', readendp - readp);
10457               if (endp == NULL)
10458                 goto invalid_data;
10459               printf ("%*s#undef %s, line %u\n",
10460                       level, "", readp, u128);
10461               readp = endp + 1;
10462               break;
10463
10464             case DW_MACRO_define_strp:
10465               get_uleb128 (u128, readp, readendp);
10466               if (readp + offset_len > readendp)
10467                 goto invalid_data;
10468               if (offset_len == 8)
10469                 off = read_8ubyte_unaligned_inc (dbg, readp);
10470               else
10471                 off = read_4ubyte_unaligned_inc (dbg, readp);
10472               printf ("%*s#define %s, line %u (indirect)\n",
10473                       level, "", dwarf_getstring (dbg, off, NULL), u128);
10474               break;
10475
10476             case DW_MACRO_undef_strp:
10477               get_uleb128 (u128, readp, readendp);
10478               if (readp + offset_len > readendp)
10479                 goto invalid_data;
10480               if (offset_len == 8)
10481                 off = read_8ubyte_unaligned_inc (dbg, readp);
10482               else
10483                 off = read_4ubyte_unaligned_inc (dbg, readp);
10484               printf ("%*s#undef %s, line %u (indirect)\n",
10485                       level, "", dwarf_getstring (dbg, off, NULL), u128);
10486               break;
10487
10488             case DW_MACRO_import:
10489               if (readp + offset_len > readendp)
10490                 goto invalid_data;
10491               if (offset_len == 8)
10492                 off = read_8ubyte_unaligned_inc (dbg, readp);
10493               else
10494                 off = read_4ubyte_unaligned_inc (dbg, readp);
10495               printf ("%*s#include offset 0x%" PRIx64 "\n",
10496                       level, "", off);
10497               break;
10498
10499             case DW_MACRO_define_sup:
10500               get_uleb128 (u128, readp, readendp);
10501               if (readp + offset_len > readendp)
10502                 goto invalid_data;
10503               printf ("%*s#define ", level, "");
10504               readp =  print_form_data (dbg, DW_FORM_strp_sup,
10505                                         readp, readendp, offset_len,
10506                                         str_offsets_base);
10507               printf (", line %u (sup)\n", u128);
10508               break;
10509
10510             case DW_MACRO_undef_sup:
10511               get_uleb128 (u128, readp, readendp);
10512               if (readp + offset_len > readendp)
10513                 goto invalid_data;
10514               printf ("%*s#undef ", level, "");
10515               readp =  print_form_data (dbg, DW_FORM_strp_sup,
10516                                         readp, readendp, offset_len,
10517                                         str_offsets_base);
10518               printf (", line %u (sup)\n", u128);
10519               break;
10520
10521             case DW_MACRO_import_sup:
10522               if (readp + offset_len > readendp)
10523                 goto invalid_data;
10524               if (offset_len == 8)
10525                 off = read_8ubyte_unaligned_inc (dbg, readp);
10526               else
10527                 off = read_4ubyte_unaligned_inc (dbg, readp);
10528               // XXX Needs support for reading from supplementary object file.
10529               printf ("%*s#include offset 0x%" PRIx64 " (sup)\n",
10530                       level, "", off);
10531               break;
10532
10533             case DW_MACRO_define_strx:
10534               get_uleb128 (u128, readp, readendp);
10535               if (readp + offset_len > readendp)
10536                 goto invalid_data;
10537               printf ("%*s#define ", level, "");
10538               readp =  print_form_data (dbg, DW_FORM_strx,
10539                                         readp, readendp, offset_len,
10540                                         str_offsets_base);
10541               printf (", line %u (strx)\n", u128);
10542               break;
10543
10544             case DW_MACRO_undef_strx:
10545               get_uleb128 (u128, readp, readendp);
10546               if (readp + offset_len > readendp)
10547                 goto invalid_data;
10548               printf ("%*s#undef ", level, "");
10549               readp =  print_form_data (dbg, DW_FORM_strx,
10550                                         readp, readendp, offset_len,
10551                                         str_offsets_base);
10552               printf (", line %u (strx)\n", u128);
10553               break;
10554
10555             default:
10556               printf ("%*svendor opcode 0x%" PRIx8, level, "", opcode);
10557               if (opcode < DW_MACRO_lo_user
10558                   || opcode > DW_MACRO_lo_user
10559                   || vendor[opcode - DW_MACRO_lo_user] == NULL)
10560                 goto invalid_data;
10561
10562               const unsigned char *op_desc;
10563               op_desc = vendor[opcode - DW_MACRO_lo_user];
10564
10565               // Just skip the arguments, we cannot really interpret them,
10566               // but print as much as we can.
10567               unsigned int args = *op_desc++;
10568               while (args > 0 && readp < readendp)
10569                 {
10570                   unsigned int form = *op_desc++;
10571                   readp = print_form_data (dbg, form, readp, readendp,
10572                                            offset_len, str_offsets_base);
10573                   args--;
10574                   if (args > 0)
10575                     printf (", ");
10576                 }
10577               putchar_unlocked ('\n');
10578             }
10579
10580           if (readp + 1 > readendp)
10581             goto invalid_data;
10582           opcode = *readp++;
10583           if (opcode == 0)
10584             putchar_unlocked ('\n');
10585         }
10586     }
10587 }
10588
10589
10590 /* Callback for printing global names.  */
10591 static int
10592 print_pubnames (Dwarf *dbg __attribute__ ((unused)), Dwarf_Global *global,
10593                 void *arg)
10594 {
10595   int *np = (int *) arg;
10596
10597   printf (_(" [%5d] DIE offset: %6" PRId64
10598                    ", CU DIE offset: %6" PRId64 ", name: %s\n"),
10599           (*np)++, global->die_offset, global->cu_offset, global->name);
10600
10601   return 0;
10602 }
10603
10604
10605 /* Print the known exported symbols in the DWARF section '.debug_pubnames'.  */
10606 static void
10607 print_debug_pubnames_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
10608                               Ebl *ebl,
10609                               GElf_Ehdr *ehdr __attribute__ ((unused)),
10610                               Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
10611 {
10612   printf (_("\nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
10613           elf_ndxscn (scn), section_name (ebl, shdr),
10614           (uint64_t) shdr->sh_offset);
10615
10616   int n = 0;
10617   (void) dwarf_getpubnames (dbg, print_pubnames, &n, 0);
10618 }
10619
10620 /* Print the content of the DWARF string section '.debug_str'.  */
10621 static void
10622 print_debug_str_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
10623                          Ebl *ebl,
10624                          GElf_Ehdr *ehdr __attribute__ ((unused)),
10625                          Elf_Scn *scn, GElf_Shdr *shdr,
10626                          Dwarf *dbg __attribute__ ((unused)))
10627 {
10628   Elf_Data *data = elf_rawdata (scn, NULL);
10629   const size_t sh_size = data ? data->d_size : 0;
10630
10631   /* Compute floor(log16(shdr->sh_size)).  */
10632   GElf_Addr tmp = sh_size;
10633   int digits = 1;
10634   while (tmp >= 16)
10635     {
10636       ++digits;
10637       tmp >>= 4;
10638     }
10639   digits = MAX (4, digits);
10640
10641   printf (_("\nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"
10642                    " %*s  String\n"),
10643           elf_ndxscn (scn),
10644           section_name (ebl, shdr), (uint64_t) shdr->sh_offset,
10645           /* TRANS: the debugstr| prefix makes the string unique.  */
10646           digits + 2, sgettext ("debugstr|Offset"));
10647
10648   Dwarf_Off offset = 0;
10649   while (offset < sh_size)
10650     {
10651       size_t len;
10652       const char *str = (const char *) data->d_buf + offset;
10653       const char *endp = memchr (str, '\0', sh_size - offset);
10654       if (unlikely (endp == NULL))
10655         {
10656           printf (_(" *** error, missing string terminator\n"));
10657           break;
10658         }
10659
10660       printf (" [%*" PRIx64 "]  \"%s\"\n", digits, (uint64_t) offset, str);
10661       len = endp - str;
10662       offset += len + 1;
10663     }
10664 }
10665
10666 static void
10667 print_debug_str_offsets_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
10668                                  Ebl *ebl,
10669                                  GElf_Ehdr *ehdr __attribute__ ((unused)),
10670                                  Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
10671 {
10672   printf (_("\
10673 \nDWARF section [%2zu] '%s' at offset %#" PRIx64 ":\n"),
10674           elf_ndxscn (scn), section_name (ebl, shdr),
10675           (uint64_t) shdr->sh_offset);
10676
10677   if (shdr->sh_size == 0)
10678     return;
10679
10680   /* We like to get the section from libdw to make sure they are relocated.  */
10681   Elf_Data *data = (dbg->sectiondata[IDX_debug_str_offsets]
10682                     ?: elf_rawdata (scn, NULL));
10683   if (unlikely (data == NULL))
10684     {
10685       error (0, 0, _("cannot get .debug_str_offsets section data: %s"),
10686              elf_errmsg (-1));
10687       return;
10688     }
10689
10690   size_t idx = 0;
10691   sort_listptr (&known_stroffbases, "str_offsets");
10692
10693   const unsigned char *start = (const unsigned char *) data->d_buf;
10694   const unsigned char *readp = start;
10695   const unsigned char *readendp = ((const unsigned char *) data->d_buf
10696                                    + data->d_size);
10697
10698   while (readp < readendp)
10699     {
10700       /* Most string offset tables will have a header.  For split
10701          dwarf unit GNU DebugFission didn't add one.  But they were
10702          also only defined for split units (main or skeleton units
10703          didn't have indirect strings).  So if we don't have a
10704          DW_AT_str_offsets_base at all and this is offset zero, then
10705          just start printing offsets immediately, if this is a .dwo
10706          section.  */
10707       Dwarf_Off off = (Dwarf_Off) (readp
10708                                    - (const unsigned char *) data->d_buf);
10709
10710       printf ("Table at offset %" PRIx64 " ", off);
10711
10712       struct listptr *listptr = get_listptr (&known_stroffbases, idx++);
10713       const unsigned char *next_unitp = readendp;
10714       uint8_t offset_size;
10715       bool has_header;
10716       if (listptr == NULL)
10717         {
10718           /* This can happen for .dwo files.  There is only an header
10719              in the case this is a version 5 split DWARF file.  */
10720           Dwarf_CU *cu;
10721           uint8_t unit_type;
10722           if (dwarf_get_units (dbg, NULL, &cu, NULL, &unit_type,
10723                                NULL, NULL) != 0)
10724             {
10725               error (0, 0, "Warning: Cannot find any DWARF unit.");
10726               /* Just guess some values.  */
10727               has_header = false;
10728               offset_size = 4;
10729             }
10730           else if (off == 0
10731                    && (unit_type == DW_UT_split_type
10732                        || unit_type == DW_UT_split_compile))
10733             {
10734               has_header = cu->version > 4;
10735               offset_size = cu->offset_size;
10736             }
10737           else
10738             {
10739               error (0, 0,
10740                      "Warning: No CU references .debug_str_offsets after %"
10741                      PRIx64, off);
10742               has_header = cu->version > 4;
10743               offset_size = cu->offset_size;
10744             }
10745           printf ("\n");
10746         }
10747       else
10748         {
10749           /* This must be DWARF5, since GNU DebugFission didn't define
10750              DW_AT_str_offsets_base.  */
10751           has_header = true;
10752
10753           Dwarf_Die cudie;
10754           if (dwarf_cu_die (listptr->cu, &cudie,
10755                             NULL, NULL, NULL, NULL,
10756                             NULL, NULL) == NULL)
10757             printf ("Unknown CU (%s):\n", dwarf_errmsg (-1));
10758           else
10759             printf ("for CU [%6" PRIx64 "]:\n", dwarf_dieoffset (&cudie));
10760         }
10761
10762       if (has_header)
10763         {
10764           uint64_t unit_length;
10765           uint16_t version;
10766           uint16_t padding;
10767
10768           unit_length = read_4ubyte_unaligned_inc (dbg, readp);
10769           if (unlikely (unit_length == 0xffffffff))
10770             {
10771               if (unlikely (readp > readendp - 8))
10772                 {
10773                 invalid_data:
10774                   error (0, 0, "Invalid data");
10775                   return;
10776                 }
10777               unit_length = read_8ubyte_unaligned_inc (dbg, readp);
10778               offset_size = 8;
10779             }
10780           else
10781             offset_size = 4;
10782
10783           printf ("\n");
10784           printf (_(" Length:        %8" PRIu64 "\n"),
10785                   unit_length);
10786           printf (_(" Offset size:   %8" PRIu8 "\n"),
10787                   offset_size);
10788
10789           /* We need at least 2-bytes (version) + 2-bytes (padding) =
10790              4 bytes to complete the header.  And this unit cannot go
10791              beyond the section data.  */
10792           if (readp > readendp - 4
10793               || unit_length < 4
10794               || unit_length > (uint64_t) (readendp - readp))
10795             goto invalid_data;
10796
10797           next_unitp = readp + unit_length;
10798
10799           version = read_2ubyte_unaligned_inc (dbg, readp);
10800           printf (_(" DWARF version: %8" PRIu16 "\n"), version);
10801
10802           if (version != 5)
10803             {
10804               error (0, 0, _("Unknown version"));
10805               goto next_unit;
10806             }
10807
10808           padding = read_2ubyte_unaligned_inc (dbg, readp);
10809           printf (_(" Padding:       %8" PRIx16 "\n"), padding);
10810
10811           if (listptr != NULL
10812               && listptr->offset != (Dwarf_Off) (readp - start))
10813             {
10814               error (0, 0, "String offsets index doesn't start after header");
10815               goto next_unit;
10816             }
10817
10818           printf ("\n");
10819         }
10820
10821       int digits = 1;
10822       size_t offsets = (next_unitp - readp) / offset_size;
10823       while (offsets >= 10)
10824         {
10825           ++digits;
10826           offsets /= 10;
10827         }
10828
10829       unsigned int uidx = 0;
10830       size_t index_offset =  readp - (const unsigned char *) data->d_buf;
10831       printf (" Offsets start at 0x%zx:\n", index_offset);
10832       while (readp <= next_unitp - offset_size)
10833         {
10834           Dwarf_Word offset;
10835           if (offset_size == 4)
10836             offset = read_4ubyte_unaligned_inc (dbg, readp);
10837           else
10838             offset = read_8ubyte_unaligned_inc (dbg, readp);
10839           const char *str = dwarf_getstring (dbg, offset, NULL);
10840           printf (" [%*u] [%*" PRIx64 "]  \"%s\"\n",
10841                   digits, uidx++, (int) offset_size * 2, offset, str ?: "???");
10842         }
10843       printf ("\n");
10844
10845       if (readp != next_unitp)
10846         error (0, 0, "extra %zd bytes at end of unit",
10847                (size_t) (next_unitp - readp));
10848
10849     next_unit:
10850       readp = next_unitp;
10851     }
10852 }
10853
10854
10855 /* Print the content of the call frame search table section
10856    '.eh_frame_hdr'.  */
10857 static void
10858 print_debug_frame_hdr_section (Dwfl_Module *dwflmod __attribute__ ((unused)),
10859                                Ebl *ebl __attribute__ ((unused)),
10860                                GElf_Ehdr *ehdr __attribute__ ((unused)),
10861                                Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
10862 {
10863   printf (_("\
10864 \nCall frame search table section [%2zu] '.eh_frame_hdr':\n"),
10865           elf_ndxscn (scn));
10866
10867   Elf_Data *data = elf_rawdata (scn, NULL);
10868
10869   if (unlikely (data == NULL))
10870     {
10871       error (0, 0, _("cannot get %s content: %s"),
10872              ".eh_frame_hdr", elf_errmsg (-1));
10873       return;
10874     }
10875
10876   const unsigned char *readp = data->d_buf;
10877   const unsigned char *const dataend = ((unsigned char *) data->d_buf
10878                                         + data->d_size);
10879
10880   if (unlikely (readp + 4 > dataend))
10881     {
10882     invalid_data:
10883       error (0, 0, _("invalid data"));
10884       return;
10885     }
10886
10887   unsigned int version = *readp++;
10888   unsigned int eh_frame_ptr_enc = *readp++;
10889   unsigned int fde_count_enc = *readp++;
10890   unsigned int table_enc = *readp++;
10891
10892   printf (" version:          %u\n"
10893           " eh_frame_ptr_enc: %#x ",
10894           version, eh_frame_ptr_enc);
10895   print_encoding_base ("", eh_frame_ptr_enc);
10896   printf (" fde_count_enc:    %#x ", fde_count_enc);
10897   print_encoding_base ("", fde_count_enc);
10898   printf (" table_enc:        %#x ", table_enc);
10899   print_encoding_base ("", table_enc);
10900
10901   uint64_t eh_frame_ptr = 0;
10902   if (eh_frame_ptr_enc != DW_EH_PE_omit)
10903     {
10904       readp = read_encoded (eh_frame_ptr_enc, readp, dataend, &eh_frame_ptr,
10905                             dbg);
10906       if (unlikely (readp == NULL))
10907         goto invalid_data;
10908
10909       printf (" eh_frame_ptr:     %#" PRIx64, eh_frame_ptr);
10910       if ((eh_frame_ptr_enc & 0x70) == DW_EH_PE_pcrel)
10911         printf (" (offset: %#" PRIx64 ")",
10912                 /* +4 because of the 4 byte header of the section.  */
10913                 (uint64_t) shdr->sh_offset + 4 + eh_frame_ptr);
10914
10915       putchar_unlocked ('\n');
10916     }
10917
10918   uint64_t fde_count = 0;
10919   if (fde_count_enc != DW_EH_PE_omit)
10920     {
10921       readp = read_encoded (fde_count_enc, readp, dataend, &fde_count, dbg);
10922       if (unlikely (readp == NULL))
10923         goto invalid_data;
10924
10925       printf (" fde_count:        %" PRIu64 "\n", fde_count);
10926     }
10927
10928   if (fde_count == 0 || table_enc == DW_EH_PE_omit)
10929     return;
10930
10931   puts (" Table:");
10932
10933   /* Optimize for the most common case.  */
10934   if (table_enc == (DW_EH_PE_datarel | DW_EH_PE_sdata4))
10935     while (fde_count > 0 && readp + 8 <= dataend)
10936       {
10937         int32_t initial_location = read_4sbyte_unaligned_inc (dbg, readp);
10938         uint64_t initial_offset = ((uint64_t) shdr->sh_offset
10939                                    + (int64_t) initial_location);
10940         int32_t address = read_4sbyte_unaligned_inc (dbg, readp);
10941         // XXX Possibly print symbol name or section offset for initial_offset
10942         printf ("  %#" PRIx32 " (offset: %#6" PRIx64 ") -> %#" PRIx32
10943                 " fde=[%6" PRIx64 "]\n",
10944                 initial_location, initial_offset,
10945                 address, address - (eh_frame_ptr + 4));
10946       }
10947   else
10948     while (0 && readp < dataend)
10949       {
10950
10951       }
10952 }
10953
10954
10955 /* Print the content of the exception handling table section
10956    '.eh_frame_hdr'.  */
10957 static void
10958 print_debug_exception_table (Dwfl_Module *dwflmod __attribute__ ((unused)),
10959                              Ebl *ebl __attribute__ ((unused)),
10960                              GElf_Ehdr *ehdr __attribute__ ((unused)),
10961                              Elf_Scn *scn,
10962                              GElf_Shdr *shdr __attribute__ ((unused)),
10963                              Dwarf *dbg __attribute__ ((unused)))
10964 {
10965   printf (_("\
10966 \nException handling table section [%2zu] '.gcc_except_table':\n"),
10967           elf_ndxscn (scn));
10968
10969   Elf_Data *data = elf_rawdata (scn, NULL);
10970
10971   if (unlikely (data == NULL))
10972     {
10973       error (0, 0, _("cannot get %s content: %s"),
10974              ".gcc_except_table", elf_errmsg (-1));
10975       return;
10976     }
10977
10978   const unsigned char *readp = data->d_buf;
10979   const unsigned char *const dataend = readp + data->d_size;
10980
10981   if (unlikely (readp + 1 > dataend))
10982     {
10983     invalid_data:
10984       error (0, 0, _("invalid data"));
10985       return;
10986     }
10987   unsigned int lpstart_encoding = *readp++;
10988   printf (_(" LPStart encoding:    %#x "), lpstart_encoding);
10989   print_encoding_base ("", lpstart_encoding);
10990   if (lpstart_encoding != DW_EH_PE_omit)
10991     {
10992       uint64_t lpstart;
10993       readp = read_encoded (lpstart_encoding, readp, dataend, &lpstart, dbg);
10994       printf (" LPStart:             %#" PRIx64 "\n", lpstart);
10995     }
10996
10997   if (unlikely (readp + 1 > dataend))
10998     goto invalid_data;
10999   unsigned int ttype_encoding = *readp++;
11000   printf (_(" TType encoding:      %#x "), ttype_encoding);
11001   print_encoding_base ("", ttype_encoding);
11002   const unsigned char *ttype_base = NULL;
11003   if (ttype_encoding != DW_EH_PE_omit)
11004     {
11005       unsigned int ttype_base_offset;
11006       get_uleb128 (ttype_base_offset, readp, dataend);
11007       printf (" TType base offset:   %#x\n", ttype_base_offset);
11008       if ((size_t) (dataend - readp) > ttype_base_offset)
11009         ttype_base = readp + ttype_base_offset;
11010     }
11011
11012   if (unlikely (readp + 1 > dataend))
11013     goto invalid_data;
11014   unsigned int call_site_encoding = *readp++;
11015   printf (_(" Call site encoding:  %#x "), call_site_encoding);
11016   print_encoding_base ("", call_site_encoding);
11017   unsigned int call_site_table_len;
11018   get_uleb128 (call_site_table_len, readp, dataend);
11019
11020   const unsigned char *const action_table = readp + call_site_table_len;
11021   if (unlikely (action_table > dataend))
11022     goto invalid_data;
11023   unsigned int u = 0;
11024   unsigned int max_action = 0;
11025   while (readp < action_table)
11026     {
11027       if (u == 0)
11028         puts (_("\n Call site table:"));
11029
11030       uint64_t call_site_start;
11031       readp = read_encoded (call_site_encoding, readp, dataend,
11032                             &call_site_start, dbg);
11033       uint64_t call_site_length;
11034       readp = read_encoded (call_site_encoding, readp, dataend,
11035                             &call_site_length, dbg);
11036       uint64_t landing_pad;
11037       readp = read_encoded (call_site_encoding, readp, dataend,
11038                             &landing_pad, dbg);
11039       unsigned int action;
11040       get_uleb128 (action, readp, dataend);
11041       max_action = MAX (action, max_action);
11042       printf (_(" [%4u] Call site start:   %#" PRIx64 "\n"
11043                        "        Call site length:  %" PRIu64 "\n"
11044                        "        Landing pad:       %#" PRIx64 "\n"
11045                        "        Action:            %u\n"),
11046               u++, call_site_start, call_site_length, landing_pad, action);
11047     }
11048   if (readp != action_table)
11049     goto invalid_data;
11050
11051   unsigned int max_ar_filter = 0;
11052   if (max_action > 0)
11053     {
11054       puts ("\n Action table:");
11055
11056       size_t maxdata = (size_t) (dataend - action_table);
11057       if (max_action > maxdata || maxdata - max_action < 1)
11058         {
11059         invalid_action_table:
11060           fputs (_("   <INVALID DATA>\n"), stdout);
11061           return;
11062         }
11063
11064       const unsigned char *const action_table_end
11065         = action_table + max_action + 1;
11066
11067       u = 0;
11068       do
11069         {
11070           int ar_filter;
11071           get_sleb128 (ar_filter, readp, action_table_end);
11072           if (ar_filter > 0 && (unsigned int) ar_filter > max_ar_filter)
11073             max_ar_filter = ar_filter;
11074           int ar_disp;
11075           if (readp >= action_table_end)
11076             goto invalid_action_table;
11077           get_sleb128 (ar_disp, readp, action_table_end);
11078
11079           printf (" [%4u] ar_filter:  % d\n"
11080                   "        ar_disp:    % -5d",
11081                   u, ar_filter, ar_disp);
11082           if (abs (ar_disp) & 1)
11083             printf (" -> [%4u]\n", u + (ar_disp + 1) / 2);
11084           else if (ar_disp != 0)
11085             puts (" -> ???");
11086           else
11087             putchar_unlocked ('\n');
11088           ++u;
11089         }
11090       while (readp < action_table_end);
11091     }
11092
11093   if (max_ar_filter > 0 && ttype_base != NULL)
11094     {
11095       unsigned char dsize;
11096       puts ("\n TType table:");
11097
11098       // XXX Not *4, size of encoding;
11099       switch (ttype_encoding & 7)
11100         {
11101         case DW_EH_PE_udata2:
11102         case DW_EH_PE_sdata2:
11103           dsize = 2;
11104           break;
11105         case DW_EH_PE_udata4:
11106         case DW_EH_PE_sdata4:
11107           dsize = 4;
11108           break;
11109         case DW_EH_PE_udata8:
11110         case DW_EH_PE_sdata8:
11111           dsize = 8;
11112           break;
11113         default:
11114           dsize = 0;
11115           error (1, 0, _("invalid TType encoding"));
11116         }
11117
11118       if (max_ar_filter
11119           > (size_t) (ttype_base - (const unsigned char *) data->d_buf) / dsize)
11120         goto invalid_data;
11121
11122       readp = ttype_base - max_ar_filter * dsize;
11123       do
11124         {
11125           uint64_t ttype;
11126           readp = read_encoded (ttype_encoding, readp, ttype_base, &ttype,
11127                                 dbg);
11128           printf (" [%4u] %#" PRIx64 "\n", max_ar_filter--, ttype);
11129         }
11130       while (readp < ttype_base);
11131     }
11132 }
11133
11134 /* Print the content of the '.gdb_index' section.
11135    http://sourceware.org/gdb/current/onlinedocs/gdb/Index-Section-Format.html
11136 */
11137 static void
11138 print_gdb_index_section (Dwfl_Module *dwflmod, Ebl *ebl,
11139                          GElf_Ehdr *ehdr __attribute__ ((unused)),
11140                          Elf_Scn *scn, GElf_Shdr *shdr, Dwarf *dbg)
11141 {
11142   printf (_("\nGDB section [%2zu] '%s' at offset %#" PRIx64
11143                    " contains %" PRId64 " bytes :\n"),
11144           elf_ndxscn (scn), section_name (ebl, shdr),
11145           (uint64_t) shdr->sh_offset, (uint64_t) shdr->sh_size);
11146
11147   Elf_Data *data = elf_rawdata (scn, NULL);
11148
11149   if (unlikely (data == NULL))
11150     {
11151       error (0, 0, _("cannot get %s content: %s"),
11152              ".gdb_index", elf_errmsg (-1));
11153       return;
11154     }
11155
11156   // .gdb_index is always in little endian.
11157   Dwarf dummy_dbg = { .other_byte_order = MY_ELFDATA != ELFDATA2LSB };
11158   dbg = &dummy_dbg;
11159
11160   const unsigned char *readp = data->d_buf;
11161   const unsigned char *const dataend = readp + data->d_size;
11162
11163   if (unlikely (readp + 4 > dataend))
11164     {
11165     invalid_data:
11166       error (0, 0, _("invalid data"));
11167       return;
11168     }
11169
11170   int32_t vers = read_4ubyte_unaligned (dbg, readp);
11171   printf (_(" Version:         %" PRId32 "\n"), vers);
11172
11173   // The only difference between version 4 and version 5 is the
11174   // hash used for generating the table.  Version 6 contains symbols
11175   // for inlined functions, older versions didn't.  Version 7 adds
11176   // symbol kinds.  Version 8 just indicates that it correctly includes
11177   // TUs for symbols.
11178   if (vers < 4 || vers > 8)
11179     {
11180       printf (_("  unknown version, cannot parse section\n"));
11181       return;
11182     }
11183
11184   readp += 4;
11185   if (unlikely (readp + 4 > dataend))
11186     goto invalid_data;
11187
11188   uint32_t cu_off = read_4ubyte_unaligned (dbg, readp);
11189   printf (_(" CU offset:       %#" PRIx32 "\n"), cu_off);
11190
11191   readp += 4;
11192   if (unlikely (readp + 4 > dataend))
11193     goto invalid_data;
11194
11195   uint32_t tu_off = read_4ubyte_unaligned (dbg, readp);
11196   printf (_(" TU offset:       %#" PRIx32 "\n"), tu_off);
11197
11198   readp += 4;
11199   if (unlikely (readp + 4 > dataend))
11200     goto invalid_data;
11201
11202   uint32_t addr_off = read_4ubyte_unaligned (dbg, readp);
11203   printf (_(" address offset:  %#" PRIx32 "\n"), addr_off);
11204
11205   readp += 4;
11206   if (unlikely (readp + 4 > dataend))
11207     goto invalid_data;
11208
11209   uint32_t sym_off = read_4ubyte_unaligned (dbg, readp);
11210   printf (_(" symbol offset:   %#" PRIx32 "\n"), sym_off);
11211
11212   readp += 4;
11213   if (unlikely (readp + 4 > dataend))
11214     goto invalid_data;
11215
11216   uint32_t const_off = read_4ubyte_unaligned (dbg, readp);
11217   printf (_(" constant offset: %#" PRIx32 "\n"), const_off);
11218
11219   if (unlikely ((size_t) (dataend - (const unsigned char *) data->d_buf)
11220                 < const_off))
11221     goto invalid_data;
11222
11223   readp = data->d_buf + cu_off;
11224
11225   const unsigned char *nextp = data->d_buf + tu_off;
11226   if (tu_off >= data->d_size)
11227     goto invalid_data;
11228
11229   size_t cu_nr = (nextp - readp) / 16;
11230
11231   printf (_("\n CU list at offset %#" PRIx32
11232                    " contains %zu entries:\n"),
11233           cu_off, cu_nr);
11234
11235   size_t n = 0;
11236   while (dataend - readp >= 16 && n < cu_nr)
11237     {
11238       uint64_t off = read_8ubyte_unaligned (dbg, readp);
11239       readp += 8;
11240
11241       uint64_t len = read_8ubyte_unaligned (dbg, readp);
11242       readp += 8;
11243
11244       printf (" [%4zu] start: %0#8" PRIx64
11245               ", length: %5" PRIu64 "\n", n, off, len);
11246       n++;
11247     }
11248
11249   readp = data->d_buf + tu_off;
11250   nextp = data->d_buf + addr_off;
11251   if (addr_off >= data->d_size)
11252     goto invalid_data;
11253
11254   size_t tu_nr = (nextp - readp) / 24;
11255
11256   printf (_("\n TU list at offset %#" PRIx32
11257                    " contains %zu entries:\n"),
11258           tu_off, tu_nr);
11259
11260   n = 0;
11261   while (dataend - readp >= 24 && n < tu_nr)
11262     {
11263       uint64_t off = read_8ubyte_unaligned (dbg, readp);
11264       readp += 8;
11265
11266       uint64_t type = read_8ubyte_unaligned (dbg, readp);
11267       readp += 8;
11268
11269       uint64_t sig = read_8ubyte_unaligned (dbg, readp);
11270       readp += 8;
11271
11272       printf (" [%4zu] CU offset: %5" PRId64
11273               ", type offset: %5" PRId64
11274               ", signature: %0#8" PRIx64 "\n", n, off, type, sig);
11275       n++;
11276     }
11277
11278   readp = data->d_buf + addr_off;
11279   nextp = data->d_buf + sym_off;
11280   if (sym_off >= data->d_size)
11281     goto invalid_data;
11282
11283   size_t addr_nr = (nextp - readp) / 20;
11284
11285   printf (_("\n Address list at offset %#" PRIx32
11286                    " contains %zu entries:\n"),
11287           addr_off, addr_nr);
11288
11289   n = 0;
11290   while (dataend - readp >= 20 && n < addr_nr)
11291     {
11292       uint64_t low = read_8ubyte_unaligned (dbg, readp);
11293       readp += 8;
11294
11295       uint64_t high = read_8ubyte_unaligned (dbg, readp);
11296       readp += 8;
11297
11298       uint32_t idx = read_4ubyte_unaligned (dbg, readp);
11299       readp += 4;
11300
11301       printf (" [%4zu] ", n);
11302       print_dwarf_addr (dwflmod, 8, low, low);
11303       printf ("..");
11304       print_dwarf_addr (dwflmod, 8, high - 1, high);
11305       printf (", CU index: %5" PRId32 "\n", idx);
11306       n++;
11307     }
11308
11309   const unsigned char *const_start = data->d_buf + const_off;
11310   if (const_off >= data->d_size)
11311     goto invalid_data;
11312
11313   readp = data->d_buf + sym_off;
11314   nextp = const_start;
11315   size_t sym_nr = (nextp - readp) / 8;
11316
11317   printf (_("\n Symbol table at offset %#" PRIx32
11318                    " contains %zu slots:\n"),
11319           addr_off, sym_nr);
11320
11321   n = 0;
11322   while (dataend - readp >= 8 && n < sym_nr)
11323     {
11324       uint32_t name = read_4ubyte_unaligned (dbg, readp);
11325       readp += 4;
11326
11327       uint32_t vector = read_4ubyte_unaligned (dbg, readp);
11328       readp += 4;
11329
11330       if (name != 0 || vector != 0)
11331         {
11332           const unsigned char *sym = const_start + name;
11333           if (unlikely ((size_t) (dataend - const_start) < name
11334                         || memchr (sym, '\0', dataend - sym) == NULL))
11335             goto invalid_data;
11336
11337           printf (" [%4zu] symbol: %s, CUs: ", n, sym);
11338
11339           const unsigned char *readcus = const_start + vector;
11340           if (unlikely ((size_t) (dataend - const_start) < vector))
11341             goto invalid_data;
11342           uint32_t cus = read_4ubyte_unaligned (dbg, readcus);
11343           while (cus--)
11344             {
11345               uint32_t cu_kind, cu, kind;
11346               bool is_static;
11347               readcus += 4;
11348               if (unlikely (readcus + 4 > dataend))
11349                 goto invalid_data;
11350               cu_kind = read_4ubyte_unaligned (dbg, readcus);
11351               cu = cu_kind & ((1 << 24) - 1);
11352               kind = (cu_kind >> 28) & 7;
11353               is_static = cu_kind & (1U << 31);
11354               if (cu > cu_nr - 1)
11355                 printf ("%" PRId32 "T", cu - (uint32_t) cu_nr);
11356               else
11357                 printf ("%" PRId32, cu);
11358               if (kind != 0)
11359                 {
11360                   printf (" (");
11361                   switch (kind)
11362                     {
11363                     case 1:
11364                       printf ("type");
11365                       break;
11366                     case 2:
11367                       printf ("var");
11368                       break;
11369                     case 3:
11370                       printf ("func");
11371                       break;
11372                     case 4:
11373                       printf ("other");
11374                       break;
11375                     default:
11376                       printf ("unknown-0x%" PRIx32, kind);
11377                       break;
11378                     }
11379                   printf (":%c)", (is_static ? 'S' : 'G'));
11380                 }
11381               if (cus > 0)
11382                 printf (", ");
11383             }
11384           printf ("\n");
11385         }
11386       n++;
11387     }
11388 }
11389
11390 /* Returns true and sets split DWARF CU id if there is a split compile
11391    unit in the given Dwarf, and no non-split units are found (before it).  */
11392 static bool
11393 is_split_dwarf (Dwarf *dbg, uint64_t *id, Dwarf_CU **split_cu)
11394 {
11395   Dwarf_CU *cu = NULL;
11396   while (dwarf_get_units (dbg, cu, &cu, NULL, NULL, NULL, NULL) == 0)
11397     {
11398       uint8_t unit_type;
11399       if (dwarf_cu_info (cu, NULL, &unit_type, NULL, NULL,
11400                          id, NULL, NULL) != 0)
11401         return false;
11402
11403       if (unit_type != DW_UT_split_compile && unit_type != DW_UT_split_type)
11404         return false;
11405
11406       /* We really only care about the split compile unit, the types
11407          should be fine and self sufficient.  Also they don't have an
11408          id that we can match with a skeleton unit.  */
11409       if (unit_type == DW_UT_split_compile)
11410         {
11411           *split_cu = cu;
11412           return true;
11413         }
11414     }
11415
11416   return false;
11417 }
11418
11419 /* Check that there is one and only one Dwfl_Module, return in arg.  */
11420 static int
11421 getone_dwflmod (Dwfl_Module *dwflmod,
11422                void **userdata __attribute__ ((unused)),
11423                const char *name __attribute__ ((unused)),
11424                Dwarf_Addr base __attribute__ ((unused)),
11425                void *arg)
11426 {
11427   Dwfl_Module **m = (Dwfl_Module **) arg;
11428   if (*m != NULL)
11429     return DWARF_CB_ABORT;
11430   *m = dwflmod;
11431   return DWARF_CB_OK;
11432 }
11433
11434 static void
11435 print_debug (Dwfl_Module *dwflmod, Ebl *ebl, GElf_Ehdr *ehdr)
11436 {
11437   /* Used for skeleton file, if necessary for split DWARF.  */
11438   Dwfl *skel_dwfl = NULL;
11439   Dwfl_Module *skel_mod = NULL;
11440   char *skel_name = NULL;
11441   Dwarf *split_dbg = NULL;
11442   Dwarf_CU *split_cu = NULL;
11443
11444   /* Before we start the real work get a debug context descriptor.  */
11445   Dwarf_Addr dwbias;
11446   Dwarf *dbg = dwfl_module_getdwarf (dwflmod, &dwbias);
11447   Dwarf dummy_dbg =
11448     {
11449       .elf = ebl->elf,
11450       .other_byte_order = MY_ELFDATA != ehdr->e_ident[EI_DATA]
11451     };
11452   if (dbg == NULL)
11453     {
11454       if ((print_debug_sections & ~(section_exception|section_frame)) != 0)
11455         error (0, 0, _("cannot get debug context descriptor: %s"),
11456                dwfl_errmsg (-1));
11457       dbg = &dummy_dbg;
11458     }
11459   else
11460     {
11461       /* If we are asked about a split dwarf (.dwo) file, use the user
11462          provided, or find the corresponding skeleton file. If we got
11463          a skeleton file, replace the given dwflmod and dbg, with one
11464          derived from the skeleton file to provide enough context.  */
11465       uint64_t split_id;
11466       if (is_split_dwarf (dbg, &split_id, &split_cu))
11467         {
11468           if (dwarf_skeleton != NULL)
11469             skel_name = strdup (dwarf_skeleton);
11470           else
11471             {
11472               /* Replace file.dwo with file.o and see if that matches. */
11473               const char *fname;
11474               dwfl_module_info (dwflmod, NULL, NULL, NULL, NULL, NULL,
11475                                 &fname, NULL);
11476               if (fname != NULL)
11477                 {
11478                   size_t flen = strlen (fname);
11479                   if (flen > 4 && strcmp (".dwo", fname + flen - 4) == 0)
11480                     {
11481                       skel_name = strdup (fname);
11482                       if (skel_name != NULL)
11483                         {
11484                           skel_name[flen - 3] = 'o';
11485                           skel_name[flen - 2] = '\0';
11486                         }
11487                     }
11488                 }
11489             }
11490
11491           if (skel_name != NULL)
11492             {
11493               int skel_fd = open (skel_name, O_RDONLY);
11494               if (skel_fd == -1)
11495                 fprintf (stderr, "Warning: Couldn't open DWARF skeleton file"
11496                          " '%s'\n", skel_name);
11497               else
11498                 skel_dwfl = create_dwfl (skel_fd, skel_name);
11499
11500               if (skel_dwfl != NULL)
11501                 {
11502                   if (dwfl_getmodules (skel_dwfl, &getone_dwflmod,
11503                                        &skel_mod, 0) != 0)
11504                     {
11505                       fprintf (stderr, "Warning: Bad DWARF skeleton,"
11506                                " multiple modules '%s'\n", skel_name);
11507                       dwfl_end (skel_dwfl);
11508                       skel_mod = NULL;
11509                     }
11510                 }
11511               else if (skel_fd != -1)
11512                 fprintf (stderr, "Warning: Couldn't create skeleton dwfl for"
11513                          " '%s': %s\n", skel_name, dwfl_errmsg (-1));
11514
11515               if (skel_mod != NULL)
11516                 {
11517                   Dwarf *skel_dbg = dwfl_module_getdwarf (skel_mod, &dwbias);
11518                   if (skel_dbg != NULL)
11519                     {
11520                       /* First check the skeleton CU DIE, only fetch
11521                          the split DIE if we know the id matches to
11522                          not unnecessary search for any split DIEs we
11523                          don't need. */
11524                       Dwarf_CU *cu = NULL;
11525                       while (dwarf_get_units (skel_dbg, cu, &cu,
11526                                               NULL, NULL, NULL, NULL) == 0)
11527                         {
11528                           uint8_t unit_type;
11529                           uint64_t skel_id;
11530                           if (dwarf_cu_info (cu, NULL, &unit_type, NULL, NULL,
11531                                              &skel_id, NULL, NULL) == 0
11532                               && unit_type == DW_UT_skeleton
11533                               && split_id == skel_id)
11534                             {
11535                               Dwarf_Die subdie;
11536                               if (dwarf_cu_info (cu, NULL, NULL, NULL,
11537                                                  &subdie,
11538                                                  NULL, NULL, NULL) == 0
11539                                   && dwarf_tag (&subdie) != DW_TAG_invalid)
11540                                 {
11541                                   split_dbg = dwarf_cu_getdwarf (subdie.cu);
11542                                   if (split_dbg == NULL)
11543                                     fprintf (stderr,
11544                                              "Warning: Couldn't get split_dbg:"
11545                                              " %s\n", dwarf_errmsg (-1));
11546                                   break;
11547                                 }
11548                               else
11549                                 {
11550                                   /* Everything matches up, but not
11551                                      according to libdw. Which means
11552                                      the user knew better.  So...
11553                                      Terrible hack... We can never
11554                                      destroy the underlying dwfl
11555                                      because it would free the wrong
11556                                      Dwarfs... So we leak memory...*/
11557                                   if (cu->split == NULL
11558                                       && dwarf_skeleton != NULL)
11559                                     {
11560                                       do_not_close_dwfl = true;
11561                                       __libdw_link_skel_split (cu, split_cu);
11562                                       split_dbg = dwarf_cu_getdwarf (split_cu);
11563                                       break;
11564                                     }
11565                                   else
11566                                     fprintf (stderr, "Warning: Couldn't get"
11567                                              " skeleton subdie: %s\n",
11568                                              dwarf_errmsg (-1));
11569                                 }
11570                             }
11571                         }
11572                       if (split_dbg == NULL)
11573                         fprintf (stderr, "Warning: '%s' didn't contain a skeleton for split id %" PRIx64 "\n", skel_name, split_id);
11574                     }
11575                   else
11576                     fprintf (stderr, "Warning: Couldn't get skeleton DWARF:"
11577                              " %s\n", dwfl_errmsg (-1));
11578                 }
11579             }
11580
11581           if (split_dbg != NULL)
11582             {
11583               dbg = split_dbg;
11584               dwflmod = skel_mod;
11585             }
11586           else if (skel_name == NULL)
11587             fprintf (stderr,
11588                      "Warning: split DWARF file, but no skeleton found.\n");
11589         }
11590       else if (dwarf_skeleton != NULL)
11591         fprintf (stderr, "Warning: DWARF skeleton given,"
11592                  " but not a split DWARF file\n");
11593     }
11594
11595   /* Get the section header string table index.  */
11596   size_t shstrndx;
11597   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
11598     error_exit (0, _("cannot get section header string table index"));
11599
11600   /* If the .debug_info section is listed as implicitly required then
11601      we must make sure to handle it before handling any other debug
11602      section.  Various other sections depend on the CU DIEs being
11603      scanned (silently) first.  */
11604   bool implicit_info = (implicit_debug_sections & section_info) != 0;
11605   bool explicit_info = (print_debug_sections & section_info) != 0;
11606   if (implicit_info)
11607     {
11608       Elf_Scn *scn = NULL;
11609       while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
11610         {
11611           GElf_Shdr shdr_mem;
11612           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
11613
11614           if (shdr != NULL && shdr->sh_type == SHT_PROGBITS)
11615             {
11616               const char *name = elf_strptr (ebl->elf, shstrndx,
11617                                              shdr->sh_name);
11618               if (name == NULL)
11619                 continue;
11620
11621               if (strcmp (name, ".debug_info") == 0
11622                   || strcmp (name, ".debug_info.dwo") == 0
11623                   || strcmp (name, ".zdebug_info") == 0
11624                   || strcmp (name, ".zdebug_info.dwo") == 0
11625                   || strcmp (name, ".gnu.debuglto_.debug_info") == 0)
11626                 {
11627                   print_debug_info_section (dwflmod, ebl, ehdr,
11628                                             scn, shdr, dbg);
11629                   break;
11630                 }
11631             }
11632         }
11633       print_debug_sections &= ~section_info;
11634       implicit_debug_sections &= ~section_info;
11635     }
11636
11637   /* Look through all the sections for the debugging sections to print.  */
11638   Elf_Scn *scn = NULL;
11639   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
11640     {
11641       GElf_Shdr shdr_mem;
11642       GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
11643
11644       if (shdr != NULL && shdr->sh_type == SHT_PROGBITS)
11645         {
11646           static const struct
11647           {
11648             const char *name;
11649             enum section_e bitmask;
11650             void (*fp) (Dwfl_Module *, Ebl *,
11651                         GElf_Ehdr *, Elf_Scn *, GElf_Shdr *, Dwarf *);
11652           } debug_sections[] =
11653             {
11654 #define NEW_SECTION(name) \
11655               { ".debug_" #name, section_##name, print_debug_##name##_section }
11656               NEW_SECTION (abbrev),
11657               NEW_SECTION (addr),
11658               NEW_SECTION (aranges),
11659               NEW_SECTION (frame),
11660               NEW_SECTION (info),
11661               NEW_SECTION (types),
11662               NEW_SECTION (line),
11663               NEW_SECTION (loc),
11664               /* loclists is loc for DWARF5.  */
11665               { ".debug_loclists", section_loc,
11666                 print_debug_loclists_section },
11667               NEW_SECTION (pubnames),
11668               NEW_SECTION (str),
11669               /* A DWARF5 specialised debug string section.  */
11670               { ".debug_line_str", section_str,
11671                 print_debug_str_section },
11672               /* DWARF5 string offsets table.  */
11673               { ".debug_str_offsets", section_str,
11674                 print_debug_str_offsets_section },
11675               NEW_SECTION (macinfo),
11676               NEW_SECTION (macro),
11677               NEW_SECTION (ranges),
11678               /* rnglists is ranges for DWARF5.  */
11679               { ".debug_rnglists", section_ranges,
11680                 print_debug_rnglists_section },
11681               { ".eh_frame", section_frame | section_exception,
11682                 print_debug_frame_section },
11683               { ".eh_frame_hdr", section_frame | section_exception,
11684                 print_debug_frame_hdr_section },
11685               { ".gcc_except_table", section_frame | section_exception,
11686                 print_debug_exception_table },
11687               { ".gdb_index", section_gdb_index, print_gdb_index_section }
11688             };
11689           const int ndebug_sections = (sizeof (debug_sections)
11690                                        / sizeof (debug_sections[0]));
11691           const char *name = elf_strptr (ebl->elf, shstrndx,
11692                                          shdr->sh_name);
11693           if (name == NULL)
11694             continue;
11695
11696           int n;
11697           for (n = 0; n < ndebug_sections; ++n)
11698             {
11699               size_t dbglen = strlen (debug_sections[n].name);
11700               size_t scnlen = strlen (name);
11701               if ((strncmp (name, debug_sections[n].name, dbglen) == 0
11702                    && (dbglen == scnlen
11703                        || (scnlen == dbglen + 4
11704                            && strstr (name, ".dwo") == name + dbglen)))
11705                   || (name[0] == '.' && name[1] == 'z'
11706                       && debug_sections[n].name[1] == 'd'
11707                       && strncmp (&name[2], &debug_sections[n].name[1],
11708                                   dbglen - 1) == 0
11709                       && (scnlen == dbglen + 1
11710                           || (scnlen == dbglen + 5
11711                               && strstr (name, ".dwo") == name + dbglen + 1)))
11712                   || (scnlen > 14 /* .gnu.debuglto_ prefix. */
11713                       && startswith (name, ".gnu.debuglto_")
11714                       && strcmp (&name[14], debug_sections[n].name) == 0)
11715 )
11716                 {
11717                   if ((print_debug_sections | implicit_debug_sections)
11718                       & debug_sections[n].bitmask)
11719                     debug_sections[n].fp (dwflmod, ebl, ehdr, scn, shdr, dbg);
11720                   break;
11721                 }
11722             }
11723         }
11724     }
11725
11726   dwfl_end (skel_dwfl);
11727   free (skel_name);
11728
11729   /* Turn implicit and/or explicit back on in case we go over another file.  */
11730   if (implicit_info)
11731     implicit_debug_sections |= section_info;
11732   if (explicit_info)
11733     print_debug_sections |= section_info;
11734
11735   reset_listptr (&known_locsptr);
11736   reset_listptr (&known_loclistsptr);
11737   reset_listptr (&known_rangelistptr);
11738   reset_listptr (&known_rnglistptr);
11739   reset_listptr (&known_addrbases);
11740   reset_listptr (&known_stroffbases);
11741 }
11742
11743
11744 #define ITEM_INDENT             4
11745 #define WRAP_COLUMN             75
11746
11747 /* Print "NAME: FORMAT", wrapping when output text would make the line
11748    exceed WRAP_COLUMN.  Unpadded numbers look better for the core items
11749    but this function is also used for registers which should be printed
11750    aligned.  Fortunately registers output uses fixed fields width (such
11751    as %11d) for the alignment.
11752
11753    Line breaks should not depend on the particular values although that
11754    may happen in some cases of the core items.  */
11755
11756 static unsigned int
11757 __attribute__ ((format (printf, 6, 7)))
11758 print_core_item (unsigned int colno, char sep, unsigned int wrap,
11759                  size_t name_width, const char *name, const char *format, ...)
11760 {
11761   size_t len = strlen (name);
11762   if (name_width < len)
11763     name_width = len;
11764
11765   char *out;
11766   va_list ap;
11767   va_start (ap, format);
11768   int out_len = vasprintf (&out, format, ap);
11769   va_end (ap);
11770   if (out_len == -1)
11771     error_exit (0, _("memory exhausted"));
11772
11773   size_t n = name_width + sizeof ": " - 1 + out_len;
11774
11775   if (colno == 0)
11776     {
11777       printf ("%*s", ITEM_INDENT, "");
11778       colno = ITEM_INDENT + n;
11779     }
11780   else if (colno + 2 + n < wrap)
11781     {
11782       printf ("%c ", sep);
11783       colno += 2 + n;
11784     }
11785   else
11786     {
11787       printf ("\n%*s", ITEM_INDENT, "");
11788       colno = ITEM_INDENT + n;
11789     }
11790
11791   printf ("%s: %*s%s", name, (int) (name_width - len), "", out);
11792
11793   free (out);
11794
11795   return colno;
11796 }
11797
11798 static const void *
11799 convert (Elf *core, Elf_Type type, uint_fast16_t count,
11800          void *value, const void *data, size_t size)
11801 {
11802   Elf_Data valuedata =
11803     {
11804       .d_type = type,
11805       .d_buf = value,
11806       .d_size = size ?: gelf_fsize (core, type, count, EV_CURRENT),
11807       .d_version = EV_CURRENT,
11808     };
11809   Elf_Data indata =
11810     {
11811       .d_type = type,
11812       .d_buf = (void *) data,
11813       .d_size = valuedata.d_size,
11814       .d_version = EV_CURRENT,
11815     };
11816
11817   Elf_Data *d = (gelf_getclass (core) == ELFCLASS32
11818                  ? elf32_xlatetom : elf64_xlatetom)
11819     (&valuedata, &indata, elf_getident (core, NULL)[EI_DATA]);
11820   if (d == NULL)
11821     error_exit (0, _("cannot convert core note data: %s"),
11822                 elf_errmsg (-1));
11823
11824   return data + indata.d_size;
11825 }
11826
11827 typedef uint8_t GElf_Byte;
11828
11829 static unsigned int
11830 handle_core_item (Elf *core, const Ebl_Core_Item *item, const void *desc,
11831                   unsigned int colno, size_t *repeated_size)
11832 {
11833   uint_fast16_t count = item->count ?: 1;
11834   /* Ebl_Core_Item count is always a small number.
11835      Make sure the backend didn't put in some large bogus value.  */
11836   assert (count < 128);
11837
11838 #define TYPES                                                                 \
11839   DO_TYPE (BYTE, Byte, "0x%.2" PRIx8, "%" PRId8);                             \
11840   DO_TYPE (HALF, Half, "0x%.4" PRIx16, "%" PRId16);                           \
11841   DO_TYPE (WORD, Word, "0x%.8" PRIx32, "%" PRId32);                           \
11842   DO_TYPE (SWORD, Sword, "%" PRId32, "%" PRId32);                             \
11843   DO_TYPE (XWORD, Xword, "0x%.16" PRIx64, "%" PRId64);                        \
11844   DO_TYPE (SXWORD, Sxword, "%" PRId64, "%" PRId64)
11845
11846 #define DO_TYPE(NAME, Name, hex, dec) GElf_##Name Name
11847   typedef union { TYPES; } value_t;
11848   void *data = alloca (count * sizeof (value_t));
11849 #undef DO_TYPE
11850
11851 #define DO_TYPE(NAME, Name, hex, dec) \
11852     GElf_##Name *value_##Name __attribute__((unused)) = data
11853   TYPES;
11854 #undef DO_TYPE
11855
11856   size_t size = gelf_fsize (core, item->type, count, EV_CURRENT);
11857   size_t convsize = size;
11858   if (repeated_size != NULL)
11859     {
11860       if (*repeated_size > size && (item->format == 'b' || item->format == 'B'))
11861         {
11862           data = alloca (*repeated_size);
11863           count *= *repeated_size / size;
11864           convsize = count * size;
11865           *repeated_size -= convsize;
11866         }
11867       else if (item->count != 0 || item->format != '\n')
11868         *repeated_size -= size;
11869     }
11870
11871   convert (core, item->type, count, data, desc + item->offset, convsize);
11872
11873   Elf_Type type = item->type;
11874   if (type == ELF_T_ADDR)
11875     type = gelf_getclass (core) == ELFCLASS32 ? ELF_T_WORD : ELF_T_XWORD;
11876
11877   switch (item->format)
11878     {
11879     case 'd':
11880       assert (count == 1);
11881       switch (type)
11882         {
11883 #define DO_TYPE(NAME, Name, hex, dec)                                         \
11884           case ELF_T_##NAME:                                                  \
11885             colno = print_core_item (colno, ',', WRAP_COLUMN,                 \
11886                                      0, item->name, dec, value_##Name[0]); \
11887             break
11888           TYPES;
11889 #undef DO_TYPE
11890         default:
11891           abort ();
11892         }
11893       break;
11894
11895     case 'x':
11896       assert (count == 1);
11897       switch (type)
11898         {
11899 #define DO_TYPE(NAME, Name, hex, dec)                                         \
11900           case ELF_T_##NAME:                                                  \
11901             colno = print_core_item (colno, ',', WRAP_COLUMN,                 \
11902                                      0, item->name, hex, value_##Name[0]);      \
11903             break
11904           TYPES;
11905 #undef DO_TYPE
11906         default:
11907           abort ();
11908         }
11909       break;
11910
11911     case 'b':
11912     case 'B':
11913       assert (size % sizeof (unsigned int) == 0);
11914       unsigned int nbits = count * size * 8;
11915       unsigned int pop = 0;
11916       for (const unsigned int *i = data; (void *) i < data + count * size; ++i)
11917         pop += __builtin_popcount (*i);
11918       bool negate = pop > nbits / 2;
11919       const unsigned int bias = item->format == 'b';
11920
11921       {
11922         char printed[(negate ? nbits - pop : pop) * 16 + 1];
11923         char *p = printed;
11924         *p = '\0';
11925
11926         if (BYTE_ORDER != LITTLE_ENDIAN && size > sizeof (unsigned int))
11927           {
11928             assert (size == sizeof (unsigned int) * 2);
11929             for (unsigned int *i = data;
11930                  (void *) i < data + count * size; i += 2)
11931               {
11932                 unsigned int w = i[1];
11933                 i[1] = i[0];
11934                 i[0] = w;
11935               }
11936           }
11937
11938         unsigned int lastbit = 0;
11939         unsigned int run = 0;
11940         for (const unsigned int *i = data;
11941              (void *) i < data + count * size; ++i)
11942           {
11943             unsigned int bit = ((void *) i - data) * 8;
11944             unsigned int w = negate ? ~*i : *i;
11945             while (w != 0)
11946               {
11947                 /* Note that a right shift equal to (or greater than)
11948                    the number of bits of w is undefined behaviour.  In
11949                    particular when the least significant bit is bit 32
11950                    (w = 0x8000000) then w >>= n is undefined.  So
11951                    explicitly handle that case separately.  */
11952                 unsigned int n = ffs (w);
11953                 if (n < sizeof (w) * 8)
11954                   w >>= n;
11955                 else
11956                   w = 0;
11957                 bit += n;
11958
11959                 if (lastbit != 0 && lastbit + 1 == bit)
11960                   ++run;
11961                 else
11962                   {
11963                     if (lastbit == 0)
11964                       p += sprintf (p, "%u", bit - bias);
11965                     else if (run == 0)
11966                       p += sprintf (p, ",%u", bit - bias);
11967                     else
11968                       p += sprintf (p, "-%u,%u", lastbit - bias, bit - bias);
11969                     run = 0;
11970                   }
11971
11972                 lastbit = bit;
11973               }
11974           }
11975         if (lastbit > 0 && run > 0 && lastbit + 1 != nbits)
11976           p += sprintf (p, "-%u", lastbit - bias);
11977
11978         colno = print_core_item (colno, ',', WRAP_COLUMN, 0, item->name,
11979                                  negate ? "~<%s>" : "<%s>", printed);
11980       }
11981       break;
11982
11983     case 'T':
11984     case (char) ('T'|0x80):
11985       assert (count == 2);
11986       Dwarf_Word sec;
11987       Dwarf_Word usec;
11988       switch (type)
11989         {
11990 #define DO_TYPE(NAME, Name, hex, dec)                                         \
11991           case ELF_T_##NAME:                                                  \
11992             sec = value_##Name[0];                                            \
11993             usec = value_##Name[1];                                           \
11994             break
11995           TYPES;
11996 #undef DO_TYPE
11997         default:
11998           abort ();
11999         }
12000       if (unlikely (item->format == (char) ('T'|0x80)))
12001         {
12002           /* This is a hack for an ill-considered 64-bit ABI where
12003              tv_usec is actually a 32-bit field with 32 bits of padding
12004              rounding out struct timeval.  We've already converted it as
12005              a 64-bit field.  For little-endian, this just means the
12006              high half is the padding; it's presumably zero, but should
12007              be ignored anyway.  For big-endian, it means the 32-bit
12008              field went into the high half of USEC.  */
12009           GElf_Ehdr ehdr_mem;
12010           GElf_Ehdr *ehdr = gelf_getehdr (core, &ehdr_mem);
12011           if (likely (ehdr->e_ident[EI_DATA] == ELFDATA2MSB))
12012             usec >>= 32;
12013           else
12014             usec &= UINT32_MAX;
12015         }
12016       colno = print_core_item (colno, ',', WRAP_COLUMN, 0, item->name,
12017                                "%" PRIu64 ".%.6" PRIu64, sec, usec);
12018       break;
12019
12020     case 'c':
12021       assert (count == 1);
12022       colno = print_core_item (colno, ',', WRAP_COLUMN, 0, item->name,
12023                                "%c", value_Byte[0]);
12024       break;
12025
12026     case 's':
12027       colno = print_core_item (colno, ',', WRAP_COLUMN, 0, item->name,
12028                                "%.*s", (int) count, value_Byte);
12029       break;
12030
12031     case '\n':
12032       /* This is a list of strings separated by '\n'.  */
12033       assert (item->count == 0);
12034       assert (repeated_size != NULL);
12035       assert (item->name == NULL);
12036       if (unlikely (item->offset >= *repeated_size))
12037         break;
12038
12039       const char *s = desc + item->offset;
12040       size = *repeated_size - item->offset;
12041       *repeated_size = 0;
12042       while (size > 0)
12043         {
12044           const char *eol = memchr (s, '\n', size);
12045           int len = size;
12046           if (eol != NULL)
12047             len = eol - s;
12048           printf ("%*s%.*s\n", ITEM_INDENT, "", len, s);
12049           if (eol == NULL)
12050             break;
12051           size -= eol + 1 - s;
12052           s = eol + 1;
12053         }
12054
12055       colno = WRAP_COLUMN;
12056       break;
12057
12058     case 'h':
12059       break;
12060
12061     default:
12062       error (0, 0, "XXX not handling format '%c' for %s",
12063              item->format, item->name);
12064       break;
12065     }
12066
12067 #undef TYPES
12068
12069   return colno;
12070 }
12071
12072
12073 /* Sort items by group, and by layout offset within each group.  */
12074 static int
12075 compare_core_items (const void *a, const void *b)
12076 {
12077   const Ebl_Core_Item *const *p1 = a;
12078   const Ebl_Core_Item *const *p2 = b;
12079   const Ebl_Core_Item *item1 = *p1;
12080   const Ebl_Core_Item *item2 = *p2;
12081
12082   return ((item1->group == item2->group ? 0
12083            : strcmp (item1->group, item2->group))
12084           ?: (int) item1->offset - (int) item2->offset);
12085 }
12086
12087 /* Sort item groups by layout offset of the first item in the group.  */
12088 static int
12089 compare_core_item_groups (const void *a, const void *b)
12090 {
12091   const Ebl_Core_Item *const *const *p1 = a;
12092   const Ebl_Core_Item *const *const *p2 = b;
12093   const Ebl_Core_Item *const *group1 = *p1;
12094   const Ebl_Core_Item *const *group2 = *p2;
12095   const Ebl_Core_Item *item1 = *group1;
12096   const Ebl_Core_Item *item2 = *group2;
12097
12098   return (int) item1->offset - (int) item2->offset;
12099 }
12100
12101 static unsigned int
12102 handle_core_items (Elf *core, const void *desc, size_t descsz,
12103                    const Ebl_Core_Item *items, size_t nitems)
12104 {
12105   if (nitems == 0)
12106     return 0;
12107   unsigned int colno = 0;
12108
12109   /* FORMAT '\n' makes sense to be present only as a single item as it
12110      processes all the data of a note.  FORMATs 'b' and 'B' have a special case
12111      if present as a single item but they can be also processed with other
12112      items below.  */
12113   if (nitems == 1 && (items[0].format == '\n' || items[0].format == 'b'
12114                       || items[0].format == 'B'))
12115     {
12116       assert (items[0].offset == 0);
12117       size_t size = descsz;
12118       colno = handle_core_item (core, items, desc, colno, &size);
12119       /* If SIZE is not zero here there is some remaining data.  But we do not
12120          know how to process it anyway.  */
12121       return colno;
12122     }
12123   for (size_t i = 0; i < nitems; ++i)
12124     assert (items[i].format != '\n');
12125
12126   /* Sort to collect the groups together.  */
12127   const Ebl_Core_Item *sorted_items[nitems];
12128   for (size_t i = 0; i < nitems; ++i)
12129     sorted_items[i] = &items[i];
12130   qsort (sorted_items, nitems, sizeof sorted_items[0], &compare_core_items);
12131
12132   /* Collect the unique groups and sort them.  */
12133   const Ebl_Core_Item **groups[nitems];
12134   groups[0] = &sorted_items[0];
12135   size_t ngroups = 1;
12136   for (size_t i = 1; i < nitems; ++i)
12137     if (sorted_items[i]->group != sorted_items[i - 1]->group
12138         && strcmp (sorted_items[i]->group, sorted_items[i - 1]->group))
12139       groups[ngroups++] = &sorted_items[i];
12140   qsort (groups, ngroups, sizeof groups[0], &compare_core_item_groups);
12141
12142   /* Write out all the groups.  */
12143   const void *last = desc;
12144   do
12145     {
12146       for (size_t i = 0; i < ngroups; ++i)
12147         {
12148           for (const Ebl_Core_Item **item = groups[i];
12149                (item < &sorted_items[nitems]
12150                 && ((*item)->group == groups[i][0]->group
12151                     || !strcmp ((*item)->group, groups[i][0]->group)));
12152                ++item)
12153             colno = handle_core_item (core, *item, desc, colno, NULL);
12154
12155           /* Force a line break at the end of the group.  */
12156           colno = WRAP_COLUMN;
12157         }
12158
12159       if (descsz == 0)
12160         break;
12161
12162       /* This set of items consumed a certain amount of the note's data.
12163          If there is more data there, we have another unit of the same size.
12164          Loop to print that out too.  */
12165       const Ebl_Core_Item *item = &items[nitems - 1];
12166       size_t eltsz = item->offset + gelf_fsize (core, item->type,
12167                                                 item->count ?: 1, EV_CURRENT);
12168
12169       int reps = -1;
12170       do
12171         {
12172           ++reps;
12173           desc += eltsz;
12174           descsz -= eltsz;
12175         }
12176       while (descsz >= eltsz && !memcmp (desc, last, eltsz));
12177
12178       if (reps == 1)
12179         {
12180           /* For just one repeat, print it unabridged twice.  */
12181           desc -= eltsz;
12182           descsz += eltsz;
12183         }
12184       else if (reps > 1)
12185         printf (_("\n%*s... <repeats %u more times> ..."),
12186                 ITEM_INDENT, "", reps);
12187
12188       last = desc;
12189     }
12190   while (descsz > 0);
12191
12192   return colno;
12193 }
12194
12195 static unsigned int
12196 handle_bit_registers (const Ebl_Register_Location *regloc, const void *desc,
12197                       unsigned int colno)
12198 {
12199   desc += regloc->offset;
12200
12201   abort ();                     /* XXX */
12202   return colno;
12203 }
12204
12205
12206 static unsigned int
12207 handle_core_register (Ebl *ebl, Elf *core, int maxregname,
12208                       const Ebl_Register_Location *regloc, const void *desc,
12209                       unsigned int colno)
12210 {
12211   if (regloc->bits % 8 != 0)
12212     return handle_bit_registers (regloc, desc, colno);
12213
12214   desc += regloc->offset;
12215
12216   for (int reg = regloc->regno; reg < regloc->regno + regloc->count; ++reg)
12217     {
12218       char name[REGNAMESZ];
12219       int bits;
12220       int type;
12221       register_info (ebl, reg, regloc, name, &bits, &type);
12222
12223 #define TYPES                                                                 \
12224       BITS (8, BYTE, "%4" PRId8, "0x%.2" PRIx8);                              \
12225       BITS (16, HALF, "%6" PRId16, "0x%.4" PRIx16);                           \
12226       BITS (32, WORD, "%11" PRId32, " 0x%.8" PRIx32);                         \
12227       BITS (64, XWORD, "%20" PRId64, "  0x%.16" PRIx64)
12228
12229 #define BITS(bits, xtype, sfmt, ufmt)                           \
12230       uint##bits##_t b##bits; int##bits##_t b##bits##s
12231       union { TYPES; uint64_t b128[2]; } value;
12232 #undef  BITS
12233
12234       switch (type)
12235         {
12236         case DW_ATE_unsigned:
12237         case DW_ATE_signed:
12238         case DW_ATE_address:
12239           switch (bits)
12240             {
12241 #define BITS(bits, xtype, sfmt, ufmt)                                         \
12242             case bits:                                                        \
12243               desc = convert (core, ELF_T_##xtype, 1, &value, desc, 0);       \
12244               if (type == DW_ATE_signed)                                      \
12245                 colno = print_core_item (colno, ' ', WRAP_COLUMN,             \
12246                                          maxregname, name,                    \
12247                                          sfmt, value.b##bits##s);             \
12248               else                                                            \
12249                 colno = print_core_item (colno, ' ', WRAP_COLUMN,             \
12250                                          maxregname, name,                    \
12251                                          ufmt, value.b##bits);                \
12252               break
12253
12254             TYPES;
12255
12256             case 128:
12257               assert (type == DW_ATE_unsigned);
12258               desc = convert (core, ELF_T_XWORD, 2, &value, desc, 0);
12259               int be = elf_getident (core, NULL)[EI_DATA] == ELFDATA2MSB;
12260               colno = print_core_item (colno, ' ', WRAP_COLUMN,
12261                                        maxregname, name,
12262                                        "0x%.16" PRIx64 "%.16" PRIx64,
12263                                        value.b128[!be], value.b128[be]);
12264               break;
12265
12266             default:
12267               abort ();
12268 #undef  BITS
12269             }
12270           break;
12271
12272         default:
12273           /* Print each byte in hex, the whole thing in native byte order.  */
12274           assert (bits % 8 == 0);
12275           const uint8_t *bytes = desc;
12276           desc += bits / 8;
12277           char hex[bits / 4 + 1];
12278           hex[bits / 4] = '\0';
12279           int incr = 1;
12280           if (elf_getident (core, NULL)[EI_DATA] == ELFDATA2LSB)
12281             {
12282               bytes += bits / 8 - 1;
12283               incr = -1;
12284             }
12285           size_t idx = 0;
12286           for (char *h = hex; bits > 0; bits -= 8, idx += incr)
12287             {
12288               *h++ = "0123456789abcdef"[bytes[idx] >> 4];
12289               *h++ = "0123456789abcdef"[bytes[idx] & 0xf];
12290             }
12291           colno = print_core_item (colno, ' ', WRAP_COLUMN,
12292                                    maxregname, name, "0x%s", hex);
12293           break;
12294         }
12295       desc += regloc->pad;
12296
12297 #undef TYPES
12298     }
12299
12300   return colno;
12301 }
12302
12303
12304 struct register_info
12305 {
12306   const Ebl_Register_Location *regloc;
12307   const char *set;
12308   char name[REGNAMESZ];
12309   int regno;
12310   int bits;
12311   int type;
12312 };
12313
12314 static int
12315 register_bitpos (const struct register_info *r)
12316 {
12317   return (r->regloc->offset * 8
12318           + ((r->regno - r->regloc->regno)
12319              * (r->regloc->bits + r->regloc->pad * 8)));
12320 }
12321
12322 static int
12323 compare_sets_by_info (const struct register_info *r1,
12324                       const struct register_info *r2)
12325 {
12326   return ((int) r2->bits - (int) r1->bits
12327           ?: register_bitpos (r1) - register_bitpos (r2));
12328 }
12329
12330 /* Sort registers by set, and by size and layout offset within each set.  */
12331 static int
12332 compare_registers (const void *a, const void *b)
12333 {
12334   const struct register_info *r1 = a;
12335   const struct register_info *r2 = b;
12336
12337   /* Unused elements sort last.  */
12338   if (r1->regloc == NULL)
12339     return r2->regloc == NULL ? 0 : 1;
12340   if (r2->regloc == NULL)
12341     return -1;
12342
12343   return ((r1->set == r2->set ? 0 : strcmp (r1->set, r2->set))
12344           ?: compare_sets_by_info (r1, r2));
12345 }
12346
12347 /* Sort register sets by layout offset of the first register in the set.  */
12348 static int
12349 compare_register_sets (const void *a, const void *b)
12350 {
12351   const struct register_info *const *p1 = a;
12352   const struct register_info *const *p2 = b;
12353   return compare_sets_by_info (*p1, *p2);
12354 }
12355
12356 static inline bool
12357 same_set (const struct register_info *a,
12358           const struct register_info *b,
12359           const struct register_info *regs,
12360           size_t maxnreg)
12361 {
12362   return (a < &regs[maxnreg] && a->regloc != NULL
12363           && b < &regs[maxnreg] && b->regloc != NULL
12364           && a->bits == b->bits
12365           && (a->set == b->set || !strcmp (a->set, b->set)));
12366 }
12367
12368 static unsigned int
12369 handle_core_registers (Ebl *ebl, Elf *core, const void *desc,
12370                        const Ebl_Register_Location *reglocs, size_t nregloc)
12371 {
12372   if (nregloc == 0)
12373     return 0;
12374
12375   ssize_t maxnreg = ebl_register_info (ebl, 0, NULL, 0, NULL, NULL, NULL, NULL);
12376   if (maxnreg <= 0)
12377     {
12378       for (size_t i = 0; i < nregloc; ++i)
12379         if (maxnreg < reglocs[i].regno + reglocs[i].count)
12380           maxnreg = reglocs[i].regno + reglocs[i].count;
12381       assert (maxnreg > 0);
12382     }
12383
12384   struct register_info regs[maxnreg];
12385   memset (regs, 0, sizeof regs);
12386
12387   /* Sort to collect the sets together.  */
12388   int maxreg = 0;
12389   for (size_t i = 0; i < nregloc; ++i)
12390     for (int reg = reglocs[i].regno;
12391          reg < reglocs[i].regno + reglocs[i].count;
12392          ++reg)
12393       {
12394         assert (reg < maxnreg);
12395         if (reg > maxreg)
12396           maxreg = reg;
12397         struct register_info *info = &regs[reg];
12398         info->regloc = &reglocs[i];
12399         info->regno = reg;
12400         info->set = register_info (ebl, reg, &reglocs[i],
12401                                    info->name, &info->bits, &info->type);
12402       }
12403   qsort (regs, maxreg + 1, sizeof regs[0], &compare_registers);
12404
12405   /* Collect the unique sets and sort them.  */
12406   struct register_info *sets[maxreg + 1];
12407   sets[0] = &regs[0];
12408   size_t nsets = 1;
12409   for (int i = 1; i <= maxreg; ++i)
12410     if (regs[i].regloc != NULL
12411         && !same_set (&regs[i], &regs[i - 1], regs, maxnreg))
12412       sets[nsets++] = &regs[i];
12413   qsort (sets, nsets, sizeof sets[0], &compare_register_sets);
12414
12415   /* Write out all the sets.  */
12416   unsigned int colno = 0;
12417   for (size_t i = 0; i < nsets; ++i)
12418     {
12419       /* Find the longest name of a register in this set.  */
12420       size_t maxname = 0;
12421       const struct register_info *end;
12422       for (end = sets[i]; same_set (sets[i], end, regs, maxnreg); ++end)
12423         {
12424           size_t len = strlen (end->name);
12425           if (len > maxname)
12426             maxname = len;
12427         }
12428
12429       for (const struct register_info *reg = sets[i];
12430            reg < end;
12431            reg += reg->regloc->count ?: 1)
12432         colno = handle_core_register (ebl, core, maxname,
12433                                       reg->regloc, desc, colno);
12434
12435       /* Force a line break at the end of the group.  */
12436       colno = WRAP_COLUMN;
12437     }
12438
12439   return colno;
12440 }
12441
12442 static void
12443 handle_auxv_note (Ebl *ebl, Elf *core, GElf_Word descsz, GElf_Off desc_pos)
12444 {
12445   Elf_Data *data = elf_getdata_rawchunk (core, desc_pos, descsz, ELF_T_AUXV);
12446   if (data == NULL)
12447   elf_error:
12448     error_exit (0, _("cannot convert core note data: %s"), elf_errmsg (-1));
12449
12450   const size_t nauxv = descsz / gelf_fsize (core, ELF_T_AUXV, 1, EV_CURRENT);
12451   for (size_t i = 0; i < nauxv; ++i)
12452     {
12453       GElf_auxv_t av_mem;
12454       GElf_auxv_t *av = gelf_getauxv (data, i, &av_mem);
12455       if (av == NULL)
12456         goto elf_error;
12457
12458       const char *name;
12459       const char *fmt;
12460       if (ebl_auxv_info (ebl, av->a_type, &name, &fmt) == 0)
12461         {
12462           /* Unknown type.  */
12463           if (av->a_un.a_val == 0)
12464             printf ("    %" PRIu64 "\n", av->a_type);
12465           else
12466             printf ("    %" PRIu64 ": %#" PRIx64 "\n",
12467                     av->a_type, av->a_un.a_val);
12468         }
12469       else
12470         switch (fmt[0])
12471           {
12472           case '\0':            /* Normally zero.  */
12473             if (av->a_un.a_val == 0)
12474               {
12475                 printf ("    %s\n", name);
12476                 break;
12477               }
12478             FALLTHROUGH;
12479           case 'x':             /* hex */
12480           case 'p':             /* address */
12481           case 's':             /* address of string */
12482             printf ("    %s: %#" PRIx64 "\n", name, av->a_un.a_val);
12483             break;
12484           case 'u':
12485             printf ("    %s: %" PRIu64 "\n", name, av->a_un.a_val);
12486             break;
12487           case 'd':
12488             printf ("    %s: %" PRId64 "\n", name, av->a_un.a_val);
12489             break;
12490
12491           case 'b':
12492             printf ("    %s: %#" PRIx64 "  ", name, av->a_un.a_val);
12493             GElf_Xword bit = 1;
12494             const char *pfx = "<";
12495             for (const char *p = fmt + 1; *p != 0; p = strchr (p, '\0') + 1)
12496               {
12497                 if (av->a_un.a_val & bit)
12498                   {
12499                     printf ("%s%s", pfx, p);
12500                     pfx = " ";
12501                   }
12502                 bit <<= 1;
12503               }
12504             printf (">\n");
12505             break;
12506
12507           default:
12508             abort ();
12509           }
12510     }
12511 }
12512
12513 static bool
12514 buf_has_data (unsigned char const *ptr, unsigned char const *end, size_t sz)
12515 {
12516   return ptr < end && (size_t) (end - ptr) >= sz;
12517 }
12518
12519 static bool
12520 buf_read_int (Elf *core, unsigned char const **ptrp, unsigned char const *end,
12521               int *retp)
12522 {
12523   if (! buf_has_data (*ptrp, end, 4))
12524     return false;
12525
12526   *ptrp = convert (core, ELF_T_WORD, 1, retp, *ptrp, 4);
12527   return true;
12528 }
12529
12530 static bool
12531 buf_read_ulong (Elf *core, unsigned char const **ptrp, unsigned char const *end,
12532                 uint64_t *retp)
12533 {
12534   size_t sz = gelf_fsize (core, ELF_T_ADDR, 1, EV_CURRENT);
12535   if (! buf_has_data (*ptrp, end, sz))
12536     return false;
12537
12538   union
12539   {
12540     uint64_t u64;
12541     uint32_t u32;
12542   } u;
12543
12544   *ptrp = convert (core, ELF_T_ADDR, 1, &u, *ptrp, sz);
12545
12546   if (sz == 4)
12547     *retp = u.u32;
12548   else
12549     *retp = u.u64;
12550   return true;
12551 }
12552
12553 static void
12554 handle_siginfo_note (Elf *core, GElf_Word descsz, GElf_Off desc_pos)
12555 {
12556   Elf_Data *data = elf_getdata_rawchunk (core, desc_pos, descsz, ELF_T_BYTE);
12557   if (data == NULL)
12558     error_exit (0, _("cannot convert core note data: %s"), elf_errmsg (-1));
12559
12560   unsigned char const *ptr = data->d_buf;
12561   unsigned char const *const end = data->d_buf + data->d_size;
12562
12563   /* Siginfo head is three ints: signal number, error number, origin
12564      code.  */
12565   int si_signo, si_errno, si_code;
12566   if (! buf_read_int (core, &ptr, end, &si_signo)
12567       || ! buf_read_int (core, &ptr, end, &si_errno)
12568       || ! buf_read_int (core, &ptr, end, &si_code))
12569     {
12570     fail:
12571       printf ("    Not enough data in NT_SIGINFO note.\n");
12572       return;
12573     }
12574
12575   /* Next is a pointer-aligned union of structures.  On 64-bit
12576      machines, that implies a word of padding.  */
12577   if (gelf_getclass (core) == ELFCLASS64)
12578     ptr += 4;
12579
12580   printf ("    si_signo: %d, si_errno: %d, si_code: %d\n",
12581           si_signo, si_errno, si_code);
12582
12583   if (si_code > 0)
12584     switch (si_signo)
12585       {
12586       case CORE_SIGILL:
12587       case CORE_SIGFPE:
12588       case CORE_SIGSEGV:
12589       case CORE_SIGBUS:
12590         {
12591           uint64_t addr;
12592           if (! buf_read_ulong (core, &ptr, end, &addr))
12593             goto fail;
12594           printf ("    fault address: %#" PRIx64 "\n", addr);
12595           break;
12596         }
12597       default:
12598         ;
12599       }
12600   else if (si_code == CORE_SI_USER)
12601     {
12602       int pid, uid;
12603       if (! buf_read_int (core, &ptr, end, &pid)
12604           || ! buf_read_int (core, &ptr, end, &uid))
12605         goto fail;
12606       printf ("    sender PID: %d, sender UID: %d\n", pid, uid);
12607     }
12608 }
12609
12610 static void
12611 handle_file_note (Elf *core, GElf_Word descsz, GElf_Off desc_pos)
12612 {
12613   Elf_Data *data = elf_getdata_rawchunk (core, desc_pos, descsz, ELF_T_BYTE);
12614   if (data == NULL)
12615     error_exit (0, _("cannot convert core note data: %s"), elf_errmsg (-1));
12616
12617   unsigned char const *ptr = data->d_buf;
12618   unsigned char const *const end = data->d_buf + data->d_size;
12619
12620   uint64_t count, page_size;
12621   if (! buf_read_ulong (core, &ptr, end, &count)
12622       || ! buf_read_ulong (core, &ptr, end, &page_size))
12623     {
12624     fail:
12625       printf ("    Not enough data in NT_FILE note.\n");
12626       return;
12627     }
12628
12629   size_t addrsize = gelf_fsize (core, ELF_T_ADDR, 1, EV_CURRENT);
12630   uint64_t maxcount = (size_t) (end - ptr) / (3 * addrsize);
12631   if (count > maxcount)
12632     goto fail;
12633
12634   /* Where file names are stored.  */
12635   unsigned char const *const fstart = ptr + 3 * count * addrsize;
12636   char const *fptr = (char *) fstart;
12637
12638   printf ("    %" PRId64 " files:\n", count);
12639   for (uint64_t i = 0; i < count; ++i)
12640     {
12641       uint64_t mstart, mend, moffset;
12642       if (! buf_read_ulong (core, &ptr, fstart, &mstart)
12643           || ! buf_read_ulong (core, &ptr, fstart, &mend)
12644           || ! buf_read_ulong (core, &ptr, fstart, &moffset))
12645         goto fail;
12646
12647       const char *fnext = memchr (fptr, '\0', (char *) end - fptr);
12648       if (fnext == NULL)
12649         goto fail;
12650
12651       int ct = printf ("      %08" PRIx64 "-%08" PRIx64
12652                        " %08" PRIx64 " %" PRId64,
12653                        mstart, mend, moffset * page_size, mend - mstart);
12654       printf ("%*s%s\n", ct > 50 ? 3 : 53 - ct, "", fptr);
12655
12656       fptr = fnext + 1;
12657     }
12658 }
12659
12660 static void
12661 handle_core_note (Ebl *ebl, const GElf_Nhdr *nhdr,
12662                   const char *name, const void *desc)
12663 {
12664   GElf_Word regs_offset;
12665   size_t nregloc;
12666   const Ebl_Register_Location *reglocs;
12667   size_t nitems;
12668   const Ebl_Core_Item *items;
12669
12670   if (! ebl_core_note (ebl, nhdr, name, desc,
12671                        &regs_offset, &nregloc, &reglocs, &nitems, &items))
12672     return;
12673
12674   /* Pass 0 for DESCSZ when there are registers in the note,
12675      so that the ITEMS array does not describe the whole thing.
12676      For non-register notes, the actual descsz might be a multiple
12677      of the unit size, not just exactly the unit size.  */
12678   unsigned int colno = handle_core_items (ebl->elf, desc,
12679                                           nregloc == 0 ? nhdr->n_descsz : 0,
12680                                           items, nitems);
12681   if (colno != 0)
12682     putchar_unlocked ('\n');
12683
12684   colno = handle_core_registers (ebl, ebl->elf, desc + regs_offset,
12685                                  reglocs, nregloc);
12686   if (colno != 0)
12687     putchar_unlocked ('\n');
12688 }
12689
12690 static void
12691 handle_notes_data (Ebl *ebl, const GElf_Ehdr *ehdr,
12692                    GElf_Off start, Elf_Data *data)
12693 {
12694   fputs_unlocked (_("  Owner          Data size  Type\n"), stdout);
12695
12696   if (data == NULL)
12697     goto bad_note;
12698
12699   size_t offset = 0;
12700   GElf_Nhdr nhdr;
12701   size_t name_offset;
12702   size_t desc_offset;
12703   while (offset < data->d_size
12704          && (offset = gelf_getnote (data, offset,
12705                                     &nhdr, &name_offset, &desc_offset)) > 0)
12706     {
12707       const char *name = nhdr.n_namesz == 0 ? "" : data->d_buf + name_offset;
12708       const char *desc = data->d_buf + desc_offset;
12709
12710       /* GNU Build Attributes are weird, they store most of their data
12711          into the owner name field.  Extract just the owner name
12712          prefix here, then use the rest later as data.  */
12713       bool is_gnu_build_attr
12714         = startswith (name, ELF_NOTE_GNU_BUILD_ATTRIBUTE_PREFIX);
12715       const char *print_name = (is_gnu_build_attr
12716                                 ? ELF_NOTE_GNU_BUILD_ATTRIBUTE_PREFIX : name);
12717       size_t print_namesz = (is_gnu_build_attr
12718                              ? strlen (print_name) : nhdr.n_namesz);
12719
12720       char buf[100];
12721       char buf2[100];
12722       printf (_("  %-13.*s  %9" PRId32 "  %s\n"),
12723               (int) print_namesz, print_name, nhdr.n_descsz,
12724               ehdr->e_type == ET_CORE
12725               ? ebl_core_note_type_name (ebl, nhdr.n_type,
12726                                          buf, sizeof (buf))
12727               : ebl_object_note_type_name (ebl, name, nhdr.n_type,
12728                                            nhdr.n_descsz,
12729                                            buf2, sizeof (buf2)));
12730
12731       /* Filter out invalid entries.  */
12732       if (memchr (name, '\0', nhdr.n_namesz) != NULL
12733           /* XXX For now help broken Linux kernels.  */
12734           || 1)
12735         {
12736           if (ehdr->e_type == ET_CORE)
12737             {
12738               if (nhdr.n_type == NT_AUXV
12739                   && (nhdr.n_namesz == 4 /* Broken old Linux kernels.  */
12740                       || (nhdr.n_namesz == 5 && name[4] == '\0'))
12741                   && !memcmp (name, "CORE", 4))
12742                 handle_auxv_note (ebl, ebl->elf, nhdr.n_descsz,
12743                                   start + desc_offset);
12744               else if (nhdr.n_namesz == 5 && strcmp (name, "CORE") == 0)
12745                 switch (nhdr.n_type)
12746                   {
12747                   case NT_SIGINFO:
12748                     handle_siginfo_note (ebl->elf, nhdr.n_descsz,
12749                                          start + desc_offset);
12750                     break;
12751
12752                   case NT_FILE:
12753                     handle_file_note (ebl->elf, nhdr.n_descsz,
12754                                       start + desc_offset);
12755                     break;
12756
12757                   default:
12758                     handle_core_note (ebl, &nhdr, name, desc);
12759                   }
12760               else
12761                 handle_core_note (ebl, &nhdr, name, desc);
12762             }
12763           else
12764             ebl_object_note (ebl, nhdr.n_namesz, name, nhdr.n_type,
12765                              nhdr.n_descsz, desc);
12766         }
12767     }
12768
12769   if (offset == data->d_size)
12770     return;
12771
12772  bad_note:
12773   error (0, 0,
12774          _("cannot get content of note: %s"),
12775          data != NULL ? "garbage data" : elf_errmsg (-1));
12776 }
12777
12778 static void
12779 handle_notes (Ebl *ebl, GElf_Ehdr *ehdr)
12780 {
12781   /* If we have section headers, just look for SHT_NOTE sections.
12782      In a debuginfo file, the program headers are not reliable.  */
12783   if (shnum != 0)
12784     {
12785       /* Get the section header string table index.  */
12786       size_t shstrndx;
12787       if (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0)
12788         error_exit (0, _("cannot get section header string table index"));
12789
12790       Elf_Scn *scn = NULL;
12791       while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
12792         {
12793           GElf_Shdr shdr_mem;
12794           GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
12795
12796           if (shdr == NULL || shdr->sh_type != SHT_NOTE)
12797             /* Not what we are looking for.  */
12798             continue;
12799
12800           if (notes_section != NULL)
12801             {
12802               char *sname = elf_strptr (ebl->elf, shstrndx, shdr->sh_name);
12803               if (sname == NULL || strcmp (sname, notes_section) != 0)
12804                 continue;
12805             }
12806
12807           printf (_("\
12808 \nNote section [%2zu] '%s' of %" PRIu64 " bytes at offset %#0" PRIx64 ":\n"),
12809                   elf_ndxscn (scn),
12810                   elf_strptr (ebl->elf, shstrndx, shdr->sh_name),
12811                   shdr->sh_size, shdr->sh_offset);
12812
12813           handle_notes_data (ebl, ehdr, shdr->sh_offset,
12814                              elf_getdata (scn, NULL));
12815         }
12816       return;
12817     }
12818
12819   /* We have to look through the program header to find the note
12820      sections.  There can be more than one.  */
12821   for (size_t cnt = 0; cnt < phnum; ++cnt)
12822     {
12823       GElf_Phdr mem;
12824       GElf_Phdr *phdr = gelf_getphdr (ebl->elf, cnt, &mem);
12825
12826       if (phdr == NULL || phdr->p_type != PT_NOTE)
12827         /* Not what we are looking for.  */
12828         continue;
12829
12830       printf (_("\
12831 \nNote segment of %" PRIu64 " bytes at offset %#0" PRIx64 ":\n"),
12832               phdr->p_filesz, phdr->p_offset);
12833
12834       handle_notes_data (ebl, ehdr, phdr->p_offset,
12835                          elf_getdata_rawchunk (ebl->elf,
12836                                                phdr->p_offset, phdr->p_filesz,
12837                                                (phdr->p_align == 8
12838                                                 ? ELF_T_NHDR8 : ELF_T_NHDR)));
12839     }
12840 }
12841
12842
12843 static void
12844 hex_dump (const uint8_t *data, size_t len)
12845 {
12846   size_t pos = 0;
12847   while (pos < len)
12848     {
12849       printf ("  0x%08zx ", pos);
12850
12851       const size_t chunk = MIN (len - pos, 16);
12852
12853       for (size_t i = 0; i < chunk; ++i)
12854         if (i % 4 == 3)
12855           printf ("%02x ", data[pos + i]);
12856         else
12857           printf ("%02x", data[pos + i]);
12858
12859       if (chunk < 16)
12860         printf ("%*s", (int) ((16 - chunk) * 2 + (16 - chunk + 3) / 4), "");
12861
12862       for (size_t i = 0; i < chunk; ++i)
12863         {
12864           unsigned char b = data[pos + i];
12865           printf ("%c", isprint (b) ? b : '.');
12866         }
12867
12868       putchar ('\n');
12869       pos += chunk;
12870     }
12871 }
12872
12873 static void
12874 dump_data_section (Elf_Scn *scn, const GElf_Shdr *shdr, const char *name)
12875 {
12876   if (shdr->sh_size == 0 || shdr->sh_type == SHT_NOBITS)
12877     printf (_("\nSection [%zu] '%s' has no data to dump.\n"),
12878             elf_ndxscn (scn), name);
12879   else
12880     {
12881       if (print_decompress)
12882         {
12883           /* We try to decompress the section, but keep the old shdr around
12884              so we can show both the original shdr size and the uncompressed
12885              data size.   */
12886           if ((shdr->sh_flags & SHF_COMPRESSED) != 0)
12887             {
12888               if (elf_compress (scn, 0, 0) < 0)
12889                 printf ("WARNING: %s [%zd]\n",
12890                         _("Couldn't uncompress section"),
12891                         elf_ndxscn (scn));
12892             }
12893           else if (startswith (name, ".zdebug"))
12894             {
12895               if (elf_compress_gnu (scn, 0, 0) < 0)
12896                 printf ("WARNING: %s [%zd]\n",
12897                         _("Couldn't uncompress section"),
12898                         elf_ndxscn (scn));
12899             }
12900         }
12901
12902       Elf_Data *data = elf_rawdata (scn, NULL);
12903       if (data == NULL)
12904         error (0, 0, _("cannot get data for section [%zu] '%s': %s"),
12905                elf_ndxscn (scn), name, elf_errmsg (-1));
12906       else
12907         {
12908           if (data->d_size == shdr->sh_size)
12909             printf (_("\nHex dump of section [%zu] '%s', %" PRIu64
12910                              " bytes at offset %#0" PRIx64 ":\n"),
12911                     elf_ndxscn (scn), name,
12912                     shdr->sh_size, shdr->sh_offset);
12913           else
12914             printf (_("\nHex dump of section [%zu] '%s', %" PRIu64
12915                              " bytes (%zd uncompressed) at offset %#0"
12916                              PRIx64 ":\n"),
12917                     elf_ndxscn (scn), name,
12918                     shdr->sh_size, data->d_size, shdr->sh_offset);
12919           hex_dump (data->d_buf, data->d_size);
12920         }
12921     }
12922 }
12923
12924 static void
12925 print_string_section (Elf_Scn *scn, const GElf_Shdr *shdr, const char *name)
12926 {
12927   if (shdr->sh_size == 0 || shdr->sh_type == SHT_NOBITS)
12928     printf (_("\nSection [%zu] '%s' has no strings to dump.\n"),
12929             elf_ndxscn (scn), name);
12930   else
12931     {
12932       if (print_decompress)
12933         {
12934           /* We try to decompress the section, but keep the old shdr around
12935              so we can show both the original shdr size and the uncompressed
12936              data size.  */
12937           if ((shdr->sh_flags & SHF_COMPRESSED) != 0)
12938             {
12939               if (elf_compress (scn, 0, 0) < 0)
12940                 printf ("WARNING: %s [%zd]\n",
12941                         _("Couldn't uncompress section"),
12942                         elf_ndxscn (scn));
12943             }
12944           else if (startswith (name, ".zdebug"))
12945             {
12946               if (elf_compress_gnu (scn, 0, 0) < 0)
12947                 printf ("WARNING: %s [%zd]\n",
12948                         _("Couldn't uncompress section"),
12949                         elf_ndxscn (scn));
12950             }
12951         }
12952
12953       Elf_Data *data = elf_rawdata (scn, NULL);
12954       if (data == NULL)
12955         error (0, 0, _("cannot get data for section [%zu] '%s': %s"),
12956                elf_ndxscn (scn), name, elf_errmsg (-1));
12957       else
12958         {
12959           if (data->d_size == shdr->sh_size)
12960             printf (_("\nString section [%zu] '%s' contains %" PRIu64
12961                              " bytes at offset %#0" PRIx64 ":\n"),
12962                     elf_ndxscn (scn), name,
12963                     shdr->sh_size, shdr->sh_offset);
12964           else
12965             printf (_("\nString section [%zu] '%s' contains %" PRIu64
12966                              " bytes (%zd uncompressed) at offset %#0"
12967                              PRIx64 ":\n"),
12968                     elf_ndxscn (scn), name,
12969                     shdr->sh_size, data->d_size, shdr->sh_offset);
12970
12971           const char *start = data->d_buf;
12972           const char *const limit = start + data->d_size;
12973           do
12974             {
12975               const char *end = memchr (start, '\0', limit - start);
12976               const size_t pos = start - (const char *) data->d_buf;
12977               if (unlikely (end == NULL))
12978                 {
12979                   printf ("  [%6zx]- %.*s\n",
12980                           pos, (int) (limit - start), start);
12981                   break;
12982                 }
12983               printf ("  [%6zx]  %s\n", pos, start);
12984               start = end + 1;
12985             } while (start < limit);
12986         }
12987     }
12988 }
12989
12990 static void
12991 for_each_section_argument (Elf *elf, const struct section_argument *list,
12992                            void (*dump) (Elf_Scn *scn, const GElf_Shdr *shdr,
12993                                          const char *name))
12994 {
12995   /* Get the section header string table index.  */
12996   size_t shstrndx;
12997   if (elf_getshdrstrndx (elf, &shstrndx) < 0)
12998     error_exit (0, _("cannot get section header string table index"));
12999
13000   for (const struct section_argument *a = list; a != NULL; a = a->next)
13001     {
13002       Elf_Scn *scn;
13003       GElf_Shdr shdr_mem;
13004       const char *name = NULL;
13005
13006       char *endp = NULL;
13007       unsigned long int shndx = strtoul (a->arg, &endp, 0);
13008       if (endp != a->arg && *endp == '\0')
13009         {
13010           scn = elf_getscn (elf, shndx);
13011           if (scn == NULL)
13012             {
13013               error (0, 0, _("\nsection [%lu] does not exist"), shndx);
13014               continue;
13015             }
13016
13017           if (gelf_getshdr (scn, &shdr_mem) == NULL)
13018             error_exit (0, _("cannot get section header: %s"),
13019                         elf_errmsg (-1));
13020           name = elf_strptr (elf, shstrndx, shdr_mem.sh_name);
13021           (*dump) (scn, &shdr_mem, name);
13022         }
13023       else
13024         {
13025           /* Need to look up the section by name.  */
13026           scn = NULL;
13027           bool found = false;
13028           while ((scn = elf_nextscn (elf, scn)) != NULL)
13029             {
13030               if (gelf_getshdr (scn, &shdr_mem) == NULL)
13031                 continue;
13032               name = elf_strptr (elf, shstrndx, shdr_mem.sh_name);
13033               if (name == NULL)
13034                 continue;
13035               if (!strcmp (name, a->arg))
13036                 {
13037                   found = true;
13038                   (*dump) (scn, &shdr_mem, name);
13039                 }
13040             }
13041
13042           if (unlikely (!found) && !a->implicit)
13043             error (0, 0, _("\nsection '%s' does not exist"), a->arg);
13044         }
13045     }
13046 }
13047
13048 static void
13049 dump_data (Ebl *ebl)
13050 {
13051   for_each_section_argument (ebl->elf, dump_data_sections, &dump_data_section);
13052 }
13053
13054 static void
13055 dump_strings (Ebl *ebl)
13056 {
13057   for_each_section_argument (ebl->elf, string_sections, &print_string_section);
13058 }
13059
13060 static void
13061 print_strings (Ebl *ebl)
13062 {
13063   /* Get the section header string table index.  */
13064   size_t shstrndx;
13065   if (unlikely (elf_getshdrstrndx (ebl->elf, &shstrndx) < 0))
13066     error_exit (0, _("cannot get section header string table index"));
13067
13068   Elf_Scn *scn;
13069   GElf_Shdr shdr_mem;
13070   const char *name;
13071   scn = NULL;
13072   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
13073     {
13074       if (gelf_getshdr (scn, &shdr_mem) == NULL)
13075         continue;
13076
13077       if (shdr_mem.sh_type != SHT_PROGBITS
13078           || !(shdr_mem.sh_flags & SHF_STRINGS))
13079         continue;
13080
13081       name = elf_strptr (ebl->elf, shstrndx, shdr_mem.sh_name);
13082       if (name == NULL)
13083         continue;
13084
13085       print_string_section (scn, &shdr_mem, name);
13086     }
13087 }
13088
13089 static void
13090 dump_archive_index (Elf *elf, const char *fname)
13091 {
13092   size_t narsym;
13093   const Elf_Arsym *arsym = elf_getarsym (elf, &narsym);
13094   if (arsym == NULL)
13095     {
13096       int result = elf_errno ();
13097       if (unlikely (result != ELF_E_NO_INDEX))
13098         error_exit (0, _("cannot get symbol index of archive '%s': %s"),
13099                     fname, elf_errmsg (result));
13100       else
13101         printf (_("\nArchive '%s' has no symbol index\n"), fname);
13102       return;
13103     }
13104
13105   printf (_("\nIndex of archive '%s' has %zu entries:\n"),
13106           fname, narsym);
13107
13108   size_t as_off = 0;
13109   for (const Elf_Arsym *s = arsym; s < &arsym[narsym - 1]; ++s)
13110     {
13111       if (s->as_off != as_off)
13112         {
13113           as_off = s->as_off;
13114
13115           Elf *subelf = NULL;
13116           if (unlikely (elf_rand (elf, as_off) == 0)
13117               || unlikely ((subelf = elf_begin (-1, ELF_C_READ_MMAP, elf))
13118                            == NULL))
13119 #if __GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 7)
13120             while (1)
13121 #endif
13122               error_exit (0,
13123                           _("cannot extract member at offset %zu in '%s': %s"),
13124                           as_off, fname, elf_errmsg (-1));
13125
13126           const Elf_Arhdr *h = elf_getarhdr (subelf);
13127
13128           printf (_("Archive member '%s' contains:\n"), h->ar_name);
13129
13130           elf_end (subelf);
13131         }
13132
13133       printf ("\t%s\n", s->as_name);
13134     }
13135 }
13136
13137 #include "debugpred.h"