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