Merge from vendor branch TCPDUMP:
[dragonfly.git] / contrib / binutils-2.14 / 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
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 2, 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, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
21
22 #include "bfd.h"
23 #include "bfdver.h"
24 #include "progress.h"
25 #include "bucomm.h"
26 #include "budemang.h"
27 #include "getopt.h"
28 #include "safe-ctype.h"
29 #include "dis-asm.h"
30 #include "libiberty.h"
31 #include "demangle.h"
32 #include "debug.h"
33 #include "budbg.h"
34
35 /* Internal headers for the ELF .stab-dump code - sorry.  */
36 #define BYTES_IN_WORD   32
37 #include "aout/aout64.h"
38
39 #ifdef NEED_DECLARATION_FPRINTF
40 /* This is needed by INIT_DISASSEMBLE_INFO.  */
41 extern int fprintf
42   PARAMS ((FILE *, const char *, ...));
43 #endif
44
45 /* Exit status.  */
46 static int exit_status = 0;
47
48 static char *default_target = NULL;     /* Default at runtime.  */
49
50 static int show_version = 0;            /* Show the version number.  */
51 static int dump_section_contents;       /* -s */
52 static int dump_section_headers;        /* -h */
53 static bfd_boolean dump_file_header;    /* -f */
54 static int dump_symtab;                 /* -t */
55 static int dump_dynamic_symtab;         /* -T */
56 static int dump_reloc_info;             /* -r */
57 static int dump_dynamic_reloc_info;     /* -R */
58 static int dump_ar_hdrs;                /* -a */
59 static int dump_private_headers;        /* -p */
60 static int prefix_addresses;            /* --prefix-addresses */
61 static int with_line_numbers;           /* -l */
62 static bfd_boolean with_source_code;    /* -S */
63 static int show_raw_insn;               /* --show-raw-insn */
64 static int dump_stab_section_info;      /* --stabs */
65 static int do_demangle;                 /* -C, --demangle */
66 static bfd_boolean disassemble;         /* -d */
67 static bfd_boolean disassemble_all;     /* -D */
68 static int disassemble_zeroes;          /* --disassemble-zeroes */
69 static bfd_boolean formats_info;        /* -i */
70 static char *only;                      /* -j secname */
71 static int wide_output;                 /* -w */
72 static bfd_vma start_address = (bfd_vma) -1; /* --start-address */
73 static bfd_vma stop_address = (bfd_vma) -1;  /* --stop-address */
74 static int dump_debugging;              /* --debugging */
75 static bfd_vma adjust_section_vma = 0;  /* --adjust-vma */
76 static int file_start_context = 0;      /* --file-start-context */
77
78 /* Extra info to pass to the disassembler address printing function.  */
79 struct objdump_disasm_info
80 {
81   bfd *abfd;
82   asection *sec;
83   bfd_boolean require_sec;
84 };
85
86 /* Architecture to disassemble for, or default if NULL.  */
87 static char *machine = (char *) NULL;
88
89 /* Target specific options to the disassembler.  */
90 static char *disassembler_options = (char *) NULL;
91
92 /* Endianness to disassemble for, or default if BFD_ENDIAN_UNKNOWN.  */
93 static enum bfd_endian endian = BFD_ENDIAN_UNKNOWN;
94
95 /* The symbol table.  */
96 static asymbol **syms;
97
98 /* Number of symbols in `syms'.  */
99 static long symcount = 0;
100
101 /* The sorted symbol table.  */
102 static asymbol **sorted_syms;
103
104 /* Number of symbols in `sorted_syms'.  */
105 static long sorted_symcount = 0;
106
107 /* The dynamic symbol table.  */
108 static asymbol **dynsyms;
109
110 /* Number of symbols in `dynsyms'.  */
111 static long dynsymcount = 0;
112
113 static bfd_byte *stabs;
114 static bfd_size_type stab_size;
115
116 static char *strtab;
117 static bfd_size_type stabstr_size;
118
119 /* Static declarations.  */
120
121 static void usage
122   PARAMS ((FILE *, int));
123 static void nonfatal
124   PARAMS ((const char *));
125 static void display_file
126   PARAMS ((char *, char *));
127 static void dump_section_header
128   PARAMS ((bfd *, asection *, PTR));
129 static void dump_headers
130   PARAMS ((bfd *));
131 static void dump_data
132   PARAMS ((bfd *));
133 static void dump_relocs
134   PARAMS ((bfd *));
135 static void dump_dynamic_relocs
136   PARAMS ((bfd *));
137 static void dump_reloc_set
138   PARAMS ((bfd *, asection *, arelent **, long));
139 static void dump_symbols
140   PARAMS ((bfd *, bfd_boolean));
141 static void dump_bfd_header
142   PARAMS ((bfd *));
143 static void dump_bfd_private_header
144   PARAMS ((bfd *));
145 static void dump_bfd
146   PARAMS ((bfd *));
147 static void display_bfd
148   PARAMS ((bfd *));
149 static void objdump_print_value
150   PARAMS ((bfd_vma, struct disassemble_info *, bfd_boolean));
151 static void objdump_print_symname
152   PARAMS ((bfd *, struct disassemble_info *, asymbol *));
153 static asymbol *find_symbol_for_address
154   PARAMS ((bfd *, asection *, bfd_vma, bfd_boolean, long *));
155 static void objdump_print_addr_with_sym
156   PARAMS ((bfd *, asection *, asymbol *, bfd_vma,
157            struct disassemble_info *, bfd_boolean));
158 static void objdump_print_addr
159   PARAMS ((bfd_vma, struct disassemble_info *, bfd_boolean));
160 static void objdump_print_address
161   PARAMS ((bfd_vma, struct disassemble_info *));
162 static int objdump_symbol_at_address
163   PARAMS ((bfd_vma, struct disassemble_info *));
164 static void show_line
165   PARAMS ((bfd *, asection *, bfd_vma));
166 static void disassemble_bytes
167   PARAMS ((struct disassemble_info *, disassembler_ftype, bfd_boolean,
168            bfd_byte *, bfd_vma, bfd_vma, arelent ***, arelent **));
169 static void disassemble_data
170   PARAMS ((bfd *));
171 static asymbol ** slurp_symtab
172   PARAMS ((bfd *));
173 static asymbol ** slurp_dynamic_symtab
174   PARAMS ((bfd *));
175 static long remove_useless_symbols
176   PARAMS ((asymbol **, long));
177 static int compare_symbols
178   PARAMS ((const PTR, const PTR));
179 static int compare_relocs
180   PARAMS ((const PTR, const PTR));
181 static void dump_stabs
182   PARAMS ((bfd *));
183 static bfd_boolean read_section_stabs
184   PARAMS ((bfd *, const char *, const char *));
185 static void print_section_stabs
186   PARAMS ((bfd *, const char *, const char *));
187 static void dump_section_stabs
188   PARAMS ((bfd *, char *, char *));
189 \f
190 static void
191 usage (stream, status)
192      FILE *stream;
193      int status;
194 {
195   fprintf (stream, _("Usage: %s <option(s)> <file(s)>\n"), program_name);
196   fprintf (stream, _(" Display information from object <file(s)>.\n"));
197   fprintf (stream, _(" At least one of the following switches must be given:\n"));
198   fprintf (stream, _("\
199   -a, --archive-headers    Display archive header information\n\
200   -f, --file-headers       Display the contents of the overall file header\n\
201   -p, --private-headers    Display object format specific file header contents\n\
202   -h, --[section-]headers  Display the contents of the section headers\n\
203   -x, --all-headers        Display the contents of all headers\n\
204   -d, --disassemble        Display assembler contents of executable sections\n\
205   -D, --disassemble-all    Display assembler contents of all sections\n\
206   -S, --source             Intermix source code with disassembly\n\
207   -s, --full-contents      Display the full contents of all sections requested\n\
208   -g, --debugging          Display debug information in object file\n\
209   -G, --stabs              Display (in raw form) any STABS info in the file\n\
210   -t, --syms               Display the contents of the symbol table(s)\n\
211   -T, --dynamic-syms       Display the contents of the dynamic symbol table\n\
212   -r, --reloc              Display the relocation entries in the file\n\
213   -R, --dynamic-reloc      Display the dynamic relocation entries in the file\n\
214   -v, --version            Display this program's version number\n\
215   -i, --info               List object formats and architectures supported\n\
216   -H, --help               Display this information\n\
217 "));
218   if (status != 2)
219     {
220       fprintf (stream, _("\n The following switches are optional:\n"));
221       fprintf (stream, _("\
222   -b, --target=BFDNAME           Specify the target object format as BFDNAME\n\
223   -m, --architecture=MACHINE     Specify the target architecture as MACHINE\n\
224   -j, --section=NAME             Only display information for section NAME\n\
225   -M, --disassembler-options=OPT Pass text OPT on to the disassembler\n\
226   -EB --endian=big               Assume big endian format when disassembling\n\
227   -EL --endian=little            Assume little endian format when disassembling\n\
228       --file-start-context       Include context from start of file (with -S)\n\
229   -l, --line-numbers             Include line numbers and filenames in output\n\
230   -C, --demangle[=STYLE]         Decode mangled/processed symbol names\n\
231                                   The STYLE, if specified, can be `auto', `gnu',\n\
232                                   `lucid', `arm', `hp', `edg', `gnu-v3', `java'\n\
233                                   or `gnat'\n\
234   -w, --wide                     Format output for more than 80 columns\n\
235   -z, --disassemble-zeroes       Do not skip blocks of zeroes when disassembling\n\
236       --start-address=ADDR       Only process data whose address is >= ADDR\n\
237       --stop-address=ADDR        Only process data whose address is <= ADDR\n\
238       --prefix-addresses         Print complete address alongside disassembly\n\
239       --[no-]show-raw-insn       Display hex alongside symbolic disassembly\n\
240       --adjust-vma=OFFSET        Add OFFSET to all displayed section addresses\n\
241 \n"));
242       list_supported_targets (program_name, stream);
243       list_supported_architectures (program_name, stream);
244
245       disassembler_usage (stream);
246     }
247   if (status == 0)
248     fprintf (stream, _("Report bugs to %s.\n"), REPORT_BUGS_TO);
249   exit (status);
250 }
251
252 /* 150 isn't special; it's just an arbitrary non-ASCII char value.  */
253
254 #define OPTION_ENDIAN (150)
255 #define OPTION_START_ADDRESS (OPTION_ENDIAN + 1)
256 #define OPTION_STOP_ADDRESS (OPTION_START_ADDRESS + 1)
257 #define OPTION_ADJUST_VMA (OPTION_STOP_ADDRESS + 1)
258
259 static struct option long_options[]=
260 {
261   {"adjust-vma", required_argument, NULL, OPTION_ADJUST_VMA},
262   {"all-headers", no_argument, NULL, 'x'},
263   {"private-headers", no_argument, NULL, 'p'},
264   {"architecture", required_argument, NULL, 'm'},
265   {"archive-headers", no_argument, NULL, 'a'},
266   {"debugging", no_argument, NULL, 'g'},
267   {"demangle", optional_argument, NULL, 'C'},
268   {"disassemble", no_argument, NULL, 'd'},
269   {"disassemble-all", no_argument, NULL, 'D'},
270   {"disassembler-options", required_argument, NULL, 'M'},
271   {"disassemble-zeroes", no_argument, NULL, 'z'},
272   {"dynamic-reloc", no_argument, NULL, 'R'},
273   {"dynamic-syms", no_argument, NULL, 'T'},
274   {"endian", required_argument, NULL, OPTION_ENDIAN},
275   {"file-headers", no_argument, NULL, 'f'},
276   {"file-start-context", no_argument, &file_start_context, 1},
277   {"full-contents", no_argument, NULL, 's'},
278   {"headers", no_argument, NULL, 'h'},
279   {"help", no_argument, NULL, 'H'},
280   {"info", no_argument, NULL, 'i'},
281   {"line-numbers", no_argument, NULL, 'l'},
282   {"no-show-raw-insn", no_argument, &show_raw_insn, -1},
283   {"prefix-addresses", no_argument, &prefix_addresses, 1},
284   {"reloc", no_argument, NULL, 'r'},
285   {"section", required_argument, NULL, 'j'},
286   {"section-headers", no_argument, NULL, 'h'},
287   {"show-raw-insn", no_argument, &show_raw_insn, 1},
288   {"source", no_argument, NULL, 'S'},
289   {"stabs", no_argument, NULL, 'G'},
290   {"start-address", required_argument, NULL, OPTION_START_ADDRESS},
291   {"stop-address", required_argument, NULL, OPTION_STOP_ADDRESS},
292   {"syms", no_argument, NULL, 't'},
293   {"target", required_argument, NULL, 'b'},
294   {"version", no_argument, NULL, 'V'},
295   {"wide", no_argument, NULL, 'w'},
296   {0, no_argument, 0, 0}
297 };
298 \f
299 static void
300 nonfatal (msg)
301      const char *msg;
302 {
303   bfd_nonfatal (msg);
304   exit_status = 1;
305 }
306 \f
307 static void
308 dump_section_header (abfd, section, ignored)
309      bfd *abfd ATTRIBUTE_UNUSED;
310      asection *section;
311      PTR ignored ATTRIBUTE_UNUSED;
312 {
313   char *comma = "";
314   unsigned int opb = bfd_octets_per_byte (abfd);
315
316   printf ("%3d %-13s %08lx  ", section->index,
317           bfd_get_section_name (abfd, section),
318           (unsigned long) bfd_section_size (abfd, section) / opb);
319   bfd_printf_vma (abfd, bfd_get_section_vma (abfd, section));
320   printf ("  ");
321   bfd_printf_vma (abfd, section->lma);
322   printf ("  %08lx  2**%u", (unsigned long) section->filepos,
323           bfd_get_section_alignment (abfd, section));
324   if (! wide_output)
325     printf ("\n                ");
326   printf ("  ");
327
328 #define PF(x, y) \
329   if (section->flags & x) { printf ("%s%s", comma, y); comma = ", "; }
330
331   PF (SEC_HAS_CONTENTS, "CONTENTS");
332   PF (SEC_ALLOC, "ALLOC");
333   PF (SEC_CONSTRUCTOR, "CONSTRUCTOR");
334   PF (SEC_LOAD, "LOAD");
335   PF (SEC_RELOC, "RELOC");
336   PF (SEC_READONLY, "READONLY");
337   PF (SEC_CODE, "CODE");
338   PF (SEC_DATA, "DATA");
339   PF (SEC_ROM, "ROM");
340   PF (SEC_DEBUGGING, "DEBUGGING");
341   PF (SEC_NEVER_LOAD, "NEVER_LOAD");
342   PF (SEC_EXCLUDE, "EXCLUDE");
343   PF (SEC_SORT_ENTRIES, "SORT_ENTRIES");
344   PF (SEC_BLOCK, "BLOCK");
345   PF (SEC_CLINK, "CLINK");
346   PF (SEC_SMALL_DATA, "SMALL_DATA");
347   PF (SEC_SHARED, "SHARED");
348   PF (SEC_ARCH_BIT_0, "ARCH_BIT_0");
349   PF (SEC_THREAD_LOCAL, "THREAD_LOCAL");
350
351   if ((section->flags & SEC_LINK_ONCE) != 0)
352     {
353       const char *ls;
354
355       switch (section->flags & SEC_LINK_DUPLICATES)
356         {
357         default:
358           abort ();
359         case SEC_LINK_DUPLICATES_DISCARD:
360           ls = "LINK_ONCE_DISCARD";
361           break;
362         case SEC_LINK_DUPLICATES_ONE_ONLY:
363           ls = "LINK_ONCE_ONE_ONLY";
364           break;
365         case SEC_LINK_DUPLICATES_SAME_SIZE:
366           ls = "LINK_ONCE_SAME_SIZE";
367           break;
368         case SEC_LINK_DUPLICATES_SAME_CONTENTS:
369           ls = "LINK_ONCE_SAME_CONTENTS";
370           break;
371         }
372       printf ("%s%s", comma, ls);
373
374       if (section->comdat != NULL)
375         printf (" (COMDAT %s %ld)", section->comdat->name,
376                 section->comdat->symbol);
377
378       comma = ", ";
379     }
380
381   printf ("\n");
382 #undef PF
383 }
384
385 static void
386 dump_headers (abfd)
387      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, (PTR) NULL);
408 }
409 \f
410 static asymbol **
411 slurp_symtab (abfd)
412      bfd *abfd;
413 {
414   asymbol **sy = (asymbol **) NULL;
415   long storage;
416
417   if (!(bfd_get_file_flags (abfd) & HAS_SYMS))
418     {
419       symcount = 0;
420       return NULL;
421     }
422
423   storage = bfd_get_symtab_upper_bound (abfd);
424   if (storage < 0)
425     bfd_fatal (bfd_get_filename (abfd));
426   if (storage)
427     sy = (asymbol **) xmalloc (storage);
428
429   symcount = bfd_canonicalize_symtab (abfd, sy);
430   if (symcount < 0)
431     bfd_fatal (bfd_get_filename (abfd));
432   return sy;
433 }
434
435 /* Read in the dynamic symbols.  */
436
437 static asymbol **
438 slurp_dynamic_symtab (abfd)
439      bfd *abfd;
440 {
441   asymbol **sy = (asymbol **) NULL;
442   long storage;
443
444   storage = bfd_get_dynamic_symtab_upper_bound (abfd);
445   if (storage < 0)
446     {
447       if (!(bfd_get_file_flags (abfd) & DYNAMIC))
448         {
449           non_fatal (_("%s: not a dynamic object"), bfd_get_filename (abfd));
450           dynsymcount = 0;
451           return NULL;
452         }
453
454       bfd_fatal (bfd_get_filename (abfd));
455     }
456   if (storage)
457     sy = (asymbol **) xmalloc (storage);
458
459   dynsymcount = bfd_canonicalize_dynamic_symtab (abfd, sy);
460   if (dynsymcount < 0)
461     bfd_fatal (bfd_get_filename (abfd));
462   return sy;
463 }
464
465 /* Filter out (in place) symbols that are useless for disassembly.
466    COUNT is the number of elements in SYMBOLS.
467    Return the number of useful symbols.  */
468
469 static long
470 remove_useless_symbols (symbols, count)
471      asymbol **symbols;
472      long count;
473 {
474   register asymbol **in_ptr = symbols, **out_ptr = symbols;
475
476   while (--count >= 0)
477     {
478       asymbol *sym = *in_ptr++;
479
480       if (sym->name == NULL || sym->name[0] == '\0')
481         continue;
482       if (sym->flags & (BSF_DEBUGGING))
483         continue;
484       if (bfd_is_und_section (sym->section)
485           || bfd_is_com_section (sym->section))
486         continue;
487
488       *out_ptr++ = sym;
489     }
490   return out_ptr - symbols;
491 }
492
493 /* Sort symbols into value order.  */
494
495 static int
496 compare_symbols (ap, bp)
497      const PTR ap;
498      const PTR bp;
499 {
500   const asymbol *a = *(const asymbol **)ap;
501   const asymbol *b = *(const asymbol **)bp;
502   const char *an, *bn;
503   size_t anl, bnl;
504   bfd_boolean af, bf;
505   flagword aflags, bflags;
506
507   if (bfd_asymbol_value (a) > bfd_asymbol_value (b))
508     return 1;
509   else if (bfd_asymbol_value (a) < bfd_asymbol_value (b))
510     return -1;
511
512   if (a->section > b->section)
513     return 1;
514   else if (a->section < b->section)
515     return -1;
516
517   an = bfd_asymbol_name (a);
518   bn = bfd_asymbol_name (b);
519   anl = strlen (an);
520   bnl = strlen (bn);
521
522   /* The symbols gnu_compiled and gcc2_compiled convey no real
523      information, so put them after other symbols with the same value.  */
524   af = (strstr (an, "gnu_compiled") != NULL
525         || strstr (an, "gcc2_compiled") != NULL);
526   bf = (strstr (bn, "gnu_compiled") != NULL
527         || strstr (bn, "gcc2_compiled") != NULL);
528
529   if (af && ! bf)
530     return 1;
531   if (! af && bf)
532     return -1;
533
534   /* We use a heuristic for the file name, to try to sort it after
535      more useful symbols.  It may not work on non Unix systems, but it
536      doesn't really matter; the only difference is precisely which
537      symbol names get printed.  */
538
539 #define file_symbol(s, sn, snl)                 \
540   (((s)->flags & BSF_FILE) != 0                 \
541    || ((sn)[(snl) - 2] == '.'                   \
542        && ((sn)[(snl) - 1] == 'o'               \
543            || (sn)[(snl) - 1] == 'a')))
544
545   af = file_symbol (a, an, anl);
546   bf = file_symbol (b, bn, bnl);
547
548   if (af && ! bf)
549     return 1;
550   if (! af && bf)
551     return -1;
552
553   /* Try to sort global symbols before local symbols before function
554      symbols before debugging symbols.  */
555
556   aflags = a->flags;
557   bflags = b->flags;
558
559   if ((aflags & BSF_DEBUGGING) != (bflags & BSF_DEBUGGING))
560     {
561       if ((aflags & BSF_DEBUGGING) != 0)
562         return 1;
563       else
564         return -1;
565     }
566   if ((aflags & BSF_FUNCTION) != (bflags & BSF_FUNCTION))
567     {
568       if ((aflags & BSF_FUNCTION) != 0)
569         return -1;
570       else
571         return 1;
572     }
573   if ((aflags & BSF_LOCAL) != (bflags & BSF_LOCAL))
574     {
575       if ((aflags & BSF_LOCAL) != 0)
576         return 1;
577       else
578         return -1;
579     }
580   if ((aflags & BSF_GLOBAL) != (bflags & BSF_GLOBAL))
581     {
582       if ((aflags & BSF_GLOBAL) != 0)
583         return -1;
584       else
585         return 1;
586     }
587
588   /* Symbols that start with '.' might be section names, so sort them
589      after symbols that don't start with '.'.  */
590   if (an[0] == '.' && bn[0] != '.')
591     return 1;
592   if (an[0] != '.' && bn[0] == '.')
593     return -1;
594
595   /* Finally, if we can't distinguish them in any other way, try to
596      get consistent results by sorting the symbols by name.  */
597   return strcmp (an, bn);
598 }
599
600 /* Sort relocs into address order.  */
601
602 static int
603 compare_relocs (ap, bp)
604      const PTR ap;
605      const PTR bp;
606 {
607   const arelent *a = *(const arelent **)ap;
608   const arelent *b = *(const arelent **)bp;
609
610   if (a->address > b->address)
611     return 1;
612   else if (a->address < b->address)
613     return -1;
614
615   /* So that associated relocations tied to the same address show up
616      in the correct order, we don't do any further sorting.  */
617   if (a > b)
618     return 1;
619   else if (a < b)
620     return -1;
621   else
622     return 0;
623 }
624
625 /* Print VMA to STREAM.  If SKIP_ZEROES is TRUE, omit leading zeroes.  */
626
627 static void
628 objdump_print_value (vma, info, skip_zeroes)
629      bfd_vma vma;
630      struct disassemble_info *info;
631      bfd_boolean skip_zeroes;
632 {
633   char buf[30];
634   char *p;
635   struct objdump_disasm_info *aux
636     = (struct objdump_disasm_info *) info->application_data;
637
638   bfd_sprintf_vma (aux->abfd, buf, vma);
639   if (! skip_zeroes)
640     p = buf;
641   else
642     {
643       for (p = buf; *p == '0'; ++p)
644         ;
645       if (*p == '\0')
646         --p;
647     }
648   (*info->fprintf_func) (info->stream, "%s", p);
649 }
650
651 /* Print the name of a symbol.  */
652
653 static void
654 objdump_print_symname (abfd, info, sym)
655      bfd *abfd;
656      struct disassemble_info *info;
657      asymbol *sym;
658 {
659   char *alloc;
660   const char *name;
661
662   alloc = NULL;
663   name = bfd_asymbol_name (sym);
664   if (do_demangle && name[0] != '\0')
665     {
666       /* Demangle the name.  */
667       alloc = demangle (abfd, name);
668       name = alloc;
669     }
670
671   if (info != NULL)
672     (*info->fprintf_func) (info->stream, "%s", name);
673   else
674     printf ("%s", name);
675
676   if (alloc != NULL)
677     free (alloc);
678 }
679
680 /* Locate a symbol given a bfd, a section, and a VMA.  If REQUIRE_SEC
681    is TRUE, then always require the symbol to be in the section.  This
682    returns NULL if there is no suitable symbol.  If PLACE is not NULL,
683    then *PLACE is set to the index of the symbol in sorted_syms.  */
684
685 static asymbol *
686 find_symbol_for_address (abfd, sec, vma, require_sec, place)
687      bfd *abfd;
688      asection *sec;
689      bfd_vma vma;
690      bfd_boolean require_sec;
691      long *place;
692 {
693   /* @@ Would it speed things up to cache the last two symbols returned,
694      and maybe their address ranges?  For many processors, only one memory
695      operand can be present at a time, so the 2-entry cache wouldn't be
696      constantly churned by code doing heavy memory accesses.  */
697
698   /* Indices in `sorted_syms'.  */
699   long min = 0;
700   long max = sorted_symcount;
701   long thisplace;
702   unsigned int opb = bfd_octets_per_byte (abfd);
703
704   if (sorted_symcount < 1)
705     return NULL;
706
707   /* Perform a binary search looking for the closest symbol to the
708      required value.  We are searching the range (min, max].  */
709   while (min + 1 < max)
710     {
711       asymbol *sym;
712
713       thisplace = (max + min) / 2;
714       sym = sorted_syms[thisplace];
715
716       if (bfd_asymbol_value (sym) > vma)
717         max = thisplace;
718       else if (bfd_asymbol_value (sym) < vma)
719         min = thisplace;
720       else
721         {
722           min = thisplace;
723           break;
724         }
725     }
726
727   /* The symbol we want is now in min, the low end of the range we
728      were searching.  If there are several symbols with the same
729      value, we want the first one.  */
730   thisplace = min;
731   while (thisplace > 0
732          && (bfd_asymbol_value (sorted_syms[thisplace])
733              == bfd_asymbol_value (sorted_syms[thisplace - 1])))
734     --thisplace;
735
736   /* If the file is relocateable, and the symbol could be from this
737      section, prefer a symbol from this section over symbols from
738      others, even if the other symbol's value might be closer.
739
740      Note that this may be wrong for some symbol references if the
741      sections have overlapping memory ranges, but in that case there's
742      no way to tell what's desired without looking at the relocation
743      table.  */
744   if (sorted_syms[thisplace]->section != sec
745       && (require_sec
746           || ((abfd->flags & HAS_RELOC) != 0
747               && vma >= bfd_get_section_vma (abfd, sec)
748               && vma < (bfd_get_section_vma (abfd, sec)
749                         + bfd_section_size (abfd, sec) / opb))))
750     {
751       long i;
752
753       for (i = thisplace + 1; i < sorted_symcount; i++)
754         {
755           if (bfd_asymbol_value (sorted_syms[i])
756               != bfd_asymbol_value (sorted_syms[thisplace]))
757             break;
758         }
759
760       --i;
761
762       for (; i >= 0; i--)
763         {
764           if (sorted_syms[i]->section == sec
765               && (i == 0
766                   || sorted_syms[i - 1]->section != sec
767                   || (bfd_asymbol_value (sorted_syms[i])
768                       != bfd_asymbol_value (sorted_syms[i - 1]))))
769             {
770               thisplace = i;
771               break;
772             }
773         }
774
775       if (sorted_syms[thisplace]->section != sec)
776         {
777           /* We didn't find a good symbol with a smaller value.
778              Look for one with a larger value.  */
779           for (i = thisplace + 1; i < sorted_symcount; i++)
780             {
781               if (sorted_syms[i]->section == sec)
782                 {
783                   thisplace = i;
784                   break;
785                 }
786             }
787         }
788
789       if (sorted_syms[thisplace]->section != sec
790           && (require_sec
791               || ((abfd->flags & HAS_RELOC) != 0
792                   && vma >= bfd_get_section_vma (abfd, sec)
793                   && vma < (bfd_get_section_vma (abfd, sec)
794                             + bfd_section_size (abfd, sec)))))
795         {
796           /* There is no suitable symbol.  */
797           return NULL;
798         }
799     }
800
801   if (place != NULL)
802     *place = thisplace;
803
804   return sorted_syms[thisplace];
805 }
806
807 /* Print an address to INFO symbolically.  */
808
809 static void
810 objdump_print_addr_with_sym (abfd, sec, sym, vma, info, skip_zeroes)
811      bfd *abfd;
812      asection *sec;
813      asymbol *sym;
814      bfd_vma vma;
815      struct disassemble_info *info;
816      bfd_boolean skip_zeroes;
817 {
818   objdump_print_value (vma, info, skip_zeroes);
819
820   if (sym == NULL)
821     {
822       bfd_vma secaddr;
823
824       (*info->fprintf_func) (info->stream, " <%s",
825                              bfd_get_section_name (abfd, sec));
826       secaddr = bfd_get_section_vma (abfd, sec);
827       if (vma < secaddr)
828         {
829           (*info->fprintf_func) (info->stream, "-0x");
830           objdump_print_value (secaddr - vma, info, TRUE);
831         }
832       else if (vma > secaddr)
833         {
834           (*info->fprintf_func) (info->stream, "+0x");
835           objdump_print_value (vma - secaddr, info, TRUE);
836         }
837       (*info->fprintf_func) (info->stream, ">");
838     }
839   else
840     {
841       (*info->fprintf_func) (info->stream, " <");
842       objdump_print_symname (abfd, info, sym);
843       if (bfd_asymbol_value (sym) > vma)
844         {
845           (*info->fprintf_func) (info->stream, "-0x");
846           objdump_print_value (bfd_asymbol_value (sym) - vma, info, TRUE);
847         }
848       else if (vma > bfd_asymbol_value (sym))
849         {
850           (*info->fprintf_func) (info->stream, "+0x");
851           objdump_print_value (vma - bfd_asymbol_value (sym), info, TRUE);
852         }
853       (*info->fprintf_func) (info->stream, ">");
854     }
855 }
856
857 /* Print VMA to INFO, symbolically if possible.  If SKIP_ZEROES is
858    TRUE, don't output leading zeroes.  */
859
860 static void
861 objdump_print_addr (vma, info, skip_zeroes)
862      bfd_vma vma;
863      struct disassemble_info *info;
864      bfd_boolean skip_zeroes;
865 {
866   struct objdump_disasm_info *aux;
867   asymbol *sym;
868
869   if (sorted_symcount < 1)
870     {
871       (*info->fprintf_func) (info->stream, "0x");
872       objdump_print_value (vma, info, skip_zeroes);
873       return;
874     }
875
876   aux = (struct objdump_disasm_info *) info->application_data;
877   sym = find_symbol_for_address (aux->abfd, aux->sec, vma, aux->require_sec,
878                                  (long *) NULL);
879   objdump_print_addr_with_sym (aux->abfd, aux->sec, sym, vma, info,
880                                skip_zeroes);
881 }
882
883 /* Print VMA to INFO.  This function is passed to the disassembler
884    routine.  */
885
886 static void
887 objdump_print_address (vma, info)
888      bfd_vma vma;
889      struct disassemble_info *info;
890 {
891   objdump_print_addr (vma, info, ! prefix_addresses);
892 }
893
894 /* Determine of the given address has a symbol associated with it.  */
895
896 static int
897 objdump_symbol_at_address (vma, info)
898      bfd_vma vma;
899      struct disassemble_info * info;
900 {
901   struct objdump_disasm_info * aux;
902   asymbol * sym;
903
904   /* No symbols - do not bother checking.  */
905   if (sorted_symcount < 1)
906     return 0;
907
908   aux = (struct objdump_disasm_info *) info->application_data;
909   sym = find_symbol_for_address (aux->abfd, aux->sec, vma, aux->require_sec,
910                                  (long *) NULL);
911
912   return (sym != NULL && (bfd_asymbol_value (sym) == vma));
913 }
914
915 /* Hold the last function name and the last line number we displayed
916    in a disassembly.  */
917
918 static char *prev_functionname;
919 static unsigned int prev_line;
920
921 /* We keep a list of all files that we have seen when doing a
922    dissassembly with source, so that we know how much of the file to
923    display.  This can be important for inlined functions.  */
924
925 struct print_file_list
926 {
927   struct print_file_list *next;
928   char *filename;
929   unsigned int line;
930   FILE *f;
931 };
932
933 static struct print_file_list *print_files;
934
935 /* The number of preceding context lines to show when we start
936    displaying a file for the first time.  */
937
938 #define SHOW_PRECEDING_CONTEXT_LINES (5)
939
940 /* Skip ahead to a given line in a file, optionally printing each
941    line.  */
942
943 static void skip_to_line
944   PARAMS ((struct print_file_list *, unsigned int, bfd_boolean));
945
946 static void
947 skip_to_line (p, line, show)
948      struct print_file_list *p;
949      unsigned int line;
950      bfd_boolean show;
951 {
952   while (p->line < line)
953     {
954       char buf[100];
955
956       if (fgets (buf, sizeof buf, p->f) == NULL)
957         {
958           fclose (p->f);
959           p->f = NULL;
960           break;
961         }
962
963       if (show)
964         printf ("%s", buf);
965
966       if (strchr (buf, '\n') != NULL)
967         ++p->line;
968     }
969 }
970
971 /* Show the line number, or the source line, in a dissassembly
972    listing.  */
973
974 static void
975 show_line (abfd, section, addr_offset)
976      bfd *abfd;
977      asection *section;
978      bfd_vma addr_offset;
979 {
980   const char *filename;
981   const char *functionname;
982   unsigned int line;
983
984   if (! with_line_numbers && ! with_source_code)
985     return;
986
987   if (! bfd_find_nearest_line (abfd, section, syms, addr_offset, &filename,
988                                &functionname, &line))
989     return;
990
991   if (filename != NULL && *filename == '\0')
992     filename = NULL;
993   if (functionname != NULL && *functionname == '\0')
994     functionname = NULL;
995
996   if (with_line_numbers)
997     {
998       if (functionname != NULL
999           && (prev_functionname == NULL
1000               || strcmp (functionname, prev_functionname) != 0))
1001         printf ("%s():\n", functionname);
1002       if (line > 0 && line != prev_line)
1003         printf ("%s:%u\n", filename == NULL ? "???" : filename, line);
1004     }
1005
1006   if (with_source_code
1007       && filename != NULL
1008       && line > 0)
1009     {
1010       struct print_file_list **pp, *p;
1011
1012       for (pp = &print_files; *pp != NULL; pp = &(*pp)->next)
1013         if (strcmp ((*pp)->filename, filename) == 0)
1014           break;
1015       p = *pp;
1016
1017       if (p != NULL)
1018         {
1019           if (p != print_files)
1020             {
1021               int l;
1022
1023               /* We have reencountered a file name which we saw
1024                  earlier.  This implies that either we are dumping out
1025                  code from an included file, or the same file was
1026                  linked in more than once.  There are two common cases
1027                  of an included file: inline functions in a header
1028                  file, and a bison or flex skeleton file.  In the
1029                  former case we want to just start printing (but we
1030                  back up a few lines to give context); in the latter
1031                  case we want to continue from where we left off.  I
1032                  can't think of a good way to distinguish the cases,
1033                  so I used a heuristic based on the file name.  */
1034               if (strcmp (p->filename + strlen (p->filename) - 2, ".h") != 0)
1035                 l = p->line;
1036               else
1037                 {
1038                   l = line - SHOW_PRECEDING_CONTEXT_LINES;
1039                   if (l < 0)
1040                     l = 0;
1041                 }
1042
1043               if (p->f == NULL)
1044                 {
1045                   p->f = fopen (p->filename, "r");
1046                   p->line = 0;
1047                 }
1048               if (p->f != NULL)
1049                 skip_to_line (p, l, FALSE);
1050
1051               if (print_files->f != NULL)
1052                 {
1053                   fclose (print_files->f);
1054                   print_files->f = NULL;
1055                 }
1056             }
1057
1058           if (p->f != NULL)
1059             {
1060               skip_to_line (p, line, TRUE);
1061               *pp = p->next;
1062               p->next = print_files;
1063               print_files = p;
1064             }
1065         }
1066       else
1067         {
1068           FILE *f;
1069
1070           f = fopen (filename, "r");
1071           if (f != NULL)
1072             {
1073               int l;
1074
1075               p = ((struct print_file_list *)
1076                    xmalloc (sizeof (struct print_file_list)));
1077               p->filename = xmalloc (strlen (filename) + 1);
1078               strcpy (p->filename, filename);
1079               p->line = 0;
1080               p->f = f;
1081
1082               if (print_files != NULL && print_files->f != NULL)
1083                 {
1084                   fclose (print_files->f);
1085                   print_files->f = NULL;
1086                 }
1087               p->next = print_files;
1088               print_files = p;
1089
1090               if (file_start_context)
1091                 l = 0;
1092               else
1093                 l = line - SHOW_PRECEDING_CONTEXT_LINES;
1094               if (l < 0)
1095                 l = 0;
1096               skip_to_line (p, l, FALSE);
1097               if (p->f != NULL)
1098                 skip_to_line (p, line, TRUE);
1099             }
1100         }
1101     }
1102
1103   if (functionname != NULL
1104       && (prev_functionname == NULL
1105           || strcmp (functionname, prev_functionname) != 0))
1106     {
1107       if (prev_functionname != NULL)
1108         free (prev_functionname);
1109       prev_functionname = xmalloc (strlen (functionname) + 1);
1110       strcpy (prev_functionname, functionname);
1111     }
1112
1113   if (line > 0 && line != prev_line)
1114     prev_line = line;
1115 }
1116
1117 /* Pseudo FILE object for strings.  */
1118 typedef struct
1119 {
1120   char *buffer;
1121   size_t size;
1122   char *current;
1123 } SFILE;
1124
1125 /* sprintf to a "stream" */
1126
1127 static int
1128 objdump_sprintf VPARAMS ((SFILE *f, const char *format, ...))
1129 {
1130   char *buf;
1131   size_t n;
1132
1133   VA_OPEN (args, format);
1134   VA_FIXEDARG (args, SFILE *, f);
1135   VA_FIXEDARG (args, const char *, format);
1136
1137   vasprintf (&buf, format, args);
1138
1139   if (buf == NULL)
1140     {
1141       va_end (args);
1142       fatal (_("Out of virtual memory"));
1143     }
1144
1145   n = strlen (buf);
1146
1147   while ((size_t) ((f->buffer + f->size) - f->current) < n + 1)
1148     {
1149       size_t curroff;
1150
1151       curroff = f->current - f->buffer;
1152       f->size *= 2;
1153       f->buffer = xrealloc (f->buffer, f->size);
1154       f->current = f->buffer + curroff;
1155     }
1156
1157   memcpy (f->current, buf, n);
1158   f->current += n;
1159   f->current[0] = '\0';
1160
1161   free (buf);
1162
1163   VA_CLOSE (args);
1164   return n;
1165 }
1166
1167 /* The number of zeroes we want to see before we start skipping them.
1168    The number is arbitrarily chosen.  */
1169
1170 #ifndef SKIP_ZEROES
1171 #define SKIP_ZEROES (8)
1172 #endif
1173
1174 /* The number of zeroes to skip at the end of a section.  If the
1175    number of zeroes at the end is between SKIP_ZEROES_AT_END and
1176    SKIP_ZEROES, they will be disassembled.  If there are fewer than
1177    SKIP_ZEROES_AT_END, they will be skipped.  This is a heuristic
1178    attempt to avoid disassembling zeroes inserted by section
1179    alignment.  */
1180
1181 #ifndef SKIP_ZEROES_AT_END
1182 #define SKIP_ZEROES_AT_END (3)
1183 #endif
1184
1185 /* Disassemble some data in memory between given values.  */
1186
1187 static void
1188 disassemble_bytes (info, disassemble_fn, insns, data,
1189                    start_offset, stop_offset, relppp,
1190                    relppend)
1191      struct disassemble_info *info;
1192      disassembler_ftype disassemble_fn;
1193      bfd_boolean insns;
1194      bfd_byte *data;
1195      bfd_vma start_offset;
1196      bfd_vma stop_offset;
1197      arelent ***relppp;
1198      arelent **relppend;
1199 {
1200   struct objdump_disasm_info *aux;
1201   asection *section;
1202   int octets_per_line;
1203   bfd_boolean done_dot;
1204   int skip_addr_chars;
1205   bfd_vma addr_offset;
1206   int opb = info->octets_per_byte;
1207
1208   aux = (struct objdump_disasm_info *) info->application_data;
1209   section = aux->sec;
1210
1211   if (insns)
1212     octets_per_line = 4;
1213   else
1214     octets_per_line = 16;
1215
1216   /* Figure out how many characters to skip at the start of an
1217      address, to make the disassembly look nicer.  We discard leading
1218      zeroes in chunks of 4, ensuring that there is always a leading
1219      zero remaining.  */
1220   skip_addr_chars = 0;
1221   if (! prefix_addresses)
1222     {
1223       char buf[30];
1224       char *s;
1225
1226       bfd_sprintf_vma
1227         (aux->abfd, buf,
1228          (section->vma
1229           + bfd_section_size (section->owner, section) / opb));
1230       s = buf;
1231       while (s[0] == '0' && s[1] == '0' && s[2] == '0' && s[3] == '0'
1232              && s[4] == '0')
1233         {
1234           skip_addr_chars += 4;
1235           s += 4;
1236         }
1237     }
1238
1239   info->insn_info_valid = 0;
1240
1241   done_dot = FALSE;
1242   addr_offset = start_offset;
1243   while (addr_offset < stop_offset)
1244     {
1245       bfd_vma z;
1246       int octets = 0;
1247       bfd_boolean need_nl = FALSE;
1248
1249       /* If we see more than SKIP_ZEROES octets of zeroes, we just
1250          print `...'.  */
1251       for (z = addr_offset * opb; z < stop_offset * opb; z++)
1252         if (data[z] != 0)
1253           break;
1254       if (! disassemble_zeroes
1255           && (info->insn_info_valid == 0
1256               || info->branch_delay_insns == 0)
1257           && (z - addr_offset * opb >= SKIP_ZEROES
1258               || (z == stop_offset * opb &&
1259                   z - addr_offset * opb < SKIP_ZEROES_AT_END)))
1260         {
1261           printf ("\t...\n");
1262
1263           /* If there are more nonzero octets to follow, we only skip
1264              zeroes in multiples of 4, to try to avoid running over
1265              the start of an instruction which happens to start with
1266              zero.  */
1267           if (z != stop_offset * opb)
1268             z = addr_offset * opb + ((z - addr_offset * opb) &~ 3);
1269
1270           octets = z - addr_offset * opb;
1271         }
1272       else
1273         {
1274           char buf[50];
1275           SFILE sfile;
1276           int bpc = 0;
1277           int pb = 0;
1278
1279           done_dot = FALSE;
1280
1281           if (with_line_numbers || with_source_code)
1282             /* The line number tables will refer to unadjusted
1283                section VMAs, so we must undo any VMA modifications
1284                when calling show_line.  */
1285             show_line (aux->abfd, section, addr_offset - adjust_section_vma);
1286
1287           if (! prefix_addresses)
1288             {
1289               char *s;
1290
1291               bfd_sprintf_vma (aux->abfd, buf, section->vma + addr_offset);
1292               for (s = buf + skip_addr_chars; *s == '0'; s++)
1293                 *s = ' ';
1294               if (*s == '\0')
1295                 *--s = '0';
1296               printf ("%s:\t", buf + skip_addr_chars);
1297             }
1298           else
1299             {
1300               aux->require_sec = TRUE;
1301               objdump_print_address (section->vma + addr_offset, info);
1302               aux->require_sec = FALSE;
1303               putchar (' ');
1304             }
1305
1306           if (insns)
1307             {
1308               sfile.size = 120;
1309               sfile.buffer = xmalloc (sfile.size);
1310               sfile.current = sfile.buffer;
1311               info->fprintf_func = (fprintf_ftype) objdump_sprintf;
1312               info->stream = (FILE *) &sfile;
1313               info->bytes_per_line = 0;
1314               info->bytes_per_chunk = 0;
1315
1316 #ifdef DISASSEMBLER_NEEDS_RELOCS
1317               /* FIXME: This is wrong.  It tests the number of octets
1318                  in the last instruction, not the current one.  */
1319               if (*relppp < relppend
1320                   && (**relppp)->address >= addr_offset
1321                   && (**relppp)->address <= addr_offset + octets / opb)
1322                 info->flags = INSN_HAS_RELOC;
1323               else
1324 #endif
1325                 info->flags = 0;
1326
1327               octets = (*disassemble_fn) (section->vma + addr_offset, info);
1328               info->fprintf_func = (fprintf_ftype) fprintf;
1329               info->stream = stdout;
1330               if (info->bytes_per_line != 0)
1331                 octets_per_line = info->bytes_per_line;
1332               if (octets < 0)
1333                 {
1334                   if (sfile.current != sfile.buffer)
1335                     printf ("%s\n", sfile.buffer);
1336                   free (sfile.buffer);
1337                   break;
1338                 }
1339             }
1340           else
1341             {
1342               bfd_vma j;
1343
1344               octets = octets_per_line;
1345               if (addr_offset + octets / opb > stop_offset)
1346                 octets = (stop_offset - addr_offset) * opb;
1347
1348               for (j = addr_offset * opb; j < addr_offset * opb + octets; ++j)
1349                 {
1350                   if (ISPRINT (data[j]))
1351                     buf[j - addr_offset * opb] = data[j];
1352                   else
1353                     buf[j - addr_offset * opb] = '.';
1354                 }
1355               buf[j - addr_offset * opb] = '\0';
1356             }
1357
1358           if (prefix_addresses
1359               ? show_raw_insn > 0
1360               : show_raw_insn >= 0)
1361             {
1362               bfd_vma j;
1363
1364               /* If ! prefix_addresses and ! wide_output, we print
1365                  octets_per_line octets per line.  */
1366               pb = octets;
1367               if (pb > octets_per_line && ! prefix_addresses && ! wide_output)
1368                 pb = octets_per_line;
1369
1370               if (info->bytes_per_chunk)
1371                 bpc = info->bytes_per_chunk;
1372               else
1373                 bpc = 1;
1374
1375               for (j = addr_offset * opb; j < addr_offset * opb + pb; j += bpc)
1376                 {
1377                   int k;
1378                   if (bpc > 1 && info->display_endian == BFD_ENDIAN_LITTLE)
1379                     {
1380                       for (k = bpc - 1; k >= 0; k--)
1381                         printf ("%02x", (unsigned) data[j + k]);
1382                       putchar (' ');
1383                     }
1384                   else
1385                     {
1386                       for (k = 0; k < bpc; k++)
1387                         printf ("%02x", (unsigned) data[j + k]);
1388                       putchar (' ');
1389                     }
1390                 }
1391
1392               for (; pb < octets_per_line; pb += bpc)
1393                 {
1394                   int k;
1395
1396                   for (k = 0; k < bpc; k++)
1397                     printf ("  ");
1398                   putchar (' ');
1399                 }
1400
1401               /* Separate raw data from instruction by extra space.  */
1402               if (insns)
1403                 putchar ('\t');
1404               else
1405                 printf ("    ");
1406             }
1407
1408           if (! insns)
1409             printf ("%s", buf);
1410           else
1411             {
1412               printf ("%s", sfile.buffer);
1413               free (sfile.buffer);
1414             }
1415
1416           if (prefix_addresses
1417               ? show_raw_insn > 0
1418               : show_raw_insn >= 0)
1419             {
1420               while (pb < octets)
1421                 {
1422                   bfd_vma j;
1423                   char *s;
1424
1425                   putchar ('\n');
1426                   j = addr_offset * opb + pb;
1427
1428                   bfd_sprintf_vma (aux->abfd, buf, section->vma + j / opb);
1429                   for (s = buf + skip_addr_chars; *s == '0'; s++)
1430                     *s = ' ';
1431                   if (*s == '\0')
1432                     *--s = '0';
1433                   printf ("%s:\t", buf + skip_addr_chars);
1434
1435                   pb += octets_per_line;
1436                   if (pb > octets)
1437                     pb = octets;
1438                   for (; j < addr_offset * opb + pb; j += bpc)
1439                     {
1440                       int k;
1441
1442                       if (bpc > 1 && info->display_endian == BFD_ENDIAN_LITTLE)
1443                         {
1444                           for (k = bpc - 1; k >= 0; k--)
1445                             printf ("%02x", (unsigned) data[j + k]);
1446                           putchar (' ');
1447                         }
1448                       else
1449                         {
1450                           for (k = 0; k < bpc; k++)
1451                             printf ("%02x", (unsigned) data[j + k]);
1452                           putchar (' ');
1453                         }
1454                     }
1455                 }
1456             }
1457
1458           if (!wide_output)
1459             putchar ('\n');
1460           else
1461             need_nl = TRUE;
1462         }
1463
1464       if ((section->flags & SEC_RELOC) != 0
1465 #ifndef DISASSEMBLER_NEEDS_RELOCS
1466           && dump_reloc_info
1467 #endif
1468           )
1469         {
1470           while ((*relppp) < relppend
1471                  && ((**relppp)->address >= (bfd_vma) addr_offset
1472                      && (**relppp)->address < (bfd_vma) addr_offset + octets / opb))
1473 #ifdef DISASSEMBLER_NEEDS_RELOCS
1474             if (! dump_reloc_info)
1475               ++(*relppp);
1476             else
1477 #endif
1478             {
1479               arelent *q;
1480
1481               q = **relppp;
1482
1483               if (wide_output)
1484                 putchar ('\t');
1485               else
1486                 printf ("\t\t\t");
1487
1488               objdump_print_value (section->vma + q->address, info, TRUE);
1489
1490               printf (": %s\t", q->howto->name);
1491
1492               if (q->sym_ptr_ptr == NULL || *q->sym_ptr_ptr == NULL)
1493                 printf ("*unknown*");
1494               else
1495                 {
1496                   const char *sym_name;
1497
1498                   sym_name = bfd_asymbol_name (*q->sym_ptr_ptr);
1499                   if (sym_name != NULL && *sym_name != '\0')
1500                     objdump_print_symname (aux->abfd, info, *q->sym_ptr_ptr);
1501                   else
1502                     {
1503                       asection *sym_sec;
1504
1505                       sym_sec = bfd_get_section (*q->sym_ptr_ptr);
1506                       sym_name = bfd_get_section_name (aux->abfd, sym_sec);
1507                       if (sym_name == NULL || *sym_name == '\0')
1508                         sym_name = "*unknown*";
1509                       printf ("%s", sym_name);
1510                     }
1511                 }
1512
1513               if (q->addend)
1514                 {
1515                   printf ("+0x");
1516                   objdump_print_value (q->addend, info, TRUE);
1517                 }
1518
1519               printf ("\n");
1520               need_nl = FALSE;
1521               ++(*relppp);
1522             }
1523         }
1524
1525       if (need_nl)
1526         printf ("\n");
1527
1528       addr_offset += octets / opb;
1529     }
1530 }
1531
1532 /* Disassemble the contents of an object file.  */
1533
1534 static void
1535 disassemble_data (abfd)
1536      bfd *abfd;
1537 {
1538   unsigned long addr_offset;
1539   disassembler_ftype disassemble_fn;
1540   struct disassemble_info disasm_info;
1541   struct objdump_disasm_info aux;
1542   asection *section;
1543   unsigned int opb;
1544
1545   print_files = NULL;
1546   prev_functionname = NULL;
1547   prev_line = -1;
1548
1549   /* We make a copy of syms to sort.  We don't want to sort syms
1550      because that will screw up the relocs.  */
1551   sorted_syms = (asymbol **) xmalloc (symcount * sizeof (asymbol *));
1552   memcpy (sorted_syms, syms, symcount * sizeof (asymbol *));
1553
1554   sorted_symcount = remove_useless_symbols (sorted_syms, symcount);
1555
1556   /* Sort the symbols into section and symbol order.  */
1557   qsort (sorted_syms, sorted_symcount, sizeof (asymbol *), compare_symbols);
1558
1559   INIT_DISASSEMBLE_INFO (disasm_info, stdout, fprintf);
1560
1561   disasm_info.application_data = (PTR) &aux;
1562   aux.abfd = abfd;
1563   aux.require_sec = FALSE;
1564   disasm_info.print_address_func = objdump_print_address;
1565   disasm_info.symbol_at_address_func = objdump_symbol_at_address;
1566
1567   if (machine != (char *) NULL)
1568     {
1569       const bfd_arch_info_type *info = bfd_scan_arch (machine);
1570
1571       if (info == NULL)
1572         fatal (_("Can't use supplied machine %s"), machine);
1573
1574       abfd->arch_info = info;
1575     }
1576
1577   if (endian != BFD_ENDIAN_UNKNOWN)
1578     {
1579       struct bfd_target *xvec;
1580
1581       xvec = (struct bfd_target *) xmalloc (sizeof (struct bfd_target));
1582       memcpy (xvec, abfd->xvec, sizeof (struct bfd_target));
1583       xvec->byteorder = endian;
1584       abfd->xvec = xvec;
1585     }
1586
1587   disassemble_fn = disassembler (abfd);
1588   if (!disassemble_fn)
1589     {
1590       non_fatal (_("Can't disassemble for architecture %s\n"),
1591                  bfd_printable_arch_mach (bfd_get_arch (abfd), 0));
1592       exit_status = 1;
1593       return;
1594     }
1595
1596   opb = bfd_octets_per_byte (abfd);
1597
1598   disasm_info.flavour = bfd_get_flavour (abfd);
1599   disasm_info.arch = bfd_get_arch (abfd);
1600   disasm_info.mach = bfd_get_mach (abfd);
1601   disasm_info.disassembler_options = disassembler_options;
1602   disasm_info.octets_per_byte = opb;
1603
1604   if (bfd_big_endian (abfd))
1605     disasm_info.display_endian = disasm_info.endian = BFD_ENDIAN_BIG;
1606   else if (bfd_little_endian (abfd))
1607     disasm_info.display_endian = disasm_info.endian = BFD_ENDIAN_LITTLE;
1608   else
1609     /* ??? Aborting here seems too drastic.  We could default to big or little
1610        instead.  */
1611     disasm_info.endian = BFD_ENDIAN_UNKNOWN;
1612
1613   for (section = abfd->sections;
1614        section != (asection *) NULL;
1615        section = section->next)
1616     {
1617       bfd_byte *data = NULL;
1618       bfd_size_type datasize = 0;
1619       arelent **relbuf = NULL;
1620       arelent **relpp = NULL;
1621       arelent **relppend = NULL;
1622       unsigned long stop_offset;
1623       asymbol *sym = NULL;
1624       long place = 0;
1625
1626       if ((section->flags & SEC_LOAD) == 0
1627           || (! disassemble_all
1628               && only == NULL
1629               && (section->flags & SEC_CODE) == 0))
1630         continue;
1631       if (only != (char *) NULL && strcmp (only, section->name) != 0)
1632         continue;
1633
1634       if ((section->flags & SEC_RELOC) != 0
1635 #ifndef DISASSEMBLER_NEEDS_RELOCS
1636           && dump_reloc_info
1637 #endif
1638           )
1639         {
1640           long relsize;
1641
1642           relsize = bfd_get_reloc_upper_bound (abfd, section);
1643           if (relsize < 0)
1644             bfd_fatal (bfd_get_filename (abfd));
1645
1646           if (relsize > 0)
1647             {
1648               long relcount;
1649
1650               relbuf = (arelent **) xmalloc (relsize);
1651               relcount = bfd_canonicalize_reloc (abfd, section, relbuf, syms);
1652               if (relcount < 0)
1653                 bfd_fatal (bfd_get_filename (abfd));
1654
1655               /* Sort the relocs by address.  */
1656               qsort (relbuf, relcount, sizeof (arelent *), compare_relocs);
1657
1658               relpp = relbuf;
1659               relppend = relpp + relcount;
1660
1661               /* Skip over the relocs belonging to addresses below the
1662                  start address.  */
1663               if (start_address != (bfd_vma) -1)
1664                 while (relpp < relppend
1665                        && (*relpp)->address < start_address)
1666                   ++relpp;
1667             }
1668         }
1669
1670       printf (_("Disassembly of section %s:\n"), section->name);
1671
1672       datasize = bfd_get_section_size_before_reloc (section);
1673       if (datasize == 0)
1674         continue;
1675
1676       data = (bfd_byte *) xmalloc ((size_t) datasize);
1677
1678       bfd_get_section_contents (abfd, section, data, 0, datasize);
1679
1680       aux.sec = section;
1681       disasm_info.buffer = data;
1682       disasm_info.buffer_vma = section->vma;
1683       disasm_info.buffer_length = datasize;
1684       disasm_info.section = section;
1685
1686       if (start_address == (bfd_vma) -1
1687           || start_address < disasm_info.buffer_vma)
1688         addr_offset = 0;
1689       else
1690         addr_offset = start_address - disasm_info.buffer_vma;
1691
1692       if (stop_address == (bfd_vma) -1)
1693         stop_offset = datasize / opb;
1694       else
1695         {
1696           if (stop_address < disasm_info.buffer_vma)
1697             stop_offset = 0;
1698           else
1699             stop_offset = stop_address - disasm_info.buffer_vma;
1700           if (stop_offset > disasm_info.buffer_length / opb)
1701             stop_offset = disasm_info.buffer_length / opb;
1702         }
1703
1704       sym = find_symbol_for_address (abfd, section, section->vma + addr_offset,
1705                                      TRUE, &place);
1706
1707       while (addr_offset < stop_offset)
1708         {
1709           asymbol *nextsym;
1710           unsigned long nextstop_offset;
1711           bfd_boolean insns;
1712
1713           if (sym != NULL && bfd_asymbol_value (sym) <= section->vma + addr_offset)
1714             {
1715               int x;
1716
1717               for (x = place;
1718                    (x < sorted_symcount
1719                     && bfd_asymbol_value (sorted_syms[x]) <= section->vma + addr_offset);
1720                    ++x)
1721                 continue;
1722
1723               disasm_info.symbols = & sorted_syms[place];
1724               disasm_info.num_symbols = x - place;
1725             }
1726           else
1727             disasm_info.symbols = NULL;
1728
1729           if (! prefix_addresses)
1730             {
1731               (* disasm_info.fprintf_func) (disasm_info.stream, "\n");
1732               objdump_print_addr_with_sym (abfd, section, sym,
1733                                            section->vma + addr_offset,
1734                                            &disasm_info,
1735                                            FALSE);
1736               (* disasm_info.fprintf_func) (disasm_info.stream, ":\n");
1737             }
1738
1739           if (sym != NULL && bfd_asymbol_value (sym) > section->vma + addr_offset)
1740             nextsym = sym;
1741           else if (sym == NULL)
1742             nextsym = NULL;
1743           else
1744             {
1745               /* Search forward for the next appropriate symbol in
1746                  SECTION.  Note that all the symbols are sorted
1747                  together into one big array, and that some sections
1748                  may have overlapping addresses.  */
1749               while (place < sorted_symcount
1750                      && (sorted_syms[place]->section != section
1751                          || (bfd_asymbol_value (sorted_syms[place])
1752                              <= bfd_asymbol_value (sym))))
1753                 ++place;
1754               if (place >= sorted_symcount)
1755                 nextsym = NULL;
1756               else
1757                 nextsym = sorted_syms[place];
1758             }
1759
1760           if (sym != NULL && bfd_asymbol_value (sym) > section->vma + addr_offset)
1761             {
1762               nextstop_offset = bfd_asymbol_value (sym) - section->vma;
1763               if (nextstop_offset > stop_offset)
1764                 nextstop_offset = stop_offset;
1765             }
1766           else if (nextsym == NULL)
1767             nextstop_offset = stop_offset;
1768           else
1769             {
1770               nextstop_offset = bfd_asymbol_value (nextsym) - section->vma;
1771               if (nextstop_offset > stop_offset)
1772                 nextstop_offset = stop_offset;
1773             }
1774
1775           /* If a symbol is explicitly marked as being an object
1776              rather than a function, just dump the bytes without
1777              disassembling them.  */
1778           if (disassemble_all
1779               || sym == NULL
1780               || bfd_asymbol_value (sym) > section->vma + addr_offset
1781               || ((sym->flags & BSF_OBJECT) == 0
1782                   && (strstr (bfd_asymbol_name (sym), "gnu_compiled")
1783                       == NULL)
1784                   && (strstr (bfd_asymbol_name (sym), "gcc2_compiled")
1785                       == NULL))
1786               || (sym->flags & BSF_FUNCTION) != 0)
1787             insns = TRUE;
1788           else
1789             insns = FALSE;
1790
1791           disassemble_bytes (&disasm_info, disassemble_fn, insns, data,
1792                              addr_offset, nextstop_offset, &relpp, relppend);
1793
1794           addr_offset = nextstop_offset;
1795           sym = nextsym;
1796         }
1797
1798       free (data);
1799
1800       if (relbuf != NULL)
1801         free (relbuf);
1802     }
1803   free (sorted_syms);
1804 }
1805 \f
1806 /* Dump the stabs sections from an object file that has a section that
1807    uses Sun stabs encoding.  */
1808
1809 static void
1810 dump_stabs (abfd)
1811      bfd *abfd;
1812 {
1813   dump_section_stabs (abfd, ".stab", ".stabstr");
1814   dump_section_stabs (abfd, ".stab.excl", ".stab.exclstr");
1815   dump_section_stabs (abfd, ".stab.index", ".stab.indexstr");
1816   dump_section_stabs (abfd, "$GDB_SYMBOLS$", "$GDB_STRINGS$");
1817 }
1818
1819 /* Read ABFD's stabs section STABSECT_NAME into `stabs'
1820    and string table section STRSECT_NAME into `strtab'.
1821    If the section exists and was read, allocate the space and return TRUE.
1822    Otherwise return FALSE.  */
1823
1824 static bfd_boolean
1825 read_section_stabs (abfd, stabsect_name, strsect_name)
1826      bfd *abfd;
1827      const char *stabsect_name;
1828      const char *strsect_name;
1829 {
1830   asection *stabsect, *stabstrsect;
1831
1832   stabsect = bfd_get_section_by_name (abfd, stabsect_name);
1833   if (0 == stabsect)
1834     {
1835       printf (_("No %s section present\n\n"), stabsect_name);
1836       return FALSE;
1837     }
1838
1839   stabstrsect = bfd_get_section_by_name (abfd, strsect_name);
1840   if (0 == stabstrsect)
1841     {
1842       non_fatal (_("%s has no %s section"),
1843                  bfd_get_filename (abfd), strsect_name);
1844       exit_status = 1;
1845       return FALSE;
1846     }
1847
1848   stab_size    = bfd_section_size (abfd, stabsect);
1849   stabstr_size = bfd_section_size (abfd, stabstrsect);
1850
1851   stabs  = (bfd_byte *) xmalloc (stab_size);
1852   strtab = (char *) xmalloc (stabstr_size);
1853
1854   if (! bfd_get_section_contents (abfd, stabsect, (PTR) stabs, 0, stab_size))
1855     {
1856       non_fatal (_("Reading %s section of %s failed: %s"),
1857                  stabsect_name, bfd_get_filename (abfd),
1858                  bfd_errmsg (bfd_get_error ()));
1859       free (stabs);
1860       free (strtab);
1861       exit_status = 1;
1862       return FALSE;
1863     }
1864
1865   if (! bfd_get_section_contents (abfd, stabstrsect, (PTR) strtab, 0,
1866                                   stabstr_size))
1867     {
1868       non_fatal (_("Reading %s section of %s failed: %s\n"),
1869                  strsect_name, bfd_get_filename (abfd),
1870                  bfd_errmsg (bfd_get_error ()));
1871       free (stabs);
1872       free (strtab);
1873       exit_status = 1;
1874       return FALSE;
1875     }
1876
1877   return TRUE;
1878 }
1879
1880 /* Stabs entries use a 12 byte format:
1881      4 byte string table index
1882      1 byte stab type
1883      1 byte stab other field
1884      2 byte stab desc field
1885      4 byte stab value
1886    FIXME: This will have to change for a 64 bit object format.  */
1887
1888 #define STRDXOFF (0)
1889 #define TYPEOFF (4)
1890 #define OTHEROFF (5)
1891 #define DESCOFF (6)
1892 #define VALOFF (8)
1893 #define STABSIZE (12)
1894
1895 /* Print ABFD's stabs section STABSECT_NAME (in `stabs'),
1896    using string table section STRSECT_NAME (in `strtab').  */
1897
1898 static void
1899 print_section_stabs (abfd, stabsect_name, strsect_name)
1900      bfd *abfd;
1901      const char *stabsect_name;
1902      const char *strsect_name ATTRIBUTE_UNUSED;
1903 {
1904   int i;
1905   unsigned file_string_table_offset = 0, next_file_string_table_offset = 0;
1906   bfd_byte *stabp, *stabs_end;
1907
1908   stabp = stabs;
1909   stabs_end = stabp + stab_size;
1910
1911   printf (_("Contents of %s section:\n\n"), stabsect_name);
1912   printf ("Symnum n_type n_othr n_desc n_value  n_strx String\n");
1913
1914   /* Loop through all symbols and print them.
1915
1916      We start the index at -1 because there is a dummy symbol on
1917      the front of stabs-in-{coff,elf} sections that supplies sizes.  */
1918   for (i = -1; stabp < stabs_end; stabp += STABSIZE, i++)
1919     {
1920       const char *name;
1921       unsigned long strx;
1922       unsigned char type, other;
1923       unsigned short desc;
1924       bfd_vma value;
1925
1926       strx = bfd_h_get_32 (abfd, stabp + STRDXOFF);
1927       type = bfd_h_get_8 (abfd, stabp + TYPEOFF);
1928       other = bfd_h_get_8 (abfd, stabp + OTHEROFF);
1929       desc = bfd_h_get_16 (abfd, stabp + DESCOFF);
1930       value = bfd_h_get_32 (abfd, stabp + VALOFF);
1931
1932       printf ("\n%-6d ", i);
1933       /* Either print the stab name, or, if unnamed, print its number
1934          again (makes consistent formatting for tools like awk).  */
1935       name = bfd_get_stab_name (type);
1936       if (name != NULL)
1937         printf ("%-6s", name);
1938       else if (type == N_UNDF)
1939         printf ("HdrSym");
1940       else
1941         printf ("%-6d", type);
1942       printf (" %-6d %-6d ", other, desc);
1943       bfd_printf_vma (abfd, value);
1944       printf (" %-6lu", strx);
1945
1946       /* Symbols with type == 0 (N_UNDF) specify the length of the
1947          string table associated with this file.  We use that info
1948          to know how to relocate the *next* file's string table indices.  */
1949       if (type == N_UNDF)
1950         {
1951           file_string_table_offset = next_file_string_table_offset;
1952           next_file_string_table_offset += value;
1953         }
1954       else
1955         {
1956           /* Using the (possibly updated) string table offset, print the
1957              string (if any) associated with this symbol.  */
1958           if ((strx + file_string_table_offset) < stabstr_size)
1959             printf (" %s", &strtab[strx + file_string_table_offset]);
1960           else
1961             printf (" *");
1962         }
1963     }
1964   printf ("\n\n");
1965 }
1966
1967 static void
1968 dump_section_stabs (abfd, stabsect_name, strsect_name)
1969      bfd *abfd;
1970      char *stabsect_name;
1971      char *strsect_name;
1972 {
1973   asection *s;
1974
1975   /* Check for section names for which stabsect_name is a prefix, to
1976      handle .stab0, etc.  */
1977   for (s = abfd->sections;
1978        s != NULL;
1979        s = s->next)
1980     {
1981       int len;
1982
1983       len = strlen (stabsect_name);
1984
1985       /* If the prefix matches, and the files section name ends with a
1986          nul or a digit, then we match.  I.e., we want either an exact
1987          match or a section followed by a number.  */
1988       if (strncmp (stabsect_name, s->name, len) == 0
1989           && (s->name[len] == '\000'
1990               || ISDIGIT (s->name[len])))
1991         {
1992           if (read_section_stabs (abfd, s->name, strsect_name))
1993             {
1994               print_section_stabs (abfd, s->name, strsect_name);
1995               free (stabs);
1996               free (strtab);
1997             }
1998         }
1999     }
2000 }
2001
2002 \f
2003 static void
2004 dump_bfd_header (abfd)
2005      bfd *abfd;
2006 {
2007   char *comma = "";
2008
2009   printf (_("architecture: %s, "),
2010           bfd_printable_arch_mach (bfd_get_arch (abfd),
2011                                    bfd_get_mach (abfd)));
2012   printf (_("flags 0x%08x:\n"), abfd->flags);
2013
2014 #define PF(x, y)    if (abfd->flags & x) {printf("%s%s", comma, y); comma=", ";}
2015   PF (HAS_RELOC, "HAS_RELOC");
2016   PF (EXEC_P, "EXEC_P");
2017   PF (HAS_LINENO, "HAS_LINENO");
2018   PF (HAS_DEBUG, "HAS_DEBUG");
2019   PF (HAS_SYMS, "HAS_SYMS");
2020   PF (HAS_LOCALS, "HAS_LOCALS");
2021   PF (DYNAMIC, "DYNAMIC");
2022   PF (WP_TEXT, "WP_TEXT");
2023   PF (D_PAGED, "D_PAGED");
2024   PF (BFD_IS_RELAXABLE, "BFD_IS_RELAXABLE");
2025   PF (HAS_LOAD_PAGE, "HAS_LOAD_PAGE");
2026   printf (_("\nstart address 0x"));
2027   bfd_printf_vma (abfd, abfd->start_address);
2028   printf ("\n");
2029 }
2030
2031 \f
2032 static void
2033 dump_bfd_private_header (abfd)
2034 bfd *abfd;
2035 {
2036   bfd_print_private_bfd_data (abfd, stdout);
2037 }
2038
2039 /* Dump selected contents of ABFD.  */
2040
2041 static void
2042 dump_bfd (abfd)
2043      bfd *abfd;
2044 {
2045   /* If we are adjusting section VMA's, change them all now.  Changing
2046      the BFD information is a hack.  However, we must do it, or
2047      bfd_find_nearest_line will not do the right thing.  */
2048   if (adjust_section_vma != 0)
2049     {
2050       asection *s;
2051
2052       for (s = abfd->sections; s != NULL; s = s->next)
2053         {
2054           s->vma += adjust_section_vma;
2055           s->lma += adjust_section_vma;
2056         }
2057     }
2058
2059   printf (_("\n%s:     file format %s\n"), bfd_get_filename (abfd),
2060           abfd->xvec->name);
2061   if (dump_ar_hdrs)
2062     print_arelt_descr (stdout, abfd, TRUE);
2063   if (dump_file_header)
2064     dump_bfd_header (abfd);
2065   if (dump_private_headers)
2066     dump_bfd_private_header (abfd);
2067   putchar ('\n');
2068   if (dump_section_headers)
2069     dump_headers (abfd);
2070
2071   if (dump_symtab || dump_reloc_info || disassemble || dump_debugging)
2072     syms = slurp_symtab (abfd);
2073   if (dump_dynamic_symtab || dump_dynamic_reloc_info)
2074     dynsyms = slurp_dynamic_symtab (abfd);
2075
2076   if (dump_symtab)
2077     dump_symbols (abfd, FALSE);
2078   if (dump_dynamic_symtab)
2079     dump_symbols (abfd, TRUE);
2080   if (dump_stab_section_info)
2081     dump_stabs (abfd);
2082   if (dump_reloc_info && ! disassemble)
2083     dump_relocs (abfd);
2084   if (dump_dynamic_reloc_info)
2085     dump_dynamic_relocs (abfd);
2086   if (dump_section_contents)
2087     dump_data (abfd);
2088   if (disassemble)
2089     disassemble_data (abfd);
2090   if (dump_debugging)
2091     {
2092       PTR dhandle;
2093
2094       dhandle = read_debugging_info (abfd, syms, symcount);
2095       if (dhandle != NULL)
2096         {
2097           if (! print_debugging_info (stdout, dhandle))
2098             {
2099               non_fatal (_("%s: printing debugging information failed"),
2100                          bfd_get_filename (abfd));
2101               exit_status = 1;
2102             }
2103         }
2104     }
2105
2106   if (syms)
2107     {
2108       free (syms);
2109       syms = NULL;
2110     }
2111
2112   if (dynsyms)
2113     {
2114       free (dynsyms);
2115       dynsyms = NULL;
2116     }
2117 }
2118
2119 static void
2120 display_bfd (abfd)
2121      bfd *abfd;
2122 {
2123   char **matching;
2124
2125   if (bfd_check_format_matches (abfd, bfd_object, &matching))
2126     {
2127       dump_bfd (abfd);
2128       return;
2129     }
2130
2131   if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
2132     {
2133       nonfatal (bfd_get_filename (abfd));
2134       list_matching_formats (matching);
2135       free (matching);
2136       return;
2137     }
2138
2139   if (bfd_get_error () != bfd_error_file_not_recognized)
2140     {
2141       nonfatal (bfd_get_filename (abfd));
2142       return;
2143     }
2144
2145   if (bfd_check_format_matches (abfd, bfd_core, &matching))
2146     {
2147       dump_bfd (abfd);
2148       return;
2149     }
2150
2151   nonfatal (bfd_get_filename (abfd));
2152
2153   if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
2154     {
2155       list_matching_formats (matching);
2156       free (matching);
2157     }
2158 }
2159
2160 static void
2161 display_file (filename, target)
2162      char *filename;
2163      char *target;
2164 {
2165   bfd *file, *arfile = (bfd *) NULL;
2166
2167   file = bfd_openr (filename, target);
2168   if (file == NULL)
2169     {
2170       nonfatal (filename);
2171       return;
2172     }
2173
2174   if (bfd_check_format (file, bfd_archive))
2175     {
2176       bfd *last_arfile = NULL;
2177
2178       printf (_("In archive %s:\n"), bfd_get_filename (file));
2179       for (;;)
2180         {
2181           bfd_set_error (bfd_error_no_error);
2182
2183           arfile = bfd_openr_next_archived_file (file, arfile);
2184           if (arfile == NULL)
2185             {
2186               if (bfd_get_error () != bfd_error_no_more_archived_files)
2187                 nonfatal (bfd_get_filename (file));
2188               break;
2189             }
2190
2191           display_bfd (arfile);
2192
2193           if (last_arfile != NULL)
2194             bfd_close (last_arfile);
2195           last_arfile = arfile;
2196         }
2197
2198       if (last_arfile != NULL)
2199         bfd_close (last_arfile);
2200     }
2201   else
2202     display_bfd (file);
2203
2204   bfd_close (file);
2205 }
2206 \f
2207 /* Actually display the various requested regions.  */
2208
2209 static void
2210 dump_data (abfd)
2211      bfd *abfd;
2212 {
2213   asection *section;
2214   bfd_byte *data = 0;
2215   bfd_size_type datasize = 0;
2216   bfd_size_type addr_offset;
2217   bfd_size_type start_offset, stop_offset;
2218   unsigned int opb = bfd_octets_per_byte (abfd);
2219
2220   for (section = abfd->sections; section != NULL; section =
2221        section->next)
2222     {
2223       int onaline = 16;
2224
2225       if (only == (char *) NULL ||
2226           strcmp (only, section->name) == 0)
2227         {
2228           if (section->flags & SEC_HAS_CONTENTS)
2229             {
2230               char buf[64];
2231               int count, width;
2232               
2233               printf (_("Contents of section %s:\n"), section->name);
2234
2235               if (bfd_section_size (abfd, section) == 0)
2236                 continue;
2237               data = (bfd_byte *) xmalloc ((size_t) bfd_section_size (abfd, section));
2238               datasize = bfd_section_size (abfd, section);
2239
2240
2241               bfd_get_section_contents (abfd, section, (PTR) data, 0, bfd_section_size (abfd, section));
2242
2243               if (start_address == (bfd_vma) -1
2244                   || start_address < section->vma)
2245                 start_offset = 0;
2246               else
2247                 start_offset = start_address - section->vma;
2248               if (stop_address == (bfd_vma) -1)
2249                 stop_offset = bfd_section_size (abfd, section) / opb;
2250               else
2251                 {
2252                   if (stop_address < section->vma)
2253                     stop_offset = 0;
2254                   else
2255                     stop_offset = stop_address - section->vma;
2256                   if (stop_offset > bfd_section_size (abfd, section) / opb)
2257                     stop_offset = bfd_section_size (abfd, section) / opb;
2258                 }
2259
2260               width = 4;
2261
2262               bfd_sprintf_vma (abfd, buf, start_offset + section->vma);
2263               if (strlen (buf) >= sizeof (buf))
2264                 abort ();
2265               count = 0;
2266               while (buf[count] == '0' && buf[count+1] != '\0')
2267                 count++;
2268               count = strlen (buf) - count;
2269               if (count > width)
2270                 width = count;
2271
2272               bfd_sprintf_vma (abfd, buf, stop_offset + section->vma - 1);
2273               if (strlen (buf) >= sizeof (buf))
2274                 abort ();
2275               count = 0;
2276               while (buf[count] == '0' && buf[count+1] != '\0')
2277                 count++;
2278               count = strlen (buf) - count;
2279               if (count > width)
2280                 width = count;
2281
2282               for (addr_offset = start_offset;
2283                    addr_offset < stop_offset; addr_offset += onaline / opb)
2284                 {
2285                   bfd_size_type j;
2286
2287                   bfd_sprintf_vma (abfd, buf, (addr_offset + section->vma));
2288                   count = strlen (buf);
2289                   if (count >= sizeof (buf))
2290                     abort ();
2291                   putchar (' ');
2292                   while (count < width)
2293                     {
2294                       putchar ('0');
2295                       count++;
2296                     }
2297                   fputs (buf + count - width, stdout);
2298                   putchar (' ');
2299
2300                   for (j = addr_offset * opb;
2301                        j < addr_offset * opb + onaline; j++)
2302                     {
2303                       if (j < stop_offset * opb)
2304                         printf ("%02x", (unsigned) (data[j]));
2305                       else
2306                         printf ("  ");
2307                       if ((j & 3) == 3)
2308                         printf (" ");
2309                     }
2310
2311                   printf (" ");
2312                   for (j = addr_offset * opb;
2313                        j < addr_offset * opb + onaline; j++)
2314                     {
2315                       if (j >= stop_offset * opb)
2316                         printf (" ");
2317                       else
2318                         printf ("%c", ISPRINT (data[j]) ? data[j] : '.');
2319                     }
2320                   putchar ('\n');
2321                 }
2322               free (data);
2323             }
2324         }
2325     }
2326 }
2327
2328 /* Should perhaps share code and display with nm?  */
2329
2330 static void
2331 dump_symbols (abfd, dynamic)
2332      bfd *abfd ATTRIBUTE_UNUSED;
2333      bfd_boolean dynamic;
2334 {
2335   asymbol **current;
2336   long max;
2337   long count;
2338
2339   if (dynamic)
2340     {
2341       current = dynsyms;
2342       max = dynsymcount;
2343       printf ("DYNAMIC SYMBOL TABLE:\n");
2344     }
2345   else
2346     {
2347       current = syms;
2348       max = symcount;
2349       printf ("SYMBOL TABLE:\n");
2350     }
2351
2352   if (max == 0)
2353     printf (_("no symbols\n"));
2354
2355   for (count = 0; count < max; count++)
2356     {
2357       if (*current)
2358         {
2359           bfd *cur_bfd = bfd_asymbol_bfd (*current);
2360
2361           if (cur_bfd != NULL)
2362             {
2363               const char *name;
2364               char *alloc;
2365
2366               name = (*current)->name;
2367               alloc = NULL;
2368               if (do_demangle && name != NULL && *name != '\0')
2369                 {
2370                   /* If we want to demangle the name, we demangle it
2371                      here, and temporarily clobber it while calling
2372                      bfd_print_symbol.  FIXME: This is a gross hack.  */
2373                   alloc = demangle (cur_bfd, name);
2374                   (*current)->name = alloc;
2375                 }
2376
2377               bfd_print_symbol (cur_bfd, stdout, *current,
2378                                 bfd_print_symbol_all);
2379
2380               (*current)->name = name;
2381               if (alloc != NULL)
2382                 free (alloc);
2383
2384               printf ("\n");
2385             }
2386         }
2387       current++;
2388     }
2389   printf ("\n");
2390   printf ("\n");
2391 }
2392
2393 static void
2394 dump_relocs (abfd)
2395      bfd *abfd;
2396 {
2397   arelent **relpp;
2398   long relcount;
2399   asection *a;
2400
2401   for (a = abfd->sections; a != (asection *) NULL; a = a->next)
2402     {
2403       long relsize;
2404
2405       if (bfd_is_abs_section (a))
2406         continue;
2407       if (bfd_is_und_section (a))
2408         continue;
2409       if (bfd_is_com_section (a))
2410         continue;
2411
2412       if (only)
2413         {
2414           if (strcmp (only, a->name))
2415             continue;
2416         }
2417       else if ((a->flags & SEC_RELOC) == 0)
2418         continue;
2419
2420       relsize = bfd_get_reloc_upper_bound (abfd, a);
2421       if (relsize < 0)
2422         bfd_fatal (bfd_get_filename (abfd));
2423
2424       printf ("RELOCATION RECORDS FOR [%s]:", a->name);
2425
2426       if (relsize == 0)
2427         {
2428           printf (" (none)\n\n");
2429         }
2430       else
2431         {
2432           relpp = (arelent **) xmalloc (relsize);
2433           relcount = bfd_canonicalize_reloc (abfd, a, relpp, syms);
2434
2435           if (relcount < 0)
2436             bfd_fatal (bfd_get_filename (abfd));
2437           else if (relcount == 0)
2438             printf (" (none)\n\n");
2439           else
2440             {
2441               printf ("\n");
2442               dump_reloc_set (abfd, a, relpp, relcount);
2443               printf ("\n\n");
2444             }
2445           free (relpp);
2446         }
2447     }
2448 }
2449
2450 static void
2451 dump_dynamic_relocs (abfd)
2452      bfd *abfd;
2453 {
2454   long relsize;
2455   arelent **relpp;
2456   long relcount;
2457
2458   relsize = bfd_get_dynamic_reloc_upper_bound (abfd);
2459   if (relsize < 0)
2460     bfd_fatal (bfd_get_filename (abfd));
2461
2462   printf ("DYNAMIC RELOCATION RECORDS");
2463
2464   if (relsize == 0)
2465     printf (" (none)\n\n");
2466   else
2467     {
2468       relpp = (arelent **) xmalloc (relsize);
2469       relcount = bfd_canonicalize_dynamic_reloc (abfd, relpp, dynsyms);
2470
2471       if (relcount < 0)
2472         bfd_fatal (bfd_get_filename (abfd));
2473       else if (relcount == 0)
2474         printf (" (none)\n\n");
2475       else
2476         {
2477           printf ("\n");
2478           dump_reloc_set (abfd, (asection *) NULL, relpp, relcount);
2479           printf ("\n\n");
2480         }
2481       free (relpp);
2482     }
2483 }
2484
2485 static void
2486 dump_reloc_set (abfd, sec, relpp, relcount)
2487      bfd *abfd;
2488      asection *sec;
2489      arelent **relpp;
2490      long relcount;
2491 {
2492   arelent **p;
2493   char *last_filename, *last_functionname;
2494   unsigned int last_line;
2495
2496   /* Get column headers lined up reasonably.  */
2497   {
2498     static int width;
2499
2500     if (width == 0)
2501       {
2502         char buf[30];
2503         bfd_sprintf_vma (abfd, buf, (bfd_vma) -1);
2504         width = strlen (buf) - 7;
2505       }
2506     printf ("OFFSET %*s TYPE %*s VALUE \n", width, "", 12, "");
2507   }
2508
2509   last_filename = NULL;
2510   last_functionname = NULL;
2511   last_line = 0;
2512
2513   for (p = relpp; relcount && *p != (arelent *) NULL; p++, relcount--)
2514     {
2515       arelent *q = *p;
2516       const char *filename, *functionname;
2517       unsigned int line;
2518       const char *sym_name;
2519       const char *section_name;
2520
2521       if (start_address != (bfd_vma) -1
2522           && q->address < start_address)
2523         continue;
2524       if (stop_address != (bfd_vma) -1
2525           && q->address > stop_address)
2526         continue;
2527
2528       if (with_line_numbers
2529           && sec != NULL
2530           && bfd_find_nearest_line (abfd, sec, syms, q->address,
2531                                     &filename, &functionname, &line))
2532         {
2533           if (functionname != NULL
2534               && (last_functionname == NULL
2535                   || strcmp (functionname, last_functionname) != 0))
2536             {
2537               printf ("%s():\n", functionname);
2538               if (last_functionname != NULL)
2539                 free (last_functionname);
2540               last_functionname = xstrdup (functionname);
2541             }
2542
2543           if (line > 0
2544               && (line != last_line
2545                   || (filename != NULL
2546                       && last_filename != NULL
2547                       && strcmp (filename, last_filename) != 0)))
2548             {
2549               printf ("%s:%u\n", filename == NULL ? "???" : filename, line);
2550               last_line = line;
2551               if (last_filename != NULL)
2552                 free (last_filename);
2553               if (filename == NULL)
2554                 last_filename = NULL;
2555               else
2556                 last_filename = xstrdup (filename);
2557             }
2558         }
2559
2560       if (q->sym_ptr_ptr && *q->sym_ptr_ptr)
2561         {
2562           sym_name = (*(q->sym_ptr_ptr))->name;
2563           section_name = (*(q->sym_ptr_ptr))->section->name;
2564         }
2565       else
2566         {
2567           sym_name = NULL;
2568           section_name = NULL;
2569         }
2570
2571       if (sym_name)
2572         {
2573           bfd_printf_vma (abfd, q->address);
2574           if (q->howto->name)
2575             printf (" %-16s  ", q->howto->name);
2576           else
2577             printf (" %-16d  ", q->howto->type);
2578           objdump_print_symname (abfd, (struct disassemble_info *) NULL,
2579                                  *q->sym_ptr_ptr);
2580         }
2581       else
2582         {
2583           if (section_name == (const char *) NULL)
2584             section_name = "*unknown*";
2585           bfd_printf_vma (abfd, q->address);
2586           printf (" %-16s  [%s]",
2587                   q->howto->name,
2588                   section_name);
2589         }
2590
2591       if (q->addend)
2592         {
2593           printf ("+0x");
2594           bfd_printf_vma (abfd, q->addend);
2595         }
2596
2597       printf ("\n");
2598     }
2599 }
2600 \f
2601 int main PARAMS ((int, char **));
2602
2603 int
2604 main (argc, argv)
2605      int argc;
2606      char **argv;
2607 {
2608   int c;
2609   char *target = default_target;
2610   bfd_boolean seenflag = FALSE;
2611
2612 #if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
2613   setlocale (LC_MESSAGES, "");
2614 #endif
2615 #if defined (HAVE_SETLOCALE)
2616   setlocale (LC_CTYPE, "");
2617 #endif
2618   bindtextdomain (PACKAGE, LOCALEDIR);
2619   textdomain (PACKAGE);
2620
2621   program_name = *argv;
2622   xmalloc_set_program_name (program_name);
2623
2624   START_PROGRESS (program_name, 0);
2625
2626   bfd_init ();
2627   set_default_bfd_target ();
2628
2629   while ((c = getopt_long (argc, argv, "pib:m:M:VvCdDlfaHhrRtTxsSj:wE:zgG",
2630                            long_options, (int *) 0))
2631          != EOF)
2632     {
2633       switch (c)
2634         {
2635         case 0:
2636           break;                /* We've been given a long option.  */
2637         case 'm':
2638           machine = optarg;
2639           break;
2640         case 'M':
2641           disassembler_options = optarg;
2642           break;
2643         case 'j':
2644           only = optarg;
2645           break;
2646         case 'l':
2647           with_line_numbers = TRUE;
2648           break;
2649         case 'b':
2650           target = optarg;
2651           break;
2652         case 'C':
2653           do_demangle = TRUE;
2654           if (optarg != NULL)
2655             {
2656               enum demangling_styles style;
2657
2658               style = cplus_demangle_name_to_style (optarg);
2659               if (style == unknown_demangling)
2660                 fatal (_("unknown demangling style `%s'"),
2661                        optarg);
2662
2663               cplus_demangle_set_style (style);
2664             }
2665           break;
2666         case 'w':
2667           wide_output = TRUE;
2668           break;
2669         case OPTION_ADJUST_VMA:
2670           adjust_section_vma = parse_vma (optarg, "--adjust-vma");
2671           break;
2672         case OPTION_START_ADDRESS:
2673           start_address = parse_vma (optarg, "--start-address");
2674           break;
2675         case OPTION_STOP_ADDRESS:
2676           stop_address = parse_vma (optarg, "--stop-address");
2677           break;
2678         case 'E':
2679           if (strcmp (optarg, "B") == 0)
2680             endian = BFD_ENDIAN_BIG;
2681           else if (strcmp (optarg, "L") == 0)
2682             endian = BFD_ENDIAN_LITTLE;
2683           else
2684             {
2685               non_fatal (_("unrecognized -E option"));
2686               usage (stderr, 1);
2687             }
2688           break;
2689         case OPTION_ENDIAN:
2690           if (strncmp (optarg, "big", strlen (optarg)) == 0)
2691             endian = BFD_ENDIAN_BIG;
2692           else if (strncmp (optarg, "little", strlen (optarg)) == 0)
2693             endian = BFD_ENDIAN_LITTLE;
2694           else
2695             {
2696               non_fatal (_("unrecognized --endian type `%s'"), optarg);
2697               usage (stderr, 1);
2698             }
2699           break;
2700
2701         case 'f':
2702           dump_file_header = TRUE;
2703           seenflag = TRUE;
2704           break;
2705         case 'i':
2706           formats_info = TRUE;
2707           seenflag = TRUE;
2708           break;
2709         case 'p':
2710           dump_private_headers = TRUE;
2711           seenflag = TRUE;
2712           break;
2713         case 'x':
2714           dump_private_headers = TRUE;
2715           dump_symtab = TRUE;
2716           dump_reloc_info = TRUE;
2717           dump_file_header = TRUE;
2718           dump_ar_hdrs = TRUE;
2719           dump_section_headers = TRUE;
2720           seenflag = TRUE;
2721           break;
2722         case 't':
2723           dump_symtab = TRUE;
2724           seenflag = TRUE;
2725           break;
2726         case 'T':
2727           dump_dynamic_symtab = TRUE;
2728           seenflag = TRUE;
2729           break;
2730         case 'd':
2731           disassemble = TRUE;
2732           seenflag = TRUE;
2733           break;
2734         case 'z':
2735           disassemble_zeroes = TRUE;
2736           break;
2737         case 'D':
2738           disassemble = TRUE;
2739           disassemble_all = TRUE;
2740           seenflag = TRUE;
2741           break;
2742         case 'S':
2743           disassemble = TRUE;
2744           with_source_code = TRUE;
2745           seenflag = TRUE;
2746           break;
2747         case 'g':
2748           dump_debugging = 1;
2749           seenflag = TRUE;
2750           break;
2751         case 'G':
2752           dump_stab_section_info = TRUE;
2753           seenflag = TRUE;
2754           break;
2755         case 's':
2756           dump_section_contents = TRUE;
2757           seenflag = TRUE;
2758           break;
2759         case 'r':
2760           dump_reloc_info = TRUE;
2761           seenflag = TRUE;
2762           break;
2763         case 'R':
2764           dump_dynamic_reloc_info = TRUE;
2765           seenflag = TRUE;
2766           break;
2767         case 'a':
2768           dump_ar_hdrs = TRUE;
2769           seenflag = TRUE;
2770           break;
2771         case 'h':
2772           dump_section_headers = TRUE;
2773           seenflag = TRUE;
2774           break;
2775         case 'H':
2776           usage (stdout, 0);
2777           seenflag = TRUE;
2778         case 'v':
2779         case 'V':
2780           show_version = TRUE;
2781           seenflag = TRUE;
2782           break;
2783
2784         default:
2785           usage (stderr, 1);
2786         }
2787     }
2788
2789   if (show_version)
2790     print_version ("objdump");
2791
2792   if (!seenflag)
2793     usage (stderr, 2);
2794
2795   if (formats_info)
2796     exit_status = display_info ();
2797   else
2798     {
2799       if (optind == argc)
2800         display_file ("a.out", target);
2801       else
2802         for (; optind < argc;)
2803           display_file (argv[optind++], target);
2804     }
2805
2806   END_PROGRESS (program_name);
2807
2808   return exit_status;
2809 }