Automatic date update in version.in
[binutils-gdb.git] / binutils / objdump.c
blob608134265669d724cca54c605c553abc9fc58944
1 /* objdump.c -- dump information about an object file.
2 Copyright (C) 1990-2023 Free Software Foundation, Inc.
4 This file is part of GNU Binutils.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, 51 Franklin Street - Fifth Floor, Boston,
19 MA 02110-1301, USA. */
22 /* Objdump overview.
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.
29 The flow of execution is as follows:
31 1. Command line arguments are checked for control switches and the
32 information to be displayed is selected.
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.
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.
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.
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. */
51 #include "sysdep.h"
52 #include "bfd.h"
53 #include "elf-bfd.h"
54 #include "coff-bfd.h"
55 #include "bucomm.h"
56 #include "elfcomm.h"
57 #include "demanguse.h"
58 #include "dwarf.h"
59 #include "ctf-api.h"
60 #include "sframe-api.h"
61 #include "getopt.h"
62 #include "safe-ctype.h"
63 #include "dis-asm.h"
64 #include "libiberty.h"
65 #include "demangle.h"
66 #include "filenames.h"
67 #include "debug.h"
68 #include "budbg.h"
69 #include "objdump.h"
71 #ifdef HAVE_MMAP
72 #include <sys/mman.h>
73 #endif
75 #ifdef HAVE_LIBDEBUGINFOD
76 #include <elfutils/debuginfod.h>
77 #endif
79 /* Internal headers for the ELF .stab-dump code - sorry. */
80 #define BYTES_IN_WORD 32
81 #include "aout/aout64.h"
83 /* Exit status. */
84 static int exit_status = 0;
86 static char *default_target = NULL; /* Default at runtime. */
88 /* The following variables are set based on arguments passed on the
89 command line. */
90 static int show_version = 0; /* Show the version number. */
91 static int dump_section_contents; /* -s */
92 static int dump_section_headers; /* -h */
93 static bool dump_file_header; /* -f */
94 static int dump_symtab; /* -t */
95 static int dump_dynamic_symtab; /* -T */
96 static int dump_reloc_info; /* -r */
97 static int dump_dynamic_reloc_info; /* -R */
98 static int dump_ar_hdrs; /* -a */
99 static int dump_private_headers; /* -p */
100 static char *dump_private_options; /* -P */
101 static int no_addresses; /* --no-addresses */
102 static int prefix_addresses; /* --prefix-addresses */
103 static int with_line_numbers; /* -l */
104 static bool with_source_code; /* -S */
105 static int show_raw_insn; /* --show-raw-insn */
106 static int dump_dwarf_section_info; /* --dwarf */
107 static int dump_stab_section_info; /* --stabs */
108 static int dump_ctf_section_info; /* --ctf */
109 static char *dump_ctf_section_name;
110 static char *dump_ctf_parent_name; /* --ctf-parent */
111 static int dump_sframe_section_info; /* --sframe */
112 static char *dump_sframe_section_name;
113 static int do_demangle; /* -C, --demangle */
114 static bool disassemble; /* -d */
115 static bool disassemble_all; /* -D */
116 static int disassemble_zeroes; /* --disassemble-zeroes */
117 static bool formats_info; /* -i */
118 int wide_output; /* -w */
119 static int insn_width; /* --insn-width */
120 static bfd_vma start_address = (bfd_vma) -1; /* --start-address */
121 static bfd_vma stop_address = (bfd_vma) -1; /* --stop-address */
122 static int dump_debugging; /* --debugging */
123 static int dump_debugging_tags; /* --debugging-tags */
124 static int suppress_bfd_header;
125 static int dump_special_syms = 0; /* --special-syms */
126 static bfd_vma adjust_section_vma = 0; /* --adjust-vma */
127 static int file_start_context = 0; /* --file-start-context */
128 static bool display_file_offsets; /* -F */
129 static const char *prefix; /* --prefix */
130 static int prefix_strip; /* --prefix-strip */
131 static size_t prefix_length;
132 static bool unwind_inlines; /* --inlines. */
133 static const char * disasm_sym; /* Disassembly start symbol. */
134 static const char * source_comment; /* --source_comment. */
135 static bool visualize_jumps = false; /* --visualize-jumps. */
136 static bool color_output = false; /* --visualize-jumps=color. */
137 static bool extended_color_output = false; /* --visualize-jumps=extended-color. */
138 static int process_links = false; /* --process-links. */
139 static int show_all_symbols; /* --show-all-symbols. */
141 static enum color_selection
143 on_if_terminal_output,
144 on, /* --disassembler-color=color. */
145 off, /* --disassembler-color=off. */
146 extended /* --disassembler-color=extended-color. */
147 } disassembler_color =
148 #if DEFAULT_FOR_COLORED_DISASSEMBLY
149 on_if_terminal_output;
150 #else
151 off;
152 #endif
154 static int dump_any_debugging;
155 static int demangle_flags = DMGL_ANSI | DMGL_PARAMS;
157 /* This is reset to false each time we enter the disassembler, and set true
158 when the disassembler emits something in the dis_style_comment_start
159 style. Once this is true, all further output on that line is done in
160 the comment style. This only has an effect when disassembler coloring
161 is turned on. */
162 static bool disassembler_in_comment = false;
164 /* A structure to record the sections mentioned in -j switches. */
165 struct only
167 const char *name; /* The name of the section. */
168 bool seen; /* A flag to indicate that the section has been found in one or more input files. */
169 struct only *next; /* Pointer to the next structure in the list. */
171 /* Pointer to an array of 'only' structures.
172 This pointer is NULL if the -j switch has not been used. */
173 static struct only * only_list = NULL;
175 /* Variables for handling include file path table. */
176 static const char **include_paths;
177 static int include_path_count;
179 /* Extra info to pass to the section disassembler and address printing
180 function. */
181 struct objdump_disasm_info
183 bfd *abfd;
184 bool require_sec;
185 disassembler_ftype disassemble_fn;
186 arelent *reloc;
187 const char *symbol;
190 /* Architecture to disassemble for, or default if NULL. */
191 static char *machine = NULL;
193 /* Target specific options to the disassembler. */
194 static char *disassembler_options = NULL;
196 /* Endianness to disassemble for, or default if BFD_ENDIAN_UNKNOWN. */
197 static enum bfd_endian endian = BFD_ENDIAN_UNKNOWN;
199 /* The symbol table. */
200 static asymbol **syms;
202 /* Number of symbols in `syms'. */
203 static long symcount = 0;
205 /* The sorted symbol table. */
206 static asymbol **sorted_syms;
208 /* Number of symbols in `sorted_syms'. */
209 static long sorted_symcount = 0;
211 /* The dynamic symbol table. */
212 static asymbol **dynsyms;
214 /* The synthetic symbol table. */
215 static asymbol *synthsyms;
216 static long synthcount = 0;
218 /* Number of symbols in `dynsyms'. */
219 static long dynsymcount = 0;
221 static bfd_byte *stabs;
222 static bfd_size_type stab_size;
224 static bfd_byte *strtab;
225 static bfd_size_type stabstr_size;
227 /* Handlers for -P/--private. */
228 static const struct objdump_private_desc * const objdump_private_vectors[] =
230 OBJDUMP_PRIVATE_VECTORS
231 NULL
234 /* The list of detected jumps inside a function. */
235 static struct jump_info *detected_jumps = NULL;
237 typedef enum unicode_display_type
239 unicode_default = 0,
240 unicode_locale,
241 unicode_escape,
242 unicode_hex,
243 unicode_highlight,
244 unicode_invalid
245 } unicode_display_type;
247 static unicode_display_type unicode_display = unicode_default;
249 static void usage (FILE *, int) ATTRIBUTE_NORETURN;
250 static void
251 usage (FILE *stream, int status)
253 fprintf (stream, _("Usage: %s <option(s)> <file(s)>\n"), program_name);
254 fprintf (stream, _(" Display information from object <file(s)>.\n"));
255 fprintf (stream, _(" At least one of the following switches must be given:\n"));
256 fprintf (stream, _("\
257 -a, --archive-headers Display archive header information\n"));
258 fprintf (stream, _("\
259 -f, --file-headers Display the contents of the overall file header\n"));
260 fprintf (stream, _("\
261 -p, --private-headers Display object format specific file header contents\n"));
262 fprintf (stream, _("\
263 -P, --private=OPT,OPT... Display object format specific contents\n"));
264 fprintf (stream, _("\
265 -h, --[section-]headers Display the contents of the section headers\n"));
266 fprintf (stream, _("\
267 -x, --all-headers Display the contents of all headers\n"));
268 fprintf (stream, _("\
269 -d, --disassemble Display assembler contents of executable sections\n"));
270 fprintf (stream, _("\
271 -D, --disassemble-all Display assembler contents of all sections\n"));
272 fprintf (stream, _("\
273 --disassemble=<sym> Display assembler contents from <sym>\n"));
274 fprintf (stream, _("\
275 -S, --source Intermix source code with disassembly\n"));
276 fprintf (stream, _("\
277 --source-comment[=<txt>] Prefix lines of source code with <txt>\n"));
278 fprintf (stream, _("\
279 -s, --full-contents Display the full contents of all sections requested\n"));
280 fprintf (stream, _("\
281 -g, --debugging Display debug information in object file\n"));
282 fprintf (stream, _("\
283 -e, --debugging-tags Display debug information using ctags style\n"));
284 fprintf (stream, _("\
285 -G, --stabs Display (in raw form) any STABS info in the file\n"));
286 fprintf (stream, _("\
287 -W, --dwarf[a/=abbrev, A/=addr, r/=aranges, c/=cu_index, L/=decodedline,\n\
288 f/=frames, F/=frames-interp, g/=gdb_index, i/=info, o/=loc,\n\
289 m/=macro, p/=pubnames, t/=pubtypes, R/=Ranges, l/=rawline,\n\
290 s/=str, O/=str-offsets, u/=trace_abbrev, T/=trace_aranges,\n\
291 U/=trace_info]\n\
292 Display the contents of DWARF debug sections\n"));
293 fprintf (stream, _("\
294 -Wk,--dwarf=links Display the contents of sections that link to\n\
295 separate debuginfo files\n"));
296 #if DEFAULT_FOR_FOLLOW_LINKS
297 fprintf (stream, _("\
298 -WK,--dwarf=follow-links\n\
299 Follow links to separate debug info files (default)\n"));
300 fprintf (stream, _("\
301 -WN,--dwarf=no-follow-links\n\
302 Do not follow links to separate debug info files\n"));
303 #else
304 fprintf (stream, _("\
305 -WK,--dwarf=follow-links\n\
306 Follow links to separate debug info files\n"));
307 fprintf (stream, _("\
308 -WN,--dwarf=no-follow-links\n\
309 Do not follow links to separate debug info files\n\
310 (default)\n"));
311 #endif
312 #if HAVE_LIBDEBUGINFOD
313 fprintf (stream, _("\
314 -WD --dwarf=use-debuginfod\n\
315 When following links, also query debuginfod servers (default)\n"));
316 fprintf (stream, _("\
317 -WE --dwarf=do-not-use-debuginfod\n\
318 When following links, do not query debuginfod servers\n"));
319 #endif
320 fprintf (stream, _("\
321 -L, --process-links Display the contents of non-debug sections in\n\
322 separate debuginfo files. (Implies -WK)\n"));
323 #ifdef ENABLE_LIBCTF
324 fprintf (stream, _("\
325 --ctf[=SECTION] Display CTF info from SECTION, (default `.ctf')\n"));
326 #endif
327 fprintf (stream, _("\
328 --sframe[=SECTION] Display SFrame info from SECTION, (default '.sframe')\n"));
329 fprintf (stream, _("\
330 -t, --syms Display the contents of the symbol table(s)\n"));
331 fprintf (stream, _("\
332 -T, --dynamic-syms Display the contents of the dynamic symbol table\n"));
333 fprintf (stream, _("\
334 -r, --reloc Display the relocation entries in the file\n"));
335 fprintf (stream, _("\
336 -R, --dynamic-reloc Display the dynamic relocation entries in the file\n"));
337 fprintf (stream, _("\
338 @<file> Read options from <file>\n"));
339 fprintf (stream, _("\
340 -v, --version Display this program's version number\n"));
341 fprintf (stream, _("\
342 -i, --info List object formats and architectures supported\n"));
343 fprintf (stream, _("\
344 -H, --help Display this information\n"));
346 if (status != 2)
348 const struct objdump_private_desc * const *desc;
350 fprintf (stream, _("\n The following switches are optional:\n"));
351 fprintf (stream, _("\
352 -b, --target=BFDNAME Specify the target object format as BFDNAME\n"));
353 fprintf (stream, _("\
354 -m, --architecture=MACHINE Specify the target architecture as MACHINE\n"));
355 fprintf (stream, _("\
356 -j, --section=NAME Only display information for section NAME\n"));
357 fprintf (stream, _("\
358 -M, --disassembler-options=OPT Pass text OPT on to the disassembler\n"));
359 fprintf (stream, _("\
360 -EB --endian=big Assume big endian format when disassembling\n"));
361 fprintf (stream, _("\
362 -EL --endian=little Assume little endian format when disassembling\n"));
363 fprintf (stream, _("\
364 --file-start-context Include context from start of file (with -S)\n"));
365 fprintf (stream, _("\
366 -I, --include=DIR Add DIR to search list for source files\n"));
367 fprintf (stream, _("\
368 -l, --line-numbers Include line numbers and filenames in output\n"));
369 fprintf (stream, _("\
370 -F, --file-offsets Include file offsets when displaying information\n"));
371 fprintf (stream, _("\
372 -C, --demangle[=STYLE] Decode mangled/processed symbol names\n"));
373 display_demangler_styles (stream, _("\
374 STYLE can be "));
375 fprintf (stream, _("\
376 --recurse-limit Enable a limit on recursion whilst demangling\n\
377 (default)\n"));
378 fprintf (stream, _("\
379 --no-recurse-limit Disable a limit on recursion whilst demangling\n"));
380 fprintf (stream, _("\
381 -w, --wide Format output for more than 80 columns\n"));
382 fprintf (stream, _("\
383 -U[d|l|i|x|e|h] Controls the display of UTF-8 unicode characters\n\
384 --unicode=[default|locale|invalid|hex|escape|highlight]\n"));
385 fprintf (stream, _("\
386 -z, --disassemble-zeroes Do not skip blocks of zeroes when disassembling\n"));
387 fprintf (stream, _("\
388 --start-address=ADDR Only process data whose address is >= ADDR\n"));
389 fprintf (stream, _("\
390 --stop-address=ADDR Only process data whose address is < ADDR\n"));
391 fprintf (stream, _("\
392 --no-addresses Do not print address alongside disassembly\n"));
393 fprintf (stream, _("\
394 --prefix-addresses Print complete address alongside disassembly\n"));
395 fprintf (stream, _("\
396 --[no-]show-raw-insn Display hex alongside symbolic disassembly\n"));
397 fprintf (stream, _("\
398 --insn-width=WIDTH Display WIDTH bytes on a single line for -d\n"));
399 fprintf (stream, _("\
400 --adjust-vma=OFFSET Add OFFSET to all displayed section addresses\n"));
401 fprintf (stream, _("\
402 --show-all-symbols When disassembling, display all symbols at a given address\n"));
403 fprintf (stream, _("\
404 --special-syms Include special symbols in symbol dumps\n"));
405 fprintf (stream, _("\
406 --inlines Print all inlines for source line (with -l)\n"));
407 fprintf (stream, _("\
408 --prefix=PREFIX Add PREFIX to absolute paths for -S\n"));
409 fprintf (stream, _("\
410 --prefix-strip=LEVEL Strip initial directory names for -S\n"));
411 fprintf (stream, _("\
412 --dwarf-depth=N Do not display DIEs at depth N or greater\n"));
413 fprintf (stream, _("\
414 --dwarf-start=N Display DIEs starting at offset N\n"));
415 fprintf (stream, _("\
416 --dwarf-check Make additional dwarf consistency checks.\n"));
417 #ifdef ENABLE_LIBCTF
418 fprintf (stream, _("\
419 --ctf-parent=NAME Use CTF archive member NAME as the CTF parent\n"));
420 #endif
421 fprintf (stream, _("\
422 --visualize-jumps Visualize jumps by drawing ASCII art lines\n"));
423 fprintf (stream, _("\
424 --visualize-jumps=color Use colors in the ASCII art\n"));
425 fprintf (stream, _("\
426 --visualize-jumps=extended-color\n\
427 Use extended 8-bit color codes\n"));
428 fprintf (stream, _("\
429 --visualize-jumps=off Disable jump visualization\n"));
430 #if DEFAULT_FOR_COLORED_DISASSEMBLY
431 fprintf (stream, _("\
432 --disassembler-color=off Disable disassembler color output.\n"));
433 fprintf (stream, _("\
434 --disassembler-color=terminal Enable disassembler color output if displaying on a terminal. (default)\n"));
435 #else
436 fprintf (stream, _("\
437 --disassembler-color=off Disable disassembler color output. (default)\n"));
438 fprintf (stream, _("\
439 --disassembler-color=terminal Enable disassembler color output if displaying on a terminal.\n"));
440 #endif
441 fprintf (stream, _("\
442 --disassembler-color=on Enable disassembler color output.\n"));
443 fprintf (stream, _("\
444 --disassembler-color=extended Use 8-bit colors in disassembler output.\n\n"));
446 list_supported_targets (program_name, stream);
447 list_supported_architectures (program_name, stream);
449 disassembler_usage (stream);
451 if (objdump_private_vectors[0] != NULL)
453 fprintf (stream,
454 _("\nOptions supported for -P/--private switch:\n"));
455 for (desc = objdump_private_vectors; *desc != NULL; desc++)
456 (*desc)->help (stream);
459 if (REPORT_BUGS_TO[0] && status == 0)
460 fprintf (stream, _("Report bugs to %s.\n"), REPORT_BUGS_TO);
461 exit (status);
464 /* 150 isn't special; it's just an arbitrary non-ASCII char value. */
465 enum option_values
467 OPTION_ENDIAN=150,
468 OPTION_START_ADDRESS,
469 OPTION_STOP_ADDRESS,
470 OPTION_DWARF,
471 OPTION_PREFIX,
472 OPTION_PREFIX_STRIP,
473 OPTION_INSN_WIDTH,
474 OPTION_ADJUST_VMA,
475 OPTION_DWARF_DEPTH,
476 OPTION_DWARF_CHECK,
477 OPTION_DWARF_START,
478 OPTION_RECURSE_LIMIT,
479 OPTION_NO_RECURSE_LIMIT,
480 OPTION_INLINES,
481 OPTION_SOURCE_COMMENT,
482 #ifdef ENABLE_LIBCTF
483 OPTION_CTF,
484 OPTION_CTF_PARENT,
485 #endif
486 OPTION_SFRAME,
487 OPTION_VISUALIZE_JUMPS,
488 OPTION_DISASSEMBLER_COLOR
491 static struct option long_options[]=
493 {"adjust-vma", required_argument, NULL, OPTION_ADJUST_VMA},
494 {"all-headers", no_argument, NULL, 'x'},
495 {"architecture", required_argument, NULL, 'm'},
496 {"archive-headers", no_argument, NULL, 'a'},
497 #ifdef ENABLE_LIBCTF
498 {"ctf", optional_argument, NULL, OPTION_CTF},
499 {"ctf-parent", required_argument, NULL, OPTION_CTF_PARENT},
500 #endif
501 {"debugging", no_argument, NULL, 'g'},
502 {"debugging-tags", no_argument, NULL, 'e'},
503 {"demangle", optional_argument, NULL, 'C'},
504 {"disassemble", optional_argument, NULL, 'd'},
505 {"disassemble-all", no_argument, NULL, 'D'},
506 {"disassemble-zeroes", no_argument, NULL, 'z'},
507 {"disassembler-options", required_argument, NULL, 'M'},
508 {"dwarf", optional_argument, NULL, OPTION_DWARF},
509 {"dwarf-check", no_argument, 0, OPTION_DWARF_CHECK},
510 {"dwarf-depth", required_argument, 0, OPTION_DWARF_DEPTH},
511 {"dwarf-start", required_argument, 0, OPTION_DWARF_START},
512 {"dynamic-reloc", no_argument, NULL, 'R'},
513 {"dynamic-syms", no_argument, NULL, 'T'},
514 {"endian", required_argument, NULL, OPTION_ENDIAN},
515 {"file-headers", no_argument, NULL, 'f'},
516 {"file-offsets", no_argument, NULL, 'F'},
517 {"file-start-context", no_argument, &file_start_context, 1},
518 {"full-contents", no_argument, NULL, 's'},
519 {"headers", no_argument, NULL, 'h'},
520 {"help", no_argument, NULL, 'H'},
521 {"include", required_argument, NULL, 'I'},
522 {"info", no_argument, NULL, 'i'},
523 {"inlines", no_argument, 0, OPTION_INLINES},
524 {"insn-width", required_argument, NULL, OPTION_INSN_WIDTH},
525 {"line-numbers", no_argument, NULL, 'l'},
526 {"no-addresses", no_argument, &no_addresses, 1},
527 {"no-recurse-limit", no_argument, NULL, OPTION_NO_RECURSE_LIMIT},
528 {"no-recursion-limit", no_argument, NULL, OPTION_NO_RECURSE_LIMIT},
529 {"no-show-raw-insn", no_argument, &show_raw_insn, -1},
530 {"prefix", required_argument, NULL, OPTION_PREFIX},
531 {"prefix-addresses", no_argument, &prefix_addresses, 1},
532 {"prefix-strip", required_argument, NULL, OPTION_PREFIX_STRIP},
533 {"private", required_argument, NULL, 'P'},
534 {"private-headers", no_argument, NULL, 'p'},
535 {"process-links", no_argument, &process_links, true},
536 {"recurse-limit", no_argument, NULL, OPTION_RECURSE_LIMIT},
537 {"recursion-limit", no_argument, NULL, OPTION_RECURSE_LIMIT},
538 {"reloc", no_argument, NULL, 'r'},
539 {"section", required_argument, NULL, 'j'},
540 {"section-headers", no_argument, NULL, 'h'},
541 {"sframe", optional_argument, NULL, OPTION_SFRAME},
542 {"show-all-symbols", no_argument, &show_all_symbols, 1},
543 {"show-raw-insn", no_argument, &show_raw_insn, 1},
544 {"source", no_argument, NULL, 'S'},
545 {"source-comment", optional_argument, NULL, OPTION_SOURCE_COMMENT},
546 {"special-syms", no_argument, &dump_special_syms, 1},
547 {"stabs", no_argument, NULL, 'G'},
548 {"start-address", required_argument, NULL, OPTION_START_ADDRESS},
549 {"stop-address", required_argument, NULL, OPTION_STOP_ADDRESS},
550 {"syms", no_argument, NULL, 't'},
551 {"target", required_argument, NULL, 'b'},
552 {"unicode", required_argument, NULL, 'U'},
553 {"version", no_argument, NULL, 'V'},
554 {"visualize-jumps", optional_argument, 0, OPTION_VISUALIZE_JUMPS},
555 {"wide", no_argument, NULL, 'w'},
556 {"disassembler-color", required_argument, NULL, OPTION_DISASSEMBLER_COLOR},
557 {NULL, no_argument, NULL, 0}
560 static void
561 my_bfd_nonfatal (const char *msg)
563 bfd_nonfatal (msg);
564 exit_status = 1;
567 /* Convert a potential UTF-8 encoded sequence in IN into characters in OUT.
568 The conversion format is controlled by the unicode_display variable.
569 Returns the number of characters added to OUT.
570 Returns the number of bytes consumed from IN in CONSUMED.
571 Always consumes at least one byte and displays at least one character. */
573 static unsigned int
574 display_utf8 (const unsigned char * in, char * out, unsigned int * consumed)
576 char * orig_out = out;
577 unsigned int nchars = 0;
578 unsigned int j;
580 if (unicode_display == unicode_default)
581 goto invalid;
583 if (in[0] < 0xc0)
584 goto invalid;
586 if ((in[1] & 0xc0) != 0x80)
587 goto invalid;
589 if ((in[0] & 0x20) == 0)
591 nchars = 2;
592 goto valid;
595 if ((in[2] & 0xc0) != 0x80)
596 goto invalid;
598 if ((in[0] & 0x10) == 0)
600 nchars = 3;
601 goto valid;
604 if ((in[3] & 0xc0) != 0x80)
605 goto invalid;
607 nchars = 4;
609 valid:
610 switch (unicode_display)
612 case unicode_locale:
613 /* Copy the bytes into the output buffer as is. */
614 memcpy (out, in, nchars);
615 out += nchars;
616 break;
618 case unicode_invalid:
619 case unicode_hex:
620 *out++ = unicode_display == unicode_hex ? '<' : '{';
621 *out++ = '0';
622 *out++ = 'x';
623 for (j = 0; j < nchars; j++)
624 out += sprintf (out, "%02x", in [j]);
625 *out++ = unicode_display == unicode_hex ? '>' : '}';
626 break;
628 case unicode_highlight:
629 if (isatty (1))
630 out += sprintf (out, "\x1B[31;47m"); /* Red. */
631 /* Fall through. */
632 case unicode_escape:
633 switch (nchars)
635 case 2:
636 out += sprintf (out, "\\u%02x%02x",
637 ((in[0] & 0x1c) >> 2),
638 ((in[0] & 0x03) << 6) | (in[1] & 0x3f));
639 break;
641 case 3:
642 out += sprintf (out, "\\u%02x%02x",
643 ((in[0] & 0x0f) << 4) | ((in[1] & 0x3c) >> 2),
644 ((in[1] & 0x03) << 6) | ((in[2] & 0x3f)));
645 break;
647 case 4:
648 out += sprintf (out, "\\u%02x%02x%02x",
649 ((in[0] & 0x07) << 6) | ((in[1] & 0x3c) >> 2),
650 ((in[1] & 0x03) << 6) | ((in[2] & 0x3c) >> 2),
651 ((in[2] & 0x03) << 6) | ((in[3] & 0x3f)));
652 break;
653 default:
654 /* URG. */
655 break;
658 if (unicode_display == unicode_highlight && isatty (1))
659 out += sprintf (out, "\x1B[0m"); /* Default colour. */
660 break;
662 default:
663 /* URG */
664 break;
667 * consumed = nchars;
668 return out - orig_out;
670 invalid:
671 /* Not a valid UTF-8 sequence. */
672 *out = *in;
673 * consumed = 1;
674 return 1;
677 /* Returns a version of IN with any control characters
678 replaced by escape sequences. Uses a static buffer
679 if necessary.
681 If unicode display is enabled, then also handles the
682 conversion of unicode characters. */
684 static const char *
685 sanitize_string (const char * in)
687 static char * buffer = NULL;
688 static size_t buffer_len = 0;
689 const char * original = in;
690 char * out;
692 /* Paranoia. */
693 if (in == NULL)
694 return "";
696 /* See if any conversion is necessary. In the majority
697 of cases it will not be needed. */
700 unsigned char c = *in++;
702 if (c == 0)
703 return original;
705 if (ISCNTRL (c))
706 break;
708 if (unicode_display != unicode_default && c >= 0xc0)
709 break;
711 while (1);
713 /* Copy the input, translating as needed. */
714 in = original;
715 /* For 2 char unicode, max out is 12 (colour escapes) + 6, ie. 9 per in
716 For hex, max out is 8 for 2 char unicode, ie. 4 per in.
717 3 and 4 char unicode produce less output for input. */
718 size_t max_needed = strlen (in) * 9 + 1;
719 if (buffer_len < max_needed)
721 buffer_len = max_needed;
722 free (buffer);
723 buffer = xmalloc (buffer_len);
726 out = buffer;
729 unsigned char c = *in++;
731 if (c == 0)
732 break;
734 if (ISCNTRL (c))
736 *out++ = '^';
737 *out++ = c + 0x40;
739 else if (unicode_display != unicode_default && c >= 0xc0)
741 unsigned int num_consumed;
743 out += display_utf8 ((const unsigned char *) --in, out, &num_consumed);
744 in += num_consumed;
746 else
747 *out++ = c;
749 while (1);
751 *out = 0;
752 return buffer;
756 /* Returns TRUE if the specified section should be dumped. */
758 static bool
759 process_section_p (asection * section)
761 struct only * only;
763 if (only_list == NULL)
764 return true;
766 for (only = only_list; only; only = only->next)
767 if (strcmp (only->name, section->name) == 0)
769 only->seen = true;
770 return true;
773 return false;
776 /* Add an entry to the 'only' list. */
778 static void
779 add_only (char * name)
781 struct only * only;
783 /* First check to make sure that we do not
784 already have an entry for this name. */
785 for (only = only_list; only; only = only->next)
786 if (strcmp (only->name, name) == 0)
787 return;
789 only = xmalloc (sizeof * only);
790 only->name = name;
791 only->seen = false;
792 only->next = only_list;
793 only_list = only;
796 /* Release the memory used by the 'only' list.
797 PR 11225: Issue a warning message for unseen sections.
798 Only do this if none of the sections were seen. This is mainly to support
799 tools like the GAS testsuite where an object file is dumped with a list of
800 generic section names known to be present in a range of different file
801 formats. */
803 static void
804 free_only_list (void)
806 bool at_least_one_seen = false;
807 struct only * only;
808 struct only * next;
810 if (only_list == NULL)
811 return;
813 for (only = only_list; only; only = only->next)
814 if (only->seen)
816 at_least_one_seen = true;
817 break;
820 for (only = only_list; only; only = next)
822 if (! at_least_one_seen)
824 non_fatal (_("section '%s' mentioned in a -j option, "
825 "but not found in any input file"),
826 only->name);
827 exit_status = 1;
829 next = only->next;
830 free (only);
835 static void
836 dump_section_header (bfd *abfd, asection *section, void *data)
838 char *comma = "";
839 unsigned int opb = bfd_octets_per_byte (abfd, section);
840 int longest_section_name = *((int *) data);
842 /* Ignore linker created section. See elfNN_ia64_object_p in
843 bfd/elfxx-ia64.c. */
844 if (section->flags & SEC_LINKER_CREATED)
845 return;
847 /* PR 10413: Skip sections that we are ignoring. */
848 if (! process_section_p (section))
849 return;
851 printf ("%3d %-*s %08lx ", section->index, longest_section_name,
852 sanitize_string (bfd_section_name (section)),
853 (unsigned long) bfd_section_size (section) / opb);
854 bfd_printf_vma (abfd, bfd_section_vma (section));
855 printf (" ");
856 bfd_printf_vma (abfd, section->lma);
857 printf (" %08lx 2**%u", (unsigned long) section->filepos,
858 bfd_section_alignment (section));
859 if (! wide_output)
860 printf ("\n ");
861 printf (" ");
863 #define PF(x, y) \
864 if (section->flags & x) { printf ("%s%s", comma, y); comma = ", "; }
866 PF (SEC_HAS_CONTENTS, "CONTENTS");
867 PF (SEC_ALLOC, "ALLOC");
868 PF (SEC_CONSTRUCTOR, "CONSTRUCTOR");
869 PF (SEC_LOAD, "LOAD");
870 PF (SEC_RELOC, "RELOC");
871 PF (SEC_READONLY, "READONLY");
872 PF (SEC_CODE, "CODE");
873 PF (SEC_DATA, "DATA");
874 PF (SEC_ROM, "ROM");
875 PF (SEC_DEBUGGING, "DEBUGGING");
876 PF (SEC_NEVER_LOAD, "NEVER_LOAD");
877 PF (SEC_EXCLUDE, "EXCLUDE");
878 PF (SEC_SORT_ENTRIES, "SORT_ENTRIES");
879 if (bfd_get_arch (abfd) == bfd_arch_tic54x)
881 PF (SEC_TIC54X_BLOCK, "BLOCK");
882 PF (SEC_TIC54X_CLINK, "CLINK");
884 PF (SEC_SMALL_DATA, "SMALL_DATA");
885 if (bfd_get_flavour (abfd) == bfd_target_coff_flavour)
887 PF (SEC_COFF_SHARED, "SHARED");
888 PF (SEC_COFF_NOREAD, "NOREAD");
890 else if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
892 PF (SEC_ELF_OCTETS, "OCTETS");
893 PF (SEC_ELF_PURECODE, "PURECODE");
895 PF (SEC_THREAD_LOCAL, "THREAD_LOCAL");
896 PF (SEC_GROUP, "GROUP");
897 if (bfd_get_arch (abfd) == bfd_arch_mep)
899 PF (SEC_MEP_VLIW, "VLIW");
902 if ((section->flags & SEC_LINK_ONCE) != 0)
904 const char *ls;
905 struct coff_comdat_info *comdat;
907 switch (section->flags & SEC_LINK_DUPLICATES)
909 default:
910 abort ();
911 case SEC_LINK_DUPLICATES_DISCARD:
912 ls = "LINK_ONCE_DISCARD";
913 break;
914 case SEC_LINK_DUPLICATES_ONE_ONLY:
915 ls = "LINK_ONCE_ONE_ONLY";
916 break;
917 case SEC_LINK_DUPLICATES_SAME_SIZE:
918 ls = "LINK_ONCE_SAME_SIZE";
919 break;
920 case SEC_LINK_DUPLICATES_SAME_CONTENTS:
921 ls = "LINK_ONCE_SAME_CONTENTS";
922 break;
924 printf ("%s%s", comma, ls);
926 comdat = bfd_coff_get_comdat_section (abfd, section);
927 if (comdat != NULL)
928 printf (" (COMDAT %s %ld)", comdat->name, comdat->symbol);
930 comma = ", ";
933 printf ("\n");
934 #undef PF
937 /* Called on each SECTION in ABFD, update the int variable pointed to by
938 DATA which contains the string length of the longest section name. */
940 static void
941 find_longest_section_name (bfd *abfd ATTRIBUTE_UNUSED,
942 asection *section, void *data)
944 int *longest_so_far = (int *) data;
945 const char *name;
946 int len;
948 /* Ignore linker created section. */
949 if (section->flags & SEC_LINKER_CREATED)
950 return;
952 /* Skip sections that we are ignoring. */
953 if (! process_section_p (section))
954 return;
956 name = bfd_section_name (section);
957 len = (int) strlen (name);
958 if (len > *longest_so_far)
959 *longest_so_far = len;
962 static void
963 dump_headers (bfd *abfd)
965 /* The default width of 13 is just an arbitrary choice. */
966 int max_section_name_length = 13;
967 int bfd_vma_width;
969 #ifndef BFD64
970 bfd_vma_width = 10;
971 #else
972 /* With BFD64, non-ELF returns -1 and wants always 64 bit addresses. */
973 if (bfd_get_arch_size (abfd) == 32)
974 bfd_vma_width = 10;
975 else
976 bfd_vma_width = 18;
977 #endif
979 printf (_("Sections:\n"));
981 if (wide_output)
982 bfd_map_over_sections (abfd, find_longest_section_name,
983 &max_section_name_length);
985 printf (_("Idx %-*s Size %-*s%-*sFile off Algn"),
986 max_section_name_length, "Name",
987 bfd_vma_width, "VMA",
988 bfd_vma_width, "LMA");
990 if (wide_output)
991 printf (_(" Flags"));
992 printf ("\n");
994 bfd_map_over_sections (abfd, dump_section_header,
995 &max_section_name_length);
998 static asymbol **
999 slurp_symtab (bfd *abfd)
1001 symcount = 0;
1002 if (!(bfd_get_file_flags (abfd) & HAS_SYMS))
1003 return NULL;
1005 long storage = bfd_get_symtab_upper_bound (abfd);
1006 if (storage < 0)
1008 non_fatal (_("failed to read symbol table from: %s"),
1009 bfd_get_filename (abfd));
1010 my_bfd_nonfatal (_("error message was"));
1013 if (storage <= 0)
1014 return NULL;
1016 asymbol **sy = (asymbol **) xmalloc (storage);
1017 symcount = bfd_canonicalize_symtab (abfd, sy);
1018 if (symcount < 0)
1020 my_bfd_nonfatal (bfd_get_filename (abfd));
1021 free (sy);
1022 sy = NULL;
1023 symcount = 0;
1025 return sy;
1028 /* Read in the dynamic symbols. */
1030 static asymbol **
1031 slurp_dynamic_symtab (bfd *abfd)
1033 dynsymcount = 0;
1034 long storage = bfd_get_dynamic_symtab_upper_bound (abfd);
1035 if (storage < 0)
1037 if (!(bfd_get_file_flags (abfd) & DYNAMIC))
1039 non_fatal (_("%s: not a dynamic object"), bfd_get_filename (abfd));
1040 exit_status = 1;
1041 return NULL;
1044 my_bfd_nonfatal (bfd_get_filename (abfd));
1047 if (storage <= 0)
1048 return NULL;
1050 asymbol **sy = (asymbol **) xmalloc (storage);
1051 dynsymcount = bfd_canonicalize_dynamic_symtab (abfd, sy);
1052 if (dynsymcount < 0)
1054 my_bfd_nonfatal (bfd_get_filename (abfd));
1055 free (sy);
1056 sy = NULL;
1057 dynsymcount = 0;
1059 return sy;
1062 /* Some symbol names are significant and should be kept in the
1063 table of sorted symbol names, even if they are marked as
1064 debugging/section symbols. */
1066 static bool
1067 is_significant_symbol_name (const char * name)
1069 return startswith (name, ".plt") || startswith (name, ".got");
1072 /* Filter out (in place) symbols that are useless for disassembly.
1073 COUNT is the number of elements in SYMBOLS.
1074 Return the number of useful symbols. */
1076 static long
1077 remove_useless_symbols (asymbol **symbols, long count)
1079 asymbol **in_ptr = symbols, **out_ptr = symbols;
1081 while (--count >= 0)
1083 asymbol *sym = *in_ptr++;
1085 if (sym->name == NULL || sym->name[0] == '\0')
1086 continue;
1087 if ((sym->flags & (BSF_DEBUGGING | BSF_SECTION_SYM))
1088 && ! is_significant_symbol_name (sym->name))
1089 continue;
1090 if (bfd_is_und_section (sym->section)
1091 || bfd_is_com_section (sym->section))
1092 continue;
1094 *out_ptr++ = sym;
1096 return out_ptr - symbols;
1099 static const asection *compare_section;
1101 /* Sort symbols into value order. */
1103 static int
1104 compare_symbols (const void *ap, const void *bp)
1106 const asymbol *a = * (const asymbol **) ap;
1107 const asymbol *b = * (const asymbol **) bp;
1108 const char *an;
1109 const char *bn;
1110 size_t anl;
1111 size_t bnl;
1112 bool as, af, bs, bf;
1113 flagword aflags;
1114 flagword bflags;
1116 if (bfd_asymbol_value (a) > bfd_asymbol_value (b))
1117 return 1;
1118 else if (bfd_asymbol_value (a) < bfd_asymbol_value (b))
1119 return -1;
1121 /* Prefer symbols from the section currently being disassembled.
1122 Don't sort symbols from other sections by section, since there
1123 isn't much reason to prefer one section over another otherwise.
1124 See sym_ok comment for why we compare by section name. */
1125 as = strcmp (compare_section->name, a->section->name) == 0;
1126 bs = strcmp (compare_section->name, b->section->name) == 0;
1127 if (as && !bs)
1128 return -1;
1129 if (!as && bs)
1130 return 1;
1132 an = bfd_asymbol_name (a);
1133 bn = bfd_asymbol_name (b);
1134 anl = strlen (an);
1135 bnl = strlen (bn);
1137 /* The symbols gnu_compiled and gcc2_compiled convey no real
1138 information, so put them after other symbols with the same value. */
1139 af = (strstr (an, "gnu_compiled") != NULL
1140 || strstr (an, "gcc2_compiled") != NULL);
1141 bf = (strstr (bn, "gnu_compiled") != NULL
1142 || strstr (bn, "gcc2_compiled") != NULL);
1144 if (af && ! bf)
1145 return 1;
1146 if (! af && bf)
1147 return -1;
1149 /* We use a heuristic for the file name, to try to sort it after
1150 more useful symbols. It may not work on non Unix systems, but it
1151 doesn't really matter; the only difference is precisely which
1152 symbol names get printed. */
1154 #define file_symbol(s, sn, snl) \
1155 (((s)->flags & BSF_FILE) != 0 \
1156 || ((snl) > 2 \
1157 && (sn)[(snl) - 2] == '.' \
1158 && ((sn)[(snl) - 1] == 'o' \
1159 || (sn)[(snl) - 1] == 'a')))
1161 af = file_symbol (a, an, anl);
1162 bf = file_symbol (b, bn, bnl);
1164 if (af && ! bf)
1165 return 1;
1166 if (! af && bf)
1167 return -1;
1169 /* Sort function and object symbols before global symbols before
1170 local symbols before section symbols before debugging symbols. */
1172 aflags = a->flags;
1173 bflags = b->flags;
1175 if ((aflags & BSF_DEBUGGING) != (bflags & BSF_DEBUGGING))
1177 if ((aflags & BSF_DEBUGGING) != 0)
1178 return 1;
1179 else
1180 return -1;
1182 if ((aflags & BSF_SECTION_SYM) != (bflags & BSF_SECTION_SYM))
1184 if ((aflags & BSF_SECTION_SYM) != 0)
1185 return 1;
1186 else
1187 return -1;
1189 if ((aflags & BSF_FUNCTION) != (bflags & BSF_FUNCTION))
1191 if ((aflags & BSF_FUNCTION) != 0)
1192 return -1;
1193 else
1194 return 1;
1196 if ((aflags & BSF_OBJECT) != (bflags & BSF_OBJECT))
1198 if ((aflags & BSF_OBJECT) != 0)
1199 return -1;
1200 else
1201 return 1;
1203 if ((aflags & BSF_LOCAL) != (bflags & BSF_LOCAL))
1205 if ((aflags & BSF_LOCAL) != 0)
1206 return 1;
1207 else
1208 return -1;
1210 if ((aflags & BSF_GLOBAL) != (bflags & BSF_GLOBAL))
1212 if ((aflags & BSF_GLOBAL) != 0)
1213 return -1;
1214 else
1215 return 1;
1218 /* Sort larger size ELF symbols before smaller. See PR20337. */
1219 bfd_vma asz = 0;
1220 if ((a->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) == 0
1221 && bfd_get_flavour (bfd_asymbol_bfd (a)) == bfd_target_elf_flavour)
1222 asz = ((elf_symbol_type *) a)->internal_elf_sym.st_size;
1223 bfd_vma bsz = 0;
1224 if ((b->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) == 0
1225 && bfd_get_flavour (bfd_asymbol_bfd (b)) == bfd_target_elf_flavour)
1226 bsz = ((elf_symbol_type *) b)->internal_elf_sym.st_size;
1227 if (asz != bsz)
1228 return asz > bsz ? -1 : 1;
1230 /* Symbols that start with '.' might be section names, so sort them
1231 after symbols that don't start with '.'. */
1232 if (an[0] == '.' && bn[0] != '.')
1233 return 1;
1234 if (an[0] != '.' && bn[0] == '.')
1235 return -1;
1237 /* Finally, if we can't distinguish them in any other way, try to
1238 get consistent results by sorting the symbols by name. */
1239 return strcmp (an, bn);
1242 /* Sort relocs into address order. */
1244 static int
1245 compare_relocs (const void *ap, const void *bp)
1247 const arelent *a = * (const arelent **) ap;
1248 const arelent *b = * (const arelent **) bp;
1250 if (a->address > b->address)
1251 return 1;
1252 else if (a->address < b->address)
1253 return -1;
1255 /* So that associated relocations tied to the same address show up
1256 in the correct order, we don't do any further sorting. */
1257 if (a > b)
1258 return 1;
1259 else if (a < b)
1260 return -1;
1261 else
1262 return 0;
1265 /* Print an address (VMA) to the output stream in INFO.
1266 If SKIP_ZEROES is TRUE, omit leading zeroes. */
1268 static void
1269 objdump_print_value (bfd_vma vma, struct disassemble_info *inf,
1270 bool skip_zeroes)
1272 char buf[30];
1273 char *p;
1274 struct objdump_disasm_info *aux;
1276 aux = (struct objdump_disasm_info *) inf->application_data;
1277 bfd_sprintf_vma (aux->abfd, buf, vma);
1278 if (! skip_zeroes)
1279 p = buf;
1280 else
1282 for (p = buf; *p == '0'; ++p)
1284 if (*p == '\0')
1285 --p;
1287 (*inf->fprintf_styled_func) (inf->stream, dis_style_address, "%s", p);
1290 /* Print the name of a symbol. */
1292 static void
1293 objdump_print_symname (bfd *abfd, struct disassemble_info *inf,
1294 asymbol *sym)
1296 char *alloc;
1297 const char *name, *version_string = NULL;
1298 bool hidden = false;
1300 alloc = NULL;
1301 name = bfd_asymbol_name (sym);
1302 if (do_demangle && name[0] != '\0')
1304 /* Demangle the name. */
1305 alloc = bfd_demangle (abfd, name, demangle_flags);
1306 if (alloc != NULL)
1307 name = alloc;
1310 if ((sym->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) == 0)
1311 version_string = bfd_get_symbol_version_string (abfd, sym, true,
1312 &hidden);
1314 if (bfd_is_und_section (bfd_asymbol_section (sym)))
1315 hidden = true;
1317 name = sanitize_string (name);
1319 if (inf != NULL)
1321 (*inf->fprintf_styled_func) (inf->stream, dis_style_symbol, "%s", name);
1322 if (version_string && *version_string != '\0')
1323 (*inf->fprintf_styled_func) (inf->stream, dis_style_symbol,
1324 hidden ? "@%s" : "@@%s",
1325 version_string);
1327 else
1329 printf ("%s", name);
1330 if (version_string && *version_string != '\0')
1331 printf (hidden ? "@%s" : "@@%s", version_string);
1334 if (alloc != NULL)
1335 free (alloc);
1338 static inline bool
1339 sym_ok (bool want_section,
1340 bfd *abfd ATTRIBUTE_UNUSED,
1341 long place,
1342 asection *sec,
1343 struct disassemble_info *inf)
1345 if (want_section)
1347 /* NB: An object file can have different sections with the same
1348 section name. Compare compare section pointers if they have
1349 the same owner. */
1350 if (sorted_syms[place]->section->owner == sec->owner
1351 && sorted_syms[place]->section != sec)
1352 return false;
1354 /* Note - we cannot just compare section pointers because they could
1355 be different, but the same... Ie the symbol that we are trying to
1356 find could have come from a separate debug info file. Under such
1357 circumstances the symbol will be associated with a section in the
1358 debug info file, whilst the section we want is in a normal file.
1359 So the section pointers will be different, but the section names
1360 will be the same. */
1361 if (strcmp (bfd_section_name (sorted_syms[place]->section),
1362 bfd_section_name (sec)) != 0)
1363 return false;
1366 return inf->symbol_is_valid (sorted_syms[place], inf);
1369 /* Locate a symbol given a bfd and a section (from INFO->application_data),
1370 and a VMA. If INFO->application_data->require_sec is TRUE, then always
1371 require the symbol to be in the section. Returns NULL if there is no
1372 suitable symbol. If PLACE is not NULL, then *PLACE is set to the index
1373 of the symbol in sorted_syms. */
1375 static asymbol *
1376 find_symbol_for_address (bfd_vma vma,
1377 struct disassemble_info *inf,
1378 long *place)
1380 /* @@ Would it speed things up to cache the last two symbols returned,
1381 and maybe their address ranges? For many processors, only one memory
1382 operand can be present at a time, so the 2-entry cache wouldn't be
1383 constantly churned by code doing heavy memory accesses. */
1385 /* Indices in `sorted_syms'. */
1386 long min = 0;
1387 long max_count = sorted_symcount;
1388 long thisplace;
1389 struct objdump_disasm_info *aux;
1390 bfd *abfd;
1391 asection *sec;
1392 unsigned int opb;
1393 bool want_section;
1394 long rel_count;
1396 if (sorted_symcount < 1)
1397 return NULL;
1399 aux = (struct objdump_disasm_info *) inf->application_data;
1400 abfd = aux->abfd;
1401 sec = inf->section;
1402 opb = inf->octets_per_byte;
1404 /* Perform a binary search looking for the closest symbol to the
1405 required value. We are searching the range (min, max_count]. */
1406 while (min + 1 < max_count)
1408 asymbol *sym;
1410 thisplace = (max_count + min) / 2;
1411 sym = sorted_syms[thisplace];
1413 if (bfd_asymbol_value (sym) > vma)
1414 max_count = thisplace;
1415 else if (bfd_asymbol_value (sym) < vma)
1416 min = thisplace;
1417 else
1419 min = thisplace;
1420 break;
1424 /* The symbol we want is now in min, the low end of the range we
1425 were searching. If there are several symbols with the same
1426 value, we want the first one. */
1427 thisplace = min;
1428 while (thisplace > 0
1429 && (bfd_asymbol_value (sorted_syms[thisplace])
1430 == bfd_asymbol_value (sorted_syms[thisplace - 1])))
1431 --thisplace;
1433 /* Prefer a symbol in the current section if we have multple symbols
1434 with the same value, as can occur with overlays or zero size
1435 sections. */
1436 min = thisplace;
1437 while (min < max_count
1438 && (bfd_asymbol_value (sorted_syms[min])
1439 == bfd_asymbol_value (sorted_syms[thisplace])))
1441 if (sym_ok (true, abfd, min, sec, inf))
1443 thisplace = min;
1445 if (place != NULL)
1446 *place = thisplace;
1448 return sorted_syms[thisplace];
1450 ++min;
1453 /* If the file is relocatable, and the symbol could be from this
1454 section, prefer a symbol from this section over symbols from
1455 others, even if the other symbol's value might be closer.
1457 Note that this may be wrong for some symbol references if the
1458 sections have overlapping memory ranges, but in that case there's
1459 no way to tell what's desired without looking at the relocation
1460 table.
1462 Also give the target a chance to reject symbols. */
1463 want_section = (aux->require_sec
1464 || ((abfd->flags & HAS_RELOC) != 0
1465 && vma >= bfd_section_vma (sec)
1466 && vma < (bfd_section_vma (sec)
1467 + bfd_section_size (sec) / opb)));
1469 if (! sym_ok (want_section, abfd, thisplace, sec, inf))
1471 long i;
1472 long newplace = sorted_symcount;
1474 for (i = min - 1; i >= 0; i--)
1476 if (sym_ok (want_section, abfd, i, sec, inf))
1478 if (newplace == sorted_symcount)
1479 newplace = i;
1481 if (bfd_asymbol_value (sorted_syms[i])
1482 != bfd_asymbol_value (sorted_syms[newplace]))
1483 break;
1485 /* Remember this symbol and keep searching until we reach
1486 an earlier address. */
1487 newplace = i;
1491 if (newplace != sorted_symcount)
1492 thisplace = newplace;
1493 else
1495 /* We didn't find a good symbol with a smaller value.
1496 Look for one with a larger value. */
1497 for (i = thisplace + 1; i < sorted_symcount; i++)
1499 if (sym_ok (want_section, abfd, i, sec, inf))
1501 thisplace = i;
1502 break;
1507 if (! sym_ok (want_section, abfd, thisplace, sec, inf))
1508 /* There is no suitable symbol. */
1509 return NULL;
1512 /* If we have not found an exact match for the specified address
1513 and we have dynamic relocations available, then we can produce
1514 a better result by matching a relocation to the address and
1515 using the symbol associated with that relocation. */
1516 rel_count = inf->dynrelcount;
1517 if (!want_section
1518 && sorted_syms[thisplace]->value != vma
1519 && rel_count > 0
1520 && inf->dynrelbuf != NULL
1521 && inf->dynrelbuf[0]->address <= vma
1522 && inf->dynrelbuf[rel_count - 1]->address >= vma
1523 /* If we have matched a synthetic symbol, then stick with that. */
1524 && (sorted_syms[thisplace]->flags & BSF_SYNTHETIC) == 0)
1526 arelent ** rel_low;
1527 arelent ** rel_high;
1529 rel_low = inf->dynrelbuf;
1530 rel_high = rel_low + rel_count - 1;
1531 while (rel_low <= rel_high)
1533 arelent **rel_mid = &rel_low[(rel_high - rel_low) / 2];
1534 arelent * rel = *rel_mid;
1536 if (rel->address == vma)
1538 /* Absolute relocations do not provide a more helpful
1539 symbolic address. Find a non-absolute relocation
1540 with the same address. */
1541 arelent **rel_vma = rel_mid;
1542 for (rel_mid--;
1543 rel_mid >= rel_low && rel_mid[0]->address == vma;
1544 rel_mid--)
1545 rel_vma = rel_mid;
1547 for (; rel_vma <= rel_high && rel_vma[0]->address == vma;
1548 rel_vma++)
1550 rel = *rel_vma;
1551 if (rel->sym_ptr_ptr != NULL
1552 && ! bfd_is_abs_section ((* rel->sym_ptr_ptr)->section))
1554 if (place != NULL)
1555 * place = thisplace;
1556 return * rel->sym_ptr_ptr;
1559 break;
1562 if (vma < rel->address)
1563 rel_high = rel_mid;
1564 else if (vma >= rel_mid[1]->address)
1565 rel_low = rel_mid + 1;
1566 else
1567 break;
1571 if (place != NULL)
1572 *place = thisplace;
1574 return sorted_syms[thisplace];
1577 /* Print an address and the offset to the nearest symbol. */
1579 static void
1580 objdump_print_addr_with_sym (bfd *abfd, asection *sec, asymbol *sym,
1581 bfd_vma vma, struct disassemble_info *inf,
1582 bool skip_zeroes)
1584 if (!no_addresses)
1586 objdump_print_value (vma, inf, skip_zeroes);
1587 (*inf->fprintf_styled_func) (inf->stream, dis_style_text, " ");
1590 if (sym == NULL)
1592 bfd_vma secaddr;
1594 (*inf->fprintf_styled_func) (inf->stream, dis_style_text,"<");
1595 (*inf->fprintf_styled_func) (inf->stream, dis_style_symbol, "%s",
1596 sanitize_string (bfd_section_name (sec)));
1597 secaddr = bfd_section_vma (sec);
1598 if (vma < secaddr)
1600 (*inf->fprintf_styled_func) (inf->stream, dis_style_immediate,
1601 "-0x");
1602 objdump_print_value (secaddr - vma, inf, true);
1604 else if (vma > secaddr)
1606 (*inf->fprintf_styled_func) (inf->stream, dis_style_immediate, "+0x");
1607 objdump_print_value (vma - secaddr, inf, true);
1609 (*inf->fprintf_styled_func) (inf->stream, dis_style_text, ">");
1611 else
1613 (*inf->fprintf_styled_func) (inf->stream, dis_style_text, "<");
1615 objdump_print_symname (abfd, inf, sym);
1617 if (bfd_asymbol_value (sym) == vma)
1619 /* Undefined symbols in an executables and dynamic objects do not have
1620 a value associated with them, so it does not make sense to display
1621 an offset relative to them. Normally we would not be provided with
1622 this kind of symbol, but the target backend might choose to do so,
1623 and the code in find_symbol_for_address might return an as yet
1624 unresolved symbol associated with a dynamic reloc. */
1625 else if ((bfd_get_file_flags (abfd) & (EXEC_P | DYNAMIC))
1626 && bfd_is_und_section (sym->section))
1628 else if (bfd_asymbol_value (sym) > vma)
1630 (*inf->fprintf_styled_func) (inf->stream, dis_style_immediate,"-0x");
1631 objdump_print_value (bfd_asymbol_value (sym) - vma, inf, true);
1633 else if (vma > bfd_asymbol_value (sym))
1635 (*inf->fprintf_styled_func) (inf->stream, dis_style_immediate, "+0x");
1636 objdump_print_value (vma - bfd_asymbol_value (sym), inf, true);
1639 (*inf->fprintf_styled_func) (inf->stream, dis_style_text, ">");
1642 if (display_file_offsets)
1643 inf->fprintf_styled_func (inf->stream, dis_style_text,
1644 _(" (File Offset: 0x%lx)"),
1645 (long int)(sec->filepos + (vma - sec->vma)));
1648 /* Print an address (VMA), symbolically if possible.
1649 If SKIP_ZEROES is TRUE, don't output leading zeroes. */
1651 static void
1652 objdump_print_addr (bfd_vma vma,
1653 struct disassemble_info *inf,
1654 bool skip_zeroes)
1656 struct objdump_disasm_info *aux;
1657 asymbol *sym = NULL;
1658 bool skip_find = false;
1660 aux = (struct objdump_disasm_info *) inf->application_data;
1662 if (sorted_symcount < 1)
1664 if (!no_addresses)
1666 (*inf->fprintf_styled_func) (inf->stream, dis_style_address, "0x");
1667 objdump_print_value (vma, inf, skip_zeroes);
1670 if (display_file_offsets)
1671 inf->fprintf_styled_func (inf->stream, dis_style_text,
1672 _(" (File Offset: 0x%lx)"),
1673 (long int) (inf->section->filepos
1674 + (vma - inf->section->vma)));
1675 return;
1678 if (aux->reloc != NULL
1679 && aux->reloc->sym_ptr_ptr != NULL
1680 && * aux->reloc->sym_ptr_ptr != NULL)
1682 sym = * aux->reloc->sym_ptr_ptr;
1684 /* Adjust the vma to the reloc. */
1685 vma += bfd_asymbol_value (sym);
1687 if (bfd_is_und_section (bfd_asymbol_section (sym)))
1688 skip_find = true;
1691 if (!skip_find)
1692 sym = find_symbol_for_address (vma, inf, NULL);
1694 objdump_print_addr_with_sym (aux->abfd, inf->section, sym, vma, inf,
1695 skip_zeroes);
1698 /* Print VMA to INFO. This function is passed to the disassembler
1699 routine. */
1701 static void
1702 objdump_print_address (bfd_vma vma, struct disassemble_info *inf)
1704 objdump_print_addr (vma, inf, ! prefix_addresses);
1707 /* Determine if the given address has a symbol associated with it. */
1709 static asymbol *
1710 objdump_symbol_at_address (bfd_vma vma, struct disassemble_info * inf)
1712 asymbol * sym;
1714 sym = find_symbol_for_address (vma, inf, NULL);
1715 if (sym != NULL && bfd_asymbol_value (sym) == vma)
1716 return sym;
1718 return NULL;
1721 /* Hold the last function name and the last line number we displayed
1722 in a disassembly. */
1724 static char *prev_functionname;
1725 static unsigned int prev_line;
1726 static unsigned int prev_discriminator;
1728 /* We keep a list of all files that we have seen when doing a
1729 disassembly with source, so that we know how much of the file to
1730 display. This can be important for inlined functions. */
1732 struct print_file_list
1734 struct print_file_list *next;
1735 const char *filename;
1736 const char *modname;
1737 const char *map;
1738 size_t mapsize;
1739 const char **linemap;
1740 unsigned maxline;
1741 unsigned last_line;
1742 unsigned max_printed;
1743 int first;
1746 static struct print_file_list *print_files;
1748 /* The number of preceding context lines to show when we start
1749 displaying a file for the first time. */
1751 #define SHOW_PRECEDING_CONTEXT_LINES (5)
1753 #if HAVE_LIBDEBUGINFOD
1754 /* Return a hex string represention of the build-id. */
1756 unsigned char *
1757 get_build_id (void * data)
1759 unsigned i;
1760 char * build_id_str;
1761 bfd * abfd = (bfd *) data;
1762 const struct bfd_build_id * build_id;
1764 build_id = abfd->build_id;
1765 if (build_id == NULL)
1766 return NULL;
1768 build_id_str = malloc (build_id->size * 2 + 1);
1769 if (build_id_str == NULL)
1770 return NULL;
1772 for (i = 0; i < build_id->size; i++)
1773 sprintf (build_id_str + (i * 2), "%02x", build_id->data[i]);
1774 build_id_str[build_id->size * 2] = '\0';
1776 return (unsigned char *) build_id_str;
1779 /* Search for a separate debug file matching ABFD's build-id. */
1781 static bfd *
1782 find_separate_debug (const bfd * abfd)
1784 const struct bfd_build_id * build_id = abfd->build_id;
1785 separate_info * i = first_separate_info;
1787 if (build_id == NULL || i == NULL)
1788 return NULL;
1790 while (i != NULL)
1792 const bfd * i_bfd = (bfd *) i->handle;
1794 if (abfd != NULL && i_bfd->build_id != NULL)
1796 const unsigned char * data = i_bfd->build_id->data;
1797 size_t size = i_bfd->build_id->size;
1799 if (size == build_id->size
1800 && memcmp (data, build_id->data, size) == 0)
1801 return (bfd *) i->handle;
1804 i = i->next;
1807 return NULL;
1810 /* Search for a separate debug file matching ABFD's .gnu_debugaltlink
1811 build-id. */
1813 static bfd *
1814 find_alt_debug (const bfd * abfd)
1816 size_t namelen;
1817 size_t id_len;
1818 const char * name;
1819 struct dwarf_section * section;
1820 const struct bfd_build_id * build_id = abfd->build_id;
1821 separate_info * i = first_separate_info;
1823 if (i == NULL
1824 || build_id == NULL
1825 || !load_debug_section (gnu_debugaltlink, (void *) abfd))
1826 return NULL;
1828 section = &debug_displays[gnu_debugaltlink].section;
1829 if (section == NULL)
1830 return NULL;
1832 name = (const char *) section->start;
1833 namelen = strnlen (name, section->size) + 1;
1834 if (namelen == 1)
1835 return NULL;
1836 if (namelen >= section->size)
1837 return NULL;
1839 id_len = section->size - namelen;
1840 if (id_len < 0x14)
1841 return NULL;
1843 /* Compare the .gnu_debugaltlink build-id with the build-ids of the
1844 known separate_info files. */
1845 while (i != NULL)
1847 const bfd * i_bfd = (bfd *) i->handle;
1849 if (i_bfd != NULL && i_bfd->build_id != NULL)
1851 const unsigned char * data = i_bfd->build_id->data;
1852 size_t size = i_bfd->build_id->size;
1854 if (id_len == size
1855 && memcmp (section->start + namelen, data, size) == 0)
1856 return (bfd *) i->handle;
1859 i = i->next;
1862 return NULL;
1865 #endif /* HAVE_LIBDEBUGINFOD */
1867 /* Reads the contents of file FN into memory. Returns a pointer to the buffer.
1868 Also returns the size of the buffer in SIZE_RETURN and a filled out
1869 stat structure in FST_RETURN. Returns NULL upon failure. */
1871 static const char *
1872 slurp_file (const char * fn,
1873 size_t * size_return,
1874 struct stat * fst_return,
1875 bfd * abfd ATTRIBUTE_UNUSED)
1877 #ifdef HAVE_MMAP
1878 int ps;
1879 size_t msize;
1880 #endif
1881 const char *map;
1882 int fd;
1884 /* Paranoia. */
1885 if (fn == NULL || * fn == 0 || size_return == NULL || fst_return == NULL)
1886 return NULL;
1888 fd = open (fn, O_RDONLY | O_BINARY);
1890 #if HAVE_LIBDEBUGINFOD
1891 if (fd < 0 && use_debuginfod && fn[0] == '/' && abfd != NULL)
1893 unsigned char *build_id = get_build_id (abfd);
1895 if (build_id)
1897 debuginfod_client *client = debuginfod_begin ();
1899 if (client)
1901 fd = debuginfod_find_source (client, build_id, 0, fn, NULL);
1902 debuginfod_end (client);
1904 free (build_id);
1907 #endif
1909 if (fd < 0)
1910 return NULL;
1912 if (fstat (fd, fst_return) < 0)
1914 close (fd);
1915 return NULL;
1918 *size_return = fst_return->st_size;
1920 #ifdef HAVE_MMAP
1921 ps = getpagesize ();
1922 msize = (*size_return + ps - 1) & ~(ps - 1);
1923 map = mmap (NULL, msize, PROT_READ, MAP_SHARED, fd, 0);
1924 if (map != (char *) -1L)
1926 close (fd);
1927 return map;
1929 #endif
1931 map = (const char *) malloc (*size_return);
1932 if (!map || (size_t) read (fd, (char *) map, *size_return) != *size_return)
1934 free ((void *) map);
1935 map = NULL;
1937 close (fd);
1938 return map;
1941 #define line_map_decrease 5
1943 /* Precompute array of lines for a mapped file. */
1945 static const char **
1946 index_file (const char *map, size_t size, unsigned int *maxline)
1948 const char *p, *lstart, *end;
1949 int chars_per_line = 45; /* First iteration will use 40. */
1950 unsigned int lineno;
1951 const char **linemap = NULL;
1952 unsigned long line_map_size = 0;
1954 lineno = 0;
1955 lstart = map;
1956 end = map + size;
1958 for (p = map; p < end; p++)
1960 if (*p == '\n')
1962 if (p + 1 < end && p[1] == '\r')
1963 p++;
1965 else if (*p == '\r')
1967 if (p + 1 < end && p[1] == '\n')
1968 p++;
1970 else
1971 continue;
1973 /* End of line found. */
1975 if (linemap == NULL || line_map_size < lineno + 1)
1977 unsigned long newsize;
1979 chars_per_line -= line_map_decrease;
1980 if (chars_per_line <= 1)
1981 chars_per_line = 1;
1982 line_map_size = size / chars_per_line + 1;
1983 if (line_map_size < lineno + 1)
1984 line_map_size = lineno + 1;
1985 newsize = line_map_size * sizeof (char *);
1986 linemap = (const char **) xrealloc (linemap, newsize);
1989 linemap[lineno++] = lstart;
1990 lstart = p + 1;
1993 *maxline = lineno;
1994 return linemap;
1997 /* Tries to open MODNAME, and if successful adds a node to print_files
1998 linked list and returns that node. Also fills in the stat structure
1999 pointed to by FST_RETURN. Returns NULL on failure. */
2001 static struct print_file_list *
2002 try_print_file_open (const char * origname,
2003 const char * modname,
2004 struct stat * fst_return,
2005 bfd * abfd)
2007 struct print_file_list *p;
2009 p = (struct print_file_list *) xmalloc (sizeof (struct print_file_list));
2011 p->map = slurp_file (modname, &p->mapsize, fst_return, abfd);
2012 if (p->map == NULL)
2014 free (p);
2015 return NULL;
2018 p->linemap = index_file (p->map, p->mapsize, &p->maxline);
2019 p->last_line = 0;
2020 p->max_printed = 0;
2021 p->filename = origname;
2022 p->modname = modname;
2023 p->next = print_files;
2024 p->first = 1;
2025 print_files = p;
2026 return p;
2029 /* If the source file, as described in the symtab, is not found
2030 try to locate it in one of the paths specified with -I
2031 If found, add location to print_files linked list. */
2033 static struct print_file_list *
2034 update_source_path (const char *filename, bfd *abfd)
2036 struct print_file_list *p;
2037 const char *fname;
2038 struct stat fst;
2039 int i;
2041 p = try_print_file_open (filename, filename, &fst, abfd);
2042 if (p == NULL)
2044 if (include_path_count == 0)
2045 return NULL;
2047 /* Get the name of the file. */
2048 fname = lbasename (filename);
2050 /* If file exists under a new path, we need to add it to the list
2051 so that show_line knows about it. */
2052 for (i = 0; i < include_path_count; i++)
2054 char *modname = concat (include_paths[i], "/", fname,
2055 (const char *) 0);
2057 p = try_print_file_open (filename, modname, &fst, abfd);
2058 if (p)
2059 break;
2061 free (modname);
2065 if (p != NULL)
2067 long mtime = bfd_get_mtime (abfd);
2069 if (fst.st_mtime > mtime)
2070 warn (_("source file %s is more recent than object file\n"),
2071 filename);
2074 return p;
2077 /* Print a source file line. */
2079 static void
2080 print_line (struct print_file_list *p, unsigned int linenum)
2082 const char *l;
2083 size_t len;
2085 if (linenum >= p->maxline)
2086 return;
2087 l = p->linemap [linenum];
2088 if (source_comment != NULL && strlen (l) > 0)
2089 printf ("%s", source_comment);
2090 len = strcspn (l, "\n\r");
2091 /* Test fwrite return value to quiet glibc warning. */
2092 if (len == 0 || fwrite (l, len, 1, stdout) == 1)
2093 putchar ('\n');
2096 /* Print a range of source code lines. */
2098 static void
2099 dump_lines (struct print_file_list *p, unsigned int start, unsigned int end)
2101 if (p->map == NULL)
2102 return;
2103 if (start != 0)
2104 --start;
2105 while (start < end)
2107 print_line (p, start);
2108 start++;
2112 /* Show the line number, or the source line, in a disassembly
2113 listing. */
2115 static void
2116 show_line (bfd *abfd, asection *section, bfd_vma addr_offset)
2118 const char *filename;
2119 const char *functionname;
2120 unsigned int linenumber;
2121 unsigned int discriminator;
2122 bool reloc;
2123 char *path = NULL;
2125 if (! with_line_numbers && ! with_source_code)
2126 return;
2128 #ifdef HAVE_LIBDEBUGINFOD
2130 bfd *debug_bfd;
2131 const char *alt_filename = NULL;
2133 if (use_debuginfod)
2135 bfd *alt_bfd;
2137 /* PR 29075: Check for separate debuginfo and .gnu_debugaltlink files.
2138 They need to be passed to bfd_find_nearest_line_with_alt in case they
2139 were downloaded from debuginfod. Otherwise libbfd will attempt to
2140 search for them and fail to locate them. */
2141 debug_bfd = find_separate_debug (abfd);
2142 if (debug_bfd == NULL)
2143 debug_bfd = abfd;
2145 alt_bfd = find_alt_debug (debug_bfd);
2146 if (alt_bfd != NULL)
2147 alt_filename = bfd_get_filename (alt_bfd);
2149 else
2150 debug_bfd = abfd;
2152 bfd_set_error (bfd_error_no_error);
2153 if (! bfd_find_nearest_line_with_alt (debug_bfd, alt_filename,
2154 section, syms,
2155 addr_offset, &filename,
2156 &functionname, &linenumber,
2157 &discriminator))
2159 if (bfd_get_error () == bfd_error_no_error)
2160 return;
2161 if (! bfd_find_nearest_line_discriminator (abfd, section, syms,
2162 addr_offset, &filename,
2163 &functionname, &linenumber,
2164 &discriminator))
2165 return;
2168 #else
2169 if (! bfd_find_nearest_line_discriminator (abfd, section, syms, addr_offset,
2170 &filename, &functionname,
2171 &linenumber, &discriminator))
2172 return;
2173 #endif
2175 if (filename != NULL && *filename == '\0')
2176 filename = NULL;
2177 if (functionname != NULL && *functionname == '\0')
2178 functionname = NULL;
2180 if (filename
2181 && IS_ABSOLUTE_PATH (filename)
2182 && prefix)
2184 char *path_up;
2185 const char *fname = filename;
2187 path = xmalloc (prefix_length + 1 + strlen (filename));
2189 if (prefix_length)
2190 memcpy (path, prefix, prefix_length);
2191 path_up = path + prefix_length;
2193 /* Build relocated filename, stripping off leading directories
2194 from the initial filename if requested. */
2195 if (prefix_strip > 0)
2197 int level = 0;
2198 const char *s;
2200 /* Skip selected directory levels. */
2201 for (s = fname + 1; *s != '\0' && level < prefix_strip; s++)
2202 if (IS_DIR_SEPARATOR (*s))
2204 fname = s;
2205 level++;
2209 /* Update complete filename. */
2210 strcpy (path_up, fname);
2212 filename = path;
2213 reloc = true;
2215 else
2216 reloc = false;
2218 if (with_line_numbers)
2220 if (functionname != NULL
2221 && (prev_functionname == NULL
2222 || strcmp (functionname, prev_functionname) != 0))
2224 char *demangle_alloc = NULL;
2225 if (do_demangle && functionname[0] != '\0')
2227 /* Demangle the name. */
2228 demangle_alloc = bfd_demangle (abfd, functionname,
2229 demangle_flags);
2232 /* Demangling adds trailing parens, so don't print those. */
2233 if (demangle_alloc != NULL)
2234 printf ("%s:\n", sanitize_string (demangle_alloc));
2235 else
2236 printf ("%s():\n", sanitize_string (functionname));
2238 prev_line = -1;
2239 free (demangle_alloc);
2241 if (linenumber > 0
2242 && (linenumber != prev_line
2243 || discriminator != prev_discriminator))
2245 if (discriminator > 0)
2246 printf ("%s:%u (discriminator %u)\n",
2247 filename == NULL ? "???" : sanitize_string (filename),
2248 linenumber, discriminator);
2249 else
2250 printf ("%s:%u\n", filename == NULL
2251 ? "???" : sanitize_string (filename),
2252 linenumber);
2254 if (unwind_inlines)
2256 const char *filename2;
2257 const char *functionname2;
2258 unsigned line2;
2260 while (bfd_find_inliner_info (abfd, &filename2, &functionname2,
2261 &line2))
2263 printf ("inlined by %s:%u",
2264 sanitize_string (filename2), line2);
2265 printf (" (%s)\n", sanitize_string (functionname2));
2270 if (with_source_code
2271 && filename != NULL
2272 && linenumber > 0)
2274 struct print_file_list **pp, *p;
2275 unsigned l;
2277 for (pp = &print_files; *pp != NULL; pp = &(*pp)->next)
2278 if (filename_cmp ((*pp)->filename, filename) == 0)
2279 break;
2280 p = *pp;
2282 if (p == NULL)
2284 if (reloc)
2285 filename = xstrdup (filename);
2286 p = update_source_path (filename, abfd);
2289 if (p != NULL && linenumber != p->last_line)
2291 if (file_start_context && p->first)
2292 l = 1;
2293 else
2295 l = linenumber - SHOW_PRECEDING_CONTEXT_LINES;
2296 if (l >= linenumber)
2297 l = 1;
2298 if (p->max_printed >= l)
2300 if (p->max_printed < linenumber)
2301 l = p->max_printed + 1;
2302 else
2303 l = linenumber;
2306 dump_lines (p, l, linenumber);
2307 if (p->max_printed < linenumber)
2308 p->max_printed = linenumber;
2309 p->last_line = linenumber;
2310 p->first = 0;
2314 if (functionname != NULL
2315 && (prev_functionname == NULL
2316 || strcmp (functionname, prev_functionname) != 0))
2318 if (prev_functionname != NULL)
2319 free (prev_functionname);
2320 prev_functionname = (char *) xmalloc (strlen (functionname) + 1);
2321 strcpy (prev_functionname, functionname);
2324 if (linenumber > 0 && linenumber != prev_line)
2325 prev_line = linenumber;
2327 if (discriminator != prev_discriminator)
2328 prev_discriminator = discriminator;
2330 if (path)
2331 free (path);
2334 /* Pseudo FILE object for strings. */
2335 typedef struct
2337 char *buffer;
2338 size_t pos;
2339 size_t alloc;
2340 } SFILE;
2342 /* sprintf to a "stream". */
2344 static int ATTRIBUTE_PRINTF_2
2345 objdump_sprintf (SFILE *f, const char *format, ...)
2347 size_t n;
2348 va_list args;
2350 while (1)
2352 size_t space = f->alloc - f->pos;
2354 va_start (args, format);
2355 n = vsnprintf (f->buffer + f->pos, space, format, args);
2356 va_end (args);
2358 if (space > n)
2359 break;
2361 f->alloc = (f->alloc + n) * 2;
2362 f->buffer = (char *) xrealloc (f->buffer, f->alloc);
2364 f->pos += n;
2366 return n;
2369 /* Return an integer greater than, or equal to zero, representing the color
2370 for STYLE, or -1 if no color should be used. */
2372 static int
2373 objdump_color_for_disassembler_style (enum disassembler_style style)
2375 int color = -1;
2377 if (style == dis_style_comment_start)
2378 disassembler_in_comment = true;
2380 if (disassembler_color == on)
2382 if (disassembler_in_comment)
2383 return color;
2385 switch (style)
2387 case dis_style_symbol:
2388 color = 32;
2389 break;
2390 case dis_style_assembler_directive:
2391 case dis_style_sub_mnemonic:
2392 case dis_style_mnemonic:
2393 color = 33;
2394 break;
2395 case dis_style_register:
2396 color = 34;
2397 break;
2398 case dis_style_address:
2399 case dis_style_address_offset:
2400 case dis_style_immediate:
2401 color = 35;
2402 break;
2403 default:
2404 case dis_style_text:
2405 color = -1;
2406 break;
2409 else if (disassembler_color == extended)
2411 if (disassembler_in_comment)
2412 return 250;
2414 switch (style)
2416 case dis_style_symbol:
2417 color = 40;
2418 break;
2419 case dis_style_assembler_directive:
2420 case dis_style_sub_mnemonic:
2421 case dis_style_mnemonic:
2422 color = 142;
2423 break;
2424 case dis_style_register:
2425 color = 27;
2426 break;
2427 case dis_style_address:
2428 case dis_style_address_offset:
2429 case dis_style_immediate:
2430 color = 134;
2431 break;
2432 default:
2433 case dis_style_text:
2434 color = -1;
2435 break;
2438 else if (disassembler_color != off)
2439 bfd_fatal (_("disassembly color not correctly selected"));
2441 return color;
2444 /* Like objdump_sprintf, but add in escape sequences to highlight the
2445 content according to STYLE. */
2447 static int ATTRIBUTE_PRINTF_3
2448 objdump_styled_sprintf (SFILE *f, enum disassembler_style style,
2449 const char *format, ...)
2451 size_t n;
2452 va_list args;
2453 int color = objdump_color_for_disassembler_style (style);
2455 if (color >= 0)
2457 while (1)
2459 size_t space = f->alloc - f->pos;
2461 if (disassembler_color == on)
2462 n = snprintf (f->buffer + f->pos, space, "\033[%dm", color);
2463 else
2464 n = snprintf (f->buffer + f->pos, space, "\033[38;5;%dm", color);
2465 if (space > n)
2466 break;
2468 f->alloc = (f->alloc + n) * 2;
2469 f->buffer = (char *) xrealloc (f->buffer, f->alloc);
2471 f->pos += n;
2474 while (1)
2476 size_t space = f->alloc - f->pos;
2478 va_start (args, format);
2479 n = vsnprintf (f->buffer + f->pos, space, format, args);
2480 va_end (args);
2482 if (space > n)
2483 break;
2485 f->alloc = (f->alloc + n) * 2;
2486 f->buffer = (char *) xrealloc (f->buffer, f->alloc);
2488 f->pos += n;
2490 if (color >= 0)
2492 while (1)
2494 size_t space = f->alloc - f->pos;
2496 n = snprintf (f->buffer + f->pos, space, "\033[0m");
2498 if (space > n)
2499 break;
2501 f->alloc = (f->alloc + n) * 2;
2502 f->buffer = (char *) xrealloc (f->buffer, f->alloc);
2504 f->pos += n;
2507 return n;
2510 /* We discard the styling information here. This function is only used
2511 when objdump is printing auxiliary information, the symbol headers, and
2512 disassembly address, or the bytes of the disassembled instruction. We
2513 don't (currently) apply styling to any of this stuff, so, for now, just
2514 print the content with no additional style added. */
2516 static int ATTRIBUTE_PRINTF_3
2517 fprintf_styled (FILE *f, enum disassembler_style style ATTRIBUTE_UNUSED,
2518 const char *fmt, ...)
2520 int res;
2521 va_list ap;
2523 va_start (ap, fmt);
2524 res = vfprintf (f, fmt, ap);
2525 va_end (ap);
2527 return res;
2530 /* Code for generating (colored) diagrams of control flow start and end
2531 points. */
2533 /* Structure used to store the properties of a jump. */
2535 struct jump_info
2537 /* The next jump, or NULL if this is the last object. */
2538 struct jump_info *next;
2539 /* The previous jump, or NULL if this is the first object. */
2540 struct jump_info *prev;
2541 /* The start addresses of the jump. */
2542 struct
2544 /* The list of start addresses. */
2545 bfd_vma *addresses;
2546 /* The number of elements. */
2547 size_t count;
2548 /* The maximum number of elements that fit into the array. */
2549 size_t max_count;
2550 } start;
2551 /* The end address of the jump. */
2552 bfd_vma end;
2553 /* The drawing level of the jump. */
2554 int level;
2557 /* Construct a jump object for a jump from start
2558 to end with the corresponding level. */
2560 static struct jump_info *
2561 jump_info_new (bfd_vma start, bfd_vma end, int level)
2563 struct jump_info *result = xmalloc (sizeof (struct jump_info));
2565 result->next = NULL;
2566 result->prev = NULL;
2567 result->start.addresses = xmalloc (sizeof (bfd_vma *) * 2);
2568 result->start.addresses[0] = start;
2569 result->start.count = 1;
2570 result->start.max_count = 2;
2571 result->end = end;
2572 result->level = level;
2574 return result;
2577 /* Free a jump object and return the next object
2578 or NULL if this was the last one. */
2580 static struct jump_info *
2581 jump_info_free (struct jump_info *ji)
2583 struct jump_info *result = NULL;
2585 if (ji)
2587 result = ji->next;
2588 if (ji->start.addresses)
2589 free (ji->start.addresses);
2590 free (ji);
2593 return result;
2596 /* Get the smallest value of all start and end addresses. */
2598 static bfd_vma
2599 jump_info_min_address (const struct jump_info *ji)
2601 bfd_vma min_address = ji->end;
2602 size_t i;
2604 for (i = ji->start.count; i-- > 0;)
2605 if (ji->start.addresses[i] < min_address)
2606 min_address = ji->start.addresses[i];
2607 return min_address;
2610 /* Get the largest value of all start and end addresses. */
2612 static bfd_vma
2613 jump_info_max_address (const struct jump_info *ji)
2615 bfd_vma max_address = ji->end;
2616 size_t i;
2618 for (i = ji->start.count; i-- > 0;)
2619 if (ji->start.addresses[i] > max_address)
2620 max_address = ji->start.addresses[i];
2621 return max_address;
2624 /* Get the target address of a jump. */
2626 static bfd_vma
2627 jump_info_end_address (const struct jump_info *ji)
2629 return ji->end;
2632 /* Test if an address is one of the start addresses of a jump. */
2634 static bool
2635 jump_info_is_start_address (const struct jump_info *ji, bfd_vma address)
2637 bool result = false;
2638 size_t i;
2640 for (i = ji->start.count; i-- > 0;)
2641 if (address == ji->start.addresses[i])
2643 result = true;
2644 break;
2647 return result;
2650 /* Test if an address is the target address of a jump. */
2652 static bool
2653 jump_info_is_end_address (const struct jump_info *ji, bfd_vma address)
2655 return (address == ji->end);
2658 /* Get the difference between the smallest and largest address of a jump. */
2660 static bfd_vma
2661 jump_info_size (const struct jump_info *ji)
2663 return jump_info_max_address (ji) - jump_info_min_address (ji);
2666 /* Unlink a jump object from a list. */
2668 static void
2669 jump_info_unlink (struct jump_info *node,
2670 struct jump_info **base)
2672 if (node->next)
2673 node->next->prev = node->prev;
2674 if (node->prev)
2675 node->prev->next = node->next;
2676 else
2677 *base = node->next;
2678 node->next = NULL;
2679 node->prev = NULL;
2682 /* Insert unlinked jump info node into a list. */
2684 static void
2685 jump_info_insert (struct jump_info *node,
2686 struct jump_info *target,
2687 struct jump_info **base)
2689 node->next = target;
2690 node->prev = target->prev;
2691 target->prev = node;
2692 if (node->prev)
2693 node->prev->next = node;
2694 else
2695 *base = node;
2698 /* Add unlinked node to the front of a list. */
2700 static void
2701 jump_info_add_front (struct jump_info *node,
2702 struct jump_info **base)
2704 node->next = *base;
2705 if (node->next)
2706 node->next->prev = node;
2707 node->prev = NULL;
2708 *base = node;
2711 /* Move linked node to target position. */
2713 static void
2714 jump_info_move_linked (struct jump_info *node,
2715 struct jump_info *target,
2716 struct jump_info **base)
2718 /* Unlink node. */
2719 jump_info_unlink (node, base);
2720 /* Insert node at target position. */
2721 jump_info_insert (node, target, base);
2724 /* Test if two jumps intersect. */
2726 static bool
2727 jump_info_intersect (const struct jump_info *a,
2728 const struct jump_info *b)
2730 return ((jump_info_max_address (a) >= jump_info_min_address (b))
2731 && (jump_info_min_address (a) <= jump_info_max_address (b)));
2734 /* Merge two compatible jump info objects. */
2736 static void
2737 jump_info_merge (struct jump_info **base)
2739 struct jump_info *a;
2741 for (a = *base; a; a = a->next)
2743 struct jump_info *b;
2745 for (b = a->next; b; b = b->next)
2747 /* Merge both jumps into one. */
2748 if (a->end == b->end)
2750 /* Reallocate addresses. */
2751 size_t needed_size = a->start.count + b->start.count;
2752 size_t i;
2754 if (needed_size > a->start.max_count)
2756 a->start.max_count += b->start.max_count;
2757 a->start.addresses =
2758 xrealloc (a->start.addresses,
2759 a->start.max_count * sizeof (bfd_vma *));
2762 /* Append start addresses. */
2763 for (i = 0; i < b->start.count; ++i)
2764 a->start.addresses[a->start.count++] =
2765 b->start.addresses[i];
2767 /* Remove and delete jump. */
2768 struct jump_info *tmp = b->prev;
2769 jump_info_unlink (b, base);
2770 jump_info_free (b);
2771 b = tmp;
2777 /* Sort jumps by their size and starting point using a stable
2778 minsort. This could be improved if sorting performance is
2779 an issue, for example by using mergesort. */
2781 static void
2782 jump_info_sort (struct jump_info **base)
2784 struct jump_info *current_element = *base;
2786 while (current_element)
2788 struct jump_info *best_match = current_element;
2789 struct jump_info *runner = current_element->next;
2790 bfd_vma best_size = jump_info_size (best_match);
2792 while (runner)
2794 bfd_vma runner_size = jump_info_size (runner);
2796 if ((runner_size < best_size)
2797 || ((runner_size == best_size)
2798 && (jump_info_min_address (runner)
2799 < jump_info_min_address (best_match))))
2801 best_match = runner;
2802 best_size = runner_size;
2805 runner = runner->next;
2808 if (best_match == current_element)
2809 current_element = current_element->next;
2810 else
2811 jump_info_move_linked (best_match, current_element, base);
2815 /* Visualize all jumps at a given address. */
2817 static void
2818 jump_info_visualize_address (bfd_vma address,
2819 int max_level,
2820 char *line_buffer,
2821 uint8_t *color_buffer)
2823 struct jump_info *ji = detected_jumps;
2824 size_t len = (max_level + 1) * 3;
2826 /* Clear line buffer. */
2827 memset (line_buffer, ' ', len);
2828 memset (color_buffer, 0, len);
2830 /* Iterate over jumps and add their ASCII art. */
2831 while (ji)
2833 /* Discard jumps that are never needed again. */
2834 if (jump_info_max_address (ji) < address)
2836 struct jump_info *tmp = ji;
2838 ji = ji->next;
2839 jump_info_unlink (tmp, &detected_jumps);
2840 jump_info_free (tmp);
2841 continue;
2844 /* This jump intersects with the current address. */
2845 if (jump_info_min_address (ji) <= address)
2847 /* Hash target address to get an even
2848 distribution between all values. */
2849 bfd_vma hash_address = jump_info_end_address (ji);
2850 uint8_t color = iterative_hash_object (hash_address, 0);
2851 /* Fetch line offset. */
2852 int offset = (max_level - ji->level) * 3;
2854 /* Draw start line. */
2855 if (jump_info_is_start_address (ji, address))
2857 size_t i = offset + 1;
2859 for (; i < len - 1; ++i)
2860 if (line_buffer[i] == ' ')
2862 line_buffer[i] = '-';
2863 color_buffer[i] = color;
2866 if (line_buffer[i] == ' ')
2868 line_buffer[i] = '-';
2869 color_buffer[i] = color;
2871 else if (line_buffer[i] == '>')
2873 line_buffer[i] = 'X';
2874 color_buffer[i] = color;
2877 if (line_buffer[offset] == ' ')
2879 if (address <= ji->end)
2880 line_buffer[offset] =
2881 (jump_info_min_address (ji) == address) ? '/': '+';
2882 else
2883 line_buffer[offset] =
2884 (jump_info_max_address (ji) == address) ? '\\': '+';
2885 color_buffer[offset] = color;
2888 /* Draw jump target. */
2889 else if (jump_info_is_end_address (ji, address))
2891 size_t i = offset + 1;
2893 for (; i < len - 1; ++i)
2894 if (line_buffer[i] == ' ')
2896 line_buffer[i] = '-';
2897 color_buffer[i] = color;
2900 if (line_buffer[i] == ' ')
2902 line_buffer[i] = '>';
2903 color_buffer[i] = color;
2905 else if (line_buffer[i] == '-')
2907 line_buffer[i] = 'X';
2908 color_buffer[i] = color;
2911 if (line_buffer[offset] == ' ')
2913 if (jump_info_min_address (ji) < address)
2914 line_buffer[offset] =
2915 (jump_info_max_address (ji) > address) ? '>' : '\\';
2916 else
2917 line_buffer[offset] = '/';
2918 color_buffer[offset] = color;
2921 /* Draw intermediate line segment. */
2922 else if (line_buffer[offset] == ' ')
2924 line_buffer[offset] = '|';
2925 color_buffer[offset] = color;
2929 ji = ji->next;
2933 /* Clone of disassemble_bytes to detect jumps inside a function. */
2934 /* FIXME: is this correct? Can we strip it down even further? */
2936 static struct jump_info *
2937 disassemble_jumps (struct disassemble_info * inf,
2938 disassembler_ftype disassemble_fn,
2939 bfd_vma start_offset,
2940 bfd_vma stop_offset,
2941 bfd_vma rel_offset,
2942 arelent *** relppp,
2943 arelent ** relppend)
2945 struct objdump_disasm_info *aux;
2946 struct jump_info *jumps = NULL;
2947 asection *section;
2948 bfd_vma addr_offset;
2949 unsigned int opb = inf->octets_per_byte;
2950 int octets = opb;
2951 SFILE sfile;
2953 aux = (struct objdump_disasm_info *) inf->application_data;
2954 section = inf->section;
2956 sfile.alloc = 120;
2957 sfile.buffer = (char *) xmalloc (sfile.alloc);
2958 sfile.pos = 0;
2960 inf->insn_info_valid = 0;
2961 disassemble_set_printf (inf, &sfile, (fprintf_ftype) objdump_sprintf,
2962 (fprintf_styled_ftype) objdump_styled_sprintf);
2964 addr_offset = start_offset;
2965 while (addr_offset < stop_offset)
2967 int previous_octets;
2969 /* Remember the length of the previous instruction. */
2970 previous_octets = octets;
2971 octets = 0;
2973 sfile.pos = 0;
2974 inf->bytes_per_line = 0;
2975 inf->bytes_per_chunk = 0;
2976 inf->flags = ((disassemble_all ? DISASSEMBLE_DATA : 0)
2977 | (wide_output ? WIDE_OUTPUT : 0));
2978 if (machine)
2979 inf->flags |= USER_SPECIFIED_MACHINE_TYPE;
2981 if (inf->disassembler_needs_relocs
2982 && (bfd_get_file_flags (aux->abfd) & EXEC_P) == 0
2983 && (bfd_get_file_flags (aux->abfd) & DYNAMIC) == 0
2984 && *relppp < relppend)
2986 bfd_signed_vma distance_to_rel;
2988 distance_to_rel = (**relppp)->address - (rel_offset + addr_offset);
2990 /* Check to see if the current reloc is associated with
2991 the instruction that we are about to disassemble. */
2992 if (distance_to_rel == 0
2993 /* FIXME: This is wrong. We are trying to catch
2994 relocs that are addressed part way through the
2995 current instruction, as might happen with a packed
2996 VLIW instruction. Unfortunately we do not know the
2997 length of the current instruction since we have not
2998 disassembled it yet. Instead we take a guess based
2999 upon the length of the previous instruction. The
3000 proper solution is to have a new target-specific
3001 disassembler function which just returns the length
3002 of an instruction at a given address without trying
3003 to display its disassembly. */
3004 || (distance_to_rel > 0
3005 && distance_to_rel < (bfd_signed_vma) (previous_octets/ opb)))
3007 inf->flags |= INSN_HAS_RELOC;
3011 if (! disassemble_all
3012 && (section->flags & (SEC_CODE | SEC_HAS_CONTENTS))
3013 == (SEC_CODE | SEC_HAS_CONTENTS))
3014 /* Set a stop_vma so that the disassembler will not read
3015 beyond the next symbol. We assume that symbols appear on
3016 the boundaries between instructions. We only do this when
3017 disassembling code of course, and when -D is in effect. */
3018 inf->stop_vma = section->vma + stop_offset;
3020 inf->stop_offset = stop_offset;
3022 /* Extract jump information. */
3023 inf->insn_info_valid = 0;
3024 disassembler_in_comment = false;
3025 octets = (*disassemble_fn) (section->vma + addr_offset, inf);
3026 /* Test if a jump was detected. */
3027 if (inf->insn_info_valid
3028 && ((inf->insn_type == dis_branch)
3029 || (inf->insn_type == dis_condbranch)
3030 || (inf->insn_type == dis_jsr)
3031 || (inf->insn_type == dis_condjsr))
3032 && (inf->target >= section->vma + start_offset)
3033 && (inf->target < section->vma + stop_offset))
3035 struct jump_info *ji =
3036 jump_info_new (section->vma + addr_offset, inf->target, -1);
3037 jump_info_add_front (ji, &jumps);
3040 inf->stop_vma = 0;
3042 addr_offset += octets / opb;
3045 disassemble_set_printf (inf, (void *) stdout, (fprintf_ftype) fprintf,
3046 (fprintf_styled_ftype) fprintf_styled);
3047 free (sfile.buffer);
3049 /* Merge jumps. */
3050 jump_info_merge (&jumps);
3051 /* Process jumps. */
3052 jump_info_sort (&jumps);
3054 /* Group jumps by level. */
3055 struct jump_info *last_jump = jumps;
3056 int max_level = -1;
3058 while (last_jump)
3060 /* The last jump is part of the next group. */
3061 struct jump_info *base = last_jump;
3062 /* Increment level. */
3063 base->level = ++max_level;
3065 /* Find jumps that can be combined on the same
3066 level, with the largest jumps tested first.
3067 This has the advantage that large jumps are on
3068 lower levels and do not intersect with small
3069 jumps that get grouped on higher levels. */
3070 struct jump_info *exchange_item = last_jump->next;
3071 struct jump_info *it = exchange_item;
3073 for (; it; it = it->next)
3075 /* Test if the jump intersects with any
3076 jump from current group. */
3077 bool ok = true;
3078 struct jump_info *it_collision;
3080 for (it_collision = base;
3081 it_collision != exchange_item;
3082 it_collision = it_collision->next)
3084 /* This jump intersects so we leave it out. */
3085 if (jump_info_intersect (it_collision, it))
3087 ok = false;
3088 break;
3092 /* Add jump to group. */
3093 if (ok)
3095 /* Move current element to the front. */
3096 if (it != exchange_item)
3098 struct jump_info *save = it->prev;
3099 jump_info_move_linked (it, exchange_item, &jumps);
3100 last_jump = it;
3101 it = save;
3103 else
3105 last_jump = exchange_item;
3106 exchange_item = exchange_item->next;
3108 last_jump->level = max_level;
3112 /* Move to next group. */
3113 last_jump = exchange_item;
3116 return jumps;
3119 /* The number of zeroes we want to see before we start skipping them.
3120 The number is arbitrarily chosen. */
3122 #define DEFAULT_SKIP_ZEROES 8
3124 /* The number of zeroes to skip at the end of a section. If the
3125 number of zeroes at the end is between SKIP_ZEROES_AT_END and
3126 SKIP_ZEROES, they will be disassembled. If there are fewer than
3127 SKIP_ZEROES_AT_END, they will be skipped. This is a heuristic
3128 attempt to avoid disassembling zeroes inserted by section
3129 alignment. */
3131 #define DEFAULT_SKIP_ZEROES_AT_END 3
3133 static int
3134 null_print (const void * stream ATTRIBUTE_UNUSED, const char * format ATTRIBUTE_UNUSED, ...)
3136 return 1;
3139 /* Like null_print, but takes the extra STYLE argument. As this is not
3140 going to print anything, the extra argument is just ignored. */
3142 static int
3143 null_styled_print (const void * stream ATTRIBUTE_UNUSED,
3144 enum disassembler_style style ATTRIBUTE_UNUSED,
3145 const char * format ATTRIBUTE_UNUSED, ...)
3147 return 1;
3150 /* Print out jump visualization. */
3152 static void
3153 print_jump_visualisation (bfd_vma addr, int max_level, char *line_buffer,
3154 uint8_t *color_buffer)
3156 if (!line_buffer)
3157 return;
3159 jump_info_visualize_address (addr, max_level, line_buffer, color_buffer);
3161 size_t line_buffer_size = strlen (line_buffer);
3162 char last_color = 0;
3163 size_t i;
3165 for (i = 0; i <= line_buffer_size; ++i)
3167 if (color_output)
3169 uint8_t color = (i < line_buffer_size) ? color_buffer[i]: 0;
3171 if (color != last_color)
3173 if (color)
3174 if (extended_color_output)
3175 /* Use extended 8bit color, but
3176 do not choose dark colors. */
3177 printf ("\033[38;5;%dm", 124 + (color % 108));
3178 else
3179 /* Use simple terminal colors. */
3180 printf ("\033[%dm", 31 + (color % 7));
3181 else
3182 /* Clear color. */
3183 printf ("\033[0m");
3184 last_color = color;
3187 putchar ((i < line_buffer_size) ? line_buffer[i]: ' ');
3191 /* Disassemble some data in memory between given values. */
3193 static void
3194 disassemble_bytes (struct disassemble_info *inf,
3195 disassembler_ftype disassemble_fn,
3196 bool insns,
3197 bfd_byte *data,
3198 bfd_vma start_offset,
3199 bfd_vma stop_offset,
3200 bfd_vma rel_offset,
3201 arelent ***relppp,
3202 arelent **relppend)
3204 struct objdump_disasm_info *aux;
3205 asection *section;
3206 unsigned int octets_per_line;
3207 unsigned int skip_addr_chars;
3208 bfd_vma addr_offset;
3209 unsigned int opb = inf->octets_per_byte;
3210 unsigned int skip_zeroes = inf->skip_zeroes;
3211 unsigned int skip_zeroes_at_end = inf->skip_zeroes_at_end;
3212 size_t octets;
3213 SFILE sfile;
3215 aux = (struct objdump_disasm_info *) inf->application_data;
3216 section = inf->section;
3218 sfile.alloc = 120;
3219 sfile.buffer = (char *) xmalloc (sfile.alloc);
3220 sfile.pos = 0;
3222 if (insn_width)
3223 octets_per_line = insn_width;
3224 else if (insns)
3225 octets_per_line = 4;
3226 else
3227 octets_per_line = 16;
3229 /* Figure out how many characters to skip at the start of an
3230 address, to make the disassembly look nicer. We discard leading
3231 zeroes in chunks of 4, ensuring that there is always a leading
3232 zero remaining. */
3233 skip_addr_chars = 0;
3234 if (!no_addresses && !prefix_addresses)
3236 char buf[30];
3238 bfd_sprintf_vma (aux->abfd, buf, section->vma + section->size / opb);
3240 while (buf[skip_addr_chars] == '0')
3241 ++skip_addr_chars;
3243 /* Don't discard zeros on overflow. */
3244 if (buf[skip_addr_chars] == '\0' && section->vma != 0)
3245 skip_addr_chars = 0;
3247 if (skip_addr_chars != 0)
3248 skip_addr_chars = (skip_addr_chars - 1) & -4;
3251 inf->insn_info_valid = 0;
3253 /* Determine maximum level. */
3254 uint8_t *color_buffer = NULL;
3255 char *line_buffer = NULL;
3256 int max_level = -1;
3258 /* Some jumps were detected. */
3259 if (detected_jumps)
3261 struct jump_info *ji;
3263 /* Find maximum jump level. */
3264 for (ji = detected_jumps; ji; ji = ji->next)
3266 if (ji->level > max_level)
3267 max_level = ji->level;
3270 /* Allocate buffers. */
3271 size_t len = (max_level + 1) * 3 + 1;
3272 line_buffer = xmalloc (len);
3273 line_buffer[len - 1] = 0;
3274 color_buffer = xmalloc (len);
3275 color_buffer[len - 1] = 0;
3278 addr_offset = start_offset;
3279 while (addr_offset < stop_offset)
3281 bool need_nl = false;
3283 octets = 0;
3285 /* Make sure we don't use relocs from previous instructions. */
3286 aux->reloc = NULL;
3288 /* If we see more than SKIP_ZEROES octets of zeroes, we just
3289 print `...'. */
3290 if (! disassemble_zeroes)
3291 for (; addr_offset * opb + octets < stop_offset * opb; octets++)
3292 if (data[addr_offset * opb + octets] != 0)
3293 break;
3294 if (! disassemble_zeroes
3295 && (inf->insn_info_valid == 0
3296 || inf->branch_delay_insns == 0)
3297 && (octets >= skip_zeroes
3298 || (addr_offset * opb + octets == stop_offset * opb
3299 && octets < skip_zeroes_at_end)))
3301 /* If there are more nonzero octets to follow, we only skip
3302 zeroes in multiples of 4, to try to avoid running over
3303 the start of an instruction which happens to start with
3304 zero. */
3305 if (addr_offset * opb + octets != stop_offset * opb)
3306 octets &= ~3;
3308 /* If we are going to display more data, and we are displaying
3309 file offsets, then tell the user how many zeroes we skip
3310 and the file offset from where we resume dumping. */
3311 if (display_file_offsets
3312 && addr_offset + octets / opb < stop_offset)
3313 printf (_("\t... (skipping %lu zeroes, "
3314 "resuming at file offset: 0x%lx)\n"),
3315 (unsigned long) (octets / opb),
3316 (unsigned long) (section->filepos
3317 + addr_offset + octets / opb));
3318 else
3319 printf ("\t...\n");
3321 else
3323 char buf[50];
3324 unsigned int bpc = 0;
3325 unsigned int pb = 0;
3327 if (with_line_numbers || with_source_code)
3328 show_line (aux->abfd, section, addr_offset);
3330 if (no_addresses)
3331 printf ("\t");
3332 else if (!prefix_addresses)
3334 char *s;
3336 bfd_sprintf_vma (aux->abfd, buf, section->vma + addr_offset);
3337 for (s = buf + skip_addr_chars; *s == '0'; s++)
3338 *s = ' ';
3339 if (*s == '\0')
3340 *--s = '0';
3341 printf ("%s:\t", buf + skip_addr_chars);
3343 else
3345 aux->require_sec = true;
3346 objdump_print_address (section->vma + addr_offset, inf);
3347 aux->require_sec = false;
3348 putchar (' ');
3351 print_jump_visualisation (section->vma + addr_offset,
3352 max_level, line_buffer,
3353 color_buffer);
3355 if (insns)
3357 int insn_size;
3359 sfile.pos = 0;
3360 disassemble_set_printf
3361 (inf, &sfile, (fprintf_ftype) objdump_sprintf,
3362 (fprintf_styled_ftype) objdump_styled_sprintf);
3363 inf->bytes_per_line = 0;
3364 inf->bytes_per_chunk = 0;
3365 inf->flags = ((disassemble_all ? DISASSEMBLE_DATA : 0)
3366 | (wide_output ? WIDE_OUTPUT : 0));
3367 if (machine)
3368 inf->flags |= USER_SPECIFIED_MACHINE_TYPE;
3370 if (inf->disassembler_needs_relocs
3371 && (bfd_get_file_flags (aux->abfd) & EXEC_P) == 0
3372 && (bfd_get_file_flags (aux->abfd) & DYNAMIC) == 0
3373 && *relppp < relppend)
3375 bfd_signed_vma distance_to_rel;
3376 int max_reloc_offset
3377 = aux->abfd->arch_info->max_reloc_offset_into_insn;
3379 distance_to_rel = ((**relppp)->address - rel_offset
3380 - addr_offset);
3382 insn_size = 0;
3383 if (distance_to_rel > 0
3384 && (max_reloc_offset < 0
3385 || distance_to_rel <= max_reloc_offset))
3387 /* This reloc *might* apply to the current insn,
3388 starting somewhere inside it. Discover the length
3389 of the current insn so that the check below will
3390 work. */
3391 if (insn_width)
3392 insn_size = insn_width;
3393 else
3395 /* We find the length by calling the dissassembler
3396 function with a dummy print handler. This should
3397 work unless the disassembler is not expecting to
3398 be called multiple times for the same address.
3400 This does mean disassembling the instruction
3401 twice, but we only do this when there is a high
3402 probability that there is a reloc that will
3403 affect the instruction. */
3404 disassemble_set_printf
3405 (inf, inf->stream, (fprintf_ftype) null_print,
3406 (fprintf_styled_ftype) null_styled_print);
3407 insn_size = disassemble_fn (section->vma
3408 + addr_offset, inf);
3409 disassemble_set_printf
3410 (inf, inf->stream,
3411 (fprintf_ftype) objdump_sprintf,
3412 (fprintf_styled_ftype) objdump_styled_sprintf);
3416 /* Check to see if the current reloc is associated with
3417 the instruction that we are about to disassemble. */
3418 if (distance_to_rel == 0
3419 || (distance_to_rel > 0
3420 && distance_to_rel < insn_size / (int) opb))
3422 inf->flags |= INSN_HAS_RELOC;
3423 aux->reloc = **relppp;
3427 if (! disassemble_all
3428 && ((section->flags & (SEC_CODE | SEC_HAS_CONTENTS))
3429 == (SEC_CODE | SEC_HAS_CONTENTS)))
3430 /* Set a stop_vma so that the disassembler will not read
3431 beyond the next symbol. We assume that symbols appear on
3432 the boundaries between instructions. We only do this when
3433 disassembling code of course, and when -D is in effect. */
3434 inf->stop_vma = section->vma + stop_offset;
3436 inf->stop_offset = stop_offset;
3437 disassembler_in_comment = false;
3438 insn_size = (*disassemble_fn) (section->vma + addr_offset, inf);
3439 octets = insn_size;
3441 inf->stop_vma = 0;
3442 disassemble_set_printf (inf, stdout, (fprintf_ftype) fprintf,
3443 (fprintf_styled_ftype) fprintf_styled);
3444 if (insn_width == 0 && inf->bytes_per_line != 0)
3445 octets_per_line = inf->bytes_per_line;
3446 if (insn_size < (int) opb)
3448 if (sfile.pos)
3449 printf ("%s\n", sfile.buffer);
3450 if (insn_size >= 0)
3452 non_fatal (_("disassemble_fn returned length %d"),
3453 insn_size);
3454 exit_status = 1;
3456 break;
3459 else
3461 bfd_vma j;
3463 octets = octets_per_line;
3464 if (addr_offset + octets / opb > stop_offset)
3465 octets = (stop_offset - addr_offset) * opb;
3467 for (j = addr_offset * opb; j < addr_offset * opb + octets; ++j)
3469 if (ISPRINT (data[j]))
3470 buf[j - addr_offset * opb] = data[j];
3471 else
3472 buf[j - addr_offset * opb] = '.';
3474 buf[j - addr_offset * opb] = '\0';
3477 if (prefix_addresses
3478 ? show_raw_insn > 0
3479 : show_raw_insn >= 0)
3481 bfd_vma j;
3483 /* If ! prefix_addresses and ! wide_output, we print
3484 octets_per_line octets per line. */
3485 pb = octets;
3486 if (pb > octets_per_line && ! prefix_addresses && ! wide_output)
3487 pb = octets_per_line;
3489 if (inf->bytes_per_chunk)
3490 bpc = inf->bytes_per_chunk;
3491 else
3492 bpc = 1;
3494 for (j = addr_offset * opb; j < addr_offset * opb + pb; j += bpc)
3496 /* PR 21580: Check for a buffer ending early. */
3497 if (j + bpc <= stop_offset * opb)
3499 unsigned int k;
3501 if (inf->display_endian == BFD_ENDIAN_LITTLE)
3503 for (k = bpc; k-- != 0; )
3504 printf ("%02x", (unsigned) data[j + k]);
3506 else
3508 for (k = 0; k < bpc; k++)
3509 printf ("%02x", (unsigned) data[j + k]);
3512 putchar (' ');
3515 for (; pb < octets_per_line; pb += bpc)
3517 unsigned int k;
3519 for (k = 0; k < bpc; k++)
3520 printf (" ");
3521 putchar (' ');
3524 /* Separate raw data from instruction by extra space. */
3525 if (insns)
3526 putchar ('\t');
3527 else
3528 printf (" ");
3531 if (! insns)
3532 printf ("%s", buf);
3533 else if (sfile.pos)
3534 printf ("%s", sfile.buffer);
3536 if (prefix_addresses
3537 ? show_raw_insn > 0
3538 : show_raw_insn >= 0)
3540 while (pb < octets)
3542 bfd_vma j;
3543 char *s;
3545 putchar ('\n');
3546 j = addr_offset * opb + pb;
3548 if (no_addresses)
3549 printf ("\t");
3550 else
3552 bfd_sprintf_vma (aux->abfd, buf, section->vma + j / opb);
3553 for (s = buf + skip_addr_chars; *s == '0'; s++)
3554 *s = ' ';
3555 if (*s == '\0')
3556 *--s = '0';
3557 printf ("%s:\t", buf + skip_addr_chars);
3560 print_jump_visualisation (section->vma + j / opb,
3561 max_level, line_buffer,
3562 color_buffer);
3564 pb += octets_per_line;
3565 if (pb > octets)
3566 pb = octets;
3567 for (; j < addr_offset * opb + pb; j += bpc)
3569 /* PR 21619: Check for a buffer ending early. */
3570 if (j + bpc <= stop_offset * opb)
3572 unsigned int k;
3574 if (inf->display_endian == BFD_ENDIAN_LITTLE)
3576 for (k = bpc; k-- != 0; )
3577 printf ("%02x", (unsigned) data[j + k]);
3579 else
3581 for (k = 0; k < bpc; k++)
3582 printf ("%02x", (unsigned) data[j + k]);
3585 putchar (' ');
3590 if (!wide_output)
3591 putchar ('\n');
3592 else
3593 need_nl = true;
3596 while ((*relppp) < relppend
3597 && (**relppp)->address < rel_offset + addr_offset + octets / opb)
3599 if (dump_reloc_info || dump_dynamic_reloc_info)
3601 arelent *q;
3603 q = **relppp;
3605 if (wide_output)
3606 putchar ('\t');
3607 else
3608 printf ("\t\t\t");
3610 if (!no_addresses)
3612 objdump_print_value (section->vma - rel_offset + q->address,
3613 inf, true);
3614 printf (": ");
3617 if (q->howto == NULL)
3618 printf ("*unknown*\t");
3619 else if (q->howto->name)
3620 printf ("%s\t", q->howto->name);
3621 else
3622 printf ("%d\t", q->howto->type);
3624 if (q->sym_ptr_ptr == NULL || *q->sym_ptr_ptr == NULL)
3625 printf ("*unknown*");
3626 else
3628 const char *sym_name;
3630 sym_name = bfd_asymbol_name (*q->sym_ptr_ptr);
3631 if (sym_name != NULL && *sym_name != '\0')
3632 objdump_print_symname (aux->abfd, inf, *q->sym_ptr_ptr);
3633 else
3635 asection *sym_sec;
3637 sym_sec = bfd_asymbol_section (*q->sym_ptr_ptr);
3638 sym_name = bfd_section_name (sym_sec);
3639 if (sym_name == NULL || *sym_name == '\0')
3640 sym_name = "*unknown*";
3641 printf ("%s", sanitize_string (sym_name));
3645 if (q->addend)
3647 bfd_vma addend = q->addend;
3648 if ((bfd_signed_vma) addend < 0)
3650 printf ("-0x");
3651 addend = -addend;
3653 else
3654 printf ("+0x");
3655 objdump_print_value (addend, inf, true);
3658 printf ("\n");
3659 need_nl = false;
3661 ++(*relppp);
3664 if (need_nl)
3665 printf ("\n");
3667 addr_offset += octets / opb;
3670 free (sfile.buffer);
3671 free (line_buffer);
3672 free (color_buffer);
3675 static void
3676 disassemble_section (bfd *abfd, asection *section, void *inf)
3678 const struct elf_backend_data *bed;
3679 bfd_vma sign_adjust = 0;
3680 struct disassemble_info *pinfo = (struct disassemble_info *) inf;
3681 struct objdump_disasm_info *paux;
3682 unsigned int opb = pinfo->octets_per_byte;
3683 bfd_byte *data = NULL;
3684 bfd_size_type datasize = 0;
3685 arelent **rel_pp = NULL;
3686 arelent **rel_ppstart = NULL;
3687 arelent **rel_ppend;
3688 bfd_vma stop_offset;
3689 asymbol *sym = NULL;
3690 long place = 0;
3691 long rel_count;
3692 bfd_vma rel_offset;
3693 unsigned long addr_offset;
3694 bool do_print;
3695 enum loop_control
3697 stop_offset_reached,
3698 function_sym,
3699 next_sym
3700 } loop_until;
3702 if (only_list == NULL)
3704 /* Sections that do not contain machine
3705 code are not normally disassembled. */
3706 if ((section->flags & SEC_HAS_CONTENTS) == 0)
3707 return;
3709 if (! disassemble_all
3710 && (section->flags & SEC_CODE) == 0)
3711 return;
3713 else if (!process_section_p (section))
3714 return;
3716 datasize = bfd_section_size (section);
3717 if (datasize == 0)
3718 return;
3720 if (start_address == (bfd_vma) -1
3721 || start_address < section->vma)
3722 addr_offset = 0;
3723 else
3724 addr_offset = start_address - section->vma;
3726 if (stop_address == (bfd_vma) -1)
3727 stop_offset = datasize / opb;
3728 else
3730 if (stop_address < section->vma)
3731 stop_offset = 0;
3732 else
3733 stop_offset = stop_address - section->vma;
3734 if (stop_offset > datasize / opb)
3735 stop_offset = datasize / opb;
3738 if (addr_offset >= stop_offset)
3739 return;
3741 /* Decide which set of relocs to use. Load them if necessary. */
3742 paux = (struct objdump_disasm_info *) pinfo->application_data;
3743 if (pinfo->dynrelbuf && dump_dynamic_reloc_info)
3745 rel_pp = pinfo->dynrelbuf;
3746 rel_count = pinfo->dynrelcount;
3747 /* Dynamic reloc addresses are absolute, non-dynamic are section
3748 relative. REL_OFFSET specifies the reloc address corresponding
3749 to the start of this section. */
3750 rel_offset = section->vma;
3752 else
3754 rel_count = 0;
3755 rel_pp = NULL;
3756 rel_offset = 0;
3758 if ((section->flags & SEC_RELOC) != 0
3759 && (dump_reloc_info || pinfo->disassembler_needs_relocs))
3761 long relsize;
3763 relsize = bfd_get_reloc_upper_bound (abfd, section);
3764 if (relsize < 0)
3765 my_bfd_nonfatal (bfd_get_filename (abfd));
3767 if (relsize > 0)
3769 rel_pp = (arelent **) xmalloc (relsize);
3770 rel_count = bfd_canonicalize_reloc (abfd, section, rel_pp, syms);
3771 if (rel_count < 0)
3773 my_bfd_nonfatal (bfd_get_filename (abfd));
3774 free (rel_pp);
3775 rel_pp = NULL;
3776 rel_count = 0;
3778 else if (rel_count > 1)
3779 /* Sort the relocs by address. */
3780 qsort (rel_pp, rel_count, sizeof (arelent *), compare_relocs);
3781 rel_ppstart = rel_pp;
3785 rel_ppend = PTR_ADD (rel_pp, rel_count);
3787 if (!bfd_malloc_and_get_section (abfd, section, &data))
3789 non_fatal (_("Reading section %s failed because: %s"),
3790 section->name, bfd_errmsg (bfd_get_error ()));
3791 return;
3794 pinfo->buffer = data;
3795 pinfo->buffer_vma = section->vma;
3796 pinfo->buffer_length = datasize;
3797 pinfo->section = section;
3799 /* Sort the symbols into value and section order. */
3800 compare_section = section;
3801 if (sorted_symcount > 1)
3802 qsort (sorted_syms, sorted_symcount, sizeof (asymbol *), compare_symbols);
3804 /* Skip over the relocs belonging to addresses below the
3805 start address. */
3806 while (rel_pp < rel_ppend
3807 && (*rel_pp)->address < rel_offset + addr_offset)
3808 ++rel_pp;
3810 printf (_("\nDisassembly of section %s:\n"), sanitize_string (section->name));
3812 /* Find the nearest symbol forwards from our current position. */
3813 paux->require_sec = true;
3814 sym = (asymbol *) find_symbol_for_address (section->vma + addr_offset,
3815 (struct disassemble_info *) inf,
3816 &place);
3817 paux->require_sec = false;
3819 /* PR 9774: If the target used signed addresses then we must make
3820 sure that we sign extend the value that we calculate for 'addr'
3821 in the loop below. */
3822 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
3823 && (bed = get_elf_backend_data (abfd)) != NULL
3824 && bed->sign_extend_vma)
3825 sign_adjust = (bfd_vma) 1 << (bed->s->arch_size - 1);
3827 /* Disassemble a block of instructions up to the address associated with
3828 the symbol we have just found. Then print the symbol and find the
3829 next symbol on. Repeat until we have disassembled the entire section
3830 or we have reached the end of the address range we are interested in. */
3831 do_print = paux->symbol == NULL;
3832 loop_until = stop_offset_reached;
3834 while (addr_offset < stop_offset)
3836 bfd_vma addr;
3837 asymbol *nextsym;
3838 bfd_vma nextstop_offset;
3839 bool insns;
3841 addr = section->vma + addr_offset;
3842 addr = ((addr & ((sign_adjust << 1) - 1)) ^ sign_adjust) - sign_adjust;
3844 if (sym != NULL && bfd_asymbol_value (sym) <= addr)
3846 int x;
3848 for (x = place;
3849 (x < sorted_symcount
3850 && (bfd_asymbol_value (sorted_syms[x]) <= addr));
3851 ++x)
3852 continue;
3854 pinfo->symbols = sorted_syms + place;
3855 pinfo->num_symbols = x - place;
3856 pinfo->symtab_pos = place;
3858 else
3860 pinfo->symbols = NULL;
3861 pinfo->num_symbols = 0;
3862 pinfo->symtab_pos = -1;
3865 /* If we are only disassembling from a specific symbol,
3866 check to see if we should start or stop displaying. */
3867 if (sym && paux->symbol)
3869 if (do_print)
3871 /* See if we should stop printing. */
3872 switch (loop_until)
3874 case function_sym:
3875 if (sym->flags & BSF_FUNCTION)
3876 do_print = false;
3877 break;
3879 case stop_offset_reached:
3880 /* Handled by the while loop. */
3881 break;
3883 case next_sym:
3884 /* FIXME: There is an implicit assumption here
3885 that the name of sym is different from
3886 paux->symbol. */
3887 if (! bfd_is_local_label (abfd, sym))
3888 do_print = false;
3889 break;
3892 else
3894 const char * name = bfd_asymbol_name (sym);
3895 char * alloc = NULL;
3897 if (do_demangle && name[0] != '\0')
3899 /* Demangle the name. */
3900 alloc = bfd_demangle (abfd, name, demangle_flags);
3901 if (alloc != NULL)
3902 name = alloc;
3905 /* We are not currently printing. Check to see
3906 if the current symbol matches the requested symbol. */
3907 if (streq (name, paux->symbol))
3909 do_print = true;
3911 /* Skip over the relocs belonging to addresses below the
3912 symbol address. */
3913 const bfd_vma sym_offset = bfd_asymbol_value (sym) - section->vma;
3914 while (rel_pp < rel_ppend &&
3915 (*rel_pp)->address - rel_offset < sym_offset)
3916 ++rel_pp;
3918 if (sym->flags & BSF_FUNCTION)
3920 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
3921 && ((elf_symbol_type *) sym)->internal_elf_sym.st_size > 0)
3923 /* Sym is a function symbol with a size associated
3924 with it. Turn on automatic disassembly for the
3925 next VALUE bytes. */
3926 stop_offset = addr_offset
3927 + ((elf_symbol_type *) sym)->internal_elf_sym.st_size;
3928 loop_until = stop_offset_reached;
3930 else
3932 /* Otherwise we need to tell the loop heuristic to
3933 loop until the next function symbol is encountered. */
3934 loop_until = function_sym;
3937 else
3939 /* Otherwise loop until the next symbol is encountered. */
3940 loop_until = next_sym;
3944 free (alloc);
3948 if (! prefix_addresses && do_print)
3950 pinfo->fprintf_func (pinfo->stream, "\n");
3951 objdump_print_addr_with_sym (abfd, section, sym, addr,
3952 pinfo, false);
3953 pinfo->fprintf_func (pinfo->stream, ":\n");
3955 if (sym != NULL && show_all_symbols)
3957 for (++place; place < sorted_symcount; place++)
3959 sym = sorted_syms[place];
3961 if (bfd_asymbol_value (sym) != addr)
3962 break;
3963 if (! pinfo->symbol_is_valid (sym, pinfo))
3964 continue;
3965 if (strcmp (bfd_section_name (sym->section), bfd_section_name (section)) != 0)
3966 break;
3968 objdump_print_addr_with_sym (abfd, section, sym, addr, pinfo, false);
3969 pinfo->fprintf_func (pinfo->stream, ":\n");
3974 if (sym != NULL && bfd_asymbol_value (sym) > addr)
3975 nextsym = sym;
3976 else if (sym == NULL)
3977 nextsym = NULL;
3978 else
3980 #define is_valid_next_sym(SYM) \
3981 (strcmp (bfd_section_name ((SYM)->section), bfd_section_name (section)) == 0 \
3982 && (bfd_asymbol_value (SYM) > bfd_asymbol_value (sym)) \
3983 && pinfo->symbol_is_valid (SYM, pinfo))
3985 /* Search forward for the next appropriate symbol in
3986 SECTION. Note that all the symbols are sorted
3987 together into one big array, and that some sections
3988 may have overlapping addresses. */
3989 while (place < sorted_symcount
3990 && ! is_valid_next_sym (sorted_syms [place]))
3991 ++place;
3993 if (place >= sorted_symcount)
3994 nextsym = NULL;
3995 else
3996 nextsym = sorted_syms[place];
3999 if (sym != NULL && bfd_asymbol_value (sym) > addr)
4000 nextstop_offset = bfd_asymbol_value (sym) - section->vma;
4001 else if (nextsym == NULL)
4002 nextstop_offset = stop_offset;
4003 else
4004 nextstop_offset = bfd_asymbol_value (nextsym) - section->vma;
4006 if (nextstop_offset > stop_offset
4007 || nextstop_offset <= addr_offset)
4008 nextstop_offset = stop_offset;
4010 /* If a symbol is explicitly marked as being an object
4011 rather than a function, just dump the bytes without
4012 disassembling them. */
4013 if (disassemble_all
4014 || sym == NULL
4015 || sym->section != section
4016 || bfd_asymbol_value (sym) > addr
4017 || ((sym->flags & BSF_OBJECT) == 0
4018 && (strstr (bfd_asymbol_name (sym), "gnu_compiled")
4019 == NULL)
4020 && (strstr (bfd_asymbol_name (sym), "gcc2_compiled")
4021 == NULL))
4022 || (sym->flags & BSF_FUNCTION) != 0)
4023 insns = true;
4024 else
4025 insns = false;
4027 if (do_print)
4029 /* Resolve symbol name. */
4030 if (visualize_jumps && abfd && sym && sym->name)
4032 struct disassemble_info di;
4033 SFILE sf;
4035 sf.alloc = strlen (sym->name) + 40;
4036 sf.buffer = (char*) xmalloc (sf.alloc);
4037 sf.pos = 0;
4038 disassemble_set_printf
4039 (&di, &sf, (fprintf_ftype) objdump_sprintf,
4040 (fprintf_styled_ftype) objdump_styled_sprintf);
4042 objdump_print_symname (abfd, &di, sym);
4044 /* Fetch jump information. */
4045 detected_jumps = disassemble_jumps
4046 (pinfo, paux->disassemble_fn,
4047 addr_offset, nextstop_offset,
4048 rel_offset, &rel_pp, rel_ppend);
4050 /* Free symbol name. */
4051 free (sf.buffer);
4054 /* Add jumps to output. */
4055 disassemble_bytes (pinfo, paux->disassemble_fn, insns, data,
4056 addr_offset, nextstop_offset,
4057 rel_offset, &rel_pp, rel_ppend);
4059 /* Free jumps. */
4060 while (detected_jumps)
4062 detected_jumps = jump_info_free (detected_jumps);
4066 addr_offset = nextstop_offset;
4067 sym = nextsym;
4070 free (data);
4072 if (rel_ppstart != NULL)
4073 free (rel_ppstart);
4076 /* Disassemble the contents of an object file. */
4078 static void
4079 disassemble_data (bfd *abfd)
4081 struct disassemble_info disasm_info;
4082 struct objdump_disasm_info aux;
4083 long i;
4085 print_files = NULL;
4086 prev_functionname = NULL;
4087 prev_line = -1;
4088 prev_discriminator = 0;
4090 /* We make a copy of syms to sort. We don't want to sort syms
4091 because that will screw up the relocs. */
4092 sorted_symcount = symcount ? symcount : dynsymcount;
4093 sorted_syms = (asymbol **) xmalloc ((sorted_symcount + synthcount)
4094 * sizeof (asymbol *));
4095 if (sorted_symcount != 0)
4097 memcpy (sorted_syms, symcount ? syms : dynsyms,
4098 sorted_symcount * sizeof (asymbol *));
4100 sorted_symcount = remove_useless_symbols (sorted_syms, sorted_symcount);
4103 for (i = 0; i < synthcount; ++i)
4105 sorted_syms[sorted_symcount] = synthsyms + i;
4106 ++sorted_symcount;
4109 init_disassemble_info (&disasm_info, stdout, (fprintf_ftype) fprintf,
4110 (fprintf_styled_ftype) fprintf_styled);
4111 disasm_info.application_data = (void *) &aux;
4112 aux.abfd = abfd;
4113 aux.require_sec = false;
4114 disasm_info.dynrelbuf = NULL;
4115 disasm_info.dynrelcount = 0;
4116 aux.reloc = NULL;
4117 aux.symbol = disasm_sym;
4119 disasm_info.print_address_func = objdump_print_address;
4120 disasm_info.symbol_at_address_func = objdump_symbol_at_address;
4122 if (machine != NULL)
4124 const bfd_arch_info_type *inf = bfd_scan_arch (machine);
4126 if (inf == NULL)
4128 non_fatal (_("can't use supplied machine %s"), machine);
4129 exit_status = 1;
4131 else
4132 abfd->arch_info = inf;
4135 if (endian != BFD_ENDIAN_UNKNOWN)
4137 struct bfd_target *xvec;
4139 xvec = (struct bfd_target *) xmalloc (sizeof (struct bfd_target));
4140 memcpy (xvec, abfd->xvec, sizeof (struct bfd_target));
4141 xvec->byteorder = endian;
4142 abfd->xvec = xvec;
4145 /* Use libopcodes to locate a suitable disassembler. */
4146 aux.disassemble_fn = disassembler (bfd_get_arch (abfd),
4147 bfd_big_endian (abfd),
4148 bfd_get_mach (abfd), abfd);
4149 if (!aux.disassemble_fn)
4151 non_fatal (_("can't disassemble for architecture %s\n"),
4152 bfd_printable_arch_mach (bfd_get_arch (abfd), 0));
4153 exit_status = 1;
4154 free (sorted_syms);
4155 return;
4158 disasm_info.flavour = bfd_get_flavour (abfd);
4159 disasm_info.arch = bfd_get_arch (abfd);
4160 disasm_info.mach = bfd_get_mach (abfd);
4161 disasm_info.disassembler_options = disassembler_options;
4162 disasm_info.octets_per_byte = bfd_octets_per_byte (abfd, NULL);
4163 disasm_info.skip_zeroes = DEFAULT_SKIP_ZEROES;
4164 disasm_info.skip_zeroes_at_end = DEFAULT_SKIP_ZEROES_AT_END;
4165 disasm_info.disassembler_needs_relocs = false;
4167 if (bfd_big_endian (abfd))
4168 disasm_info.display_endian = disasm_info.endian = BFD_ENDIAN_BIG;
4169 else if (bfd_little_endian (abfd))
4170 disasm_info.display_endian = disasm_info.endian = BFD_ENDIAN_LITTLE;
4171 else
4172 /* ??? Aborting here seems too drastic. We could default to big or little
4173 instead. */
4174 disasm_info.endian = BFD_ENDIAN_UNKNOWN;
4176 disasm_info.endian_code = disasm_info.endian;
4178 /* Allow the target to customize the info structure. */
4179 disassemble_init_for_target (& disasm_info);
4181 /* Pre-load the dynamic relocs as we may need them during the disassembly. */
4182 long relsize = bfd_get_dynamic_reloc_upper_bound (abfd);
4184 if (relsize > 0)
4186 disasm_info.dynrelbuf = (arelent **) xmalloc (relsize);
4187 disasm_info.dynrelcount
4188 = bfd_canonicalize_dynamic_reloc (abfd, disasm_info.dynrelbuf, dynsyms);
4189 if (disasm_info.dynrelcount < 0)
4191 my_bfd_nonfatal (bfd_get_filename (abfd));
4192 free (disasm_info.dynrelbuf);
4193 disasm_info.dynrelbuf = NULL;
4194 disasm_info.dynrelcount = 0;
4196 else if (disasm_info.dynrelcount > 1)
4197 /* Sort the relocs by address. */
4198 qsort (disasm_info.dynrelbuf, disasm_info.dynrelcount,
4199 sizeof (arelent *), compare_relocs);
4202 disasm_info.symtab = sorted_syms;
4203 disasm_info.symtab_size = sorted_symcount;
4205 bfd_map_over_sections (abfd, disassemble_section, & disasm_info);
4207 free (disasm_info.dynrelbuf);
4208 disasm_info.dynrelbuf = NULL;
4209 free (sorted_syms);
4210 disassemble_free_target (&disasm_info);
4213 static bool
4214 load_specific_debug_section (enum dwarf_section_display_enum debug,
4215 asection *sec, void *file)
4217 struct dwarf_section *section = &debug_displays [debug].section;
4218 bfd *abfd = (bfd *) file;
4219 bfd_byte *contents;
4220 bfd_size_type amt;
4221 size_t alloced;
4222 bool ret;
4224 if (section->start != NULL)
4226 /* If it is already loaded, do nothing. */
4227 if (streq (section->filename, bfd_get_filename (abfd)))
4228 return true;
4229 free (section->start);
4232 section->filename = bfd_get_filename (abfd);
4233 section->reloc_info = NULL;
4234 section->num_relocs = 0;
4235 section->address = bfd_section_vma (sec);
4236 section->size = bfd_section_size (sec);
4237 /* PR 24360: On 32-bit hosts sizeof (size_t) < sizeof (bfd_size_type). */
4238 alloced = amt = section->size + 1;
4239 if (alloced != amt
4240 || alloced == 0
4241 || (bfd_get_size (abfd) != 0 && alloced >= bfd_get_size (abfd)))
4243 section->start = NULL;
4244 free_debug_section (debug);
4245 printf (_("\nSection '%s' has an invalid size: %#" PRIx64 ".\n"),
4246 sanitize_string (section->name),
4247 section->size);
4248 return false;
4251 section->start = contents = xmalloc (alloced);
4252 /* Ensure any string section has a terminating NUL. */
4253 section->start[section->size] = 0;
4255 if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0
4256 && debug_displays [debug].relocate)
4258 ret = bfd_simple_get_relocated_section_contents (abfd,
4259 sec,
4260 section->start,
4261 syms) != NULL;
4262 if (ret)
4264 long reloc_size = bfd_get_reloc_upper_bound (abfd, sec);
4266 if (reloc_size > 0)
4268 long reloc_count;
4269 arelent **relocs;
4271 relocs = (arelent **) xmalloc (reloc_size);
4273 reloc_count = bfd_canonicalize_reloc (abfd, sec, relocs, syms);
4274 if (reloc_count <= 0)
4275 free (relocs);
4276 else
4278 section->reloc_info = relocs;
4279 section->num_relocs = reloc_count;
4284 else
4285 ret = bfd_get_full_section_contents (abfd, sec, &contents);
4287 if (!ret)
4289 free_debug_section (debug);
4290 printf (_("\nCan't get contents for section '%s'.\n"),
4291 sanitize_string (section->name));
4292 return false;
4295 return true;
4298 bool
4299 reloc_at (struct dwarf_section * dsec, uint64_t offset)
4301 arelent ** relocs;
4302 arelent * rp;
4304 if (dsec == NULL || dsec->reloc_info == NULL)
4305 return false;
4307 relocs = (arelent **) dsec->reloc_info;
4309 for (; (rp = * relocs) != NULL; ++ relocs)
4310 if (rp->address == offset)
4311 return true;
4313 return false;
4316 bool
4317 load_debug_section (enum dwarf_section_display_enum debug, void *file)
4319 struct dwarf_section *section = &debug_displays [debug].section;
4320 bfd *abfd = (bfd *) file;
4321 asection *sec;
4322 const char *name;
4324 if (!dump_any_debugging)
4325 return false;
4327 /* If it is already loaded, do nothing. */
4328 if (section->start != NULL)
4330 if (streq (section->filename, bfd_get_filename (abfd)))
4331 return true;
4333 /* Locate the debug section. */
4334 name = section->uncompressed_name;
4335 sec = bfd_get_section_by_name (abfd, name);
4336 if (sec == NULL)
4338 name = section->compressed_name;
4339 if (*name)
4340 sec = bfd_get_section_by_name (abfd, name);
4342 if (sec == NULL)
4344 name = section->xcoff_name;
4345 if (*name)
4346 sec = bfd_get_section_by_name (abfd, name);
4348 if (sec == NULL)
4349 return false;
4351 section->name = name;
4352 return load_specific_debug_section (debug, sec, file);
4355 void
4356 free_debug_section (enum dwarf_section_display_enum debug)
4358 struct dwarf_section *section = &debug_displays [debug].section;
4360 free ((char *) section->start);
4361 section->start = NULL;
4362 section->address = 0;
4363 section->size = 0;
4364 free ((char*) section->reloc_info);
4365 section->reloc_info = NULL;
4366 section->num_relocs= 0;
4369 void
4370 close_debug_file (void * file)
4372 bfd * abfd = (bfd *) file;
4374 bfd_close (abfd);
4377 void *
4378 open_debug_file (const char * pathname)
4380 bfd * data;
4382 data = bfd_openr (pathname, NULL);
4383 if (data == NULL)
4384 return NULL;
4386 if (! bfd_check_format (data, bfd_object))
4387 return NULL;
4389 return data;
4392 static void
4393 dump_dwarf_section (bfd *abfd, asection *section,
4394 void *arg)
4396 const char *name = bfd_section_name (section);
4397 const char *match;
4398 int i;
4399 bool is_mainfile = *(bool *) arg;
4401 if (*name == 0)
4402 return;
4404 if (!is_mainfile && !process_links
4405 && (section->flags & SEC_DEBUGGING) == 0)
4406 return;
4408 if (startswith (name, ".gnu.linkonce.wi."))
4409 match = ".debug_info";
4410 else
4411 match = name;
4413 for (i = 0; i < max; i++)
4414 if ((strcmp (debug_displays [i].section.uncompressed_name, match) == 0
4415 || strcmp (debug_displays [i].section.compressed_name, match) == 0
4416 || strcmp (debug_displays [i].section.xcoff_name, match) == 0)
4417 && debug_displays [i].enabled != NULL
4418 && *debug_displays [i].enabled)
4420 struct dwarf_section *sec = &debug_displays [i].section;
4422 if (strcmp (sec->uncompressed_name, match) == 0)
4423 sec->name = sec->uncompressed_name;
4424 else if (strcmp (sec->compressed_name, match) == 0)
4425 sec->name = sec->compressed_name;
4426 else
4427 sec->name = sec->xcoff_name;
4428 if (load_specific_debug_section ((enum dwarf_section_display_enum) i,
4429 section, abfd))
4431 debug_displays [i].display (sec, abfd);
4433 if (i != info && i != abbrev)
4434 free_debug_section ((enum dwarf_section_display_enum) i);
4436 break;
4440 /* Dump the dwarf debugging information. */
4442 static void
4443 dump_dwarf (bfd *abfd, bool is_mainfile)
4445 /* The byte_get pointer should have been set at the start of dump_bfd(). */
4446 if (byte_get == NULL)
4448 warn (_("File %s does not contain any dwarf debug information\n"),
4449 bfd_get_filename (abfd));
4450 return;
4453 switch (bfd_get_arch (abfd))
4455 case bfd_arch_s12z:
4456 /* S12Z has a 24 bit address space. But the only known
4457 producer of dwarf_info encodes addresses into 32 bits. */
4458 eh_addr_size = 4;
4459 break;
4461 default:
4462 eh_addr_size = bfd_arch_bits_per_address (abfd) / 8;
4463 break;
4466 init_dwarf_regnames_by_bfd_arch_and_mach (bfd_get_arch (abfd),
4467 bfd_get_mach (abfd));
4469 bfd_map_over_sections (abfd, dump_dwarf_section, (void *) &is_mainfile);
4472 /* Read ABFD's section SECT_NAME into *CONTENTS, and return a pointer to
4473 the section. Return NULL on failure. */
4475 static asection *
4476 read_section (bfd *abfd, const char *sect_name, bfd_byte **contents)
4478 asection *sec;
4480 *contents = NULL;
4481 sec = bfd_get_section_by_name (abfd, sect_name);
4482 if (sec == NULL)
4484 printf (_("No %s section present\n\n"), sanitize_string (sect_name));
4485 return NULL;
4488 if ((bfd_section_flags (sec) & SEC_HAS_CONTENTS) == 0)
4489 bfd_set_error (bfd_error_no_contents);
4490 else if (bfd_malloc_and_get_section (abfd, sec, contents))
4491 return sec;
4493 non_fatal (_("reading %s section of %s failed: %s"),
4494 sect_name, bfd_get_filename (abfd),
4495 bfd_errmsg (bfd_get_error ()));
4496 exit_status = 1;
4497 return NULL;
4500 /* Stabs entries use a 12 byte format:
4501 4 byte string table index
4502 1 byte stab type
4503 1 byte stab other field
4504 2 byte stab desc field
4505 4 byte stab value
4506 FIXME: This will have to change for a 64 bit object format. */
4508 #define STRDXOFF (0)
4509 #define TYPEOFF (4)
4510 #define OTHEROFF (5)
4511 #define DESCOFF (6)
4512 #define VALOFF (8)
4513 #define STABSIZE (12)
4515 /* Print ABFD's stabs section STABSECT_NAME (in `stabs'),
4516 using string table section STRSECT_NAME (in `strtab'). */
4518 static void
4519 print_section_stabs (bfd *abfd,
4520 const char *stabsect_name,
4521 unsigned *string_offset_ptr)
4523 int i;
4524 unsigned file_string_table_offset = 0;
4525 unsigned next_file_string_table_offset = *string_offset_ptr;
4526 bfd_byte *stabp, *stabs_end;
4528 stabp = stabs;
4529 stabs_end = PTR_ADD (stabp, stab_size);
4531 printf (_("Contents of %s section:\n\n"), sanitize_string (stabsect_name));
4532 printf ("Symnum n_type n_othr n_desc n_value n_strx String\n");
4534 /* Loop through all symbols and print them.
4536 We start the index at -1 because there is a dummy symbol on
4537 the front of stabs-in-{coff,elf} sections that supplies sizes. */
4538 for (i = -1; (size_t) (stabs_end - stabp) >= STABSIZE; stabp += STABSIZE, i++)
4540 const char *name;
4541 unsigned long strx;
4542 unsigned char type, other;
4543 unsigned short desc;
4544 bfd_vma value;
4546 strx = bfd_h_get_32 (abfd, stabp + STRDXOFF);
4547 type = bfd_h_get_8 (abfd, stabp + TYPEOFF);
4548 other = bfd_h_get_8 (abfd, stabp + OTHEROFF);
4549 desc = bfd_h_get_16 (abfd, stabp + DESCOFF);
4550 value = bfd_h_get_32 (abfd, stabp + VALOFF);
4552 printf ("\n%-6d ", i);
4553 /* Either print the stab name, or, if unnamed, print its number
4554 again (makes consistent formatting for tools like awk). */
4555 name = bfd_get_stab_name (type);
4556 if (name != NULL)
4557 printf ("%-6s", sanitize_string (name));
4558 else if (type == N_UNDF)
4559 printf ("HdrSym");
4560 else
4561 printf ("%-6d", type);
4562 printf (" %-6d %-6d ", other, desc);
4563 bfd_printf_vma (abfd, value);
4564 printf (" %-6lu", strx);
4566 /* Symbols with type == 0 (N_UNDF) specify the length of the
4567 string table associated with this file. We use that info
4568 to know how to relocate the *next* file's string table indices. */
4569 if (type == N_UNDF)
4571 file_string_table_offset = next_file_string_table_offset;
4572 next_file_string_table_offset += value;
4574 else
4576 bfd_size_type amt = strx + file_string_table_offset;
4578 /* Using the (possibly updated) string table offset, print the
4579 string (if any) associated with this symbol. */
4580 if (amt < stabstr_size)
4581 /* PR 17512: file: 079-79389-0.001:0.1.
4582 FIXME: May need to sanitize this string before displaying. */
4583 printf (" %.*s", (int)(stabstr_size - amt), strtab + amt);
4584 else
4585 printf (" *");
4588 printf ("\n\n");
4589 *string_offset_ptr = next_file_string_table_offset;
4592 typedef struct
4594 const char * section_name;
4595 const char * string_section_name;
4596 unsigned string_offset;
4598 stab_section_names;
4600 static void
4601 find_stabs_section (bfd *abfd, asection *section, void *names)
4603 int len;
4604 stab_section_names * sought = (stab_section_names *) names;
4606 /* Check for section names for which stabsect_name is a prefix, to
4607 handle .stab.N, etc. */
4608 len = strlen (sought->section_name);
4610 /* If the prefix matches, and the files section name ends with a
4611 nul or a digit, then we match. I.e., we want either an exact
4612 match or a section followed by a number. */
4613 if (strncmp (sought->section_name, section->name, len) == 0
4614 && (section->name[len] == 0
4615 || (section->name[len] == '.' && ISDIGIT (section->name[len + 1]))))
4617 asection *s;
4618 if (strtab == NULL)
4620 s = read_section (abfd, sought->string_section_name, &strtab);
4621 if (s != NULL)
4622 stabstr_size = bfd_section_size (s);
4625 if (strtab)
4627 s = read_section (abfd, section->name, &stabs);
4628 if (s != NULL)
4630 stab_size = bfd_section_size (s);
4631 print_section_stabs (abfd, section->name, &sought->string_offset);
4632 free (stabs);
4638 static void
4639 dump_stabs_section (bfd *abfd, char *stabsect_name, char *strsect_name)
4641 stab_section_names s;
4643 s.section_name = stabsect_name;
4644 s.string_section_name = strsect_name;
4645 s.string_offset = 0;
4647 bfd_map_over_sections (abfd, find_stabs_section, & s);
4649 free (strtab);
4650 strtab = NULL;
4653 /* Dump the any sections containing stabs debugging information. */
4655 static void
4656 dump_stabs (bfd *abfd)
4658 dump_stabs_section (abfd, ".stab", ".stabstr");
4659 dump_stabs_section (abfd, ".stab.excl", ".stab.exclstr");
4660 dump_stabs_section (abfd, ".stab.index", ".stab.indexstr");
4662 /* For Darwin. */
4663 dump_stabs_section (abfd, "LC_SYMTAB.stabs", "LC_SYMTAB.stabstr");
4665 dump_stabs_section (abfd, "$GDB_SYMBOLS$", "$GDB_STRINGS$");
4668 static void
4669 dump_bfd_header (bfd *abfd)
4671 char *comma = "";
4673 printf (_("architecture: %s, "),
4674 bfd_printable_arch_mach (bfd_get_arch (abfd),
4675 bfd_get_mach (abfd)));
4676 printf (_("flags 0x%08x:\n"), abfd->flags & ~BFD_FLAGS_FOR_BFD_USE_MASK);
4678 #define PF(x, y) if (abfd->flags & x) {printf ("%s%s", comma, y); comma=", ";}
4679 PF (HAS_RELOC, "HAS_RELOC");
4680 PF (EXEC_P, "EXEC_P");
4681 PF (HAS_LINENO, "HAS_LINENO");
4682 PF (HAS_DEBUG, "HAS_DEBUG");
4683 PF (HAS_SYMS, "HAS_SYMS");
4684 PF (HAS_LOCALS, "HAS_LOCALS");
4685 PF (DYNAMIC, "DYNAMIC");
4686 PF (WP_TEXT, "WP_TEXT");
4687 PF (D_PAGED, "D_PAGED");
4688 PF (BFD_IS_RELAXABLE, "BFD_IS_RELAXABLE");
4689 printf (_("\nstart address 0x"));
4690 bfd_printf_vma (abfd, abfd->start_address);
4691 printf ("\n");
4695 #ifdef ENABLE_LIBCTF
4696 /* Formatting callback function passed to ctf_dump. Returns either the pointer
4697 it is passed, or a pointer to newly-allocated storage, in which case
4698 dump_ctf() will free it when it no longer needs it. */
4700 static char *
4701 dump_ctf_indent_lines (ctf_sect_names_t sect ATTRIBUTE_UNUSED,
4702 char *s, void *arg)
4704 const char *blanks = arg;
4705 char *new_s;
4707 if (asprintf (&new_s, "%s%s", blanks, s) < 0)
4708 return s;
4709 return new_s;
4712 /* Make a ctfsect suitable for ctf_bfdopen_ctfsect(). */
4713 static ctf_sect_t
4714 make_ctfsect (const char *name, bfd_byte *data,
4715 bfd_size_type size)
4717 ctf_sect_t ctfsect;
4719 ctfsect.cts_name = name;
4720 ctfsect.cts_entsize = 1;
4721 ctfsect.cts_size = size;
4722 ctfsect.cts_data = data;
4724 return ctfsect;
4727 /* Dump CTF errors/warnings. */
4728 static void
4729 dump_ctf_errs (ctf_dict_t *fp)
4731 ctf_next_t *it = NULL;
4732 char *errtext;
4733 int is_warning;
4734 int err;
4736 /* Dump accumulated errors and warnings. */
4737 while ((errtext = ctf_errwarning_next (fp, &it, &is_warning, &err)) != NULL)
4739 non_fatal (_("%s: %s"), is_warning ? _("warning"): _("error"),
4740 errtext);
4741 free (errtext);
4743 if (err != ECTF_NEXT_END)
4745 non_fatal (_("CTF error: cannot get CTF errors: `%s'"),
4746 ctf_errmsg (err));
4750 /* Dump one CTF archive member. */
4752 static void
4753 dump_ctf_archive_member (ctf_dict_t *ctf, const char *name, ctf_dict_t *parent,
4754 size_t member)
4756 const char *things[] = {"Header", "Labels", "Data objects",
4757 "Function objects", "Variables", "Types", "Strings",
4758 ""};
4759 const char **thing;
4760 size_t i;
4762 /* Don't print out the name of the default-named archive member if it appears
4763 first in the list. The name .ctf appears everywhere, even for things that
4764 aren't really archives, so printing it out is liable to be confusing; also,
4765 the common case by far is for only one archive member to exist, and hiding
4766 it in that case seems worthwhile. */
4768 if (strcmp (name, ".ctf") != 0 || member != 0)
4769 printf (_("\nCTF archive member: %s:\n"), sanitize_string (name));
4771 if (ctf_parent_name (ctf) != NULL)
4772 ctf_import (ctf, parent);
4774 for (i = 0, thing = things; *thing[0]; thing++, i++)
4776 ctf_dump_state_t *s = NULL;
4777 char *item;
4779 printf ("\n %s:\n", *thing);
4780 while ((item = ctf_dump (ctf, &s, i, dump_ctf_indent_lines,
4781 (void *) " ")) != NULL)
4783 printf ("%s\n", item);
4784 free (item);
4787 if (ctf_errno (ctf))
4789 non_fatal (_("Iteration failed: %s, %s"), *thing,
4790 ctf_errmsg (ctf_errno (ctf)));
4791 break;
4795 dump_ctf_errs (ctf);
4798 /* Dump the CTF debugging information. */
4800 static void
4801 dump_ctf (bfd *abfd, const char *sect_name, const char *parent_name)
4803 asection *sec;
4804 ctf_archive_t *ctfa = NULL;
4805 bfd_byte *ctfdata;
4806 ctf_sect_t ctfsect;
4807 ctf_dict_t *parent;
4808 ctf_dict_t *fp;
4809 ctf_next_t *i = NULL;
4810 const char *name;
4811 size_t member = 0;
4812 int err;
4814 if (sect_name == NULL)
4815 sect_name = ".ctf";
4817 sec = read_section (abfd, sect_name, &ctfdata);
4818 if (sec == NULL)
4820 my_bfd_nonfatal (bfd_get_filename (abfd));
4821 return;
4824 /* Load the CTF file and dump it. Preload the parent dict, since it will
4825 need to be imported into every child in turn. */
4827 ctfsect = make_ctfsect (sect_name, ctfdata, bfd_section_size (sec));
4828 if ((ctfa = ctf_bfdopen_ctfsect (abfd, &ctfsect, &err)) == NULL)
4830 dump_ctf_errs (NULL);
4831 non_fatal (_("CTF open failure: %s"), ctf_errmsg (err));
4832 my_bfd_nonfatal (bfd_get_filename (abfd));
4833 free (ctfdata);
4834 return;
4837 if ((parent = ctf_dict_open (ctfa, parent_name, &err)) == NULL)
4839 dump_ctf_errs (NULL);
4840 non_fatal (_("CTF open failure: %s"), ctf_errmsg (err));
4841 my_bfd_nonfatal (bfd_get_filename (abfd));
4842 ctf_close (ctfa);
4843 free (ctfdata);
4844 return;
4847 printf (_("Contents of CTF section %s:\n"), sanitize_string (sect_name));
4849 while ((fp = ctf_archive_next (ctfa, &i, &name, 0, &err)) != NULL)
4850 dump_ctf_archive_member (fp, name, parent, member++);
4851 if (err != ECTF_NEXT_END)
4853 dump_ctf_errs (NULL);
4854 non_fatal (_("CTF archive member open failure: %s"), ctf_errmsg (err));
4855 my_bfd_nonfatal (bfd_get_filename (abfd));
4857 ctf_dict_close (parent);
4858 ctf_close (ctfa);
4859 free (ctfdata);
4861 #else
4862 static void
4863 dump_ctf (bfd *abfd ATTRIBUTE_UNUSED, const char *sect_name ATTRIBUTE_UNUSED,
4864 const char *parent_name ATTRIBUTE_UNUSED) {}
4865 #endif
4867 static void
4868 dump_section_sframe (bfd *abfd ATTRIBUTE_UNUSED,
4869 const char * sect_name)
4871 asection *sec;
4872 sframe_decoder_ctx *sfd_ctx = NULL;
4873 bfd_size_type sf_size;
4874 bfd_byte *sframe_data;
4875 bfd_vma sf_vma;
4876 int err = 0;
4878 if (sect_name == NULL)
4879 sect_name = ".sframe";
4881 sec = read_section (abfd, sect_name, &sframe_data);
4882 if (sec == NULL)
4884 my_bfd_nonfatal (bfd_get_filename (abfd));
4885 return;
4887 sf_size = bfd_section_size (sec);
4888 sf_vma = bfd_section_vma (sec);
4890 /* Decode the contents of the section. */
4891 sfd_ctx = sframe_decode ((const char*)sframe_data, sf_size, &err);
4892 if (!sfd_ctx)
4894 my_bfd_nonfatal (bfd_get_filename (abfd));
4895 free (sframe_data);
4896 return;
4899 printf (_("Contents of the SFrame section %s:"),
4900 sanitize_string (sect_name));
4901 /* Dump the contents as text. */
4902 dump_sframe (sfd_ctx, sf_vma);
4904 sframe_decoder_free (&sfd_ctx);
4905 free (sframe_data);
4909 static void
4910 dump_bfd_private_header (bfd *abfd)
4912 if (!bfd_print_private_bfd_data (abfd, stdout))
4913 non_fatal (_("warning: private headers incomplete: %s"),
4914 bfd_errmsg (bfd_get_error ()));
4917 static void
4918 dump_target_specific (bfd *abfd)
4920 const struct objdump_private_desc * const *desc;
4921 struct objdump_private_option *opt;
4922 char *e, *b;
4924 /* Find the desc. */
4925 for (desc = objdump_private_vectors; *desc != NULL; desc++)
4926 if ((*desc)->filter (abfd))
4927 break;
4929 if (*desc == NULL)
4931 non_fatal (_("option -P/--private not supported by this file"));
4932 return;
4935 /* Clear all options. */
4936 for (opt = (*desc)->options; opt->name; opt++)
4937 opt->selected = false;
4939 /* Decode options. */
4940 b = dump_private_options;
4943 e = strchr (b, ',');
4945 if (e)
4946 *e = 0;
4948 for (opt = (*desc)->options; opt->name; opt++)
4949 if (strcmp (opt->name, b) == 0)
4951 opt->selected = true;
4952 break;
4954 if (opt->name == NULL)
4955 non_fatal (_("target specific dump '%s' not supported"), b);
4957 if (e)
4959 *e = ',';
4960 b = e + 1;
4963 while (e != NULL);
4965 /* Dump. */
4966 (*desc)->dump (abfd);
4969 /* Display a section in hexadecimal format with associated characters.
4970 Each line prefixed by the zero padded address. */
4972 static void
4973 dump_section (bfd *abfd, asection *section, void *dummy ATTRIBUTE_UNUSED)
4975 bfd_byte *data = NULL;
4976 bfd_size_type datasize;
4977 bfd_vma addr_offset;
4978 bfd_vma start_offset;
4979 bfd_vma stop_offset;
4980 unsigned int opb = bfd_octets_per_byte (abfd, section);
4981 /* Bytes per line. */
4982 const int onaline = 16;
4983 char buf[64];
4984 int count;
4985 int width;
4987 if (only_list == NULL)
4989 if ((section->flags & SEC_HAS_CONTENTS) == 0)
4990 return;
4992 else if (!process_section_p (section))
4993 return;
4995 if ((datasize = bfd_section_size (section)) == 0)
4996 return;
4998 /* Compute the address range to display. */
4999 if (start_address == (bfd_vma) -1
5000 || start_address < section->vma)
5001 start_offset = 0;
5002 else
5003 start_offset = start_address - section->vma;
5005 if (stop_address == (bfd_vma) -1)
5006 stop_offset = datasize / opb;
5007 else
5009 if (stop_address < section->vma)
5010 stop_offset = 0;
5011 else
5012 stop_offset = stop_address - section->vma;
5014 if (stop_offset > datasize / opb)
5015 stop_offset = datasize / opb;
5018 if (start_offset >= stop_offset)
5019 return;
5021 printf (_("Contents of section %s:"), sanitize_string (section->name));
5022 if (display_file_offsets)
5023 printf (_(" (Starting at file offset: 0x%lx)"),
5024 (unsigned long) (section->filepos + start_offset));
5025 printf ("\n");
5027 if (!bfd_get_full_section_contents (abfd, section, &data))
5029 non_fatal (_("Reading section %s failed because: %s"),
5030 section->name, bfd_errmsg (bfd_get_error ()));
5031 return;
5034 width = 4;
5036 bfd_sprintf_vma (abfd, buf, start_offset + section->vma);
5037 if (strlen (buf) >= sizeof (buf))
5038 abort ();
5040 count = 0;
5041 while (buf[count] == '0' && buf[count+1] != '\0')
5042 count++;
5043 count = strlen (buf) - count;
5044 if (count > width)
5045 width = count;
5047 bfd_sprintf_vma (abfd, buf, stop_offset + section->vma - 1);
5048 if (strlen (buf) >= sizeof (buf))
5049 abort ();
5051 count = 0;
5052 while (buf[count] == '0' && buf[count+1] != '\0')
5053 count++;
5054 count = strlen (buf) - count;
5055 if (count > width)
5056 width = count;
5058 for (addr_offset = start_offset;
5059 addr_offset < stop_offset; addr_offset += onaline / opb)
5061 bfd_size_type j;
5063 bfd_sprintf_vma (abfd, buf, (addr_offset + section->vma));
5064 count = strlen (buf);
5065 if ((size_t) count >= sizeof (buf))
5066 abort ();
5068 putchar (' ');
5069 while (count < width)
5071 putchar ('0');
5072 count++;
5074 fputs (buf + count - width, stdout);
5075 putchar (' ');
5077 for (j = addr_offset * opb;
5078 j < addr_offset * opb + onaline; j++)
5080 if (j < stop_offset * opb)
5081 printf ("%02x", (unsigned) (data[j]));
5082 else
5083 printf (" ");
5084 if ((j & 3) == 3)
5085 printf (" ");
5088 printf (" ");
5089 for (j = addr_offset * opb;
5090 j < addr_offset * opb + onaline; j++)
5092 if (j >= stop_offset * opb)
5093 printf (" ");
5094 else
5095 printf ("%c", ISPRINT (data[j]) ? data[j] : '.');
5097 putchar ('\n');
5099 free (data);
5102 /* Actually display the various requested regions. */
5104 static void
5105 dump_data (bfd *abfd)
5107 bfd_map_over_sections (abfd, dump_section, NULL);
5110 /* Should perhaps share code and display with nm? */
5112 static void
5113 dump_symbols (bfd *abfd ATTRIBUTE_UNUSED, bool dynamic)
5115 asymbol **current;
5116 long max_count;
5117 long count;
5119 if (dynamic)
5121 current = dynsyms;
5122 max_count = dynsymcount;
5123 printf ("DYNAMIC SYMBOL TABLE:\n");
5125 else
5127 current = syms;
5128 max_count = symcount;
5129 printf ("SYMBOL TABLE:\n");
5132 if (max_count == 0)
5133 printf (_("no symbols\n"));
5135 for (count = 0; count < max_count; count++)
5137 bfd *cur_bfd;
5139 if (*current == NULL)
5140 printf (_("no information for symbol number %ld\n"), count);
5142 else if ((cur_bfd = bfd_asymbol_bfd (*current)) == NULL)
5143 printf (_("could not determine the type of symbol number %ld\n"),
5144 count);
5146 else if (process_section_p ((* current)->section)
5147 && (dump_special_syms
5148 || !bfd_is_target_special_symbol (cur_bfd, *current)))
5150 const char *name = (*current)->name;
5152 if (do_demangle && name != NULL && *name != '\0')
5154 char *alloc;
5156 /* If we want to demangle the name, we demangle it
5157 here, and temporarily clobber it while calling
5158 bfd_print_symbol. FIXME: This is a gross hack. */
5159 alloc = bfd_demangle (cur_bfd, name, demangle_flags);
5160 if (alloc != NULL)
5161 (*current)->name = alloc;
5162 bfd_print_symbol (cur_bfd, stdout, *current,
5163 bfd_print_symbol_all);
5164 if (alloc != NULL)
5166 (*current)->name = name;
5167 free (alloc);
5170 else if (unicode_display != unicode_default
5171 && name != NULL && *name != '\0')
5173 const char * sanitized_name;
5175 /* If we want to sanitize the name, we do it here, and
5176 temporarily clobber it while calling bfd_print_symbol.
5177 FIXME: This is a gross hack. */
5178 sanitized_name = sanitize_string (name);
5179 if (sanitized_name != name)
5180 (*current)->name = sanitized_name;
5181 else
5182 sanitized_name = NULL;
5183 bfd_print_symbol (cur_bfd, stdout, *current,
5184 bfd_print_symbol_all);
5185 if (sanitized_name != NULL)
5186 (*current)->name = name;
5188 else
5189 bfd_print_symbol (cur_bfd, stdout, *current,
5190 bfd_print_symbol_all);
5191 printf ("\n");
5194 current++;
5196 printf ("\n\n");
5199 static void
5200 dump_reloc_set (bfd *abfd, asection *sec, arelent **relpp, long relcount)
5202 arelent **p;
5203 char *last_filename, *last_functionname;
5204 unsigned int last_line;
5205 unsigned int last_discriminator;
5207 /* Get column headers lined up reasonably. */
5209 static int width;
5211 if (width == 0)
5213 char buf[30];
5215 bfd_sprintf_vma (abfd, buf, (bfd_vma) -1);
5216 width = strlen (buf) - 7;
5218 printf ("OFFSET %*s TYPE %*s VALUE\n", width, "", 12, "");
5221 last_filename = NULL;
5222 last_functionname = NULL;
5223 last_line = 0;
5224 last_discriminator = 0;
5226 for (p = relpp; relcount && *p != NULL; p++, relcount--)
5228 arelent *q = *p;
5229 const char *filename, *functionname;
5230 unsigned int linenumber;
5231 unsigned int discriminator;
5232 const char *sym_name;
5233 const char *section_name;
5234 bfd_vma addend2 = 0;
5236 if (start_address != (bfd_vma) -1
5237 && q->address < start_address)
5238 continue;
5239 if (stop_address != (bfd_vma) -1
5240 && q->address > stop_address)
5241 continue;
5243 if (with_line_numbers
5244 && sec != NULL
5245 && bfd_find_nearest_line_discriminator (abfd, sec, syms, q->address,
5246 &filename, &functionname,
5247 &linenumber, &discriminator))
5249 if (functionname != NULL
5250 && (last_functionname == NULL
5251 || strcmp (functionname, last_functionname) != 0))
5253 printf ("%s():\n", sanitize_string (functionname));
5254 if (last_functionname != NULL)
5255 free (last_functionname);
5256 last_functionname = xstrdup (functionname);
5259 if (linenumber > 0
5260 && (linenumber != last_line
5261 || (filename != NULL
5262 && last_filename != NULL
5263 && filename_cmp (filename, last_filename) != 0)
5264 || (discriminator != last_discriminator)))
5266 if (discriminator > 0)
5267 printf ("%s:%u\n", filename == NULL ? "???" :
5268 sanitize_string (filename), linenumber);
5269 else
5270 printf ("%s:%u (discriminator %u)\n",
5271 filename == NULL ? "???" : sanitize_string (filename),
5272 linenumber, discriminator);
5273 last_line = linenumber;
5274 last_discriminator = discriminator;
5275 if (last_filename != NULL)
5276 free (last_filename);
5277 if (filename == NULL)
5278 last_filename = NULL;
5279 else
5280 last_filename = xstrdup (filename);
5284 if (q->sym_ptr_ptr && *q->sym_ptr_ptr)
5286 sym_name = (*(q->sym_ptr_ptr))->name;
5287 section_name = (*(q->sym_ptr_ptr))->section->name;
5289 else
5291 sym_name = NULL;
5292 section_name = NULL;
5295 bfd_printf_vma (abfd, q->address);
5296 if (q->howto == NULL)
5297 printf (" *unknown* ");
5298 else if (q->howto->name)
5300 const char *name = q->howto->name;
5302 /* R_SPARC_OLO10 relocations contain two addends.
5303 But because 'arelent' lacks enough storage to
5304 store them both, the 64-bit ELF Sparc backend
5305 records this as two relocations. One R_SPARC_LO10
5306 and one R_SPARC_13, both pointing to the same
5307 address. This is merely so that we have some
5308 place to store both addend fields.
5310 Undo this transformation, otherwise the output
5311 will be confusing. */
5312 if (abfd->xvec->flavour == bfd_target_elf_flavour
5313 && elf_tdata (abfd)->elf_header->e_machine == EM_SPARCV9
5314 && relcount > 1
5315 && !strcmp (q->howto->name, "R_SPARC_LO10"))
5317 arelent *q2 = *(p + 1);
5318 if (q2 != NULL
5319 && q2->howto
5320 && q->address == q2->address
5321 && !strcmp (q2->howto->name, "R_SPARC_13"))
5323 name = "R_SPARC_OLO10";
5324 addend2 = q2->addend;
5325 p++;
5328 printf (" %-16s ", name);
5330 else
5331 printf (" %-16d ", q->howto->type);
5333 if (sym_name)
5335 objdump_print_symname (abfd, NULL, *q->sym_ptr_ptr);
5337 else
5339 if (section_name == NULL)
5340 section_name = "*unknown*";
5341 printf ("[%s]", sanitize_string (section_name));
5344 if (q->addend)
5346 bfd_signed_vma addend = q->addend;
5347 if (addend < 0)
5349 printf ("-0x");
5350 addend = -addend;
5352 else
5353 printf ("+0x");
5354 bfd_printf_vma (abfd, addend);
5356 if (addend2)
5358 printf ("+0x");
5359 bfd_printf_vma (abfd, addend2);
5362 printf ("\n");
5365 if (last_filename != NULL)
5366 free (last_filename);
5367 if (last_functionname != NULL)
5368 free (last_functionname);
5371 static void
5372 dump_relocs_in_section (bfd *abfd,
5373 asection *section,
5374 void *dummy ATTRIBUTE_UNUSED)
5376 arelent **relpp;
5377 long relcount;
5378 long relsize;
5380 if ( bfd_is_abs_section (section)
5381 || bfd_is_und_section (section)
5382 || bfd_is_com_section (section)
5383 || (! process_section_p (section))
5384 || ((section->flags & SEC_RELOC) == 0))
5385 return;
5387 printf ("RELOCATION RECORDS FOR [%s]:", sanitize_string (section->name));
5389 relsize = bfd_get_reloc_upper_bound (abfd, section);
5390 if (relsize == 0)
5392 printf (" (none)\n\n");
5393 return;
5396 if (relsize < 0)
5398 relpp = NULL;
5399 relcount = relsize;
5401 else
5403 relpp = (arelent **) xmalloc (relsize);
5404 relcount = bfd_canonicalize_reloc (abfd, section, relpp, syms);
5407 if (relcount < 0)
5409 printf ("\n");
5410 non_fatal (_("failed to read relocs in: %s"),
5411 sanitize_string (bfd_get_filename (abfd)));
5412 my_bfd_nonfatal (_("error message was"));
5414 else if (relcount == 0)
5415 printf (" (none)\n\n");
5416 else
5418 printf ("\n");
5419 dump_reloc_set (abfd, section, relpp, relcount);
5420 printf ("\n\n");
5422 free (relpp);
5425 static void
5426 dump_relocs (bfd *abfd)
5428 bfd_map_over_sections (abfd, dump_relocs_in_section, NULL);
5431 static void
5432 dump_dynamic_relocs (bfd *abfd)
5434 long relsize;
5435 arelent **relpp;
5436 long relcount;
5438 relsize = bfd_get_dynamic_reloc_upper_bound (abfd);
5440 printf ("DYNAMIC RELOCATION RECORDS");
5442 if (relsize == 0)
5444 printf (" (none)\n\n");
5445 return;
5448 if (relsize < 0)
5450 relpp = NULL;
5451 relcount = relsize;
5453 else
5455 relpp = (arelent **) xmalloc (relsize);
5456 relcount = bfd_canonicalize_dynamic_reloc (abfd, relpp, dynsyms);
5459 if (relcount < 0)
5461 printf ("\n");
5462 non_fatal (_("failed to read relocs in: %s"),
5463 sanitize_string (bfd_get_filename (abfd)));
5464 my_bfd_nonfatal (_("error message was"));
5466 else if (relcount == 0)
5467 printf (" (none)\n\n");
5468 else
5470 printf ("\n");
5471 dump_reloc_set (abfd, NULL, relpp, relcount);
5472 printf ("\n\n");
5474 free (relpp);
5477 /* Creates a table of paths, to search for source files. */
5479 static void
5480 add_include_path (const char *path)
5482 if (path[0] == 0)
5483 return;
5484 include_path_count++;
5485 include_paths = (const char **)
5486 xrealloc (include_paths, include_path_count * sizeof (*include_paths));
5487 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
5488 if (path[1] == ':' && path[2] == 0)
5489 path = concat (path, ".", (const char *) 0);
5490 #endif
5491 include_paths[include_path_count - 1] = path;
5494 static void
5495 adjust_addresses (bfd *abfd ATTRIBUTE_UNUSED,
5496 asection *section,
5497 void *arg)
5499 if ((section->flags & SEC_DEBUGGING) == 0)
5501 bool *has_reloc_p = (bool *) arg;
5502 section->vma += adjust_section_vma;
5503 if (*has_reloc_p)
5504 section->lma += adjust_section_vma;
5508 /* Return the sign-extended form of an ARCH_SIZE sized VMA. */
5510 static bfd_vma
5511 sign_extend_address (bfd *abfd ATTRIBUTE_UNUSED,
5512 bfd_vma vma,
5513 unsigned arch_size)
5515 bfd_vma mask;
5516 mask = (bfd_vma) 1 << (arch_size - 1);
5517 return (((vma & ((mask << 1) - 1)) ^ mask) - mask);
5520 static bool
5521 might_need_separate_debug_info (bool is_mainfile)
5523 /* We do not follow links from debug info files. */
5524 if (! is_mainfile)
5525 return false;
5527 /* Since do_follow_links might be enabled by default, only treat it as an
5528 indication that separate files should be loaded if setting it was a
5529 deliberate user action. */
5530 if (DEFAULT_FOR_FOLLOW_LINKS == 0 && do_follow_links)
5531 return true;
5533 if (process_links || dump_symtab || dump_debugging
5534 || dump_dwarf_section_info || with_source_code)
5535 return true;
5537 return false;
5540 /* Dump selected contents of ABFD. */
5542 static void
5543 dump_bfd (bfd *abfd, bool is_mainfile)
5545 const struct elf_backend_data * bed;
5547 if (bfd_big_endian (abfd))
5548 byte_get = byte_get_big_endian;
5549 else if (bfd_little_endian (abfd))
5550 byte_get = byte_get_little_endian;
5551 else
5552 byte_get = NULL;
5554 /* Load any separate debug information files. */
5555 if (byte_get != NULL && might_need_separate_debug_info (is_mainfile))
5557 load_separate_debug_files (abfd, bfd_get_filename (abfd));
5559 /* If asked to do so, recursively dump the separate files. */
5560 if (do_follow_links)
5562 separate_info * i;
5564 for (i = first_separate_info; i != NULL; i = i->next)
5565 dump_bfd (i->handle, false);
5569 /* Adjust user-specified start and stop limits for targets that use
5570 signed addresses. */
5571 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
5572 && (bed = get_elf_backend_data (abfd)) != NULL
5573 && bed->sign_extend_vma)
5575 start_address = sign_extend_address (abfd, start_address,
5576 bed->s->arch_size);
5577 stop_address = sign_extend_address (abfd, stop_address,
5578 bed->s->arch_size);
5581 /* If we are adjusting section VMA's, change them all now. Changing
5582 the BFD information is a hack. However, we must do it, or
5583 bfd_find_nearest_line will not do the right thing. */
5584 if (adjust_section_vma != 0)
5586 bool has_reloc = (abfd->flags & HAS_RELOC);
5587 bfd_map_over_sections (abfd, adjust_addresses, &has_reloc);
5590 if (is_mainfile || process_links)
5592 if (! dump_debugging_tags && ! suppress_bfd_header)
5593 printf (_("\n%s: file format %s\n"),
5594 sanitize_string (bfd_get_filename (abfd)),
5595 abfd->xvec->name);
5596 if (dump_ar_hdrs)
5597 print_arelt_descr (stdout, abfd, true, false);
5598 if (dump_file_header)
5599 dump_bfd_header (abfd);
5600 if (dump_private_headers)
5601 dump_bfd_private_header (abfd);
5602 if (dump_private_options != NULL)
5603 dump_target_specific (abfd);
5604 if (! dump_debugging_tags && ! suppress_bfd_header)
5605 putchar ('\n');
5608 if (dump_symtab
5609 || dump_reloc_info
5610 || disassemble
5611 || dump_debugging
5612 || dump_dwarf_section_info)
5614 syms = slurp_symtab (abfd);
5616 /* If following links, load any symbol tables from the linked files as well. */
5617 if (do_follow_links && is_mainfile)
5619 separate_info * i;
5621 for (i = first_separate_info; i != NULL; i = i->next)
5623 asymbol ** extra_syms;
5624 long old_symcount = symcount;
5626 extra_syms = slurp_symtab (i->handle);
5628 if (extra_syms)
5630 if (old_symcount == 0)
5632 syms = extra_syms;
5634 else
5636 syms = xrealloc (syms, ((symcount + old_symcount + 1)
5637 * sizeof (asymbol *)));
5638 memcpy (syms + old_symcount,
5639 extra_syms,
5640 (symcount + 1) * sizeof (asymbol *));
5644 symcount += old_symcount;
5649 if (is_mainfile || process_links)
5651 if (dump_section_headers)
5652 dump_headers (abfd);
5654 if (dump_dynamic_symtab || dump_dynamic_reloc_info
5655 || (disassemble && bfd_get_dynamic_symtab_upper_bound (abfd) > 0))
5656 dynsyms = slurp_dynamic_symtab (abfd);
5658 if (disassemble)
5660 synthcount = bfd_get_synthetic_symtab (abfd, symcount, syms,
5661 dynsymcount, dynsyms,
5662 &synthsyms);
5663 if (synthcount < 0)
5664 synthcount = 0;
5667 if (dump_symtab)
5668 dump_symbols (abfd, false);
5669 if (dump_dynamic_symtab)
5670 dump_symbols (abfd, true);
5672 if (dump_dwarf_section_info)
5673 dump_dwarf (abfd, is_mainfile);
5674 if (is_mainfile || process_links)
5676 if (dump_ctf_section_info)
5677 dump_ctf (abfd, dump_ctf_section_name, dump_ctf_parent_name);
5678 if (dump_sframe_section_info)
5679 dump_section_sframe (abfd, dump_sframe_section_name);
5680 if (dump_stab_section_info)
5681 dump_stabs (abfd);
5682 if (dump_reloc_info && ! disassemble)
5683 dump_relocs (abfd);
5684 if (dump_dynamic_reloc_info && ! disassemble)
5685 dump_dynamic_relocs (abfd);
5686 if (dump_section_contents)
5687 dump_data (abfd);
5688 if (disassemble)
5689 disassemble_data (abfd);
5692 if (dump_debugging)
5694 void *dhandle;
5696 dhandle = read_debugging_info (abfd, syms, symcount, true);
5697 if (dhandle != NULL)
5699 if (!print_debugging_info (stdout, dhandle, abfd, syms,
5700 bfd_demangle,
5701 dump_debugging_tags != 0))
5703 non_fatal (_("%s: printing debugging information failed"),
5704 bfd_get_filename (abfd));
5705 exit_status = 1;
5708 /* PR 6483: If there was no STABS debug info in the file, try
5709 DWARF instead. */
5710 else if (! dump_dwarf_section_info)
5712 dwarf_select_sections_all ();
5713 dump_dwarf (abfd, is_mainfile);
5717 if (syms)
5719 free (syms);
5720 syms = NULL;
5723 if (dynsyms)
5725 free (dynsyms);
5726 dynsyms = NULL;
5729 if (synthsyms)
5731 free (synthsyms);
5732 synthsyms = NULL;
5735 symcount = 0;
5736 dynsymcount = 0;
5737 synthcount = 0;
5739 if (is_mainfile)
5740 free_debug_memory ();
5743 static void
5744 display_object_bfd (bfd *abfd)
5746 char **matching;
5748 if (bfd_check_format_matches (abfd, bfd_object, &matching))
5750 dump_bfd (abfd, true);
5751 return;
5754 if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
5756 my_bfd_nonfatal (bfd_get_filename (abfd));
5757 list_matching_formats (matching);
5758 return;
5761 if (bfd_get_error () != bfd_error_file_not_recognized)
5763 my_bfd_nonfatal (bfd_get_filename (abfd));
5764 return;
5767 if (bfd_check_format_matches (abfd, bfd_core, &matching))
5769 dump_bfd (abfd, true);
5770 return;
5773 my_bfd_nonfatal (bfd_get_filename (abfd));
5775 if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
5776 list_matching_formats (matching);
5779 static void
5780 display_any_bfd (bfd *file, int level)
5782 /* Decompress sections unless dumping the section contents. */
5783 if (!dump_section_contents)
5784 file->flags |= BFD_DECOMPRESS;
5786 /* If the file is an archive, process all of its elements. */
5787 if (bfd_check_format (file, bfd_archive))
5789 bfd *arfile = NULL;
5790 bfd *last_arfile = NULL;
5792 if (level == 0)
5793 printf (_("In archive %s:\n"), sanitize_string (bfd_get_filename (file)));
5794 else if (level > 100)
5796 /* Prevent corrupted files from spinning us into an
5797 infinite loop. 100 is an arbitrary heuristic. */
5798 non_fatal (_("Archive nesting is too deep"));
5799 exit_status = 1;
5800 return;
5802 else
5803 printf (_("In nested archive %s:\n"),
5804 sanitize_string (bfd_get_filename (file)));
5806 for (;;)
5808 bfd_set_error (bfd_error_no_error);
5810 arfile = bfd_openr_next_archived_file (file, arfile);
5811 if (arfile == NULL)
5813 if (bfd_get_error () != bfd_error_no_more_archived_files)
5814 my_bfd_nonfatal (bfd_get_filename (file));
5815 break;
5818 display_any_bfd (arfile, level + 1);
5820 if (last_arfile != NULL)
5822 bfd_close (last_arfile);
5823 /* PR 17512: file: ac585d01. */
5824 if (arfile == last_arfile)
5826 last_arfile = NULL;
5827 break;
5830 last_arfile = arfile;
5833 if (last_arfile != NULL)
5834 bfd_close (last_arfile);
5836 else
5837 display_object_bfd (file);
5840 static void
5841 display_file (char *filename, char *target, bool last_file)
5843 bfd *file;
5845 if (get_file_size (filename) < 1)
5847 exit_status = 1;
5848 return;
5851 file = bfd_openr (filename, target);
5852 if (file == NULL)
5854 my_bfd_nonfatal (filename);
5855 return;
5858 display_any_bfd (file, 0);
5860 /* This is an optimization to improve the speed of objdump, especially when
5861 dumping a file with lots of associated debug informatiom. Calling
5862 bfd_close on such a file can take a non-trivial amount of time as there
5863 are lots of lists to walk and buffers to free. This is only really
5864 necessary however if we are about to load another file and we need the
5865 memory back. Otherwise, if we are about to exit, then we can save (a lot
5866 of) time by only doing a quick close, and allowing the OS to reclaim the
5867 memory for us. */
5868 if (! last_file)
5869 bfd_close (file);
5870 else
5871 bfd_close_all_done (file);
5875 main (int argc, char **argv)
5877 int c;
5878 char *target = default_target;
5879 bool seenflag = false;
5881 #ifdef HAVE_LC_MESSAGES
5882 setlocale (LC_MESSAGES, "");
5883 #endif
5884 setlocale (LC_CTYPE, "");
5886 bindtextdomain (PACKAGE, LOCALEDIR);
5887 textdomain (PACKAGE);
5889 program_name = *argv;
5890 xmalloc_set_program_name (program_name);
5891 bfd_set_error_program_name (program_name);
5893 expandargv (&argc, &argv);
5895 if (bfd_init () != BFD_INIT_MAGIC)
5896 fatal (_("fatal error: libbfd ABI mismatch"));
5897 set_default_bfd_target ();
5899 while ((c = getopt_long (argc, argv,
5900 "CDE:FGHI:LM:P:RSTU:VW::ab:defghij:lm:prstvwxz",
5901 long_options, (int *) 0))
5902 != EOF)
5904 switch (c)
5906 case 0:
5907 break; /* We've been given a long option. */
5908 case 'm':
5909 machine = optarg;
5910 break;
5911 case 'M':
5913 char *options;
5914 if (disassembler_options)
5915 /* Ignore potential memory leak for now. */
5916 options = concat (disassembler_options, ",",
5917 optarg, (const char *) NULL);
5918 else
5919 options = optarg;
5920 disassembler_options = remove_whitespace_and_extra_commas (options);
5922 break;
5923 case 'j':
5924 add_only (optarg);
5925 break;
5926 case 'F':
5927 display_file_offsets = true;
5928 break;
5929 case 'l':
5930 with_line_numbers = true;
5931 break;
5932 case 'b':
5933 target = optarg;
5934 break;
5935 case 'C':
5936 do_demangle = true;
5937 if (optarg != NULL)
5939 enum demangling_styles style;
5941 style = cplus_demangle_name_to_style (optarg);
5942 if (style == unknown_demangling)
5943 fatal (_("unknown demangling style `%s'"),
5944 optarg);
5946 cplus_demangle_set_style (style);
5948 break;
5949 case OPTION_RECURSE_LIMIT:
5950 demangle_flags &= ~ DMGL_NO_RECURSE_LIMIT;
5951 break;
5952 case OPTION_NO_RECURSE_LIMIT:
5953 demangle_flags |= DMGL_NO_RECURSE_LIMIT;
5954 break;
5955 case 'w':
5956 do_wide = wide_output = true;
5957 break;
5958 case OPTION_ADJUST_VMA:
5959 adjust_section_vma = parse_vma (optarg, "--adjust-vma");
5960 break;
5961 case OPTION_START_ADDRESS:
5962 start_address = parse_vma (optarg, "--start-address");
5963 if ((stop_address != (bfd_vma) -1) && stop_address <= start_address)
5964 fatal (_("error: the start address should be before the end address"));
5965 break;
5966 case OPTION_STOP_ADDRESS:
5967 stop_address = parse_vma (optarg, "--stop-address");
5968 if ((start_address != (bfd_vma) -1) && stop_address <= start_address)
5969 fatal (_("error: the stop address should be after the start address"));
5970 break;
5971 case OPTION_PREFIX:
5972 prefix = optarg;
5973 prefix_length = strlen (prefix);
5974 /* Remove an unnecessary trailing '/' */
5975 while (IS_DIR_SEPARATOR (prefix[prefix_length - 1]))
5976 prefix_length--;
5977 break;
5978 case OPTION_PREFIX_STRIP:
5979 prefix_strip = atoi (optarg);
5980 if (prefix_strip < 0)
5981 fatal (_("error: prefix strip must be non-negative"));
5982 break;
5983 case OPTION_INSN_WIDTH:
5984 insn_width = strtoul (optarg, NULL, 0);
5985 if (insn_width <= 0)
5986 fatal (_("error: instruction width must be positive"));
5987 break;
5988 case OPTION_INLINES:
5989 unwind_inlines = true;
5990 break;
5991 case OPTION_VISUALIZE_JUMPS:
5992 visualize_jumps = true;
5993 color_output = false;
5994 extended_color_output = false;
5995 if (optarg != NULL)
5997 if (streq (optarg, "color"))
5998 color_output = true;
5999 else if (streq (optarg, "extended-color"))
6001 color_output = true;
6002 extended_color_output = true;
6004 else if (streq (optarg, "off"))
6005 visualize_jumps = false;
6006 else
6008 non_fatal (_("unrecognized argument to --visualize-option"));
6009 usage (stderr, 1);
6012 break;
6013 case OPTION_DISASSEMBLER_COLOR:
6014 if (streq (optarg, "off"))
6015 disassembler_color = off;
6016 else if (streq (optarg, "terminal"))
6017 disassembler_color = on_if_terminal_output;
6018 else if (streq (optarg, "color")
6019 || streq (optarg, "colour")
6020 || streq (optarg, "on"))
6021 disassembler_color = on;
6022 else if (streq (optarg, "extended")
6023 || streq (optarg, "extended-color")
6024 || streq (optarg, "extended-colour"))
6025 disassembler_color = extended;
6026 else
6028 non_fatal (_("unrecognized argument to --disassembler-color"));
6029 usage (stderr, 1);
6031 break;
6032 case 'E':
6033 if (strcmp (optarg, "B") == 0)
6034 endian = BFD_ENDIAN_BIG;
6035 else if (strcmp (optarg, "L") == 0)
6036 endian = BFD_ENDIAN_LITTLE;
6037 else
6039 non_fatal (_("unrecognized -E option"));
6040 usage (stderr, 1);
6042 break;
6043 case OPTION_ENDIAN:
6044 if (strncmp (optarg, "big", strlen (optarg)) == 0)
6045 endian = BFD_ENDIAN_BIG;
6046 else if (strncmp (optarg, "little", strlen (optarg)) == 0)
6047 endian = BFD_ENDIAN_LITTLE;
6048 else
6050 non_fatal (_("unrecognized --endian type `%s'"), optarg);
6051 usage (stderr, 1);
6053 break;
6055 case 'f':
6056 dump_file_header = true;
6057 seenflag = true;
6058 break;
6059 case 'i':
6060 formats_info = true;
6061 seenflag = true;
6062 break;
6063 case 'I':
6064 add_include_path (optarg);
6065 break;
6066 case 'p':
6067 dump_private_headers = true;
6068 seenflag = true;
6069 break;
6070 case 'P':
6071 dump_private_options = optarg;
6072 seenflag = true;
6073 break;
6074 case 'x':
6075 dump_private_headers = true;
6076 dump_symtab = true;
6077 dump_reloc_info = true;
6078 dump_file_header = true;
6079 dump_ar_hdrs = true;
6080 dump_section_headers = true;
6081 seenflag = true;
6082 break;
6083 case 't':
6084 dump_symtab = true;
6085 seenflag = true;
6086 break;
6087 case 'T':
6088 dump_dynamic_symtab = true;
6089 seenflag = true;
6090 break;
6091 case 'd':
6092 disassemble = true;
6093 seenflag = true;
6094 disasm_sym = optarg;
6095 break;
6096 case 'z':
6097 disassemble_zeroes = true;
6098 break;
6099 case 'D':
6100 disassemble = true;
6101 disassemble_all = true;
6102 seenflag = true;
6103 break;
6104 case 'S':
6105 disassemble = true;
6106 with_source_code = true;
6107 seenflag = true;
6108 break;
6109 case OPTION_SOURCE_COMMENT:
6110 disassemble = true;
6111 with_source_code = true;
6112 seenflag = true;
6113 if (optarg)
6114 source_comment = xstrdup (sanitize_string (optarg));
6115 else
6116 source_comment = xstrdup ("# ");
6117 break;
6118 case 'g':
6119 dump_debugging = 1;
6120 seenflag = true;
6121 break;
6122 case 'e':
6123 dump_debugging = 1;
6124 dump_debugging_tags = 1;
6125 do_demangle = true;
6126 seenflag = true;
6127 break;
6128 case 'L':
6129 process_links = true;
6130 do_follow_links = true;
6131 break;
6132 case 'W':
6133 seenflag = true;
6134 if (optarg)
6136 if (dwarf_select_sections_by_letters (optarg))
6137 dump_dwarf_section_info = true;
6139 else
6141 dump_dwarf_section_info = true;
6142 dwarf_select_sections_all ();
6144 break;
6145 case OPTION_DWARF:
6146 seenflag = true;
6147 if (optarg)
6149 if (dwarf_select_sections_by_names (optarg))
6150 dump_dwarf_section_info = true;
6152 else
6154 dwarf_select_sections_all ();
6155 dump_dwarf_section_info = true;
6157 break;
6158 case OPTION_DWARF_DEPTH:
6160 char *cp;
6161 dwarf_cutoff_level = strtoul (optarg, & cp, 0);
6163 break;
6164 case OPTION_DWARF_START:
6166 char *cp;
6167 dwarf_start_die = strtoul (optarg, & cp, 0);
6168 suppress_bfd_header = 1;
6170 break;
6171 case OPTION_DWARF_CHECK:
6172 dwarf_check = true;
6173 break;
6174 #ifdef ENABLE_LIBCTF
6175 case OPTION_CTF:
6176 dump_ctf_section_info = true;
6177 if (optarg)
6178 dump_ctf_section_name = xstrdup (optarg);
6179 seenflag = true;
6180 break;
6181 case OPTION_CTF_PARENT:
6182 dump_ctf_parent_name = xstrdup (optarg);
6183 break;
6184 #endif
6185 case OPTION_SFRAME:
6186 dump_sframe_section_info = true;
6187 if (optarg)
6188 dump_sframe_section_name = xstrdup (optarg);
6189 seenflag = true;
6190 break;
6191 case 'G':
6192 dump_stab_section_info = true;
6193 seenflag = true;
6194 break;
6195 case 's':
6196 dump_section_contents = true;
6197 seenflag = true;
6198 break;
6199 case 'r':
6200 dump_reloc_info = true;
6201 seenflag = true;
6202 break;
6203 case 'R':
6204 dump_dynamic_reloc_info = true;
6205 seenflag = true;
6206 break;
6207 case 'a':
6208 dump_ar_hdrs = true;
6209 seenflag = true;
6210 break;
6211 case 'h':
6212 dump_section_headers = true;
6213 seenflag = true;
6214 break;
6215 case 'v':
6216 case 'V':
6217 show_version = true;
6218 seenflag = true;
6219 break;
6221 case 'U':
6222 if (streq (optarg, "default") || streq (optarg, "d"))
6223 unicode_display = unicode_default;
6224 else if (streq (optarg, "locale") || streq (optarg, "l"))
6225 unicode_display = unicode_locale;
6226 else if (streq (optarg, "escape") || streq (optarg, "e"))
6227 unicode_display = unicode_escape;
6228 else if (streq (optarg, "invalid") || streq (optarg, "i"))
6229 unicode_display = unicode_invalid;
6230 else if (streq (optarg, "hex") || streq (optarg, "x"))
6231 unicode_display = unicode_hex;
6232 else if (streq (optarg, "highlight") || streq (optarg, "h"))
6233 unicode_display = unicode_highlight;
6234 else
6235 fatal (_("invalid argument to -U/--unicode: %s"), optarg);
6236 break;
6238 case 'H':
6239 usage (stdout, 0);
6240 /* No need to set seenflag or to break - usage() does not return. */
6241 default:
6242 usage (stderr, 1);
6246 if (disassembler_color == on_if_terminal_output)
6247 disassembler_color = isatty (1) ? on : off;
6249 if (show_version)
6250 print_version ("objdump");
6252 if (!seenflag)
6253 usage (stderr, 2);
6255 dump_any_debugging = (dump_debugging
6256 || dump_dwarf_section_info
6257 || process_links
6258 || with_source_code);
6260 if (formats_info)
6261 exit_status = display_info ();
6262 else
6264 if (optind == argc)
6265 display_file ("a.out", target, true);
6266 else
6267 for (; optind < argc;)
6269 display_file (argv[optind], target, optind == argc - 1);
6270 optind++;
6274 free_only_list ();
6275 free (dump_ctf_section_name);
6276 free (dump_ctf_parent_name);
6277 free ((void *) source_comment);
6279 return exit_status;