1 /* objdump.c -- dump information about an object file.
2    Copyright (C) 1990-2020 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 "ctf-api.h"
60 #include "getopt.h"
61 #include "safe-ctype.h"
62 #include "dis-asm.h"
63 #include "libiberty.h"
64 #include "demangle.h"
65 #include "filenames.h"
66 #include "debug.h"
67 #include "budbg.h"
68 #include "objdump.h"
69 
70 #ifdef HAVE_MMAP
71 #include <sys/mman.h>
72 #endif
73 
74 /* Internal headers for the ELF .stab-dump code - sorry.  */
75 #define	BYTES_IN_WORD	32
76 #include "aout/aout64.h"
77 
78 /* Exit status.  */
79 static int exit_status = 0;
80 
81 static char *default_target = NULL;	/* Default at runtime.  */
82 
83 /* The following variables are set based on arguments passed on the
84    command line.  */
85 static int show_version = 0;		/* Show the version number.  */
86 static int dump_section_contents;	/* -s */
87 static int dump_section_headers;	/* -h */
88 static bfd_boolean dump_file_header;	/* -f */
89 static int dump_symtab;			/* -t */
90 static int dump_dynamic_symtab;		/* -T */
91 static int dump_reloc_info;		/* -r */
92 static int dump_dynamic_reloc_info;	/* -R */
93 static int dump_ar_hdrs;		/* -a */
94 static int dump_private_headers;	/* -p */
95 static char *dump_private_options;	/* -P */
96 static int prefix_addresses;		/* --prefix-addresses */
97 static int with_line_numbers;		/* -l */
98 static bfd_boolean with_source_code;	/* -S */
99 static int show_raw_insn;		/* --show-raw-insn */
100 static int dump_dwarf_section_info;	/* --dwarf */
101 static int dump_stab_section_info;	/* --stabs */
102 static int dump_ctf_section_info;       /* --ctf */
103 static char *dump_ctf_section_name;
104 static char *dump_ctf_parent_name;	/* --ctf-parent */
105 static int do_demangle;			/* -C, --demangle */
106 static bfd_boolean disassemble;		/* -d */
107 static bfd_boolean disassemble_all;	/* -D */
108 static int disassemble_zeroes;		/* --disassemble-zeroes */
109 static bfd_boolean formats_info;	/* -i */
110 static int wide_output;			/* -w */
111 static int insn_width;			/* --insn-width */
112 static bfd_vma start_address = (bfd_vma) -1; /* --start-address */
113 static bfd_vma stop_address = (bfd_vma) -1;  /* --stop-address */
114 static int dump_debugging;		/* --debugging */
115 static int dump_debugging_tags;		/* --debugging-tags */
116 static int suppress_bfd_header;
117 static int dump_special_syms = 0;	/* --special-syms */
118 static bfd_vma adjust_section_vma = 0;	/* --adjust-vma */
119 static int file_start_context = 0;      /* --file-start-context */
120 static bfd_boolean display_file_offsets;/* -F */
121 static const char *prefix;		/* --prefix */
122 static int prefix_strip;		/* --prefix-strip */
123 static size_t prefix_length;
124 static bfd_boolean unwind_inlines;	/* --inlines.  */
125 static const char * disasm_sym;		/* Disassembly start symbol.  */
126 static const char * source_comment;     /* --source_comment.  */
127 static bfd_boolean visualize_jumps = FALSE;          /* --visualize-jumps.  */
128 static bfd_boolean color_output = FALSE;             /* --visualize-jumps=color.  */
129 static bfd_boolean extended_color_output = FALSE;    /* --visualize-jumps=extended-color.  */
130 
131 static int demangle_flags = DMGL_ANSI | DMGL_PARAMS;
132 
133 /* A structure to record the sections mentioned in -j switches.  */
134 struct only
135 {
136   const char * name; /* The name of the section.  */
137   bfd_boolean  seen; /* A flag to indicate that the section has been found in one or more input files.  */
138   struct only * next; /* Pointer to the next structure in the list.  */
139 };
140 /* Pointer to an array of 'only' structures.
141    This pointer is NULL if the -j switch has not been used.  */
142 static struct only * only_list = NULL;
143 
144 /* Variables for handling include file path table.  */
145 static const char **include_paths;
146 static int include_path_count;
147 
148 /* Extra info to pass to the section disassembler and address printing
149    function.  */
150 struct objdump_disasm_info
151 {
152   bfd *              abfd;
153   bfd_boolean        require_sec;
154   arelent **         dynrelbuf;
155   long               dynrelcount;
156   disassembler_ftype disassemble_fn;
157   arelent *          reloc;
158   const char *       symbol;
159 };
160 
161 /* Architecture to disassemble for, or default if NULL.  */
162 static char *machine = NULL;
163 
164 /* Target specific options to the disassembler.  */
165 static char *disassembler_options = NULL;
166 
167 /* Endianness to disassemble for, or default if BFD_ENDIAN_UNKNOWN.  */
168 static enum bfd_endian endian = BFD_ENDIAN_UNKNOWN;
169 
170 /* The symbol table.  */
171 static asymbol **syms;
172 
173 /* Number of symbols in `syms'.  */
174 static long symcount = 0;
175 
176 /* The sorted symbol table.  */
177 static asymbol **sorted_syms;
178 
179 /* Number of symbols in `sorted_syms'.  */
180 static long sorted_symcount = 0;
181 
182 /* The dynamic symbol table.  */
183 static asymbol **dynsyms;
184 
185 /* The synthetic symbol table.  */
186 static asymbol *synthsyms;
187 static long synthcount = 0;
188 
189 /* Number of symbols in `dynsyms'.  */
190 static long dynsymcount = 0;
191 
192 static bfd_byte *stabs;
193 static bfd_size_type stab_size;
194 
195 static bfd_byte *strtab;
196 static bfd_size_type stabstr_size;
197 
198 /* Handlers for -P/--private.  */
199 static const struct objdump_private_desc * const objdump_private_vectors[] =
200   {
201     OBJDUMP_PRIVATE_VECTORS
202     NULL
203   };
204 
205 /* The list of detected jumps inside a function.  */
206 static struct jump_info *detected_jumps = NULL;
207 
208 static void usage (FILE *, int) ATTRIBUTE_NORETURN;
209 static void
210 usage (FILE *stream, int status)
211 {
212   fprintf (stream, _("Usage: %s <option(s)> <file(s)>\n"), program_name);
213   fprintf (stream, _(" Display information from object <file(s)>.\n"));
214   fprintf (stream, _(" At least one of the following switches must be given:\n"));
215   fprintf (stream, _("\
216   -a, --archive-headers    Display archive header information\n\
217   -f, --file-headers       Display the contents of the overall file header\n\
218   -p, --private-headers    Display object format specific file header contents\n\
219   -P, --private=OPT,OPT... Display object format specific contents\n\
220   -h, --[section-]headers  Display the contents of the section headers\n\
221   -x, --all-headers        Display the contents of all headers\n\
222   -d, --disassemble        Display assembler contents of executable sections\n\
223   -D, --disassemble-all    Display assembler contents of all sections\n\
224       --disassemble=<sym>  Display assembler contents from <sym>\n\
225   -S, --source             Intermix source code with disassembly\n\
226       --source-comment[=<txt>] Prefix lines of source code with <txt>\n\
227   -s, --full-contents      Display the full contents of all sections requested\n\
228   -g, --debugging          Display debug information in object file\n\
229   -e, --debugging-tags     Display debug information using ctags style\n\
230   -G, --stabs              Display (in raw form) any STABS info in the file\n\
231   -W[lLiaprmfFsoRtUuTgAckK] or\n\
232   --dwarf[=rawline,=decodedline,=info,=abbrev,=pubnames,=aranges,=macro,=frames,\n\
233           =frames-interp,=str,=loc,=Ranges,=pubtypes,\n\
234           =gdb_index,=trace_info,=trace_abbrev,=trace_aranges,\n\
235           =addr,=cu_index,=links,=follow-links]\n\
236                            Display DWARF info in the file\n\
237   --ctf=SECTION            Display CTF info from SECTION\n\
238   -t, --syms               Display the contents of the symbol table(s)\n\
239   -T, --dynamic-syms       Display the contents of the dynamic symbol table\n\
240   -r, --reloc              Display the relocation entries in the file\n\
241   -R, --dynamic-reloc      Display the dynamic relocation entries in the file\n\
242   @<file>                  Read options from <file>\n\
243   -v, --version            Display this program's version number\n\
244   -i, --info               List object formats and architectures supported\n\
245   -H, --help               Display this information\n\
246 "));
247   if (status != 2)
248     {
249       const struct objdump_private_desc * const *desc;
250 
251       fprintf (stream, _("\n The following switches are optional:\n"));
252       fprintf (stream, _("\
253   -b, --target=BFDNAME           Specify the target object format as BFDNAME\n\
254   -m, --architecture=MACHINE     Specify the target architecture as MACHINE\n\
255   -j, --section=NAME             Only display information for section NAME\n\
256   -M, --disassembler-options=OPT Pass text OPT on to the disassembler\n\
257   -EB --endian=big               Assume big endian format when disassembling\n\
258   -EL --endian=little            Assume little endian format when disassembling\n\
259       --file-start-context       Include context from start of file (with -S)\n\
260   -I, --include=DIR              Add DIR to search list for source files\n\
261   -l, --line-numbers             Include line numbers and filenames in output\n\
262   -F, --file-offsets             Include file offsets when displaying information\n\
263   -C, --demangle[=STYLE]         Decode mangled/processed symbol names\n\
264                                   The STYLE, if specified, can be `auto', `gnu',\n\
265                                   `lucid', `arm', `hp', `edg', `gnu-v3', `java'\n\
266                                   or `gnat'\n\
267       --recurse-limit            Enable a limit on recursion whilst demangling.  [Default]\n\
268       --no-recurse-limit         Disable a limit on recursion whilst demangling\n\
269   -w, --wide                     Format output for more than 80 columns\n\
270   -z, --disassemble-zeroes       Do not skip blocks of zeroes when disassembling\n\
271       --start-address=ADDR       Only process data whose address is >= ADDR\n\
272       --stop-address=ADDR        Only process data whose address is < ADDR\n\
273       --prefix-addresses         Print complete address alongside disassembly\n\
274       --[no-]show-raw-insn       Display hex alongside symbolic disassembly\n\
275       --insn-width=WIDTH         Display WIDTH bytes on a single line for -d\n\
276       --adjust-vma=OFFSET        Add OFFSET to all displayed section addresses\n\
277       --special-syms             Include special symbols in symbol dumps\n\
278       --inlines                  Print all inlines for source line (with -l)\n\
279       --prefix=PREFIX            Add PREFIX to absolute paths for -S\n\
280       --prefix-strip=LEVEL       Strip initial directory names for -S\n"));
281       fprintf (stream, _("\
282       --dwarf-depth=N        Do not display DIEs at depth N or greater\n\
283       --dwarf-start=N        Display DIEs starting with N, at the same depth\n\
284                              or deeper\n\
285       --dwarf-check          Make additional dwarf internal consistency checks.\
286       \n\
287       --ctf-parent=SECTION       Use SECTION as the CTF parent\n\
288       --visualize-jumps          Visualize jumps by drawing ASCII art lines\n\
289       --visualize-jumps=color    Use colors in the ASCII art\n\
290       --visualize-jumps=extended-color   Use extended 8-bit color codes\n\
291       --visualize-jumps=off      Disable jump visualization\n\n"));
292 
293       list_supported_targets (program_name, stream);
294       list_supported_architectures (program_name, stream);
295 
296       disassembler_usage (stream);
297 
298       if (objdump_private_vectors[0] != NULL)
299         {
300           fprintf (stream,
301                    _("\nOptions supported for -P/--private switch:\n"));
302           for (desc = objdump_private_vectors; *desc != NULL; desc++)
303             (*desc)->help (stream);
304         }
305     }
306   if (REPORT_BUGS_TO[0] && status == 0)
307     fprintf (stream, _("Report bugs to %s.\n"), REPORT_BUGS_TO);
308   exit (status);
309 }
310 
311 /* 150 isn't special; it's just an arbitrary non-ASCII char value.  */
312 enum option_values
313   {
314     OPTION_ENDIAN=150,
315     OPTION_START_ADDRESS,
316     OPTION_STOP_ADDRESS,
317     OPTION_DWARF,
318     OPTION_PREFIX,
319     OPTION_PREFIX_STRIP,
320     OPTION_INSN_WIDTH,
321     OPTION_ADJUST_VMA,
322     OPTION_DWARF_DEPTH,
323     OPTION_DWARF_CHECK,
324     OPTION_DWARF_START,
325     OPTION_RECURSE_LIMIT,
326     OPTION_NO_RECURSE_LIMIT,
327     OPTION_INLINES,
328     OPTION_SOURCE_COMMENT,
329     OPTION_CTF,
330     OPTION_CTF_PARENT,
331     OPTION_VISUALIZE_JUMPS
332   };
333 
334 static struct option long_options[]=
335 {
336   {"adjust-vma", required_argument, NULL, OPTION_ADJUST_VMA},
337   {"all-headers", no_argument, NULL, 'x'},
338   {"private-headers", no_argument, NULL, 'p'},
339   {"private", required_argument, NULL, 'P'},
340   {"architecture", required_argument, NULL, 'm'},
341   {"archive-headers", no_argument, NULL, 'a'},
342   {"debugging", no_argument, NULL, 'g'},
343   {"debugging-tags", no_argument, NULL, 'e'},
344   {"demangle", optional_argument, NULL, 'C'},
345   {"disassemble", optional_argument, NULL, 'd'},
346   {"disassemble-all", no_argument, NULL, 'D'},
347   {"disassembler-options", required_argument, NULL, 'M'},
348   {"disassemble-zeroes", no_argument, NULL, 'z'},
349   {"dynamic-reloc", no_argument, NULL, 'R'},
350   {"dynamic-syms", no_argument, NULL, 'T'},
351   {"endian", required_argument, NULL, OPTION_ENDIAN},
352   {"file-headers", no_argument, NULL, 'f'},
353   {"file-offsets", no_argument, NULL, 'F'},
354   {"file-start-context", no_argument, &file_start_context, 1},
355   {"full-contents", no_argument, NULL, 's'},
356   {"headers", no_argument, NULL, 'h'},
357   {"help", no_argument, NULL, 'H'},
358   {"info", no_argument, NULL, 'i'},
359   {"line-numbers", no_argument, NULL, 'l'},
360   {"no-show-raw-insn", no_argument, &show_raw_insn, -1},
361   {"prefix-addresses", no_argument, &prefix_addresses, 1},
362   {"recurse-limit", no_argument, NULL, OPTION_RECURSE_LIMIT},
363   {"recursion-limit", no_argument, NULL, OPTION_RECURSE_LIMIT},
364   {"no-recurse-limit", no_argument, NULL, OPTION_NO_RECURSE_LIMIT},
365   {"no-recursion-limit", no_argument, NULL, OPTION_NO_RECURSE_LIMIT},
366   {"reloc", no_argument, NULL, 'r'},
367   {"section", required_argument, NULL, 'j'},
368   {"section-headers", no_argument, NULL, 'h'},
369   {"show-raw-insn", no_argument, &show_raw_insn, 1},
370   {"source", no_argument, NULL, 'S'},
371   {"source-comment", optional_argument, NULL, OPTION_SOURCE_COMMENT},
372   {"special-syms", no_argument, &dump_special_syms, 1},
373   {"include", required_argument, NULL, 'I'},
374   {"dwarf", optional_argument, NULL, OPTION_DWARF},
375   {"ctf", required_argument, NULL, OPTION_CTF},
376   {"ctf-parent", required_argument, NULL, OPTION_CTF_PARENT},
377   {"stabs", no_argument, NULL, 'G'},
378   {"start-address", required_argument, NULL, OPTION_START_ADDRESS},
379   {"stop-address", required_argument, NULL, OPTION_STOP_ADDRESS},
380   {"syms", no_argument, NULL, 't'},
381   {"target", required_argument, NULL, 'b'},
382   {"version", no_argument, NULL, 'V'},
383   {"wide", no_argument, NULL, 'w'},
384   {"prefix", required_argument, NULL, OPTION_PREFIX},
385   {"prefix-strip", required_argument, NULL, OPTION_PREFIX_STRIP},
386   {"insn-width", required_argument, NULL, OPTION_INSN_WIDTH},
387   {"dwarf-depth", required_argument, 0, OPTION_DWARF_DEPTH},
388   {"dwarf-start", required_argument, 0, OPTION_DWARF_START},
389   {"dwarf-check", no_argument, 0, OPTION_DWARF_CHECK},
390   {"inlines", no_argument, 0, OPTION_INLINES},
391   {"visualize-jumps", optional_argument, 0, OPTION_VISUALIZE_JUMPS},
392   {0, no_argument, 0, 0}
393 };
394 
395 static void
396 nonfatal (const char *msg)
397 {
398   bfd_nonfatal (msg);
399   exit_status = 1;
400 }
401 
402 /* Returns a version of IN with any control characters
403    replaced by escape sequences.  Uses a static buffer
404    if necessary.  */
405 
406 static const char *
407 sanitize_string (const char * in)
408 {
409   static char *  buffer = NULL;
410   static size_t  buffer_len = 0;
411   const char *   original = in;
412   char *         out;
413 
414   /* Paranoia.  */
415   if (in == NULL)
416     return "";
417 
418   /* See if any conversion is necessary.  In the majority
419      of cases it will not be needed.  */
420   do
421     {
422       char c = *in++;
423 
424       if (c == 0)
425 	return original;
426 
427       if (ISCNTRL (c))
428 	break;
429     }
430   while (1);
431 
432   /* Copy the input, translating as needed.  */
433   in = original;
434   if (buffer_len < (strlen (in) * 2))
435     {
436       free ((void *) buffer);
437       buffer_len = strlen (in) * 2;
438       buffer = xmalloc (buffer_len + 1);
439     }
440 
441   out = buffer;
442   do
443     {
444       char c = *in++;
445 
446       if (c == 0)
447 	break;
448 
449       if (!ISCNTRL (c))
450 	*out++ = c;
451       else
452 	{
453 	  *out++ = '^';
454 	  *out++ = c + 0x40;
455 	}
456     }
457   while (1);
458 
459   *out = 0;
460   return buffer;
461 }
462 
463 
464 /* Returns TRUE if the specified section should be dumped.  */
465 
466 static bfd_boolean
467 process_section_p (asection * section)
468 {
469   struct only * only;
470 
471   if (only_list == NULL)
472     return TRUE;
473 
474   for (only = only_list; only; only = only->next)
475     if (strcmp (only->name, section->name) == 0)
476       {
477 	only->seen = TRUE;
478 	return TRUE;
479       }
480 
481   return FALSE;
482 }
483 
484 /* Add an entry to the 'only' list.  */
485 
486 static void
487 add_only (char * name)
488 {
489   struct only * only;
490 
491   /* First check to make sure that we do not
492      already have an entry for this name.  */
493   for (only = only_list; only; only = only->next)
494     if (strcmp (only->name, name) == 0)
495       return;
496 
497   only = xmalloc (sizeof * only);
498   only->name = name;
499   only->seen = FALSE;
500   only->next = only_list;
501   only_list = only;
502 }
503 
504 /* Release the memory used by the 'only' list.
505    PR 11225: Issue a warning message for unseen sections.
506    Only do this if none of the sections were seen.  This is mainly to support
507    tools like the GAS testsuite where an object file is dumped with a list of
508    generic section names known to be present in a range of different file
509    formats.  */
510 
511 static void
512 free_only_list (void)
513 {
514   bfd_boolean at_least_one_seen = FALSE;
515   struct only * only;
516   struct only * next;
517 
518   if (only_list == NULL)
519     return;
520 
521   for (only = only_list; only; only = only->next)
522     if (only->seen)
523       {
524 	at_least_one_seen = TRUE;
525 	break;
526       }
527 
528   for (only = only_list; only; only = next)
529     {
530       if (! at_least_one_seen)
531 	{
532 	  non_fatal (_("section '%s' mentioned in a -j option, "
533 		       "but not found in any input file"),
534 		     only->name);
535 	  exit_status = 1;
536 	}
537       next = only->next;
538       free (only);
539     }
540 }
541 
542 
543 static void
544 dump_section_header (bfd *abfd, asection *section, void *data)
545 {
546   char *comma = "";
547   unsigned int opb = bfd_octets_per_byte (abfd, section);
548   int longest_section_name = *((int *) data);
549 
550   /* Ignore linker created section.  See elfNN_ia64_object_p in
551      bfd/elfxx-ia64.c.  */
552   if (section->flags & SEC_LINKER_CREATED)
553     return;
554 
555   /* PR 10413: Skip sections that we are ignoring.  */
556   if (! process_section_p (section))
557     return;
558 
559   printf ("%3d %-*s %08lx  ", section->index, longest_section_name,
560 	  sanitize_string (bfd_section_name (section)),
561 	  (unsigned long) bfd_section_size (section) / opb);
562   bfd_printf_vma (abfd, bfd_section_vma (section));
563   printf ("  ");
564   bfd_printf_vma (abfd, section->lma);
565   printf ("  %08lx  2**%u", (unsigned long) section->filepos,
566 	  bfd_section_alignment (section));
567   if (! wide_output)
568     printf ("\n                ");
569   printf ("  ");
570 
571 #define PF(x, y) \
572   if (section->flags & x) { printf ("%s%s", comma, y); comma = ", "; }
573 
574   PF (SEC_HAS_CONTENTS, "CONTENTS");
575   PF (SEC_ALLOC, "ALLOC");
576   PF (SEC_CONSTRUCTOR, "CONSTRUCTOR");
577   PF (SEC_LOAD, "LOAD");
578   PF (SEC_RELOC, "RELOC");
579   PF (SEC_READONLY, "READONLY");
580   PF (SEC_CODE, "CODE");
581   PF (SEC_DATA, "DATA");
582   PF (SEC_ROM, "ROM");
583   PF (SEC_DEBUGGING, "DEBUGGING");
584   PF (SEC_NEVER_LOAD, "NEVER_LOAD");
585   PF (SEC_EXCLUDE, "EXCLUDE");
586   PF (SEC_SORT_ENTRIES, "SORT_ENTRIES");
587   if (bfd_get_arch (abfd) == bfd_arch_tic54x)
588     {
589       PF (SEC_TIC54X_BLOCK, "BLOCK");
590       PF (SEC_TIC54X_CLINK, "CLINK");
591     }
592   PF (SEC_SMALL_DATA, "SMALL_DATA");
593   if (bfd_get_flavour (abfd) == bfd_target_coff_flavour)
594     {
595       PF (SEC_COFF_SHARED, "SHARED");
596       PF (SEC_COFF_NOREAD, "NOREAD");
597     }
598   else if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
599     {
600       PF (SEC_ELF_OCTETS, "OCTETS");
601       PF (SEC_ELF_PURECODE, "PURECODE");
602     }
603   PF (SEC_THREAD_LOCAL, "THREAD_LOCAL");
604   PF (SEC_GROUP, "GROUP");
605   if (bfd_get_arch (abfd) == bfd_arch_mep)
606     {
607       PF (SEC_MEP_VLIW, "VLIW");
608     }
609 
610   if ((section->flags & SEC_LINK_ONCE) != 0)
611     {
612       const char *ls;
613       struct coff_comdat_info *comdat;
614 
615       switch (section->flags & SEC_LINK_DUPLICATES)
616 	{
617 	default:
618 	  abort ();
619 	case SEC_LINK_DUPLICATES_DISCARD:
620 	  ls = "LINK_ONCE_DISCARD";
621 	  break;
622 	case SEC_LINK_DUPLICATES_ONE_ONLY:
623 	  ls = "LINK_ONCE_ONE_ONLY";
624 	  break;
625 	case SEC_LINK_DUPLICATES_SAME_SIZE:
626 	  ls = "LINK_ONCE_SAME_SIZE";
627 	  break;
628 	case SEC_LINK_DUPLICATES_SAME_CONTENTS:
629 	  ls = "LINK_ONCE_SAME_CONTENTS";
630 	  break;
631 	}
632       printf ("%s%s", comma, ls);
633 
634       comdat = bfd_coff_get_comdat_section (abfd, section);
635       if (comdat != NULL)
636 	printf (" (COMDAT %s %ld)", comdat->name, comdat->symbol);
637 
638       comma = ", ";
639     }
640 
641   printf ("\n");
642 #undef PF
643 }
644 
645 /* Called on each SECTION in ABFD, update the int variable pointed to by
646    DATA which contains the string length of the longest section name.  */
647 
648 static void
649 find_longest_section_name (bfd *abfd ATTRIBUTE_UNUSED,
650 			   asection *section, void *data)
651 {
652   int *longest_so_far = (int *) data;
653   const char *name;
654   int len;
655 
656   /* Ignore linker created section.  */
657   if (section->flags & SEC_LINKER_CREATED)
658     return;
659 
660   /* Skip sections that we are ignoring.  */
661   if (! process_section_p (section))
662     return;
663 
664   name = bfd_section_name (section);
665   len = (int) strlen (name);
666   if (len > *longest_so_far)
667     *longest_so_far = len;
668 }
669 
670 static void
671 dump_headers (bfd *abfd)
672 {
673   /* The default width of 13 is just an arbitrary choice.  */
674   int max_section_name_length = 13;
675   int bfd_vma_width;
676 
677 #ifndef BFD64
678   bfd_vma_width = 10;
679 #else
680   /* With BFD64, non-ELF returns -1 and wants always 64 bit addresses.  */
681   if (bfd_get_arch_size (abfd) == 32)
682     bfd_vma_width = 10;
683   else
684     bfd_vma_width = 18;
685 #endif
686 
687   printf (_("Sections:\n"));
688 
689   if (wide_output)
690     bfd_map_over_sections (abfd, find_longest_section_name,
691                            &max_section_name_length);
692 
693   printf (_("Idx %-*s Size      %-*s%-*sFile off  Algn"),
694 	  max_section_name_length, "Name",
695 	  bfd_vma_width, "VMA",
696 	  bfd_vma_width, "LMA");
697 
698   if (wide_output)
699     printf (_("  Flags"));
700   printf ("\n");
701 
702   bfd_map_over_sections (abfd, dump_section_header,
703                          &max_section_name_length);
704 }
705 
706 static asymbol **
707 slurp_symtab (bfd *abfd)
708 {
709   asymbol **sy = NULL;
710   long storage;
711 
712   if (!(bfd_get_file_flags (abfd) & HAS_SYMS))
713     {
714       symcount = 0;
715       return NULL;
716     }
717 
718   storage = bfd_get_symtab_upper_bound (abfd);
719   if (storage < 0)
720     {
721       non_fatal (_("failed to read symbol table from: %s"), bfd_get_filename (abfd));
722       bfd_fatal (_("error message was"));
723     }
724   if (storage)
725     {
726       off_t filesize = bfd_get_file_size (abfd);
727 
728       /* qv PR 24707.  */
729       if (filesize > 0
730 	  && filesize < storage
731 	  /* The MMO file format supports its own special compression
732 	     technique, so its sections can be larger than the file size.  */
733 	  && bfd_get_flavour (abfd) != bfd_target_mmo_flavour)
734 	{
735 	  bfd_nonfatal_message (bfd_get_filename (abfd), abfd, NULL,
736 				_("error: symbol table size (%#lx) is larger than filesize (%#lx)"),
737 			storage, (long) filesize);
738 	  exit_status = 1;
739 	  symcount = 0;
740 	  return NULL;
741 	}
742 
743       sy = (asymbol **) xmalloc (storage);
744     }
745 
746   symcount = bfd_canonicalize_symtab (abfd, sy);
747   if (symcount < 0)
748     bfd_fatal (bfd_get_filename (abfd));
749   return sy;
750 }
751 
752 /* Read in the dynamic symbols.  */
753 
754 static asymbol **
755 slurp_dynamic_symtab (bfd *abfd)
756 {
757   asymbol **sy = NULL;
758   long storage;
759 
760   storage = bfd_get_dynamic_symtab_upper_bound (abfd);
761   if (storage < 0)
762     {
763       if (!(bfd_get_file_flags (abfd) & DYNAMIC))
764 	{
765 	  non_fatal (_("%s: not a dynamic object"), bfd_get_filename (abfd));
766 	  exit_status = 1;
767 	  dynsymcount = 0;
768 	  return NULL;
769 	}
770 
771       bfd_fatal (bfd_get_filename (abfd));
772     }
773   if (storage)
774     sy = (asymbol **) xmalloc (storage);
775 
776   dynsymcount = bfd_canonicalize_dynamic_symtab (abfd, sy);
777   if (dynsymcount < 0)
778     bfd_fatal (bfd_get_filename (abfd));
779   return sy;
780 }
781 
782 /* Some symbol names are significant and should be kept in the
783    table of sorted symbol names, even if they are marked as
784    debugging/section symbols.  */
785 
786 static bfd_boolean
787 is_significant_symbol_name (const char * name)
788 {
789   return strncmp (name, ".plt", 4) == 0 || strcmp (name, ".got") == 0;
790 }
791 
792 /* Filter out (in place) symbols that are useless for disassembly.
793    COUNT is the number of elements in SYMBOLS.
794    Return the number of useful symbols.  */
795 
796 static long
797 remove_useless_symbols (asymbol **symbols, long count)
798 {
799   asymbol **in_ptr = symbols, **out_ptr = symbols;
800 
801   while (--count >= 0)
802     {
803       asymbol *sym = *in_ptr++;
804 
805       if (sym->name == NULL || sym->name[0] == '\0')
806 	continue;
807       if ((sym->flags & (BSF_DEBUGGING | BSF_SECTION_SYM))
808 	  && ! is_significant_symbol_name (sym->name))
809 	continue;
810       if (bfd_is_und_section (sym->section)
811 	  || bfd_is_com_section (sym->section))
812 	continue;
813 
814       *out_ptr++ = sym;
815     }
816   return out_ptr - symbols;
817 }
818 
819 static const asection *compare_section;
820 
821 /* Sort symbols into value order.  */
822 
823 static int
824 compare_symbols (const void *ap, const void *bp)
825 {
826   const asymbol *a = * (const asymbol **) ap;
827   const asymbol *b = * (const asymbol **) bp;
828   const char *an;
829   const char *bn;
830   size_t anl;
831   size_t bnl;
832   bfd_boolean as, af, bs, bf;
833   flagword aflags;
834   flagword bflags;
835 
836   if (bfd_asymbol_value (a) > bfd_asymbol_value (b))
837     return 1;
838   else if (bfd_asymbol_value (a) < bfd_asymbol_value (b))
839     return -1;
840 
841   /* Prefer symbols from the section currently being disassembled.
842      Don't sort symbols from other sections by section, since there
843      isn't much reason to prefer one section over another otherwise.
844      See sym_ok comment for why we compare by section name.  */
845   as = strcmp (compare_section->name, a->section->name) == 0;
846   bs = strcmp (compare_section->name, b->section->name) == 0;
847   if (as && !bs)
848     return -1;
849   if (!as && bs)
850     return 1;
851 
852   an = bfd_asymbol_name (a);
853   bn = bfd_asymbol_name (b);
854   anl = strlen (an);
855   bnl = strlen (bn);
856 
857   /* The symbols gnu_compiled and gcc2_compiled convey no real
858      information, so put them after other symbols with the same value.  */
859   af = (strstr (an, "gnu_compiled") != NULL
860 	|| strstr (an, "gcc2_compiled") != NULL);
861   bf = (strstr (bn, "gnu_compiled") != NULL
862 	|| strstr (bn, "gcc2_compiled") != NULL);
863 
864   if (af && ! bf)
865     return 1;
866   if (! af && bf)
867     return -1;
868 
869   /* We use a heuristic for the file name, to try to sort it after
870      more useful symbols.  It may not work on non Unix systems, but it
871      doesn't really matter; the only difference is precisely which
872      symbol names get printed.  */
873 
874 #define file_symbol(s, sn, snl)			\
875   (((s)->flags & BSF_FILE) != 0			\
876    || ((snl) > 2				\
877        && (sn)[(snl) - 2] == '.'		\
878        && ((sn)[(snl) - 1] == 'o'		\
879 	   || (sn)[(snl) - 1] == 'a')))
880 
881   af = file_symbol (a, an, anl);
882   bf = file_symbol (b, bn, bnl);
883 
884   if (af && ! bf)
885     return 1;
886   if (! af && bf)
887     return -1;
888 
889   /* Sort function and object symbols before global symbols before
890      local symbols before section symbols before debugging symbols.  */
891 
892   aflags = a->flags;
893   bflags = b->flags;
894 
895   if ((aflags & BSF_DEBUGGING) != (bflags & BSF_DEBUGGING))
896     {
897       if ((aflags & BSF_DEBUGGING) != 0)
898 	return 1;
899       else
900 	return -1;
901     }
902   if ((aflags & BSF_SECTION_SYM) != (bflags & BSF_SECTION_SYM))
903     {
904       if ((aflags & BSF_SECTION_SYM) != 0)
905 	return 1;
906       else
907 	return -1;
908     }
909   if ((aflags & BSF_FUNCTION) != (bflags & BSF_FUNCTION))
910     {
911       if ((aflags & BSF_FUNCTION) != 0)
912 	return -1;
913       else
914 	return 1;
915     }
916   if ((aflags & BSF_OBJECT) != (bflags & BSF_OBJECT))
917     {
918       if ((aflags & BSF_OBJECT) != 0)
919 	return -1;
920       else
921 	return 1;
922     }
923   if ((aflags & BSF_LOCAL) != (bflags & BSF_LOCAL))
924     {
925       if ((aflags & BSF_LOCAL) != 0)
926 	return 1;
927       else
928 	return -1;
929     }
930   if ((aflags & BSF_GLOBAL) != (bflags & BSF_GLOBAL))
931     {
932       if ((aflags & BSF_GLOBAL) != 0)
933 	return -1;
934       else
935 	return 1;
936     }
937 
938   if (bfd_get_flavour (bfd_asymbol_bfd (a)) == bfd_target_elf_flavour
939       && bfd_get_flavour (bfd_asymbol_bfd (b)) == bfd_target_elf_flavour)
940     {
941       bfd_vma asz, bsz;
942 
943       asz = 0;
944       if ((a->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) == 0)
945 	asz = ((elf_symbol_type *) a)->internal_elf_sym.st_size;
946       bsz = 0;
947       if ((b->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) == 0)
948 	bsz = ((elf_symbol_type *) b)->internal_elf_sym.st_size;
949       if (asz != bsz)
950 	return asz > bsz ? -1 : 1;
951     }
952 
953   /* Symbols that start with '.' might be section names, so sort them
954      after symbols that don't start with '.'.  */
955   if (an[0] == '.' && bn[0] != '.')
956     return 1;
957   if (an[0] != '.' && bn[0] == '.')
958     return -1;
959 
960   /* Finally, if we can't distinguish them in any other way, try to
961      get consistent results by sorting the symbols by name.  */
962   return strcmp (an, bn);
963 }
964 
965 /* Sort relocs into address order.  */
966 
967 static int
968 compare_relocs (const void *ap, const void *bp)
969 {
970   const arelent *a = * (const arelent **) ap;
971   const arelent *b = * (const arelent **) bp;
972 
973   if (a->address > b->address)
974     return 1;
975   else if (a->address < b->address)
976     return -1;
977 
978   /* So that associated relocations tied to the same address show up
979      in the correct order, we don't do any further sorting.  */
980   if (a > b)
981     return 1;
982   else if (a < b)
983     return -1;
984   else
985     return 0;
986 }
987 
988 /* Print an address (VMA) to the output stream in INFO.
989    If SKIP_ZEROES is TRUE, omit leading zeroes.  */
990 
991 static void
992 objdump_print_value (bfd_vma vma, struct disassemble_info *inf,
993 		     bfd_boolean skip_zeroes)
994 {
995   char buf[30];
996   char *p;
997   struct objdump_disasm_info *aux;
998 
999   aux = (struct objdump_disasm_info *) inf->application_data;
1000   bfd_sprintf_vma (aux->abfd, buf, vma);
1001   if (! skip_zeroes)
1002     p = buf;
1003   else
1004     {
1005       for (p = buf; *p == '0'; ++p)
1006 	;
1007       if (*p == '\0')
1008 	--p;
1009     }
1010   (*inf->fprintf_func) (inf->stream, "%s", p);
1011 }
1012 
1013 /* Print the name of a symbol.  */
1014 
1015 static void
1016 objdump_print_symname (bfd *abfd, struct disassemble_info *inf,
1017 		       asymbol *sym)
1018 {
1019   char *alloc;
1020   const char *name, *version_string = NULL;
1021   bfd_boolean hidden = FALSE;
1022 
1023   alloc = NULL;
1024   name = bfd_asymbol_name (sym);
1025   if (do_demangle && name[0] != '\0')
1026     {
1027       /* Demangle the name.  */
1028       alloc = bfd_demangle (abfd, name, demangle_flags);
1029       if (alloc != NULL)
1030 	name = alloc;
1031     }
1032 
1033   if ((sym->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) == 0)
1034     version_string = bfd_get_symbol_version_string (abfd, sym, &hidden);
1035 
1036   if (bfd_is_und_section (bfd_asymbol_section (sym)))
1037     hidden = TRUE;
1038 
1039   name = sanitize_string (name);
1040 
1041   if (inf != NULL)
1042     {
1043       (*inf->fprintf_func) (inf->stream, "%s", name);
1044       if (version_string && *version_string != '\0')
1045 	(*inf->fprintf_func) (inf->stream, hidden ? "@%s" : "@@%s",
1046 			      version_string);
1047     }
1048   else
1049     {
1050       printf ("%s", name);
1051       if (version_string && *version_string != '\0')
1052 	printf (hidden ? "@%s" : "@@%s", version_string);
1053     }
1054 
1055   if (alloc != NULL)
1056     free (alloc);
1057 }
1058 
1059 static inline bfd_boolean
1060 sym_ok (bfd_boolean               want_section,
1061 	bfd *                     abfd ATTRIBUTE_UNUSED,
1062 	long                      place,
1063 	asection *                sec,
1064 	struct disassemble_info * inf)
1065 {
1066   if (want_section)
1067     {
1068       /* Note - we cannot just compare section pointers because they could
1069 	 be different, but the same...  Ie the symbol that we are trying to
1070 	 find could have come from a separate debug info file.  Under such
1071 	 circumstances the symbol will be associated with a section in the
1072 	 debug info file, whilst the section we want is in a normal file.
1073 	 So the section pointers will be different, but the section names
1074 	 will be the same.  */
1075       if (strcmp (bfd_section_name (sorted_syms[place]->section),
1076 		  bfd_section_name (sec)) != 0)
1077 	return FALSE;
1078     }
1079 
1080   return inf->symbol_is_valid (sorted_syms[place], inf);
1081 }
1082 
1083 /* Locate a symbol given a bfd and a section (from INFO->application_data),
1084    and a VMA.  If INFO->application_data->require_sec is TRUE, then always
1085    require the symbol to be in the section.  Returns NULL if there is no
1086    suitable symbol.  If PLACE is not NULL, then *PLACE is set to the index
1087    of the symbol in sorted_syms.  */
1088 
1089 static asymbol *
1090 find_symbol_for_address (bfd_vma vma,
1091 			 struct disassemble_info *inf,
1092 			 long *place)
1093 {
1094   /* @@ Would it speed things up to cache the last two symbols returned,
1095      and maybe their address ranges?  For many processors, only one memory
1096      operand can be present at a time, so the 2-entry cache wouldn't be
1097      constantly churned by code doing heavy memory accesses.  */
1098 
1099   /* Indices in `sorted_syms'.  */
1100   long min = 0;
1101   long max_count = sorted_symcount;
1102   long thisplace;
1103   struct objdump_disasm_info *aux;
1104   bfd *abfd;
1105   asection *sec;
1106   unsigned int opb;
1107   bfd_boolean want_section;
1108   long rel_count;
1109 
1110   if (sorted_symcount < 1)
1111     return NULL;
1112 
1113   aux = (struct objdump_disasm_info *) inf->application_data;
1114   abfd = aux->abfd;
1115   sec = inf->section;
1116   opb = inf->octets_per_byte;
1117 
1118   /* Perform a binary search looking for the closest symbol to the
1119      required value.  We are searching the range (min, max_count].  */
1120   while (min + 1 < max_count)
1121     {
1122       asymbol *sym;
1123 
1124       thisplace = (max_count + min) / 2;
1125       sym = sorted_syms[thisplace];
1126 
1127       if (bfd_asymbol_value (sym) > vma)
1128 	max_count = thisplace;
1129       else if (bfd_asymbol_value (sym) < vma)
1130 	min = thisplace;
1131       else
1132 	{
1133 	  min = thisplace;
1134 	  break;
1135 	}
1136     }
1137 
1138   /* The symbol we want is now in min, the low end of the range we
1139      were searching.  If there are several symbols with the same
1140      value, we want the first one.  */
1141   thisplace = min;
1142   while (thisplace > 0
1143 	 && (bfd_asymbol_value (sorted_syms[thisplace])
1144 	     == bfd_asymbol_value (sorted_syms[thisplace - 1])))
1145     --thisplace;
1146 
1147   /* Prefer a symbol in the current section if we have multple symbols
1148      with the same value, as can occur with overlays or zero size
1149      sections.  */
1150   min = thisplace;
1151   while (min < max_count
1152 	 && (bfd_asymbol_value (sorted_syms[min])
1153 	     == bfd_asymbol_value (sorted_syms[thisplace])))
1154     {
1155       if (sym_ok (TRUE, abfd, min, sec, inf))
1156 	{
1157 	  thisplace = min;
1158 
1159 	  if (place != NULL)
1160 	    *place = thisplace;
1161 
1162 	  return sorted_syms[thisplace];
1163 	}
1164       ++min;
1165     }
1166 
1167   /* If the file is relocatable, and the symbol could be from this
1168      section, prefer a symbol from this section over symbols from
1169      others, even if the other symbol's value might be closer.
1170 
1171      Note that this may be wrong for some symbol references if the
1172      sections have overlapping memory ranges, but in that case there's
1173      no way to tell what's desired without looking at the relocation
1174      table.
1175 
1176      Also give the target a chance to reject symbols.  */
1177   want_section = (aux->require_sec
1178 		  || ((abfd->flags & HAS_RELOC) != 0
1179 		      && vma >= bfd_section_vma (sec)
1180 		      && vma < (bfd_section_vma (sec)
1181 				+ bfd_section_size (sec) / opb)));
1182 
1183   if (! sym_ok (want_section, abfd, thisplace, sec, inf))
1184     {
1185       long i;
1186       long newplace = sorted_symcount;
1187 
1188       for (i = min - 1; i >= 0; i--)
1189 	{
1190 	  if (sym_ok (want_section, abfd, i, sec, inf))
1191 	    {
1192 	      if (newplace == sorted_symcount)
1193 		newplace = i;
1194 
1195 	      if (bfd_asymbol_value (sorted_syms[i])
1196 		  != bfd_asymbol_value (sorted_syms[newplace]))
1197 		break;
1198 
1199 	      /* Remember this symbol and keep searching until we reach
1200 		 an earlier address.  */
1201 	      newplace = i;
1202 	    }
1203 	}
1204 
1205       if (newplace != sorted_symcount)
1206 	thisplace = newplace;
1207       else
1208 	{
1209 	  /* We didn't find a good symbol with a smaller value.
1210 	     Look for one with a larger value.  */
1211 	  for (i = thisplace + 1; i < sorted_symcount; i++)
1212 	    {
1213 	      if (sym_ok (want_section, abfd, i, sec, inf))
1214 		{
1215 		  thisplace = i;
1216 		  break;
1217 		}
1218 	    }
1219 	}
1220 
1221       if (! sym_ok (want_section, abfd, thisplace, sec, inf))
1222 	/* There is no suitable symbol.  */
1223 	return NULL;
1224     }
1225 
1226   /* If we have not found an exact match for the specified address
1227      and we have dynamic relocations available, then we can produce
1228      a better result by matching a relocation to the address and
1229      using the symbol associated with that relocation.  */
1230   rel_count = aux->dynrelcount;
1231   if (!want_section
1232       && sorted_syms[thisplace]->value != vma
1233       && rel_count > 0
1234       && aux->dynrelbuf != NULL
1235       && aux->dynrelbuf[0]->address <= vma
1236       && aux->dynrelbuf[rel_count - 1]->address >= vma
1237       /* If we have matched a synthetic symbol, then stick with that.  */
1238       && (sorted_syms[thisplace]->flags & BSF_SYNTHETIC) == 0)
1239     {
1240       arelent **  rel_low;
1241       arelent **  rel_high;
1242 
1243       rel_low = aux->dynrelbuf;
1244       rel_high = rel_low + rel_count - 1;
1245       while (rel_low <= rel_high)
1246 	{
1247 	  arelent **rel_mid = &rel_low[(rel_high - rel_low) / 2];
1248 	  arelent * rel = *rel_mid;
1249 
1250 	  if (rel->address == vma)
1251 	    {
1252 	      /* Absolute relocations do not provide a more helpful
1253 	         symbolic address.  Find a non-absolute relocation
1254 		 with the same address.  */
1255 	      arelent **rel_vma = rel_mid;
1256 	      for (rel_mid--;
1257 		   rel_mid >= rel_low && rel_mid[0]->address == vma;
1258 		   rel_mid--)
1259 		rel_vma = rel_mid;
1260 
1261 	      for (; rel_vma <= rel_high && rel_vma[0]->address == vma;
1262 		   rel_vma++)
1263 		{
1264 		  rel = *rel_vma;
1265 		  if (rel->sym_ptr_ptr != NULL
1266 		      && ! bfd_is_abs_section ((* rel->sym_ptr_ptr)->section))
1267 		    {
1268 		      if (place != NULL)
1269 			* place = thisplace;
1270 		      return * rel->sym_ptr_ptr;
1271 		    }
1272 		}
1273 	      break;
1274 	    }
1275 
1276 	  if (vma < rel->address)
1277 	    rel_high = rel_mid;
1278 	  else if (vma >= rel_mid[1]->address)
1279 	    rel_low = rel_mid + 1;
1280 	  else
1281 	    break;
1282 	}
1283     }
1284 
1285   if (place != NULL)
1286     *place = thisplace;
1287 
1288   return sorted_syms[thisplace];
1289 }
1290 
1291 /* Print an address and the offset to the nearest symbol.  */
1292 
1293 static void
1294 objdump_print_addr_with_sym (bfd *abfd, asection *sec, asymbol *sym,
1295 			     bfd_vma vma, struct disassemble_info *inf,
1296 			     bfd_boolean skip_zeroes)
1297 {
1298   objdump_print_value (vma, inf, skip_zeroes);
1299 
1300   if (sym == NULL)
1301     {
1302       bfd_vma secaddr;
1303 
1304       (*inf->fprintf_func) (inf->stream, " <%s",
1305 			    sanitize_string (bfd_section_name (sec)));
1306       secaddr = bfd_section_vma (sec);
1307       if (vma < secaddr)
1308 	{
1309 	  (*inf->fprintf_func) (inf->stream, "-0x");
1310 	  objdump_print_value (secaddr - vma, inf, TRUE);
1311 	}
1312       else if (vma > secaddr)
1313 	{
1314 	  (*inf->fprintf_func) (inf->stream, "+0x");
1315 	  objdump_print_value (vma - secaddr, inf, TRUE);
1316 	}
1317       (*inf->fprintf_func) (inf->stream, ">");
1318     }
1319   else
1320     {
1321       (*inf->fprintf_func) (inf->stream, " <");
1322 
1323       objdump_print_symname (abfd, inf, sym);
1324 
1325       if (bfd_asymbol_value (sym) == vma)
1326 	;
1327       /* Undefined symbols in an executables and dynamic objects do not have
1328 	 a value associated with them, so it does not make sense to display
1329 	 an offset relative to them.  Normally we would not be provided with
1330 	 this kind of symbol, but the target backend might choose to do so,
1331 	 and the code in find_symbol_for_address might return an as yet
1332 	 unresolved symbol associated with a dynamic reloc.  */
1333       else if ((bfd_get_file_flags (abfd) & (EXEC_P | DYNAMIC))
1334 	       && bfd_is_und_section (sym->section))
1335 	;
1336       else if (bfd_asymbol_value (sym) > vma)
1337 	{
1338 	  (*inf->fprintf_func) (inf->stream, "-0x");
1339 	  objdump_print_value (bfd_asymbol_value (sym) - vma, inf, TRUE);
1340 	}
1341       else if (vma > bfd_asymbol_value (sym))
1342 	{
1343 	  (*inf->fprintf_func) (inf->stream, "+0x");
1344 	  objdump_print_value (vma - bfd_asymbol_value (sym), inf, TRUE);
1345 	}
1346 
1347       (*inf->fprintf_func) (inf->stream, ">");
1348     }
1349 
1350   if (display_file_offsets)
1351     inf->fprintf_func (inf->stream, _(" (File Offset: 0x%lx)"),
1352 			(long int)(sec->filepos + (vma - sec->vma)));
1353 }
1354 
1355 /* Print an address (VMA), symbolically if possible.
1356    If SKIP_ZEROES is TRUE, don't output leading zeroes.  */
1357 
1358 static void
1359 objdump_print_addr (bfd_vma vma,
1360 		    struct disassemble_info *inf,
1361 		    bfd_boolean skip_zeroes)
1362 {
1363   struct objdump_disasm_info *aux;
1364   asymbol *sym = NULL;
1365   bfd_boolean skip_find = FALSE;
1366 
1367   aux = (struct objdump_disasm_info *) inf->application_data;
1368 
1369   if (sorted_symcount < 1)
1370     {
1371       (*inf->fprintf_func) (inf->stream, "0x");
1372       objdump_print_value (vma, inf, skip_zeroes);
1373 
1374       if (display_file_offsets)
1375 	inf->fprintf_func (inf->stream, _(" (File Offset: 0x%lx)"),
1376 			   (long int) (inf->section->filepos
1377 				       + (vma - inf->section->vma)));
1378       return;
1379     }
1380 
1381   if (aux->reloc != NULL
1382       && aux->reloc->sym_ptr_ptr != NULL
1383       && * aux->reloc->sym_ptr_ptr != NULL)
1384     {
1385       sym = * aux->reloc->sym_ptr_ptr;
1386 
1387       /* Adjust the vma to the reloc.  */
1388       vma += bfd_asymbol_value (sym);
1389 
1390       if (bfd_is_und_section (bfd_asymbol_section (sym)))
1391 	skip_find = TRUE;
1392     }
1393 
1394   if (!skip_find)
1395     sym = find_symbol_for_address (vma, inf, NULL);
1396 
1397   objdump_print_addr_with_sym (aux->abfd, inf->section, sym, vma, inf,
1398 			       skip_zeroes);
1399 }
1400 
1401 /* Print VMA to INFO.  This function is passed to the disassembler
1402    routine.  */
1403 
1404 static void
1405 objdump_print_address (bfd_vma vma, struct disassemble_info *inf)
1406 {
1407   objdump_print_addr (vma, inf, ! prefix_addresses);
1408 }
1409 
1410 /* Determine if the given address has a symbol associated with it.  */
1411 
1412 static int
1413 objdump_symbol_at_address (bfd_vma vma, struct disassemble_info * inf)
1414 {
1415   asymbol * sym;
1416 
1417   sym = find_symbol_for_address (vma, inf, NULL);
1418 
1419   return (sym != NULL && (bfd_asymbol_value (sym) == vma));
1420 }
1421 
1422 /* Hold the last function name and the last line number we displayed
1423    in a disassembly.  */
1424 
1425 static char *prev_functionname;
1426 static unsigned int prev_line;
1427 static unsigned int prev_discriminator;
1428 
1429 /* We keep a list of all files that we have seen when doing a
1430    disassembly with source, so that we know how much of the file to
1431    display.  This can be important for inlined functions.  */
1432 
1433 struct print_file_list
1434 {
1435   struct print_file_list *next;
1436   const char *filename;
1437   const char *modname;
1438   const char *map;
1439   size_t mapsize;
1440   const char **linemap;
1441   unsigned maxline;
1442   unsigned last_line;
1443   unsigned max_printed;
1444   int first;
1445 };
1446 
1447 static struct print_file_list *print_files;
1448 
1449 /* The number of preceding context lines to show when we start
1450    displaying a file for the first time.  */
1451 
1452 #define SHOW_PRECEDING_CONTEXT_LINES (5)
1453 
1454 /* Read a complete file into memory.  */
1455 
1456 static const char *
1457 slurp_file (const char *fn, size_t *size, struct stat *fst)
1458 {
1459 #ifdef HAVE_MMAP
1460   int ps = getpagesize ();
1461   size_t msize;
1462 #endif
1463   const char *map;
1464   int fd = open (fn, O_RDONLY | O_BINARY);
1465 
1466   if (fd < 0)
1467     return NULL;
1468   if (fstat (fd, fst) < 0)
1469     {
1470       close (fd);
1471       return NULL;
1472     }
1473   *size = fst->st_size;
1474 #ifdef HAVE_MMAP
1475   msize = (*size + ps - 1) & ~(ps - 1);
1476   map = mmap (NULL, msize, PROT_READ, MAP_SHARED, fd, 0);
1477   if (map != (char *) -1L)
1478     {
1479       close (fd);
1480       return map;
1481     }
1482 #endif
1483   map = (const char *) malloc (*size);
1484   if (!map || (size_t) read (fd, (char *) map, *size) != *size)
1485     {
1486       free ((void *) map);
1487       map = NULL;
1488     }
1489   close (fd);
1490   return map;
1491 }
1492 
1493 #define line_map_decrease 5
1494 
1495 /* Precompute array of lines for a mapped file. */
1496 
1497 static const char **
1498 index_file (const char *map, size_t size, unsigned int *maxline)
1499 {
1500   const char *p, *lstart, *end;
1501   int chars_per_line = 45; /* First iteration will use 40.  */
1502   unsigned int lineno;
1503   const char **linemap = NULL;
1504   unsigned long line_map_size = 0;
1505 
1506   lineno = 0;
1507   lstart = map;
1508   end = map + size;
1509 
1510   for (p = map; p < end; p++)
1511     {
1512       if (*p == '\n')
1513 	{
1514 	  if (p + 1 < end && p[1] == '\r')
1515 	    p++;
1516 	}
1517       else if (*p == '\r')
1518 	{
1519 	  if (p + 1 < end && p[1] == '\n')
1520 	    p++;
1521 	}
1522       else
1523 	continue;
1524 
1525       /* End of line found.  */
1526 
1527       if (linemap == NULL || line_map_size < lineno + 1)
1528 	{
1529 	  unsigned long newsize;
1530 
1531 	  chars_per_line -= line_map_decrease;
1532 	  if (chars_per_line <= 1)
1533 	    chars_per_line = 1;
1534 	  line_map_size = size / chars_per_line + 1;
1535 	  if (line_map_size < lineno + 1)
1536 	    line_map_size = lineno + 1;
1537 	  newsize = line_map_size * sizeof (char *);
1538 	  linemap = (const char **) xrealloc (linemap, newsize);
1539 	}
1540 
1541       linemap[lineno++] = lstart;
1542       lstart = p + 1;
1543     }
1544 
1545   *maxline = lineno;
1546   return linemap;
1547 }
1548 
1549 /* Tries to open MODNAME, and if successful adds a node to print_files
1550    linked list and returns that node.  Returns NULL on failure.  */
1551 
1552 static struct print_file_list *
1553 try_print_file_open (const char *origname, const char *modname, struct stat *fst)
1554 {
1555   struct print_file_list *p;
1556 
1557   p = (struct print_file_list *) xmalloc (sizeof (struct print_file_list));
1558 
1559   p->map = slurp_file (modname, &p->mapsize, fst);
1560   if (p->map == NULL)
1561     {
1562       free (p);
1563       return NULL;
1564     }
1565 
1566   p->linemap = index_file (p->map, p->mapsize, &p->maxline);
1567   p->last_line = 0;
1568   p->max_printed = 0;
1569   p->filename = origname;
1570   p->modname = modname;
1571   p->next = print_files;
1572   p->first = 1;
1573   print_files = p;
1574   return p;
1575 }
1576 
1577 /* If the source file, as described in the symtab, is not found
1578    try to locate it in one of the paths specified with -I
1579    If found, add location to print_files linked list.  */
1580 
1581 static struct print_file_list *
1582 update_source_path (const char *filename, bfd *abfd)
1583 {
1584   struct print_file_list *p;
1585   const char *fname;
1586   struct stat fst;
1587   int i;
1588 
1589   p = try_print_file_open (filename, filename, &fst);
1590   if (p == NULL)
1591     {
1592       if (include_path_count == 0)
1593 	return NULL;
1594 
1595       /* Get the name of the file.  */
1596       fname = lbasename (filename);
1597 
1598       /* If file exists under a new path, we need to add it to the list
1599 	 so that show_line knows about it.  */
1600       for (i = 0; i < include_path_count; i++)
1601 	{
1602 	  char *modname = concat (include_paths[i], "/", fname,
1603 				  (const char *) 0);
1604 
1605 	  p = try_print_file_open (filename, modname, &fst);
1606 	  if (p)
1607 	    break;
1608 
1609 	  free (modname);
1610 	}
1611     }
1612 
1613   if (p != NULL)
1614     {
1615       long mtime = bfd_get_mtime (abfd);
1616 
1617       if (fst.st_mtime > mtime)
1618 	warn (_("source file %s is more recent than object file\n"),
1619 	      filename);
1620     }
1621 
1622   return p;
1623 }
1624 
1625 /* Print a source file line.  */
1626 
1627 static void
1628 print_line (struct print_file_list *p, unsigned int linenum)
1629 {
1630   const char *l;
1631   size_t len;
1632 
1633   --linenum;
1634   if (linenum >= p->maxline)
1635     return;
1636   l = p->linemap [linenum];
1637   if (source_comment != NULL && strlen (l) > 0)
1638     printf ("%s", source_comment);
1639   len = strcspn (l, "\n\r");
1640   /* Test fwrite return value to quiet glibc warning.  */
1641   if (len == 0 || fwrite (l, len, 1, stdout) == 1)
1642     putchar ('\n');
1643 }
1644 
1645 /* Print a range of source code lines. */
1646 
1647 static void
1648 dump_lines (struct print_file_list *p, unsigned int start, unsigned int end)
1649 {
1650   if (p->map == NULL)
1651     return;
1652   while (start <= end)
1653     {
1654       print_line (p, start);
1655       start++;
1656     }
1657 }
1658 
1659 /* Show the line number, or the source line, in a disassembly
1660    listing.  */
1661 
1662 static void
1663 show_line (bfd *abfd, asection *section, bfd_vma addr_offset)
1664 {
1665   const char *filename;
1666   const char *functionname;
1667   unsigned int linenumber;
1668   unsigned int discriminator;
1669   bfd_boolean reloc;
1670   char *path = NULL;
1671 
1672   if (! with_line_numbers && ! with_source_code)
1673     return;
1674 
1675   if (! bfd_find_nearest_line_discriminator (abfd, section, syms, addr_offset,
1676 					     &filename, &functionname,
1677 					     &linenumber, &discriminator))
1678     return;
1679 
1680   if (filename != NULL && *filename == '\0')
1681     filename = NULL;
1682   if (functionname != NULL && *functionname == '\0')
1683     functionname = NULL;
1684 
1685   if (filename
1686       && IS_ABSOLUTE_PATH (filename)
1687       && prefix)
1688     {
1689       char *path_up;
1690       const char *fname = filename;
1691 
1692       path = xmalloc (prefix_length + PATH_MAX + 1);
1693 
1694       if (prefix_length)
1695 	memcpy (path, prefix, prefix_length);
1696       path_up = path + prefix_length;
1697 
1698       /* Build relocated filename, stripping off leading directories
1699 	 from the initial filename if requested.  */
1700       if (prefix_strip > 0)
1701 	{
1702 	  int level = 0;
1703 	  const char *s;
1704 
1705 	  /* Skip selected directory levels.  */
1706 	  for (s = fname + 1; *s != '\0' && level < prefix_strip; s++)
1707 	    if (IS_DIR_SEPARATOR (*s))
1708 	      {
1709 		fname = s;
1710 		level++;
1711 	      }
1712 	}
1713 
1714       /* Update complete filename.  */
1715       strncpy (path_up, fname, PATH_MAX);
1716       path_up[PATH_MAX] = '\0';
1717 
1718       filename = path;
1719       reloc = TRUE;
1720     }
1721   else
1722     reloc = FALSE;
1723 
1724   if (with_line_numbers)
1725     {
1726       if (functionname != NULL
1727 	  && (prev_functionname == NULL
1728 	      || strcmp (functionname, prev_functionname) != 0))
1729 	{
1730 	  printf ("%s():\n", sanitize_string (functionname));
1731 	  prev_line = -1;
1732 	}
1733       if (linenumber > 0
1734 	  && (linenumber != prev_line
1735 	      || discriminator != prev_discriminator))
1736 	{
1737 	  if (discriminator > 0)
1738 	    printf ("%s:%u (discriminator %u)\n",
1739 		    filename == NULL ? "???" : sanitize_string (filename),
1740 		    linenumber, discriminator);
1741 	  else
1742 	    printf ("%s:%u\n", filename == NULL
1743 		    ? "???" : sanitize_string (filename),
1744 		    linenumber);
1745 	}
1746       if (unwind_inlines)
1747 	{
1748 	  const char *filename2;
1749 	  const char *functionname2;
1750 	  unsigned line2;
1751 
1752 	  while (bfd_find_inliner_info (abfd, &filename2, &functionname2,
1753 					&line2))
1754 	    {
1755 	      printf ("inlined by %s:%u",
1756 		      sanitize_string (filename2), line2);
1757 	      printf (" (%s)\n", sanitize_string (functionname2));
1758 	    }
1759 	}
1760     }
1761 
1762   if (with_source_code
1763       && filename != NULL
1764       && linenumber > 0)
1765     {
1766       struct print_file_list **pp, *p;
1767       unsigned l;
1768 
1769       for (pp = &print_files; *pp != NULL; pp = &(*pp)->next)
1770 	if (filename_cmp ((*pp)->filename, filename) == 0)
1771 	  break;
1772       p = *pp;
1773 
1774       if (p == NULL)
1775 	{
1776 	  if (reloc)
1777 	    filename = xstrdup (filename);
1778 	  p = update_source_path (filename, abfd);
1779 	}
1780 
1781       if (p != NULL && linenumber != p->last_line)
1782 	{
1783 	  if (file_start_context && p->first)
1784 	    l = 1;
1785 	  else
1786 	    {
1787 	      l = linenumber - SHOW_PRECEDING_CONTEXT_LINES;
1788 	      if (l >= linenumber)
1789 		l = 1;
1790 	      if (p->max_printed >= l)
1791 		{
1792 		  if (p->max_printed < linenumber)
1793 		    l = p->max_printed + 1;
1794 		  else
1795 		    l = linenumber;
1796 		}
1797 	    }
1798 	  dump_lines (p, l, linenumber);
1799 	  if (p->max_printed < linenumber)
1800 	    p->max_printed = linenumber;
1801 	  p->last_line = linenumber;
1802 	  p->first = 0;
1803 	}
1804     }
1805 
1806   if (functionname != NULL
1807       && (prev_functionname == NULL
1808 	  || strcmp (functionname, prev_functionname) != 0))
1809     {
1810       if (prev_functionname != NULL)
1811 	free (prev_functionname);
1812       prev_functionname = (char *) xmalloc (strlen (functionname) + 1);
1813       strcpy (prev_functionname, functionname);
1814     }
1815 
1816   if (linenumber > 0 && linenumber != prev_line)
1817     prev_line = linenumber;
1818 
1819   if (discriminator != prev_discriminator)
1820     prev_discriminator = discriminator;
1821 
1822   if (path)
1823     free (path);
1824 }
1825 
1826 /* Pseudo FILE object for strings.  */
1827 typedef struct
1828 {
1829   char *buffer;
1830   size_t pos;
1831   size_t alloc;
1832 } SFILE;
1833 
1834 /* sprintf to a "stream".  */
1835 
1836 static int ATTRIBUTE_PRINTF_2
1837 objdump_sprintf (SFILE *f, const char *format, ...)
1838 {
1839   size_t n;
1840   va_list args;
1841 
1842   while (1)
1843     {
1844       size_t space = f->alloc - f->pos;
1845 
1846       va_start (args, format);
1847       n = vsnprintf (f->buffer + f->pos, space, format, args);
1848       va_end (args);
1849 
1850       if (space > n)
1851 	break;
1852 
1853       f->alloc = (f->alloc + n) * 2;
1854       f->buffer = (char *) xrealloc (f->buffer, f->alloc);
1855     }
1856   f->pos += n;
1857 
1858   return n;
1859 }
1860 
1861 /* Code for generating (colored) diagrams of control flow start and end
1862    points.  */
1863 
1864 /* Structure used to store the properties of a jump.  */
1865 
1866 struct jump_info
1867 {
1868   /* The next jump, or NULL if this is the last object.  */
1869   struct jump_info *next;
1870   /* The previous jump, or NULL if this is the first object.  */
1871   struct jump_info *prev;
1872   /* The start addresses of the jump.  */
1873   struct
1874     {
1875       /* The list of start addresses.  */
1876       bfd_vma *addresses;
1877       /* The number of elements.  */
1878       size_t count;
1879       /* The maximum number of elements that fit into the array.  */
1880       size_t max_count;
1881     } start;
1882   /* The end address of the jump.  */
1883   bfd_vma end;
1884   /* The drawing level of the jump.  */
1885   int level;
1886 };
1887 
1888 /* Construct a jump object for a jump from start
1889    to end with the corresponding level.  */
1890 
1891 static struct jump_info *
1892 jump_info_new (bfd_vma start, bfd_vma end, int level)
1893 {
1894   struct jump_info *result = xmalloc (sizeof (struct jump_info));
1895 
1896   result->next = NULL;
1897   result->prev = NULL;
1898   result->start.addresses = xmalloc (sizeof (bfd_vma *) * 2);
1899   result->start.addresses[0] = start;
1900   result->start.count = 1;
1901   result->start.max_count = 2;
1902   result->end = end;
1903   result->level = level;
1904 
1905   return result;
1906 }
1907 
1908 /* Free a jump object and return the next object
1909    or NULL if this was the last one.  */
1910 
1911 static struct jump_info *
1912 jump_info_free (struct jump_info *ji)
1913 {
1914   struct jump_info *result = NULL;
1915 
1916   if (ji)
1917     {
1918       result = ji->next;
1919       if (ji->start.addresses)
1920 	free (ji->start.addresses);
1921       free (ji);
1922     }
1923 
1924   return result;
1925 }
1926 
1927 /* Get the smallest value of all start and end addresses.  */
1928 
1929 static bfd_vma
1930 jump_info_min_address (const struct jump_info *ji)
1931 {
1932   bfd_vma min_address = ji->end;
1933   size_t i;
1934 
1935   for (i = ji->start.count; i-- > 0;)
1936     if (ji->start.addresses[i] < min_address)
1937       min_address = ji->start.addresses[i];
1938   return min_address;
1939 }
1940 
1941 /* Get the largest value of all start and end addresses.  */
1942 
1943 static bfd_vma
1944 jump_info_max_address (const struct jump_info *ji)
1945 {
1946   bfd_vma max_address = ji->end;
1947   size_t i;
1948 
1949   for (i = ji->start.count; i-- > 0;)
1950     if (ji->start.addresses[i] > max_address)
1951       max_address = ji->start.addresses[i];
1952   return max_address;
1953 }
1954 
1955 /* Get the target address of a jump.  */
1956 
1957 static bfd_vma
1958 jump_info_end_address (const struct jump_info *ji)
1959 {
1960   return ji->end;
1961 }
1962 
1963 /* Test if an address is one of the start addresses of a jump.  */
1964 
1965 static bfd_boolean
1966 jump_info_is_start_address (const struct jump_info *ji, bfd_vma address)
1967 {
1968   bfd_boolean result = FALSE;
1969   size_t i;
1970 
1971   for (i = ji->start.count; i-- > 0;)
1972     if (address == ji->start.addresses[i])
1973       {
1974 	result = TRUE;
1975 	break;
1976       }
1977 
1978   return result;
1979 }
1980 
1981 /* Test if an address is the target address of a jump.  */
1982 
1983 static bfd_boolean
1984 jump_info_is_end_address (const struct jump_info *ji, bfd_vma address)
1985 {
1986   return (address == ji->end);
1987 }
1988 
1989 /* Get the difference between the smallest and largest address of a jump.  */
1990 
1991 static bfd_vma
1992 jump_info_size (const struct jump_info *ji)
1993 {
1994   return jump_info_max_address (ji) - jump_info_min_address (ji);
1995 }
1996 
1997 /* Unlink a jump object from a list.  */
1998 
1999 static void
2000 jump_info_unlink (struct jump_info *node,
2001 		  struct jump_info **base)
2002 {
2003   if (node->next)
2004     node->next->prev = node->prev;
2005   if (node->prev)
2006     node->prev->next = node->next;
2007   else
2008     *base = node->next;
2009   node->next = NULL;
2010   node->prev = NULL;
2011 }
2012 
2013 /* Insert unlinked jump info node into a list.  */
2014 
2015 static void
2016 jump_info_insert (struct jump_info *node,
2017 		  struct jump_info *target,
2018 		  struct jump_info **base)
2019 {
2020   node->next = target;
2021   node->prev = target->prev;
2022   target->prev = node;
2023   if (node->prev)
2024     node->prev->next = node;
2025   else
2026     *base = node;
2027 }
2028 
2029 /* Add unlinked node to the front of a list.  */
2030 
2031 static void
2032 jump_info_add_front (struct jump_info *node,
2033 		     struct jump_info **base)
2034 {
2035   node->next = *base;
2036   if (node->next)
2037     node->next->prev = node;
2038   node->prev = NULL;
2039   *base = node;
2040 }
2041 
2042 /* Move linked node to target position.  */
2043 
2044 static void
2045 jump_info_move_linked (struct jump_info *node,
2046 		       struct jump_info *target,
2047 		       struct jump_info **base)
2048 {
2049   /* Unlink node.  */
2050   jump_info_unlink (node, base);
2051   /* Insert node at target position.  */
2052   jump_info_insert (node, target, base);
2053 }
2054 
2055 /* Test if two jumps intersect.  */
2056 
2057 static bfd_boolean
2058 jump_info_intersect (const struct jump_info *a,
2059 		     const struct jump_info *b)
2060 {
2061   return ((jump_info_max_address (a) >= jump_info_min_address (b))
2062 	  && (jump_info_min_address (a) <= jump_info_max_address (b)));
2063 }
2064 
2065 /* Merge two compatible jump info objects.  */
2066 
2067 static void
2068 jump_info_merge (struct jump_info **base)
2069 {
2070   struct jump_info *a;
2071 
2072   for (a = *base; a; a = a->next)
2073     {
2074       struct jump_info *b;
2075 
2076       for (b = a->next; b; b = b->next)
2077 	{
2078 	  /* Merge both jumps into one.  */
2079 	  if (a->end == b->end)
2080 	    {
2081 	      /* Reallocate addresses.  */
2082 	      size_t needed_size = a->start.count + b->start.count;
2083 	      size_t i;
2084 
2085 	      if (needed_size > a->start.max_count)
2086 		{
2087 		  a->start.max_count += b->start.max_count;
2088 		  a->start.addresses =
2089 		    xrealloc (a->start.addresses,
2090 			      a->start.max_count * sizeof (bfd_vma *));
2091 		}
2092 
2093 	      /* Append start addresses.  */
2094 	      for (i = 0; i < b->start.count; ++i)
2095 		a->start.addresses[a->start.count++] =
2096 		  b->start.addresses[i];
2097 
2098 	      /* Remove and delete jump.  */
2099 	      struct jump_info *tmp = b->prev;
2100 	      jump_info_unlink (b, base);
2101 	      jump_info_free (b);
2102 	      b = tmp;
2103 	    }
2104 	}
2105     }
2106 }
2107 
2108 /* Sort jumps by their size and starting point using a stable
2109    minsort. This could be improved if sorting performance is
2110    an issue, for example by using mergesort.  */
2111 
2112 static void
2113 jump_info_sort (struct jump_info **base)
2114 {
2115   struct jump_info *current_element = *base;
2116 
2117   while (current_element)
2118     {
2119       struct jump_info *best_match = current_element;
2120       struct jump_info *runner = current_element->next;
2121       bfd_vma best_size = jump_info_size (best_match);
2122 
2123       while (runner)
2124 	{
2125 	  bfd_vma runner_size = jump_info_size (runner);
2126 
2127 	  if ((runner_size < best_size)
2128 	      || ((runner_size == best_size)
2129 		  && (jump_info_min_address (runner)
2130 		      < jump_info_min_address (best_match))))
2131 	    {
2132 	      best_match = runner;
2133 	      best_size = runner_size;
2134 	    }
2135 
2136 	  runner = runner->next;
2137 	}
2138 
2139       if (best_match == current_element)
2140 	current_element = current_element->next;
2141       else
2142 	jump_info_move_linked (best_match, current_element, base);
2143     }
2144 }
2145 
2146 /* Visualize all jumps at a given address.  */
2147 
2148 static void
2149 jump_info_visualize_address (bfd_vma address,
2150 			     int max_level,
2151 			     char *line_buffer,
2152 			     uint8_t *color_buffer)
2153 {
2154   struct jump_info *ji = detected_jumps;
2155   size_t len = (max_level + 1) * 3;
2156 
2157   /* Clear line buffer.  */
2158   memset (line_buffer, ' ', len);
2159   memset (color_buffer, 0, len);
2160 
2161   /* Iterate over jumps and add their ASCII art.  */
2162   while (ji)
2163     {
2164       /* Discard jumps that are never needed again.  */
2165       if (jump_info_max_address (ji) < address)
2166 	{
2167 	  struct jump_info *tmp = ji;
2168 
2169 	  ji = ji->next;
2170 	  jump_info_unlink (tmp, &detected_jumps);
2171 	  jump_info_free (tmp);
2172 	  continue;
2173 	}
2174 
2175       /* This jump intersects with the current address.  */
2176       if (jump_info_min_address (ji) <= address)
2177 	{
2178 	  /* Hash target address to get an even
2179 	     distribution between all values.  */
2180 	  bfd_vma hash_address = jump_info_end_address (ji);
2181 	  uint8_t color = iterative_hash_object (hash_address, 0);
2182 	  /* Fetch line offset.  */
2183 	  int offset = (max_level - ji->level) * 3;
2184 
2185 	  /* Draw start line.  */
2186 	  if (jump_info_is_start_address (ji, address))
2187 	    {
2188 	      size_t i = offset + 1;
2189 
2190 	      for (; i < len - 1; ++i)
2191 		if (line_buffer[i] == ' ')
2192 		  {
2193 		    line_buffer[i] = '-';
2194 		    color_buffer[i] = color;
2195 		  }
2196 
2197 	      if (line_buffer[i] == ' ')
2198 		{
2199 		  line_buffer[i] = '-';
2200 		  color_buffer[i] = color;
2201 		}
2202 	      else if (line_buffer[i] == '>')
2203 		{
2204 		  line_buffer[i] = 'X';
2205 		  color_buffer[i] = color;
2206 		}
2207 
2208 	      if (line_buffer[offset] == ' ')
2209 		{
2210 		  if (address <= ji->end)
2211 		    line_buffer[offset] =
2212 		      (jump_info_min_address (ji) == address) ? '/': '+';
2213 		  else
2214 		    line_buffer[offset] =
2215 		      (jump_info_max_address (ji) == address) ? '\\': '+';
2216 		  color_buffer[offset] = color;
2217 		}
2218 	    }
2219 	  /* Draw jump target.  */
2220 	  else if (jump_info_is_end_address (ji, address))
2221 	    {
2222 	      size_t i = offset + 1;
2223 
2224 	      for (; i < len - 1; ++i)
2225 		if (line_buffer[i] == ' ')
2226 		  {
2227 		    line_buffer[i] = '-';
2228 		    color_buffer[i] = color;
2229 		  }
2230 
2231 	      if (line_buffer[i] == ' ')
2232 		{
2233 		  line_buffer[i] = '>';
2234 		  color_buffer[i] = color;
2235 		}
2236 	      else if (line_buffer[i] == '-')
2237 		{
2238 		  line_buffer[i] = 'X';
2239 		  color_buffer[i] = color;
2240 		}
2241 
2242 	      if (line_buffer[offset] == ' ')
2243 		{
2244 		  if (jump_info_min_address (ji) < address)
2245 		    line_buffer[offset] =
2246 		      (jump_info_max_address (ji) > address) ? '>' : '\\';
2247 		  else
2248 		    line_buffer[offset] = '/';
2249 		  color_buffer[offset] = color;
2250 		}
2251 	    }
2252 	  /* Draw intermediate line segment.  */
2253 	  else if (line_buffer[offset] == ' ')
2254 	    {
2255 	      line_buffer[offset] = '|';
2256 	      color_buffer[offset] = color;
2257 	    }
2258 	}
2259 
2260       ji = ji->next;
2261     }
2262 }
2263 
2264 /* Clone of disassemble_bytes to detect jumps inside a function.  */
2265 /* FIXME: is this correct? Can we strip it down even further?  */
2266 
2267 static struct jump_info *
2268 disassemble_jumps (struct disassemble_info * inf,
2269 		   disassembler_ftype        disassemble_fn,
2270 		   bfd_vma                   start_offset,
2271 		   bfd_vma                   stop_offset,
2272 		   bfd_vma		     rel_offset,
2273 		   arelent ***               relppp,
2274 		   arelent **                relppend)
2275 {
2276   struct objdump_disasm_info *aux;
2277   struct jump_info *jumps = NULL;
2278   asection *section;
2279   bfd_vma addr_offset;
2280   unsigned int opb = inf->octets_per_byte;
2281   int octets = opb;
2282   SFILE sfile;
2283 
2284   aux = (struct objdump_disasm_info *) inf->application_data;
2285   section = inf->section;
2286 
2287   sfile.alloc = 120;
2288   sfile.buffer = (char *) xmalloc (sfile.alloc);
2289   sfile.pos = 0;
2290 
2291   inf->insn_info_valid = 0;
2292   inf->fprintf_func = (fprintf_ftype) objdump_sprintf;
2293   inf->stream = &sfile;
2294 
2295   addr_offset = start_offset;
2296   while (addr_offset < stop_offset)
2297     {
2298       int previous_octets;
2299 
2300       /* Remember the length of the previous instruction.  */
2301       previous_octets = octets;
2302       octets = 0;
2303 
2304       sfile.pos = 0;
2305       inf->bytes_per_line = 0;
2306       inf->bytes_per_chunk = 0;
2307       inf->flags = ((disassemble_all ? DISASSEMBLE_DATA : 0)
2308         | (wide_output ? WIDE_OUTPUT : 0));
2309       if (machine)
2310 	inf->flags |= USER_SPECIFIED_MACHINE_TYPE;
2311 
2312       if (inf->disassembler_needs_relocs
2313 	  && (bfd_get_file_flags (aux->abfd) & EXEC_P) == 0
2314 	  && (bfd_get_file_flags (aux->abfd) & DYNAMIC) == 0
2315 	  && *relppp < relppend)
2316 	{
2317 	  bfd_signed_vma distance_to_rel;
2318 
2319 	  distance_to_rel = (**relppp)->address - (rel_offset + addr_offset);
2320 
2321 	  /* Check to see if the current reloc is associated with
2322 	     the instruction that we are about to disassemble.  */
2323 	  if (distance_to_rel == 0
2324 	      /* FIXME: This is wrong.  We are trying to catch
2325 		 relocs that are addressed part way through the
2326 		 current instruction, as might happen with a packed
2327 		 VLIW instruction.  Unfortunately we do not know the
2328 		 length of the current instruction since we have not
2329 		 disassembled it yet.  Instead we take a guess based
2330 		 upon the length of the previous instruction.  The
2331 		 proper solution is to have a new target-specific
2332 		 disassembler function which just returns the length
2333 		 of an instruction at a given address without trying
2334 		 to display its disassembly. */
2335 	      || (distance_to_rel > 0
2336 		&& distance_to_rel < (bfd_signed_vma) (previous_octets/ opb)))
2337 	    {
2338 	      inf->flags |= INSN_HAS_RELOC;
2339 	    }
2340 	}
2341 
2342       if (! disassemble_all
2343 	  && (section->flags & (SEC_CODE | SEC_HAS_CONTENTS))
2344 	  == (SEC_CODE | SEC_HAS_CONTENTS))
2345 	/* Set a stop_vma so that the disassembler will not read
2346 	   beyond the next symbol.  We assume that symbols appear on
2347 	   the boundaries between instructions.  We only do this when
2348 	   disassembling code of course, and when -D is in effect.  */
2349 	inf->stop_vma = section->vma + stop_offset;
2350 
2351       inf->stop_offset = stop_offset;
2352 
2353       /* Extract jump information.  */
2354       inf->insn_info_valid = 0;
2355       octets = (*disassemble_fn) (section->vma + addr_offset, inf);
2356       /* Test if a jump was detected.  */
2357       if (inf->insn_info_valid
2358 	  && ((inf->insn_type == dis_branch)
2359 	      || (inf->insn_type == dis_condbranch)
2360 	      || (inf->insn_type == dis_jsr)
2361 	      || (inf->insn_type == dis_condjsr))
2362 	  && (inf->target >= section->vma + start_offset)
2363 	  && (inf->target < section->vma + stop_offset))
2364 	{
2365 	  struct jump_info *ji =
2366 	    jump_info_new (section->vma + addr_offset, inf->target, -1);
2367 	  jump_info_add_front (ji, &jumps);
2368 	}
2369 
2370       inf->stop_vma = 0;
2371 
2372       addr_offset += octets / opb;
2373     }
2374 
2375   inf->fprintf_func = (fprintf_ftype) fprintf;
2376   inf->stream = stdout;
2377 
2378   free (sfile.buffer);
2379 
2380   /* Merge jumps.  */
2381   jump_info_merge (&jumps);
2382   /* Process jumps.  */
2383   jump_info_sort (&jumps);
2384 
2385   /* Group jumps by level.  */
2386   struct jump_info *last_jump = jumps;
2387   int max_level = -1;
2388 
2389   while (last_jump)
2390     {
2391       /* The last jump is part of the next group.  */
2392       struct jump_info *base = last_jump;
2393       /* Increment level.  */
2394       base->level = ++max_level;
2395 
2396       /* Find jumps that can be combined on the same
2397 	 level, with the largest jumps tested first.
2398 	 This has the advantage that large jumps are on
2399 	 lower levels and do not intersect with small
2400 	 jumps that get grouped on higher levels.  */
2401       struct jump_info *exchange_item = last_jump->next;
2402       struct jump_info *it = exchange_item;
2403 
2404       for (; it; it = it->next)
2405 	{
2406 	  /* Test if the jump intersects with any
2407 	     jump from current group.  */
2408 	  bfd_boolean ok = TRUE;
2409 	  struct jump_info *it_collision;
2410 
2411 	  for (it_collision = base;
2412 	       it_collision != exchange_item;
2413 	       it_collision = it_collision->next)
2414 	    {
2415 	      /* This jump intersects so we leave it out.  */
2416 	      if (jump_info_intersect (it_collision, it))
2417 		{
2418 		  ok = FALSE;
2419 		  break;
2420 		}
2421 	    }
2422 
2423 	  /* Add jump to group.  */
2424 	  if (ok)
2425 	    {
2426 	      /* Move current element to the front.  */
2427 	      if (it != exchange_item)
2428 		{
2429 		  struct jump_info *save = it->prev;
2430 		  jump_info_move_linked (it, exchange_item, &jumps);
2431 		  last_jump = it;
2432 		  it = save;
2433 		}
2434 	      else
2435 		{
2436 		  last_jump = exchange_item;
2437 		  exchange_item = exchange_item->next;
2438 		}
2439 	      last_jump->level = max_level;
2440 	    }
2441 	}
2442 
2443       /* Move to next group.  */
2444       last_jump = exchange_item;
2445     }
2446 
2447   return jumps;
2448 }
2449 
2450 /* The number of zeroes we want to see before we start skipping them.
2451    The number is arbitrarily chosen.  */
2452 
2453 #define DEFAULT_SKIP_ZEROES 8
2454 
2455 /* The number of zeroes to skip at the end of a section.  If the
2456    number of zeroes at the end is between SKIP_ZEROES_AT_END and
2457    SKIP_ZEROES, they will be disassembled.  If there are fewer than
2458    SKIP_ZEROES_AT_END, they will be skipped.  This is a heuristic
2459    attempt to avoid disassembling zeroes inserted by section
2460    alignment.  */
2461 
2462 #define DEFAULT_SKIP_ZEROES_AT_END 3
2463 
2464 static int
2465 null_print (const void * stream ATTRIBUTE_UNUSED, const char * format ATTRIBUTE_UNUSED, ...)
2466 {
2467   return 1;
2468 }
2469 
2470 /* Disassemble some data in memory between given values.  */
2471 
2472 static void
2473 disassemble_bytes (struct disassemble_info * inf,
2474 		   disassembler_ftype        disassemble_fn,
2475 		   bfd_boolean               insns,
2476 		   bfd_byte *                data,
2477 		   bfd_vma                   start_offset,
2478 		   bfd_vma                   stop_offset,
2479 		   bfd_vma		     rel_offset,
2480 		   arelent ***               relppp,
2481 		   arelent **                relppend)
2482 {
2483   struct objdump_disasm_info *aux;
2484   asection *section;
2485   int octets_per_line;
2486   int skip_addr_chars;
2487   bfd_vma addr_offset;
2488   unsigned int opb = inf->octets_per_byte;
2489   unsigned int skip_zeroes = inf->skip_zeroes;
2490   unsigned int skip_zeroes_at_end = inf->skip_zeroes_at_end;
2491   int octets = opb;
2492   SFILE sfile;
2493 
2494   aux = (struct objdump_disasm_info *) inf->application_data;
2495   section = inf->section;
2496 
2497   sfile.alloc = 120;
2498   sfile.buffer = (char *) xmalloc (sfile.alloc);
2499   sfile.pos = 0;
2500 
2501   if (insn_width)
2502     octets_per_line = insn_width;
2503   else if (insns)
2504     octets_per_line = 4;
2505   else
2506     octets_per_line = 16;
2507 
2508   /* Figure out how many characters to skip at the start of an
2509      address, to make the disassembly look nicer.  We discard leading
2510      zeroes in chunks of 4, ensuring that there is always a leading
2511      zero remaining.  */
2512   skip_addr_chars = 0;
2513   if (! prefix_addresses)
2514     {
2515       char buf[30];
2516 
2517       bfd_sprintf_vma (aux->abfd, buf, section->vma + section->size / opb);
2518 
2519       while (buf[skip_addr_chars] == '0')
2520 	++skip_addr_chars;
2521 
2522       /* Don't discard zeros on overflow.  */
2523       if (buf[skip_addr_chars] == '\0' && section->vma != 0)
2524 	skip_addr_chars = 0;
2525 
2526       if (skip_addr_chars != 0)
2527 	skip_addr_chars = (skip_addr_chars - 1) & -4;
2528     }
2529 
2530   inf->insn_info_valid = 0;
2531 
2532   /* Determine maximum level. */
2533   uint8_t *color_buffer = NULL;
2534   char *line_buffer = NULL;
2535   int max_level = -1;
2536 
2537   /* Some jumps were detected.  */
2538   if (detected_jumps)
2539     {
2540       struct jump_info *ji;
2541 
2542       /* Find maximum jump level.  */
2543       for (ji = detected_jumps; ji; ji = ji->next)
2544 	{
2545 	  if (ji->level > max_level)
2546 	    max_level = ji->level;
2547 	}
2548 
2549       /* Allocate buffers.  */
2550       size_t len = (max_level + 1) * 3 + 1;
2551       line_buffer = xmalloc (len);
2552       line_buffer[len - 1] = 0;
2553       color_buffer = xmalloc (len);
2554       color_buffer[len - 1] = 0;
2555     }
2556 
2557   addr_offset = start_offset;
2558   while (addr_offset < stop_offset)
2559     {
2560       bfd_vma z;
2561       bfd_boolean need_nl = FALSE;
2562 
2563       octets = 0;
2564 
2565       /* Make sure we don't use relocs from previous instructions.  */
2566       aux->reloc = NULL;
2567 
2568       /* If we see more than SKIP_ZEROES octets of zeroes, we just
2569 	 print `...'.  */
2570       for (z = addr_offset * opb; z < stop_offset * opb; z++)
2571 	if (data[z] != 0)
2572 	  break;
2573       if (! disassemble_zeroes
2574 	  && (inf->insn_info_valid == 0
2575 	      || inf->branch_delay_insns == 0)
2576 	  && (z - addr_offset * opb >= skip_zeroes
2577 	      || (z == stop_offset * opb &&
2578 		  z - addr_offset * opb < skip_zeroes_at_end)))
2579 	{
2580 	  /* If there are more nonzero octets to follow, we only skip
2581 	     zeroes in multiples of 4, to try to avoid running over
2582 	     the start of an instruction which happens to start with
2583 	     zero.  */
2584 	  if (z != stop_offset * opb)
2585 	    z = addr_offset * opb + ((z - addr_offset * opb) &~ 3);
2586 
2587 	  octets = z - addr_offset * opb;
2588 
2589 	  /* If we are going to display more data, and we are displaying
2590 	     file offsets, then tell the user how many zeroes we skip
2591 	     and the file offset from where we resume dumping.  */
2592 	  if (display_file_offsets && ((addr_offset + (octets / opb)) < stop_offset))
2593 	    printf ("\t... (skipping %d zeroes, resuming at file offset: 0x%lx)\n",
2594 		    octets / opb,
2595 		    (unsigned long) (section->filepos
2596 				     + (addr_offset + (octets / opb))));
2597 	  else
2598 	    printf ("\t...\n");
2599 	}
2600       else
2601 	{
2602 	  char buf[50];
2603 	  int bpc = 0;
2604 	  int pb = 0;
2605 
2606 	  if (with_line_numbers || with_source_code)
2607 	    show_line (aux->abfd, section, addr_offset);
2608 
2609 	  if (! prefix_addresses)
2610 	    {
2611 	      char *s;
2612 
2613 	      bfd_sprintf_vma (aux->abfd, buf, section->vma + addr_offset);
2614 	      for (s = buf + skip_addr_chars; *s == '0'; s++)
2615 		*s = ' ';
2616 	      if (*s == '\0')
2617 		*--s = '0';
2618 	      printf ("%s:\t", buf + skip_addr_chars);
2619 	    }
2620 	  else
2621 	    {
2622 	      aux->require_sec = TRUE;
2623 	      objdump_print_address (section->vma + addr_offset, inf);
2624 	      aux->require_sec = FALSE;
2625 	      putchar (' ');
2626 	    }
2627 
2628 	  /* Visualize jumps. */
2629 	  if (line_buffer)
2630 	    {
2631 	      jump_info_visualize_address (section->vma + addr_offset,
2632 					   max_level,
2633 					   line_buffer,
2634 					   color_buffer);
2635 
2636 	      size_t line_buffer_size = strlen (line_buffer);
2637 	      char last_color = 0;
2638 	      size_t i;
2639 
2640 	      for (i = 0; i <= line_buffer_size; ++i)
2641 		{
2642 		  if (color_output)
2643 		    {
2644 		      uint8_t color = (i < line_buffer_size) ? color_buffer[i]: 0;
2645 
2646 		      if (color != last_color)
2647 			{
2648 			  if (color)
2649 			    if (extended_color_output)
2650 			      /* Use extended 8bit color, but
2651 			         do not choose dark colors.  */
2652 			      printf ("\033[38;5;%dm", 124 + (color % 108));
2653 			    else
2654 			      /* Use simple terminal colors.  */
2655 			      printf ("\033[%dm", 31 + (color % 7));
2656 			  else
2657 			    /* Clear color.  */
2658 			    printf ("\033[0m");
2659 			  last_color = color;
2660 			}
2661 		    }
2662 		  putchar ((i < line_buffer_size) ? line_buffer[i]: ' ');
2663 		}
2664 	    }
2665 
2666 	  if (insns)
2667 	    {
2668 	      sfile.pos = 0;
2669 	      inf->fprintf_func = (fprintf_ftype) objdump_sprintf;
2670 	      inf->stream = &sfile;
2671 	      inf->bytes_per_line = 0;
2672 	      inf->bytes_per_chunk = 0;
2673 	      inf->flags = ((disassemble_all ? DISASSEMBLE_DATA : 0)
2674 			    | (wide_output ? WIDE_OUTPUT : 0));
2675 	      if (machine)
2676 		inf->flags |= USER_SPECIFIED_MACHINE_TYPE;
2677 
2678 	      if (inf->disassembler_needs_relocs
2679 		  && (bfd_get_file_flags (aux->abfd) & EXEC_P) == 0
2680 		  && (bfd_get_file_flags (aux->abfd) & DYNAMIC) == 0
2681 		  && *relppp < relppend)
2682 		{
2683 		  bfd_signed_vma distance_to_rel;
2684 		  int insn_size = 0;
2685 		  int max_reloc_offset
2686 		    = aux->abfd->arch_info->max_reloc_offset_into_insn;
2687 
2688 		  distance_to_rel = ((**relppp)->address - rel_offset
2689 				     - addr_offset);
2690 
2691 		  if (distance_to_rel > 0
2692 		      && (max_reloc_offset < 0
2693 			  || distance_to_rel <= max_reloc_offset))
2694 		    {
2695 		      /* This reloc *might* apply to the current insn,
2696 			 starting somewhere inside it.  Discover the length
2697 			 of the current insn so that the check below will
2698 			 work.  */
2699 		      if (insn_width)
2700 			insn_size = insn_width;
2701 		      else
2702 			{
2703 			  /* We find the length by calling the dissassembler
2704 			     function with a dummy print handler.  This should
2705 			     work unless the disassembler is not expecting to
2706 			     be called multiple times for the same address.
2707 
2708 			     This does mean disassembling the instruction
2709 			     twice, but we only do this when there is a high
2710 			     probability that there is a reloc that will
2711 			     affect the instruction.  */
2712 			  inf->fprintf_func = (fprintf_ftype) null_print;
2713 			  insn_size = disassemble_fn (section->vma
2714 						      + addr_offset, inf);
2715 			  inf->fprintf_func = (fprintf_ftype) objdump_sprintf;
2716 			}
2717 		    }
2718 
2719 		  /* Check to see if the current reloc is associated with
2720 		     the instruction that we are about to disassemble.  */
2721 		  if (distance_to_rel == 0
2722 		      || (distance_to_rel > 0
2723 			  && distance_to_rel < insn_size / (int) opb))
2724 		    {
2725 		      inf->flags |= INSN_HAS_RELOC;
2726 		      aux->reloc = **relppp;
2727 		    }
2728 		}
2729 
2730 	      if (! disassemble_all
2731 		  && (section->flags & (SEC_CODE | SEC_HAS_CONTENTS))
2732 		  == (SEC_CODE | SEC_HAS_CONTENTS))
2733 		/* Set a stop_vma so that the disassembler will not read
2734 		   beyond the next symbol.  We assume that symbols appear on
2735 		   the boundaries between instructions.  We only do this when
2736 		   disassembling code of course, and when -D is in effect.  */
2737 		inf->stop_vma = section->vma + stop_offset;
2738 
2739 	      inf->stop_offset = stop_offset;
2740 	      octets = (*disassemble_fn) (section->vma + addr_offset, inf);
2741 
2742 	      inf->stop_vma = 0;
2743 	      inf->fprintf_func = (fprintf_ftype) fprintf;
2744 	      inf->stream = stdout;
2745 	      if (insn_width == 0 && inf->bytes_per_line != 0)
2746 		octets_per_line = inf->bytes_per_line;
2747 	      if (octets < (int) opb)
2748 		{
2749 		  if (sfile.pos)
2750 		    printf ("%s\n", sfile.buffer);
2751 		  if (octets >= 0)
2752 		    {
2753 		      non_fatal (_("disassemble_fn returned length %d"),
2754 				 octets);
2755 		      exit_status = 1;
2756 		    }
2757 		  break;
2758 		}
2759 	    }
2760 	  else
2761 	    {
2762 	      bfd_vma j;
2763 
2764 	      octets = octets_per_line;
2765 	      if (addr_offset + octets / opb > stop_offset)
2766 		octets = (stop_offset - addr_offset) * opb;
2767 
2768 	      for (j = addr_offset * opb; j < addr_offset * opb + octets; ++j)
2769 		{
2770 		  if (ISPRINT (data[j]))
2771 		    buf[j - addr_offset * opb] = data[j];
2772 		  else
2773 		    buf[j - addr_offset * opb] = '.';
2774 		}
2775 	      buf[j - addr_offset * opb] = '\0';
2776 	    }
2777 
2778 	  if (prefix_addresses
2779 	      ? show_raw_insn > 0
2780 	      : show_raw_insn >= 0)
2781 	    {
2782 	      bfd_vma j;
2783 
2784 	      /* If ! prefix_addresses and ! wide_output, we print
2785 		 octets_per_line octets per line.  */
2786 	      pb = octets;
2787 	      if (pb > octets_per_line && ! prefix_addresses && ! wide_output)
2788 		pb = octets_per_line;
2789 
2790 	      if (inf->bytes_per_chunk)
2791 		bpc = inf->bytes_per_chunk;
2792 	      else
2793 		bpc = 1;
2794 
2795 	      for (j = addr_offset * opb; j < addr_offset * opb + pb; j += bpc)
2796 		{
2797 		  /* PR 21580: Check for a buffer ending early.  */
2798 		  if (j + bpc <= stop_offset * opb)
2799 		    {
2800 		      int k;
2801 
2802 		      if (inf->display_endian == BFD_ENDIAN_LITTLE)
2803 			{
2804 			  for (k = bpc - 1; k >= 0; k--)
2805 			    printf ("%02x", (unsigned) data[j + k]);
2806 			}
2807 		      else
2808 			{
2809 			  for (k = 0; k < bpc; k++)
2810 			    printf ("%02x", (unsigned) data[j + k]);
2811 			}
2812 		    }
2813 		  putchar (' ');
2814 		}
2815 
2816 	      for (; pb < octets_per_line; pb += bpc)
2817 		{
2818 		  int k;
2819 
2820 		  for (k = 0; k < bpc; k++)
2821 		    printf ("  ");
2822 		  putchar (' ');
2823 		}
2824 
2825 	      /* Separate raw data from instruction by extra space.  */
2826 	      if (insns)
2827 		putchar ('\t');
2828 	      else
2829 		printf ("    ");
2830 	    }
2831 
2832 	  if (! insns)
2833 	    printf ("%s", buf);
2834 	  else if (sfile.pos)
2835 	    printf ("%s", sfile.buffer);
2836 
2837 	  if (prefix_addresses
2838 	      ? show_raw_insn > 0
2839 	      : show_raw_insn >= 0)
2840 	    {
2841 	      while (pb < octets)
2842 		{
2843 		  bfd_vma j;
2844 		  char *s;
2845 
2846 		  putchar ('\n');
2847 		  j = addr_offset * opb + pb;
2848 
2849 		  bfd_sprintf_vma (aux->abfd, buf, section->vma + j / opb);
2850 		  for (s = buf + skip_addr_chars; *s == '0'; s++)
2851 		    *s = ' ';
2852 		  if (*s == '\0')
2853 		    *--s = '0';
2854 		  printf ("%s:\t", buf + skip_addr_chars);
2855 
2856 		  pb += octets_per_line;
2857 		  if (pb > octets)
2858 		    pb = octets;
2859 		  for (; j < addr_offset * opb + pb; j += bpc)
2860 		    {
2861 		      /* PR 21619: Check for a buffer ending early.  */
2862 		      if (j + bpc <= stop_offset * opb)
2863 			{
2864 			  int k;
2865 
2866 			  if (inf->display_endian == BFD_ENDIAN_LITTLE)
2867 			    {
2868 			      for (k = bpc - 1; k >= 0; k--)
2869 				printf ("%02x", (unsigned) data[j + k]);
2870 			    }
2871 			  else
2872 			    {
2873 			      for (k = 0; k < bpc; k++)
2874 				printf ("%02x", (unsigned) data[j + k]);
2875 			    }
2876 			}
2877 		      putchar (' ');
2878 		    }
2879 		}
2880 	    }
2881 
2882 	  if (!wide_output)
2883 	    putchar ('\n');
2884 	  else
2885 	    need_nl = TRUE;
2886 	}
2887 
2888       while ((*relppp) < relppend
2889 	     && (**relppp)->address < rel_offset + addr_offset + octets / opb)
2890 	{
2891 	  if (dump_reloc_info || dump_dynamic_reloc_info)
2892 	    {
2893 	      arelent *q;
2894 
2895 	      q = **relppp;
2896 
2897 	      if (wide_output)
2898 		putchar ('\t');
2899 	      else
2900 		printf ("\t\t\t");
2901 
2902 	      objdump_print_value (section->vma - rel_offset + q->address,
2903 				   inf, TRUE);
2904 
2905 	      if (q->howto == NULL)
2906 		printf (": *unknown*\t");
2907 	      else if (q->howto->name)
2908 		printf (": %s\t", q->howto->name);
2909 	      else
2910 		printf (": %d\t", q->howto->type);
2911 
2912 	      if (q->sym_ptr_ptr == NULL || *q->sym_ptr_ptr == NULL)
2913 		printf ("*unknown*");
2914 	      else
2915 		{
2916 		  const char *sym_name;
2917 
2918 		  sym_name = bfd_asymbol_name (*q->sym_ptr_ptr);
2919 		  if (sym_name != NULL && *sym_name != '\0')
2920 		    objdump_print_symname (aux->abfd, inf, *q->sym_ptr_ptr);
2921 		  else
2922 		    {
2923 		      asection *sym_sec;
2924 
2925 		      sym_sec = bfd_asymbol_section (*q->sym_ptr_ptr);
2926 		      sym_name = bfd_section_name (sym_sec);
2927 		      if (sym_name == NULL || *sym_name == '\0')
2928 			sym_name = "*unknown*";
2929 		      printf ("%s", sanitize_string (sym_name));
2930 		    }
2931 		}
2932 
2933 	      if (q->addend)
2934 		{
2935 		  bfd_signed_vma addend = q->addend;
2936 		  if (addend < 0)
2937 		    {
2938 		      printf ("-0x");
2939 		      addend = -addend;
2940 		    }
2941 		  else
2942 		    printf ("+0x");
2943 		  objdump_print_value (addend, inf, TRUE);
2944 		}
2945 
2946 	      printf ("\n");
2947 	      need_nl = FALSE;
2948 	    }
2949 	  ++(*relppp);
2950 	}
2951 
2952       if (need_nl)
2953 	printf ("\n");
2954 
2955       addr_offset += octets / opb;
2956     }
2957 
2958   free (sfile.buffer);
2959   free (line_buffer);
2960   free (color_buffer);
2961 }
2962 
2963 static void
2964 disassemble_section (bfd *abfd, asection *section, void *inf)
2965 {
2966   const struct elf_backend_data * bed;
2967   bfd_vma                      sign_adjust = 0;
2968   struct disassemble_info *    pinfo = (struct disassemble_info *) inf;
2969   struct objdump_disasm_info * paux;
2970   unsigned int                 opb = pinfo->octets_per_byte;
2971   bfd_byte *                   data = NULL;
2972   bfd_size_type                datasize = 0;
2973   arelent **                   rel_pp = NULL;
2974   arelent **                   rel_ppstart = NULL;
2975   arelent **                   rel_ppend;
2976   bfd_vma                      stop_offset;
2977   asymbol *                    sym = NULL;
2978   long                         place = 0;
2979   long                         rel_count;
2980   bfd_vma                      rel_offset;
2981   unsigned long                addr_offset;
2982   bfd_boolean                  do_print;
2983   enum loop_control
2984   {
2985    stop_offset_reached,
2986    function_sym,
2987    next_sym
2988   } loop_until;
2989 
2990   /* Sections that do not contain machine
2991      code are not normally disassembled.  */
2992   if (! disassemble_all
2993       && only_list == NULL
2994       && ((section->flags & (SEC_CODE | SEC_HAS_CONTENTS))
2995 	  != (SEC_CODE | SEC_HAS_CONTENTS)))
2996     return;
2997 
2998   if (! process_section_p (section))
2999     return;
3000 
3001   datasize = bfd_section_size (section);
3002   if (datasize == 0)
3003     return;
3004 
3005   if (start_address == (bfd_vma) -1
3006       || start_address < section->vma)
3007     addr_offset = 0;
3008   else
3009     addr_offset = start_address - section->vma;
3010 
3011   if (stop_address == (bfd_vma) -1)
3012     stop_offset = datasize / opb;
3013   else
3014     {
3015       if (stop_address < section->vma)
3016 	stop_offset = 0;
3017       else
3018 	stop_offset = stop_address - section->vma;
3019       if (stop_offset > datasize / opb)
3020 	stop_offset = datasize / opb;
3021     }
3022 
3023   if (addr_offset >= stop_offset)
3024     return;
3025 
3026   /* Decide which set of relocs to use.  Load them if necessary.  */
3027   paux = (struct objdump_disasm_info *) pinfo->application_data;
3028   if (paux->dynrelbuf && dump_dynamic_reloc_info)
3029     {
3030       rel_pp = paux->dynrelbuf;
3031       rel_count = paux->dynrelcount;
3032       /* Dynamic reloc addresses are absolute, non-dynamic are section
3033 	 relative.  REL_OFFSET specifies the reloc address corresponding
3034 	 to the start of this section.  */
3035       rel_offset = section->vma;
3036     }
3037   else
3038     {
3039       rel_count = 0;
3040       rel_pp = NULL;
3041       rel_offset = 0;
3042 
3043       if ((section->flags & SEC_RELOC) != 0
3044 	  && (dump_reloc_info || pinfo->disassembler_needs_relocs))
3045 	{
3046 	  long relsize;
3047 
3048 	  relsize = bfd_get_reloc_upper_bound (abfd, section);
3049 	  if (relsize < 0)
3050 	    bfd_fatal (bfd_get_filename (abfd));
3051 
3052 	  if (relsize > 0)
3053 	    {
3054 	      rel_ppstart = rel_pp = (arelent **) xmalloc (relsize);
3055 	      rel_count = bfd_canonicalize_reloc (abfd, section, rel_pp, syms);
3056 	      if (rel_count < 0)
3057 		bfd_fatal (bfd_get_filename (abfd));
3058 
3059 	      /* Sort the relocs by address.  */
3060 	      qsort (rel_pp, rel_count, sizeof (arelent *), compare_relocs);
3061 	    }
3062 	}
3063     }
3064   rel_ppend = rel_pp + rel_count;
3065 
3066   if (!bfd_malloc_and_get_section (abfd, section, &data))
3067     {
3068       non_fatal (_("Reading section %s failed because: %s"),
3069 		 section->name, bfd_errmsg (bfd_get_error ()));
3070       return;
3071     }
3072 
3073   pinfo->buffer = data;
3074   pinfo->buffer_vma = section->vma;
3075   pinfo->buffer_length = datasize;
3076   pinfo->section = section;
3077 
3078   /* Sort the symbols into value and section order.  */
3079   compare_section = section;
3080   qsort (sorted_syms, sorted_symcount, sizeof (asymbol *), compare_symbols);
3081 
3082   /* Skip over the relocs belonging to addresses below the
3083      start address.  */
3084   while (rel_pp < rel_ppend
3085 	 && (*rel_pp)->address < rel_offset + addr_offset)
3086     ++rel_pp;
3087 
3088   printf (_("\nDisassembly of section %s:\n"), sanitize_string (section->name));
3089 
3090   /* Find the nearest symbol forwards from our current position.  */
3091   paux->require_sec = TRUE;
3092   sym = (asymbol *) find_symbol_for_address (section->vma + addr_offset,
3093                                              (struct disassemble_info *) inf,
3094                                              &place);
3095   paux->require_sec = FALSE;
3096 
3097   /* PR 9774: If the target used signed addresses then we must make
3098      sure that we sign extend the value that we calculate for 'addr'
3099      in the loop below.  */
3100   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
3101       && (bed = get_elf_backend_data (abfd)) != NULL
3102       && bed->sign_extend_vma)
3103     sign_adjust = (bfd_vma) 1 << (bed->s->arch_size - 1);
3104 
3105   /* Disassemble a block of instructions up to the address associated with
3106      the symbol we have just found.  Then print the symbol and find the
3107      next symbol on.  Repeat until we have disassembled the entire section
3108      or we have reached the end of the address range we are interested in.  */
3109   do_print = paux->symbol == NULL;
3110   loop_until = stop_offset_reached;
3111 
3112   while (addr_offset < stop_offset)
3113     {
3114       bfd_vma addr;
3115       asymbol *nextsym;
3116       bfd_vma nextstop_offset;
3117       bfd_boolean insns;
3118 
3119       addr = section->vma + addr_offset;
3120       addr = ((addr & ((sign_adjust << 1) - 1)) ^ sign_adjust) - sign_adjust;
3121 
3122       if (sym != NULL && bfd_asymbol_value (sym) <= addr)
3123 	{
3124 	  int x;
3125 
3126 	  for (x = place;
3127 	       (x < sorted_symcount
3128 		&& (bfd_asymbol_value (sorted_syms[x]) <= addr));
3129 	       ++x)
3130 	    continue;
3131 
3132 	  pinfo->symbols = sorted_syms + place;
3133 	  pinfo->num_symbols = x - place;
3134 	  pinfo->symtab_pos = place;
3135 	}
3136       else
3137 	{
3138 	  pinfo->symbols = NULL;
3139 	  pinfo->num_symbols = 0;
3140 	  pinfo->symtab_pos = -1;
3141 	}
3142 
3143       /* If we are only disassembling from a specific symbol,
3144 	 check to see if we should start or stop displaying.  */
3145       if (sym && paux->symbol)
3146 	{
3147 	  if (do_print)
3148 	    {
3149 	      /* See if we should stop printing.  */
3150 	      switch (loop_until)
3151 		{
3152 		case function_sym:
3153 		  if (sym->flags & BSF_FUNCTION)
3154 		    do_print = FALSE;
3155 		  break;
3156 
3157 		case stop_offset_reached:
3158 		  /* Handled by the while loop.  */
3159 		  break;
3160 
3161 		case next_sym:
3162 		  /* FIXME: There is an implicit assumption here
3163 		     that the name of sym is different from
3164 		     paux->symbol.  */
3165 		  if (! bfd_is_local_label (abfd, sym))
3166 		    do_print = FALSE;
3167 		  break;
3168 		}
3169 	    }
3170 	  else
3171 	    {
3172 	      const char * name = bfd_asymbol_name (sym);
3173 	      char * alloc = NULL;
3174 
3175 	      if (do_demangle && name[0] != '\0')
3176 		{
3177 		  /* Demangle the name.  */
3178 		  alloc = bfd_demangle (abfd, name, demangle_flags);
3179 		  if (alloc != NULL)
3180 		    name = alloc;
3181 		}
3182 
3183 	      /* We are not currently printing.  Check to see
3184 		 if the current symbol matches the requested symbol.  */
3185 	      if (streq (name, paux->symbol))
3186 		{
3187 		  do_print = TRUE;
3188 
3189 		  if (sym->flags & BSF_FUNCTION)
3190 		    {
3191 		      if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
3192 			  && ((elf_symbol_type *) sym)->internal_elf_sym.st_size > 0)
3193 			{
3194 			  /* Sym is a function symbol with a size associated
3195 			     with it.  Turn on automatic disassembly for the
3196 			     next VALUE bytes.  */
3197 			  stop_offset = addr_offset
3198 			    + ((elf_symbol_type *) sym)->internal_elf_sym.st_size;
3199 			  loop_until = stop_offset_reached;
3200 			}
3201 		      else
3202 			{
3203 			  /* Otherwise we need to tell the loop heuristic to
3204 			     loop until the next function symbol is encountered.  */
3205 			  loop_until = function_sym;
3206 			}
3207 		    }
3208 		  else
3209 		    {
3210 		      /* Otherwise loop until the next symbol is encountered.  */
3211 		      loop_until = next_sym;
3212 		    }
3213 		}
3214 
3215 	      free (alloc);
3216 	    }
3217 	}
3218 
3219       if (! prefix_addresses && do_print)
3220 	{
3221 	  pinfo->fprintf_func (pinfo->stream, "\n");
3222 	  objdump_print_addr_with_sym (abfd, section, sym, addr,
3223 				       pinfo, FALSE);
3224 	  pinfo->fprintf_func (pinfo->stream, ":\n");
3225 	}
3226 
3227       if (sym != NULL && bfd_asymbol_value (sym) > addr)
3228 	nextsym = sym;
3229       else if (sym == NULL)
3230 	nextsym = NULL;
3231       else
3232 	{
3233 #define is_valid_next_sym(SYM) \
3234   (strcmp (bfd_section_name ((SYM)->section), bfd_section_name (section)) == 0 \
3235    && (bfd_asymbol_value (SYM) > bfd_asymbol_value (sym)) \
3236    && pinfo->symbol_is_valid (SYM, pinfo))
3237 
3238 	  /* Search forward for the next appropriate symbol in
3239 	     SECTION.  Note that all the symbols are sorted
3240 	     together into one big array, and that some sections
3241 	     may have overlapping addresses.  */
3242 	  while (place < sorted_symcount
3243 		 && ! is_valid_next_sym (sorted_syms [place]))
3244 	    ++place;
3245 
3246 	  if (place >= sorted_symcount)
3247 	    nextsym = NULL;
3248 	  else
3249 	    nextsym = sorted_syms[place];
3250 	}
3251 
3252       if (sym != NULL && bfd_asymbol_value (sym) > addr)
3253 	nextstop_offset = bfd_asymbol_value (sym) - section->vma;
3254       else if (nextsym == NULL)
3255 	nextstop_offset = stop_offset;
3256       else
3257 	nextstop_offset = bfd_asymbol_value (nextsym) - section->vma;
3258 
3259       if (nextstop_offset > stop_offset
3260 	  || nextstop_offset <= addr_offset)
3261 	nextstop_offset = stop_offset;
3262 
3263       /* If a symbol is explicitly marked as being an object
3264 	 rather than a function, just dump the bytes without
3265 	 disassembling them.  */
3266       if (disassemble_all
3267 	  || sym == NULL
3268 	  || sym->section != section
3269 	  || bfd_asymbol_value (sym) > addr
3270 	  || ((sym->flags & BSF_OBJECT) == 0
3271 	      && (strstr (bfd_asymbol_name (sym), "gnu_compiled")
3272 		  == NULL)
3273 	      && (strstr (bfd_asymbol_name (sym), "gcc2_compiled")
3274 		  == NULL))
3275 	  || (sym->flags & BSF_FUNCTION) != 0)
3276 	insns = TRUE;
3277       else
3278 	insns = FALSE;
3279 
3280       if (do_print)
3281 	{
3282 	  /* Resolve symbol name.  */
3283 	  if (visualize_jumps && abfd && sym && sym->name)
3284 	    {
3285 	      struct disassemble_info di;
3286 	      SFILE sf;
3287 
3288 	      sf.alloc = strlen (sym->name) + 40;
3289 	      sf.buffer = (char*) xmalloc (sf.alloc);
3290 	      sf.pos = 0;
3291 	      di.fprintf_func = (fprintf_ftype) objdump_sprintf;
3292 	      di.stream = &sf;
3293 
3294 	      objdump_print_symname (abfd, &di, sym);
3295 
3296 	      /* Fetch jump information.  */
3297 	      detected_jumps = disassemble_jumps
3298 		(pinfo, paux->disassemble_fn,
3299 		 addr_offset, nextstop_offset,
3300 		 rel_offset, &rel_pp, rel_ppend);
3301 
3302 	      /* Free symbol name.  */
3303 	      free (sf.buffer);
3304 	    }
3305 
3306 	  /* Add jumps to output.  */
3307 	  disassemble_bytes (pinfo, paux->disassemble_fn, insns, data,
3308 			     addr_offset, nextstop_offset,
3309 			     rel_offset, &rel_pp, rel_ppend);
3310 
3311 	  /* Free jumps.  */
3312 	  while (detected_jumps)
3313 	    {
3314 	      detected_jumps = jump_info_free (detected_jumps);
3315 	    }
3316 	}
3317 
3318       addr_offset = nextstop_offset;
3319       sym = nextsym;
3320     }
3321 
3322   free (data);
3323 
3324   if (rel_ppstart != NULL)
3325     free (rel_ppstart);
3326 }
3327 
3328 /* Disassemble the contents of an object file.  */
3329 
3330 static void
3331 disassemble_data (bfd *abfd)
3332 {
3333   struct disassemble_info disasm_info;
3334   struct objdump_disasm_info aux;
3335   long i;
3336 
3337   print_files = NULL;
3338   prev_functionname = NULL;
3339   prev_line = -1;
3340   prev_discriminator = 0;
3341 
3342   /* We make a copy of syms to sort.  We don't want to sort syms
3343      because that will screw up the relocs.  */
3344   sorted_symcount = symcount ? symcount : dynsymcount;
3345   sorted_syms = (asymbol **) xmalloc ((sorted_symcount + synthcount)
3346                                       * sizeof (asymbol *));
3347   memcpy (sorted_syms, symcount ? syms : dynsyms,
3348 	  sorted_symcount * sizeof (asymbol *));
3349 
3350   sorted_symcount = remove_useless_symbols (sorted_syms, sorted_symcount);
3351 
3352   for (i = 0; i < synthcount; ++i)
3353     {
3354       sorted_syms[sorted_symcount] = synthsyms + i;
3355       ++sorted_symcount;
3356     }
3357 
3358   init_disassemble_info (&disasm_info, stdout, (fprintf_ftype) fprintf);
3359 
3360   disasm_info.application_data = (void *) &aux;
3361   aux.abfd = abfd;
3362   aux.require_sec = FALSE;
3363   aux.dynrelbuf = NULL;
3364   aux.dynrelcount = 0;
3365   aux.reloc = NULL;
3366   aux.symbol = disasm_sym;
3367 
3368   disasm_info.print_address_func = objdump_print_address;
3369   disasm_info.symbol_at_address_func = objdump_symbol_at_address;
3370 
3371   if (machine != NULL)
3372     {
3373       const bfd_arch_info_type *inf = bfd_scan_arch (machine);
3374 
3375       if (inf == NULL)
3376 	fatal (_("can't use supplied machine %s"), machine);
3377 
3378       abfd->arch_info = inf;
3379     }
3380 
3381   if (endian != BFD_ENDIAN_UNKNOWN)
3382     {
3383       struct bfd_target *xvec;
3384 
3385       xvec = (struct bfd_target *) xmalloc (sizeof (struct bfd_target));
3386       memcpy (xvec, abfd->xvec, sizeof (struct bfd_target));
3387       xvec->byteorder = endian;
3388       abfd->xvec = xvec;
3389     }
3390 
3391   /* Use libopcodes to locate a suitable disassembler.  */
3392   aux.disassemble_fn = disassembler (bfd_get_arch (abfd),
3393 				     bfd_big_endian (abfd),
3394 				     bfd_get_mach (abfd), abfd);
3395   if (!aux.disassemble_fn)
3396     {
3397       non_fatal (_("can't disassemble for architecture %s\n"),
3398 		 bfd_printable_arch_mach (bfd_get_arch (abfd), 0));
3399       exit_status = 1;
3400       return;
3401     }
3402 
3403   disasm_info.flavour = bfd_get_flavour (abfd);
3404   disasm_info.arch = bfd_get_arch (abfd);
3405   disasm_info.mach = bfd_get_mach (abfd);
3406   disasm_info.disassembler_options = disassembler_options;
3407   disasm_info.octets_per_byte = bfd_octets_per_byte (abfd, NULL);
3408   disasm_info.skip_zeroes = DEFAULT_SKIP_ZEROES;
3409   disasm_info.skip_zeroes_at_end = DEFAULT_SKIP_ZEROES_AT_END;
3410   disasm_info.disassembler_needs_relocs = FALSE;
3411 
3412   if (bfd_big_endian (abfd))
3413     disasm_info.display_endian = disasm_info.endian = BFD_ENDIAN_BIG;
3414   else if (bfd_little_endian (abfd))
3415     disasm_info.display_endian = disasm_info.endian = BFD_ENDIAN_LITTLE;
3416   else
3417     /* ??? Aborting here seems too drastic.  We could default to big or little
3418        instead.  */
3419     disasm_info.endian = BFD_ENDIAN_UNKNOWN;
3420 
3421   /* Allow the target to customize the info structure.  */
3422   disassemble_init_for_target (& disasm_info);
3423 
3424   /* Pre-load the dynamic relocs as we may need them during the disassembly.  */
3425     {
3426       long relsize = bfd_get_dynamic_reloc_upper_bound (abfd);
3427 
3428       if (relsize < 0 && dump_dynamic_reloc_info)
3429 	bfd_fatal (bfd_get_filename (abfd));
3430 
3431       if (relsize > 0)
3432 	{
3433 	  aux.dynrelbuf = (arelent **) xmalloc (relsize);
3434 	  aux.dynrelcount = bfd_canonicalize_dynamic_reloc (abfd,
3435 							    aux.dynrelbuf,
3436 							    dynsyms);
3437 	  if (aux.dynrelcount < 0)
3438 	    bfd_fatal (bfd_get_filename (abfd));
3439 
3440 	  /* Sort the relocs by address.  */
3441 	  qsort (aux.dynrelbuf, aux.dynrelcount, sizeof (arelent *),
3442 		 compare_relocs);
3443 	}
3444     }
3445   disasm_info.symtab = sorted_syms;
3446   disasm_info.symtab_size = sorted_symcount;
3447 
3448   bfd_map_over_sections (abfd, disassemble_section, & disasm_info);
3449 
3450   if (aux.dynrelbuf != NULL)
3451     free (aux.dynrelbuf);
3452   free (sorted_syms);
3453   disassemble_free_target (&disasm_info);
3454 }
3455 
3456 static bfd_boolean
3457 load_specific_debug_section (enum dwarf_section_display_enum debug,
3458 			     asection *sec, void *file)
3459 {
3460   struct dwarf_section *section = &debug_displays [debug].section;
3461   bfd *abfd = (bfd *) file;
3462   bfd_byte *contents;
3463   bfd_size_type amt;
3464   size_t alloced;
3465 
3466   if (section->start != NULL)
3467     {
3468       /* If it is already loaded, do nothing.  */
3469       if (streq (section->filename, bfd_get_filename (abfd)))
3470 	return TRUE;
3471       free (section->start);
3472     }
3473 
3474   section->filename = bfd_get_filename (abfd);
3475   section->reloc_info = NULL;
3476   section->num_relocs = 0;
3477   section->address = bfd_section_vma (sec);
3478   section->user_data = sec;
3479   section->size = bfd_section_size (sec);
3480   /* PR 24360: On 32-bit hosts sizeof (size_t) < sizeof (bfd_size_type). */
3481   alloced = amt = section->size + 1;
3482   if (alloced != amt || alloced == 0)
3483     {
3484       section->start = NULL;
3485       free_debug_section (debug);
3486       printf (_("\nSection '%s' has an invalid size: %#llx.\n"),
3487 	      sanitize_string (section->name),
3488 	      (unsigned long long) section->size);
3489       return FALSE;
3490     }
3491   section->start = contents = malloc (alloced);
3492   if (section->start == NULL
3493       || !bfd_get_full_section_contents (abfd, sec, &contents))
3494     {
3495       free_debug_section (debug);
3496       printf (_("\nCan't get contents for section '%s'.\n"),
3497 	      sanitize_string (section->name));
3498       return FALSE;
3499     }
3500   /* Ensure any string section has a terminating NUL.  */
3501   section->start[section->size] = 0;
3502 
3503   if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0
3504       && debug_displays [debug].relocate)
3505     {
3506       long         reloc_size;
3507       bfd_boolean  ret;
3508 
3509       bfd_cache_section_contents (sec, section->start);
3510 
3511       ret = bfd_simple_get_relocated_section_contents (abfd,
3512 						       sec,
3513 						       section->start,
3514 						       syms) != NULL;
3515 
3516       if (! ret)
3517         {
3518           free_debug_section (debug);
3519           printf (_("\nCan't get contents for section '%s'.\n"),
3520 	          sanitize_string (section->name));
3521           return FALSE;
3522         }
3523 
3524       reloc_size = bfd_get_reloc_upper_bound (abfd, sec);
3525       if (reloc_size > 0)
3526 	{
3527 	  unsigned long reloc_count;
3528 	  arelent **relocs;
3529 
3530 	  relocs = (arelent **) xmalloc (reloc_size);
3531 
3532 	  reloc_count = bfd_canonicalize_reloc (abfd, sec, relocs, NULL);
3533 	  if (reloc_count == 0)
3534 	    free (relocs);
3535 	  else
3536 	    {
3537 	      section->reloc_info = relocs;
3538 	      section->num_relocs = reloc_count;
3539 	    }
3540 	}
3541     }
3542 
3543   return TRUE;
3544 }
3545 
3546 bfd_boolean
3547 reloc_at (struct dwarf_section * dsec, dwarf_vma offset)
3548 {
3549   arelent ** relocs;
3550   arelent * rp;
3551 
3552   if (dsec == NULL || dsec->reloc_info == NULL)
3553     return FALSE;
3554 
3555   relocs = (arelent **) dsec->reloc_info;
3556 
3557   for (; (rp = * relocs) != NULL; ++ relocs)
3558     if (rp->address == offset)
3559       return TRUE;
3560 
3561   return FALSE;
3562 }
3563 
3564 bfd_boolean
3565 load_debug_section (enum dwarf_section_display_enum debug, void *file)
3566 {
3567   struct dwarf_section *section = &debug_displays [debug].section;
3568   bfd *abfd = (bfd *) file;
3569   asection *sec;
3570 
3571   /* If it is already loaded, do nothing.  */
3572   if (section->start != NULL)
3573     {
3574       if (streq (section->filename, bfd_get_filename (abfd)))
3575 	return TRUE;
3576     }
3577 
3578   /* Locate the debug section.  */
3579   sec = bfd_get_section_by_name (abfd, section->uncompressed_name);
3580   if (sec != NULL)
3581     section->name = section->uncompressed_name;
3582   else
3583     {
3584       sec = bfd_get_section_by_name (abfd, section->compressed_name);
3585       if (sec != NULL)
3586         section->name = section->compressed_name;
3587     }
3588   if (sec == NULL)
3589     return FALSE;
3590 
3591   return load_specific_debug_section (debug, sec, file);
3592 }
3593 
3594 void
3595 free_debug_section (enum dwarf_section_display_enum debug)
3596 {
3597   struct dwarf_section *section = &debug_displays [debug].section;
3598 
3599   if (section->start == NULL)
3600     return;
3601 
3602   /* PR 17512: file: 0f67f69d.  */
3603   if (section->user_data != NULL)
3604     {
3605       asection * sec = (asection *) section->user_data;
3606 
3607       /* If we are freeing contents that are also pointed to by the BFD
3608 	 library's section structure then make sure to update those pointers
3609 	 too.  Otherwise, the next time we try to load data for this section
3610 	 we can end up using a stale pointer.  */
3611       if (section->start == sec->contents)
3612 	{
3613 	  sec->contents = NULL;
3614 	  sec->flags &= ~ SEC_IN_MEMORY;
3615 	  sec->compress_status = COMPRESS_SECTION_NONE;
3616 	}
3617     }
3618 
3619   free ((char *) section->start);
3620   section->start = NULL;
3621   section->address = 0;
3622   section->size = 0;
3623 }
3624 
3625 void
3626 close_debug_file (void * file)
3627 {
3628   bfd * abfd = (bfd *) file;
3629 
3630   bfd_close (abfd);
3631 }
3632 
3633 void *
3634 open_debug_file (const char * pathname)
3635 {
3636   bfd * data;
3637 
3638   data = bfd_openr (pathname, NULL);
3639   if (data == NULL)
3640     return NULL;
3641 
3642   if (! bfd_check_format (data, bfd_object))
3643     return NULL;
3644 
3645   return data;
3646 }
3647 
3648 #if HAVE_LIBDEBUGINFOD
3649 /* Return a hex string represention of the build-id.  */
3650 
3651 unsigned char *
3652 get_build_id (void * data)
3653 {
3654   unsigned i;
3655   char * build_id_str;
3656   bfd * abfd = (bfd *) data;
3657   const struct bfd_build_id * build_id;
3658 
3659   build_id = abfd->build_id;
3660   if (build_id == NULL)
3661     return NULL;
3662 
3663   build_id_str = malloc (build_id->size * 2 + 1);
3664   if (build_id_str == NULL)
3665     return NULL;
3666 
3667   for (i = 0; i < build_id->size; i++)
3668     sprintf (build_id_str + (i * 2), "%02x", build_id->data[i]);
3669   build_id_str[build_id->size * 2] = '\0';
3670 
3671   return (unsigned char *)build_id_str;
3672 }
3673 #endif /* HAVE_LIBDEBUGINFOD */
3674 
3675 static void
3676 dump_dwarf_section (bfd *abfd, asection *section,
3677 		    void *arg ATTRIBUTE_UNUSED)
3678 {
3679   const char *name = bfd_section_name (section);
3680   const char *match;
3681   int i;
3682 
3683   if (CONST_STRNEQ (name, ".gnu.linkonce.wi."))
3684     match = ".debug_info";
3685   else
3686     match = name;
3687 
3688   for (i = 0; i < max; i++)
3689     if ((strcmp (debug_displays [i].section.uncompressed_name, match) == 0
3690 	 || strcmp (debug_displays [i].section.compressed_name, match) == 0)
3691 	&& debug_displays [i].enabled != NULL
3692 	&& *debug_displays [i].enabled)
3693       {
3694 	struct dwarf_section *sec = &debug_displays [i].section;
3695 
3696 	if (strcmp (sec->uncompressed_name, match) == 0)
3697 	  sec->name = sec->uncompressed_name;
3698 	else
3699 	  sec->name = sec->compressed_name;
3700 	if (load_specific_debug_section ((enum dwarf_section_display_enum) i,
3701                                          section, abfd))
3702 	  {
3703 	    debug_displays [i].display (sec, abfd);
3704 
3705 	    if (i != info && i != abbrev)
3706 	      free_debug_section ((enum dwarf_section_display_enum) i);
3707 	  }
3708 	break;
3709       }
3710 }
3711 
3712 /* Dump the dwarf debugging information.  */
3713 
3714 static void
3715 dump_dwarf (bfd *abfd)
3716 {
3717   /* The byte_get pointer should have been set at the start of dump_bfd().  */
3718   if (byte_get == NULL)
3719     {
3720       warn (_("File %s does not contain any dwarf debug information\n"),
3721 	    bfd_get_filename (abfd));
3722       return;
3723     }
3724 
3725   switch (bfd_get_arch (abfd))
3726     {
3727     case bfd_arch_s12z:
3728       /* S12Z has a 24 bit address space.  But the only known
3729 	 producer of dwarf_info encodes addresses into 32 bits.  */
3730       eh_addr_size = 4;
3731       break;
3732 
3733     default:
3734       eh_addr_size = bfd_arch_bits_per_address (abfd) / 8;
3735       break;
3736     }
3737 
3738   init_dwarf_regnames_by_bfd_arch_and_mach (bfd_get_arch (abfd),
3739 					    bfd_get_mach (abfd));
3740 
3741   bfd_map_over_sections (abfd, dump_dwarf_section, NULL);
3742 }
3743 
3744 /* Read ABFD's stabs section STABSECT_NAME, and return a pointer to
3745    it.  Return NULL on failure.   */
3746 
3747 static bfd_byte *
3748 read_section_stabs (bfd *abfd, const char *sect_name, bfd_size_type *size_ptr,
3749 		    bfd_size_type *entsize_ptr)
3750 {
3751   asection *stabsect;
3752   bfd_byte *contents;
3753 
3754   stabsect = bfd_get_section_by_name (abfd, sect_name);
3755   if (stabsect == NULL)
3756     {
3757       printf (_("No %s section present\n\n"),
3758 	      sanitize_string (sect_name));
3759       return FALSE;
3760     }
3761 
3762   if (!bfd_malloc_and_get_section (abfd, stabsect, &contents))
3763     {
3764       non_fatal (_("reading %s section of %s failed: %s"),
3765 		 sect_name, bfd_get_filename (abfd),
3766 		 bfd_errmsg (bfd_get_error ()));
3767       exit_status = 1;
3768       free (contents);
3769       return NULL;
3770     }
3771 
3772   *size_ptr = bfd_section_size (stabsect);
3773   if (entsize_ptr)
3774     *entsize_ptr = stabsect->entsize;
3775 
3776   return contents;
3777 }
3778 
3779 /* Stabs entries use a 12 byte format:
3780      4 byte string table index
3781      1 byte stab type
3782      1 byte stab other field
3783      2 byte stab desc field
3784      4 byte stab value
3785    FIXME: This will have to change for a 64 bit object format.  */
3786 
3787 #define STRDXOFF  (0)
3788 #define TYPEOFF   (4)
3789 #define OTHEROFF  (5)
3790 #define DESCOFF   (6)
3791 #define VALOFF    (8)
3792 #define STABSIZE (12)
3793 
3794 /* Print ABFD's stabs section STABSECT_NAME (in `stabs'),
3795    using string table section STRSECT_NAME (in `strtab').  */
3796 
3797 static void
3798 print_section_stabs (bfd *abfd,
3799 		     const char *stabsect_name,
3800 		     unsigned *string_offset_ptr)
3801 {
3802   int i;
3803   unsigned file_string_table_offset = 0;
3804   unsigned next_file_string_table_offset = *string_offset_ptr;
3805   bfd_byte *stabp, *stabs_end;
3806 
3807   stabp = stabs;
3808   stabs_end = stabp + stab_size;
3809 
3810   printf (_("Contents of %s section:\n\n"), sanitize_string (stabsect_name));
3811   printf ("Symnum n_type n_othr n_desc n_value  n_strx String\n");
3812 
3813   /* Loop through all symbols and print them.
3814 
3815      We start the index at -1 because there is a dummy symbol on
3816      the front of stabs-in-{coff,elf} sections that supplies sizes.  */
3817   for (i = -1; stabp <= stabs_end - STABSIZE; stabp += STABSIZE, i++)
3818     {
3819       const char *name;
3820       unsigned long strx;
3821       unsigned char type, other;
3822       unsigned short desc;
3823       bfd_vma value;
3824 
3825       strx = bfd_h_get_32 (abfd, stabp + STRDXOFF);
3826       type = bfd_h_get_8 (abfd, stabp + TYPEOFF);
3827       other = bfd_h_get_8 (abfd, stabp + OTHEROFF);
3828       desc = bfd_h_get_16 (abfd, stabp + DESCOFF);
3829       value = bfd_h_get_32 (abfd, stabp + VALOFF);
3830 
3831       printf ("\n%-6d ", i);
3832       /* Either print the stab name, or, if unnamed, print its number
3833 	 again (makes consistent formatting for tools like awk).  */
3834       name = bfd_get_stab_name (type);
3835       if (name != NULL)
3836 	printf ("%-6s", sanitize_string (name));
3837       else if (type == N_UNDF)
3838 	printf ("HdrSym");
3839       else
3840 	printf ("%-6d", type);
3841       printf (" %-6d %-6d ", other, desc);
3842       bfd_printf_vma (abfd, value);
3843       printf (" %-6lu", strx);
3844 
3845       /* Symbols with type == 0 (N_UNDF) specify the length of the
3846 	 string table associated with this file.  We use that info
3847 	 to know how to relocate the *next* file's string table indices.  */
3848       if (type == N_UNDF)
3849 	{
3850 	  file_string_table_offset = next_file_string_table_offset;
3851 	  next_file_string_table_offset += value;
3852 	}
3853       else
3854 	{
3855 	  bfd_size_type amt = strx + file_string_table_offset;
3856 
3857 	  /* Using the (possibly updated) string table offset, print the
3858 	     string (if any) associated with this symbol.  */
3859 	  if (amt < stabstr_size)
3860 	    /* PR 17512: file: 079-79389-0.001:0.1.
3861 	       FIXME: May need to sanitize this string before displaying.  */
3862 	    printf (" %.*s", (int)(stabstr_size - amt), strtab + amt);
3863 	  else
3864 	    printf (" *");
3865 	}
3866     }
3867   printf ("\n\n");
3868   *string_offset_ptr = next_file_string_table_offset;
3869 }
3870 
3871 typedef struct
3872 {
3873   const char * section_name;
3874   const char * string_section_name;
3875   unsigned string_offset;
3876 }
3877 stab_section_names;
3878 
3879 static void
3880 find_stabs_section (bfd *abfd, asection *section, void *names)
3881 {
3882   int len;
3883   stab_section_names * sought = (stab_section_names *) names;
3884 
3885   /* Check for section names for which stabsect_name is a prefix, to
3886      handle .stab.N, etc.  */
3887   len = strlen (sought->section_name);
3888 
3889   /* If the prefix matches, and the files section name ends with a
3890      nul or a digit, then we match.  I.e., we want either an exact
3891      match or a section followed by a number.  */
3892   if (strncmp (sought->section_name, section->name, len) == 0
3893       && (section->name[len] == 0
3894 	  || (section->name[len] == '.' && ISDIGIT (section->name[len + 1]))))
3895     {
3896       if (strtab == NULL)
3897 	strtab = read_section_stabs (abfd, sought->string_section_name,
3898 				     &stabstr_size, NULL);
3899 
3900       if (strtab)
3901 	{
3902 	  stabs = read_section_stabs (abfd, section->name, &stab_size, NULL);
3903 	  if (stabs)
3904 	    print_section_stabs (abfd, section->name, &sought->string_offset);
3905 	}
3906     }
3907 }
3908 
3909 static void
3910 dump_stabs_section (bfd *abfd, char *stabsect_name, char *strsect_name)
3911 {
3912   stab_section_names s;
3913 
3914   s.section_name = stabsect_name;
3915   s.string_section_name = strsect_name;
3916   s.string_offset = 0;
3917 
3918   bfd_map_over_sections (abfd, find_stabs_section, & s);
3919 
3920   free (strtab);
3921   strtab = NULL;
3922 }
3923 
3924 /* Dump the any sections containing stabs debugging information.  */
3925 
3926 static void
3927 dump_stabs (bfd *abfd)
3928 {
3929   dump_stabs_section (abfd, ".stab", ".stabstr");
3930   dump_stabs_section (abfd, ".stab.excl", ".stab.exclstr");
3931   dump_stabs_section (abfd, ".stab.index", ".stab.indexstr");
3932 
3933   /* For Darwin.  */
3934   dump_stabs_section (abfd, "LC_SYMTAB.stabs", "LC_SYMTAB.stabstr");
3935 
3936   dump_stabs_section (abfd, "$GDB_SYMBOLS$", "$GDB_STRINGS$");
3937 }
3938 
3939 static void
3940 dump_bfd_header (bfd *abfd)
3941 {
3942   char *comma = "";
3943 
3944   printf (_("architecture: %s, "),
3945 	  bfd_printable_arch_mach (bfd_get_arch (abfd),
3946 				   bfd_get_mach (abfd)));
3947   printf (_("flags 0x%08x:\n"), abfd->flags & ~BFD_FLAGS_FOR_BFD_USE_MASK);
3948 
3949 #define PF(x, y)    if (abfd->flags & x) {printf ("%s%s", comma, y); comma=", ";}
3950   PF (HAS_RELOC, "HAS_RELOC");
3951   PF (EXEC_P, "EXEC_P");
3952   PF (HAS_LINENO, "HAS_LINENO");
3953   PF (HAS_DEBUG, "HAS_DEBUG");
3954   PF (HAS_SYMS, "HAS_SYMS");
3955   PF (HAS_LOCALS, "HAS_LOCALS");
3956   PF (DYNAMIC, "DYNAMIC");
3957   PF (WP_TEXT, "WP_TEXT");
3958   PF (D_PAGED, "D_PAGED");
3959   PF (BFD_IS_RELAXABLE, "BFD_IS_RELAXABLE");
3960   printf (_("\nstart address 0x"));
3961   bfd_printf_vma (abfd, abfd->start_address);
3962   printf ("\n");
3963 }
3964 
3965 
3966 /* Formatting callback function passed to ctf_dump.  Returns either the pointer
3967    it is passed, or a pointer to newly-allocated storage, in which case
3968    dump_ctf() will free it when it no longer needs it.  */
3969 
3970 static char *
3971 dump_ctf_indent_lines (ctf_sect_names_t sect ATTRIBUTE_UNUSED,
3972 		       char *s, void *arg)
3973 {
3974   const char *blanks = arg;
3975   char *new_s;
3976 
3977   if (asprintf (&new_s, "%s%s", blanks, s) < 0)
3978     return s;
3979   return new_s;
3980 }
3981 
3982 /* Make a ctfsect suitable for ctf_bfdopen_ctfsect().  */
3983 static ctf_sect_t
3984 make_ctfsect (const char *name, bfd_byte *data,
3985 	      bfd_size_type size)
3986 {
3987   ctf_sect_t ctfsect;
3988 
3989   ctfsect.cts_name = name;
3990   ctfsect.cts_entsize = 1;
3991   ctfsect.cts_size = size;
3992   ctfsect.cts_data = data;
3993 
3994   return ctfsect;
3995 }
3996 
3997 /* Dump one CTF archive member.  */
3998 
3999 static int
4000 dump_ctf_archive_member (ctf_file_t *ctf, const char *name, void *arg)
4001 {
4002   ctf_file_t *parent = (ctf_file_t *) arg;
4003   const char *things[] = {"Header", "Labels", "Data objects",
4004 			  "Function objects", "Variables", "Types", "Strings",
4005 			  ""};
4006   const char **thing;
4007   size_t i;
4008 
4009   /* Only print out the name of non-default-named archive members.
4010      The name .ctf appears everywhere, even for things that aren't
4011      really archives, so printing it out is liable to be confusing.
4012 
4013      The parent, if there is one, is the default-owned archive member:
4014      avoid importing it into itself.  (This does no harm, but looks
4015      confusing.)  */
4016 
4017   if (strcmp (name, ".ctf") != 0)
4018     {
4019       printf (_("\nCTF archive member: %s:\n"), sanitize_string (name));
4020       ctf_import (ctf, parent);
4021     }
4022 
4023   for (i = 0, thing = things; *thing[0]; thing++, i++)
4024     {
4025       ctf_dump_state_t *s = NULL;
4026       char *item;
4027 
4028       printf ("\n  %s:\n", *thing);
4029       while ((item = ctf_dump (ctf, &s, i, dump_ctf_indent_lines,
4030 			       (void *) "    ")) != NULL)
4031 	{
4032 	  printf ("%s\n", item);
4033 	  free (item);
4034 	}
4035 
4036       if (ctf_errno (ctf))
4037 	{
4038 	  non_fatal (_("Iteration failed: %s, %s\n"), *thing,
4039 		   ctf_errmsg (ctf_errno (ctf)));
4040 	  break;
4041 	}
4042     }
4043   return 0;
4044 }
4045 
4046 /* Dump the CTF debugging information.  */
4047 
4048 static void
4049 dump_ctf (bfd *abfd, const char *sect_name, const char *parent_name)
4050 {
4051   ctf_archive_t *ctfa, *parenta = NULL, *lookparent;
4052   bfd_byte *ctfdata, *parentdata = NULL;
4053   bfd_size_type ctfsize, parentsize;
4054   ctf_sect_t ctfsect;
4055   ctf_file_t *parent = NULL;
4056   int err;
4057 
4058   if ((ctfdata = read_section_stabs (abfd, sect_name, &ctfsize, NULL)) == NULL)
4059       bfd_fatal (bfd_get_filename (abfd));
4060 
4061   if (parent_name
4062       && (parentdata = read_section_stabs (abfd, parent_name, &parentsize,
4063 					   NULL)) == NULL)
4064       bfd_fatal (bfd_get_filename (abfd));
4065 
4066   /* Load the CTF file and dump it.  */
4067 
4068   ctfsect = make_ctfsect (sect_name, ctfdata, ctfsize);
4069   if ((ctfa = ctf_bfdopen_ctfsect (abfd, &ctfsect, &err)) == NULL)
4070     {
4071       non_fatal (_("CTF open failure: %s\n"), ctf_errmsg (err));
4072       bfd_fatal (bfd_get_filename (abfd));
4073     }
4074 
4075   if (parentdata)
4076     {
4077       ctfsect = make_ctfsect (parent_name, parentdata, parentsize);
4078       if ((parenta = ctf_bfdopen_ctfsect (abfd, &ctfsect, &err)) == NULL)
4079 	{
4080 	  non_fatal (_("CTF open failure: %s\n"), ctf_errmsg (err));
4081 	  bfd_fatal (bfd_get_filename (abfd));
4082 	}
4083 
4084       lookparent = parenta;
4085     }
4086   else
4087     lookparent = ctfa;
4088 
4089   /* Assume that the applicable parent archive member is the default one.
4090      (This is what all known implementations are expected to do, if they
4091      put CTFs and their parents in archives together.)  */
4092   if ((parent = ctf_arc_open_by_name (lookparent, NULL, &err)) == NULL)
4093     {
4094       non_fatal (_("CTF open failure: %s\n"), ctf_errmsg (err));
4095       bfd_fatal (bfd_get_filename (abfd));
4096     }
4097 
4098   printf (_("Contents of CTF section %s:\n"), sanitize_string (sect_name));
4099 
4100   ctf_archive_iter (ctfa, dump_ctf_archive_member, parent);
4101   ctf_file_close (parent);
4102   ctf_close (ctfa);
4103   ctf_close (parenta);
4104   free (parentdata);
4105   free (ctfdata);
4106 }
4107 
4108 
4109 static void
4110 dump_bfd_private_header (bfd *abfd)
4111 {
4112   if (!bfd_print_private_bfd_data (abfd, stdout))
4113     non_fatal (_("warning: private headers incomplete: %s"),
4114 	       bfd_errmsg (bfd_get_error ()));
4115 }
4116 
4117 static void
4118 dump_target_specific (bfd *abfd)
4119 {
4120   const struct objdump_private_desc * const *desc;
4121   struct objdump_private_option *opt;
4122   char *e, *b;
4123 
4124   /* Find the desc.  */
4125   for (desc = objdump_private_vectors; *desc != NULL; desc++)
4126     if ((*desc)->filter (abfd))
4127       break;
4128 
4129   if (*desc == NULL)
4130     {
4131       non_fatal (_("option -P/--private not supported by this file"));
4132       return;
4133     }
4134 
4135   /* Clear all options.  */
4136   for (opt = (*desc)->options; opt->name; opt++)
4137     opt->selected = FALSE;
4138 
4139   /* Decode options.  */
4140   b = dump_private_options;
4141   do
4142     {
4143       e = strchr (b, ',');
4144 
4145       if (e)
4146         *e = 0;
4147 
4148       for (opt = (*desc)->options; opt->name; opt++)
4149         if (strcmp (opt->name, b) == 0)
4150           {
4151             opt->selected = TRUE;
4152             break;
4153           }
4154       if (opt->name == NULL)
4155         non_fatal (_("target specific dump '%s' not supported"), b);
4156 
4157       if (e)
4158         {
4159           *e = ',';
4160           b = e + 1;
4161         }
4162     }
4163   while (e != NULL);
4164 
4165   /* Dump.  */
4166   (*desc)->dump (abfd);
4167 }
4168 
4169 /* Display a section in hexadecimal format with associated characters.
4170    Each line prefixed by the zero padded address.  */
4171 
4172 static void
4173 dump_section (bfd *abfd, asection *section, void *dummy ATTRIBUTE_UNUSED)
4174 {
4175   bfd_byte *data = NULL;
4176   bfd_size_type datasize;
4177   bfd_vma addr_offset;
4178   bfd_vma start_offset;
4179   bfd_vma stop_offset;
4180   unsigned int opb = bfd_octets_per_byte (abfd, section);
4181   /* Bytes per line.  */
4182   const int onaline = 16;
4183   char buf[64];
4184   int count;
4185   int width;
4186 
4187   if ((section->flags & SEC_HAS_CONTENTS) == 0)
4188     return;
4189 
4190   if (! process_section_p (section))
4191     return;
4192 
4193   if ((datasize = bfd_section_size (section)) == 0)
4194     return;
4195 
4196   /* Compute the address range to display.  */
4197   if (start_address == (bfd_vma) -1
4198       || start_address < section->vma)
4199     start_offset = 0;
4200   else
4201     start_offset = start_address - section->vma;
4202 
4203   if (stop_address == (bfd_vma) -1)
4204     stop_offset = datasize / opb;
4205   else
4206     {
4207       if (stop_address < section->vma)
4208 	stop_offset = 0;
4209       else
4210 	stop_offset = stop_address - section->vma;
4211 
4212       if (stop_offset > datasize / opb)
4213 	stop_offset = datasize / opb;
4214     }
4215 
4216   if (start_offset >= stop_offset)
4217     return;
4218 
4219   printf (_("Contents of section %s:"), sanitize_string (section->name));
4220   if (display_file_offsets)
4221     printf (_("  (Starting at file offset: 0x%lx)"),
4222 	    (unsigned long) (section->filepos + start_offset));
4223   printf ("\n");
4224 
4225   if (!bfd_get_full_section_contents (abfd, section, &data))
4226     {
4227       non_fatal (_("Reading section %s failed because: %s"),
4228 		 section->name, bfd_errmsg (bfd_get_error ()));
4229       return;
4230     }
4231 
4232   width = 4;
4233 
4234   bfd_sprintf_vma (abfd, buf, start_offset + section->vma);
4235   if (strlen (buf) >= sizeof (buf))
4236     abort ();
4237 
4238   count = 0;
4239   while (buf[count] == '0' && buf[count+1] != '\0')
4240     count++;
4241   count = strlen (buf) - count;
4242   if (count > width)
4243     width = count;
4244 
4245   bfd_sprintf_vma (abfd, buf, stop_offset + section->vma - 1);
4246   if (strlen (buf) >= sizeof (buf))
4247     abort ();
4248 
4249   count = 0;
4250   while (buf[count] == '0' && buf[count+1] != '\0')
4251     count++;
4252   count = strlen (buf) - count;
4253   if (count > width)
4254     width = count;
4255 
4256   for (addr_offset = start_offset;
4257        addr_offset < stop_offset; addr_offset += onaline / opb)
4258     {
4259       bfd_size_type j;
4260 
4261       bfd_sprintf_vma (abfd, buf, (addr_offset + section->vma));
4262       count = strlen (buf);
4263       if ((size_t) count >= sizeof (buf))
4264 	abort ();
4265 
4266       putchar (' ');
4267       while (count < width)
4268 	{
4269 	  putchar ('0');
4270 	  count++;
4271 	}
4272       fputs (buf + count - width, stdout);
4273       putchar (' ');
4274 
4275       for (j = addr_offset * opb;
4276 	   j < addr_offset * opb + onaline; j++)
4277 	{
4278 	  if (j < stop_offset * opb)
4279 	    printf ("%02x", (unsigned) (data[j]));
4280 	  else
4281 	    printf ("  ");
4282 	  if ((j & 3) == 3)
4283 	    printf (" ");
4284 	}
4285 
4286       printf (" ");
4287       for (j = addr_offset * opb;
4288 	   j < addr_offset * opb + onaline; j++)
4289 	{
4290 	  if (j >= stop_offset * opb)
4291 	    printf (" ");
4292 	  else
4293 	    printf ("%c", ISPRINT (data[j]) ? data[j] : '.');
4294 	}
4295       putchar ('\n');
4296     }
4297   free (data);
4298 }
4299 
4300 /* Actually display the various requested regions.  */
4301 
4302 static void
4303 dump_data (bfd *abfd)
4304 {
4305   bfd_map_over_sections (abfd, dump_section, NULL);
4306 }
4307 
4308 /* Should perhaps share code and display with nm?  */
4309 
4310 static void
4311 dump_symbols (bfd *abfd ATTRIBUTE_UNUSED, bfd_boolean dynamic)
4312 {
4313   asymbol **current;
4314   long max_count;
4315   long count;
4316 
4317   if (dynamic)
4318     {
4319       current = dynsyms;
4320       max_count = dynsymcount;
4321       printf ("DYNAMIC SYMBOL TABLE:\n");
4322     }
4323   else
4324     {
4325       current = syms;
4326       max_count = symcount;
4327       printf ("SYMBOL TABLE:\n");
4328     }
4329 
4330   if (max_count == 0)
4331     printf (_("no symbols\n"));
4332 
4333   for (count = 0; count < max_count; count++)
4334     {
4335       bfd *cur_bfd;
4336 
4337       if (*current == NULL)
4338 	printf (_("no information for symbol number %ld\n"), count);
4339 
4340       else if ((cur_bfd = bfd_asymbol_bfd (*current)) == NULL)
4341 	printf (_("could not determine the type of symbol number %ld\n"),
4342 		count);
4343 
4344       else if (process_section_p ((* current)->section)
4345 	       && (dump_special_syms
4346 		   || !bfd_is_target_special_symbol (cur_bfd, *current)))
4347 	{
4348 	  const char *name = (*current)->name;
4349 
4350 	  if (do_demangle && name != NULL && *name != '\0')
4351 	    {
4352 	      char *alloc;
4353 
4354 	      /* If we want to demangle the name, we demangle it
4355 		 here, and temporarily clobber it while calling
4356 		 bfd_print_symbol.  FIXME: This is a gross hack.  */
4357 	      alloc = bfd_demangle (cur_bfd, name, demangle_flags);
4358 	      if (alloc != NULL)
4359 		(*current)->name = alloc;
4360 	      bfd_print_symbol (cur_bfd, stdout, *current,
4361 				bfd_print_symbol_all);
4362 	      if (alloc != NULL)
4363 		{
4364 		  (*current)->name = name;
4365 		  free (alloc);
4366 		}
4367 	    }
4368 	  else
4369 	    bfd_print_symbol (cur_bfd, stdout, *current,
4370 			      bfd_print_symbol_all);
4371 	  printf ("\n");
4372 	}
4373 
4374       current++;
4375     }
4376   printf ("\n\n");
4377 }
4378 
4379 static void
4380 dump_reloc_set (bfd *abfd, asection *sec, arelent **relpp, long relcount)
4381 {
4382   arelent **p;
4383   char *last_filename, *last_functionname;
4384   unsigned int last_line;
4385   unsigned int last_discriminator;
4386 
4387   /* Get column headers lined up reasonably.  */
4388   {
4389     static int width;
4390 
4391     if (width == 0)
4392       {
4393 	char buf[30];
4394 
4395 	bfd_sprintf_vma (abfd, buf, (bfd_vma) -1);
4396 	width = strlen (buf) - 7;
4397       }
4398     printf ("OFFSET %*s TYPE %*s VALUE \n", width, "", 12, "");
4399   }
4400 
4401   last_filename = NULL;
4402   last_functionname = NULL;
4403   last_line = 0;
4404   last_discriminator = 0;
4405 
4406   for (p = relpp; relcount && *p != NULL; p++, relcount--)
4407     {
4408       arelent *q = *p;
4409       const char *filename, *functionname;
4410       unsigned int linenumber;
4411       unsigned int discriminator;
4412       const char *sym_name;
4413       const char *section_name;
4414       bfd_vma addend2 = 0;
4415 
4416       if (start_address != (bfd_vma) -1
4417 	  && q->address < start_address)
4418 	continue;
4419       if (stop_address != (bfd_vma) -1
4420 	  && q->address > stop_address)
4421 	continue;
4422 
4423       if (with_line_numbers
4424 	  && sec != NULL
4425 	  && bfd_find_nearest_line_discriminator (abfd, sec, syms, q->address,
4426                                                   &filename, &functionname,
4427                                                   &linenumber, &discriminator))
4428 	{
4429 	  if (functionname != NULL
4430 	      && (last_functionname == NULL
4431 		  || strcmp (functionname, last_functionname) != 0))
4432 	    {
4433 	      printf ("%s():\n", sanitize_string (functionname));
4434 	      if (last_functionname != NULL)
4435 		free (last_functionname);
4436 	      last_functionname = xstrdup (functionname);
4437 	    }
4438 
4439 	  if (linenumber > 0
4440 	      && (linenumber != last_line
4441 		  || (filename != NULL
4442 		      && last_filename != NULL
4443 		      && filename_cmp (filename, last_filename) != 0)
4444                   || (discriminator != last_discriminator)))
4445 	    {
4446               if (discriminator > 0)
4447                 printf ("%s:%u\n", filename == NULL ? "???" :
4448 			sanitize_string (filename), linenumber);
4449               else
4450                 printf ("%s:%u (discriminator %u)\n",
4451 			filename == NULL ? "???" : sanitize_string (filename),
4452                         linenumber, discriminator);
4453 	      last_line = linenumber;
4454 	      last_discriminator = discriminator;
4455 	      if (last_filename != NULL)
4456 		free (last_filename);
4457 	      if (filename == NULL)
4458 		last_filename = NULL;
4459 	      else
4460 		last_filename = xstrdup (filename);
4461 	    }
4462 	}
4463 
4464       if (q->sym_ptr_ptr && *q->sym_ptr_ptr)
4465 	{
4466 	  sym_name = (*(q->sym_ptr_ptr))->name;
4467 	  section_name = (*(q->sym_ptr_ptr))->section->name;
4468 	}
4469       else
4470 	{
4471 	  sym_name = NULL;
4472 	  section_name = NULL;
4473 	}
4474 
4475       bfd_printf_vma (abfd, q->address);
4476       if (q->howto == NULL)
4477 	printf (" *unknown*         ");
4478       else if (q->howto->name)
4479 	{
4480 	  const char *name = q->howto->name;
4481 
4482 	  /* R_SPARC_OLO10 relocations contain two addends.
4483 	     But because 'arelent' lacks enough storage to
4484 	     store them both, the 64-bit ELF Sparc backend
4485 	     records this as two relocations.  One R_SPARC_LO10
4486 	     and one R_SPARC_13, both pointing to the same
4487 	     address.  This is merely so that we have some
4488 	     place to store both addend fields.
4489 
4490 	     Undo this transformation, otherwise the output
4491 	     will be confusing.  */
4492 	  if (abfd->xvec->flavour == bfd_target_elf_flavour
4493 	      && elf_tdata (abfd)->elf_header->e_machine == EM_SPARCV9
4494 	      && relcount > 1
4495 	      && !strcmp (q->howto->name, "R_SPARC_LO10"))
4496 	    {
4497 	      arelent *q2 = *(p + 1);
4498 	      if (q2 != NULL
4499 		  && q2->howto
4500 		  && q->address == q2->address
4501 		  && !strcmp (q2->howto->name, "R_SPARC_13"))
4502 		{
4503 		  name = "R_SPARC_OLO10";
4504 		  addend2 = q2->addend;
4505 		  p++;
4506 		}
4507 	    }
4508 	  printf (" %-16s  ", name);
4509 	}
4510       else
4511 	printf (" %-16d  ", q->howto->type);
4512 
4513       if (sym_name)
4514 	{
4515 	  objdump_print_symname (abfd, NULL, *q->sym_ptr_ptr);
4516 	}
4517       else
4518 	{
4519 	  if (section_name == NULL)
4520 	    section_name = "*unknown*";
4521 	  printf ("[%s]", sanitize_string (section_name));
4522 	}
4523 
4524       if (q->addend)
4525 	{
4526 	  bfd_signed_vma addend = q->addend;
4527 	  if (addend < 0)
4528 	    {
4529 	      printf ("-0x");
4530 	      addend = -addend;
4531 	    }
4532 	  else
4533 	    printf ("+0x");
4534 	  bfd_printf_vma (abfd, addend);
4535 	}
4536       if (addend2)
4537 	{
4538 	  printf ("+0x");
4539 	  bfd_printf_vma (abfd, addend2);
4540 	}
4541 
4542       printf ("\n");
4543     }
4544 
4545   if (last_filename != NULL)
4546     free (last_filename);
4547   if (last_functionname != NULL)
4548     free (last_functionname);
4549 }
4550 
4551 static void
4552 dump_relocs_in_section (bfd *abfd,
4553 			asection *section,
4554 			void *dummy ATTRIBUTE_UNUSED)
4555 {
4556   arelent **relpp = NULL;
4557   long relcount;
4558   long relsize;
4559 
4560   if (   bfd_is_abs_section (section)
4561       || bfd_is_und_section (section)
4562       || bfd_is_com_section (section)
4563       || (! process_section_p (section))
4564       || ((section->flags & SEC_RELOC) == 0))
4565     return;
4566 
4567   printf ("RELOCATION RECORDS FOR [%s]:", sanitize_string (section->name));
4568 
4569   relsize = bfd_get_reloc_upper_bound (abfd, section);
4570   if (relsize == 0)
4571     {
4572       printf (" (none)\n\n");
4573       return;
4574     }
4575 
4576   if (relsize < 0)
4577     relcount = relsize;
4578   else
4579     {
4580       relpp = (arelent **) xmalloc (relsize);
4581       relcount = bfd_canonicalize_reloc (abfd, section, relpp, syms);
4582     }
4583 
4584   if (relcount < 0)
4585     {
4586       printf ("\n");
4587       non_fatal (_("failed to read relocs in: %s"),
4588 		 sanitize_string (bfd_get_filename (abfd)));
4589       bfd_fatal (_("error message was"));
4590     }
4591   else if (relcount == 0)
4592     printf (" (none)\n\n");
4593   else
4594     {
4595       printf ("\n");
4596       dump_reloc_set (abfd, section, relpp, relcount);
4597       printf ("\n\n");
4598     }
4599   free (relpp);
4600 }
4601 
4602 static void
4603 dump_relocs (bfd *abfd)
4604 {
4605   bfd_map_over_sections (abfd, dump_relocs_in_section, NULL);
4606 }
4607 
4608 static void
4609 dump_dynamic_relocs (bfd *abfd)
4610 {
4611   long relsize;
4612   arelent **relpp;
4613   long relcount;
4614 
4615   relsize = bfd_get_dynamic_reloc_upper_bound (abfd);
4616   if (relsize < 0)
4617     bfd_fatal (bfd_get_filename (abfd));
4618 
4619   printf ("DYNAMIC RELOCATION RECORDS");
4620 
4621   if (relsize == 0)
4622     printf (" (none)\n\n");
4623   else
4624     {
4625       relpp = (arelent **) xmalloc (relsize);
4626       relcount = bfd_canonicalize_dynamic_reloc (abfd, relpp, dynsyms);
4627 
4628       if (relcount < 0)
4629 	bfd_fatal (bfd_get_filename (abfd));
4630       else if (relcount == 0)
4631 	printf (" (none)\n\n");
4632       else
4633 	{
4634 	  printf ("\n");
4635 	  dump_reloc_set (abfd, NULL, relpp, relcount);
4636 	  printf ("\n\n");
4637 	}
4638       free (relpp);
4639     }
4640 }
4641 
4642 /* Creates a table of paths, to search for source files.  */
4643 
4644 static void
4645 add_include_path (const char *path)
4646 {
4647   if (path[0] == 0)
4648     return;
4649   include_path_count++;
4650   include_paths = (const char **)
4651       xrealloc (include_paths, include_path_count * sizeof (*include_paths));
4652 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
4653   if (path[1] == ':' && path[2] == 0)
4654     path = concat (path, ".", (const char *) 0);
4655 #endif
4656   include_paths[include_path_count - 1] = path;
4657 }
4658 
4659 static void
4660 adjust_addresses (bfd *abfd ATTRIBUTE_UNUSED,
4661 		  asection *section,
4662 		  void *arg)
4663 {
4664   if ((section->flags & SEC_DEBUGGING) == 0)
4665     {
4666       bfd_boolean *has_reloc_p = (bfd_boolean *) arg;
4667       section->vma += adjust_section_vma;
4668       if (*has_reloc_p)
4669 	section->lma += adjust_section_vma;
4670     }
4671 }
4672 
4673 /* Return the sign-extended form of an ARCH_SIZE sized VMA.  */
4674 
4675 static bfd_vma
4676 sign_extend_address (bfd *abfd ATTRIBUTE_UNUSED,
4677 		     bfd_vma vma,
4678 		     unsigned arch_size)
4679 {
4680   bfd_vma mask;
4681   mask = (bfd_vma) 1 << (arch_size - 1);
4682   return (((vma & ((mask << 1) - 1)) ^ mask) - mask);
4683 }
4684 
4685 /* Dump selected contents of ABFD.  */
4686 
4687 static void
4688 dump_bfd (bfd *abfd, bfd_boolean is_mainfile)
4689 {
4690   const struct elf_backend_data * bed;
4691 
4692   if (bfd_big_endian (abfd))
4693     byte_get = byte_get_big_endian;
4694   else if (bfd_little_endian (abfd))
4695     byte_get = byte_get_little_endian;
4696   else
4697     byte_get = NULL;
4698 
4699   /* Load any separate debug information files.
4700      We do this now and without checking do_follow_links because separate
4701      debug info files may contain symbol tables that we will need when
4702      displaying information about the main file.  Any memory allocated by
4703      load_separate_debug_files will be released when we call
4704      free_debug_memory below.
4705 
4706      The test on is_mainfile is there because the chain of separate debug
4707      info files is a global variable shared by all invocations of dump_bfd.  */
4708   if (is_mainfile)
4709     {
4710       load_separate_debug_files (abfd, bfd_get_filename (abfd));
4711 
4712       /* If asked to do so, recursively dump the separate files.  */
4713       if (do_follow_links)
4714 	{
4715 	  separate_info * i;
4716 
4717 	  for (i = first_separate_info; i != NULL; i = i->next)
4718 	    dump_bfd (i->handle, FALSE);
4719 	}
4720     }
4721 
4722   /* Adjust user-specified start and stop limits for targets that use
4723      signed addresses.  */
4724   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
4725       && (bed = get_elf_backend_data (abfd)) != NULL
4726       && bed->sign_extend_vma)
4727     {
4728       start_address = sign_extend_address (abfd, start_address,
4729 					   bed->s->arch_size);
4730       stop_address = sign_extend_address (abfd, stop_address,
4731 					  bed->s->arch_size);
4732     }
4733 
4734   /* If we are adjusting section VMA's, change them all now.  Changing
4735      the BFD information is a hack.  However, we must do it, or
4736      bfd_find_nearest_line will not do the right thing.  */
4737   if (adjust_section_vma != 0)
4738     {
4739       bfd_boolean has_reloc = (abfd->flags & HAS_RELOC);
4740       bfd_map_over_sections (abfd, adjust_addresses, &has_reloc);
4741     }
4742 
4743   if (! dump_debugging_tags && ! suppress_bfd_header)
4744     printf (_("\n%s:     file format %s\n"),
4745 	    sanitize_string (bfd_get_filename (abfd)),
4746 	    abfd->xvec->name);
4747   if (dump_ar_hdrs)
4748     print_arelt_descr (stdout, abfd, TRUE, FALSE);
4749   if (dump_file_header)
4750     dump_bfd_header (abfd);
4751   if (dump_private_headers)
4752     dump_bfd_private_header (abfd);
4753   if (dump_private_options != NULL)
4754     dump_target_specific (abfd);
4755   if (! dump_debugging_tags && ! suppress_bfd_header)
4756     putchar ('\n');
4757 
4758   if (dump_symtab
4759       || dump_reloc_info
4760       || disassemble
4761       || dump_debugging
4762       || dump_dwarf_section_info)
4763     {
4764       syms = slurp_symtab (abfd);
4765 
4766       /* If following links, load any symbol tables from the linked files as well.  */
4767       if (do_follow_links && is_mainfile)
4768 	{
4769 	  separate_info * i;
4770 
4771 	  for (i = first_separate_info; i != NULL; i = i->next)
4772 	    {
4773 	      asymbol **  extra_syms;
4774 	      long        old_symcount = symcount;
4775 
4776 	      extra_syms = slurp_symtab (i->handle);
4777 
4778 	      if (extra_syms)
4779 		{
4780 		  if (old_symcount == 0)
4781 		    {
4782 		      syms = extra_syms;
4783 		    }
4784 		  else
4785 		    {
4786 		      syms = xrealloc (syms, (symcount + old_symcount) * sizeof (asymbol *));
4787 		      memcpy (syms + old_symcount,
4788 			      extra_syms,
4789 			      symcount * sizeof (asymbol *));
4790 		    }
4791 		}
4792 
4793 	      symcount += old_symcount;
4794 	    }
4795 	}
4796     }
4797 
4798   if (dump_section_headers)
4799     dump_headers (abfd);
4800 
4801   if (dump_dynamic_symtab || dump_dynamic_reloc_info
4802       || (disassemble && bfd_get_dynamic_symtab_upper_bound (abfd) > 0))
4803     dynsyms = slurp_dynamic_symtab (abfd);
4804 
4805   if (disassemble)
4806     {
4807       synthcount = bfd_get_synthetic_symtab (abfd, symcount, syms,
4808 					     dynsymcount, dynsyms, &synthsyms);
4809       if (synthcount < 0)
4810 	synthcount = 0;
4811     }
4812 
4813   if (dump_symtab)
4814     dump_symbols (abfd, FALSE);
4815   if (dump_dynamic_symtab)
4816     dump_symbols (abfd, TRUE);
4817   if (dump_dwarf_section_info)
4818     dump_dwarf (abfd);
4819   if (dump_ctf_section_info)
4820     dump_ctf (abfd, dump_ctf_section_name, dump_ctf_parent_name);
4821   if (dump_stab_section_info)
4822     dump_stabs (abfd);
4823   if (dump_reloc_info && ! disassemble)
4824     dump_relocs (abfd);
4825   if (dump_dynamic_reloc_info && ! disassemble)
4826     dump_dynamic_relocs (abfd);
4827   if (dump_section_contents)
4828     dump_data (abfd);
4829   if (disassemble)
4830     disassemble_data (abfd);
4831 
4832   if (dump_debugging)
4833     {
4834       void *dhandle;
4835 
4836       dhandle = read_debugging_info (abfd, syms, symcount, TRUE);
4837       if (dhandle != NULL)
4838 	{
4839 	  if (!print_debugging_info (stdout, dhandle, abfd, syms,
4840 				     bfd_demangle,
4841 				     dump_debugging_tags ? TRUE : FALSE))
4842 	    {
4843 	      non_fatal (_("%s: printing debugging information failed"),
4844 			 bfd_get_filename (abfd));
4845 	      exit_status = 1;
4846 	    }
4847 
4848 	  free (dhandle);
4849 	}
4850       /* PR 6483: If there was no STABS debug info in the file, try
4851 	 DWARF instead.  */
4852       else if (! dump_dwarf_section_info)
4853 	{
4854 	  dwarf_select_sections_all ();
4855 	  dump_dwarf (abfd);
4856 	}
4857     }
4858 
4859   if (syms)
4860     {
4861       free (syms);
4862       syms = NULL;
4863     }
4864 
4865   if (dynsyms)
4866     {
4867       free (dynsyms);
4868       dynsyms = NULL;
4869     }
4870 
4871   if (synthsyms)
4872     {
4873       free (synthsyms);
4874       synthsyms = NULL;
4875     }
4876 
4877   symcount = 0;
4878   dynsymcount = 0;
4879   synthcount = 0;
4880 
4881   if (is_mainfile)
4882     free_debug_memory ();
4883 }
4884 
4885 static void
4886 display_object_bfd (bfd *abfd)
4887 {
4888   char **matching;
4889 
4890   if (bfd_check_format_matches (abfd, bfd_object, &matching))
4891     {
4892       dump_bfd (abfd, TRUE);
4893       return;
4894     }
4895 
4896   if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
4897     {
4898       nonfatal (bfd_get_filename (abfd));
4899       list_matching_formats (matching);
4900       free (matching);
4901       return;
4902     }
4903 
4904   if (bfd_get_error () != bfd_error_file_not_recognized)
4905     {
4906       nonfatal (bfd_get_filename (abfd));
4907       return;
4908     }
4909 
4910   if (bfd_check_format_matches (abfd, bfd_core, &matching))
4911     {
4912       dump_bfd (abfd, TRUE);
4913       return;
4914     }
4915 
4916   nonfatal (bfd_get_filename (abfd));
4917 
4918   if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
4919     {
4920       list_matching_formats (matching);
4921       free (matching);
4922     }
4923 }
4924 
4925 static void
4926 display_any_bfd (bfd *file, int level)
4927 {
4928   /* Decompress sections unless dumping the section contents.  */
4929   if (!dump_section_contents)
4930     file->flags |= BFD_DECOMPRESS;
4931 
4932   /* If the file is an archive, process all of its elements.  */
4933   if (bfd_check_format (file, bfd_archive))
4934     {
4935       bfd *arfile = NULL;
4936       bfd *last_arfile = NULL;
4937 
4938       if (level == 0)
4939         printf (_("In archive %s:\n"), sanitize_string (bfd_get_filename (file)));
4940       else if (level > 100)
4941 	{
4942 	  /* Prevent corrupted files from spinning us into an
4943 	     infinite loop.  100 is an arbitrary heuristic.  */
4944 	  fatal (_("Archive nesting is too deep"));
4945 	  return;
4946 	}
4947       else
4948         printf (_("In nested archive %s:\n"),
4949 		sanitize_string (bfd_get_filename (file)));
4950 
4951       for (;;)
4952 	{
4953 	  bfd_set_error (bfd_error_no_error);
4954 
4955 	  arfile = bfd_openr_next_archived_file (file, arfile);
4956 	  if (arfile == NULL)
4957 	    {
4958 	      if (bfd_get_error () != bfd_error_no_more_archived_files)
4959 		nonfatal (bfd_get_filename (file));
4960 	      break;
4961 	    }
4962 
4963 	  display_any_bfd (arfile, level + 1);
4964 
4965 	  if (last_arfile != NULL)
4966 	    {
4967 	      bfd_close (last_arfile);
4968 	      /* PR 17512: file: ac585d01.  */
4969 	      if (arfile == last_arfile)
4970 		{
4971 		  last_arfile = NULL;
4972 		  break;
4973 		}
4974 	    }
4975 	  last_arfile = arfile;
4976 	}
4977 
4978       if (last_arfile != NULL)
4979 	bfd_close (last_arfile);
4980     }
4981   else
4982     display_object_bfd (file);
4983 }
4984 
4985 static void
4986 display_file (char *filename, char *target, bfd_boolean last_file)
4987 {
4988   bfd *file;
4989 
4990   if (get_file_size (filename) < 1)
4991     {
4992       exit_status = 1;
4993       return;
4994     }
4995 
4996   file = bfd_openr (filename, target);
4997   if (file == NULL)
4998     {
4999       nonfatal (filename);
5000       return;
5001     }
5002 
5003   display_any_bfd (file, 0);
5004 
5005   /* This is an optimization to improve the speed of objdump, especially when
5006      dumping a file with lots of associated debug informatiom.  Calling
5007      bfd_close on such a file can take a non-trivial amount of time as there
5008      are lots of lists to walk and buffers to free.  This is only really
5009      necessary however if we are about to load another file and we need the
5010      memory back.  Otherwise, if we are about to exit, then we can save (a lot
5011      of) time by only doing a quick close, and allowing the OS to reclaim the
5012      memory for us.  */
5013   if (! last_file)
5014     bfd_close (file);
5015   else
5016     bfd_close_all_done (file);
5017 }
5018 
5019 int
5020 main (int argc, char **argv)
5021 {
5022   int c;
5023   char *target = default_target;
5024   bfd_boolean seenflag = FALSE;
5025 
5026 #if defined (HAVE_SETLOCALE)
5027 #if defined (HAVE_LC_MESSAGES)
5028   setlocale (LC_MESSAGES, "");
5029 #endif
5030   setlocale (LC_CTYPE, "");
5031 #endif
5032 
5033   bindtextdomain (PACKAGE, LOCALEDIR);
5034   textdomain (PACKAGE);
5035 
5036   program_name = *argv;
5037   xmalloc_set_program_name (program_name);
5038   bfd_set_error_program_name (program_name);
5039 
5040   START_PROGRESS (program_name, 0);
5041 
5042   expandargv (&argc, &argv);
5043 
5044   if (bfd_init () != BFD_INIT_MAGIC)
5045     fatal (_("fatal error: libbfd ABI mismatch"));
5046   set_default_bfd_target ();
5047 
5048   while ((c = getopt_long (argc, argv,
5049 			   "pP:ib:m:M:VvCdDlfFaHhrRtTxsSI:j:wE:zgeGW::",
5050 			   long_options, (int *) 0))
5051 	 != EOF)
5052     {
5053       switch (c)
5054 	{
5055 	case 0:
5056 	  break;		/* We've been given a long option.  */
5057 	case 'm':
5058 	  machine = optarg;
5059 	  break;
5060 	case 'M':
5061 	  {
5062 	    char *options;
5063 	    if (disassembler_options)
5064 	      /* Ignore potential memory leak for now.  */
5065 	      options = concat (disassembler_options, ",",
5066 				optarg, (const char *) NULL);
5067 	    else
5068 	      options = optarg;
5069 	    disassembler_options = remove_whitespace_and_extra_commas (options);
5070 	  }
5071 	  break;
5072 	case 'j':
5073 	  add_only (optarg);
5074 	  break;
5075 	case 'F':
5076 	  display_file_offsets = TRUE;
5077 	  break;
5078 	case 'l':
5079 	  with_line_numbers = TRUE;
5080 	  break;
5081 	case 'b':
5082 	  target = optarg;
5083 	  break;
5084 	case 'C':
5085 	  do_demangle = TRUE;
5086 	  if (optarg != NULL)
5087 	    {
5088 	      enum demangling_styles style;
5089 
5090 	      style = cplus_demangle_name_to_style (optarg);
5091 	      if (style == unknown_demangling)
5092 		fatal (_("unknown demangling style `%s'"),
5093 		       optarg);
5094 
5095 	      cplus_demangle_set_style (style);
5096 	    }
5097 	  break;
5098 	case OPTION_RECURSE_LIMIT:
5099 	  demangle_flags &= ~ DMGL_NO_RECURSE_LIMIT;
5100 	  break;
5101 	case OPTION_NO_RECURSE_LIMIT:
5102 	  demangle_flags |= DMGL_NO_RECURSE_LIMIT;
5103 	  break;
5104 	case 'w':
5105 	  do_wide = wide_output = TRUE;
5106 	  break;
5107 	case OPTION_ADJUST_VMA:
5108 	  adjust_section_vma = parse_vma (optarg, "--adjust-vma");
5109 	  break;
5110 	case OPTION_START_ADDRESS:
5111 	  start_address = parse_vma (optarg, "--start-address");
5112 	  if ((stop_address != (bfd_vma) -1) && stop_address <= start_address)
5113 	    fatal (_("error: the start address should be before the end address"));
5114 	  break;
5115 	case OPTION_STOP_ADDRESS:
5116 	  stop_address = parse_vma (optarg, "--stop-address");
5117 	  if ((start_address != (bfd_vma) -1) && stop_address <= start_address)
5118 	    fatal (_("error: the stop address should be after the start address"));
5119 	  break;
5120 	case OPTION_PREFIX:
5121 	  prefix = optarg;
5122 	  prefix_length = strlen (prefix);
5123 	  /* Remove an unnecessary trailing '/' */
5124 	  while (IS_DIR_SEPARATOR (prefix[prefix_length - 1]))
5125 	    prefix_length--;
5126 	  break;
5127 	case OPTION_PREFIX_STRIP:
5128 	  prefix_strip = atoi (optarg);
5129 	  if (prefix_strip < 0)
5130 	    fatal (_("error: prefix strip must be non-negative"));
5131 	  break;
5132 	case OPTION_INSN_WIDTH:
5133 	  insn_width = strtoul (optarg, NULL, 0);
5134 	  if (insn_width <= 0)
5135 	    fatal (_("error: instruction width must be positive"));
5136 	  break;
5137 	case OPTION_INLINES:
5138 	  unwind_inlines = TRUE;
5139 	  break;
5140 	case OPTION_VISUALIZE_JUMPS:
5141 	  visualize_jumps = TRUE;
5142 	  color_output = FALSE;
5143 	  extended_color_output = FALSE;
5144 	  if (optarg != NULL)
5145 	    {
5146 	      if (streq (optarg, "color"))
5147 		color_output = TRUE;
5148 	      else if (streq (optarg, "extended-color"))
5149 		{
5150 		  color_output = TRUE;
5151 		  extended_color_output = TRUE;
5152 		}
5153 	      else if (streq (optarg, "off"))
5154 		visualize_jumps = FALSE;
5155 	      else
5156 		nonfatal (_("unrecognized argument to --visualize-option"));
5157 	    }
5158 	  break;
5159 	case 'E':
5160 	  if (strcmp (optarg, "B") == 0)
5161 	    endian = BFD_ENDIAN_BIG;
5162 	  else if (strcmp (optarg, "L") == 0)
5163 	    endian = BFD_ENDIAN_LITTLE;
5164 	  else
5165 	    {
5166 	      nonfatal (_("unrecognized -E option"));
5167 	      usage (stderr, 1);
5168 	    }
5169 	  break;
5170 	case OPTION_ENDIAN:
5171 	  if (strncmp (optarg, "big", strlen (optarg)) == 0)
5172 	    endian = BFD_ENDIAN_BIG;
5173 	  else if (strncmp (optarg, "little", strlen (optarg)) == 0)
5174 	    endian = BFD_ENDIAN_LITTLE;
5175 	  else
5176 	    {
5177 	      non_fatal (_("unrecognized --endian type `%s'"), optarg);
5178 	      exit_status = 1;
5179 	      usage (stderr, 1);
5180 	    }
5181 	  break;
5182 
5183 	case 'f':
5184 	  dump_file_header = TRUE;
5185 	  seenflag = TRUE;
5186 	  break;
5187 	case 'i':
5188 	  formats_info = TRUE;
5189 	  seenflag = TRUE;
5190 	  break;
5191 	case 'I':
5192 	  add_include_path (optarg);
5193 	  break;
5194 	case 'p':
5195 	  dump_private_headers = TRUE;
5196 	  seenflag = TRUE;
5197 	  break;
5198 	case 'P':
5199 	  dump_private_options = optarg;
5200 	  seenflag = TRUE;
5201 	  break;
5202 	case 'x':
5203 	  dump_private_headers = TRUE;
5204 	  dump_symtab = TRUE;
5205 	  dump_reloc_info = TRUE;
5206 	  dump_file_header = TRUE;
5207 	  dump_ar_hdrs = TRUE;
5208 	  dump_section_headers = TRUE;
5209 	  seenflag = TRUE;
5210 	  break;
5211 	case 't':
5212 	  dump_symtab = TRUE;
5213 	  seenflag = TRUE;
5214 	  break;
5215 	case 'T':
5216 	  dump_dynamic_symtab = TRUE;
5217 	  seenflag = TRUE;
5218 	  break;
5219 	case 'd':
5220 	  disassemble = TRUE;
5221 	  seenflag = TRUE;
5222 	  disasm_sym = optarg;
5223 	  break;
5224 	case 'z':
5225 	  disassemble_zeroes = TRUE;
5226 	  break;
5227 	case 'D':
5228 	  disassemble = TRUE;
5229 	  disassemble_all = TRUE;
5230 	  seenflag = TRUE;
5231 	  break;
5232 	case 'S':
5233 	  disassemble = TRUE;
5234 	  with_source_code = TRUE;
5235 	  seenflag = TRUE;
5236 	  break;
5237 	case OPTION_SOURCE_COMMENT:
5238 	  disassemble = TRUE;
5239 	  with_source_code = TRUE;
5240 	  seenflag = TRUE;
5241 	  if (optarg)
5242 	    source_comment = xstrdup (sanitize_string (optarg));
5243 	  else
5244 	    source_comment = xstrdup ("# ");
5245 	  break;
5246 	case 'g':
5247 	  dump_debugging = 1;
5248 	  seenflag = TRUE;
5249 	  break;
5250 	case 'e':
5251 	  dump_debugging = 1;
5252 	  dump_debugging_tags = 1;
5253 	  do_demangle = TRUE;
5254 	  seenflag = TRUE;
5255 	  break;
5256 	case 'W':
5257 	  dump_dwarf_section_info = TRUE;
5258 	  seenflag = TRUE;
5259 	  if (optarg)
5260 	    dwarf_select_sections_by_letters (optarg);
5261 	  else
5262 	    dwarf_select_sections_all ();
5263 	  break;
5264 	case OPTION_DWARF:
5265 	  dump_dwarf_section_info = TRUE;
5266 	  seenflag = TRUE;
5267 	  if (optarg)
5268 	    dwarf_select_sections_by_names (optarg);
5269 	  else
5270 	    dwarf_select_sections_all ();
5271 	  break;
5272 	case OPTION_DWARF_DEPTH:
5273 	  {
5274 	    char *cp;
5275 	    dwarf_cutoff_level = strtoul (optarg, & cp, 0);
5276 	  }
5277 	  break;
5278 	case OPTION_DWARF_START:
5279 	  {
5280 	    char *cp;
5281 	    dwarf_start_die = strtoul (optarg, & cp, 0);
5282 	    suppress_bfd_header = 1;
5283 	  }
5284 	  break;
5285 	case OPTION_DWARF_CHECK:
5286 	  dwarf_check = TRUE;
5287 	  break;
5288 	case OPTION_CTF:
5289 	  dump_ctf_section_info = TRUE;
5290 	  dump_ctf_section_name = xstrdup (optarg);
5291 	  seenflag = TRUE;
5292 	  break;
5293 	case OPTION_CTF_PARENT:
5294 	  dump_ctf_parent_name = xstrdup (optarg);
5295 	  break;
5296 	case 'G':
5297 	  dump_stab_section_info = TRUE;
5298 	  seenflag = TRUE;
5299 	  break;
5300 	case 's':
5301 	  dump_section_contents = TRUE;
5302 	  seenflag = TRUE;
5303 	  break;
5304 	case 'r':
5305 	  dump_reloc_info = TRUE;
5306 	  seenflag = TRUE;
5307 	  break;
5308 	case 'R':
5309 	  dump_dynamic_reloc_info = TRUE;
5310 	  seenflag = TRUE;
5311 	  break;
5312 	case 'a':
5313 	  dump_ar_hdrs = TRUE;
5314 	  seenflag = TRUE;
5315 	  break;
5316 	case 'h':
5317 	  dump_section_headers = TRUE;
5318 	  seenflag = TRUE;
5319 	  break;
5320 	case 'v':
5321 	case 'V':
5322 	  show_version = TRUE;
5323 	  seenflag = TRUE;
5324 	  break;
5325 
5326 	case 'H':
5327 	  usage (stdout, 0);
5328 	  /* No need to set seenflag or to break - usage() does not return.  */
5329 	default:
5330 	  usage (stderr, 1);
5331 	}
5332     }
5333 
5334   if (show_version)
5335     print_version ("objdump");
5336 
5337   if (!seenflag)
5338     usage (stderr, 2);
5339 
5340   if (formats_info)
5341     exit_status = display_info ();
5342   else
5343     {
5344       if (optind == argc)
5345 	display_file ("a.out", target, TRUE);
5346       else
5347 	for (; optind < argc;)
5348 	  {
5349 	    display_file (argv[optind], target, optind == argc - 1);
5350 	    optind++;
5351 	  }
5352     }
5353 
5354   free_only_list ();
5355   free (dump_ctf_section_name);
5356   free (dump_ctf_parent_name);
5357   free ((void *) source_comment);
5358 
5359   END_PROGRESS (program_name);
5360 
5361   return exit_status;
5362 }
5363