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