Fix a possible integer overflow problem when examining corrupt binaries using a 32...
[external/binutils.git] / binutils / objdump.c
1 /* objdump.c -- dump information about an object file.
2    Copyright (C) 1990-2019 Free Software Foundation, Inc.
3
4    This file is part of GNU Binutils.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3, or (at your option)
9    any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, 51 Franklin Street - Fifth Floor, Boston,
19    MA 02110-1301, USA.  */
20
21
22 /* Objdump overview.
23
24    Objdump displays information about one or more object files, either on
25    their own, or inside libraries.  It is commonly used as a disassembler,
26    but it can also display information about file headers, symbol tables,
27    relocations, debugging directives and more.
28
29    The flow of execution is as follows:
30
31    1. Command line arguments are checked for control switches and the
32       information to be displayed is selected.
33
34    2. Any remaining arguments are assumed to be object files, and they are
35       processed in order by display_bfd().  If the file is an archive each
36       of its elements is processed in turn.
37
38    3. The file's target architecture and binary file format are determined
39       by bfd_check_format().  If they are recognised, then dump_bfd() is
40       called.
41
42    4. dump_bfd() in turn calls separate functions to display the requested
43       item(s) of information(s).  For example disassemble_data() is called if
44       a disassembly has been requested.
45
46    When disassembling the code loops through blocks of instructions bounded
47    by symbols, calling disassemble_bytes() on each block.  The actual
48    disassembling is done by the libopcodes library, via a function pointer
49    supplied by the disassembler() function.  */
50
51 #include "sysdep.h"
52 #include "bfd.h"
53 #include "elf-bfd.h"
54 #include "coff-bfd.h"
55 #include "progress.h"
56 #include "bucomm.h"
57 #include "elfcomm.h"
58 #include "dwarf.h"
59 #include "getopt.h"
60 #include "safe-ctype.h"
61 #include "dis-asm.h"
62 #include "libiberty.h"
63 #include "demangle.h"
64 #include "filenames.h"
65 #include "debug.h"
66 #include "budbg.h"
67 #include "objdump.h"
68
69 #ifdef HAVE_MMAP
70 #include <sys/mman.h>
71 #endif
72
73 /* Internal headers for the ELF .stab-dump code - sorry.  */
74 #define BYTES_IN_WORD   32
75 #include "aout/aout64.h"
76
77 /* Exit status.  */
78 static int exit_status = 0;
79
80 static char *default_target = NULL;     /* Default at runtime.  */
81
82 /* The following variables are set based on arguments passed on the
83    command line.  */
84 static int show_version = 0;            /* Show the version number.  */
85 static int dump_section_contents;       /* -s */
86 static int dump_section_headers;        /* -h */
87 static bfd_boolean dump_file_header;    /* -f */
88 static int dump_symtab;                 /* -t */
89 static int dump_dynamic_symtab;         /* -T */
90 static int dump_reloc_info;             /* -r */
91 static int dump_dynamic_reloc_info;     /* -R */
92 static int dump_ar_hdrs;                /* -a */
93 static int dump_private_headers;        /* -p */
94 static char *dump_private_options;      /* -P */
95 static int prefix_addresses;            /* --prefix-addresses */
96 static int with_line_numbers;           /* -l */
97 static bfd_boolean with_source_code;    /* -S */
98 static int show_raw_insn;               /* --show-raw-insn */
99 static int dump_dwarf_section_info;     /* --dwarf */
100 static int dump_stab_section_info;      /* --stabs */
101 static int do_demangle;                 /* -C, --demangle */
102 static bfd_boolean disassemble;         /* -d */
103 static bfd_boolean disassemble_all;     /* -D */
104 static int disassemble_zeroes;          /* --disassemble-zeroes */
105 static bfd_boolean formats_info;        /* -i */
106 static int wide_output;                 /* -w */
107 static int insn_width;                  /* --insn-width */
108 static bfd_vma start_address = (bfd_vma) -1; /* --start-address */
109 static bfd_vma stop_address = (bfd_vma) -1;  /* --stop-address */
110 static int dump_debugging;              /* --debugging */
111 static int dump_debugging_tags;         /* --debugging-tags */
112 static int suppress_bfd_header;
113 static int dump_special_syms = 0;       /* --special-syms */
114 static bfd_vma adjust_section_vma = 0;  /* --adjust-vma */
115 static int file_start_context = 0;      /* --file-start-context */
116 static bfd_boolean display_file_offsets;/* -F */
117 static const char *prefix;              /* --prefix */
118 static int prefix_strip;                /* --prefix-strip */
119 static size_t prefix_length;
120 static bfd_boolean unwind_inlines;      /* --inlines.  */
121 static const char * disasm_sym;         /* Disassembly start symbol.  */
122
123 static int demangle_flags = DMGL_ANSI | DMGL_PARAMS;
124
125 /* A structure to record the sections mentioned in -j switches.  */
126 struct only
127 {
128   const char * name; /* The name of the section.  */
129   bfd_boolean  seen; /* A flag to indicate that the section has been found in one or more input files.  */
130   struct only * next; /* Pointer to the next structure in the list.  */
131 };
132 /* Pointer to an array of 'only' structures.
133    This pointer is NULL if the -j switch has not been used.  */
134 static struct only * only_list = NULL;
135
136 /* Variables for handling include file path table.  */
137 static const char **include_paths;
138 static int include_path_count;
139
140 /* Extra info to pass to the section disassembler and address printing
141    function.  */
142 struct objdump_disasm_info
143 {
144   bfd *              abfd;
145   asection *         sec;
146   bfd_boolean        require_sec;
147   arelent **         dynrelbuf;
148   long               dynrelcount;
149   disassembler_ftype disassemble_fn;
150   arelent *          reloc;
151   const char *       symbol;
152 };
153
154 /* Architecture to disassemble for, or default if NULL.  */
155 static char *machine = NULL;
156
157 /* Target specific options to the disassembler.  */
158 static char *disassembler_options = NULL;
159
160 /* Endianness to disassemble for, or default if BFD_ENDIAN_UNKNOWN.  */
161 static enum bfd_endian endian = BFD_ENDIAN_UNKNOWN;
162
163 /* The symbol table.  */
164 static asymbol **syms;
165
166 /* Number of symbols in `syms'.  */
167 static long symcount = 0;
168
169 /* The sorted symbol table.  */
170 static asymbol **sorted_syms;
171
172 /* Number of symbols in `sorted_syms'.  */
173 static long sorted_symcount = 0;
174
175 /* The dynamic symbol table.  */
176 static asymbol **dynsyms;
177
178 /* The synthetic symbol table.  */
179 static asymbol *synthsyms;
180 static long synthcount = 0;
181
182 /* Number of symbols in `dynsyms'.  */
183 static long dynsymcount = 0;
184
185 static bfd_byte *stabs;
186 static bfd_size_type stab_size;
187
188 static bfd_byte *strtab;
189 static bfd_size_type stabstr_size;
190
191 static bfd_boolean is_relocatable = FALSE;
192
193 /* Handlers for -P/--private.  */
194 static const struct objdump_private_desc * const objdump_private_vectors[] =
195   {
196     OBJDUMP_PRIVATE_VECTORS
197     NULL
198   };
199 \f
200 static void usage (FILE *, int) ATTRIBUTE_NORETURN;
201 static void
202 usage (FILE *stream, int status)
203 {
204   fprintf (stream, _("Usage: %s <option(s)> <file(s)>\n"), program_name);
205   fprintf (stream, _(" Display information from object <file(s)>.\n"));
206   fprintf (stream, _(" At least one of the following switches must be given:\n"));
207   fprintf (stream, _("\
208   -a, --archive-headers    Display archive header information\n\
209   -f, --file-headers       Display the contents of the overall file header\n\
210   -p, --private-headers    Display object format specific file header contents\n\
211   -P, --private=OPT,OPT... Display object format specific contents\n\
212   -h, --[section-]headers  Display the contents of the section headers\n\
213   -x, --all-headers        Display the contents of all headers\n\
214   -d, --disassemble        Display assembler contents of executable sections\n\
215   -D, --disassemble-all    Display assembler contents of all sections\n\
216       --disassemble=<sym>  Display assembler contents from <sym>\n\
217   -S, --source             Intermix source code with disassembly\n\
218   -s, --full-contents      Display the full contents of all sections requested\n\
219   -g, --debugging          Display debug information in object file\n\
220   -e, --debugging-tags     Display debug information using ctags style\n\
221   -G, --stabs              Display (in raw form) any STABS info in the file\n\
222   -W[lLiaprmfFsoRtUuTgAckK] or\n\
223   --dwarf[=rawline,=decodedline,=info,=abbrev,=pubnames,=aranges,=macro,=frames,\n\
224           =frames-interp,=str,=loc,=Ranges,=pubtypes,\n\
225           =gdb_index,=trace_info,=trace_abbrev,=trace_aranges,\n\
226           =addr,=cu_index,=links,=follow-links]\n\
227                            Display DWARF info in the file\n\
228   -t, --syms               Display the contents of the symbol table(s)\n\
229   -T, --dynamic-syms       Display the contents of the dynamic symbol table\n\
230   -r, --reloc              Display the relocation entries in the file\n\
231   -R, --dynamic-reloc      Display the dynamic relocation entries in the file\n\
232   @<file>                  Read options from <file>\n\
233   -v, --version            Display this program's version number\n\
234   -i, --info               List object formats and architectures supported\n\
235   -H, --help               Display this information\n\
236 "));
237   if (status != 2)
238     {
239       const struct objdump_private_desc * const *desc;
240
241       fprintf (stream, _("\n The following switches are optional:\n"));
242       fprintf (stream, _("\
243   -b, --target=BFDNAME           Specify the target object format as BFDNAME\n\
244   -m, --architecture=MACHINE     Specify the target architecture as MACHINE\n\
245   -j, --section=NAME             Only display information for section NAME\n\
246   -M, --disassembler-options=OPT Pass text OPT on to the disassembler\n\
247   -EB --endian=big               Assume big endian format when disassembling\n\
248   -EL --endian=little            Assume little endian format when disassembling\n\
249       --file-start-context       Include context from start of file (with -S)\n\
250   -I, --include=DIR              Add DIR to search list for source files\n\
251   -l, --line-numbers             Include line numbers and filenames in output\n\
252   -F, --file-offsets             Include file offsets when displaying information\n\
253   -C, --demangle[=STYLE]         Decode mangled/processed symbol names\n\
254                                   The STYLE, if specified, can be `auto', `gnu',\n\
255                                   `lucid', `arm', `hp', `edg', `gnu-v3', `java'\n\
256                                   or `gnat'\n\
257       --recurse-limit            Enable a limit on recursion whilst demangling.  [Default]\n\
258       --no-recurse-limit         Disable a limit on recursion whilst demangling\n\
259   -w, --wide                     Format output for more than 80 columns\n\
260   -z, --disassemble-zeroes       Do not skip blocks of zeroes when disassembling\n\
261       --start-address=ADDR       Only process data whose address is >= ADDR\n\
262       --stop-address=ADDR        Only process data whose address is <= ADDR\n\
263       --prefix-addresses         Print complete address alongside disassembly\n\
264       --[no-]show-raw-insn       Display hex alongside symbolic disassembly\n\
265       --insn-width=WIDTH         Display WIDTH bytes on a single line for -d\n\
266       --adjust-vma=OFFSET        Add OFFSET to all displayed section addresses\n\
267       --special-syms             Include special symbols in symbol dumps\n\
268       --inlines                  Print all inlines for source line (with -l)\n\
269       --prefix=PREFIX            Add PREFIX to absolute paths for -S\n\
270       --prefix-strip=LEVEL       Strip initial directory names for -S\n"));
271       fprintf (stream, _("\
272       --dwarf-depth=N        Do not display DIEs at depth N or greater\n\
273       --dwarf-start=N        Display DIEs starting with N, at the same depth\n\
274                              or deeper\n\
275       --dwarf-check          Make additional dwarf internal consistency checks.\
276       \n\n"));
277       list_supported_targets (program_name, stream);
278       list_supported_architectures (program_name, stream);
279
280       disassembler_usage (stream);
281
282       if (objdump_private_vectors[0] != NULL)
283         {
284           fprintf (stream,
285                    _("\nOptions supported for -P/--private switch:\n"));
286           for (desc = objdump_private_vectors; *desc != NULL; desc++)
287             (*desc)->help (stream);
288         }
289     }
290   if (REPORT_BUGS_TO[0] && status == 0)
291     fprintf (stream, _("Report bugs to %s.\n"), REPORT_BUGS_TO);
292   exit (status);
293 }
294
295 /* 150 isn't special; it's just an arbitrary non-ASCII char value.  */
296 enum option_values
297   {
298     OPTION_ENDIAN=150,
299     OPTION_START_ADDRESS,
300     OPTION_STOP_ADDRESS,
301     OPTION_DWARF,
302     OPTION_PREFIX,
303     OPTION_PREFIX_STRIP,
304     OPTION_INSN_WIDTH,
305     OPTION_ADJUST_VMA,
306     OPTION_DWARF_DEPTH,
307     OPTION_DWARF_CHECK,
308     OPTION_DWARF_START,
309     OPTION_RECURSE_LIMIT,
310     OPTION_NO_RECURSE_LIMIT,
311     OPTION_INLINES
312   };
313
314 static struct option long_options[]=
315 {
316   {"adjust-vma", required_argument, NULL, OPTION_ADJUST_VMA},
317   {"all-headers", no_argument, NULL, 'x'},
318   {"private-headers", no_argument, NULL, 'p'},
319   {"private", required_argument, NULL, 'P'},
320   {"architecture", required_argument, NULL, 'm'},
321   {"archive-headers", no_argument, NULL, 'a'},
322   {"debugging", no_argument, NULL, 'g'},
323   {"debugging-tags", no_argument, NULL, 'e'},
324   {"demangle", optional_argument, NULL, 'C'},
325   {"disassemble", optional_argument, NULL, 'd'},
326   {"disassemble-all", no_argument, NULL, 'D'},
327   {"disassembler-options", required_argument, NULL, 'M'},
328   {"disassemble-zeroes", no_argument, NULL, 'z'},
329   {"dynamic-reloc", no_argument, NULL, 'R'},
330   {"dynamic-syms", no_argument, NULL, 'T'},
331   {"endian", required_argument, NULL, OPTION_ENDIAN},
332   {"file-headers", no_argument, NULL, 'f'},
333   {"file-offsets", no_argument, NULL, 'F'},
334   {"file-start-context", no_argument, &file_start_context, 1},
335   {"full-contents", no_argument, NULL, 's'},
336   {"headers", no_argument, NULL, 'h'},
337   {"help", no_argument, NULL, 'H'},
338   {"info", no_argument, NULL, 'i'},
339   {"line-numbers", no_argument, NULL, 'l'},
340   {"no-show-raw-insn", no_argument, &show_raw_insn, -1},
341   {"prefix-addresses", no_argument, &prefix_addresses, 1},
342   {"recurse-limit", no_argument, NULL, OPTION_RECURSE_LIMIT},
343   {"recursion-limit", no_argument, NULL, OPTION_RECURSE_LIMIT},
344   {"no-recurse-limit", no_argument, NULL, OPTION_NO_RECURSE_LIMIT},
345   {"no-recursion-limit", no_argument, NULL, OPTION_NO_RECURSE_LIMIT},
346   {"reloc", no_argument, NULL, 'r'},
347   {"section", required_argument, NULL, 'j'},
348   {"section-headers", no_argument, NULL, 'h'},
349   {"show-raw-insn", no_argument, &show_raw_insn, 1},
350   {"source", no_argument, NULL, 'S'},
351   {"special-syms", no_argument, &dump_special_syms, 1},
352   {"include", required_argument, NULL, 'I'},
353   {"dwarf", optional_argument, NULL, OPTION_DWARF},
354   {"stabs", no_argument, NULL, 'G'},
355   {"start-address", required_argument, NULL, OPTION_START_ADDRESS},
356   {"stop-address", required_argument, NULL, OPTION_STOP_ADDRESS},
357   {"syms", no_argument, NULL, 't'},
358   {"target", required_argument, NULL, 'b'},
359   {"version", no_argument, NULL, 'V'},
360   {"wide", no_argument, NULL, 'w'},
361   {"prefix", required_argument, NULL, OPTION_PREFIX},
362   {"prefix-strip", required_argument, NULL, OPTION_PREFIX_STRIP},
363   {"insn-width", required_argument, NULL, OPTION_INSN_WIDTH},
364   {"dwarf-depth", required_argument, 0, OPTION_DWARF_DEPTH},
365   {"dwarf-start", required_argument, 0, OPTION_DWARF_START},
366   {"dwarf-check", no_argument, 0, OPTION_DWARF_CHECK},
367   {"inlines", no_argument, 0, OPTION_INLINES},
368   {0, no_argument, 0, 0}
369 };
370 \f
371 static void
372 nonfatal (const char *msg)
373 {
374   bfd_nonfatal (msg);
375   exit_status = 1;
376 }
377 \f
378 /* Returns TRUE if the specified section should be dumped.  */
379
380 static bfd_boolean
381 process_section_p (asection * section)
382 {
383   struct only * only;
384
385   if (only_list == NULL)
386     return TRUE;
387
388   for (only = only_list; only; only = only->next)
389     if (strcmp (only->name, section->name) == 0)
390       {
391         only->seen = TRUE;
392         return TRUE;
393       }
394
395   return FALSE;
396 }
397
398 /* Add an entry to the 'only' list.  */
399
400 static void
401 add_only (char * name)
402 {
403   struct only * only;
404
405   /* First check to make sure that we do not
406      already have an entry for this name.  */
407   for (only = only_list; only; only = only->next)
408     if (strcmp (only->name, name) == 0)
409       return;
410
411   only = xmalloc (sizeof * only);
412   only->name = name;
413   only->seen = FALSE;
414   only->next = only_list;
415   only_list = only;
416 }
417
418 /* Release the memory used by the 'only' list.
419    PR 11225: Issue a warning message for unseen sections.
420    Only do this if none of the sections were seen.  This is mainly to support
421    tools like the GAS testsuite where an object file is dumped with a list of
422    generic section names known to be present in a range of different file
423    formats.  */
424
425 static void
426 free_only_list (void)
427 {
428   bfd_boolean at_least_one_seen = FALSE;
429   struct only * only;
430   struct only * next;
431
432   if (only_list == NULL)
433     return;
434
435   for (only = only_list; only; only = only->next)
436     if (only->seen)
437       {
438         at_least_one_seen = TRUE;
439         break;
440       }
441
442   for (only = only_list; only; only = next)
443     {
444       if (! at_least_one_seen)
445         {
446           non_fatal (_("section '%s' mentioned in a -j option, "
447                        "but not found in any input file"),
448                      only->name);
449           exit_status = 1;
450         }
451       next = only->next;
452       free (only);
453     }
454 }
455
456 \f
457 static void
458 dump_section_header (bfd *abfd, asection *section, void *data)
459 {
460   char *comma = "";
461   unsigned int opb = bfd_octets_per_byte (abfd);
462   int longest_section_name = *((int *) data);
463
464   /* Ignore linker created section.  See elfNN_ia64_object_p in
465      bfd/elfxx-ia64.c.  */
466   if (section->flags & SEC_LINKER_CREATED)
467     return;
468
469   /* PR 10413: Skip sections that we are ignoring.  */
470   if (! process_section_p (section))
471     return;
472
473   printf ("%3d %-*s %08lx  ", section->index, longest_section_name,
474           bfd_get_section_name (abfd, section),
475           (unsigned long) bfd_section_size (abfd, section) / opb);
476   bfd_printf_vma (abfd, bfd_get_section_vma (abfd, section));
477   printf ("  ");
478   bfd_printf_vma (abfd, section->lma);
479   printf ("  %08lx  2**%u", (unsigned long) section->filepos,
480           bfd_get_section_alignment (abfd, section));
481   if (! wide_output)
482     printf ("\n                ");
483   printf ("  ");
484
485 #define PF(x, y) \
486   if (section->flags & x) { printf ("%s%s", comma, y); comma = ", "; }
487
488   PF (SEC_HAS_CONTENTS, "CONTENTS");
489   PF (SEC_ALLOC, "ALLOC");
490   PF (SEC_CONSTRUCTOR, "CONSTRUCTOR");
491   PF (SEC_LOAD, "LOAD");
492   PF (SEC_RELOC, "RELOC");
493   PF (SEC_READONLY, "READONLY");
494   PF (SEC_CODE, "CODE");
495   PF (SEC_DATA, "DATA");
496   PF (SEC_ROM, "ROM");
497   PF (SEC_DEBUGGING, "DEBUGGING");
498   PF (SEC_NEVER_LOAD, "NEVER_LOAD");
499   PF (SEC_EXCLUDE, "EXCLUDE");
500   PF (SEC_SORT_ENTRIES, "SORT_ENTRIES");
501   if (bfd_get_arch (abfd) == bfd_arch_tic54x)
502     {
503       PF (SEC_TIC54X_BLOCK, "BLOCK");
504       PF (SEC_TIC54X_CLINK, "CLINK");
505     }
506   PF (SEC_SMALL_DATA, "SMALL_DATA");
507   if (bfd_get_flavour (abfd) == bfd_target_coff_flavour)
508     {
509       PF (SEC_COFF_SHARED, "SHARED");
510       PF (SEC_COFF_NOREAD, "NOREAD");
511     }
512   else if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
513     PF (SEC_ELF_PURECODE, "PURECODE");
514   PF (SEC_THREAD_LOCAL, "THREAD_LOCAL");
515   PF (SEC_GROUP, "GROUP");
516   if (bfd_get_arch (abfd) == bfd_arch_mep)
517     {
518       PF (SEC_MEP_VLIW, "VLIW");
519     }
520
521   if ((section->flags & SEC_LINK_ONCE) != 0)
522     {
523       const char *ls;
524       struct coff_comdat_info *comdat;
525
526       switch (section->flags & SEC_LINK_DUPLICATES)
527         {
528         default:
529           abort ();
530         case SEC_LINK_DUPLICATES_DISCARD:
531           ls = "LINK_ONCE_DISCARD";
532           break;
533         case SEC_LINK_DUPLICATES_ONE_ONLY:
534           ls = "LINK_ONCE_ONE_ONLY";
535           break;
536         case SEC_LINK_DUPLICATES_SAME_SIZE:
537           ls = "LINK_ONCE_SAME_SIZE";
538           break;
539         case SEC_LINK_DUPLICATES_SAME_CONTENTS:
540           ls = "LINK_ONCE_SAME_CONTENTS";
541           break;
542         }
543       printf ("%s%s", comma, ls);
544
545       comdat = bfd_coff_get_comdat_section (abfd, section);
546       if (comdat != NULL)
547         printf (" (COMDAT %s %ld)", comdat->name, comdat->symbol);
548
549       comma = ", ";
550     }
551
552   printf ("\n");
553 #undef PF
554 }
555
556 /* Called on each SECTION in ABFD, update the int variable pointed to by
557    DATA which contains the string length of the longest section name.  */
558
559 static void
560 find_longest_section_name (bfd *abfd, asection *section, void *data)
561 {
562   int *longest_so_far = (int *) data;
563   const char *name;
564   int len;
565
566   /* Ignore linker created section.  */
567   if (section->flags & SEC_LINKER_CREATED)
568     return;
569
570   /* Skip sections that we are ignoring.  */
571   if (! process_section_p (section))
572     return;
573
574   name = bfd_get_section_name (abfd, section);
575   len = (int) strlen (name);
576   if (len > *longest_so_far)
577     *longest_so_far = len;
578 }
579
580 static void
581 dump_headers (bfd *abfd)
582 {
583   /* The default width of 13 is just an arbitrary choice.  */
584   int max_section_name_length = 13;
585   int bfd_vma_width;
586
587 #ifndef BFD64
588   bfd_vma_width = 10;
589 #else
590   /* With BFD64, non-ELF returns -1 and wants always 64 bit addresses.  */
591   if (bfd_get_arch_size (abfd) == 32)
592     bfd_vma_width = 10;
593   else
594     bfd_vma_width = 18;
595 #endif
596
597   printf (_("Sections:\n"));
598
599   if (wide_output)
600     bfd_map_over_sections (abfd, find_longest_section_name,
601                            &max_section_name_length);
602
603   printf (_("Idx %-*s Size      %-*s%-*sFile off  Algn"),
604           max_section_name_length, "Name",
605           bfd_vma_width, "VMA",
606           bfd_vma_width, "LMA");
607
608   if (wide_output)
609     printf (_("  Flags"));
610   printf ("\n");
611
612   bfd_map_over_sections (abfd, dump_section_header,
613                          &max_section_name_length);
614 }
615 \f
616 static asymbol **
617 slurp_symtab (bfd *abfd)
618 {
619   asymbol **sy = NULL;
620   long storage;
621
622   if (!(bfd_get_file_flags (abfd) & HAS_SYMS))
623     {
624       symcount = 0;
625       return NULL;
626     }
627
628   storage = bfd_get_symtab_upper_bound (abfd);
629   if (storage < 0)
630     {
631       non_fatal (_("failed to read symbol table from: %s"), bfd_get_filename (abfd));
632       bfd_fatal (_("error message was"));
633     }
634   if (storage)
635     sy = (asymbol **) xmalloc (storage);
636
637   symcount = bfd_canonicalize_symtab (abfd, sy);
638   if (symcount < 0)
639     bfd_fatal (bfd_get_filename (abfd));
640   return sy;
641 }
642
643 /* Read in the dynamic symbols.  */
644
645 static asymbol **
646 slurp_dynamic_symtab (bfd *abfd)
647 {
648   asymbol **sy = NULL;
649   long storage;
650
651   storage = bfd_get_dynamic_symtab_upper_bound (abfd);
652   if (storage < 0)
653     {
654       if (!(bfd_get_file_flags (abfd) & DYNAMIC))
655         {
656           non_fatal (_("%s: not a dynamic object"), bfd_get_filename (abfd));
657           exit_status = 1;
658           dynsymcount = 0;
659           return NULL;
660         }
661
662       bfd_fatal (bfd_get_filename (abfd));
663     }
664   if (storage)
665     sy = (asymbol **) xmalloc (storage);
666
667   dynsymcount = bfd_canonicalize_dynamic_symtab (abfd, sy);
668   if (dynsymcount < 0)
669     bfd_fatal (bfd_get_filename (abfd));
670   return sy;
671 }
672
673 /* Some symbol names are significant and should be kept in the
674    table of sorted symbol names, even if they are marked as
675    debugging/section symbols.  */
676
677 static bfd_boolean
678 is_significant_symbol_name (const char * name)
679 {
680   return strncmp (name, ".plt", 4) == 0 || strcmp (name, ".got") == 0;
681 }
682
683 /* Filter out (in place) symbols that are useless for disassembly.
684    COUNT is the number of elements in SYMBOLS.
685    Return the number of useful symbols.  */
686
687 static long
688 remove_useless_symbols (asymbol **symbols, long count)
689 {
690   asymbol **in_ptr = symbols, **out_ptr = symbols;
691
692   while (--count >= 0)
693     {
694       asymbol *sym = *in_ptr++;
695
696       if (sym->name == NULL || sym->name[0] == '\0')
697         continue;
698       if ((sym->flags & (BSF_DEBUGGING | BSF_SECTION_SYM))
699           && ! is_significant_symbol_name (sym->name))
700         continue;
701       if (bfd_is_und_section (sym->section)
702           || bfd_is_com_section (sym->section))
703         continue;
704
705       *out_ptr++ = sym;
706     }
707   return out_ptr - symbols;
708 }
709
710 /* Sort symbols into value order.  */
711
712 static int
713 compare_symbols (const void *ap, const void *bp)
714 {
715   const asymbol *a = * (const asymbol **) ap;
716   const asymbol *b = * (const asymbol **) bp;
717   const char *an;
718   const char *bn;
719   size_t anl;
720   size_t bnl;
721   bfd_boolean af;
722   bfd_boolean bf;
723   flagword aflags;
724   flagword bflags;
725
726   if (bfd_asymbol_value (a) > bfd_asymbol_value (b))
727     return 1;
728   else if (bfd_asymbol_value (a) < bfd_asymbol_value (b))
729     return -1;
730
731   if (a->section > b->section)
732     return 1;
733   else if (a->section < b->section)
734     return -1;
735
736   an = bfd_asymbol_name (a);
737   bn = bfd_asymbol_name (b);
738   anl = strlen (an);
739   bnl = strlen (bn);
740
741   /* The symbols gnu_compiled and gcc2_compiled convey no real
742      information, so put them after other symbols with the same value.  */
743   af = (strstr (an, "gnu_compiled") != NULL
744         || strstr (an, "gcc2_compiled") != NULL);
745   bf = (strstr (bn, "gnu_compiled") != NULL
746         || strstr (bn, "gcc2_compiled") != NULL);
747
748   if (af && ! bf)
749     return 1;
750   if (! af && bf)
751     return -1;
752
753   /* We use a heuristic for the file name, to try to sort it after
754      more useful symbols.  It may not work on non Unix systems, but it
755      doesn't really matter; the only difference is precisely which
756      symbol names get printed.  */
757
758 #define file_symbol(s, sn, snl)                 \
759   (((s)->flags & BSF_FILE) != 0                 \
760    || ((sn)[(snl) - 2] == '.'                   \
761        && ((sn)[(snl) - 1] == 'o'               \
762            || (sn)[(snl) - 1] == 'a')))
763
764   af = file_symbol (a, an, anl);
765   bf = file_symbol (b, bn, bnl);
766
767   if (af && ! bf)
768     return 1;
769   if (! af && bf)
770     return -1;
771
772   /* Try to sort global symbols before local symbols before function
773      symbols before debugging symbols.  */
774
775   aflags = a->flags;
776   bflags = b->flags;
777
778   if ((aflags & BSF_DEBUGGING) != (bflags & BSF_DEBUGGING))
779     {
780       if ((aflags & BSF_DEBUGGING) != 0)
781         return 1;
782       else
783         return -1;
784     }
785   if ((aflags & BSF_FUNCTION) != (bflags & BSF_FUNCTION))
786     {
787       if ((aflags & BSF_FUNCTION) != 0)
788         return -1;
789       else
790         return 1;
791     }
792   if ((aflags & BSF_LOCAL) != (bflags & BSF_LOCAL))
793     {
794       if ((aflags & BSF_LOCAL) != 0)
795         return 1;
796       else
797         return -1;
798     }
799   if ((aflags & BSF_GLOBAL) != (bflags & BSF_GLOBAL))
800     {
801       if ((aflags & BSF_GLOBAL) != 0)
802         return -1;
803       else
804         return 1;
805     }
806
807   if (bfd_get_flavour (bfd_asymbol_bfd (a)) == bfd_target_elf_flavour
808       && bfd_get_flavour (bfd_asymbol_bfd (b)) == bfd_target_elf_flavour)
809     {
810       bfd_vma asz, bsz;
811
812       asz = 0;
813       if ((a->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) == 0)
814         asz = ((elf_symbol_type *) a)->internal_elf_sym.st_size;
815       bsz = 0;
816       if ((b->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) == 0)
817         bsz = ((elf_symbol_type *) b)->internal_elf_sym.st_size;
818       if (asz != bsz)
819         return asz > bsz ? -1 : 1;
820     }
821
822   /* Symbols that start with '.' might be section names, so sort them
823      after symbols that don't start with '.'.  */
824   if (an[0] == '.' && bn[0] != '.')
825     return 1;
826   if (an[0] != '.' && bn[0] == '.')
827     return -1;
828
829   /* Finally, if we can't distinguish them in any other way, try to
830      get consistent results by sorting the symbols by name.  */
831   return strcmp (an, bn);
832 }
833
834 /* Sort relocs into address order.  */
835
836 static int
837 compare_relocs (const void *ap, const void *bp)
838 {
839   const arelent *a = * (const arelent **) ap;
840   const arelent *b = * (const arelent **) bp;
841
842   if (a->address > b->address)
843     return 1;
844   else if (a->address < b->address)
845     return -1;
846
847   /* So that associated relocations tied to the same address show up
848      in the correct order, we don't do any further sorting.  */
849   if (a > b)
850     return 1;
851   else if (a < b)
852     return -1;
853   else
854     return 0;
855 }
856
857 /* Print an address (VMA) to the output stream in INFO.
858    If SKIP_ZEROES is TRUE, omit leading zeroes.  */
859
860 static void
861 objdump_print_value (bfd_vma vma, struct disassemble_info *inf,
862                      bfd_boolean skip_zeroes)
863 {
864   char buf[30];
865   char *p;
866   struct objdump_disasm_info *aux;
867
868   aux = (struct objdump_disasm_info *) inf->application_data;
869   bfd_sprintf_vma (aux->abfd, buf, vma);
870   if (! skip_zeroes)
871     p = buf;
872   else
873     {
874       for (p = buf; *p == '0'; ++p)
875         ;
876       if (*p == '\0')
877         --p;
878     }
879   (*inf->fprintf_func) (inf->stream, "%s", p);
880 }
881
882 /* Print the name of a symbol.  */
883
884 static void
885 objdump_print_symname (bfd *abfd, struct disassemble_info *inf,
886                        asymbol *sym)
887 {
888   char *alloc;
889   const char *name, *version_string = NULL;
890   bfd_boolean hidden = FALSE;
891
892   alloc = NULL;
893   name = bfd_asymbol_name (sym);
894   if (do_demangle && name[0] != '\0')
895     {
896       /* Demangle the name.  */
897       alloc = bfd_demangle (abfd, name, demangle_flags);
898       if (alloc != NULL)
899         name = alloc;
900     }
901
902   if ((sym->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) == 0)
903     version_string = bfd_get_symbol_version_string (abfd, sym, &hidden);
904
905   if (bfd_is_und_section (bfd_get_section (sym)))
906     hidden = TRUE;
907
908   if (inf != NULL)
909     {
910       (*inf->fprintf_func) (inf->stream, "%s", name);
911       if (version_string && *version_string != '\0')
912         (*inf->fprintf_func) (inf->stream, hidden ? "@%s" : "@@%s",
913                               version_string);
914     }
915   else
916     {
917       printf ("%s", name);
918       if (version_string && *version_string != '\0')
919         printf (hidden ? "@%s" : "@@%s", version_string);
920     }
921
922   if (alloc != NULL)
923     free (alloc);
924 }
925
926 /* Locate a symbol given a bfd and a section (from INFO->application_data),
927    and a VMA.  If INFO->application_data->require_sec is TRUE, then always
928    require the symbol to be in the section.  Returns NULL if there is no
929    suitable symbol.  If PLACE is not NULL, then *PLACE is set to the index
930    of the symbol in sorted_syms.  */
931
932 static asymbol *
933 find_symbol_for_address (bfd_vma vma,
934                          struct disassemble_info *inf,
935                          long *place)
936 {
937   /* @@ Would it speed things up to cache the last two symbols returned,
938      and maybe their address ranges?  For many processors, only one memory
939      operand can be present at a time, so the 2-entry cache wouldn't be
940      constantly churned by code doing heavy memory accesses.  */
941
942   /* Indices in `sorted_syms'.  */
943   long min = 0;
944   long max_count = sorted_symcount;
945   long thisplace;
946   struct objdump_disasm_info *aux;
947   bfd *abfd;
948   asection *sec;
949   unsigned int opb;
950   bfd_boolean want_section;
951   long rel_count;
952
953   if (sorted_symcount < 1)
954     return NULL;
955
956   aux = (struct objdump_disasm_info *) inf->application_data;
957   abfd = aux->abfd;
958   sec = aux->sec;
959   opb = inf->octets_per_byte;
960
961   /* Perform a binary search looking for the closest symbol to the
962      required value.  We are searching the range (min, max_count].  */
963   while (min + 1 < max_count)
964     {
965       asymbol *sym;
966
967       thisplace = (max_count + min) / 2;
968       sym = sorted_syms[thisplace];
969
970       if (bfd_asymbol_value (sym) > vma)
971         max_count = thisplace;
972       else if (bfd_asymbol_value (sym) < vma)
973         min = thisplace;
974       else
975         {
976           min = thisplace;
977           break;
978         }
979     }
980
981   /* The symbol we want is now in min, the low end of the range we
982      were searching.  If there are several symbols with the same
983      value, we want the first (non-section/non-debugging) one.  */
984   thisplace = min;
985   while (thisplace > 0
986          && (bfd_asymbol_value (sorted_syms[thisplace])
987              == bfd_asymbol_value (sorted_syms[thisplace - 1]))
988          && ((sorted_syms[thisplace - 1]->flags
989               & (BSF_SECTION_SYM | BSF_DEBUGGING)) == 0)
990          )
991     --thisplace;
992
993   /* Prefer a symbol in the current section if we have multple symbols
994      with the same value, as can occur with overlays or zero size
995      sections.  */
996   min = thisplace;
997   while (min < max_count
998          && (bfd_asymbol_value (sorted_syms[min])
999              == bfd_asymbol_value (sorted_syms[thisplace])))
1000     {
1001       if (sorted_syms[min]->section == sec
1002           && inf->symbol_is_valid (sorted_syms[min], inf))
1003         {
1004           thisplace = min;
1005
1006           if (place != NULL)
1007             *place = thisplace;
1008
1009           return sorted_syms[thisplace];
1010         }
1011       ++min;
1012     }
1013
1014   /* If the file is relocatable, and the symbol could be from this
1015      section, prefer a symbol from this section over symbols from
1016      others, even if the other symbol's value might be closer.
1017
1018      Note that this may be wrong for some symbol references if the
1019      sections have overlapping memory ranges, but in that case there's
1020      no way to tell what's desired without looking at the relocation
1021      table.
1022
1023      Also give the target a chance to reject symbols.  */
1024   want_section = (aux->require_sec
1025                   || ((abfd->flags & HAS_RELOC) != 0
1026                       && vma >= bfd_get_section_vma (abfd, sec)
1027                       && vma < (bfd_get_section_vma (abfd, sec)
1028                                 + bfd_section_size (abfd, sec) / opb)));
1029   if ((sorted_syms[thisplace]->section != sec && want_section)
1030       || ! inf->symbol_is_valid (sorted_syms[thisplace], inf))
1031     {
1032       long i;
1033       long newplace = sorted_symcount;
1034
1035       for (i = min - 1; i >= 0; i--)
1036         {
1037           if ((sorted_syms[i]->section == sec || !want_section)
1038               && inf->symbol_is_valid (sorted_syms[i], inf))
1039             {
1040               if (newplace == sorted_symcount)
1041                 newplace = i;
1042
1043               if (bfd_asymbol_value (sorted_syms[i])
1044                   != bfd_asymbol_value (sorted_syms[newplace]))
1045                 break;
1046
1047               /* Remember this symbol and keep searching until we reach
1048                  an earlier address.  */
1049               newplace = i;
1050             }
1051         }
1052
1053       if (newplace != sorted_symcount)
1054         thisplace = newplace;
1055       else
1056         {
1057           /* We didn't find a good symbol with a smaller value.
1058              Look for one with a larger value.  */
1059           for (i = thisplace + 1; i < sorted_symcount; i++)
1060             {
1061               if ((sorted_syms[i]->section == sec || !want_section)
1062                   && inf->symbol_is_valid (sorted_syms[i], inf))
1063                 {
1064                   thisplace = i;
1065                   break;
1066                 }
1067             }
1068         }
1069
1070       if ((sorted_syms[thisplace]->section != sec && want_section)
1071           || ! inf->symbol_is_valid (sorted_syms[thisplace], inf))
1072         /* There is no suitable symbol.  */
1073         return NULL;
1074     }
1075
1076   /* If we have not found an exact match for the specified address
1077      and we have dynamic relocations available, then we can produce
1078      a better result by matching a relocation to the address and
1079      using the symbol associated with that relocation.  */
1080   rel_count = aux->dynrelcount;
1081   if (!want_section
1082       && sorted_syms[thisplace]->value != vma
1083       && rel_count > 0
1084       && aux->dynrelbuf != NULL
1085       && aux->dynrelbuf[0]->address <= vma
1086       && aux->dynrelbuf[rel_count - 1]->address >= vma
1087       /* If we have matched a synthetic symbol, then stick with that.  */
1088       && (sorted_syms[thisplace]->flags & BSF_SYNTHETIC) == 0)
1089     {
1090       arelent **  rel_low;
1091       arelent **  rel_high;
1092
1093       rel_low = aux->dynrelbuf;
1094       rel_high = rel_low + rel_count - 1;
1095       while (rel_low <= rel_high)
1096         {
1097           arelent **rel_mid = &rel_low[(rel_high - rel_low) / 2];
1098           arelent * rel = *rel_mid;
1099
1100           if (rel->address == vma)
1101             {
1102               /* Absolute relocations do not provide a more helpful
1103                  symbolic address.  Find a non-absolute relocation
1104                  with the same address.  */
1105               arelent **rel_vma = rel_mid;
1106               for (rel_mid--;
1107                    rel_mid >= rel_low && rel_mid[0]->address == vma;
1108                    rel_mid--)
1109                 rel_vma = rel_mid;
1110
1111               for (; rel_vma <= rel_high && rel_vma[0]->address == vma;
1112                    rel_vma++)
1113                 {
1114                   rel = *rel_vma;
1115                   if (rel->sym_ptr_ptr != NULL
1116                       && ! bfd_is_abs_section ((* rel->sym_ptr_ptr)->section))
1117                     {
1118                       if (place != NULL)
1119                         * place = thisplace;
1120                       return * rel->sym_ptr_ptr;
1121                     }
1122                 }
1123               break;
1124             }
1125
1126           if (vma < rel->address)
1127             rel_high = rel_mid;
1128           else if (vma >= rel_mid[1]->address)
1129             rel_low = rel_mid + 1;
1130           else
1131             break;
1132         }
1133     }
1134
1135   if (place != NULL)
1136     *place = thisplace;
1137
1138   return sorted_syms[thisplace];
1139 }
1140
1141 /* Print an address and the offset to the nearest symbol.  */
1142
1143 static void
1144 objdump_print_addr_with_sym (bfd *abfd, asection *sec, asymbol *sym,
1145                              bfd_vma vma, struct disassemble_info *inf,
1146                              bfd_boolean skip_zeroes)
1147 {
1148   objdump_print_value (vma, inf, skip_zeroes);
1149
1150   if (sym == NULL)
1151     {
1152       bfd_vma secaddr;
1153
1154       (*inf->fprintf_func) (inf->stream, " <%s",
1155                             bfd_get_section_name (abfd, sec));
1156       secaddr = bfd_get_section_vma (abfd, sec);
1157       if (vma < secaddr)
1158         {
1159           (*inf->fprintf_func) (inf->stream, "-0x");
1160           objdump_print_value (secaddr - vma, inf, TRUE);
1161         }
1162       else if (vma > secaddr)
1163         {
1164           (*inf->fprintf_func) (inf->stream, "+0x");
1165           objdump_print_value (vma - secaddr, inf, TRUE);
1166         }
1167       (*inf->fprintf_func) (inf->stream, ">");
1168     }
1169   else
1170     {
1171       (*inf->fprintf_func) (inf->stream, " <");
1172
1173       objdump_print_symname (abfd, inf, sym);
1174
1175       if (bfd_asymbol_value (sym) == vma)
1176         ;
1177       /* Undefined symbols in an executables and dynamic objects do not have
1178          a value associated with them, so it does not make sense to display
1179          an offset relative to them.  Normally we would not be provided with
1180          this kind of symbol, but the target backend might choose to do so,
1181          and the code in find_symbol_for_address might return an as yet
1182          unresolved symbol associated with a dynamic reloc.  */
1183       else if ((bfd_get_file_flags (abfd) & (EXEC_P | DYNAMIC))
1184                && bfd_is_und_section (sym->section))
1185         ;
1186       else if (bfd_asymbol_value (sym) > vma)
1187         {
1188           (*inf->fprintf_func) (inf->stream, "-0x");
1189           objdump_print_value (bfd_asymbol_value (sym) - vma, inf, TRUE);
1190         }
1191       else if (vma > bfd_asymbol_value (sym))
1192         {
1193           (*inf->fprintf_func) (inf->stream, "+0x");
1194           objdump_print_value (vma - bfd_asymbol_value (sym), inf, TRUE);
1195         }
1196
1197       (*inf->fprintf_func) (inf->stream, ">");
1198     }
1199
1200   if (display_file_offsets)
1201     inf->fprintf_func (inf->stream, _(" (File Offset: 0x%lx)"),
1202                         (long int)(sec->filepos + (vma - sec->vma)));
1203 }
1204
1205 /* Print an address (VMA), symbolically if possible.
1206    If SKIP_ZEROES is TRUE, don't output leading zeroes.  */
1207
1208 static void
1209 objdump_print_addr (bfd_vma vma,
1210                     struct disassemble_info *inf,
1211                     bfd_boolean skip_zeroes)
1212 {
1213   struct objdump_disasm_info *aux;
1214   asymbol *sym = NULL;
1215   bfd_boolean skip_find = FALSE;
1216
1217   aux = (struct objdump_disasm_info *) inf->application_data;
1218
1219   if (sorted_symcount < 1)
1220     {
1221       (*inf->fprintf_func) (inf->stream, "0x");
1222       objdump_print_value (vma, inf, skip_zeroes);
1223
1224       if (display_file_offsets)
1225         inf->fprintf_func (inf->stream, _(" (File Offset: 0x%lx)"),
1226                            (long int)(aux->sec->filepos + (vma - aux->sec->vma)));
1227       return;
1228     }
1229
1230   if (aux->reloc != NULL
1231       && aux->reloc->sym_ptr_ptr != NULL
1232       && * aux->reloc->sym_ptr_ptr != NULL)
1233     {
1234       sym = * aux->reloc->sym_ptr_ptr;
1235
1236       /* Adjust the vma to the reloc.  */
1237       vma += bfd_asymbol_value (sym);
1238
1239       if (bfd_is_und_section (bfd_get_section (sym)))
1240         skip_find = TRUE;
1241     }
1242
1243   if (!skip_find)
1244     sym = find_symbol_for_address (vma, inf, NULL);
1245
1246   objdump_print_addr_with_sym (aux->abfd, aux->sec, sym, vma, inf,
1247                                skip_zeroes);
1248 }
1249
1250 /* Print VMA to INFO.  This function is passed to the disassembler
1251    routine.  */
1252
1253 static void
1254 objdump_print_address (bfd_vma vma, struct disassemble_info *inf)
1255 {
1256   objdump_print_addr (vma, inf, ! prefix_addresses);
1257 }
1258
1259 /* Determine if the given address has a symbol associated with it.  */
1260
1261 static int
1262 objdump_symbol_at_address (bfd_vma vma, struct disassemble_info * inf)
1263 {
1264   asymbol * sym;
1265
1266   sym = find_symbol_for_address (vma, inf, NULL);
1267
1268   return (sym != NULL && (bfd_asymbol_value (sym) == vma));
1269 }
1270
1271 /* Hold the last function name and the last line number we displayed
1272    in a disassembly.  */
1273
1274 static char *prev_functionname;
1275 static unsigned int prev_line;
1276 static unsigned int prev_discriminator;
1277
1278 /* We keep a list of all files that we have seen when doing a
1279    disassembly with source, so that we know how much of the file to
1280    display.  This can be important for inlined functions.  */
1281
1282 struct print_file_list
1283 {
1284   struct print_file_list *next;
1285   const char *filename;
1286   const char *modname;
1287   const char *map;
1288   size_t mapsize;
1289   const char **linemap;
1290   unsigned maxline;
1291   unsigned last_line;
1292   unsigned max_printed;
1293   int first;
1294 };
1295
1296 static struct print_file_list *print_files;
1297
1298 /* The number of preceding context lines to show when we start
1299    displaying a file for the first time.  */
1300
1301 #define SHOW_PRECEDING_CONTEXT_LINES (5)
1302
1303 /* Read a complete file into memory.  */
1304
1305 static const char *
1306 slurp_file (const char *fn, size_t *size, struct stat *fst)
1307 {
1308 #ifdef HAVE_MMAP
1309   int ps = getpagesize ();
1310   size_t msize;
1311 #endif
1312   const char *map;
1313   int fd = open (fn, O_RDONLY | O_BINARY);
1314
1315   if (fd < 0)
1316     return NULL;
1317   if (fstat (fd, fst) < 0)
1318     {
1319       close (fd);
1320       return NULL;
1321     }
1322   *size = fst->st_size;
1323 #ifdef HAVE_MMAP
1324   msize = (*size + ps - 1) & ~(ps - 1);
1325   map = mmap (NULL, msize, PROT_READ, MAP_SHARED, fd, 0);
1326   if (map != (char *) -1L)
1327     {
1328       close (fd);
1329       return map;
1330     }
1331 #endif
1332   map = (const char *) malloc (*size);
1333   if (!map || (size_t) read (fd, (char *) map, *size) != *size)
1334     {
1335       free ((void *) map);
1336       map = NULL;
1337     }
1338   close (fd);
1339   return map;
1340 }
1341
1342 #define line_map_decrease 5
1343
1344 /* Precompute array of lines for a mapped file. */
1345
1346 static const char **
1347 index_file (const char *map, size_t size, unsigned int *maxline)
1348 {
1349   const char *p, *lstart, *end;
1350   int chars_per_line = 45; /* First iteration will use 40.  */
1351   unsigned int lineno;
1352   const char **linemap = NULL;
1353   unsigned long line_map_size = 0;
1354
1355   lineno = 0;
1356   lstart = map;
1357   end = map + size;
1358
1359   for (p = map; p < end; p++)
1360     {
1361       if (*p == '\n')
1362         {
1363           if (p + 1 < end && p[1] == '\r')
1364             p++;
1365         }
1366       else if (*p == '\r')
1367         {
1368           if (p + 1 < end && p[1] == '\n')
1369             p++;
1370         }
1371       else
1372         continue;
1373
1374       /* End of line found.  */
1375
1376       if (linemap == NULL || line_map_size < lineno + 1)
1377         {
1378           unsigned long newsize;
1379
1380           chars_per_line -= line_map_decrease;
1381           if (chars_per_line <= 1)
1382             chars_per_line = 1;
1383           line_map_size = size / chars_per_line + 1;
1384           if (line_map_size < lineno + 1)
1385             line_map_size = lineno + 1;
1386           newsize = line_map_size * sizeof (char *);
1387           linemap = (const char **) xrealloc (linemap, newsize);
1388         }
1389
1390       linemap[lineno++] = lstart;
1391       lstart = p + 1;
1392     }
1393
1394   *maxline = lineno;
1395   return linemap;
1396 }
1397
1398 /* Tries to open MODNAME, and if successful adds a node to print_files
1399    linked list and returns that node.  Returns NULL on failure.  */
1400
1401 static struct print_file_list *
1402 try_print_file_open (const char *origname, const char *modname, struct stat *fst)
1403 {
1404   struct print_file_list *p;
1405
1406   p = (struct print_file_list *) xmalloc (sizeof (struct print_file_list));
1407
1408   p->map = slurp_file (modname, &p->mapsize, fst);
1409   if (p->map == NULL)
1410     {
1411       free (p);
1412       return NULL;
1413     }
1414
1415   p->linemap = index_file (p->map, p->mapsize, &p->maxline);
1416   p->last_line = 0;
1417   p->max_printed = 0;
1418   p->filename = origname;
1419   p->modname = modname;
1420   p->next = print_files;
1421   p->first = 1;
1422   print_files = p;
1423   return p;
1424 }
1425
1426 /* If the source file, as described in the symtab, is not found
1427    try to locate it in one of the paths specified with -I
1428    If found, add location to print_files linked list.  */
1429
1430 static struct print_file_list *
1431 update_source_path (const char *filename, bfd *abfd)
1432 {
1433   struct print_file_list *p;
1434   const char *fname;
1435   struct stat fst;
1436   int i;
1437
1438   p = try_print_file_open (filename, filename, &fst);
1439   if (p == NULL)
1440     {
1441       if (include_path_count == 0)
1442         return NULL;
1443
1444       /* Get the name of the file.  */
1445       fname = lbasename (filename);
1446
1447       /* If file exists under a new path, we need to add it to the list
1448          so that show_line knows about it.  */
1449       for (i = 0; i < include_path_count; i++)
1450         {
1451           char *modname = concat (include_paths[i], "/", fname,
1452                                   (const char *) 0);
1453
1454           p = try_print_file_open (filename, modname, &fst);
1455           if (p)
1456             break;
1457
1458           free (modname);
1459         }
1460     }
1461
1462   if (p != NULL)
1463     {
1464       long mtime = bfd_get_mtime (abfd);
1465
1466       if (fst.st_mtime > mtime)
1467         warn (_("source file %s is more recent than object file\n"),
1468               filename);
1469     }
1470
1471   return p;
1472 }
1473
1474 /* Print a source file line.  */
1475
1476 static void
1477 print_line (struct print_file_list *p, unsigned int linenum)
1478 {
1479   const char *l;
1480   size_t len;
1481
1482   --linenum;
1483   if (linenum >= p->maxline)
1484     return;
1485   l = p->linemap [linenum];
1486   /* Test fwrite return value to quiet glibc warning.  */
1487   len = strcspn (l, "\n\r");
1488   if (len == 0 || fwrite (l, len, 1, stdout) == 1)
1489     putchar ('\n');
1490 }
1491
1492 /* Print a range of source code lines. */
1493
1494 static void
1495 dump_lines (struct print_file_list *p, unsigned int start, unsigned int end)
1496 {
1497   if (p->map == NULL)
1498     return;
1499   while (start <= end)
1500     {
1501       print_line (p, start);
1502       start++;
1503     }
1504 }
1505
1506 /* Show the line number, or the source line, in a disassembly
1507    listing.  */
1508
1509 static void
1510 show_line (bfd *abfd, asection *section, bfd_vma addr_offset)
1511 {
1512   const char *filename;
1513   const char *functionname;
1514   unsigned int linenumber;
1515   unsigned int discriminator;
1516   bfd_boolean reloc;
1517   char *path = NULL;
1518
1519   if (! with_line_numbers && ! with_source_code)
1520     return;
1521
1522   if (! bfd_find_nearest_line_discriminator (abfd, section, syms, addr_offset,
1523                                              &filename, &functionname,
1524                                              &linenumber, &discriminator))
1525     return;
1526
1527   if (filename != NULL && *filename == '\0')
1528     filename = NULL;
1529   if (functionname != NULL && *functionname == '\0')
1530     functionname = NULL;
1531
1532   if (filename
1533       && IS_ABSOLUTE_PATH (filename)
1534       && prefix)
1535     {
1536       char *path_up;
1537       const char *fname = filename;
1538
1539       path = xmalloc (prefix_length + PATH_MAX + 1);
1540
1541       if (prefix_length)
1542         memcpy (path, prefix, prefix_length);
1543       path_up = path + prefix_length;
1544
1545       /* Build relocated filename, stripping off leading directories
1546          from the initial filename if requested.  */
1547       if (prefix_strip > 0)
1548         {
1549           int level = 0;
1550           const char *s;
1551
1552           /* Skip selected directory levels.  */
1553           for (s = fname + 1; *s != '\0' && level < prefix_strip; s++)
1554             if (IS_DIR_SEPARATOR(*s))
1555               {
1556                 fname = s;
1557                 level++;
1558               }
1559         }
1560
1561       /* Update complete filename.  */
1562       strncpy (path_up, fname, PATH_MAX);
1563       path_up[PATH_MAX] = '\0';
1564
1565       filename = path;
1566       reloc = TRUE;
1567     }
1568   else
1569     reloc = FALSE;
1570
1571   if (with_line_numbers)
1572     {
1573       if (functionname != NULL
1574           && (prev_functionname == NULL
1575               || strcmp (functionname, prev_functionname) != 0))
1576         {
1577           printf ("%s():\n", functionname);
1578           prev_line = -1;
1579         }
1580       if (linenumber > 0
1581           && (linenumber != prev_line
1582               || discriminator != prev_discriminator))
1583         {
1584           if (discriminator > 0)
1585             printf ("%s:%u (discriminator %u)\n",
1586                     filename == NULL ? "???" : filename,
1587                     linenumber, discriminator);
1588           else
1589             printf ("%s:%u\n", filename == NULL ? "???" : filename,
1590                     linenumber);
1591         }
1592       if (unwind_inlines)
1593         {
1594           const char *filename2;
1595           const char *functionname2;
1596           unsigned line2;
1597
1598           while (bfd_find_inliner_info (abfd, &filename2, &functionname2,
1599                                         &line2))
1600             printf ("inlined by %s:%u (%s)\n", filename2, line2,
1601                     functionname2);
1602         }
1603     }
1604
1605   if (with_source_code
1606       && filename != NULL
1607       && linenumber > 0)
1608     {
1609       struct print_file_list **pp, *p;
1610       unsigned l;
1611
1612       for (pp = &print_files; *pp != NULL; pp = &(*pp)->next)
1613         if (filename_cmp ((*pp)->filename, filename) == 0)
1614           break;
1615       p = *pp;
1616
1617       if (p == NULL)
1618         {
1619           if (reloc)
1620             filename = xstrdup (filename);
1621           p = update_source_path (filename, abfd);
1622         }
1623
1624       if (p != NULL && linenumber != p->last_line)
1625         {
1626           if (file_start_context && p->first)
1627             l = 1;
1628           else
1629             {
1630               l = linenumber - SHOW_PRECEDING_CONTEXT_LINES;
1631               if (l >= linenumber)
1632                 l = 1;
1633               if (p->max_printed >= l)
1634                 {
1635                   if (p->max_printed < linenumber)
1636                     l = p->max_printed + 1;
1637                   else
1638                     l = linenumber;
1639                 }
1640             }
1641           dump_lines (p, l, linenumber);
1642           if (p->max_printed < linenumber)
1643             p->max_printed = linenumber;
1644           p->last_line = linenumber;
1645           p->first = 0;
1646         }
1647     }
1648
1649   if (functionname != NULL
1650       && (prev_functionname == NULL
1651           || strcmp (functionname, prev_functionname) != 0))
1652     {
1653       if (prev_functionname != NULL)
1654         free (prev_functionname);
1655       prev_functionname = (char *) xmalloc (strlen (functionname) + 1);
1656       strcpy (prev_functionname, functionname);
1657     }
1658
1659   if (linenumber > 0 && linenumber != prev_line)
1660     prev_line = linenumber;
1661
1662   if (discriminator != prev_discriminator)
1663     prev_discriminator = discriminator;
1664
1665   if (path)
1666     free (path);
1667 }
1668
1669 /* Pseudo FILE object for strings.  */
1670 typedef struct
1671 {
1672   char *buffer;
1673   size_t pos;
1674   size_t alloc;
1675 } SFILE;
1676
1677 /* sprintf to a "stream".  */
1678
1679 static int ATTRIBUTE_PRINTF_2
1680 objdump_sprintf (SFILE *f, const char *format, ...)
1681 {
1682   size_t n;
1683   va_list args;
1684
1685   while (1)
1686     {
1687       size_t space = f->alloc - f->pos;
1688
1689       va_start (args, format);
1690       n = vsnprintf (f->buffer + f->pos, space, format, args);
1691       va_end (args);
1692
1693       if (space > n)
1694         break;
1695
1696       f->alloc = (f->alloc + n) * 2;
1697       f->buffer = (char *) xrealloc (f->buffer, f->alloc);
1698     }
1699   f->pos += n;
1700
1701   return n;
1702 }
1703
1704 /* The number of zeroes we want to see before we start skipping them.
1705    The number is arbitrarily chosen.  */
1706
1707 #define DEFAULT_SKIP_ZEROES 8
1708
1709 /* The number of zeroes to skip at the end of a section.  If the
1710    number of zeroes at the end is between SKIP_ZEROES_AT_END and
1711    SKIP_ZEROES, they will be disassembled.  If there are fewer than
1712    SKIP_ZEROES_AT_END, they will be skipped.  This is a heuristic
1713    attempt to avoid disassembling zeroes inserted by section
1714    alignment.  */
1715
1716 #define DEFAULT_SKIP_ZEROES_AT_END 3
1717
1718 /* Disassemble some data in memory between given values.  */
1719
1720 static void
1721 disassemble_bytes (struct disassemble_info * inf,
1722                    disassembler_ftype        disassemble_fn,
1723                    bfd_boolean               insns,
1724                    bfd_byte *                data,
1725                    bfd_vma                   start_offset,
1726                    bfd_vma                   stop_offset,
1727                    bfd_vma                   rel_offset,
1728                    arelent ***               relppp,
1729                    arelent **                relppend)
1730 {
1731   struct objdump_disasm_info *aux;
1732   asection *section;
1733   int octets_per_line;
1734   int skip_addr_chars;
1735   bfd_vma addr_offset;
1736   unsigned int opb = inf->octets_per_byte;
1737   unsigned int skip_zeroes = inf->skip_zeroes;
1738   unsigned int skip_zeroes_at_end = inf->skip_zeroes_at_end;
1739   int octets = opb;
1740   SFILE sfile;
1741
1742   aux = (struct objdump_disasm_info *) inf->application_data;
1743   section = aux->sec;
1744
1745   sfile.alloc = 120;
1746   sfile.buffer = (char *) xmalloc (sfile.alloc);
1747   sfile.pos = 0;
1748
1749   if (insn_width)
1750     octets_per_line = insn_width;
1751   else if (insns)
1752     octets_per_line = 4;
1753   else
1754     octets_per_line = 16;
1755
1756   /* Figure out how many characters to skip at the start of an
1757      address, to make the disassembly look nicer.  We discard leading
1758      zeroes in chunks of 4, ensuring that there is always a leading
1759      zero remaining.  */
1760   skip_addr_chars = 0;
1761   if (! prefix_addresses)
1762     {
1763       char buf[30];
1764
1765       bfd_sprintf_vma (aux->abfd, buf, section->vma + section->size / opb);
1766
1767       while (buf[skip_addr_chars] == '0')
1768         ++skip_addr_chars;
1769
1770       /* Don't discard zeros on overflow.  */
1771       if (buf[skip_addr_chars] == '\0' && section->vma != 0)
1772         skip_addr_chars = 0;
1773
1774       if (skip_addr_chars != 0)
1775         skip_addr_chars = (skip_addr_chars - 1) & -4;
1776     }
1777
1778   inf->insn_info_valid = 0;
1779
1780   addr_offset = start_offset;
1781   while (addr_offset < stop_offset)
1782     {
1783       bfd_vma z;
1784       bfd_boolean need_nl = FALSE;
1785       int previous_octets;
1786
1787       /* Remember the length of the previous instruction.  */
1788       previous_octets = octets;
1789       octets = 0;
1790
1791       /* Make sure we don't use relocs from previous instructions.  */
1792       aux->reloc = NULL;
1793
1794       /* If we see more than SKIP_ZEROES octets of zeroes, we just
1795          print `...'.  */
1796       for (z = addr_offset * opb; z < stop_offset * opb; z++)
1797         if (data[z] != 0)
1798           break;
1799       if (! disassemble_zeroes
1800           && (inf->insn_info_valid == 0
1801               || inf->branch_delay_insns == 0)
1802           && (z - addr_offset * opb >= skip_zeroes
1803               || (z == stop_offset * opb &&
1804                   z - addr_offset * opb < skip_zeroes_at_end)))
1805         {
1806           /* If there are more nonzero octets to follow, we only skip
1807              zeroes in multiples of 4, to try to avoid running over
1808              the start of an instruction which happens to start with
1809              zero.  */
1810           if (z != stop_offset * opb)
1811             z = addr_offset * opb + ((z - addr_offset * opb) &~ 3);
1812
1813           octets = z - addr_offset * opb;
1814
1815           /* If we are going to display more data, and we are displaying
1816              file offsets, then tell the user how many zeroes we skip
1817              and the file offset from where we resume dumping.  */
1818           if (display_file_offsets && ((addr_offset + (octets / opb)) < stop_offset))
1819             printf ("\t... (skipping %d zeroes, resuming at file offset: 0x%lx)\n",
1820                     octets / opb,
1821                     (unsigned long) (section->filepos
1822                                      + (addr_offset + (octets / opb))));
1823           else
1824             printf ("\t...\n");
1825         }
1826       else
1827         {
1828           char buf[50];
1829           int bpc = 0;
1830           int pb = 0;
1831
1832           if (with_line_numbers || with_source_code)
1833             show_line (aux->abfd, section, addr_offset);
1834
1835           if (! prefix_addresses)
1836             {
1837               char *s;
1838
1839               bfd_sprintf_vma (aux->abfd, buf, section->vma + addr_offset);
1840               for (s = buf + skip_addr_chars; *s == '0'; s++)
1841                 *s = ' ';
1842               if (*s == '\0')
1843                 *--s = '0';
1844               printf ("%s:\t", buf + skip_addr_chars);
1845             }
1846           else
1847             {
1848               aux->require_sec = TRUE;
1849               objdump_print_address (section->vma + addr_offset, inf);
1850               aux->require_sec = FALSE;
1851               putchar (' ');
1852             }
1853
1854           if (insns)
1855             {
1856               sfile.pos = 0;
1857               inf->fprintf_func = (fprintf_ftype) objdump_sprintf;
1858               inf->stream = &sfile;
1859               inf->bytes_per_line = 0;
1860               inf->bytes_per_chunk = 0;
1861               inf->flags = disassemble_all ? DISASSEMBLE_DATA : 0;
1862               if (machine)
1863                 inf->flags |= USER_SPECIFIED_MACHINE_TYPE;
1864
1865               if (inf->disassembler_needs_relocs
1866                   && (bfd_get_file_flags (aux->abfd) & EXEC_P) == 0
1867                   && (bfd_get_file_flags (aux->abfd) & DYNAMIC) == 0
1868                   && *relppp < relppend)
1869                 {
1870                   bfd_signed_vma distance_to_rel;
1871
1872                   distance_to_rel = (**relppp)->address
1873                     - (rel_offset + addr_offset);
1874
1875                   /* Check to see if the current reloc is associated with
1876                      the instruction that we are about to disassemble.  */
1877                   if (distance_to_rel == 0
1878                       /* FIXME: This is wrong.  We are trying to catch
1879                          relocs that are addressed part way through the
1880                          current instruction, as might happen with a packed
1881                          VLIW instruction.  Unfortunately we do not know the
1882                          length of the current instruction since we have not
1883                          disassembled it yet.  Instead we take a guess based
1884                          upon the length of the previous instruction.  The
1885                          proper solution is to have a new target-specific
1886                          disassembler function which just returns the length
1887                          of an instruction at a given address without trying
1888                          to display its disassembly. */
1889                       || (distance_to_rel > 0
1890                           && distance_to_rel < (bfd_signed_vma) (previous_octets/ opb)))
1891                     {
1892                       inf->flags |= INSN_HAS_RELOC;
1893                       aux->reloc = **relppp;
1894                     }
1895                 }
1896
1897               if (! disassemble_all
1898                   && (section->flags & (SEC_CODE | SEC_HAS_CONTENTS))
1899                   == (SEC_CODE | SEC_HAS_CONTENTS))
1900                 /* Set a stop_vma so that the disassembler will not read
1901                    beyond the next symbol.  We assume that symbols appear on
1902                    the boundaries between instructions.  We only do this when
1903                    disassembling code of course, and when -D is in effect.  */
1904                 inf->stop_vma = section->vma + stop_offset;
1905
1906               octets = (*disassemble_fn) (section->vma + addr_offset, inf);
1907
1908               inf->stop_vma = 0;
1909               inf->fprintf_func = (fprintf_ftype) fprintf;
1910               inf->stream = stdout;
1911               if (insn_width == 0 && inf->bytes_per_line != 0)
1912                 octets_per_line = inf->bytes_per_line;
1913               if (octets < (int) opb)
1914                 {
1915                   if (sfile.pos)
1916                     printf ("%s\n", sfile.buffer);
1917                   if (octets >= 0)
1918                     {
1919                       non_fatal (_("disassemble_fn returned length %d"),
1920                                  octets);
1921                       exit_status = 1;
1922                     }
1923                   break;
1924                 }
1925             }
1926           else
1927             {
1928               bfd_vma j;
1929
1930               octets = octets_per_line;
1931               if (addr_offset + octets / opb > stop_offset)
1932                 octets = (stop_offset - addr_offset) * opb;
1933
1934               for (j = addr_offset * opb; j < addr_offset * opb + octets; ++j)
1935                 {
1936                   if (ISPRINT (data[j]))
1937                     buf[j - addr_offset * opb] = data[j];
1938                   else
1939                     buf[j - addr_offset * opb] = '.';
1940                 }
1941               buf[j - addr_offset * opb] = '\0';
1942             }
1943
1944           if (prefix_addresses
1945               ? show_raw_insn > 0
1946               : show_raw_insn >= 0)
1947             {
1948               bfd_vma j;
1949
1950               /* If ! prefix_addresses and ! wide_output, we print
1951                  octets_per_line octets per line.  */
1952               pb = octets;
1953               if (pb > octets_per_line && ! prefix_addresses && ! wide_output)
1954                 pb = octets_per_line;
1955
1956               if (inf->bytes_per_chunk)
1957                 bpc = inf->bytes_per_chunk;
1958               else
1959                 bpc = 1;
1960
1961               for (j = addr_offset * opb; j < addr_offset * opb + pb; j += bpc)
1962                 {
1963                   /* PR 21580: Check for a buffer ending early.  */
1964                   if (j + bpc <= stop_offset * opb)
1965                     {
1966                       int k;
1967
1968                       if (inf->display_endian == BFD_ENDIAN_LITTLE)
1969                         {
1970                           for (k = bpc - 1; k >= 0; k--)
1971                             printf ("%02x", (unsigned) data[j + k]);
1972                         }
1973                       else
1974                         {
1975                           for (k = 0; k < bpc; k++)
1976                             printf ("%02x", (unsigned) data[j + k]);
1977                         }
1978                     }
1979                   putchar (' ');
1980                 }
1981
1982               for (; pb < octets_per_line; pb += bpc)
1983                 {
1984                   int k;
1985
1986                   for (k = 0; k < bpc; k++)
1987                     printf ("  ");
1988                   putchar (' ');
1989                 }
1990
1991               /* Separate raw data from instruction by extra space.  */
1992               if (insns)
1993                 putchar ('\t');
1994               else
1995                 printf ("    ");
1996             }
1997
1998           if (! insns)
1999             printf ("%s", buf);
2000           else if (sfile.pos)
2001             printf ("%s", sfile.buffer);
2002
2003           if (prefix_addresses
2004               ? show_raw_insn > 0
2005               : show_raw_insn >= 0)
2006             {
2007               while (pb < octets)
2008                 {
2009                   bfd_vma j;
2010                   char *s;
2011
2012                   putchar ('\n');
2013                   j = addr_offset * opb + pb;
2014
2015                   bfd_sprintf_vma (aux->abfd, buf, section->vma + j / opb);
2016                   for (s = buf + skip_addr_chars; *s == '0'; s++)
2017                     *s = ' ';
2018                   if (*s == '\0')
2019                     *--s = '0';
2020                   printf ("%s:\t", buf + skip_addr_chars);
2021
2022                   pb += octets_per_line;
2023                   if (pb > octets)
2024                     pb = octets;
2025                   for (; j < addr_offset * opb + pb; j += bpc)
2026                     {
2027                       /* PR 21619: Check for a buffer ending early.  */
2028                       if (j + bpc <= stop_offset * opb)
2029                         {
2030                           int k;
2031
2032                           if (inf->display_endian == BFD_ENDIAN_LITTLE)
2033                             {
2034                               for (k = bpc - 1; k >= 0; k--)
2035                                 printf ("%02x", (unsigned) data[j + k]);
2036                             }
2037                           else
2038                             {
2039                               for (k = 0; k < bpc; k++)
2040                                 printf ("%02x", (unsigned) data[j + k]);
2041                             }
2042                         }
2043                       putchar (' ');
2044                     }
2045                 }
2046             }
2047
2048           if (!wide_output)
2049             putchar ('\n');
2050           else
2051             need_nl = TRUE;
2052         }
2053
2054       while ((*relppp) < relppend
2055              && (**relppp)->address < rel_offset + addr_offset + octets / opb)
2056         {
2057           if (dump_reloc_info || dump_dynamic_reloc_info)
2058             {
2059               arelent *q;
2060
2061               q = **relppp;
2062
2063               if (wide_output)
2064                 putchar ('\t');
2065               else
2066                 printf ("\t\t\t");
2067
2068               objdump_print_value (section->vma - rel_offset + q->address,
2069                                    inf, TRUE);
2070
2071               if (q->howto == NULL)
2072                 printf (": *unknown*\t");
2073               else if (q->howto->name)
2074                 printf (": %s\t", q->howto->name);
2075               else
2076                 printf (": %d\t", q->howto->type);
2077
2078               if (q->sym_ptr_ptr == NULL || *q->sym_ptr_ptr == NULL)
2079                 printf ("*unknown*");
2080               else
2081                 {
2082                   const char *sym_name;
2083
2084                   sym_name = bfd_asymbol_name (*q->sym_ptr_ptr);
2085                   if (sym_name != NULL && *sym_name != '\0')
2086                     objdump_print_symname (aux->abfd, inf, *q->sym_ptr_ptr);
2087                   else
2088                     {
2089                       asection *sym_sec;
2090
2091                       sym_sec = bfd_get_section (*q->sym_ptr_ptr);
2092                       sym_name = bfd_get_section_name (aux->abfd, sym_sec);
2093                       if (sym_name == NULL || *sym_name == '\0')
2094                         sym_name = "*unknown*";
2095                       printf ("%s", sym_name);
2096                     }
2097                 }
2098
2099               if (q->addend)
2100                 {
2101                   bfd_signed_vma addend = q->addend;
2102                   if (addend < 0)
2103                     {
2104                       printf ("-0x");
2105                       addend = -addend;
2106                     }
2107                   else
2108                     printf ("+0x");
2109                   objdump_print_value (addend, inf, TRUE);
2110                 }
2111
2112               printf ("\n");
2113               need_nl = FALSE;
2114             }
2115           ++(*relppp);
2116         }
2117
2118       if (need_nl)
2119         printf ("\n");
2120
2121       addr_offset += octets / opb;
2122     }
2123
2124   free (sfile.buffer);
2125 }
2126
2127 static void
2128 disassemble_section (bfd *abfd, asection *section, void *inf)
2129 {
2130   const struct elf_backend_data * bed;
2131   bfd_vma                      sign_adjust = 0;
2132   struct disassemble_info *    pinfo = (struct disassemble_info *) inf;
2133   struct objdump_disasm_info * paux;
2134   unsigned int                 opb = pinfo->octets_per_byte;
2135   bfd_byte *                   data = NULL;
2136   bfd_size_type                datasize = 0;
2137   arelent **                   rel_pp = NULL;
2138   arelent **                   rel_ppstart = NULL;
2139   arelent **                   rel_ppend;
2140   bfd_vma                      stop_offset;
2141   asymbol *                    sym = NULL;
2142   long                         place = 0;
2143   long                         rel_count;
2144   bfd_vma                      rel_offset;
2145   unsigned long                addr_offset;
2146
2147   /* Sections that do not contain machine
2148      code are not normally disassembled.  */
2149   if (! disassemble_all
2150       && only_list == NULL
2151       && ((section->flags & (SEC_CODE | SEC_HAS_CONTENTS))
2152           != (SEC_CODE | SEC_HAS_CONTENTS)))
2153     return;
2154
2155   if (! process_section_p (section))
2156     return;
2157
2158   datasize = bfd_get_section_size (section);
2159   if (datasize == 0)
2160     return;
2161
2162   if (start_address == (bfd_vma) -1
2163       || start_address < section->vma)
2164     addr_offset = 0;
2165   else
2166     addr_offset = start_address - section->vma;
2167
2168   if (stop_address == (bfd_vma) -1)
2169     stop_offset = datasize / opb;
2170   else
2171     {
2172       if (stop_address < section->vma)
2173         stop_offset = 0;
2174       else
2175         stop_offset = stop_address - section->vma;
2176       if (stop_offset > datasize / opb)
2177         stop_offset = datasize / opb;
2178     }
2179
2180   if (addr_offset >= stop_offset)
2181     return;
2182
2183   /* Decide which set of relocs to use.  Load them if necessary.  */
2184   paux = (struct objdump_disasm_info *) pinfo->application_data;
2185   if (paux->dynrelbuf && dump_dynamic_reloc_info)
2186     {
2187       rel_pp = paux->dynrelbuf;
2188       rel_count = paux->dynrelcount;
2189       /* Dynamic reloc addresses are absolute, non-dynamic are section
2190          relative.  REL_OFFSET specifies the reloc address corresponding
2191          to the start of this section.  */
2192       rel_offset = section->vma;
2193     }
2194   else
2195     {
2196       rel_count = 0;
2197       rel_pp = NULL;
2198       rel_offset = 0;
2199
2200       if ((section->flags & SEC_RELOC) != 0
2201           && (dump_reloc_info || pinfo->disassembler_needs_relocs))
2202         {
2203           long relsize;
2204
2205           relsize = bfd_get_reloc_upper_bound (abfd, section);
2206           if (relsize < 0)
2207             bfd_fatal (bfd_get_filename (abfd));
2208
2209           if (relsize > 0)
2210             {
2211               rel_ppstart = rel_pp = (arelent **) xmalloc (relsize);
2212               rel_count = bfd_canonicalize_reloc (abfd, section, rel_pp, syms);
2213               if (rel_count < 0)
2214                 bfd_fatal (bfd_get_filename (abfd));
2215
2216               /* Sort the relocs by address.  */
2217               qsort (rel_pp, rel_count, sizeof (arelent *), compare_relocs);
2218             }
2219         }
2220     }
2221   rel_ppend = rel_pp + rel_count;
2222
2223   if (!bfd_malloc_and_get_section (abfd, section, &data))
2224     {
2225       non_fatal (_("Reading section %s failed because: %s"),
2226                  section->name, bfd_errmsg (bfd_get_error ()));
2227       return;
2228     }
2229
2230   paux->sec = section;
2231   pinfo->buffer = data;
2232   pinfo->buffer_vma = section->vma;
2233   pinfo->buffer_length = datasize;
2234   pinfo->section = section;
2235
2236   /* Skip over the relocs belonging to addresses below the
2237      start address.  */
2238   while (rel_pp < rel_ppend
2239          && (*rel_pp)->address < rel_offset + addr_offset)
2240     ++rel_pp;
2241
2242   printf (_("\nDisassembly of section %s:\n"), section->name);
2243
2244   /* Find the nearest symbol forwards from our current position.  */
2245   paux->require_sec = TRUE;
2246   sym = (asymbol *) find_symbol_for_address (section->vma + addr_offset,
2247                                              (struct disassemble_info *) inf,
2248                                              &place);
2249   paux->require_sec = FALSE;
2250
2251   /* PR 9774: If the target used signed addresses then we must make
2252      sure that we sign extend the value that we calculate for 'addr'
2253      in the loop below.  */
2254   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
2255       && (bed = get_elf_backend_data (abfd)) != NULL
2256       && bed->sign_extend_vma)
2257     sign_adjust = (bfd_vma) 1 << (bed->s->arch_size - 1);
2258
2259   /* Disassemble a block of instructions up to the address associated with
2260      the symbol we have just found.  Then print the symbol and find the
2261      next symbol on.  Repeat until we have disassembled the entire section
2262      or we have reached the end of the address range we are interested in.  */
2263   while (addr_offset < stop_offset)
2264     {
2265       bfd_vma addr;
2266       asymbol *nextsym;
2267       bfd_vma nextstop_offset;
2268       bfd_boolean insns;
2269       bfd_boolean do_print = TRUE;
2270
2271       addr = section->vma + addr_offset;
2272       addr = ((addr & ((sign_adjust << 1) - 1)) ^ sign_adjust) - sign_adjust;
2273
2274       if (sym != NULL && bfd_asymbol_value (sym) <= addr)
2275         {
2276           int x;
2277
2278           for (x = place;
2279                (x < sorted_symcount
2280                 && (bfd_asymbol_value (sorted_syms[x]) <= addr));
2281                ++x)
2282             continue;
2283
2284           pinfo->symbols = sorted_syms + place;
2285           pinfo->num_symbols = x - place;
2286           pinfo->symtab_pos = place;
2287         }
2288       else
2289         {
2290           pinfo->symbols = NULL;
2291           pinfo->num_symbols = 0;
2292           pinfo->symtab_pos = -1;
2293         }
2294
2295       if (sym && paux->symbol)
2296         {
2297           const char *name = bfd_asymbol_name (sym);
2298           char *alloc = NULL;
2299
2300           if (do_demangle && name[0] != '\0')
2301             {
2302               /* Demangle the name.  */
2303               alloc = bfd_demangle (abfd, name, demangle_flags);
2304               if (alloc != NULL)
2305                 name = alloc;
2306             }
2307           do_print = streq (name, paux->symbol);
2308           free (alloc);
2309         }
2310
2311       if (! prefix_addresses && do_print)
2312         {
2313           pinfo->fprintf_func (pinfo->stream, "\n");
2314           objdump_print_addr_with_sym (abfd, section, sym, addr,
2315                                        pinfo, FALSE);
2316           pinfo->fprintf_func (pinfo->stream, ":\n");
2317         }
2318
2319       if (sym != NULL && bfd_asymbol_value (sym) > addr)
2320         nextsym = sym;
2321       else if (sym == NULL)
2322         nextsym = NULL;
2323       else
2324         {
2325 #define is_valid_next_sym(SYM) \
2326   ((SYM)->section == section \
2327    && (bfd_asymbol_value (SYM) > bfd_asymbol_value (sym)) \
2328    && pinfo->symbol_is_valid (SYM, pinfo))
2329
2330           /* Search forward for the next appropriate symbol in
2331              SECTION.  Note that all the symbols are sorted
2332              together into one big array, and that some sections
2333              may have overlapping addresses.  */
2334           while (place < sorted_symcount
2335                  && ! is_valid_next_sym (sorted_syms [place]))
2336             ++place;
2337
2338           if (place >= sorted_symcount)
2339             nextsym = NULL;
2340           else
2341             nextsym = sorted_syms[place];
2342         }
2343
2344       if (sym != NULL && bfd_asymbol_value (sym) > addr)
2345         nextstop_offset = bfd_asymbol_value (sym) - section->vma;
2346       else if (nextsym == NULL)
2347         nextstop_offset = stop_offset;
2348       else
2349         nextstop_offset = bfd_asymbol_value (nextsym) - section->vma;
2350
2351       if (nextstop_offset > stop_offset
2352           || nextstop_offset <= addr_offset)
2353         nextstop_offset = stop_offset;
2354
2355       /* If a symbol is explicitly marked as being an object
2356          rather than a function, just dump the bytes without
2357          disassembling them.  */
2358       if (disassemble_all
2359           || sym == NULL
2360           || sym->section != section
2361           || bfd_asymbol_value (sym) > addr
2362           || ((sym->flags & BSF_OBJECT) == 0
2363               && (strstr (bfd_asymbol_name (sym), "gnu_compiled")
2364                   == NULL)
2365               && (strstr (bfd_asymbol_name (sym), "gcc2_compiled")
2366                   == NULL))
2367           || (sym->flags & BSF_FUNCTION) != 0)
2368         insns = TRUE;
2369       else
2370         insns = FALSE;
2371
2372       if (do_print)
2373         {
2374           disassemble_bytes (pinfo, paux->disassemble_fn, insns, data,
2375                              addr_offset, nextstop_offset,
2376                              rel_offset, &rel_pp, rel_ppend);
2377           if (paux->symbol)
2378             break;
2379         }
2380
2381       addr_offset = nextstop_offset;
2382       sym = nextsym;
2383     }
2384
2385   free (data);
2386
2387   if (rel_ppstart != NULL)
2388     free (rel_ppstart);
2389 }
2390
2391 /* Disassemble the contents of an object file.  */
2392
2393 static void
2394 disassemble_data (bfd *abfd)
2395 {
2396   struct disassemble_info disasm_info;
2397   struct objdump_disasm_info aux;
2398   long i;
2399
2400   print_files = NULL;
2401   prev_functionname = NULL;
2402   prev_line = -1;
2403   prev_discriminator = 0;
2404
2405   /* We make a copy of syms to sort.  We don't want to sort syms
2406      because that will screw up the relocs.  */
2407   sorted_symcount = symcount ? symcount : dynsymcount;
2408   sorted_syms = (asymbol **) xmalloc ((sorted_symcount + synthcount)
2409                                       * sizeof (asymbol *));
2410   memcpy (sorted_syms, symcount ? syms : dynsyms,
2411           sorted_symcount * sizeof (asymbol *));
2412
2413   sorted_symcount = remove_useless_symbols (sorted_syms, sorted_symcount);
2414
2415   for (i = 0; i < synthcount; ++i)
2416     {
2417       sorted_syms[sorted_symcount] = synthsyms + i;
2418       ++sorted_symcount;
2419     }
2420
2421   /* Sort the symbols into section and symbol order.  */
2422   qsort (sorted_syms, sorted_symcount, sizeof (asymbol *), compare_symbols);
2423
2424   init_disassemble_info (&disasm_info, stdout, (fprintf_ftype) fprintf);
2425
2426   disasm_info.application_data = (void *) &aux;
2427   aux.abfd = abfd;
2428   aux.require_sec = FALSE;
2429   aux.dynrelbuf = NULL;
2430   aux.dynrelcount = 0;
2431   aux.reloc = NULL;
2432   aux.symbol = disasm_sym;
2433
2434   disasm_info.print_address_func = objdump_print_address;
2435   disasm_info.symbol_at_address_func = objdump_symbol_at_address;
2436
2437   if (machine != NULL)
2438     {
2439       const bfd_arch_info_type *inf = bfd_scan_arch (machine);
2440
2441       if (inf == NULL)
2442         fatal (_("can't use supplied machine %s"), machine);
2443
2444       abfd->arch_info = inf;
2445     }
2446
2447   if (endian != BFD_ENDIAN_UNKNOWN)
2448     {
2449       struct bfd_target *xvec;
2450
2451       xvec = (struct bfd_target *) xmalloc (sizeof (struct bfd_target));
2452       memcpy (xvec, abfd->xvec, sizeof (struct bfd_target));
2453       xvec->byteorder = endian;
2454       abfd->xvec = xvec;
2455     }
2456
2457   /* Use libopcodes to locate a suitable disassembler.  */
2458   aux.disassemble_fn = disassembler (bfd_get_arch (abfd),
2459                                      bfd_big_endian (abfd),
2460                                      bfd_get_mach (abfd), abfd);
2461   if (!aux.disassemble_fn)
2462     {
2463       non_fatal (_("can't disassemble for architecture %s\n"),
2464                  bfd_printable_arch_mach (bfd_get_arch (abfd), 0));
2465       exit_status = 1;
2466       return;
2467     }
2468
2469   disasm_info.flavour = bfd_get_flavour (abfd);
2470   disasm_info.arch = bfd_get_arch (abfd);
2471   disasm_info.mach = bfd_get_mach (abfd);
2472   disasm_info.disassembler_options = disassembler_options;
2473   disasm_info.octets_per_byte = bfd_octets_per_byte (abfd);
2474   disasm_info.skip_zeroes = DEFAULT_SKIP_ZEROES;
2475   disasm_info.skip_zeroes_at_end = DEFAULT_SKIP_ZEROES_AT_END;
2476   disasm_info.disassembler_needs_relocs = FALSE;
2477
2478   if (bfd_big_endian (abfd))
2479     disasm_info.display_endian = disasm_info.endian = BFD_ENDIAN_BIG;
2480   else if (bfd_little_endian (abfd))
2481     disasm_info.display_endian = disasm_info.endian = BFD_ENDIAN_LITTLE;
2482   else
2483     /* ??? Aborting here seems too drastic.  We could default to big or little
2484        instead.  */
2485     disasm_info.endian = BFD_ENDIAN_UNKNOWN;
2486
2487   /* Allow the target to customize the info structure.  */
2488   disassemble_init_for_target (& disasm_info);
2489
2490   /* Pre-load the dynamic relocs as we may need them during the disassembly.  */
2491     {
2492       long relsize = bfd_get_dynamic_reloc_upper_bound (abfd);
2493
2494       if (relsize < 0 && dump_dynamic_reloc_info)
2495         bfd_fatal (bfd_get_filename (abfd));
2496
2497       if (relsize > 0)
2498         {
2499           aux.dynrelbuf = (arelent **) xmalloc (relsize);
2500           aux.dynrelcount = bfd_canonicalize_dynamic_reloc (abfd,
2501                                                             aux.dynrelbuf,
2502                                                             dynsyms);
2503           if (aux.dynrelcount < 0)
2504             bfd_fatal (bfd_get_filename (abfd));
2505
2506           /* Sort the relocs by address.  */
2507           qsort (aux.dynrelbuf, aux.dynrelcount, sizeof (arelent *),
2508                  compare_relocs);
2509         }
2510     }
2511   disasm_info.symtab = sorted_syms;
2512   disasm_info.symtab_size = sorted_symcount;
2513
2514   bfd_map_over_sections (abfd, disassemble_section, & disasm_info);
2515
2516   if (aux.dynrelbuf != NULL)
2517     free (aux.dynrelbuf);
2518   free (sorted_syms);
2519 }
2520 \f
2521 static bfd_boolean
2522 load_specific_debug_section (enum dwarf_section_display_enum debug,
2523                              asection *sec, void *file)
2524 {
2525   struct dwarf_section *section = &debug_displays [debug].section;
2526   bfd *abfd = (bfd *) file;
2527   bfd_byte *contents;
2528   bfd_size_type amt;
2529
2530   if (section->start != NULL)
2531     {
2532       /* If it is already loaded, do nothing.  */
2533       if (streq (section->filename, bfd_get_filename (abfd)))
2534         return TRUE;
2535       free (section->start);
2536     }
2537
2538   section->filename = bfd_get_filename (abfd);
2539   section->reloc_info = NULL;
2540   section->num_relocs = 0;
2541   section->address = bfd_get_section_vma (abfd, sec);
2542   section->user_data = sec;
2543   section->size = bfd_get_section_size (sec);
2544   amt = section->size + 1;
2545   if (amt == 0 || amt > bfd_get_file_size (abfd))
2546     {
2547       section->start = NULL;
2548       free_debug_section (debug);
2549       printf (_("\nSection '%s' has an invalid size: %#llx.\n"),
2550               section->name, (unsigned long long) section->size);
2551       return FALSE;
2552     }
2553   section->start = contents = malloc (amt);
2554   if (section->start == NULL
2555       || !bfd_get_full_section_contents (abfd, sec, &contents))
2556     {
2557       free_debug_section (debug);
2558       printf (_("\nCan't get contents for section '%s'.\n"),
2559               section->name);
2560       return FALSE;
2561     }
2562   /* Ensure any string section has a terminating NUL.  */
2563   section->start[section->size] = 0;
2564
2565   if (is_relocatable && debug_displays [debug].relocate)
2566     {
2567       long         reloc_size;
2568       bfd_boolean  ret;
2569
2570       bfd_cache_section_contents (sec, section->start);
2571
2572       ret = bfd_simple_get_relocated_section_contents (abfd,
2573                                                        sec,
2574                                                        section->start,
2575                                                        syms) != NULL;
2576
2577       if (! ret)
2578         {
2579           free_debug_section (debug);
2580           printf (_("\nCan't get contents for section '%s'.\n"),
2581                   section->name);
2582           return FALSE;
2583         }
2584
2585       reloc_size = bfd_get_reloc_upper_bound (abfd, sec);
2586       if (reloc_size > 0)
2587         {
2588           unsigned long reloc_count;
2589           arelent **relocs;
2590
2591           relocs = (arelent **) xmalloc (reloc_size);
2592
2593           reloc_count = bfd_canonicalize_reloc (abfd, sec, relocs, NULL);
2594           if (reloc_count == 0)
2595             free (relocs);
2596           else
2597             {
2598               section->reloc_info = relocs;
2599               section->num_relocs = reloc_count;
2600             }
2601         }
2602     }
2603
2604   return TRUE;
2605 }
2606
2607 bfd_boolean
2608 reloc_at (struct dwarf_section * dsec, dwarf_vma offset)
2609 {
2610   arelent ** relocs;
2611   arelent * rp;
2612
2613   if (dsec == NULL || dsec->reloc_info == NULL)
2614     return FALSE;
2615
2616   relocs = (arelent **) dsec->reloc_info;
2617
2618   for (; (rp = * relocs) != NULL; ++ relocs)
2619     if (rp->address == offset)
2620       return TRUE;
2621
2622   return FALSE;
2623 }
2624
2625 bfd_boolean
2626 load_debug_section (enum dwarf_section_display_enum debug, void *file)
2627 {
2628   struct dwarf_section *section = &debug_displays [debug].section;
2629   bfd *abfd = (bfd *) file;
2630   asection *sec;
2631
2632   /* If it is already loaded, do nothing.  */
2633   if (section->start != NULL)
2634     {
2635       if (streq (section->filename, bfd_get_filename (abfd)))
2636         return TRUE;
2637     }
2638
2639   /* Locate the debug section.  */
2640   sec = bfd_get_section_by_name (abfd, section->uncompressed_name);
2641   if (sec != NULL)
2642     section->name = section->uncompressed_name;
2643   else
2644     {
2645       sec = bfd_get_section_by_name (abfd, section->compressed_name);
2646       if (sec != NULL)
2647         section->name = section->compressed_name;
2648     }
2649   if (sec == NULL)
2650     return FALSE;
2651
2652   return load_specific_debug_section (debug, sec, file);
2653 }
2654
2655 void
2656 free_debug_section (enum dwarf_section_display_enum debug)
2657 {
2658   struct dwarf_section *section = &debug_displays [debug].section;
2659
2660   if (section->start == NULL)
2661     return;
2662
2663   /* PR 17512: file: 0f67f69d.  */
2664   if (section->user_data != NULL)
2665     {
2666       asection * sec = (asection *) section->user_data;
2667
2668       /* If we are freeing contents that are also pointed to by the BFD
2669          library's section structure then make sure to update those pointers
2670          too.  Otherwise, the next time we try to load data for this section
2671          we can end up using a stale pointer.  */
2672       if (section->start == sec->contents)
2673         {
2674           sec->contents = NULL;
2675           sec->flags &= ~ SEC_IN_MEMORY;
2676           sec->compress_status = COMPRESS_SECTION_NONE;
2677         }
2678     }
2679
2680   free ((char *) section->start);
2681   section->start = NULL;
2682   section->address = 0;
2683   section->size = 0;
2684 }
2685
2686 void
2687 close_debug_file (void * file)
2688 {
2689   bfd * abfd = (bfd *) file;
2690
2691   bfd_close (abfd);
2692 }
2693
2694 void *
2695 open_debug_file (const char * pathname)
2696 {
2697   bfd * data;
2698
2699   data = bfd_openr (pathname, NULL);
2700   if (data == NULL)
2701     return NULL;
2702
2703   if (! bfd_check_format (data, bfd_object))
2704     return NULL;
2705   
2706   return data;
2707 }
2708
2709 static void
2710 dump_dwarf_section (bfd *abfd, asection *section,
2711                     void *arg ATTRIBUTE_UNUSED)
2712 {
2713   const char *name = bfd_get_section_name (abfd, section);
2714   const char *match;
2715   int i;
2716
2717   if (CONST_STRNEQ (name, ".gnu.linkonce.wi."))
2718     match = ".debug_info";
2719   else
2720     match = name;
2721
2722   for (i = 0; i < max; i++)
2723     if ((strcmp (debug_displays [i].section.uncompressed_name, match) == 0
2724          || strcmp (debug_displays [i].section.compressed_name, match) == 0)
2725         && debug_displays [i].enabled != NULL
2726         && *debug_displays [i].enabled)
2727       {
2728         struct dwarf_section *sec = &debug_displays [i].section;
2729
2730         if (strcmp (sec->uncompressed_name, match) == 0)
2731           sec->name = sec->uncompressed_name;
2732         else
2733           sec->name = sec->compressed_name;
2734         if (load_specific_debug_section ((enum dwarf_section_display_enum) i,
2735                                          section, abfd))
2736           {
2737             debug_displays [i].display (sec, abfd);
2738
2739             if (i != info && i != abbrev)
2740               free_debug_section ((enum dwarf_section_display_enum) i);
2741           }
2742         break;
2743       }
2744 }
2745
2746 /* Dump the dwarf debugging information.  */
2747
2748 static void
2749 dump_dwarf (bfd *abfd)
2750 {
2751   bfd * separates;
2752
2753   is_relocatable = (abfd->flags & (EXEC_P | DYNAMIC)) == 0;
2754
2755   eh_addr_size = bfd_arch_bits_per_address (abfd) / 8;
2756
2757   if (bfd_big_endian (abfd))
2758     byte_get = byte_get_big_endian;
2759   else if (bfd_little_endian (abfd))
2760     byte_get = byte_get_little_endian;
2761   else
2762     /* PR 17512: file: objdump-s-endless-loop.tekhex.  */
2763     {
2764       warn (_("File %s does not contain any dwarf debug information\n"),
2765             bfd_get_filename (abfd));
2766       return;
2767     }
2768
2769   switch (bfd_get_arch (abfd))
2770     {
2771     case bfd_arch_i386:
2772       switch (bfd_get_mach (abfd))
2773         {
2774         case bfd_mach_x86_64:
2775         case bfd_mach_x86_64_intel_syntax:
2776         case bfd_mach_x86_64_nacl:
2777         case bfd_mach_x64_32:
2778         case bfd_mach_x64_32_intel_syntax:
2779         case bfd_mach_x64_32_nacl:
2780           init_dwarf_regnames_x86_64 ();
2781           break;
2782
2783         default:
2784           init_dwarf_regnames_i386 ();
2785           break;
2786         }
2787       break;
2788
2789     case bfd_arch_iamcu:
2790       init_dwarf_regnames_iamcu ();
2791       break;
2792
2793     case bfd_arch_aarch64:
2794       init_dwarf_regnames_aarch64();
2795       break;
2796
2797     case bfd_arch_s390:
2798       init_dwarf_regnames_s390 ();
2799       break;
2800
2801     case bfd_arch_riscv:
2802       init_dwarf_regnames_riscv ();
2803       break;
2804
2805     case bfd_arch_s12z:
2806       /* S12Z has a 24 bit address space.  But the only known
2807          producer of dwarf_info encodes addresses into 32 bits.  */
2808       eh_addr_size = 4;
2809       break;
2810
2811     default:
2812       break;
2813     }
2814
2815   separates = load_separate_debug_file (abfd, bfd_get_filename (abfd));
2816
2817   bfd_map_over_sections (abfd, dump_dwarf_section, NULL);
2818
2819   if (separates)
2820     bfd_map_over_sections (separates, dump_dwarf_section, NULL);
2821
2822   free_debug_memory ();
2823 }
2824 \f
2825 /* Read ABFD's stabs section STABSECT_NAME, and return a pointer to
2826    it.  Return NULL on failure.   */
2827
2828 static bfd_byte *
2829 read_section_stabs (bfd *abfd, const char *sect_name, bfd_size_type *size_ptr)
2830 {
2831   asection *stabsect;
2832   bfd_byte *contents;
2833
2834   stabsect = bfd_get_section_by_name (abfd, sect_name);
2835   if (stabsect == NULL)
2836     {
2837       printf (_("No %s section present\n\n"), sect_name);
2838       return FALSE;
2839     }
2840
2841   if (!bfd_malloc_and_get_section (abfd, stabsect, &contents))
2842     {
2843       non_fatal (_("reading %s section of %s failed: %s"),
2844                  sect_name, bfd_get_filename (abfd),
2845                  bfd_errmsg (bfd_get_error ()));
2846       exit_status = 1;
2847       free (contents);
2848       return NULL;
2849     }
2850
2851   *size_ptr = bfd_section_size (abfd, stabsect);
2852
2853   return contents;
2854 }
2855
2856 /* Stabs entries use a 12 byte format:
2857      4 byte string table index
2858      1 byte stab type
2859      1 byte stab other field
2860      2 byte stab desc field
2861      4 byte stab value
2862    FIXME: This will have to change for a 64 bit object format.  */
2863
2864 #define STRDXOFF  (0)
2865 #define TYPEOFF   (4)
2866 #define OTHEROFF  (5)
2867 #define DESCOFF   (6)
2868 #define VALOFF    (8)
2869 #define STABSIZE (12)
2870
2871 /* Print ABFD's stabs section STABSECT_NAME (in `stabs'),
2872    using string table section STRSECT_NAME (in `strtab').  */
2873
2874 static void
2875 print_section_stabs (bfd *abfd,
2876                      const char *stabsect_name,
2877                      unsigned *string_offset_ptr)
2878 {
2879   int i;
2880   unsigned file_string_table_offset = 0;
2881   unsigned next_file_string_table_offset = *string_offset_ptr;
2882   bfd_byte *stabp, *stabs_end;
2883
2884   stabp = stabs;
2885   stabs_end = stabp + stab_size;
2886
2887   printf (_("Contents of %s section:\n\n"), stabsect_name);
2888   printf ("Symnum n_type n_othr n_desc n_value  n_strx String\n");
2889
2890   /* Loop through all symbols and print them.
2891
2892      We start the index at -1 because there is a dummy symbol on
2893      the front of stabs-in-{coff,elf} sections that supplies sizes.  */
2894   for (i = -1; stabp <= stabs_end - STABSIZE; stabp += STABSIZE, i++)
2895     {
2896       const char *name;
2897       unsigned long strx;
2898       unsigned char type, other;
2899       unsigned short desc;
2900       bfd_vma value;
2901
2902       strx = bfd_h_get_32 (abfd, stabp + STRDXOFF);
2903       type = bfd_h_get_8 (abfd, stabp + TYPEOFF);
2904       other = bfd_h_get_8 (abfd, stabp + OTHEROFF);
2905       desc = bfd_h_get_16 (abfd, stabp + DESCOFF);
2906       value = bfd_h_get_32 (abfd, stabp + VALOFF);
2907
2908       printf ("\n%-6d ", i);
2909       /* Either print the stab name, or, if unnamed, print its number
2910          again (makes consistent formatting for tools like awk).  */
2911       name = bfd_get_stab_name (type);
2912       if (name != NULL)
2913         printf ("%-6s", name);
2914       else if (type == N_UNDF)
2915         printf ("HdrSym");
2916       else
2917         printf ("%-6d", type);
2918       printf (" %-6d %-6d ", other, desc);
2919       bfd_printf_vma (abfd, value);
2920       printf (" %-6lu", strx);
2921
2922       /* Symbols with type == 0 (N_UNDF) specify the length of the
2923          string table associated with this file.  We use that info
2924          to know how to relocate the *next* file's string table indices.  */
2925       if (type == N_UNDF)
2926         {
2927           file_string_table_offset = next_file_string_table_offset;
2928           next_file_string_table_offset += value;
2929         }
2930       else
2931         {
2932           bfd_size_type amt = strx + file_string_table_offset;
2933
2934           /* Using the (possibly updated) string table offset, print the
2935              string (if any) associated with this symbol.  */
2936           if (amt < stabstr_size)
2937             /* PR 17512: file: 079-79389-0.001:0.1.  */
2938             printf (" %.*s", (int)(stabstr_size - amt), strtab + amt);
2939           else
2940             printf (" *");
2941         }
2942     }
2943   printf ("\n\n");
2944   *string_offset_ptr = next_file_string_table_offset;
2945 }
2946
2947 typedef struct
2948 {
2949   const char * section_name;
2950   const char * string_section_name;
2951   unsigned string_offset;
2952 }
2953 stab_section_names;
2954
2955 static void
2956 find_stabs_section (bfd *abfd, asection *section, void *names)
2957 {
2958   int len;
2959   stab_section_names * sought = (stab_section_names *) names;
2960
2961   /* Check for section names for which stabsect_name is a prefix, to
2962      handle .stab.N, etc.  */
2963   len = strlen (sought->section_name);
2964
2965   /* If the prefix matches, and the files section name ends with a
2966      nul or a digit, then we match.  I.e., we want either an exact
2967      match or a section followed by a number.  */
2968   if (strncmp (sought->section_name, section->name, len) == 0
2969       && (section->name[len] == 0
2970           || (section->name[len] == '.' && ISDIGIT (section->name[len + 1]))))
2971     {
2972       if (strtab == NULL)
2973         strtab = read_section_stabs (abfd, sought->string_section_name,
2974                                      &stabstr_size);
2975
2976       if (strtab)
2977         {
2978           stabs = read_section_stabs (abfd, section->name, &stab_size);
2979           if (stabs)
2980             print_section_stabs (abfd, section->name, &sought->string_offset);
2981         }
2982     }
2983 }
2984
2985 static void
2986 dump_stabs_section (bfd *abfd, char *stabsect_name, char *strsect_name)
2987 {
2988   stab_section_names s;
2989
2990   s.section_name = stabsect_name;
2991   s.string_section_name = strsect_name;
2992   s.string_offset = 0;
2993
2994   bfd_map_over_sections (abfd, find_stabs_section, & s);
2995
2996   free (strtab);
2997   strtab = NULL;
2998 }
2999
3000 /* Dump the any sections containing stabs debugging information.  */
3001
3002 static void
3003 dump_stabs (bfd *abfd)
3004 {
3005   dump_stabs_section (abfd, ".stab", ".stabstr");
3006   dump_stabs_section (abfd, ".stab.excl", ".stab.exclstr");
3007   dump_stabs_section (abfd, ".stab.index", ".stab.indexstr");
3008
3009   /* For Darwin.  */
3010   dump_stabs_section (abfd, "LC_SYMTAB.stabs", "LC_SYMTAB.stabstr");
3011
3012   dump_stabs_section (abfd, "$GDB_SYMBOLS$", "$GDB_STRINGS$");
3013 }
3014 \f
3015 static void
3016 dump_bfd_header (bfd *abfd)
3017 {
3018   char *comma = "";
3019
3020   printf (_("architecture: %s, "),
3021           bfd_printable_arch_mach (bfd_get_arch (abfd),
3022                                    bfd_get_mach (abfd)));
3023   printf (_("flags 0x%08x:\n"), abfd->flags & ~BFD_FLAGS_FOR_BFD_USE_MASK);
3024
3025 #define PF(x, y)    if (abfd->flags & x) {printf("%s%s", comma, y); comma=", ";}
3026   PF (HAS_RELOC, "HAS_RELOC");
3027   PF (EXEC_P, "EXEC_P");
3028   PF (HAS_LINENO, "HAS_LINENO");
3029   PF (HAS_DEBUG, "HAS_DEBUG");
3030   PF (HAS_SYMS, "HAS_SYMS");
3031   PF (HAS_LOCALS, "HAS_LOCALS");
3032   PF (DYNAMIC, "DYNAMIC");
3033   PF (WP_TEXT, "WP_TEXT");
3034   PF (D_PAGED, "D_PAGED");
3035   PF (BFD_IS_RELAXABLE, "BFD_IS_RELAXABLE");
3036   printf (_("\nstart address 0x"));
3037   bfd_printf_vma (abfd, abfd->start_address);
3038   printf ("\n");
3039 }
3040
3041 \f
3042 static void
3043 dump_bfd_private_header (bfd *abfd)
3044 {
3045   bfd_print_private_bfd_data (abfd, stdout);
3046 }
3047
3048 static void
3049 dump_target_specific (bfd *abfd)
3050 {
3051   const struct objdump_private_desc * const *desc;
3052   struct objdump_private_option *opt;
3053   char *e, *b;
3054
3055   /* Find the desc.  */
3056   for (desc = objdump_private_vectors; *desc != NULL; desc++)
3057     if ((*desc)->filter (abfd))
3058       break;
3059
3060   if (*desc == NULL)
3061     {
3062       non_fatal (_("option -P/--private not supported by this file"));
3063       return;
3064     }
3065
3066   /* Clear all options.  */
3067   for (opt = (*desc)->options; opt->name; opt++)
3068     opt->selected = FALSE;
3069
3070   /* Decode options.  */
3071   b = dump_private_options;
3072   do
3073     {
3074       e = strchr (b, ',');
3075
3076       if (e)
3077         *e = 0;
3078
3079       for (opt = (*desc)->options; opt->name; opt++)
3080         if (strcmp (opt->name, b) == 0)
3081           {
3082             opt->selected = TRUE;
3083             break;
3084           }
3085       if (opt->name == NULL)
3086         non_fatal (_("target specific dump '%s' not supported"), b);
3087
3088       if (e)
3089         {
3090           *e = ',';
3091           b = e + 1;
3092         }
3093     }
3094   while (e != NULL);
3095
3096   /* Dump.  */
3097   (*desc)->dump (abfd);
3098 }
3099 \f
3100 /* Display a section in hexadecimal format with associated characters.
3101    Each line prefixed by the zero padded address.  */
3102
3103 static void
3104 dump_section (bfd *abfd, asection *section, void *dummy ATTRIBUTE_UNUSED)
3105 {
3106   bfd_byte *data = NULL;
3107   bfd_size_type datasize;
3108   bfd_vma addr_offset;
3109   bfd_vma start_offset;
3110   bfd_vma stop_offset;
3111   unsigned int opb = bfd_octets_per_byte (abfd);
3112   /* Bytes per line.  */
3113   const int onaline = 16;
3114   char buf[64];
3115   int count;
3116   int width;
3117
3118   if ((section->flags & SEC_HAS_CONTENTS) == 0)
3119     return;
3120
3121   if (! process_section_p (section))
3122     return;
3123
3124   if ((datasize = bfd_section_size (abfd, section)) == 0)
3125     return;
3126
3127   /* Compute the address range to display.  */
3128   if (start_address == (bfd_vma) -1
3129       || start_address < section->vma)
3130     start_offset = 0;
3131   else
3132     start_offset = start_address - section->vma;
3133
3134   if (stop_address == (bfd_vma) -1)
3135     stop_offset = datasize / opb;
3136   else
3137     {
3138       if (stop_address < section->vma)
3139         stop_offset = 0;
3140       else
3141         stop_offset = stop_address - section->vma;
3142
3143       if (stop_offset > datasize / opb)
3144         stop_offset = datasize / opb;
3145     }
3146
3147   if (start_offset >= stop_offset)
3148     return;
3149
3150   printf (_("Contents of section %s:"), section->name);
3151   if (display_file_offsets)
3152     printf (_("  (Starting at file offset: 0x%lx)"),
3153             (unsigned long) (section->filepos + start_offset));
3154   printf ("\n");
3155
3156   if (!bfd_get_full_section_contents (abfd, section, &data))
3157     {
3158       non_fatal (_("Reading section %s failed because: %s"),
3159                  section->name, bfd_errmsg (bfd_get_error ()));
3160       return;
3161     }
3162
3163   width = 4;
3164
3165   bfd_sprintf_vma (abfd, buf, start_offset + section->vma);
3166   if (strlen (buf) >= sizeof (buf))
3167     abort ();
3168
3169   count = 0;
3170   while (buf[count] == '0' && buf[count+1] != '\0')
3171     count++;
3172   count = strlen (buf) - count;
3173   if (count > width)
3174     width = count;
3175
3176   bfd_sprintf_vma (abfd, buf, stop_offset + section->vma - 1);
3177   if (strlen (buf) >= sizeof (buf))
3178     abort ();
3179
3180   count = 0;
3181   while (buf[count] == '0' && buf[count+1] != '\0')
3182     count++;
3183   count = strlen (buf) - count;
3184   if (count > width)
3185     width = count;
3186
3187   for (addr_offset = start_offset;
3188        addr_offset < stop_offset; addr_offset += onaline / opb)
3189     {
3190       bfd_size_type j;
3191
3192       bfd_sprintf_vma (abfd, buf, (addr_offset + section->vma));
3193       count = strlen (buf);
3194       if ((size_t) count >= sizeof (buf))
3195         abort ();
3196
3197       putchar (' ');
3198       while (count < width)
3199         {
3200           putchar ('0');
3201           count++;
3202         }
3203       fputs (buf + count - width, stdout);
3204       putchar (' ');
3205
3206       for (j = addr_offset * opb;
3207            j < addr_offset * opb + onaline; j++)
3208         {
3209           if (j < stop_offset * opb)
3210             printf ("%02x", (unsigned) (data[j]));
3211           else
3212             printf ("  ");
3213           if ((j & 3) == 3)
3214             printf (" ");
3215         }
3216
3217       printf (" ");
3218       for (j = addr_offset * opb;
3219            j < addr_offset * opb + onaline; j++)
3220         {
3221           if (j >= stop_offset * opb)
3222             printf (" ");
3223           else
3224             printf ("%c", ISPRINT (data[j]) ? data[j] : '.');
3225         }
3226       putchar ('\n');
3227     }
3228   free (data);
3229 }
3230
3231 /* Actually display the various requested regions.  */
3232
3233 static void
3234 dump_data (bfd *abfd)
3235 {
3236   bfd_map_over_sections (abfd, dump_section, NULL);
3237 }
3238
3239 /* Should perhaps share code and display with nm?  */
3240
3241 static void
3242 dump_symbols (bfd *abfd ATTRIBUTE_UNUSED, bfd_boolean dynamic)
3243 {
3244   asymbol **current;
3245   long max_count;
3246   long count;
3247
3248   if (dynamic)
3249     {
3250       current = dynsyms;
3251       max_count = dynsymcount;
3252       printf ("DYNAMIC SYMBOL TABLE:\n");
3253     }
3254   else
3255     {
3256       current = syms;
3257       max_count = symcount;
3258       printf ("SYMBOL TABLE:\n");
3259     }
3260
3261   if (max_count == 0)
3262     printf (_("no symbols\n"));
3263
3264   for (count = 0; count < max_count; count++)
3265     {
3266       bfd *cur_bfd;
3267
3268       if (*current == NULL)
3269         printf (_("no information for symbol number %ld\n"), count);
3270
3271       else if ((cur_bfd = bfd_asymbol_bfd (*current)) == NULL)
3272         printf (_("could not determine the type of symbol number %ld\n"),
3273                 count);
3274
3275       else if (process_section_p ((* current)->section)
3276                && (dump_special_syms
3277                    || !bfd_is_target_special_symbol (cur_bfd, *current)))
3278         {
3279           const char *name = (*current)->name;
3280
3281           if (do_demangle && name != NULL && *name != '\0')
3282             {
3283               char *alloc;
3284
3285               /* If we want to demangle the name, we demangle it
3286                  here, and temporarily clobber it while calling
3287                  bfd_print_symbol.  FIXME: This is a gross hack.  */
3288               alloc = bfd_demangle (cur_bfd, name, demangle_flags);
3289               if (alloc != NULL)
3290                 (*current)->name = alloc;
3291               bfd_print_symbol (cur_bfd, stdout, *current,
3292                                 bfd_print_symbol_all);
3293               if (alloc != NULL)
3294                 {
3295                   (*current)->name = name;
3296                   free (alloc);
3297                 }
3298             }
3299           else
3300             bfd_print_symbol (cur_bfd, stdout, *current,
3301                               bfd_print_symbol_all);
3302           printf ("\n");
3303         }
3304
3305       current++;
3306     }
3307   printf ("\n\n");
3308 }
3309 \f
3310 static void
3311 dump_reloc_set (bfd *abfd, asection *sec, arelent **relpp, long relcount)
3312 {
3313   arelent **p;
3314   char *last_filename, *last_functionname;
3315   unsigned int last_line;
3316   unsigned int last_discriminator;
3317
3318   /* Get column headers lined up reasonably.  */
3319   {
3320     static int width;
3321
3322     if (width == 0)
3323       {
3324         char buf[30];
3325
3326         bfd_sprintf_vma (abfd, buf, (bfd_vma) -1);
3327         width = strlen (buf) - 7;
3328       }
3329     printf ("OFFSET %*s TYPE %*s VALUE \n", width, "", 12, "");
3330   }
3331
3332   last_filename = NULL;
3333   last_functionname = NULL;
3334   last_line = 0;
3335   last_discriminator = 0;
3336
3337   for (p = relpp; relcount && *p != NULL; p++, relcount--)
3338     {
3339       arelent *q = *p;
3340       const char *filename, *functionname;
3341       unsigned int linenumber;
3342       unsigned int discriminator;
3343       const char *sym_name;
3344       const char *section_name;
3345       bfd_vma addend2 = 0;
3346
3347       if (start_address != (bfd_vma) -1
3348           && q->address < start_address)
3349         continue;
3350       if (stop_address != (bfd_vma) -1
3351           && q->address > stop_address)
3352         continue;
3353
3354       if (with_line_numbers
3355           && sec != NULL
3356           && bfd_find_nearest_line_discriminator (abfd, sec, syms, q->address,
3357                                                   &filename, &functionname,
3358                                                   &linenumber, &discriminator))
3359         {
3360           if (functionname != NULL
3361               && (last_functionname == NULL
3362                   || strcmp (functionname, last_functionname) != 0))
3363             {
3364               printf ("%s():\n", functionname);
3365               if (last_functionname != NULL)
3366                 free (last_functionname);
3367               last_functionname = xstrdup (functionname);
3368             }
3369
3370           if (linenumber > 0
3371               && (linenumber != last_line
3372                   || (filename != NULL
3373                       && last_filename != NULL
3374                       && filename_cmp (filename, last_filename) != 0)
3375                   || (discriminator != last_discriminator)))
3376             {
3377               if (discriminator > 0)
3378                 printf ("%s:%u\n", filename == NULL ? "???" : filename, linenumber);
3379               else
3380                 printf ("%s:%u (discriminator %u)\n", filename == NULL ? "???" : filename,
3381                         linenumber, discriminator);
3382               last_line = linenumber;
3383               last_discriminator = discriminator;
3384               if (last_filename != NULL)
3385                 free (last_filename);
3386               if (filename == NULL)
3387                 last_filename = NULL;
3388               else
3389                 last_filename = xstrdup (filename);
3390             }
3391         }
3392
3393       if (q->sym_ptr_ptr && *q->sym_ptr_ptr)
3394         {
3395           sym_name = (*(q->sym_ptr_ptr))->name;
3396           section_name = (*(q->sym_ptr_ptr))->section->name;
3397         }
3398       else
3399         {
3400           sym_name = NULL;
3401           section_name = NULL;
3402         }
3403
3404       bfd_printf_vma (abfd, q->address);
3405       if (q->howto == NULL)
3406         printf (" *unknown*         ");
3407       else if (q->howto->name)
3408         {
3409           const char *name = q->howto->name;
3410
3411           /* R_SPARC_OLO10 relocations contain two addends.
3412              But because 'arelent' lacks enough storage to
3413              store them both, the 64-bit ELF Sparc backend
3414              records this as two relocations.  One R_SPARC_LO10
3415              and one R_SPARC_13, both pointing to the same
3416              address.  This is merely so that we have some
3417              place to store both addend fields.
3418
3419              Undo this transformation, otherwise the output
3420              will be confusing.  */
3421           if (abfd->xvec->flavour == bfd_target_elf_flavour
3422               && elf_tdata(abfd)->elf_header->e_machine == EM_SPARCV9
3423               && relcount > 1
3424               && !strcmp (q->howto->name, "R_SPARC_LO10"))
3425             {
3426               arelent *q2 = *(p + 1);
3427               if (q2 != NULL
3428                   && q2->howto
3429                   && q->address == q2->address
3430                   && !strcmp (q2->howto->name, "R_SPARC_13"))
3431                 {
3432                   name = "R_SPARC_OLO10";
3433                   addend2 = q2->addend;
3434                   p++;
3435                 }
3436             }
3437           printf (" %-16s  ", name);
3438         }
3439       else
3440         printf (" %-16d  ", q->howto->type);
3441
3442       if (sym_name)
3443         {
3444           objdump_print_symname (abfd, NULL, *q->sym_ptr_ptr);
3445         }
3446       else
3447         {
3448           if (section_name == NULL)
3449             section_name = "*unknown*";
3450           printf ("[%s]", section_name);
3451         }
3452
3453       if (q->addend)
3454         {
3455           bfd_signed_vma addend = q->addend;
3456           if (addend < 0)
3457             {
3458               printf ("-0x");
3459               addend = -addend;
3460             }
3461           else
3462             printf ("+0x");
3463           bfd_printf_vma (abfd, addend);
3464         }
3465       if (addend2)
3466         {
3467           printf ("+0x");
3468           bfd_printf_vma (abfd, addend2);
3469         }
3470
3471       printf ("\n");
3472     }
3473
3474   if (last_filename != NULL)
3475     free (last_filename);
3476   if (last_functionname != NULL)
3477     free (last_functionname);
3478 }
3479
3480 static void
3481 dump_relocs_in_section (bfd *abfd,
3482                         asection *section,
3483                         void *dummy ATTRIBUTE_UNUSED)
3484 {
3485   arelent **relpp;
3486   long relcount;
3487   long relsize;
3488
3489   if (   bfd_is_abs_section (section)
3490       || bfd_is_und_section (section)
3491       || bfd_is_com_section (section)
3492       || (! process_section_p (section))
3493       || ((section->flags & SEC_RELOC) == 0))
3494     return;
3495
3496   relsize = bfd_get_reloc_upper_bound (abfd, section);
3497   if (relsize < 0)
3498     bfd_fatal (bfd_get_filename (abfd));
3499
3500   printf ("RELOCATION RECORDS FOR [%s]:", section->name);
3501
3502   if (relsize == 0)
3503     {
3504       printf (" (none)\n\n");
3505       return;
3506     }
3507
3508   if ((bfd_get_file_flags (abfd) & (BFD_IN_MEMORY | BFD_LINKER_CREATED)) == 0
3509       && (/* Check that the size of the relocs is reasonable.  Note that some
3510              file formats, eg aout, can have relocs whose internal size is
3511              larger than their external size, thus we check the size divided
3512              by four against the file size.  See PR 23931 for an example of
3513              this.  */
3514           ((ufile_ptr) (relsize / 4) > bfd_get_file_size (abfd))
3515           /* Also check the section's reloc count since if this is negative
3516              (or very large) the computation in bfd_get_reloc_upper_bound
3517              may have resulted in returning a small, positive integer.
3518              See PR 22508 for a reproducer.
3519
3520              Note - we check against file size rather than section size as
3521              it is possible for there to be more relocs that apply to a
3522              section than there are bytes in that section.  */
3523           || (section->reloc_count > bfd_get_file_size (abfd))))
3524     {
3525       printf (" (too many: %#x relocs)\n", section->reloc_count);
3526       bfd_set_error (bfd_error_file_truncated);
3527       bfd_fatal (bfd_get_filename (abfd));
3528     }
3529
3530   relpp = (arelent **) xmalloc (relsize);
3531   relcount = bfd_canonicalize_reloc (abfd, section, relpp, syms);
3532
3533   if (relcount < 0)
3534     {
3535       printf ("\n");
3536       non_fatal (_("failed to read relocs in: %s"), bfd_get_filename (abfd));
3537       bfd_fatal (_("error message was"));
3538     }
3539   else if (relcount == 0)
3540     printf (" (none)\n\n");
3541   else
3542     {
3543       printf ("\n");
3544       dump_reloc_set (abfd, section, relpp, relcount);
3545       printf ("\n\n");
3546     }
3547   free (relpp);
3548 }
3549
3550 static void
3551 dump_relocs (bfd *abfd)
3552 {
3553   bfd_map_over_sections (abfd, dump_relocs_in_section, NULL);
3554 }
3555
3556 static void
3557 dump_dynamic_relocs (bfd *abfd)
3558 {
3559   long relsize;
3560   arelent **relpp;
3561   long relcount;
3562
3563   relsize = bfd_get_dynamic_reloc_upper_bound (abfd);
3564   if (relsize < 0)
3565     bfd_fatal (bfd_get_filename (abfd));
3566
3567   printf ("DYNAMIC RELOCATION RECORDS");
3568
3569   if (relsize == 0)
3570     printf (" (none)\n\n");
3571   else
3572     {
3573       relpp = (arelent **) xmalloc (relsize);
3574       relcount = bfd_canonicalize_dynamic_reloc (abfd, relpp, dynsyms);
3575
3576       if (relcount < 0)
3577         bfd_fatal (bfd_get_filename (abfd));
3578       else if (relcount == 0)
3579         printf (" (none)\n\n");
3580       else
3581         {
3582           printf ("\n");
3583           dump_reloc_set (abfd, NULL, relpp, relcount);
3584           printf ("\n\n");
3585         }
3586       free (relpp);
3587     }
3588 }
3589
3590 /* Creates a table of paths, to search for source files.  */
3591
3592 static void
3593 add_include_path (const char *path)
3594 {
3595   if (path[0] == 0)
3596     return;
3597   include_path_count++;
3598   include_paths = (const char **)
3599       xrealloc (include_paths, include_path_count * sizeof (*include_paths));
3600 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
3601   if (path[1] == ':' && path[2] == 0)
3602     path = concat (path, ".", (const char *) 0);
3603 #endif
3604   include_paths[include_path_count - 1] = path;
3605 }
3606
3607 static void
3608 adjust_addresses (bfd *abfd ATTRIBUTE_UNUSED,
3609                   asection *section,
3610                   void *arg)
3611 {
3612   if ((section->flags & SEC_DEBUGGING) == 0)
3613     {
3614       bfd_boolean *has_reloc_p = (bfd_boolean *) arg;
3615       section->vma += adjust_section_vma;
3616       if (*has_reloc_p)
3617         section->lma += adjust_section_vma;
3618     }
3619 }
3620
3621 /* Dump selected contents of ABFD.  */
3622
3623 static void
3624 dump_bfd (bfd *abfd)
3625 {
3626   /* If we are adjusting section VMA's, change them all now.  Changing
3627      the BFD information is a hack.  However, we must do it, or
3628      bfd_find_nearest_line will not do the right thing.  */
3629   if (adjust_section_vma != 0)
3630     {
3631       bfd_boolean has_reloc = (abfd->flags & HAS_RELOC);
3632       bfd_map_over_sections (abfd, adjust_addresses, &has_reloc);
3633     }
3634
3635   if (! dump_debugging_tags && ! suppress_bfd_header)
3636     printf (_("\n%s:     file format %s\n"), bfd_get_filename (abfd),
3637             abfd->xvec->name);
3638   if (dump_ar_hdrs)
3639     print_arelt_descr (stdout, abfd, TRUE, FALSE);
3640   if (dump_file_header)
3641     dump_bfd_header (abfd);
3642   if (dump_private_headers)
3643     dump_bfd_private_header (abfd);
3644   if (dump_private_options != NULL)
3645     dump_target_specific (abfd);
3646   if (! dump_debugging_tags && ! suppress_bfd_header)
3647     putchar ('\n');
3648
3649   if (dump_symtab
3650       || dump_reloc_info
3651       || disassemble
3652       || dump_debugging
3653       || dump_dwarf_section_info)
3654     syms = slurp_symtab (abfd);
3655
3656   if (dump_section_headers)
3657     dump_headers (abfd);
3658
3659   if (dump_dynamic_symtab || dump_dynamic_reloc_info
3660       || (disassemble && bfd_get_dynamic_symtab_upper_bound (abfd) > 0))
3661     dynsyms = slurp_dynamic_symtab (abfd);
3662   if (disassemble)
3663     {
3664       synthcount = bfd_get_synthetic_symtab (abfd, symcount, syms,
3665                                              dynsymcount, dynsyms, &synthsyms);
3666       if (synthcount < 0)
3667         synthcount = 0;
3668     }
3669
3670   if (dump_symtab)
3671     dump_symbols (abfd, FALSE);
3672   if (dump_dynamic_symtab)
3673     dump_symbols (abfd, TRUE);
3674   if (dump_dwarf_section_info)
3675     dump_dwarf (abfd);
3676   if (dump_stab_section_info)
3677     dump_stabs (abfd);
3678   if (dump_reloc_info && ! disassemble)
3679     dump_relocs (abfd);
3680   if (dump_dynamic_reloc_info && ! disassemble)
3681     dump_dynamic_relocs (abfd);
3682   if (dump_section_contents)
3683     dump_data (abfd);
3684   if (disassemble)
3685     disassemble_data (abfd);
3686
3687   if (dump_debugging)
3688     {
3689       void *dhandle;
3690
3691       dhandle = read_debugging_info (abfd, syms, symcount, TRUE);
3692       if (dhandle != NULL)
3693         {
3694           if (!print_debugging_info (stdout, dhandle, abfd, syms,
3695                                      bfd_demangle,
3696                                      dump_debugging_tags ? TRUE : FALSE))
3697             {
3698               non_fatal (_("%s: printing debugging information failed"),
3699                          bfd_get_filename (abfd));
3700               exit_status = 1;
3701             }
3702
3703           free (dhandle);
3704         }
3705       /* PR 6483: If there was no STABS debug info in the file, try
3706          DWARF instead.  */
3707       else if (! dump_dwarf_section_info)
3708         {
3709           dwarf_select_sections_all ();
3710           dump_dwarf (abfd);
3711         }
3712     }
3713
3714   if (syms)
3715     {
3716       free (syms);
3717       syms = NULL;
3718     }
3719
3720   if (dynsyms)
3721     {
3722       free (dynsyms);
3723       dynsyms = NULL;
3724     }
3725
3726   if (synthsyms)
3727     {
3728       free (synthsyms);
3729       synthsyms = NULL;
3730     }
3731
3732   symcount = 0;
3733   dynsymcount = 0;
3734   synthcount = 0;
3735 }
3736
3737 static void
3738 display_object_bfd (bfd *abfd)
3739 {
3740   char **matching;
3741
3742   if (bfd_check_format_matches (abfd, bfd_object, &matching))
3743     {
3744       dump_bfd (abfd);
3745       return;
3746     }
3747
3748   if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
3749     {
3750       nonfatal (bfd_get_filename (abfd));
3751       list_matching_formats (matching);
3752       free (matching);
3753       return;
3754     }
3755
3756   if (bfd_get_error () != bfd_error_file_not_recognized)
3757     {
3758       nonfatal (bfd_get_filename (abfd));
3759       return;
3760     }
3761
3762   if (bfd_check_format_matches (abfd, bfd_core, &matching))
3763     {
3764       dump_bfd (abfd);
3765       return;
3766     }
3767
3768   nonfatal (bfd_get_filename (abfd));
3769
3770   if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
3771     {
3772       list_matching_formats (matching);
3773       free (matching);
3774     }
3775 }
3776
3777 static void
3778 display_any_bfd (bfd *file, int level)
3779 {
3780   /* Decompress sections unless dumping the section contents.  */
3781   if (!dump_section_contents)
3782     file->flags |= BFD_DECOMPRESS;
3783
3784   /* If the file is an archive, process all of its elements.  */
3785   if (bfd_check_format (file, bfd_archive))
3786     {
3787       bfd *arfile = NULL;
3788       bfd *last_arfile = NULL;
3789
3790       if (level == 0)
3791         printf (_("In archive %s:\n"), bfd_get_filename (file));
3792       else if (level > 100)
3793         {
3794           /* Prevent corrupted files from spinning us into an
3795              infinite loop.  100 is an arbitrary heuristic.  */
3796           fatal (_("Archive nesting is too deep"));
3797           return;
3798         }
3799       else
3800         printf (_("In nested archive %s:\n"), bfd_get_filename (file));
3801
3802       for (;;)
3803         {
3804           bfd_set_error (bfd_error_no_error);
3805
3806           arfile = bfd_openr_next_archived_file (file, arfile);
3807           if (arfile == NULL)
3808             {
3809               if (bfd_get_error () != bfd_error_no_more_archived_files)
3810                 nonfatal (bfd_get_filename (file));
3811               break;
3812             }
3813
3814           display_any_bfd (arfile, level + 1);
3815
3816           if (last_arfile != NULL)
3817             {
3818               bfd_close (last_arfile);
3819               /* PR 17512: file: ac585d01.  */
3820               if (arfile == last_arfile)
3821                 {
3822                   last_arfile = NULL;
3823                   break;
3824                 }
3825             }
3826           last_arfile = arfile;
3827         }
3828
3829       if (last_arfile != NULL)
3830         bfd_close (last_arfile);
3831     }
3832   else
3833     display_object_bfd (file);
3834 }
3835
3836 static void
3837 display_file (char *filename, char *target, bfd_boolean last_file)
3838 {
3839   bfd *file;
3840
3841   if (get_file_size (filename) < 1)
3842     {
3843       exit_status = 1;
3844       return;
3845     }
3846
3847   file = bfd_openr (filename, target);
3848   if (file == NULL)
3849     {
3850       nonfatal (filename);
3851       return;
3852     }
3853
3854   display_any_bfd (file, 0);
3855
3856   /* This is an optimization to improve the speed of objdump, especially when
3857      dumping a file with lots of associated debug informatiom.  Calling
3858      bfd_close on such a file can take a non-trivial amount of time as there
3859      are lots of lists to walk and buffers to free.  This is only really
3860      necessary however if we are about to load another file and we need the
3861      memory back.  Otherwise, if we are about to exit, then we can save (a lot
3862      of) time by only doing a quick close, and allowing the OS to reclaim the
3863      memory for us.  */
3864   if (! last_file)
3865     bfd_close (file);
3866   else
3867     bfd_close_all_done (file);
3868 }
3869 \f
3870 int
3871 main (int argc, char **argv)
3872 {
3873   int c;
3874   char *target = default_target;
3875   bfd_boolean seenflag = FALSE;
3876
3877 #if defined (HAVE_SETLOCALE)
3878 #if defined (HAVE_LC_MESSAGES)
3879   setlocale (LC_MESSAGES, "");
3880 #endif
3881   setlocale (LC_CTYPE, "");
3882 #endif
3883
3884   bindtextdomain (PACKAGE, LOCALEDIR);
3885   textdomain (PACKAGE);
3886
3887   program_name = *argv;
3888   xmalloc_set_program_name (program_name);
3889   bfd_set_error_program_name (program_name);
3890
3891   START_PROGRESS (program_name, 0);
3892
3893   expandargv (&argc, &argv);
3894
3895   if (bfd_init () != BFD_INIT_MAGIC)
3896     fatal (_("fatal error: libbfd ABI mismatch"));
3897   set_default_bfd_target ();
3898
3899   while ((c = getopt_long (argc, argv,
3900                            "pP:ib:m:M:VvCdDlfFaHhrRtTxsSI:j:wE:zgeGW::",
3901                            long_options, (int *) 0))
3902          != EOF)
3903     {
3904       switch (c)
3905         {
3906         case 0:
3907           break;                /* We've been given a long option.  */
3908         case 'm':
3909           machine = optarg;
3910           break;
3911         case 'M':
3912           {
3913             char *options;
3914             if (disassembler_options)
3915               /* Ignore potential memory leak for now.  */
3916               options = concat (disassembler_options, ",",
3917                                 optarg, (const char *) NULL);
3918             else
3919               options = optarg;
3920             disassembler_options = remove_whitespace_and_extra_commas (options);
3921           }
3922           break;
3923         case 'j':
3924           add_only (optarg);
3925           break;
3926         case 'F':
3927           display_file_offsets = TRUE;
3928           break;
3929         case 'l':
3930           with_line_numbers = TRUE;
3931           break;
3932         case 'b':
3933           target = optarg;
3934           break;
3935         case 'C':
3936           do_demangle = TRUE;
3937           if (optarg != NULL)
3938             {
3939               enum demangling_styles style;
3940
3941               style = cplus_demangle_name_to_style (optarg);
3942               if (style == unknown_demangling)
3943                 fatal (_("unknown demangling style `%s'"),
3944                        optarg);
3945
3946               cplus_demangle_set_style (style);
3947             }
3948           break;
3949         case OPTION_RECURSE_LIMIT:
3950           demangle_flags &= ~ DMGL_NO_RECURSE_LIMIT;
3951           break;
3952         case OPTION_NO_RECURSE_LIMIT:
3953           demangle_flags |= DMGL_NO_RECURSE_LIMIT;
3954           break;
3955         case 'w':
3956           do_wide = wide_output = TRUE;
3957           break;
3958         case OPTION_ADJUST_VMA:
3959           adjust_section_vma = parse_vma (optarg, "--adjust-vma");
3960           break;
3961         case OPTION_START_ADDRESS:
3962           start_address = parse_vma (optarg, "--start-address");
3963           if ((stop_address != (bfd_vma) -1) && stop_address <= start_address)
3964             fatal (_("error: the start address should be before the end address"));
3965           break;
3966         case OPTION_STOP_ADDRESS:
3967           stop_address = parse_vma (optarg, "--stop-address");
3968           if ((start_address != (bfd_vma) -1) && stop_address <= start_address)
3969             fatal (_("error: the stop address should be after the start address"));
3970           break;
3971         case OPTION_PREFIX:
3972           prefix = optarg;
3973           prefix_length = strlen (prefix);
3974           /* Remove an unnecessary trailing '/' */
3975           while (IS_DIR_SEPARATOR (prefix[prefix_length - 1]))
3976             prefix_length--;
3977           break;
3978         case OPTION_PREFIX_STRIP:
3979           prefix_strip = atoi (optarg);
3980           if (prefix_strip < 0)
3981             fatal (_("error: prefix strip must be non-negative"));
3982           break;
3983         case OPTION_INSN_WIDTH:
3984           insn_width = strtoul (optarg, NULL, 0);
3985           if (insn_width <= 0)
3986             fatal (_("error: instruction width must be positive"));
3987           break;
3988         case OPTION_INLINES:
3989           unwind_inlines = TRUE;
3990           break;
3991         case 'E':
3992           if (strcmp (optarg, "B") == 0)
3993             endian = BFD_ENDIAN_BIG;
3994           else if (strcmp (optarg, "L") == 0)
3995             endian = BFD_ENDIAN_LITTLE;
3996           else
3997             {
3998               nonfatal (_("unrecognized -E option"));
3999               usage (stderr, 1);
4000             }
4001           break;
4002         case OPTION_ENDIAN:
4003           if (strncmp (optarg, "big", strlen (optarg)) == 0)
4004             endian = BFD_ENDIAN_BIG;
4005           else if (strncmp (optarg, "little", strlen (optarg)) == 0)
4006             endian = BFD_ENDIAN_LITTLE;
4007           else
4008             {
4009               non_fatal (_("unrecognized --endian type `%s'"), optarg);
4010               exit_status = 1;
4011               usage (stderr, 1);
4012             }
4013           break;
4014
4015         case 'f':
4016           dump_file_header = TRUE;
4017           seenflag = TRUE;
4018           break;
4019         case 'i':
4020           formats_info = TRUE;
4021           seenflag = TRUE;
4022           break;
4023         case 'I':
4024           add_include_path (optarg);
4025           break;
4026         case 'p':
4027           dump_private_headers = TRUE;
4028           seenflag = TRUE;
4029           break;
4030         case 'P':
4031           dump_private_options = optarg;
4032           seenflag = TRUE;
4033           break;
4034         case 'x':
4035           dump_private_headers = TRUE;
4036           dump_symtab = TRUE;
4037           dump_reloc_info = TRUE;
4038           dump_file_header = TRUE;
4039           dump_ar_hdrs = TRUE;
4040           dump_section_headers = TRUE;
4041           seenflag = TRUE;
4042           break;
4043         case 't':
4044           dump_symtab = TRUE;
4045           seenflag = TRUE;
4046           break;
4047         case 'T':
4048           dump_dynamic_symtab = TRUE;
4049           seenflag = TRUE;
4050           break;
4051         case 'd':
4052           disassemble = TRUE;
4053           seenflag = TRUE;
4054           disasm_sym = optarg;
4055           break;
4056         case 'z':
4057           disassemble_zeroes = TRUE;
4058           break;
4059         case 'D':
4060           disassemble = TRUE;
4061           disassemble_all = TRUE;
4062           seenflag = TRUE;
4063           break;
4064         case 'S':
4065           disassemble = TRUE;
4066           with_source_code = TRUE;
4067           seenflag = TRUE;
4068           break;
4069         case 'g':
4070           dump_debugging = 1;
4071           seenflag = TRUE;
4072           break;
4073         case 'e':
4074           dump_debugging = 1;
4075           dump_debugging_tags = 1;
4076           do_demangle = TRUE;
4077           seenflag = TRUE;
4078           break;
4079         case 'W':
4080           dump_dwarf_section_info = TRUE;
4081           seenflag = TRUE;
4082           if (optarg)
4083             dwarf_select_sections_by_letters (optarg);
4084           else
4085             dwarf_select_sections_all ();
4086           break;
4087         case OPTION_DWARF:
4088           dump_dwarf_section_info = TRUE;
4089           seenflag = TRUE;
4090           if (optarg)
4091             dwarf_select_sections_by_names (optarg);
4092           else
4093             dwarf_select_sections_all ();
4094           break;
4095         case OPTION_DWARF_DEPTH:
4096           {
4097             char *cp;
4098             dwarf_cutoff_level = strtoul (optarg, & cp, 0);
4099           }
4100           break;
4101         case OPTION_DWARF_START:
4102           {
4103             char *cp;
4104             dwarf_start_die = strtoul (optarg, & cp, 0);
4105             suppress_bfd_header = 1;
4106           }
4107           break;
4108         case OPTION_DWARF_CHECK:
4109           dwarf_check = TRUE;
4110           break;
4111         case 'G':
4112           dump_stab_section_info = TRUE;
4113           seenflag = TRUE;
4114           break;
4115         case 's':
4116           dump_section_contents = TRUE;
4117           seenflag = TRUE;
4118           break;
4119         case 'r':
4120           dump_reloc_info = TRUE;
4121           seenflag = TRUE;
4122           break;
4123         case 'R':
4124           dump_dynamic_reloc_info = TRUE;
4125           seenflag = TRUE;
4126           break;
4127         case 'a':
4128           dump_ar_hdrs = TRUE;
4129           seenflag = TRUE;
4130           break;
4131         case 'h':
4132           dump_section_headers = TRUE;
4133           seenflag = TRUE;
4134           break;
4135         case 'v':
4136         case 'V':
4137           show_version = TRUE;
4138           seenflag = TRUE;
4139           break;
4140
4141         case 'H':
4142           usage (stdout, 0);
4143           /* No need to set seenflag or to break - usage() does not return.  */
4144         default:
4145           usage (stderr, 1);
4146         }
4147     }
4148
4149   if (show_version)
4150     print_version ("objdump");
4151
4152   if (!seenflag)
4153     usage (stderr, 2);
4154
4155   if (formats_info)
4156     exit_status = display_info ();
4157   else
4158     {
4159       if (optind == argc)
4160         display_file ("a.out", target, TRUE);
4161       else
4162         for (; optind < argc;)
4163           {
4164             display_file (argv[optind], target, optind == argc - 1);
4165             optind++;
4166           }
4167     }
4168
4169   free_only_list ();
4170
4171   END_PROGRESS (program_name);
4172
4173   return exit_status;
4174 }