* objdump.c (print_line): Check fwrite return value.
[external/binutils.git] / binutils / objdump.c
1 /* objdump.c -- dump information about an object file.
2    Copyright 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
3    2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
4    Free Software Foundation, Inc.
5
6    This file is part of GNU Binutils.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3, or (at your option)
11    any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, 51 Franklin Street - Fifth Floor, Boston,
21    MA 02110-1301, USA.  */
22
23
24 /* Objdump overview.
25
26    Objdump displays information about one or more object files, either on
27    their own, or inside libraries.  It is commonly used as a disassembler,
28    but it can also display information about file headers, symbol tables,
29    relocations, debugging directives and more.
30
31    The flow of execution is as follows:
32  
33    1. Command line arguments are checked for control switches and the
34       information to be displayed is selected.
35       
36    2. Any remaining arguments are assumed to be object files, and they are
37       processed in order by display_bfd().  If the file is an archive each
38       of its elements is processed in turn.
39       
40    3. The file's target architecture and binary file format are determined
41       by bfd_check_format().  If they are recognised, then dump_bfd() is
42       called.
43
44    4. dump_bfd() in turn calls separate functions to display the requested
45       item(s) of information(s).  For example disassemble_data() is called if
46       a disassembly has been requested.
47
48    When disassembling the code loops through blocks of instructions bounded
49    by symbols, calling disassemble_bytes() on each block.  The actual
50    disassembling is done by the libopcodes library, via a function pointer
51    supplied by the disassembler() function.  */
52
53 #include "sysdep.h"
54 #include "bfd.h"
55 #include "progress.h"
56 #include "bucomm.h"
57 #include "dwarf.h"
58 #include "getopt.h"
59 #include "safe-ctype.h"
60 #include "dis-asm.h"
61 #include "libiberty.h"
62 #include "demangle.h"
63 #include "debug.h"
64 #include "budbg.h"
65
66 #ifdef HAVE_MMAP
67 #include <sys/mman.h>
68 #endif
69
70 #include <sys/stat.h>
71
72 /* Internal headers for the ELF .stab-dump code - sorry.  */
73 #define BYTES_IN_WORD   32
74 #include "aout/aout64.h"
75
76 /* Exit status.  */
77 static int exit_status = 0;
78
79 static char *default_target = NULL;     /* Default at runtime.  */
80
81 /* The following variables are set based on arguments passed on the
82    command line.  */
83 static int show_version = 0;            /* Show the version number.  */
84 static int dump_section_contents;       /* -s */
85 static int dump_section_headers;        /* -h */
86 static bfd_boolean dump_file_header;    /* -f */
87 static int dump_symtab;                 /* -t */
88 static int dump_dynamic_symtab;         /* -T */
89 static int dump_reloc_info;             /* -r */
90 static int dump_dynamic_reloc_info;     /* -R */
91 static int dump_ar_hdrs;                /* -a */
92 static int dump_private_headers;        /* -p */
93 static int prefix_addresses;            /* --prefix-addresses */
94 static int with_line_numbers;           /* -l */
95 static bfd_boolean with_source_code;    /* -S */
96 static int show_raw_insn;               /* --show-raw-insn */
97 static int dump_dwarf_section_info;     /* --dwarf */
98 static int dump_stab_section_info;      /* --stabs */
99 static int do_demangle;                 /* -C, --demangle */
100 static bfd_boolean disassemble;         /* -d */
101 static bfd_boolean disassemble_all;     /* -D */
102 static int disassemble_zeroes;          /* --disassemble-zeroes */
103 static bfd_boolean formats_info;        /* -i */
104 static int wide_output;                 /* -w */
105 static bfd_vma start_address = (bfd_vma) -1; /* --start-address */
106 static bfd_vma stop_address = (bfd_vma) -1;  /* --stop-address */
107 static int dump_debugging;              /* --debugging */
108 static int dump_debugging_tags;         /* --debugging-tags */
109 static int dump_special_syms = 0;       /* --special-syms */
110 static bfd_vma adjust_section_vma = 0;  /* --adjust-vma */
111 static int file_start_context = 0;      /* --file-start-context */
112
113 /* Pointer to an array of section names provided by
114    one or more "-j secname" command line options.  */
115 static char **only;
116 /* The total number of slots in the only[] array.  */
117 static size_t only_size = 0;
118 /* The number of occupied slots in the only[] array.  */
119 static size_t only_used = 0;
120
121 /* Variables for handling include file path table.  */
122 static const char **include_paths;
123 static int include_path_count;
124
125 /* Extra info to pass to the section disassembler and address printing
126    function.  */
127 struct objdump_disasm_info
128 {
129   bfd *              abfd;
130   asection *         sec;
131   bfd_boolean        require_sec;
132   arelent **         dynrelbuf;
133   long               dynrelcount;
134   disassembler_ftype disassemble_fn;
135   arelent *          reloc;
136 };
137
138 /* Architecture to disassemble for, or default if NULL.  */
139 static char *machine = NULL;
140
141 /* Target specific options to the disassembler.  */
142 static char *disassembler_options = NULL;
143
144 /* Endianness to disassemble for, or default if BFD_ENDIAN_UNKNOWN.  */
145 static enum bfd_endian endian = BFD_ENDIAN_UNKNOWN;
146
147 /* The symbol table.  */
148 static asymbol **syms;
149
150 /* Number of symbols in `syms'.  */
151 static long symcount = 0;
152
153 /* The sorted symbol table.  */
154 static asymbol **sorted_syms;
155
156 /* Number of symbols in `sorted_syms'.  */
157 static long sorted_symcount = 0;
158
159 /* The dynamic symbol table.  */
160 static asymbol **dynsyms;
161
162 /* The synthetic symbol table.  */
163 static asymbol *synthsyms;
164 static long synthcount = 0;
165
166 /* Number of symbols in `dynsyms'.  */
167 static long dynsymcount = 0;
168
169 static bfd_byte *stabs;
170 static bfd_size_type stab_size;
171
172 static char *strtab;
173 static bfd_size_type stabstr_size;
174 \f
175 static void
176 usage (FILE *stream, int status)
177 {
178   fprintf (stream, _("Usage: %s <option(s)> <file(s)>\n"), program_name);
179   fprintf (stream, _(" Display information from object <file(s)>.\n"));
180   fprintf (stream, _(" At least one of the following switches must be given:\n"));
181   fprintf (stream, _("\
182   -a, --archive-headers    Display archive header information\n\
183   -f, --file-headers       Display the contents of the overall file header\n\
184   -p, --private-headers    Display object format specific file header contents\n\
185   -h, --[section-]headers  Display the contents of the section headers\n\
186   -x, --all-headers        Display the contents of all headers\n\
187   -d, --disassemble        Display assembler contents of executable sections\n\
188   -D, --disassemble-all    Display assembler contents of all sections\n\
189   -S, --source             Intermix source code with disassembly\n\
190   -s, --full-contents      Display the full contents of all sections requested\n\
191   -g, --debugging          Display debug information in object file\n\
192   -e, --debugging-tags     Display debug information using ctags style\n\
193   -G, --stabs              Display (in raw form) any STABS info in the file\n\
194   -W, --dwarf              Display DWARF info in the file\n\
195   -t, --syms               Display the contents of the symbol table(s)\n\
196   -T, --dynamic-syms       Display the contents of the dynamic symbol table\n\
197   -r, --reloc              Display the relocation entries in the file\n\
198   -R, --dynamic-reloc      Display the dynamic relocation entries in the file\n\
199   @<file>                  Read options from <file>\n\
200   -v, --version            Display this program's version number\n\
201   -i, --info               List object formats and architectures supported\n\
202   -H, --help               Display this information\n\
203 "));
204   if (status != 2)
205     {
206       fprintf (stream, _("\n The following switches are optional:\n"));
207       fprintf (stream, _("\
208   -b, --target=BFDNAME           Specify the target object format as BFDNAME\n\
209   -m, --architecture=MACHINE     Specify the target architecture as MACHINE\n\
210   -j, --section=NAME             Only display information for section NAME\n\
211   -M, --disassembler-options=OPT Pass text OPT on to the disassembler\n\
212   -EB --endian=big               Assume big endian format when disassembling\n\
213   -EL --endian=little            Assume little endian format when disassembling\n\
214       --file-start-context       Include context from start of file (with -S)\n\
215   -I, --include=DIR              Add DIR to search list for source files\n\
216   -l, --line-numbers             Include line numbers and filenames in output\n\
217   -C, --demangle[=STYLE]         Decode mangled/processed symbol names\n\
218                                   The STYLE, if specified, can be `auto', `gnu',\n\
219                                   `lucid', `arm', `hp', `edg', `gnu-v3', `java'\n\
220                                   or `gnat'\n\
221   -w, --wide                     Format output for more than 80 columns\n\
222   -z, --disassemble-zeroes       Do not skip blocks of zeroes when disassembling\n\
223       --start-address=ADDR       Only process data whose address is >= ADDR\n\
224       --stop-address=ADDR        Only process data whose address is <= ADDR\n\
225       --prefix-addresses         Print complete address alongside disassembly\n\
226       --[no-]show-raw-insn       Display hex alongside symbolic disassembly\n\
227       --adjust-vma=OFFSET        Add OFFSET to all displayed section addresses\n\
228       --special-syms             Include special symbols in symbol dumps\n\
229 \n"));
230       list_supported_targets (program_name, stream);
231       list_supported_architectures (program_name, stream);
232
233       disassembler_usage (stream);
234     }
235   if (REPORT_BUGS_TO[0] && status == 0)
236     fprintf (stream, _("Report bugs to %s.\n"), REPORT_BUGS_TO);
237   exit (status);
238 }
239
240 /* 150 isn't special; it's just an arbitrary non-ASCII char value.  */
241 enum option_values
242   {
243     OPTION_ENDIAN=150,
244     OPTION_START_ADDRESS,
245     OPTION_STOP_ADDRESS,
246     OPTION_ADJUST_VMA
247   };
248
249 static struct option long_options[]=
250 {
251   {"adjust-vma", required_argument, NULL, OPTION_ADJUST_VMA},
252   {"all-headers", no_argument, NULL, 'x'},
253   {"private-headers", no_argument, NULL, 'p'},
254   {"architecture", required_argument, NULL, 'm'},
255   {"archive-headers", no_argument, NULL, 'a'},
256   {"debugging", no_argument, NULL, 'g'},
257   {"debugging-tags", no_argument, NULL, 'e'},
258   {"demangle", optional_argument, NULL, 'C'},
259   {"disassemble", no_argument, NULL, 'd'},
260   {"disassemble-all", no_argument, NULL, 'D'},
261   {"disassembler-options", required_argument, NULL, 'M'},
262   {"disassemble-zeroes", no_argument, NULL, 'z'},
263   {"dynamic-reloc", no_argument, NULL, 'R'},
264   {"dynamic-syms", no_argument, NULL, 'T'},
265   {"endian", required_argument, NULL, OPTION_ENDIAN},
266   {"file-headers", no_argument, NULL, 'f'},
267   {"file-start-context", no_argument, &file_start_context, 1},
268   {"full-contents", no_argument, NULL, 's'},
269   {"headers", no_argument, NULL, 'h'},
270   {"help", no_argument, NULL, 'H'},
271   {"info", no_argument, NULL, 'i'},
272   {"line-numbers", no_argument, NULL, 'l'},
273   {"no-show-raw-insn", no_argument, &show_raw_insn, -1},
274   {"prefix-addresses", no_argument, &prefix_addresses, 1},
275   {"reloc", no_argument, NULL, 'r'},
276   {"section", required_argument, NULL, 'j'},
277   {"section-headers", no_argument, NULL, 'h'},
278   {"show-raw-insn", no_argument, &show_raw_insn, 1},
279   {"source", no_argument, NULL, 'S'},
280   {"special-syms", no_argument, &dump_special_syms, 1},
281   {"include", required_argument, NULL, 'I'},
282   {"dwarf", no_argument, NULL, 'W'},
283   {"stabs", no_argument, NULL, 'G'},
284   {"start-address", required_argument, NULL, OPTION_START_ADDRESS},
285   {"stop-address", required_argument, NULL, OPTION_STOP_ADDRESS},
286   {"syms", no_argument, NULL, 't'},
287   {"target", required_argument, NULL, 'b'},
288   {"version", no_argument, NULL, 'V'},
289   {"wide", no_argument, NULL, 'w'},
290   {0, no_argument, 0, 0}
291 };
292 \f
293 static void
294 nonfatal (const char *msg)
295 {
296   bfd_nonfatal (msg);
297   exit_status = 1;
298 }
299 \f
300 static void
301 dump_section_header (bfd *abfd, asection *section,
302                      void *ignored ATTRIBUTE_UNUSED)
303 {
304   char *comma = "";
305   unsigned int opb = bfd_octets_per_byte (abfd);
306
307   /* Ignore linker created section.  See elfNN_ia64_object_p in
308      bfd/elfxx-ia64.c.  */
309   if (section->flags & SEC_LINKER_CREATED)
310     return;
311
312   printf ("%3d %-13s %08lx  ", section->index,
313           bfd_get_section_name (abfd, section),
314           (unsigned long) bfd_section_size (abfd, section) / opb);
315   bfd_printf_vma (abfd, bfd_get_section_vma (abfd, section));
316   printf ("  ");
317   bfd_printf_vma (abfd, section->lma);
318   printf ("  %08lx  2**%u", (unsigned long) section->filepos,
319           bfd_get_section_alignment (abfd, section));
320   if (! wide_output)
321     printf ("\n                ");
322   printf ("  ");
323
324 #define PF(x, y) \
325   if (section->flags & x) { printf ("%s%s", comma, y); comma = ", "; }
326
327   PF (SEC_HAS_CONTENTS, "CONTENTS");
328   PF (SEC_ALLOC, "ALLOC");
329   PF (SEC_CONSTRUCTOR, "CONSTRUCTOR");
330   PF (SEC_LOAD, "LOAD");
331   PF (SEC_RELOC, "RELOC");
332   PF (SEC_READONLY, "READONLY");
333   PF (SEC_CODE, "CODE");
334   PF (SEC_DATA, "DATA");
335   PF (SEC_ROM, "ROM");
336   PF (SEC_DEBUGGING, "DEBUGGING");
337   PF (SEC_NEVER_LOAD, "NEVER_LOAD");
338   PF (SEC_EXCLUDE, "EXCLUDE");
339   PF (SEC_SORT_ENTRIES, "SORT_ENTRIES");
340   if (bfd_get_arch (abfd) == bfd_arch_tic54x)
341     {
342       PF (SEC_TIC54X_BLOCK, "BLOCK");
343       PF (SEC_TIC54X_CLINK, "CLINK");
344     }
345   PF (SEC_SMALL_DATA, "SMALL_DATA");
346   if (bfd_get_flavour (abfd) == bfd_target_coff_flavour)
347     PF (SEC_COFF_SHARED, "SHARED");
348   PF (SEC_THREAD_LOCAL, "THREAD_LOCAL");
349   PF (SEC_GROUP, "GROUP");
350
351   if ((section->flags & SEC_LINK_ONCE) != 0)
352     {
353       const char *ls;
354       struct coff_comdat_info *comdat;
355
356       switch (section->flags & SEC_LINK_DUPLICATES)
357         {
358         default:
359           abort ();
360         case SEC_LINK_DUPLICATES_DISCARD:
361           ls = "LINK_ONCE_DISCARD";
362           break;
363         case SEC_LINK_DUPLICATES_ONE_ONLY:
364           ls = "LINK_ONCE_ONE_ONLY";
365           break;
366         case SEC_LINK_DUPLICATES_SAME_SIZE:
367           ls = "LINK_ONCE_SAME_SIZE";
368           break;
369         case SEC_LINK_DUPLICATES_SAME_CONTENTS:
370           ls = "LINK_ONCE_SAME_CONTENTS";
371           break;
372         }
373       printf ("%s%s", comma, ls);
374
375       comdat = bfd_coff_get_comdat_section (abfd, section);
376       if (comdat != NULL)
377         printf (" (COMDAT %s %ld)", comdat->name, comdat->symbol);
378
379       comma = ", ";
380     }
381
382   printf ("\n");
383 #undef PF
384 }
385
386 static void
387 dump_headers (bfd *abfd)
388 {
389   printf (_("Sections:\n"));
390
391 #ifndef BFD64
392   printf (_("Idx Name          Size      VMA       LMA       File off  Algn"));
393 #else
394   /* With BFD64, non-ELF returns -1 and wants always 64 bit addresses.  */
395   if (bfd_get_arch_size (abfd) == 32)
396     printf (_("Idx Name          Size      VMA       LMA       File off  Algn"));
397   else
398     printf (_("Idx Name          Size      VMA               LMA               File off  Algn"));
399 #endif
400
401   if (wide_output)
402     printf (_("  Flags"));
403   if (abfd->flags & HAS_LOAD_PAGE)
404     printf (_("  Pg"));
405   printf ("\n");
406
407   bfd_map_over_sections (abfd, dump_section_header, NULL);
408 }
409 \f
410 static asymbol **
411 slurp_symtab (bfd *abfd)
412 {
413   asymbol **sy = NULL;
414   long storage;
415
416   if (!(bfd_get_file_flags (abfd) & HAS_SYMS))
417     {
418       symcount = 0;
419       return NULL;
420     }
421
422   storage = bfd_get_symtab_upper_bound (abfd);
423   if (storage < 0)
424     bfd_fatal (bfd_get_filename (abfd));
425   if (storage)
426     sy = xmalloc (storage);
427
428   symcount = bfd_canonicalize_symtab (abfd, sy);
429   if (symcount < 0)
430     bfd_fatal (bfd_get_filename (abfd));
431   return sy;
432 }
433
434 /* Read in the dynamic symbols.  */
435
436 static asymbol **
437 slurp_dynamic_symtab (bfd *abfd)
438 {
439   asymbol **sy = NULL;
440   long storage;
441
442   storage = bfd_get_dynamic_symtab_upper_bound (abfd);
443   if (storage < 0)
444     {
445       if (!(bfd_get_file_flags (abfd) & DYNAMIC))
446         {
447           non_fatal (_("%s: not a dynamic object"), bfd_get_filename (abfd));
448           dynsymcount = 0;
449           return NULL;
450         }
451
452       bfd_fatal (bfd_get_filename (abfd));
453     }
454   if (storage)
455     sy = xmalloc (storage);
456
457   dynsymcount = bfd_canonicalize_dynamic_symtab (abfd, sy);
458   if (dynsymcount < 0)
459     bfd_fatal (bfd_get_filename (abfd));
460   return sy;
461 }
462
463 /* Filter out (in place) symbols that are useless for disassembly.
464    COUNT is the number of elements in SYMBOLS.
465    Return the number of useful symbols.  */
466
467 static long
468 remove_useless_symbols (asymbol **symbols, long count)
469 {
470   asymbol **in_ptr = symbols, **out_ptr = symbols;
471
472   while (--count >= 0)
473     {
474       asymbol *sym = *in_ptr++;
475
476       if (sym->name == NULL || sym->name[0] == '\0')
477         continue;
478       if (sym->flags & (BSF_DEBUGGING | BSF_SECTION_SYM))
479         continue;
480       if (bfd_is_und_section (sym->section)
481           || bfd_is_com_section (sym->section))
482         continue;
483
484       *out_ptr++ = sym;
485     }
486   return out_ptr - symbols;
487 }
488
489 /* Sort symbols into value order.  */
490
491 static int
492 compare_symbols (const void *ap, const void *bp)
493 {
494   const asymbol *a = * (const asymbol **) ap;
495   const asymbol *b = * (const asymbol **) bp;
496   const char *an;
497   const char *bn;
498   size_t anl;
499   size_t bnl;
500   bfd_boolean af;
501   bfd_boolean bf;
502   flagword aflags;
503   flagword bflags;
504
505   if (bfd_asymbol_value (a) > bfd_asymbol_value (b))
506     return 1;
507   else if (bfd_asymbol_value (a) < bfd_asymbol_value (b))
508     return -1;
509
510   if (a->section > b->section)
511     return 1;
512   else if (a->section < b->section)
513     return -1;
514
515   an = bfd_asymbol_name (a);
516   bn = bfd_asymbol_name (b);
517   anl = strlen (an);
518   bnl = strlen (bn);
519
520   /* The symbols gnu_compiled and gcc2_compiled convey no real
521      information, so put them after other symbols with the same value.  */
522   af = (strstr (an, "gnu_compiled") != NULL
523         || strstr (an, "gcc2_compiled") != NULL);
524   bf = (strstr (bn, "gnu_compiled") != NULL
525         || strstr (bn, "gcc2_compiled") != NULL);
526
527   if (af && ! bf)
528     return 1;
529   if (! af && bf)
530     return -1;
531
532   /* We use a heuristic for the file name, to try to sort it after
533      more useful symbols.  It may not work on non Unix systems, but it
534      doesn't really matter; the only difference is precisely which
535      symbol names get printed.  */
536
537 #define file_symbol(s, sn, snl)                 \
538   (((s)->flags & BSF_FILE) != 0                 \
539    || ((sn)[(snl) - 2] == '.'                   \
540        && ((sn)[(snl) - 1] == 'o'               \
541            || (sn)[(snl) - 1] == 'a')))
542
543   af = file_symbol (a, an, anl);
544   bf = file_symbol (b, bn, bnl);
545
546   if (af && ! bf)
547     return 1;
548   if (! af && bf)
549     return -1;
550
551   /* Try to sort global symbols before local symbols before function
552      symbols before debugging symbols.  */
553
554   aflags = a->flags;
555   bflags = b->flags;
556
557   if ((aflags & BSF_DEBUGGING) != (bflags & BSF_DEBUGGING))
558     {
559       if ((aflags & BSF_DEBUGGING) != 0)
560         return 1;
561       else
562         return -1;
563     }
564   if ((aflags & BSF_FUNCTION) != (bflags & BSF_FUNCTION))
565     {
566       if ((aflags & BSF_FUNCTION) != 0)
567         return -1;
568       else
569         return 1;
570     }
571   if ((aflags & BSF_LOCAL) != (bflags & BSF_LOCAL))
572     {
573       if ((aflags & BSF_LOCAL) != 0)
574         return 1;
575       else
576         return -1;
577     }
578   if ((aflags & BSF_GLOBAL) != (bflags & BSF_GLOBAL))
579     {
580       if ((aflags & BSF_GLOBAL) != 0)
581         return -1;
582       else
583         return 1;
584     }
585
586   /* Symbols that start with '.' might be section names, so sort them
587      after symbols that don't start with '.'.  */
588   if (an[0] == '.' && bn[0] != '.')
589     return 1;
590   if (an[0] != '.' && bn[0] == '.')
591     return -1;
592
593   /* Finally, if we can't distinguish them in any other way, try to
594      get consistent results by sorting the symbols by name.  */
595   return strcmp (an, bn);
596 }
597
598 /* Sort relocs into address order.  */
599
600 static int
601 compare_relocs (const void *ap, const void *bp)
602 {
603   const arelent *a = * (const arelent **) ap;
604   const arelent *b = * (const arelent **) bp;
605
606   if (a->address > b->address)
607     return 1;
608   else if (a->address < b->address)
609     return -1;
610
611   /* So that associated relocations tied to the same address show up
612      in the correct order, we don't do any further sorting.  */
613   if (a > b)
614     return 1;
615   else if (a < b)
616     return -1;
617   else
618     return 0;
619 }
620
621 /* Print an address (VMA) to the output stream in INFO.
622    If SKIP_ZEROES is TRUE, omit leading zeroes.  */
623
624 static void
625 objdump_print_value (bfd_vma vma, struct disassemble_info *info,
626                      bfd_boolean skip_zeroes)
627 {
628   char buf[30];
629   char *p;
630   struct objdump_disasm_info *aux;
631
632   aux = (struct objdump_disasm_info *) info->application_data;
633   bfd_sprintf_vma (aux->abfd, buf, vma);
634   if (! skip_zeroes)
635     p = buf;
636   else
637     {
638       for (p = buf; *p == '0'; ++p)
639         ;
640       if (*p == '\0')
641         --p;
642     }
643   (*info->fprintf_func) (info->stream, "%s", p);
644 }
645
646 /* Print the name of a symbol.  */
647
648 static void
649 objdump_print_symname (bfd *abfd, struct disassemble_info *info,
650                        asymbol *sym)
651 {
652   char *alloc;
653   const char *name;
654
655   alloc = NULL;
656   name = bfd_asymbol_name (sym);
657   if (do_demangle && name[0] != '\0')
658     {
659       /* Demangle the name.  */
660       alloc = bfd_demangle (abfd, name, DMGL_ANSI | DMGL_PARAMS);
661       if (alloc != NULL)
662         name = alloc;
663     }
664
665   if (info != NULL)
666     (*info->fprintf_func) (info->stream, "%s", name);
667   else
668     printf ("%s", name);
669
670   if (alloc != NULL)
671     free (alloc);
672 }
673
674 /* Locate a symbol given a bfd and a section (from INFO->application_data),
675    and a VMA.  If INFO->application_data->require_sec is TRUE, then always
676    require the symbol to be in the section.  Returns NULL if there is no
677    suitable symbol.  If PLACE is not NULL, then *PLACE is set to the index
678    of the symbol in sorted_syms.  */
679
680 static asymbol *
681 find_symbol_for_address (bfd_vma vma,
682                          struct disassemble_info *info,
683                          long *place)
684 {
685   /* @@ Would it speed things up to cache the last two symbols returned,
686      and maybe their address ranges?  For many processors, only one memory
687      operand can be present at a time, so the 2-entry cache wouldn't be
688      constantly churned by code doing heavy memory accesses.  */
689
690   /* Indices in `sorted_syms'.  */
691   long min = 0;
692   long max = sorted_symcount;
693   long thisplace;
694   struct objdump_disasm_info *aux;
695   bfd *abfd;
696   asection *sec;
697   unsigned int opb;
698   bfd_boolean want_section;
699
700   if (sorted_symcount < 1)
701     return NULL;
702
703   aux = (struct objdump_disasm_info *) info->application_data;
704   abfd = aux->abfd;
705   sec = aux->sec;
706   opb = bfd_octets_per_byte (abfd);
707
708   /* Perform a binary search looking for the closest symbol to the
709      required value.  We are searching the range (min, max].  */
710   while (min + 1 < max)
711     {
712       asymbol *sym;
713
714       thisplace = (max + min) / 2;
715       sym = sorted_syms[thisplace];
716
717       if (bfd_asymbol_value (sym) > vma)
718         max = thisplace;
719       else if (bfd_asymbol_value (sym) < vma)
720         min = thisplace;
721       else
722         {
723           min = thisplace;
724           break;
725         }
726     }
727
728   /* The symbol we want is now in min, the low end of the range we
729      were searching.  If there are several symbols with the same
730      value, we want the first one.  */
731   thisplace = min;
732   while (thisplace > 0
733          && (bfd_asymbol_value (sorted_syms[thisplace])
734              == bfd_asymbol_value (sorted_syms[thisplace - 1])))
735     --thisplace;
736
737   /* If the file is relocatable, and the symbol could be from this
738      section, prefer a symbol from this section over symbols from
739      others, even if the other symbol's value might be closer.
740
741      Note that this may be wrong for some symbol references if the
742      sections have overlapping memory ranges, but in that case there's
743      no way to tell what's desired without looking at the relocation
744      table.
745      
746      Also give the target a chance to reject symbols.  */
747   want_section = (aux->require_sec
748                   || ((abfd->flags & HAS_RELOC) != 0
749                       && vma >= bfd_get_section_vma (abfd, sec)
750                       && vma < (bfd_get_section_vma (abfd, sec)
751                                 + bfd_section_size (abfd, sec) / opb)));
752   if ((sorted_syms[thisplace]->section != sec && want_section)
753       || !info->symbol_is_valid (sorted_syms[thisplace], info))
754     {
755       long i;
756       long newplace;
757
758       for (i = thisplace + 1; i < sorted_symcount; i++)
759         {
760           if (bfd_asymbol_value (sorted_syms[i])
761               != bfd_asymbol_value (sorted_syms[thisplace]))
762             break;
763         }
764
765       --i;
766       newplace = sorted_symcount;
767
768       for (; i >= 0; i--)
769         {
770           if ((sorted_syms[i]->section == sec || !want_section)
771               && info->symbol_is_valid (sorted_syms[i], info))
772             {
773               if (newplace == sorted_symcount)
774                 newplace = i;
775
776               if (bfd_asymbol_value (sorted_syms[i])
777                   != bfd_asymbol_value (sorted_syms[newplace]))
778                 break;
779
780               /* Remember this symbol and keep searching until we reach
781                  an earlier address.  */
782               newplace = i;
783             }
784         }
785
786       if (newplace != sorted_symcount)
787         thisplace = newplace;
788       else
789         {
790           /* We didn't find a good symbol with a smaller value.
791              Look for one with a larger value.  */
792           for (i = thisplace + 1; i < sorted_symcount; i++)
793             {
794               if ((sorted_syms[i]->section == sec || !want_section)
795                   && info->symbol_is_valid (sorted_syms[i], info))
796                 {
797                   thisplace = i;
798                   break;
799                 }
800             }
801         }
802
803       if ((sorted_syms[thisplace]->section != sec && want_section)
804           || !info->symbol_is_valid (sorted_syms[thisplace], info))
805         /* There is no suitable symbol.  */
806         return NULL;
807     }
808
809   if (place != NULL)
810     *place = thisplace;
811
812   return sorted_syms[thisplace];
813 }
814
815 /* Print an address and the offset to the nearest symbol.  */
816
817 static void
818 objdump_print_addr_with_sym (bfd *abfd, asection *sec, asymbol *sym,
819                              bfd_vma vma, struct disassemble_info *info,
820                              bfd_boolean skip_zeroes)
821 {
822   objdump_print_value (vma, info, skip_zeroes);
823
824   if (sym == NULL)
825     {
826       bfd_vma secaddr;
827
828       (*info->fprintf_func) (info->stream, " <%s",
829                              bfd_get_section_name (abfd, sec));
830       secaddr = bfd_get_section_vma (abfd, sec);
831       if (vma < secaddr)
832         {
833           (*info->fprintf_func) (info->stream, "-0x");
834           objdump_print_value (secaddr - vma, info, TRUE);
835         }
836       else if (vma > secaddr)
837         {
838           (*info->fprintf_func) (info->stream, "+0x");
839           objdump_print_value (vma - secaddr, info, TRUE);
840         }
841       (*info->fprintf_func) (info->stream, ">");
842     }
843   else
844     {
845       (*info->fprintf_func) (info->stream, " <");
846       objdump_print_symname (abfd, info, sym);
847       if (bfd_asymbol_value (sym) > vma)
848         {
849           (*info->fprintf_func) (info->stream, "-0x");
850           objdump_print_value (bfd_asymbol_value (sym) - vma, info, TRUE);
851         }
852       else if (vma > bfd_asymbol_value (sym))
853         {
854           (*info->fprintf_func) (info->stream, "+0x");
855           objdump_print_value (vma - bfd_asymbol_value (sym), info, TRUE);
856         }
857       (*info->fprintf_func) (info->stream, ">");
858     }
859 }
860
861 /* Print an address (VMA), symbolically if possible.
862    If SKIP_ZEROES is TRUE, don't output leading zeroes.  */
863
864 static void
865 objdump_print_addr (bfd_vma vma,
866                     struct disassemble_info *info,
867                     bfd_boolean skip_zeroes)
868 {
869   struct objdump_disasm_info *aux;
870   asymbol *sym = NULL; /* Initialize to avoid compiler warning.  */
871   bfd_boolean skip_find = FALSE;
872
873   if (sorted_symcount < 1)
874     {
875       (*info->fprintf_func) (info->stream, "0x");
876       objdump_print_value (vma, info, skip_zeroes);
877       return;
878     }
879
880   aux = (struct objdump_disasm_info *) info->application_data;
881
882   if (aux->reloc != NULL
883       && aux->reloc->sym_ptr_ptr != NULL
884       && * aux->reloc->sym_ptr_ptr != NULL)
885     {
886       sym = * aux->reloc->sym_ptr_ptr;
887
888       /* Adjust the vma to the reloc.  */
889       vma += bfd_asymbol_value (sym);
890
891       if (bfd_is_und_section (bfd_get_section (sym)))
892         skip_find = TRUE;
893     }
894
895   if (!skip_find)
896     sym = find_symbol_for_address (vma, info, NULL);
897
898   objdump_print_addr_with_sym (aux->abfd, aux->sec, sym, vma, info,
899                                skip_zeroes);
900 }
901
902 /* Print VMA to INFO.  This function is passed to the disassembler
903    routine.  */
904
905 static void
906 objdump_print_address (bfd_vma vma, struct disassemble_info *info)
907 {
908   objdump_print_addr (vma, info, ! prefix_addresses);
909 }
910
911 /* Determine if the given address has a symbol associated with it.  */
912
913 static int
914 objdump_symbol_at_address (bfd_vma vma, struct disassemble_info * info)
915 {
916   asymbol * sym;
917
918   sym = find_symbol_for_address (vma, info, NULL);
919
920   return (sym != NULL && (bfd_asymbol_value (sym) == vma));
921 }
922
923 /* Hold the last function name and the last line number we displayed
924    in a disassembly.  */
925
926 static char *prev_functionname;
927 static unsigned int prev_line;
928
929 /* We keep a list of all files that we have seen when doing a
930    disassembly with source, so that we know how much of the file to
931    display.  This can be important for inlined functions.  */
932
933 struct print_file_list
934 {
935   struct print_file_list *next;
936   const char *filename;
937   const char *modname;
938   const char *map; 
939   size_t mapsize;
940   const char **linemap; 
941   unsigned maxline;
942   unsigned last_line;
943   int first;
944 };
945
946 static struct print_file_list *print_files;
947
948 /* The number of preceding context lines to show when we start
949    displaying a file for the first time.  */
950
951 #define SHOW_PRECEDING_CONTEXT_LINES (5)
952
953 /* Read a complete file into memory. */
954
955 static const char *
956 slurp_file (const char *fn, size_t *size)
957 {
958 #ifdef HAVE_MMAP
959   int ps = getpagesize ();
960   size_t msize;
961 #endif
962   const char *map;
963   struct stat st;
964   int fd = open (fn, O_RDONLY);
965
966   if (fd < 0)
967     return NULL;
968   if (fstat (fd, &st) < 0)
969     return NULL;
970   *size = st.st_size;
971 #ifdef HAVE_MMAP
972   msize = (*size + ps - 1) & ~(ps - 1);
973   map = mmap (NULL, msize, PROT_READ, MAP_SHARED, fd, 0);
974   if (map != (char *)-1L)
975     {
976       close(fd);
977       return map; 
978     }
979 #endif
980   map = malloc (*size);
981   if (!map || (size_t) read (fd, (char *)map, *size) != *size) 
982     { 
983       free ((void *)map);
984       map = NULL;
985     }
986   close (fd);
987   return map; 
988 }
989
990 #define line_map_decrease 5
991
992 /* Precompute array of lines for a mapped file. */
993
994 static const char ** 
995 index_file (const char *map, size_t size, unsigned int *maxline) 
996 {
997   const char *p, *lstart, *end;
998   int chars_per_line = 45; /* First iteration will use 40.  */
999   unsigned int lineno;
1000   const char **linemap = NULL; 
1001   unsigned long line_map_size = 0;
1002  
1003   lineno = 0;
1004   lstart = map;
1005   end = map + size;
1006
1007   for (p = map; p < end; p++) 
1008     { 
1009       if (*p == '\n') 
1010         { 
1011           if (p + 1 < end && p[1] == '\r') 
1012             p++;  
1013         } 
1014       else if (*p == '\r') 
1015         { 
1016           if (p + 1 < end && p[1] == '\n')
1017             p++;
1018         }
1019       else
1020         continue;
1021       
1022       /* End of line found.  */
1023
1024       if (linemap == NULL || line_map_size < lineno + 1) 
1025         { 
1026           unsigned long newsize;
1027
1028           chars_per_line -= line_map_decrease;
1029           if (chars_per_line <= 1)
1030             chars_per_line = 1;
1031           line_map_size = size / chars_per_line + 1;
1032           if (line_map_size < lineno + 1)
1033             line_map_size = lineno + 1;
1034           newsize = line_map_size * sizeof (char *);
1035           linemap = xrealloc (linemap, newsize);
1036         }
1037
1038       linemap[lineno++] = lstart; 
1039       lstart = p + 1; 
1040     }
1041   
1042   *maxline = lineno; 
1043   return linemap;
1044 }
1045
1046 /* Tries to open MODNAME, and if successful adds a node to print_files
1047    linked list and returns that node.  Returns NULL on failure.  */
1048
1049 static struct print_file_list *
1050 try_print_file_open (const char *origname, const char *modname)
1051 {
1052   struct print_file_list *p;
1053
1054   p = xmalloc (sizeof (struct print_file_list));
1055
1056   p->map = slurp_file (modname, &p->mapsize);
1057   if (p->map == NULL)
1058     {
1059       free (p);
1060       return NULL;
1061     }
1062   
1063   p->linemap = index_file (p->map, p->mapsize, &p->maxline);
1064   p->last_line = 0;
1065   p->filename = origname;
1066   p->modname = modname;
1067   p->next = print_files;
1068   p->first = 1;
1069   print_files = p;
1070   return p;
1071 }
1072
1073 /* If the the source file, as described in the symtab, is not found
1074    try to locate it in one of the paths specified with -I
1075    If found, add location to print_files linked list.  */
1076
1077 static struct print_file_list *
1078 update_source_path (const char *filename)
1079 {
1080   struct print_file_list *p;
1081   const char *fname;
1082   int i;
1083
1084   if (filename == NULL)
1085     return NULL;
1086
1087   p = try_print_file_open (filename, filename);
1088   if (p != NULL)
1089     return p;
1090
1091   if (include_path_count == 0)
1092     return NULL;
1093
1094   /* Get the name of the file.  */
1095   fname = strrchr (filename, '/');
1096 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
1097   {
1098     /* We could have a mixed forward/back slash case.  */
1099     char *backslash = strrchr (filename, '\\');
1100     if (fname == NULL || (backslash != NULL && backslash > fname))
1101       fname = backslash;
1102     if (fname == NULL && filename[0] != '\0' && filename[1] == ':')
1103       fname = filename + 1;
1104   }
1105 #endif
1106   if (fname == NULL)
1107     fname = filename;
1108   else
1109     ++fname;
1110
1111   /* If file exists under a new path, we need to add it to the list
1112      so that show_line knows about it.  */
1113   for (i = 0; i < include_path_count; i++)
1114     {
1115       char *modname = concat (include_paths[i], "/", fname, (const char *) 0);
1116
1117       p = try_print_file_open (filename, modname);
1118       if (p)
1119         return p;
1120
1121       free (modname);
1122     }
1123
1124   return NULL;
1125 }
1126
1127 /* Print a source file line.  */
1128
1129 static void 
1130 print_line (struct print_file_list *p, unsigned int line)
1131 {
1132   const char *l;
1133   size_t len;
1134  
1135   --line; 
1136   if (line >= p->maxline)
1137     return;
1138   l = p->linemap [line];
1139   /* Test fwrite return value to quiet glibc warning.  */
1140   len = strcspn (l, "\n\r");
1141   if (len == 0 || fwrite (l, len, 1, stdout) == 1)
1142     putchar ('\n');
1143 }
1144
1145 /* Print a range of source code lines. */
1146
1147 static void
1148 dump_lines (struct print_file_list *p, unsigned int start, unsigned int end)
1149 {
1150   if (p->map == NULL)
1151     return;
1152   while (start <= end) 
1153     {
1154       print_line (p, start);
1155       start++;
1156     }
1157 }
1158
1159 /* Show the line number, or the source line, in a disassembly
1160    listing.  */
1161
1162 static void
1163 show_line (bfd *abfd, asection *section, bfd_vma addr_offset)
1164 {
1165   const char *filename;
1166   const char *functionname;
1167   unsigned int line;
1168
1169   if (! with_line_numbers && ! with_source_code)
1170     return;
1171
1172   if (! bfd_find_nearest_line (abfd, section, syms, addr_offset, &filename,
1173                                &functionname, &line))
1174     return;
1175
1176   if (filename != NULL && *filename == '\0')
1177     filename = NULL;
1178   if (functionname != NULL && *functionname == '\0')
1179     functionname = NULL;
1180
1181   if (with_line_numbers)
1182     {
1183       if (functionname != NULL
1184           && (prev_functionname == NULL
1185               || strcmp (functionname, prev_functionname) != 0))
1186         printf ("%s():\n", functionname);
1187       if (line > 0 && line != prev_line)
1188         printf ("%s:%u\n", filename == NULL ? "???" : filename, line);
1189     }
1190
1191   if (with_source_code
1192       && filename != NULL
1193       && line > 0)
1194     {
1195       struct print_file_list **pp, *p;
1196       unsigned l;
1197
1198       for (pp = &print_files; *pp != NULL; pp = &(*pp)->next)
1199         if (strcmp ((*pp)->filename, filename) == 0)
1200           break;
1201       p = *pp;
1202
1203       if (p == NULL)
1204           p = update_source_path (filename);
1205
1206       if (p != NULL && line != p->last_line)
1207         {
1208           if (file_start_context && p->first) 
1209             l = 1;
1210           else 
1211             {
1212               l = line - SHOW_PRECEDING_CONTEXT_LINES;
1213               if (l >= line) 
1214                 l = 1;
1215               if (p->last_line >= l && p->last_line <= line)
1216                 l = p->last_line + 1;
1217             }
1218           dump_lines (p, l, line);
1219           p->last_line = line;
1220           p->first = 0;
1221         }
1222     }
1223
1224   if (functionname != NULL
1225       && (prev_functionname == NULL
1226           || strcmp (functionname, prev_functionname) != 0))
1227     {
1228       if (prev_functionname != NULL)
1229         free (prev_functionname);
1230       prev_functionname = xmalloc (strlen (functionname) + 1);
1231       strcpy (prev_functionname, functionname);
1232     }
1233
1234   if (line > 0 && line != prev_line)
1235     prev_line = line;
1236 }
1237
1238 /* Pseudo FILE object for strings.  */
1239 typedef struct
1240 {
1241   char *buffer;
1242   size_t pos;
1243   size_t alloc;
1244 } SFILE;
1245
1246 /* sprintf to a "stream".  */
1247
1248 static int ATTRIBUTE_PRINTF_2
1249 objdump_sprintf (SFILE *f, const char *format, ...)
1250 {
1251   size_t n;
1252   va_list args;
1253
1254   while (1)
1255     {
1256       size_t space = f->alloc - f->pos;
1257   
1258       va_start (args, format);
1259       n = vsnprintf (f->buffer + f->pos, space, format, args);
1260       va_end (args);
1261
1262       if (space > n)
1263         break;
1264       
1265       f->alloc = (f->alloc + n) * 2;
1266       f->buffer = xrealloc (f->buffer, f->alloc);
1267     }
1268   f->pos += n;
1269   
1270   return n;
1271 }
1272
1273 /* Returns TRUE if the specified section should be dumped.  */
1274
1275 static bfd_boolean
1276 process_section_p (asection * section)
1277 {
1278   size_t i;
1279
1280   if (only == NULL)
1281     return TRUE;
1282
1283   for (i = 0; i < only_used; i++)
1284     if (strcmp (only [i], section->name) == 0)
1285       return TRUE;
1286
1287   return FALSE;
1288 }
1289
1290
1291 /* The number of zeroes we want to see before we start skipping them.
1292    The number is arbitrarily chosen.  */
1293
1294 #define DEFAULT_SKIP_ZEROES 8
1295
1296 /* The number of zeroes to skip at the end of a section.  If the
1297    number of zeroes at the end is between SKIP_ZEROES_AT_END and
1298    SKIP_ZEROES, they will be disassembled.  If there are fewer than
1299    SKIP_ZEROES_AT_END, they will be skipped.  This is a heuristic
1300    attempt to avoid disassembling zeroes inserted by section
1301    alignment.  */
1302
1303 #define DEFAULT_SKIP_ZEROES_AT_END 3
1304
1305 /* Disassemble some data in memory between given values.  */
1306
1307 static void
1308 disassemble_bytes (struct disassemble_info * info,
1309                    disassembler_ftype        disassemble_fn,
1310                    bfd_boolean               insns,
1311                    bfd_byte *                data,
1312                    bfd_vma                   start_offset,
1313                    bfd_vma                   stop_offset,
1314                    bfd_vma                   rel_offset,
1315                    arelent ***               relppp,
1316                    arelent **                relppend)
1317 {
1318   struct objdump_disasm_info *aux;
1319   asection *section;
1320   int octets_per_line;
1321   bfd_boolean done_dot;
1322   int skip_addr_chars;
1323   bfd_vma addr_offset;
1324   unsigned int opb = info->octets_per_byte;
1325   unsigned int skip_zeroes = info->skip_zeroes;
1326   unsigned int skip_zeroes_at_end = info->skip_zeroes_at_end;
1327   int octets = opb;
1328   SFILE sfile;
1329
1330   aux = (struct objdump_disasm_info *) info->application_data;
1331   section = aux->sec;
1332
1333   sfile.alloc = 120;
1334   sfile.buffer = xmalloc (sfile.alloc);
1335   sfile.pos = 0;
1336   
1337   if (insns)
1338     octets_per_line = 4;
1339   else
1340     octets_per_line = 16;
1341
1342   /* Figure out how many characters to skip at the start of an
1343      address, to make the disassembly look nicer.  We discard leading
1344      zeroes in chunks of 4, ensuring that there is always a leading
1345      zero remaining.  */
1346   skip_addr_chars = 0;
1347   if (! prefix_addresses)
1348     {
1349       char buf[30];
1350       char *s;
1351
1352       bfd_sprintf_vma
1353         (aux->abfd, buf,
1354          (section->vma
1355           + bfd_section_size (section->owner, section) / opb));
1356       s = buf;
1357       while (s[0] == '0' && s[1] == '0' && s[2] == '0' && s[3] == '0'
1358              && s[4] == '0')
1359         {
1360           skip_addr_chars += 4;
1361           s += 4;
1362         }
1363     }
1364
1365   info->insn_info_valid = 0;
1366
1367   done_dot = FALSE;
1368   addr_offset = start_offset;
1369   while (addr_offset < stop_offset)
1370     {
1371       bfd_vma z;
1372       bfd_boolean need_nl = FALSE;
1373       int previous_octets;
1374
1375       /* Remember the length of the previous instruction.  */
1376       previous_octets = octets;
1377       octets = 0;
1378
1379       /* If we see more than SKIP_ZEROES octets of zeroes, we just
1380          print `...'.  */
1381       for (z = addr_offset * opb; z < stop_offset * opb; z++)
1382         if (data[z] != 0)
1383           break;
1384       if (! disassemble_zeroes
1385           && (info->insn_info_valid == 0
1386               || info->branch_delay_insns == 0)
1387           && (z - addr_offset * opb >= skip_zeroes
1388               || (z == stop_offset * opb &&
1389                   z - addr_offset * opb < skip_zeroes_at_end)))
1390         {
1391           printf ("\t...\n");
1392
1393           /* If there are more nonzero octets to follow, we only skip
1394              zeroes in multiples of 4, to try to avoid running over
1395              the start of an instruction which happens to start with
1396              zero.  */
1397           if (z != stop_offset * opb)
1398             z = addr_offset * opb + ((z - addr_offset * opb) &~ 3);
1399
1400           octets = z - addr_offset * opb;
1401         }
1402       else
1403         {
1404           char buf[50];
1405           int bpc = 0;
1406           int pb = 0;
1407
1408           done_dot = FALSE;
1409
1410           if (with_line_numbers || with_source_code)
1411             show_line (aux->abfd, section, addr_offset);
1412
1413           if (! prefix_addresses)
1414             {
1415               char *s;
1416
1417               bfd_sprintf_vma (aux->abfd, buf, section->vma + addr_offset);
1418               for (s = buf + skip_addr_chars; *s == '0'; s++)
1419                 *s = ' ';
1420               if (*s == '\0')
1421                 *--s = '0';
1422               printf ("%s:\t", buf + skip_addr_chars);
1423             }
1424           else
1425             {
1426               aux->require_sec = TRUE;
1427               objdump_print_address (section->vma + addr_offset, info);
1428               aux->require_sec = FALSE;
1429               putchar (' ');
1430             }
1431
1432           if (insns)
1433             {
1434               sfile.pos = 0;
1435               info->fprintf_func = (fprintf_ftype) objdump_sprintf;
1436               info->stream = &sfile;
1437               info->bytes_per_line = 0;
1438               info->bytes_per_chunk = 0;
1439               info->flags = 0;
1440
1441               if (info->disassembler_needs_relocs
1442                   && (bfd_get_file_flags (aux->abfd) & EXEC_P) == 0
1443                   && (bfd_get_file_flags (aux->abfd) & DYNAMIC) == 0
1444                   && *relppp < relppend)
1445                 {
1446                   bfd_signed_vma distance_to_rel;
1447
1448                   distance_to_rel = (**relppp)->address
1449                     - (rel_offset + addr_offset);
1450
1451                   /* Check to see if the current reloc is associated with
1452                      the instruction that we are about to disassemble.  */
1453                   if (distance_to_rel == 0
1454                       /* FIXME: This is wrong.  We are trying to catch
1455                          relocs that are addressed part way through the
1456                          current instruction, as might happen with a packed
1457                          VLIW instruction.  Unfortunately we do not know the
1458                          length of the current instruction since we have not
1459                          disassembled it yet.  Instead we take a guess based
1460                          upon the length of the previous instruction.  The
1461                          proper solution is to have a new target-specific
1462                          disassembler function which just returns the length
1463                          of an instruction at a given address without trying
1464                          to display its disassembly. */
1465                       || (distance_to_rel > 0
1466                           && distance_to_rel < (bfd_signed_vma) (previous_octets/ opb)))
1467                     {
1468                       info->flags = INSN_HAS_RELOC;
1469                       aux->reloc = **relppp;
1470                     }
1471                   else
1472                     aux->reloc = NULL;
1473                 }
1474
1475               octets = (*disassemble_fn) (section->vma + addr_offset, info);
1476               info->fprintf_func = (fprintf_ftype) fprintf;
1477               info->stream = stdout;
1478               if (info->bytes_per_line != 0)
1479                 octets_per_line = info->bytes_per_line;
1480               if (octets < 0)
1481                 {
1482                   if (sfile.pos)
1483                     printf ("%s\n", sfile.buffer);
1484                   break;
1485                 }
1486             }
1487           else
1488             {
1489               bfd_vma j;
1490
1491               octets = octets_per_line;
1492               if (addr_offset + octets / opb > stop_offset)
1493                 octets = (stop_offset - addr_offset) * opb;
1494
1495               for (j = addr_offset * opb; j < addr_offset * opb + octets; ++j)
1496                 {
1497                   if (ISPRINT (data[j]))
1498                     buf[j - addr_offset * opb] = data[j];
1499                   else
1500                     buf[j - addr_offset * opb] = '.';
1501                 }
1502               buf[j - addr_offset * opb] = '\0';
1503             }
1504
1505           if (prefix_addresses
1506               ? show_raw_insn > 0
1507               : show_raw_insn >= 0)
1508             {
1509               bfd_vma j;
1510
1511               /* If ! prefix_addresses and ! wide_output, we print
1512                  octets_per_line octets per line.  */
1513               pb = octets;
1514               if (pb > octets_per_line && ! prefix_addresses && ! wide_output)
1515                 pb = octets_per_line;
1516
1517               if (info->bytes_per_chunk)
1518                 bpc = info->bytes_per_chunk;
1519               else
1520                 bpc = 1;
1521
1522               for (j = addr_offset * opb; j < addr_offset * opb + pb; j += bpc)
1523                 {
1524                   int k;
1525
1526                   if (bpc > 1 && info->display_endian == BFD_ENDIAN_LITTLE)
1527                     {
1528                       for (k = bpc - 1; k >= 0; k--)
1529                         printf ("%02x", (unsigned) data[j + k]);
1530                       putchar (' ');
1531                     }
1532                   else
1533                     {
1534                       for (k = 0; k < bpc; k++)
1535                         printf ("%02x", (unsigned) data[j + k]);
1536                       putchar (' ');
1537                     }
1538                 }
1539
1540               for (; pb < octets_per_line; pb += bpc)
1541                 {
1542                   int k;
1543
1544                   for (k = 0; k < bpc; k++)
1545                     printf ("  ");
1546                   putchar (' ');
1547                 }
1548
1549               /* Separate raw data from instruction by extra space.  */
1550               if (insns)
1551                 putchar ('\t');
1552               else
1553                 printf ("    ");
1554             }
1555
1556           if (! insns)
1557             printf ("%s", buf);
1558           else if (sfile.pos)
1559             printf ("%s", sfile.buffer);
1560
1561           if (prefix_addresses
1562               ? show_raw_insn > 0
1563               : show_raw_insn >= 0)
1564             {
1565               while (pb < octets)
1566                 {
1567                   bfd_vma j;
1568                   char *s;
1569
1570                   putchar ('\n');
1571                   j = addr_offset * opb + pb;
1572
1573                   bfd_sprintf_vma (aux->abfd, buf, section->vma + j / opb);
1574                   for (s = buf + skip_addr_chars; *s == '0'; s++)
1575                     *s = ' ';
1576                   if (*s == '\0')
1577                     *--s = '0';
1578                   printf ("%s:\t", buf + skip_addr_chars);
1579
1580                   pb += octets_per_line;
1581                   if (pb > octets)
1582                     pb = octets;
1583                   for (; j < addr_offset * opb + pb; j += bpc)
1584                     {
1585                       int k;
1586
1587                       if (bpc > 1 && info->display_endian == BFD_ENDIAN_LITTLE)
1588                         {
1589                           for (k = bpc - 1; k >= 0; k--)
1590                             printf ("%02x", (unsigned) data[j + k]);
1591                           putchar (' ');
1592                         }
1593                       else
1594                         {
1595                           for (k = 0; k < bpc; k++)
1596                             printf ("%02x", (unsigned) data[j + k]);
1597                           putchar (' ');
1598                         }
1599                     }
1600                 }
1601             }
1602
1603           if (!wide_output)
1604             putchar ('\n');
1605           else
1606             need_nl = TRUE;
1607         }
1608
1609       while ((*relppp) < relppend
1610              && (**relppp)->address < rel_offset + addr_offset + octets / opb)
1611         {
1612           if (dump_reloc_info || dump_dynamic_reloc_info)
1613             {
1614               arelent *q;
1615
1616               q = **relppp;
1617
1618               if (wide_output)
1619                 putchar ('\t');
1620               else
1621                 printf ("\t\t\t");
1622
1623               objdump_print_value (section->vma - rel_offset + q->address,
1624                                    info, TRUE);
1625
1626               if (q->howto == NULL)
1627                 printf (": *unknown*\t");
1628               else if (q->howto->name)
1629                 printf (": %s\t", q->howto->name);
1630               else
1631                 printf (": %d\t", q->howto->type);
1632
1633               if (q->sym_ptr_ptr == NULL || *q->sym_ptr_ptr == NULL)
1634                 printf ("*unknown*");
1635               else
1636                 {
1637                   const char *sym_name;
1638
1639                   sym_name = bfd_asymbol_name (*q->sym_ptr_ptr);
1640                   if (sym_name != NULL && *sym_name != '\0')
1641                     objdump_print_symname (aux->abfd, info, *q->sym_ptr_ptr);
1642                   else
1643                     {
1644                       asection *sym_sec;
1645
1646                       sym_sec = bfd_get_section (*q->sym_ptr_ptr);
1647                       sym_name = bfd_get_section_name (aux->abfd, sym_sec);
1648                       if (sym_name == NULL || *sym_name == '\0')
1649                         sym_name = "*unknown*";
1650                       printf ("%s", sym_name);
1651                     }
1652                 }
1653
1654               if (q->addend)
1655                 {
1656                   printf ("+0x");
1657                   objdump_print_value (q->addend, info, TRUE);
1658                 }
1659
1660               printf ("\n");
1661               need_nl = FALSE;
1662             }
1663           ++(*relppp);
1664         }
1665
1666       if (need_nl)
1667         printf ("\n");
1668
1669       addr_offset += octets / opb;
1670     }
1671
1672   free (sfile.buffer);
1673 }
1674
1675 static void
1676 disassemble_section (bfd *abfd, asection *section, void *info)
1677 {
1678   struct disassemble_info *    pinfo = (struct disassemble_info *) info;
1679   struct objdump_disasm_info * paux;
1680   unsigned int                 opb = pinfo->octets_per_byte;
1681   bfd_byte *                   data = NULL;
1682   bfd_size_type                datasize = 0;
1683   arelent **                   rel_pp = NULL;
1684   arelent **                   rel_ppstart = NULL;
1685   arelent **                   rel_ppend;
1686   unsigned long                stop_offset;
1687   asymbol *                    sym = NULL;
1688   long                         place = 0;
1689   long                         rel_count;
1690   bfd_vma                      rel_offset;
1691   unsigned long                addr_offset;
1692
1693   /* Sections that do not contain machine
1694      code are not normally disassembled.  */
1695   if (! disassemble_all
1696       && only == NULL
1697       && ((section->flags & (SEC_CODE | SEC_HAS_CONTENTS))
1698           != (SEC_CODE | SEC_HAS_CONTENTS)))
1699     return;
1700
1701   if (! process_section_p (section))
1702     return;
1703
1704   datasize = bfd_get_section_size (section);
1705   if (datasize == 0)
1706     return;
1707
1708   /* Decide which set of relocs to use.  Load them if necessary.  */
1709   paux = (struct objdump_disasm_info *) pinfo->application_data;
1710   if (paux->dynrelbuf)
1711     {
1712       rel_pp = paux->dynrelbuf;
1713       rel_count = paux->dynrelcount;
1714       /* Dynamic reloc addresses are absolute, non-dynamic are section
1715          relative.  REL_OFFSET specifies the reloc address corresponding
1716          to the start of this section.  */
1717       rel_offset = section->vma;
1718     }
1719   else
1720     {
1721       rel_count = 0;
1722       rel_pp = NULL;
1723       rel_offset = 0;
1724
1725       if ((section->flags & SEC_RELOC) != 0
1726           && (dump_reloc_info || pinfo->disassembler_needs_relocs))
1727         {
1728           long relsize;
1729
1730           relsize = bfd_get_reloc_upper_bound (abfd, section);
1731           if (relsize < 0)
1732             bfd_fatal (bfd_get_filename (abfd));
1733
1734           if (relsize > 0)
1735             {
1736               rel_ppstart = rel_pp = xmalloc (relsize);
1737               rel_count = bfd_canonicalize_reloc (abfd, section, rel_pp, syms);
1738               if (rel_count < 0)
1739                 bfd_fatal (bfd_get_filename (abfd));
1740
1741               /* Sort the relocs by address.  */
1742               qsort (rel_pp, rel_count, sizeof (arelent *), compare_relocs);
1743             }
1744         }
1745
1746     }
1747   rel_ppend = rel_pp + rel_count;
1748
1749   data = xmalloc (datasize);
1750
1751   bfd_get_section_contents (abfd, section, data, 0, datasize);
1752
1753   paux->sec = section;
1754   pinfo->buffer = data;
1755   pinfo->buffer_vma = section->vma;
1756   pinfo->buffer_length = datasize;
1757   pinfo->section = section;
1758
1759   if (start_address == (bfd_vma) -1
1760       || start_address < pinfo->buffer_vma)
1761     addr_offset = 0;
1762   else
1763     addr_offset = start_address - pinfo->buffer_vma;
1764
1765   if (stop_address == (bfd_vma) -1)
1766     stop_offset = datasize / opb;
1767   else
1768     {
1769       if (stop_address < pinfo->buffer_vma)
1770         stop_offset = 0;
1771       else
1772         stop_offset = stop_address - pinfo->buffer_vma;
1773       if (stop_offset > pinfo->buffer_length / opb)
1774         stop_offset = pinfo->buffer_length / opb;
1775     }
1776
1777   /* Skip over the relocs belonging to addresses below the
1778      start address.  */
1779   while (rel_pp < rel_ppend
1780          && (*rel_pp)->address < rel_offset + addr_offset)
1781     ++rel_pp;
1782
1783   printf (_("Disassembly of section %s:\n"), section->name);
1784
1785   /* Find the nearest symbol forwards from our current position.  */
1786   paux->require_sec = TRUE;
1787   sym = find_symbol_for_address (section->vma + addr_offset, info, &place);
1788   paux->require_sec = FALSE;
1789
1790   /* Disassemble a block of instructions up to the address associated with
1791      the symbol we have just found.  Then print the symbol and find the
1792      next symbol on.  Repeat until we have disassembled the entire section
1793      or we have reached the end of the address range we are interested in.  */
1794   while (addr_offset < stop_offset)
1795     {
1796       bfd_vma addr;
1797       asymbol *nextsym;
1798       unsigned long nextstop_offset;
1799       bfd_boolean insns;
1800
1801       addr = section->vma + addr_offset;
1802
1803       if (sym != NULL && bfd_asymbol_value (sym) <= addr)
1804         {
1805           int x;
1806
1807           for (x = place;
1808                (x < sorted_symcount
1809                 && (bfd_asymbol_value (sorted_syms[x]) <= addr));
1810                ++x)
1811             continue;
1812
1813           pinfo->symbols = sorted_syms + place;
1814           pinfo->num_symbols = x - place;
1815           pinfo->symtab_pos = place;
1816         }
1817       else
1818         {
1819           pinfo->symbols = NULL;
1820           pinfo->num_symbols = 0;
1821           pinfo->symtab_pos = -1;
1822         }
1823
1824       if (! prefix_addresses)
1825         {
1826           pinfo->fprintf_func (pinfo->stream, "\n");
1827           objdump_print_addr_with_sym (abfd, section, sym, addr,
1828                                        pinfo, FALSE);
1829           pinfo->fprintf_func (pinfo->stream, ":\n");
1830         }
1831
1832       if (sym != NULL && bfd_asymbol_value (sym) > addr)
1833         nextsym = sym;
1834       else if (sym == NULL)
1835         nextsym = NULL;
1836       else
1837         {
1838 #define is_valid_next_sym(SYM) \
1839   ((SYM)->section == section \
1840    && (bfd_asymbol_value (SYM) > bfd_asymbol_value (sym)) \
1841    && pinfo->symbol_is_valid (SYM, pinfo))
1842             
1843           /* Search forward for the next appropriate symbol in
1844              SECTION.  Note that all the symbols are sorted
1845              together into one big array, and that some sections
1846              may have overlapping addresses.  */
1847           while (place < sorted_symcount
1848                  && ! is_valid_next_sym (sorted_syms [place]))
1849             ++place;
1850
1851           if (place >= sorted_symcount)
1852             nextsym = NULL;
1853           else
1854             nextsym = sorted_syms[place];
1855         }
1856
1857       if (sym != NULL && bfd_asymbol_value (sym) > addr)
1858         nextstop_offset = bfd_asymbol_value (sym) - section->vma;
1859       else if (nextsym == NULL)
1860         nextstop_offset = stop_offset;
1861       else
1862         nextstop_offset = bfd_asymbol_value (nextsym) - section->vma;
1863
1864       if (nextstop_offset > stop_offset)
1865         nextstop_offset = stop_offset;
1866
1867       /* If a symbol is explicitly marked as being an object
1868          rather than a function, just dump the bytes without
1869          disassembling them.  */
1870       if (disassemble_all
1871           || sym == NULL
1872           || bfd_asymbol_value (sym) > addr
1873           || ((sym->flags & BSF_OBJECT) == 0
1874               && (strstr (bfd_asymbol_name (sym), "gnu_compiled")
1875                   == NULL)
1876               && (strstr (bfd_asymbol_name (sym), "gcc2_compiled")
1877                   == NULL))
1878           || (sym->flags & BSF_FUNCTION) != 0)
1879         insns = TRUE;
1880       else
1881         insns = FALSE;
1882
1883       disassemble_bytes (pinfo, paux->disassemble_fn, insns, data,
1884                          addr_offset, nextstop_offset,
1885                          rel_offset, &rel_pp, rel_ppend);
1886
1887       addr_offset = nextstop_offset;
1888       sym = nextsym;
1889     }
1890
1891   free (data);
1892
1893   if (rel_ppstart != NULL)
1894     free (rel_ppstart);
1895 }
1896
1897 /* Disassemble the contents of an object file.  */
1898
1899 static void
1900 disassemble_data (bfd *abfd)
1901 {
1902   struct disassemble_info disasm_info;
1903   struct objdump_disasm_info aux;
1904   long i;
1905
1906   print_files = NULL;
1907   prev_functionname = NULL;
1908   prev_line = -1;
1909
1910   /* We make a copy of syms to sort.  We don't want to sort syms
1911      because that will screw up the relocs.  */
1912   sorted_symcount = symcount ? symcount : dynsymcount;
1913   sorted_syms = xmalloc ((sorted_symcount + synthcount) * sizeof (asymbol *));
1914   memcpy (sorted_syms, symcount ? syms : dynsyms,
1915           sorted_symcount * sizeof (asymbol *));
1916
1917   sorted_symcount = remove_useless_symbols (sorted_syms, sorted_symcount);
1918
1919   for (i = 0; i < synthcount; ++i)
1920     {
1921       sorted_syms[sorted_symcount] = synthsyms + i;
1922       ++sorted_symcount;
1923     }
1924
1925   /* Sort the symbols into section and symbol order.  */
1926   qsort (sorted_syms, sorted_symcount, sizeof (asymbol *), compare_symbols);
1927
1928   init_disassemble_info (&disasm_info, stdout, (fprintf_ftype) fprintf);
1929
1930   disasm_info.application_data = (void *) &aux;
1931   aux.abfd = abfd;
1932   aux.require_sec = FALSE;
1933   aux.dynrelbuf = NULL;
1934   aux.dynrelcount = 0;
1935   aux.reloc = NULL;
1936
1937   disasm_info.print_address_func = objdump_print_address;
1938   disasm_info.symbol_at_address_func = objdump_symbol_at_address;
1939
1940   if (machine != NULL)
1941     {
1942       const bfd_arch_info_type *info = bfd_scan_arch (machine);
1943
1944       if (info == NULL)
1945         fatal (_("Can't use supplied machine %s"), machine);
1946
1947       abfd->arch_info = info;
1948     }
1949
1950   if (endian != BFD_ENDIAN_UNKNOWN)
1951     {
1952       struct bfd_target *xvec;
1953
1954       xvec = xmalloc (sizeof (struct bfd_target));
1955       memcpy (xvec, abfd->xvec, sizeof (struct bfd_target));
1956       xvec->byteorder = endian;
1957       abfd->xvec = xvec;
1958     }
1959
1960   /* Use libopcodes to locate a suitable disassembler.  */
1961   aux.disassemble_fn = disassembler (abfd);
1962   if (!aux.disassemble_fn)
1963     {
1964       non_fatal (_("Can't disassemble for architecture %s\n"),
1965                  bfd_printable_arch_mach (bfd_get_arch (abfd), 0));
1966       exit_status = 1;
1967       return;
1968     }
1969
1970   disasm_info.flavour = bfd_get_flavour (abfd);
1971   disasm_info.arch = bfd_get_arch (abfd);
1972   disasm_info.mach = bfd_get_mach (abfd);
1973   disasm_info.disassembler_options = disassembler_options;
1974   disasm_info.octets_per_byte = bfd_octets_per_byte (abfd);
1975   disasm_info.skip_zeroes = DEFAULT_SKIP_ZEROES;
1976   disasm_info.skip_zeroes_at_end = DEFAULT_SKIP_ZEROES_AT_END;
1977   disasm_info.disassembler_needs_relocs = FALSE;
1978
1979   if (bfd_big_endian (abfd))
1980     disasm_info.display_endian = disasm_info.endian = BFD_ENDIAN_BIG;
1981   else if (bfd_little_endian (abfd))
1982     disasm_info.display_endian = disasm_info.endian = BFD_ENDIAN_LITTLE;
1983   else
1984     /* ??? Aborting here seems too drastic.  We could default to big or little
1985        instead.  */
1986     disasm_info.endian = BFD_ENDIAN_UNKNOWN;
1987
1988   /* Allow the target to customize the info structure.  */
1989   disassemble_init_for_target (& disasm_info);
1990
1991   /* Pre-load the dynamic relocs if we are going
1992      to be dumping them along with the disassembly.  */
1993   if (dump_dynamic_reloc_info)
1994     {
1995       long relsize = bfd_get_dynamic_reloc_upper_bound (abfd);
1996   
1997       if (relsize < 0)
1998         bfd_fatal (bfd_get_filename (abfd));
1999
2000       if (relsize > 0)
2001         {
2002           aux.dynrelbuf = xmalloc (relsize);
2003           aux.dynrelcount = bfd_canonicalize_dynamic_reloc (abfd,
2004                                                             aux.dynrelbuf,
2005                                                             dynsyms);
2006           if (aux.dynrelcount < 0)
2007             bfd_fatal (bfd_get_filename (abfd));
2008
2009           /* Sort the relocs by address.  */
2010           qsort (aux.dynrelbuf, aux.dynrelcount, sizeof (arelent *),
2011                  compare_relocs);
2012         }
2013     }
2014   disasm_info.symtab = sorted_syms;
2015   disasm_info.symtab_size = sorted_symcount;
2016
2017   bfd_map_over_sections (abfd, disassemble_section, & disasm_info);
2018
2019   if (aux.dynrelbuf != NULL)
2020     free (aux.dynrelbuf);
2021   free (sorted_syms);
2022 }
2023 \f
2024 int
2025 load_debug_section (enum dwarf_section_display_enum debug, void *file)
2026 {
2027   struct dwarf_section *section = &debug_displays [debug].section;
2028   bfd *abfd = file;
2029   asection *sec;
2030   bfd_boolean ret;
2031
2032   /* If it is already loaded, do nothing.  */
2033   if (section->start != NULL)
2034     return 1;
2035
2036   /* Locate the debug section.  */
2037   sec = bfd_get_section_by_name (abfd, section->name);
2038   if (sec == NULL)
2039     return 0;
2040
2041   /* Compute a bias to be added to offsets found within the DWARF debug
2042      information.  These offsets are meant to be relative to the start of
2043      the dwarf section, and hence the bias should be 0.  For MACH-O however
2044      a dwarf section is really just a region of a much larger section and so
2045      the bias is the address of the start of that area within the larger
2046      section.  This test is important for PE and COFF based targets which
2047      use DWARF debug information, since unlike ELF, they do not allow the
2048      dwarf sections to be placed at address 0.  */
2049   if (bfd_get_flavour (abfd) == bfd_target_mach_o_flavour)
2050     section->address = bfd_get_section_vma (abfd, sec);
2051   else
2052     section->address = 0;
2053     
2054   section->size = bfd_get_section_size (sec);
2055   section->start = xmalloc (section->size);
2056
2057   if (is_relocatable && debug_displays [debug].relocate)
2058     ret = bfd_simple_get_relocated_section_contents (abfd,
2059                                                      sec,
2060                                                      section->start,
2061                                                      syms) != NULL;
2062   else
2063     ret = bfd_get_section_contents (abfd, sec, section->start, 0,
2064                                     section->size);
2065
2066   if (!ret)
2067     {
2068       free_debug_section (debug);
2069       printf (_("\nCan't get contents for section '%s'.\n"),
2070               section->name);
2071     }
2072
2073   return ret;
2074 }
2075
2076 void
2077 free_debug_section (enum dwarf_section_display_enum debug)
2078 {
2079   struct dwarf_section *section = &debug_displays [debug].section;
2080
2081   if (section->start == NULL)
2082     return;
2083
2084   free ((char *) section->start);
2085   section->start = NULL;
2086   section->address = 0;
2087   section->size = 0;
2088 }
2089
2090 static void
2091 dump_dwarf_section (bfd *abfd, asection *section,
2092                     void *arg ATTRIBUTE_UNUSED)
2093 {
2094   const char *name = bfd_get_section_name (abfd, section);
2095   const char *match;
2096   enum dwarf_section_display_enum i;
2097
2098   if (CONST_STRNEQ (name, ".gnu.linkonce.wi."))
2099     match = ".debug_info";
2100   else
2101     match = name;
2102
2103   for (i = 0; i < max; i++)
2104     if (strcmp (debug_displays[i].section.name, match) == 0)
2105       {
2106         if (!debug_displays[i].eh_frame)
2107           {
2108             struct dwarf_section *sec = &debug_displays [i].section;
2109
2110             if (load_debug_section (i, abfd))
2111               {
2112                 debug_displays[i].display (sec, abfd);
2113
2114                 if (i != info && i != abbrev)
2115                   free_debug_section (i);
2116               }
2117           }
2118         break;
2119       }
2120 }
2121
2122 static const char *mach_o_dwarf_sections [] = {
2123   "LC_SEGMENT.__DWARFA.__debug_abbrev",         /* .debug_abbrev */
2124   "LC_SEGMENT.__DWARFA.__debug_aranges",        /* .debug_aranges */
2125   "LC_SEGMENT.__DWARFA.__debug_frame",          /* .debug_frame */
2126   "LC_SEGMENT.__DWARFA.__debug_info",           /* .debug_info */
2127   "LC_SEGMENT.__DWARFA.__debug_line",           /* .debug_line */
2128   "LC_SEGMENT.__DWARFA.__debug_pubnames",       /* .debug_pubnames */
2129   ".eh_frame",                                  /* .eh_frame */
2130   "LC_SEGMENT.__DWARFA.__debug_macinfo",        /* .debug_macinfo */
2131   "LC_SEGMENT.__DWARFA.__debug_str",            /* .debug_str */
2132   "LC_SEGMENT.__DWARFA.__debug_loc",            /* .debug_loc */
2133   "LC_SEGMENT.__DWARFA.__debug_pubtypes",       /* .debug_pubtypes */
2134   "LC_SEGMENT.__DWARFA.__debug_ranges",         /* .debug_ranges */
2135   "LC_SEGMENT.__DWARFA.__debug_static_func",    /* .debug_static_func */
2136   "LC_SEGMENT.__DWARFA.__debug_static_vars",    /* .debug_static_vars */
2137   "LC_SEGMENT.__DWARFA.__debug_types",          /* .debug_types */
2138   "LC_SEGMENT.__DWARFA.__debug_weaknames"       /* .debug_weaknames */
2139 };
2140
2141 static const char *generic_dwarf_sections [max];
2142
2143 static void
2144 check_mach_o_dwarf (bfd *abfd)
2145 {
2146   static enum bfd_flavour old_flavour = bfd_target_unknown_flavour;
2147   enum bfd_flavour current_flavour = bfd_get_flavour (abfd);
2148   enum dwarf_section_display_enum i;
2149
2150   if (generic_dwarf_sections [0] == NULL)
2151     for (i = 0; i < max; i++)
2152       generic_dwarf_sections [i] = debug_displays[i].section.name;
2153
2154   if (old_flavour != current_flavour)
2155     {
2156       if (current_flavour == bfd_target_mach_o_flavour)
2157         for (i = 0; i < max; i++)
2158           debug_displays[i].section.name = mach_o_dwarf_sections [i];
2159       else if (old_flavour == bfd_target_mach_o_flavour)
2160         for (i = 0; i < max; i++)
2161           debug_displays[i].section.name = generic_dwarf_sections [i];
2162
2163       old_flavour = current_flavour;
2164     }
2165 }
2166
2167 /* Dump the dwarf debugging information.  */
2168
2169 static void
2170 dump_dwarf (bfd *abfd)
2171 {
2172   is_relocatable = (abfd->flags & (EXEC_P | DYNAMIC)) == 0;
2173
2174   /* FIXME: bfd_get_arch_size may return -1.  We assume that 64bit
2175      targets will return 64.  */
2176   eh_addr_size = bfd_get_arch_size (abfd) == 64 ? 8 : 4;
2177
2178   if (bfd_big_endian (abfd))
2179     byte_get = byte_get_big_endian;
2180   else if (bfd_little_endian (abfd))
2181     byte_get = byte_get_little_endian;
2182   else
2183     abort ();
2184
2185   check_mach_o_dwarf (abfd);
2186
2187   bfd_map_over_sections (abfd, dump_dwarf_section, NULL);
2188
2189   free_debug_memory ();
2190 }
2191 \f
2192 /* Read ABFD's stabs section STABSECT_NAME, and return a pointer to
2193    it.  Return NULL on failure.   */
2194
2195 static char *
2196 read_section_stabs (bfd *abfd, const char *sect_name, bfd_size_type *size_ptr)
2197 {
2198   asection *stabsect;
2199   bfd_size_type size;
2200   char *contents;
2201
2202   stabsect = bfd_get_section_by_name (abfd, sect_name);
2203   if (stabsect == NULL)
2204     {
2205       printf (_("No %s section present\n\n"), sect_name);
2206       return FALSE;
2207     }
2208
2209   size = bfd_section_size (abfd, stabsect);
2210   contents  = xmalloc (size);
2211
2212   if (! bfd_get_section_contents (abfd, stabsect, contents, 0, size))
2213     {
2214       non_fatal (_("Reading %s section of %s failed: %s"),
2215                  sect_name, bfd_get_filename (abfd),
2216                  bfd_errmsg (bfd_get_error ()));
2217       free (contents);
2218       exit_status = 1;
2219       return NULL;
2220     }
2221
2222   *size_ptr = size;
2223
2224   return contents;
2225 }
2226
2227 /* Stabs entries use a 12 byte format:
2228      4 byte string table index
2229      1 byte stab type
2230      1 byte stab other field
2231      2 byte stab desc field
2232      4 byte stab value
2233    FIXME: This will have to change for a 64 bit object format.  */
2234
2235 #define STRDXOFF  (0)
2236 #define TYPEOFF   (4)
2237 #define OTHEROFF  (5)
2238 #define DESCOFF   (6)
2239 #define VALOFF    (8)
2240 #define STABSIZE (12)
2241
2242 /* Print ABFD's stabs section STABSECT_NAME (in `stabs'),
2243    using string table section STRSECT_NAME (in `strtab').  */
2244
2245 static void
2246 print_section_stabs (bfd *abfd,
2247                      const char *stabsect_name,
2248                      unsigned *string_offset_ptr)
2249 {
2250   int i;
2251   unsigned file_string_table_offset = 0;
2252   unsigned next_file_string_table_offset = *string_offset_ptr;
2253   bfd_byte *stabp, *stabs_end;
2254
2255   stabp = stabs;
2256   stabs_end = stabp + stab_size;
2257
2258   printf (_("Contents of %s section:\n\n"), stabsect_name);
2259   printf ("Symnum n_type n_othr n_desc n_value  n_strx String\n");
2260
2261   /* Loop through all symbols and print them.
2262
2263      We start the index at -1 because there is a dummy symbol on
2264      the front of stabs-in-{coff,elf} sections that supplies sizes.  */
2265   for (i = -1; stabp < stabs_end; stabp += STABSIZE, i++)
2266     {
2267       const char *name;
2268       unsigned long strx;
2269       unsigned char type, other;
2270       unsigned short desc;
2271       bfd_vma value;
2272
2273       strx = bfd_h_get_32 (abfd, stabp + STRDXOFF);
2274       type = bfd_h_get_8 (abfd, stabp + TYPEOFF);
2275       other = bfd_h_get_8 (abfd, stabp + OTHEROFF);
2276       desc = bfd_h_get_16 (abfd, stabp + DESCOFF);
2277       value = bfd_h_get_32 (abfd, stabp + VALOFF);
2278
2279       printf ("\n%-6d ", i);
2280       /* Either print the stab name, or, if unnamed, print its number
2281          again (makes consistent formatting for tools like awk).  */
2282       name = bfd_get_stab_name (type);
2283       if (name != NULL)
2284         printf ("%-6s", name);
2285       else if (type == N_UNDF)
2286         printf ("HdrSym");
2287       else
2288         printf ("%-6d", type);
2289       printf (" %-6d %-6d ", other, desc);
2290       bfd_printf_vma (abfd, value);
2291       printf (" %-6lu", strx);
2292
2293       /* Symbols with type == 0 (N_UNDF) specify the length of the
2294          string table associated with this file.  We use that info
2295          to know how to relocate the *next* file's string table indices.  */
2296       if (type == N_UNDF)
2297         {
2298           file_string_table_offset = next_file_string_table_offset;
2299           next_file_string_table_offset += value;
2300         }
2301       else
2302         {
2303           /* Using the (possibly updated) string table offset, print the
2304              string (if any) associated with this symbol.  */
2305           if ((strx + file_string_table_offset) < stabstr_size)
2306             printf (" %s", &strtab[strx + file_string_table_offset]);
2307           else
2308             printf (" *");
2309         }
2310     }
2311   printf ("\n\n");
2312   *string_offset_ptr = next_file_string_table_offset;
2313 }
2314
2315 typedef struct
2316 {
2317   const char * section_name;
2318   const char * string_section_name;
2319   unsigned string_offset;
2320 }
2321 stab_section_names;
2322
2323 static void
2324 find_stabs_section (bfd *abfd, asection *section, void *names)
2325 {
2326   int len;
2327   stab_section_names * sought = (stab_section_names *) names;
2328
2329   /* Check for section names for which stabsect_name is a prefix, to
2330      handle .stab.N, etc.  */
2331   len = strlen (sought->section_name);
2332
2333   /* If the prefix matches, and the files section name ends with a
2334      nul or a digit, then we match.  I.e., we want either an exact
2335      match or a section followed by a number.  */
2336   if (strncmp (sought->section_name, section->name, len) == 0
2337       && (section->name[len] == 0
2338           || (section->name[len] == '.' && ISDIGIT (section->name[len + 1]))))
2339     {
2340       if (strtab == NULL)
2341         strtab = read_section_stabs (abfd, sought->string_section_name,
2342                                      &stabstr_size);
2343       
2344       if (strtab)
2345         {
2346           stabs = (bfd_byte *) read_section_stabs (abfd, section->name,
2347                                                    &stab_size);
2348           if (stabs)
2349             print_section_stabs (abfd, section->name, &sought->string_offset);
2350         }
2351     }
2352 }
2353
2354 static void
2355 dump_stabs_section (bfd *abfd, char *stabsect_name, char *strsect_name)
2356 {
2357   stab_section_names s;
2358
2359   s.section_name = stabsect_name;
2360   s.string_section_name = strsect_name;
2361   s.string_offset = 0;
2362
2363   bfd_map_over_sections (abfd, find_stabs_section, & s);
2364
2365   free (strtab);
2366   strtab = NULL;
2367 }
2368
2369 /* Dump the any sections containing stabs debugging information.  */
2370
2371 static void
2372 dump_stabs (bfd *abfd)
2373 {
2374   dump_stabs_section (abfd, ".stab", ".stabstr");
2375   dump_stabs_section (abfd, ".stab.excl", ".stab.exclstr");
2376   dump_stabs_section (abfd, ".stab.index", ".stab.indexstr");
2377   dump_stabs_section (abfd, "$GDB_SYMBOLS$", "$GDB_STRINGS$");
2378 }
2379 \f
2380 static void
2381 dump_bfd_header (bfd *abfd)
2382 {
2383   char *comma = "";
2384
2385   printf (_("architecture: %s, "),
2386           bfd_printable_arch_mach (bfd_get_arch (abfd),
2387                                    bfd_get_mach (abfd)));
2388   printf (_("flags 0x%08x:\n"), abfd->flags);
2389
2390 #define PF(x, y)    if (abfd->flags & x) {printf("%s%s", comma, y); comma=", ";}
2391   PF (HAS_RELOC, "HAS_RELOC");
2392   PF (EXEC_P, "EXEC_P");
2393   PF (HAS_LINENO, "HAS_LINENO");
2394   PF (HAS_DEBUG, "HAS_DEBUG");
2395   PF (HAS_SYMS, "HAS_SYMS");
2396   PF (HAS_LOCALS, "HAS_LOCALS");
2397   PF (DYNAMIC, "DYNAMIC");
2398   PF (WP_TEXT, "WP_TEXT");
2399   PF (D_PAGED, "D_PAGED");
2400   PF (BFD_IS_RELAXABLE, "BFD_IS_RELAXABLE");
2401   PF (HAS_LOAD_PAGE, "HAS_LOAD_PAGE");
2402   printf (_("\nstart address 0x"));
2403   bfd_printf_vma (abfd, abfd->start_address);
2404   printf ("\n");
2405 }
2406
2407 \f
2408 static void
2409 dump_bfd_private_header (bfd *abfd)
2410 {
2411   bfd_print_private_bfd_data (abfd, stdout);
2412 }
2413
2414 \f
2415 /* Display a section in hexadecimal format with associated characters.
2416    Each line prefixed by the zero padded address.  */
2417
2418 static void
2419 dump_section (bfd *abfd, asection *section, void *dummy ATTRIBUTE_UNUSED)
2420 {
2421   bfd_byte *data = 0;
2422   bfd_size_type datasize;
2423   bfd_size_type addr_offset;
2424   bfd_size_type start_offset;
2425   bfd_size_type stop_offset;
2426   unsigned int opb = bfd_octets_per_byte (abfd);
2427   /* Bytes per line.  */
2428   const int onaline = 16;
2429   char buf[64];
2430   int count;
2431   int width;
2432
2433   if ((section->flags & SEC_HAS_CONTENTS) == 0)
2434     return;
2435
2436   if (! process_section_p (section))
2437     return;
2438   
2439   if ((datasize = bfd_section_size (abfd, section)) == 0)
2440     return;
2441
2442   printf (_("Contents of section %s:\n"), section->name);
2443
2444   data = xmalloc (datasize);
2445
2446   bfd_get_section_contents (abfd, section, data, 0, datasize);
2447
2448   /* Compute the address range to display.  */
2449   if (start_address == (bfd_vma) -1
2450       || start_address < section->vma)
2451     start_offset = 0;
2452   else
2453     start_offset = start_address - section->vma;
2454
2455   if (stop_address == (bfd_vma) -1)
2456     stop_offset = datasize / opb;
2457   else
2458     {
2459       if (stop_address < section->vma)
2460         stop_offset = 0;
2461       else
2462         stop_offset = stop_address - section->vma;
2463
2464       if (stop_offset > datasize / opb)
2465         stop_offset = datasize / opb;
2466     }
2467
2468   width = 4;
2469
2470   bfd_sprintf_vma (abfd, buf, start_offset + section->vma);
2471   if (strlen (buf) >= sizeof (buf))
2472     abort ();
2473
2474   count = 0;
2475   while (buf[count] == '0' && buf[count+1] != '\0')
2476     count++;
2477   count = strlen (buf) - count;
2478   if (count > width)
2479     width = count;
2480
2481   bfd_sprintf_vma (abfd, buf, stop_offset + section->vma - 1);
2482   if (strlen (buf) >= sizeof (buf))
2483     abort ();
2484
2485   count = 0;
2486   while (buf[count] == '0' && buf[count+1] != '\0')
2487     count++;
2488   count = strlen (buf) - count;
2489   if (count > width)
2490     width = count;
2491
2492   for (addr_offset = start_offset;
2493        addr_offset < stop_offset; addr_offset += onaline / opb)
2494     {
2495       bfd_size_type j;
2496
2497       bfd_sprintf_vma (abfd, buf, (addr_offset + section->vma));
2498       count = strlen (buf);
2499       if ((size_t) count >= sizeof (buf))
2500         abort ();
2501
2502       putchar (' ');
2503       while (count < width)
2504         {
2505           putchar ('0');
2506           count++;
2507         }
2508       fputs (buf + count - width, stdout);
2509       putchar (' ');
2510
2511       for (j = addr_offset * opb;
2512            j < addr_offset * opb + onaline; j++)
2513         {
2514           if (j < stop_offset * opb)
2515             printf ("%02x", (unsigned) (data[j]));
2516           else
2517             printf ("  ");
2518           if ((j & 3) == 3)
2519             printf (" ");
2520         }
2521
2522       printf (" ");
2523       for (j = addr_offset * opb;
2524            j < addr_offset * opb + onaline; j++)
2525         {
2526           if (j >= stop_offset * opb)
2527             printf (" ");
2528           else
2529             printf ("%c", ISPRINT (data[j]) ? data[j] : '.');
2530         }
2531       putchar ('\n');
2532     }
2533   free (data);
2534 }
2535
2536 /* Actually display the various requested regions.  */
2537
2538 static void
2539 dump_data (bfd *abfd)
2540 {
2541   bfd_map_over_sections (abfd, dump_section, NULL);
2542 }
2543
2544 /* Should perhaps share code and display with nm?  */
2545
2546 static void
2547 dump_symbols (bfd *abfd ATTRIBUTE_UNUSED, bfd_boolean dynamic)
2548 {
2549   asymbol **current;
2550   long max;
2551   long count;
2552
2553   if (dynamic)
2554     {
2555       current = dynsyms;
2556       max = dynsymcount;
2557       printf ("DYNAMIC SYMBOL TABLE:\n");
2558     }
2559   else
2560     {
2561       current = syms;
2562       max = symcount;
2563       printf ("SYMBOL TABLE:\n");
2564     }
2565
2566   if (max == 0)
2567     printf (_("no symbols\n"));
2568
2569   for (count = 0; count < max; count++)
2570     {
2571       bfd *cur_bfd;
2572
2573       if (*current == NULL)
2574         printf (_("no information for symbol number %ld\n"), count);
2575
2576       else if ((cur_bfd = bfd_asymbol_bfd (*current)) == NULL)
2577         printf (_("could not determine the type of symbol number %ld\n"),
2578                 count);
2579
2580       else if (process_section_p ((* current)->section)
2581                && (dump_special_syms
2582                    || !bfd_is_target_special_symbol (cur_bfd, *current)))
2583         {
2584           const char *name = (*current)->name;
2585
2586           if (do_demangle && name != NULL && *name != '\0')
2587             {
2588               char *alloc;
2589
2590               /* If we want to demangle the name, we demangle it
2591                  here, and temporarily clobber it while calling
2592                  bfd_print_symbol.  FIXME: This is a gross hack.  */
2593               alloc = bfd_demangle (cur_bfd, name, DMGL_ANSI | DMGL_PARAMS);
2594               if (alloc != NULL)
2595                 (*current)->name = alloc;
2596               bfd_print_symbol (cur_bfd, stdout, *current,
2597                                 bfd_print_symbol_all);
2598               if (alloc != NULL)
2599                 {
2600                   (*current)->name = name;
2601                   free (alloc);
2602                 }
2603             }
2604           else
2605             bfd_print_symbol (cur_bfd, stdout, *current,
2606                               bfd_print_symbol_all);
2607           printf ("\n");
2608         }
2609
2610       current++;
2611     }
2612   printf ("\n\n");
2613 }
2614 \f
2615 static void
2616 dump_reloc_set (bfd *abfd, asection *sec, arelent **relpp, long relcount)
2617 {
2618   arelent **p;
2619   char *last_filename, *last_functionname;
2620   unsigned int last_line;
2621
2622   /* Get column headers lined up reasonably.  */
2623   {
2624     static int width;
2625
2626     if (width == 0)
2627       {
2628         char buf[30];
2629
2630         bfd_sprintf_vma (abfd, buf, (bfd_vma) -1);
2631         width = strlen (buf) - 7;
2632       }
2633     printf ("OFFSET %*s TYPE %*s VALUE \n", width, "", 12, "");
2634   }
2635
2636   last_filename = NULL;
2637   last_functionname = NULL;
2638   last_line = 0;
2639
2640   for (p = relpp; relcount && *p != NULL; p++, relcount--)
2641     {
2642       arelent *q = *p;
2643       const char *filename, *functionname;
2644       unsigned int line;
2645       const char *sym_name;
2646       const char *section_name;
2647
2648       if (start_address != (bfd_vma) -1
2649           && q->address < start_address)
2650         continue;
2651       if (stop_address != (bfd_vma) -1
2652           && q->address > stop_address)
2653         continue;
2654
2655       if (with_line_numbers
2656           && sec != NULL
2657           && bfd_find_nearest_line (abfd, sec, syms, q->address,
2658                                     &filename, &functionname, &line))
2659         {
2660           if (functionname != NULL
2661               && (last_functionname == NULL
2662                   || strcmp (functionname, last_functionname) != 0))
2663             {
2664               printf ("%s():\n", functionname);
2665               if (last_functionname != NULL)
2666                 free (last_functionname);
2667               last_functionname = xstrdup (functionname);
2668             }
2669
2670           if (line > 0
2671               && (line != last_line
2672                   || (filename != NULL
2673                       && last_filename != NULL
2674                       && strcmp (filename, last_filename) != 0)))
2675             {
2676               printf ("%s:%u\n", filename == NULL ? "???" : filename, line);
2677               last_line = line;
2678               if (last_filename != NULL)
2679                 free (last_filename);
2680               if (filename == NULL)
2681                 last_filename = NULL;
2682               else
2683                 last_filename = xstrdup (filename);
2684             }
2685         }
2686
2687       if (q->sym_ptr_ptr && *q->sym_ptr_ptr)
2688         {
2689           sym_name = (*(q->sym_ptr_ptr))->name;
2690           section_name = (*(q->sym_ptr_ptr))->section->name;
2691         }
2692       else
2693         {
2694           sym_name = NULL;
2695           section_name = NULL;
2696         }
2697
2698       bfd_printf_vma (abfd, q->address);
2699       if (q->howto == NULL)
2700         printf (" *unknown*         ");
2701       else if (q->howto->name)
2702         printf (" %-16s  ", q->howto->name);
2703       else
2704         printf (" %-16d  ", q->howto->type);
2705       if (sym_name)
2706         objdump_print_symname (abfd, NULL, *q->sym_ptr_ptr);
2707       else
2708         {
2709           if (section_name == NULL)
2710             section_name = "*unknown*";
2711           printf ("[%s]", section_name);
2712         }
2713
2714       if (q->addend)
2715         {
2716           printf ("+0x");
2717           bfd_printf_vma (abfd, q->addend);
2718         }
2719
2720       printf ("\n");
2721     }
2722 }
2723
2724 static void
2725 dump_relocs_in_section (bfd *abfd,
2726                         asection *section,
2727                         void *dummy ATTRIBUTE_UNUSED)
2728 {
2729   arelent **relpp;
2730   long relcount;
2731   long relsize;
2732
2733   if (   bfd_is_abs_section (section)
2734       || bfd_is_und_section (section)
2735       || bfd_is_com_section (section)
2736       || (! process_section_p (section))
2737       || ((section->flags & SEC_RELOC) == 0))
2738     return;
2739
2740   relsize = bfd_get_reloc_upper_bound (abfd, section);
2741   if (relsize < 0)
2742     bfd_fatal (bfd_get_filename (abfd));
2743
2744   printf ("RELOCATION RECORDS FOR [%s]:", section->name);
2745
2746   if (relsize == 0)
2747     {
2748       printf (" (none)\n\n");
2749       return;
2750     }
2751
2752   relpp = xmalloc (relsize);
2753   relcount = bfd_canonicalize_reloc (abfd, section, relpp, syms);
2754
2755   if (relcount < 0)
2756     bfd_fatal (bfd_get_filename (abfd));
2757   else if (relcount == 0)
2758     printf (" (none)\n\n");
2759   else
2760     {
2761       printf ("\n");
2762       dump_reloc_set (abfd, section, relpp, relcount);
2763       printf ("\n\n");
2764     }
2765   free (relpp);
2766 }
2767
2768 static void
2769 dump_relocs (bfd *abfd)
2770 {
2771   bfd_map_over_sections (abfd, dump_relocs_in_section, NULL);
2772 }
2773
2774 static void
2775 dump_dynamic_relocs (bfd *abfd)
2776 {
2777   long relsize;
2778   arelent **relpp;
2779   long relcount;
2780
2781   relsize = bfd_get_dynamic_reloc_upper_bound (abfd);
2782   if (relsize < 0)
2783     bfd_fatal (bfd_get_filename (abfd));
2784
2785   printf ("DYNAMIC RELOCATION RECORDS");
2786
2787   if (relsize == 0)
2788     printf (" (none)\n\n");
2789   else
2790     {
2791       relpp = xmalloc (relsize);
2792       relcount = bfd_canonicalize_dynamic_reloc (abfd, relpp, dynsyms);
2793
2794       if (relcount < 0)
2795         bfd_fatal (bfd_get_filename (abfd));
2796       else if (relcount == 0)
2797         printf (" (none)\n\n");
2798       else
2799         {
2800           printf ("\n");
2801           dump_reloc_set (abfd, NULL, relpp, relcount);
2802           printf ("\n\n");
2803         }
2804       free (relpp);
2805     }
2806 }
2807
2808 /* Creates a table of paths, to search for source files.  */
2809
2810 static void
2811 add_include_path (const char *path)
2812 {
2813   if (path[0] == 0)
2814     return;
2815   include_path_count++;
2816   include_paths = xrealloc (include_paths,
2817                             include_path_count * sizeof (*include_paths));
2818 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
2819   if (path[1] == ':' && path[2] == 0)
2820     path = concat (path, ".", (const char *) 0);
2821 #endif
2822   include_paths[include_path_count - 1] = path;
2823 }
2824
2825 static void
2826 adjust_addresses (bfd *abfd ATTRIBUTE_UNUSED,
2827                   asection *section,
2828                   void *arg)
2829 {
2830   if ((section->flags & SEC_DEBUGGING) == 0)
2831     {
2832       bfd_boolean *has_reloc_p = (bfd_boolean *) arg;
2833       section->vma += adjust_section_vma;
2834       if (*has_reloc_p)
2835         section->lma += adjust_section_vma;
2836     }
2837 }
2838
2839 /* Dump selected contents of ABFD.  */
2840
2841 static void
2842 dump_bfd (bfd *abfd)
2843 {
2844   /* If we are adjusting section VMA's, change them all now.  Changing
2845      the BFD information is a hack.  However, we must do it, or
2846      bfd_find_nearest_line will not do the right thing.  */
2847   if (adjust_section_vma != 0)
2848     {
2849       bfd_boolean has_reloc = (abfd->flags & HAS_RELOC);
2850       bfd_map_over_sections (abfd, adjust_addresses, &has_reloc);
2851     }
2852
2853   if (! dump_debugging_tags)
2854     printf (_("\n%s:     file format %s\n"), bfd_get_filename (abfd),
2855             abfd->xvec->name);
2856   if (dump_ar_hdrs)
2857     print_arelt_descr (stdout, abfd, TRUE);
2858   if (dump_file_header)
2859     dump_bfd_header (abfd);
2860   if (dump_private_headers)
2861     dump_bfd_private_header (abfd);
2862   if (! dump_debugging_tags)
2863     putchar ('\n');
2864   if (dump_section_headers)
2865     dump_headers (abfd);
2866
2867   if (dump_symtab
2868       || dump_reloc_info
2869       || disassemble
2870       || dump_debugging
2871       || dump_dwarf_section_info)
2872     syms = slurp_symtab (abfd);
2873   if (dump_dynamic_symtab || dump_dynamic_reloc_info
2874       || (disassemble && bfd_get_dynamic_symtab_upper_bound (abfd) > 0))
2875     dynsyms = slurp_dynamic_symtab (abfd);
2876   if (disassemble)
2877     {
2878       synthcount = bfd_get_synthetic_symtab (abfd, symcount, syms,
2879                                              dynsymcount, dynsyms, &synthsyms);
2880       if (synthcount < 0)
2881         synthcount = 0;
2882     }
2883
2884   if (dump_symtab)
2885     dump_symbols (abfd, FALSE);
2886   if (dump_dynamic_symtab)
2887     dump_symbols (abfd, TRUE);
2888   if (dump_dwarf_section_info)
2889     dump_dwarf (abfd);
2890   if (dump_stab_section_info)
2891     dump_stabs (abfd);
2892   if (dump_reloc_info && ! disassemble)
2893     dump_relocs (abfd);
2894   if (dump_dynamic_reloc_info && ! disassemble)
2895     dump_dynamic_relocs (abfd);
2896   if (dump_section_contents)
2897     dump_data (abfd);
2898   if (disassemble)
2899     disassemble_data (abfd);
2900
2901   if (dump_debugging)
2902     {
2903       void *dhandle;
2904
2905       dhandle = read_debugging_info (abfd, syms, symcount);
2906       if (dhandle != NULL)
2907         {
2908           if (!print_debugging_info (stdout, dhandle, abfd, syms,
2909                                      bfd_demangle,
2910                                      dump_debugging_tags ? TRUE : FALSE))
2911             {
2912               non_fatal (_("%s: printing debugging information failed"),
2913                          bfd_get_filename (abfd));
2914               exit_status = 1;
2915             }
2916         }
2917     }
2918
2919   if (syms)
2920     {
2921       free (syms);
2922       syms = NULL;
2923     }
2924
2925   if (dynsyms)
2926     {
2927       free (dynsyms);
2928       dynsyms = NULL;
2929     }
2930
2931   if (synthsyms)
2932     {
2933       free (synthsyms);
2934       synthsyms = NULL;
2935     }
2936
2937   symcount = 0;
2938   dynsymcount = 0;
2939   synthcount = 0;
2940 }
2941
2942 static void
2943 display_bfd (bfd *abfd)
2944 {
2945   char **matching;
2946
2947   if (bfd_check_format_matches (abfd, bfd_object, &matching))
2948     {
2949       dump_bfd (abfd);
2950       return;
2951     }
2952
2953   if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
2954     {
2955       nonfatal (bfd_get_filename (abfd));
2956       list_matching_formats (matching);
2957       free (matching);
2958       return;
2959     }
2960
2961   if (bfd_get_error () != bfd_error_file_not_recognized)
2962     {
2963       nonfatal (bfd_get_filename (abfd));
2964       return;
2965     }
2966
2967   if (bfd_check_format_matches (abfd, bfd_core, &matching))
2968     {
2969       dump_bfd (abfd);
2970       return;
2971     }
2972
2973   nonfatal (bfd_get_filename (abfd));
2974
2975   if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
2976     {
2977       list_matching_formats (matching);
2978       free (matching);
2979     }
2980 }
2981
2982 static void
2983 display_file (char *filename, char *target)
2984 {
2985   bfd *file;
2986   bfd *arfile = NULL;
2987
2988   if (get_file_size (filename) < 1)
2989     {
2990       exit_status = 1;
2991       return;
2992     }
2993
2994   file = bfd_openr (filename, target);
2995   if (file == NULL)
2996     {
2997       nonfatal (filename);
2998       return;
2999     }
3000
3001   /* If the file is an archive, process all of its elements.  */
3002   if (bfd_check_format (file, bfd_archive))
3003     {
3004       bfd *last_arfile = NULL;
3005
3006       printf (_("In archive %s:\n"), bfd_get_filename (file));
3007       for (;;)
3008         {
3009           bfd_set_error (bfd_error_no_error);
3010
3011           arfile = bfd_openr_next_archived_file (file, arfile);
3012           if (arfile == NULL)
3013             {
3014               if (bfd_get_error () != bfd_error_no_more_archived_files)
3015                 nonfatal (bfd_get_filename (file));
3016               break;
3017             }
3018
3019           display_bfd (arfile);
3020
3021           if (last_arfile != NULL)
3022             bfd_close (last_arfile);
3023           last_arfile = arfile;
3024         }
3025
3026       if (last_arfile != NULL)
3027         bfd_close (last_arfile);
3028     }
3029   else
3030     display_bfd (file);
3031
3032   bfd_close (file);
3033 }
3034 \f
3035 int
3036 main (int argc, char **argv)
3037 {
3038   int c;
3039   char *target = default_target;
3040   bfd_boolean seenflag = FALSE;
3041
3042 #if defined (HAVE_SETLOCALE)
3043 #if defined (HAVE_LC_MESSAGES)
3044   setlocale (LC_MESSAGES, "");
3045 #endif
3046   setlocale (LC_CTYPE, "");
3047 #endif
3048
3049   bindtextdomain (PACKAGE, LOCALEDIR);
3050   textdomain (PACKAGE);
3051
3052   program_name = *argv;
3053   xmalloc_set_program_name (program_name);
3054
3055   START_PROGRESS (program_name, 0);
3056
3057   expandargv (&argc, &argv);
3058
3059   bfd_init ();
3060   set_default_bfd_target ();
3061
3062   while ((c = getopt_long (argc, argv, "pib:m:M:VvCdDlfaHhrRtTxsSI:j:wE:zgeGW",
3063                            long_options, (int *) 0))
3064          != EOF)
3065     {
3066       switch (c)
3067         {
3068         case 0:
3069           break;                /* We've been given a long option.  */
3070         case 'm':
3071           machine = optarg;
3072           break;
3073         case 'M':
3074           if (disassembler_options)
3075             /* Ignore potential memory leak for now.  */
3076             disassembler_options = concat (disassembler_options, ",",
3077                                            optarg, NULL);
3078           else
3079             disassembler_options = optarg;
3080           break;
3081         case 'j':
3082           if (only_used == only_size)
3083             {
3084               only_size += 8;
3085               only = xrealloc (only, only_size * sizeof (char *));
3086             }
3087           only [only_used++] = optarg;
3088           break;
3089         case 'l':
3090           with_line_numbers = TRUE;
3091           break;
3092         case 'b':
3093           target = optarg;
3094           break;
3095         case 'C':
3096           do_demangle = TRUE;
3097           if (optarg != NULL)
3098             {
3099               enum demangling_styles style;
3100
3101               style = cplus_demangle_name_to_style (optarg);
3102               if (style == unknown_demangling)
3103                 fatal (_("unknown demangling style `%s'"),
3104                        optarg);
3105
3106               cplus_demangle_set_style (style);
3107             }
3108           break;
3109         case 'w':
3110           wide_output = TRUE;
3111           break;
3112         case OPTION_ADJUST_VMA:
3113           adjust_section_vma = parse_vma (optarg, "--adjust-vma");
3114           break;
3115         case OPTION_START_ADDRESS:
3116           start_address = parse_vma (optarg, "--start-address");
3117           break;
3118         case OPTION_STOP_ADDRESS:
3119           stop_address = parse_vma (optarg, "--stop-address");
3120           break;
3121         case 'E':
3122           if (strcmp (optarg, "B") == 0)
3123             endian = BFD_ENDIAN_BIG;
3124           else if (strcmp (optarg, "L") == 0)
3125             endian = BFD_ENDIAN_LITTLE;
3126           else
3127             {
3128               non_fatal (_("unrecognized -E option"));
3129               usage (stderr, 1);
3130             }
3131           break;
3132         case OPTION_ENDIAN:
3133           if (strncmp (optarg, "big", strlen (optarg)) == 0)
3134             endian = BFD_ENDIAN_BIG;
3135           else if (strncmp (optarg, "little", strlen (optarg)) == 0)
3136             endian = BFD_ENDIAN_LITTLE;
3137           else
3138             {
3139               non_fatal (_("unrecognized --endian type `%s'"), optarg);
3140               usage (stderr, 1);
3141             }
3142           break;
3143
3144         case 'f':
3145           dump_file_header = TRUE;
3146           seenflag = TRUE;
3147           break;
3148         case 'i':
3149           formats_info = TRUE;
3150           seenflag = TRUE;
3151           break;
3152         case 'I':
3153           add_include_path (optarg);
3154           break;
3155         case 'p':
3156           dump_private_headers = TRUE;
3157           seenflag = TRUE;
3158           break;
3159         case 'x':
3160           dump_private_headers = TRUE;
3161           dump_symtab = TRUE;
3162           dump_reloc_info = TRUE;
3163           dump_file_header = TRUE;
3164           dump_ar_hdrs = TRUE;
3165           dump_section_headers = TRUE;
3166           seenflag = TRUE;
3167           break;
3168         case 't':
3169           dump_symtab = TRUE;
3170           seenflag = TRUE;
3171           break;
3172         case 'T':
3173           dump_dynamic_symtab = TRUE;
3174           seenflag = TRUE;
3175           break;
3176         case 'd':
3177           disassemble = TRUE;
3178           seenflag = TRUE;
3179           break;
3180         case 'z':
3181           disassemble_zeroes = TRUE;
3182           break;
3183         case 'D':
3184           disassemble = TRUE;
3185           disassemble_all = TRUE;
3186           seenflag = TRUE;
3187           break;
3188         case 'S':
3189           disassemble = TRUE;
3190           with_source_code = TRUE;
3191           seenflag = TRUE;
3192           break;
3193         case 'g':
3194           dump_debugging = 1;
3195           seenflag = TRUE;
3196           break;
3197         case 'e':
3198           dump_debugging = 1;
3199           dump_debugging_tags = 1;
3200           do_demangle = TRUE;
3201           seenflag = TRUE;
3202           break;
3203         case 'W':
3204           dump_dwarf_section_info = TRUE;
3205           seenflag = TRUE;
3206           do_debug_info = 1;
3207           do_debug_abbrevs = 1;
3208           do_debug_lines = 1;
3209           do_debug_pubnames = 1;
3210           do_debug_aranges = 1;
3211           do_debug_ranges = 1;
3212           do_debug_frames = 1;
3213           do_debug_macinfo = 1;
3214           do_debug_str = 1;
3215           do_debug_loc = 1;
3216           break;
3217         case 'G':
3218           dump_stab_section_info = TRUE;
3219           seenflag = TRUE;
3220           break;
3221         case 's':
3222           dump_section_contents = TRUE;
3223           seenflag = TRUE;
3224           break;
3225         case 'r':
3226           dump_reloc_info = TRUE;
3227           seenflag = TRUE;
3228           break;
3229         case 'R':
3230           dump_dynamic_reloc_info = TRUE;
3231           seenflag = TRUE;
3232           break;
3233         case 'a':
3234           dump_ar_hdrs = TRUE;
3235           seenflag = TRUE;
3236           break;
3237         case 'h':
3238           dump_section_headers = TRUE;
3239           seenflag = TRUE;
3240           break;
3241         case 'H':
3242           usage (stdout, 0);
3243           seenflag = TRUE;
3244         case 'v':
3245         case 'V':
3246           show_version = TRUE;
3247           seenflag = TRUE;
3248           break;
3249
3250         default:
3251           usage (stderr, 1);
3252         }
3253     }
3254
3255   if (show_version)
3256     print_version ("objdump");
3257
3258   if (!seenflag)
3259     usage (stderr, 2);
3260
3261   if (formats_info)
3262     exit_status = display_info ();
3263   else
3264     {
3265       if (optind == argc)
3266         display_file ("a.out", target);
3267       else
3268         for (; optind < argc;)
3269           display_file (argv[optind++], target);
3270     }
3271
3272   END_PROGRESS (program_name);
3273
3274   return exit_status;
3275 }