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