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