Update release-README after completing the 2.43 release.
[binutils-gdb.git] / binutils / objdump.c
blob324254658c609fa78ed8b1720736e1f9954f7a03
1 /* objdump.c -- dump information about an object file.
2 Copyright (C) 1990-2024 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 char *dump_ctf_parent_section_name; /* --ctf-parent-section */
112 static int dump_sframe_section_info; /* --sframe */
113 static char *dump_sframe_section_name;
114 static int do_demangle; /* -C, --demangle */
115 static bool disassemble; /* -d */
116 static bool disassemble_all; /* -D */
117 static int disassemble_zeroes; /* --disassemble-zeroes */
118 static bool formats_info; /* -i */
119 int wide_output; /* -w */
120 static int insn_width; /* --insn-width */
121 static bfd_vma start_address = (bfd_vma) -1; /* --start-address */
122 static bfd_vma stop_address = (bfd_vma) -1; /* --stop-address */
123 static int dump_debugging; /* --debugging */
124 static int dump_debugging_tags; /* --debugging-tags */
125 static int suppress_bfd_header;
126 static int dump_special_syms = 0; /* --special-syms */
127 static bfd_vma adjust_section_vma = 0; /* --adjust-vma */
128 static int file_start_context = 0; /* --file-start-context */
129 static bool display_file_offsets; /* -F */
130 static const char *prefix; /* --prefix */
131 static int prefix_strip; /* --prefix-strip */
132 static size_t prefix_length;
133 static bool unwind_inlines; /* --inlines. */
134 static const char * disasm_sym; /* Disassembly start symbol. */
135 static const char * source_comment; /* --source_comment. */
136 static bool visualize_jumps = false; /* --visualize-jumps. */
137 static bool color_output = false; /* --visualize-jumps=color. */
138 static bool extended_color_output = false; /* --visualize-jumps=extended-color. */
139 static int process_links = false; /* --process-links. */
140 static int show_all_symbols; /* --show-all-symbols. */
141 static bool decompressed_dumps = false; /* -Z, --decompress. */
143 static enum color_selection
145 on_if_terminal_output,
146 on, /* --disassembler-color=color. */
147 off, /* --disassembler-color=off. */
148 extended /* --disassembler-color=extended-color. */
149 } disassembler_color =
150 #if DEFAULT_FOR_COLORED_DISASSEMBLY
151 on_if_terminal_output;
152 #else
153 off;
154 #endif
156 static int dump_any_debugging;
157 static int demangle_flags = DMGL_ANSI | DMGL_PARAMS;
159 /* This is reset to false each time we enter the disassembler, and set true
160 when the disassembler emits something in the dis_style_comment_start
161 style. Once this is true, all further output on that line is done in
162 the comment style. This only has an effect when disassembler coloring
163 is turned on. */
164 static bool disassembler_in_comment = false;
166 /* A structure to record the sections mentioned in -j switches. */
167 struct only
169 const char *name; /* The name of the section. */
170 bool seen; /* A flag to indicate that the section has been found in one or more input files. */
171 struct only *next; /* Pointer to the next structure in the list. */
173 /* Pointer to an array of 'only' structures.
174 This pointer is NULL if the -j switch has not been used. */
175 static struct only * only_list = NULL;
177 /* Variables for handling include file path table. */
178 static const char **include_paths;
179 static int include_path_count;
181 /* Extra info to pass to the section disassembler and address printing
182 function. */
183 struct objdump_disasm_info
185 bfd *abfd;
186 bool require_sec;
187 disassembler_ftype disassemble_fn;
188 arelent *reloc;
189 const char *symbol;
192 /* Architecture to disassemble for, or default if NULL. */
193 static char *machine = NULL;
195 /* Target specific options to the disassembler. */
196 static char *disassembler_options = NULL;
198 /* Endianness to disassemble for, or default if BFD_ENDIAN_UNKNOWN. */
199 static enum bfd_endian endian = BFD_ENDIAN_UNKNOWN;
201 /* The symbol table. */
202 static asymbol **syms;
204 /* Number of symbols in `syms'. */
205 static long symcount = 0;
207 /* The sorted symbol table. */
208 static asymbol **sorted_syms;
210 /* Number of symbols in `sorted_syms'. */
211 static long sorted_symcount = 0;
213 /* The dynamic symbol table. */
214 static asymbol **dynsyms;
216 /* The synthetic symbol table. */
217 static asymbol *synthsyms;
218 static long synthcount = 0;
220 /* Number of symbols in `dynsyms'. */
221 static long dynsymcount = 0;
223 static bfd_byte *stabs;
224 static bfd_size_type stab_size;
226 static bfd_byte *strtab;
227 static bfd_size_type stabstr_size;
229 /* Handlers for -P/--private. */
230 static const struct objdump_private_desc * const objdump_private_vectors[] =
232 OBJDUMP_PRIVATE_VECTORS
233 NULL
236 /* The list of detected jumps inside a function. */
237 static struct jump_info *detected_jumps = NULL;
239 typedef enum unicode_display_type
241 unicode_default = 0,
242 unicode_locale,
243 unicode_escape,
244 unicode_hex,
245 unicode_highlight,
246 unicode_invalid
247 } unicode_display_type;
249 static unicode_display_type unicode_display = unicode_default;
251 static void usage (FILE *, int) ATTRIBUTE_NORETURN;
252 static void
253 usage (FILE *stream, int status)
255 fprintf (stream, _("Usage: %s <option(s)> <file(s)>\n"), program_name);
256 fprintf (stream, _(" Display information from object <file(s)>.\n"));
257 fprintf (stream, _(" At least one of the following switches must be given:\n"));
258 fprintf (stream, _("\
259 -a, --archive-headers Display archive header information\n"));
260 fprintf (stream, _("\
261 -f, --file-headers Display the contents of the overall file header\n"));
262 fprintf (stream, _("\
263 -p, --private-headers Display object format specific file header contents\n"));
264 fprintf (stream, _("\
265 -P, --private=OPT,OPT... Display object format specific contents\n"));
266 fprintf (stream, _("\
267 -h, --[section-]headers Display the contents of the section headers\n"));
268 fprintf (stream, _("\
269 -x, --all-headers Display the contents of all headers\n"));
270 fprintf (stream, _("\
271 -d, --disassemble Display assembler contents of executable sections\n"));
272 fprintf (stream, _("\
273 -D, --disassemble-all Display assembler contents of all sections\n"));
274 fprintf (stream, _("\
275 --disassemble=<sym> Display assembler contents from <sym>\n"));
276 fprintf (stream, _("\
277 -S, --source Intermix source code with disassembly\n"));
278 fprintf (stream, _("\
279 --source-comment[=<txt>] Prefix lines of source code with <txt>\n"));
280 fprintf (stream, _("\
281 -s, --full-contents Display the full contents of all sections requested\n"));
282 fprintf (stream, _("\
283 -Z, --decompress Decompress section(s) before displaying their contents\n"));
284 fprintf (stream, _("\
285 -g, --debugging Display debug information in object file\n"));
286 fprintf (stream, _("\
287 -e, --debugging-tags Display debug information using ctags style\n"));
288 fprintf (stream, _("\
289 -G, --stabs Display (in raw form) any STABS info in the file\n"));
290 fprintf (stream, _("\
291 -W, --dwarf[a/=abbrev, A/=addr, r/=aranges, c/=cu_index, L/=decodedline,\n\
292 f/=frames, F/=frames-interp, g/=gdb_index, i/=info, o/=loc,\n\
293 m/=macro, p/=pubnames, t/=pubtypes, R/=Ranges, l/=rawline,\n\
294 s/=str, O/=str-offsets, u/=trace_abbrev, T/=trace_aranges,\n\
295 U/=trace_info]\n\
296 Display the contents of DWARF debug sections\n"));
297 fprintf (stream, _("\
298 -Wk,--dwarf=links Display the contents of sections that link to\n\
299 separate debuginfo files\n"));
300 #if DEFAULT_FOR_FOLLOW_LINKS
301 fprintf (stream, _("\
302 -WK,--dwarf=follow-links\n\
303 Follow links to separate debug info files (default)\n"));
304 fprintf (stream, _("\
305 -WN,--dwarf=no-follow-links\n\
306 Do not follow links to separate debug info files\n"));
307 #else
308 fprintf (stream, _("\
309 -WK,--dwarf=follow-links\n\
310 Follow links to separate debug info files\n"));
311 fprintf (stream, _("\
312 -WN,--dwarf=no-follow-links\n\
313 Do not follow links to separate debug info files\n\
314 (default)\n"));
315 #endif
316 #if HAVE_LIBDEBUGINFOD
317 fprintf (stream, _("\
318 -WD --dwarf=use-debuginfod\n\
319 When following links, also query debuginfod servers (default)\n"));
320 fprintf (stream, _("\
321 -WE --dwarf=do-not-use-debuginfod\n\
322 When following links, do not query debuginfod servers\n"));
323 #endif
324 fprintf (stream, _("\
325 -L, --process-links Display the contents of non-debug sections in\n\
326 separate debuginfo files. (Implies -WK)\n"));
327 #ifdef ENABLE_LIBCTF
328 fprintf (stream, _("\
329 --ctf[=SECTION] Display CTF info from SECTION, (default `.ctf')\n"));
330 #endif
331 fprintf (stream, _("\
332 --sframe[=SECTION] Display SFrame info from SECTION, (default '.sframe')\n"));
333 fprintf (stream, _("\
334 -t, --syms Display the contents of the symbol table(s)\n"));
335 fprintf (stream, _("\
336 -T, --dynamic-syms Display the contents of the dynamic symbol table\n"));
337 fprintf (stream, _("\
338 -r, --reloc Display the relocation entries in the file\n"));
339 fprintf (stream, _("\
340 -R, --dynamic-reloc Display the dynamic relocation entries in the file\n"));
341 fprintf (stream, _("\
342 @<file> Read options from <file>\n"));
343 fprintf (stream, _("\
344 -v, --version Display this program's version number\n"));
345 fprintf (stream, _("\
346 -i, --info List object formats and architectures supported\n"));
347 fprintf (stream, _("\
348 -H, --help Display this information\n"));
350 if (status != 2)
352 const struct objdump_private_desc * const *desc;
354 fprintf (stream, _("\n The following switches are optional:\n"));
355 fprintf (stream, _("\
356 -b, --target=BFDNAME Specify the target object format as BFDNAME\n"));
357 fprintf (stream, _("\
358 -m, --architecture=MACHINE Specify the target architecture as MACHINE\n"));
359 fprintf (stream, _("\
360 -j, --section=NAME Only display information for section NAME\n"));
361 fprintf (stream, _("\
362 -M, --disassembler-options=OPT Pass text OPT on to the disassembler\n"));
363 fprintf (stream, _("\
364 -EB --endian=big Assume big endian format when disassembling\n"));
365 fprintf (stream, _("\
366 -EL --endian=little Assume little endian format when disassembling\n"));
367 fprintf (stream, _("\
368 --file-start-context Include context from start of file (with -S)\n"));
369 fprintf (stream, _("\
370 -I, --include=DIR Add DIR to search list for source files\n"));
371 fprintf (stream, _("\
372 -l, --line-numbers Include line numbers and filenames in output\n"));
373 fprintf (stream, _("\
374 -F, --file-offsets Include file offsets when displaying information\n"));
375 fprintf (stream, _("\
376 -C, --demangle[=STYLE] Decode mangled/processed symbol names\n"));
377 display_demangler_styles (stream, _("\
378 STYLE can be "));
379 fprintf (stream, _("\
380 --recurse-limit Enable a limit on recursion whilst demangling\n\
381 (default)\n"));
382 fprintf (stream, _("\
383 --no-recurse-limit Disable a limit on recursion whilst demangling\n"));
384 fprintf (stream, _("\
385 -w, --wide Format output for more than 80 columns\n"));
386 fprintf (stream, _("\
387 -U[d|l|i|x|e|h] Controls the display of UTF-8 unicode characters\n\
388 --unicode=[default|locale|invalid|hex|escape|highlight]\n"));
389 fprintf (stream, _("\
390 -z, --disassemble-zeroes Do not skip blocks of zeroes when disassembling\n"));
391 fprintf (stream, _("\
392 --start-address=ADDR Only process data whose address is >= ADDR\n"));
393 fprintf (stream, _("\
394 --stop-address=ADDR Only process data whose address is < ADDR\n"));
395 fprintf (stream, _("\
396 --no-addresses Do not print address alongside disassembly\n"));
397 fprintf (stream, _("\
398 --prefix-addresses Print complete address alongside disassembly\n"));
399 fprintf (stream, _("\
400 --[no-]show-raw-insn Display hex alongside symbolic disassembly\n"));
401 fprintf (stream, _("\
402 --insn-width=WIDTH Display WIDTH bytes on a single line for -d\n"));
403 fprintf (stream, _("\
404 --adjust-vma=OFFSET Add OFFSET to all displayed section addresses\n"));
405 fprintf (stream, _("\
406 --show-all-symbols When disassembling, display all symbols at a given address\n"));
407 fprintf (stream, _("\
408 --special-syms Include special symbols in symbol dumps\n"));
409 fprintf (stream, _("\
410 --inlines Print all inlines for source line (with -l)\n"));
411 fprintf (stream, _("\
412 --prefix=PREFIX Add PREFIX to absolute paths for -S\n"));
413 fprintf (stream, _("\
414 --prefix-strip=LEVEL Strip initial directory names for -S\n"));
415 fprintf (stream, _("\
416 --dwarf-depth=N Do not display DIEs at depth N or greater\n"));
417 fprintf (stream, _("\
418 --dwarf-start=N Display DIEs starting at offset N\n"));
419 fprintf (stream, _("\
420 --dwarf-check Make additional dwarf consistency checks.\n"));
421 #ifdef ENABLE_LIBCTF
422 fprintf (stream, _("\
423 --ctf-parent=NAME Use CTF archive member NAME as the CTF parent\n"));
424 #endif
425 fprintf (stream, _("\
426 --visualize-jumps Visualize jumps by drawing ASCII art lines\n"));
427 fprintf (stream, _("\
428 --visualize-jumps=color Use colors in the ASCII art\n"));
429 fprintf (stream, _("\
430 --visualize-jumps=extended-color\n\
431 Use extended 8-bit color codes\n"));
432 fprintf (stream, _("\
433 --visualize-jumps=off Disable jump visualization\n"));
434 #if DEFAULT_FOR_COLORED_DISASSEMBLY
435 fprintf (stream, _("\
436 --disassembler-color=off Disable disassembler color output.\n"));
437 fprintf (stream, _("\
438 --disassembler-color=terminal Enable disassembler color output if displaying on a terminal. (default)\n"));
439 #else
440 fprintf (stream, _("\
441 --disassembler-color=off Disable disassembler color output. (default)\n"));
442 fprintf (stream, _("\
443 --disassembler-color=terminal Enable disassembler color output if displaying on a terminal.\n"));
444 #endif
445 fprintf (stream, _("\
446 --disassembler-color=on Enable disassembler color output.\n"));
447 fprintf (stream, _("\
448 --disassembler-color=extended Use 8-bit colors in disassembler output.\n\n"));
450 list_supported_targets (program_name, stream);
451 list_supported_architectures (program_name, stream);
453 disassembler_usage (stream);
455 if (objdump_private_vectors[0] != NULL)
457 fprintf (stream,
458 _("\nOptions supported for -P/--private switch:\n"));
459 for (desc = objdump_private_vectors; *desc != NULL; desc++)
460 (*desc)->help (stream);
463 if (REPORT_BUGS_TO[0] && status == 0)
464 fprintf (stream, _("Report bugs to %s.\n"), REPORT_BUGS_TO);
465 exit (status);
468 /* 150 isn't special; it's just an arbitrary non-ASCII char value. */
469 enum option_values
471 OPTION_ENDIAN=150,
472 OPTION_START_ADDRESS,
473 OPTION_STOP_ADDRESS,
474 OPTION_DWARF,
475 OPTION_PREFIX,
476 OPTION_PREFIX_STRIP,
477 OPTION_INSN_WIDTH,
478 OPTION_ADJUST_VMA,
479 OPTION_DWARF_DEPTH,
480 OPTION_DWARF_CHECK,
481 OPTION_DWARF_START,
482 OPTION_RECURSE_LIMIT,
483 OPTION_NO_RECURSE_LIMIT,
484 OPTION_INLINES,
485 OPTION_SOURCE_COMMENT,
486 #ifdef ENABLE_LIBCTF
487 OPTION_CTF,
488 OPTION_CTF_PARENT,
489 OPTION_CTF_PARENT_SECTION,
490 #endif
491 OPTION_SFRAME,
492 OPTION_VISUALIZE_JUMPS,
493 OPTION_DISASSEMBLER_COLOR
496 static struct option long_options[]=
498 {"adjust-vma", required_argument, NULL, OPTION_ADJUST_VMA},
499 {"all-headers", no_argument, NULL, 'x'},
500 {"architecture", required_argument, NULL, 'm'},
501 {"archive-headers", no_argument, NULL, 'a'},
502 #ifdef ENABLE_LIBCTF
503 {"ctf", optional_argument, NULL, OPTION_CTF},
504 {"ctf-parent", required_argument, NULL, OPTION_CTF_PARENT},
505 {"ctf-parent-section", required_argument, NULL, OPTION_CTF_PARENT_SECTION},
506 #endif
507 {"debugging", no_argument, NULL, 'g'},
508 {"debugging-tags", no_argument, NULL, 'e'},
509 {"decompress", no_argument, NULL, 'Z'},
510 {"demangle", optional_argument, NULL, 'C'},
511 {"disassemble", optional_argument, NULL, 'd'},
512 {"disassemble-all", no_argument, NULL, 'D'},
513 {"disassemble-zeroes", no_argument, NULL, 'z'},
514 {"disassembler-options", required_argument, NULL, 'M'},
515 {"dwarf", optional_argument, NULL, OPTION_DWARF},
516 {"dwarf-check", no_argument, 0, OPTION_DWARF_CHECK},
517 {"dwarf-depth", required_argument, 0, OPTION_DWARF_DEPTH},
518 {"dwarf-start", required_argument, 0, OPTION_DWARF_START},
519 {"dynamic-reloc", no_argument, NULL, 'R'},
520 {"dynamic-syms", no_argument, NULL, 'T'},
521 {"endian", required_argument, NULL, OPTION_ENDIAN},
522 {"file-headers", no_argument, NULL, 'f'},
523 {"file-offsets", no_argument, NULL, 'F'},
524 {"file-start-context", no_argument, &file_start_context, 1},
525 {"full-contents", no_argument, NULL, 's'},
526 {"headers", no_argument, NULL, 'h'},
527 {"help", no_argument, NULL, 'H'},
528 {"include", required_argument, NULL, 'I'},
529 {"info", no_argument, NULL, 'i'},
530 {"inlines", no_argument, 0, OPTION_INLINES},
531 {"insn-width", required_argument, NULL, OPTION_INSN_WIDTH},
532 {"line-numbers", no_argument, NULL, 'l'},
533 {"no-addresses", no_argument, &no_addresses, 1},
534 {"no-recurse-limit", no_argument, NULL, OPTION_NO_RECURSE_LIMIT},
535 {"no-recursion-limit", no_argument, NULL, OPTION_NO_RECURSE_LIMIT},
536 {"no-show-raw-insn", no_argument, &show_raw_insn, -1},
537 {"prefix", required_argument, NULL, OPTION_PREFIX},
538 {"prefix-addresses", no_argument, &prefix_addresses, 1},
539 {"prefix-strip", required_argument, NULL, OPTION_PREFIX_STRIP},
540 {"private", required_argument, NULL, 'P'},
541 {"private-headers", no_argument, NULL, 'p'},
542 {"process-links", no_argument, &process_links, true},
543 {"recurse-limit", no_argument, NULL, OPTION_RECURSE_LIMIT},
544 {"recursion-limit", no_argument, NULL, OPTION_RECURSE_LIMIT},
545 {"reloc", no_argument, NULL, 'r'},
546 {"section", required_argument, NULL, 'j'},
547 {"section-headers", no_argument, NULL, 'h'},
548 {"sframe", optional_argument, NULL, OPTION_SFRAME},
549 {"show-all-symbols", no_argument, &show_all_symbols, 1},
550 {"show-raw-insn", no_argument, &show_raw_insn, 1},
551 {"source", no_argument, NULL, 'S'},
552 {"source-comment", optional_argument, NULL, OPTION_SOURCE_COMMENT},
553 {"special-syms", no_argument, &dump_special_syms, 1},
554 {"stabs", no_argument, NULL, 'G'},
555 {"start-address", required_argument, NULL, OPTION_START_ADDRESS},
556 {"stop-address", required_argument, NULL, OPTION_STOP_ADDRESS},
557 {"syms", no_argument, NULL, 't'},
558 {"target", required_argument, NULL, 'b'},
559 {"unicode", required_argument, NULL, 'U'},
560 {"version", no_argument, NULL, 'V'},
561 {"visualize-jumps", optional_argument, 0, OPTION_VISUALIZE_JUMPS},
562 {"wide", no_argument, NULL, 'w'},
563 {"disassembler-color", required_argument, NULL, OPTION_DISASSEMBLER_COLOR},
564 {NULL, no_argument, NULL, 0}
567 static void
568 my_bfd_nonfatal (const char *msg)
570 bfd_nonfatal (msg);
571 exit_status = 1;
574 /* Convert a potential UTF-8 encoded sequence in IN into characters in OUT.
575 The conversion format is controlled by the unicode_display variable.
576 Returns the number of characters added to OUT.
577 Returns the number of bytes consumed from IN in CONSUMED.
578 Always consumes at least one byte and displays at least one character. */
580 static unsigned int
581 display_utf8 (const unsigned char * in, char * out, unsigned int * consumed)
583 char * orig_out = out;
584 unsigned int nchars = 0;
585 unsigned int j;
587 if (unicode_display == unicode_default)
588 goto invalid;
590 if (in[0] < 0xc0)
591 goto invalid;
593 if ((in[1] & 0xc0) != 0x80)
594 goto invalid;
596 if ((in[0] & 0x20) == 0)
598 nchars = 2;
599 goto valid;
602 if ((in[2] & 0xc0) != 0x80)
603 goto invalid;
605 if ((in[0] & 0x10) == 0)
607 nchars = 3;
608 goto valid;
611 if ((in[3] & 0xc0) != 0x80)
612 goto invalid;
614 nchars = 4;
616 valid:
617 switch (unicode_display)
619 case unicode_locale:
620 /* Copy the bytes into the output buffer as is. */
621 memcpy (out, in, nchars);
622 out += nchars;
623 break;
625 case unicode_invalid:
626 case unicode_hex:
627 *out++ = unicode_display == unicode_hex ? '<' : '{';
628 *out++ = '0';
629 *out++ = 'x';
630 for (j = 0; j < nchars; j++)
631 out += sprintf (out, "%02x", in [j]);
632 *out++ = unicode_display == unicode_hex ? '>' : '}';
633 break;
635 case unicode_highlight:
636 if (isatty (1))
637 out += sprintf (out, "\x1B[31;47m"); /* Red. */
638 /* Fall through. */
639 case unicode_escape:
640 switch (nchars)
642 case 2:
643 out += sprintf (out, "\\u%02x%02x",
644 ((in[0] & 0x1c) >> 2),
645 ((in[0] & 0x03) << 6) | (in[1] & 0x3f));
646 break;
648 case 3:
649 out += sprintf (out, "\\u%02x%02x",
650 ((in[0] & 0x0f) << 4) | ((in[1] & 0x3c) >> 2),
651 ((in[1] & 0x03) << 6) | ((in[2] & 0x3f)));
652 break;
654 case 4:
655 out += sprintf (out, "\\u%02x%02x%02x",
656 ((in[0] & 0x07) << 6) | ((in[1] & 0x3c) >> 2),
657 ((in[1] & 0x03) << 6) | ((in[2] & 0x3c) >> 2),
658 ((in[2] & 0x03) << 6) | ((in[3] & 0x3f)));
659 break;
660 default:
661 /* URG. */
662 break;
665 if (unicode_display == unicode_highlight && isatty (1))
666 out += sprintf (out, "\x1B[0m"); /* Default colour. */
667 break;
669 default:
670 /* URG */
671 break;
674 * consumed = nchars;
675 return out - orig_out;
677 invalid:
678 /* Not a valid UTF-8 sequence. */
679 *out = *in;
680 * consumed = 1;
681 return 1;
684 /* Returns a version of IN with any control characters
685 replaced by escape sequences. Uses a static buffer
686 if necessary.
688 If unicode display is enabled, then also handles the
689 conversion of unicode characters. */
691 static const char *
692 sanitize_string (const char * in)
694 static char * buffer = NULL;
695 static size_t buffer_len = 0;
696 const char * original = in;
697 char * out;
699 /* Paranoia. */
700 if (in == NULL)
701 return "";
703 /* See if any conversion is necessary. In the majority
704 of cases it will not be needed. */
707 unsigned char c = *in++;
709 if (c == 0)
710 return original;
712 if (ISCNTRL (c))
713 break;
715 if (unicode_display != unicode_default && c >= 0xc0)
716 break;
718 while (1);
720 /* Copy the input, translating as needed. */
721 in = original;
722 /* For 2 char unicode, max out is 12 (colour escapes) + 6, ie. 9 per in
723 For hex, max out is 8 for 2 char unicode, ie. 4 per in.
724 3 and 4 char unicode produce less output for input. */
725 size_t max_needed = strlen (in) * 9 + 1;
726 if (buffer_len < max_needed)
728 buffer_len = max_needed;
729 free (buffer);
730 buffer = xmalloc (buffer_len);
733 out = buffer;
736 unsigned char c = *in++;
738 if (c == 0)
739 break;
741 if (ISCNTRL (c))
743 *out++ = '^';
744 *out++ = c + 0x40;
746 else if (unicode_display != unicode_default && c >= 0xc0)
748 unsigned int num_consumed;
750 out += display_utf8 ((const unsigned char *) --in, out, &num_consumed);
751 in += num_consumed;
753 else
754 *out++ = c;
756 while (1);
758 *out = 0;
759 return buffer;
763 /* Returns TRUE if the specified section should be dumped. */
765 static bool
766 process_section_p (asection * section)
768 struct only * only;
770 if (only_list == NULL)
771 return true;
773 for (only = only_list; only; only = only->next)
774 if (strcmp (only->name, section->name) == 0)
776 only->seen = true;
777 return true;
780 return false;
783 /* Add an entry to the 'only' list. */
785 static void
786 add_only (char * name)
788 struct only * only;
790 /* First check to make sure that we do not
791 already have an entry for this name. */
792 for (only = only_list; only; only = only->next)
793 if (strcmp (only->name, name) == 0)
794 return;
796 only = xmalloc (sizeof * only);
797 only->name = name;
798 only->seen = false;
799 only->next = only_list;
800 only_list = only;
803 /* Release the memory used by the 'only' list.
804 PR 11225: Issue a warning message for unseen sections.
805 Only do this if none of the sections were seen. This is mainly to support
806 tools like the GAS testsuite where an object file is dumped with a list of
807 generic section names known to be present in a range of different file
808 formats. */
810 static void
811 free_only_list (void)
813 bool at_least_one_seen = false;
814 struct only * only;
815 struct only * next;
817 if (only_list == NULL)
818 return;
820 for (only = only_list; only; only = only->next)
821 if (only->seen)
823 at_least_one_seen = true;
824 break;
827 for (only = only_list; only; only = next)
829 if (! at_least_one_seen)
831 non_fatal (_("section '%s' mentioned in a -j option, "
832 "but not found in any input file"),
833 only->name);
834 exit_status = 1;
836 next = only->next;
837 free (only);
842 static void
843 dump_section_header (bfd *abfd, asection *section, void *data)
845 char *comma = "";
846 unsigned int opb = bfd_octets_per_byte (abfd, section);
847 int longest_section_name = *((int *) data);
849 /* Ignore linker created section. See elfNN_ia64_object_p in
850 bfd/elfxx-ia64.c. */
851 if (section->flags & SEC_LINKER_CREATED)
852 return;
854 /* PR 10413: Skip sections that we are ignoring. */
855 if (! process_section_p (section))
856 return;
858 printf ("%3d %-*s %08lx ", section->index, longest_section_name,
859 sanitize_string (bfd_section_name (section)),
860 (unsigned long) bfd_section_size (section) / opb);
861 bfd_printf_vma (abfd, bfd_section_vma (section));
862 printf (" ");
863 bfd_printf_vma (abfd, section->lma);
864 printf (" %08lx 2**%u", (unsigned long) section->filepos,
865 bfd_section_alignment (section));
866 if (! wide_output)
867 printf ("\n ");
868 printf (" ");
870 #define PF(x, y) \
871 if (section->flags & x) { printf ("%s%s", comma, y); comma = ", "; }
873 PF (SEC_HAS_CONTENTS, "CONTENTS");
874 PF (SEC_ALLOC, "ALLOC");
875 PF (SEC_CONSTRUCTOR, "CONSTRUCTOR");
876 PF (SEC_LOAD, "LOAD");
877 PF (SEC_RELOC, "RELOC");
878 PF (SEC_READONLY, "READONLY");
879 PF (SEC_CODE, "CODE");
880 PF (SEC_DATA, "DATA");
881 PF (SEC_ROM, "ROM");
882 PF (SEC_DEBUGGING, "DEBUGGING");
883 PF (SEC_NEVER_LOAD, "NEVER_LOAD");
884 PF (SEC_EXCLUDE, "EXCLUDE");
885 PF (SEC_SORT_ENTRIES, "SORT_ENTRIES");
886 if (bfd_get_arch (abfd) == bfd_arch_tic54x)
888 PF (SEC_TIC54X_BLOCK, "BLOCK");
889 PF (SEC_TIC54X_CLINK, "CLINK");
891 PF (SEC_SMALL_DATA, "SMALL_DATA");
892 if (bfd_get_flavour (abfd) == bfd_target_coff_flavour)
894 PF (SEC_COFF_SHARED, "SHARED");
895 PF (SEC_COFF_NOREAD, "NOREAD");
897 else if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
899 PF (SEC_ELF_OCTETS, "OCTETS");
900 PF (SEC_ELF_PURECODE, "PURECODE");
902 PF (SEC_THREAD_LOCAL, "THREAD_LOCAL");
903 PF (SEC_GROUP, "GROUP");
904 if (bfd_get_arch (abfd) == bfd_arch_mep)
906 PF (SEC_MEP_VLIW, "VLIW");
909 if ((section->flags & SEC_LINK_ONCE) != 0)
911 const char *ls;
912 struct coff_comdat_info *comdat;
914 switch (section->flags & SEC_LINK_DUPLICATES)
916 default:
917 abort ();
918 case SEC_LINK_DUPLICATES_DISCARD:
919 ls = "LINK_ONCE_DISCARD";
920 break;
921 case SEC_LINK_DUPLICATES_ONE_ONLY:
922 ls = "LINK_ONCE_ONE_ONLY";
923 break;
924 case SEC_LINK_DUPLICATES_SAME_SIZE:
925 ls = "LINK_ONCE_SAME_SIZE";
926 break;
927 case SEC_LINK_DUPLICATES_SAME_CONTENTS:
928 ls = "LINK_ONCE_SAME_CONTENTS";
929 break;
931 printf ("%s%s", comma, ls);
933 comdat = bfd_coff_get_comdat_section (abfd, section);
934 if (comdat != NULL)
935 printf (" (COMDAT %s %ld)", comdat->name, comdat->symbol);
937 comma = ", ";
940 if (bfd_is_section_compressed (abfd, section))
941 printf ("%sCOMPRESSED", comma);
943 printf ("\n");
944 #undef PF
947 /* Called on each SECTION in ABFD, update the int variable pointed to by
948 DATA which contains the string length of the longest section name. */
950 static void
951 find_longest_section_name (bfd *abfd ATTRIBUTE_UNUSED,
952 asection *section, void *data)
954 int *longest_so_far = (int *) data;
955 const char *name;
956 int len;
958 /* Ignore linker created section. */
959 if (section->flags & SEC_LINKER_CREATED)
960 return;
962 /* Skip sections that we are ignoring. */
963 if (! process_section_p (section))
964 return;
966 name = bfd_section_name (section);
967 len = (int) strlen (name);
968 if (len > *longest_so_far)
969 *longest_so_far = len;
972 static void
973 dump_headers (bfd *abfd)
975 /* The default width of 13 is just an arbitrary choice. */
976 int max_section_name_length = 13;
977 int bfd_vma_width;
979 #ifndef BFD64
980 bfd_vma_width = 10;
981 #else
982 /* With BFD64, non-ELF returns -1 and wants always 64 bit addresses. */
983 if (bfd_get_arch_size (abfd) == 32)
984 bfd_vma_width = 10;
985 else
986 bfd_vma_width = 18;
987 #endif
989 printf (_("Sections:\n"));
991 if (wide_output)
992 bfd_map_over_sections (abfd, find_longest_section_name,
993 &max_section_name_length);
995 printf (_("Idx %-*s Size %-*s%-*sFile off Algn"),
996 max_section_name_length, "Name",
997 bfd_vma_width, "VMA",
998 bfd_vma_width, "LMA");
1000 if (wide_output)
1001 printf (_(" Flags"));
1002 printf ("\n");
1004 bfd_map_over_sections (abfd, dump_section_header,
1005 &max_section_name_length);
1008 static asymbol **
1009 slurp_symtab (bfd *abfd)
1011 symcount = 0;
1012 if (!(bfd_get_file_flags (abfd) & HAS_SYMS))
1013 return NULL;
1015 long storage = bfd_get_symtab_upper_bound (abfd);
1016 if (storage < 0)
1018 non_fatal (_("failed to read symbol table from: %s"),
1019 bfd_get_filename (abfd));
1020 my_bfd_nonfatal (_("error message was"));
1023 if (storage <= 0)
1024 return NULL;
1026 asymbol **sy = (asymbol **) xmalloc (storage);
1027 symcount = bfd_canonicalize_symtab (abfd, sy);
1028 if (symcount < 0)
1030 my_bfd_nonfatal (bfd_get_filename (abfd));
1031 free (sy);
1032 sy = NULL;
1033 symcount = 0;
1035 return sy;
1038 /* Read in the dynamic symbols. */
1040 static asymbol **
1041 slurp_dynamic_symtab (bfd *abfd)
1043 dynsymcount = 0;
1044 long storage = bfd_get_dynamic_symtab_upper_bound (abfd);
1045 if (storage < 0)
1047 if (!(bfd_get_file_flags (abfd) & DYNAMIC))
1049 non_fatal (_("%s: not a dynamic object"), bfd_get_filename (abfd));
1050 exit_status = 1;
1051 return NULL;
1054 my_bfd_nonfatal (bfd_get_filename (abfd));
1057 if (storage <= 0)
1058 return NULL;
1060 asymbol **sy = (asymbol **) xmalloc (storage);
1061 dynsymcount = bfd_canonicalize_dynamic_symtab (abfd, sy);
1062 if (dynsymcount < 0)
1064 my_bfd_nonfatal (bfd_get_filename (abfd));
1065 free (sy);
1066 sy = NULL;
1067 dynsymcount = 0;
1069 return sy;
1072 /* Some symbol names are significant and should be kept in the
1073 table of sorted symbol names, even if they are marked as
1074 debugging/section symbols. */
1076 static bool
1077 is_significant_symbol_name (const char * name)
1079 return startswith (name, ".plt") || startswith (name, ".got");
1082 /* Filter out (in place) symbols that are useless for disassembly.
1083 COUNT is the number of elements in SYMBOLS.
1084 Return the number of useful symbols. */
1086 static long
1087 remove_useless_symbols (asymbol **symbols, long count)
1089 asymbol **in_ptr = symbols, **out_ptr = symbols;
1091 while (--count >= 0)
1093 asymbol *sym = *in_ptr++;
1095 if (sym->name == NULL || sym->name[0] == '\0')
1096 continue;
1097 if ((sym->flags & (BSF_DEBUGGING | BSF_SECTION_SYM))
1098 && ! is_significant_symbol_name (sym->name))
1099 continue;
1100 if (bfd_is_und_section (sym->section)
1101 || bfd_is_com_section (sym->section))
1102 continue;
1104 *out_ptr++ = sym;
1106 return out_ptr - symbols;
1109 static const asection *compare_section;
1111 /* Sort symbols into value order. */
1113 static int
1114 compare_symbols (const void *ap, const void *bp)
1116 const asymbol *a = * (const asymbol **) ap;
1117 const asymbol *b = * (const asymbol **) bp;
1118 const char *an;
1119 const char *bn;
1120 size_t anl;
1121 size_t bnl;
1122 bool as, af, bs, bf;
1123 flagword aflags;
1124 flagword bflags;
1126 if (bfd_asymbol_value (a) > bfd_asymbol_value (b))
1127 return 1;
1128 else if (bfd_asymbol_value (a) < bfd_asymbol_value (b))
1129 return -1;
1131 /* Prefer symbols from the section currently being disassembled.
1132 Don't sort symbols from other sections by section, since there
1133 isn't much reason to prefer one section over another otherwise.
1134 See sym_ok comment for why we compare by section name. */
1135 as = strcmp (compare_section->name, a->section->name) == 0;
1136 bs = strcmp (compare_section->name, b->section->name) == 0;
1137 if (as && !bs)
1138 return -1;
1139 if (!as && bs)
1140 return 1;
1142 an = bfd_asymbol_name (a);
1143 bn = bfd_asymbol_name (b);
1144 anl = strlen (an);
1145 bnl = strlen (bn);
1147 /* The symbols gnu_compiled and gcc2_compiled convey no real
1148 information, so put them after other symbols with the same value. */
1149 af = (strstr (an, "gnu_compiled") != NULL
1150 || strstr (an, "gcc2_compiled") != NULL);
1151 bf = (strstr (bn, "gnu_compiled") != NULL
1152 || strstr (bn, "gcc2_compiled") != NULL);
1154 if (af && ! bf)
1155 return 1;
1156 if (! af && bf)
1157 return -1;
1159 /* We use a heuristic for the file name, to try to sort it after
1160 more useful symbols. It may not work on non Unix systems, but it
1161 doesn't really matter; the only difference is precisely which
1162 symbol names get printed. */
1164 #define file_symbol(s, sn, snl) \
1165 (((s)->flags & BSF_FILE) != 0 \
1166 || ((snl) > 2 \
1167 && (sn)[(snl) - 2] == '.' \
1168 && ((sn)[(snl) - 1] == 'o' \
1169 || (sn)[(snl) - 1] == 'a')))
1171 af = file_symbol (a, an, anl);
1172 bf = file_symbol (b, bn, bnl);
1174 if (af && ! bf)
1175 return 1;
1176 if (! af && bf)
1177 return -1;
1179 /* Sort function and object symbols before global symbols before
1180 local symbols before section symbols before debugging symbols. */
1182 aflags = a->flags;
1183 bflags = b->flags;
1185 if ((aflags & BSF_DEBUGGING) != (bflags & BSF_DEBUGGING))
1187 if ((aflags & BSF_DEBUGGING) != 0)
1188 return 1;
1189 else
1190 return -1;
1192 if ((aflags & BSF_SECTION_SYM) != (bflags & BSF_SECTION_SYM))
1194 if ((aflags & BSF_SECTION_SYM) != 0)
1195 return 1;
1196 else
1197 return -1;
1199 if ((aflags & BSF_FUNCTION) != (bflags & BSF_FUNCTION))
1201 if ((aflags & BSF_FUNCTION) != 0)
1202 return -1;
1203 else
1204 return 1;
1206 if ((aflags & BSF_OBJECT) != (bflags & BSF_OBJECT))
1208 if ((aflags & BSF_OBJECT) != 0)
1209 return -1;
1210 else
1211 return 1;
1213 if ((aflags & BSF_LOCAL) != (bflags & BSF_LOCAL))
1215 if ((aflags & BSF_LOCAL) != 0)
1216 return 1;
1217 else
1218 return -1;
1220 if ((aflags & BSF_GLOBAL) != (bflags & BSF_GLOBAL))
1222 if ((aflags & BSF_GLOBAL) != 0)
1223 return -1;
1224 else
1225 return 1;
1228 /* Sort larger size ELF symbols before smaller. See PR20337. */
1229 bfd_vma asz = 0;
1230 if ((a->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) == 0
1231 && bfd_get_flavour (bfd_asymbol_bfd (a)) == bfd_target_elf_flavour)
1232 asz = ((elf_symbol_type *) a)->internal_elf_sym.st_size;
1233 bfd_vma bsz = 0;
1234 if ((b->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) == 0
1235 && bfd_get_flavour (bfd_asymbol_bfd (b)) == bfd_target_elf_flavour)
1236 bsz = ((elf_symbol_type *) b)->internal_elf_sym.st_size;
1237 if (asz != bsz)
1238 return asz > bsz ? -1 : 1;
1240 /* Symbols that start with '.' might be section names, so sort them
1241 after symbols that don't start with '.'. */
1242 if (an[0] == '.' && bn[0] != '.')
1243 return 1;
1244 if (an[0] != '.' && bn[0] == '.')
1245 return -1;
1247 /* Finally, if we can't distinguish them in any other way, try to
1248 get consistent results by sorting the symbols by name. */
1249 return strcmp (an, bn);
1252 /* Sort relocs into address order. */
1254 static int
1255 compare_relocs (const void *ap, const void *bp)
1257 const arelent *a = * (const arelent **) ap;
1258 const arelent *b = * (const arelent **) bp;
1260 if (a->address > b->address)
1261 return 1;
1262 else if (a->address < b->address)
1263 return -1;
1265 /* So that associated relocations tied to the same address show up
1266 in the correct order, we don't do any further sorting. */
1267 if (a > b)
1268 return 1;
1269 else if (a < b)
1270 return -1;
1271 else
1272 return 0;
1275 /* Print an address (VMA) to the output stream in INFO.
1276 If SKIP_ZEROES is TRUE, omit leading zeroes. */
1278 static void
1279 objdump_print_value (bfd_vma vma, struct disassemble_info *inf,
1280 bool skip_zeroes)
1282 char buf[30];
1283 char *p;
1284 struct objdump_disasm_info *aux;
1286 aux = (struct objdump_disasm_info *) inf->application_data;
1287 bfd_sprintf_vma (aux->abfd, buf, vma);
1288 if (! skip_zeroes)
1289 p = buf;
1290 else
1292 for (p = buf; *p == '0'; ++p)
1294 if (*p == '\0')
1295 --p;
1297 (*inf->fprintf_styled_func) (inf->stream, dis_style_address, "%s", p);
1300 /* Print the name of a symbol. */
1302 static void
1303 objdump_print_symname (bfd *abfd, struct disassemble_info *inf,
1304 asymbol *sym)
1306 char *alloc;
1307 const char *name, *version_string = NULL;
1308 bool hidden = false;
1310 alloc = NULL;
1311 name = bfd_asymbol_name (sym);
1312 if (do_demangle && name[0] != '\0')
1314 /* Demangle the name. */
1315 alloc = bfd_demangle (abfd, name, demangle_flags);
1316 if (alloc != NULL)
1317 name = alloc;
1320 if ((sym->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) == 0)
1321 version_string = bfd_get_symbol_version_string (abfd, sym, true,
1322 &hidden);
1324 if (bfd_is_und_section (bfd_asymbol_section (sym)))
1325 hidden = true;
1327 name = sanitize_string (name);
1329 if (inf != NULL)
1331 (*inf->fprintf_styled_func) (inf->stream, dis_style_symbol, "%s", name);
1332 if (version_string && *version_string != '\0')
1333 (*inf->fprintf_styled_func) (inf->stream, dis_style_symbol,
1334 hidden ? "@%s" : "@@%s",
1335 version_string);
1337 else
1339 printf ("%s", name);
1340 if (version_string && *version_string != '\0')
1341 printf (hidden ? "@%s" : "@@%s", version_string);
1344 if (alloc != NULL)
1345 free (alloc);
1348 static inline bool
1349 sym_ok (bool want_section,
1350 bfd *abfd ATTRIBUTE_UNUSED,
1351 long place,
1352 asection *sec,
1353 struct disassemble_info *inf)
1355 if (want_section)
1357 /* NB: An object file can have different sections with the same
1358 section name. Compare compare section pointers if they have
1359 the same owner. */
1360 if (sorted_syms[place]->section->owner == sec->owner
1361 && sorted_syms[place]->section != sec)
1362 return false;
1364 /* Note - we cannot just compare section pointers because they could
1365 be different, but the same... Ie the symbol that we are trying to
1366 find could have come from a separate debug info file. Under such
1367 circumstances the symbol will be associated with a section in the
1368 debug info file, whilst the section we want is in a normal file.
1369 So the section pointers will be different, but the section names
1370 will be the same. */
1371 if (strcmp (bfd_section_name (sorted_syms[place]->section),
1372 bfd_section_name (sec)) != 0)
1373 return false;
1376 return inf->symbol_is_valid (sorted_syms[place], inf);
1379 /* Locate a symbol given a bfd and a section (from INFO->application_data),
1380 and a VMA. If INFO->application_data->require_sec is TRUE, then always
1381 require the symbol to be in the section. Returns NULL if there is no
1382 suitable symbol. If PLACE is not NULL, then *PLACE is set to the index
1383 of the symbol in sorted_syms. */
1385 static asymbol *
1386 find_symbol_for_address (bfd_vma vma,
1387 struct disassemble_info *inf,
1388 long *place)
1390 /* @@ Would it speed things up to cache the last two symbols returned,
1391 and maybe their address ranges? For many processors, only one memory
1392 operand can be present at a time, so the 2-entry cache wouldn't be
1393 constantly churned by code doing heavy memory accesses. */
1395 /* Indices in `sorted_syms'. */
1396 long min = 0;
1397 long max_count = sorted_symcount;
1398 long thisplace;
1399 struct objdump_disasm_info *aux;
1400 bfd *abfd;
1401 asection *sec;
1402 unsigned int opb;
1403 bool want_section;
1404 long rel_count;
1406 if (sorted_symcount < 1)
1407 return NULL;
1409 aux = (struct objdump_disasm_info *) inf->application_data;
1410 abfd = aux->abfd;
1411 sec = inf->section;
1412 opb = inf->octets_per_byte;
1414 /* Perform a binary search looking for the closest symbol to the
1415 required value. We are searching the range (min, max_count]. */
1416 while (min + 1 < max_count)
1418 asymbol *sym;
1420 thisplace = (max_count + min) / 2;
1421 sym = sorted_syms[thisplace];
1423 if (bfd_asymbol_value (sym) > vma)
1424 max_count = thisplace;
1425 else if (bfd_asymbol_value (sym) < vma)
1426 min = thisplace;
1427 else
1429 min = thisplace;
1430 break;
1434 /* The symbol we want is now in min, the low end of the range we
1435 were searching. If there are several symbols with the same
1436 value, we want the first one. */
1437 thisplace = min;
1438 while (thisplace > 0
1439 && (bfd_asymbol_value (sorted_syms[thisplace])
1440 == bfd_asymbol_value (sorted_syms[thisplace - 1])))
1441 --thisplace;
1443 /* Prefer a symbol in the current section if we have multple symbols
1444 with the same value, as can occur with overlays or zero size
1445 sections. */
1446 min = thisplace;
1447 while (min < max_count
1448 && (bfd_asymbol_value (sorted_syms[min])
1449 == bfd_asymbol_value (sorted_syms[thisplace])))
1451 if (sym_ok (true, abfd, min, sec, inf))
1453 thisplace = min;
1455 if (place != NULL)
1456 *place = thisplace;
1458 return sorted_syms[thisplace];
1460 ++min;
1463 /* If the file is relocatable, and the symbol could be from this
1464 section, prefer a symbol from this section over symbols from
1465 others, even if the other symbol's value might be closer.
1467 Note that this may be wrong for some symbol references if the
1468 sections have overlapping memory ranges, but in that case there's
1469 no way to tell what's desired without looking at the relocation
1470 table.
1472 Also give the target a chance to reject symbols. */
1473 want_section = (aux->require_sec
1474 || ((abfd->flags & HAS_RELOC) != 0
1475 && vma >= bfd_section_vma (sec)
1476 && vma < (bfd_section_vma (sec)
1477 + bfd_section_size (sec) / opb)));
1479 if (! sym_ok (want_section, abfd, thisplace, sec, inf))
1481 long i;
1482 long newplace = sorted_symcount;
1484 for (i = min - 1; i >= 0; i--)
1486 if (sym_ok (want_section, abfd, i, sec, inf))
1488 if (newplace == sorted_symcount)
1489 newplace = i;
1491 if (bfd_asymbol_value (sorted_syms[i])
1492 != bfd_asymbol_value (sorted_syms[newplace]))
1493 break;
1495 /* Remember this symbol and keep searching until we reach
1496 an earlier address. */
1497 newplace = i;
1501 if (newplace != sorted_symcount)
1502 thisplace = newplace;
1503 else
1505 /* We didn't find a good symbol with a smaller value.
1506 Look for one with a larger value. */
1507 for (i = thisplace + 1; i < sorted_symcount; i++)
1509 if (sym_ok (want_section, abfd, i, sec, inf))
1511 thisplace = i;
1512 break;
1517 if (! sym_ok (want_section, abfd, thisplace, sec, inf))
1518 /* There is no suitable symbol. */
1519 return NULL;
1522 /* If we have not found an exact match for the specified address
1523 and we have dynamic relocations available, then we can produce
1524 a better result by matching a relocation to the address and
1525 using the symbol associated with that relocation. */
1526 rel_count = inf->dynrelcount;
1527 if (!want_section
1528 && sorted_syms[thisplace]->value != vma
1529 && rel_count > 0
1530 && inf->dynrelbuf != NULL
1531 && inf->dynrelbuf[0]->address <= vma
1532 && inf->dynrelbuf[rel_count - 1]->address >= vma
1533 /* If we have matched a synthetic symbol, then stick with that. */
1534 && (sorted_syms[thisplace]->flags & BSF_SYNTHETIC) == 0)
1536 arelent ** rel_low;
1537 arelent ** rel_high;
1539 rel_low = inf->dynrelbuf;
1540 rel_high = rel_low + rel_count - 1;
1541 while (rel_low <= rel_high)
1543 arelent **rel_mid = &rel_low[(rel_high - rel_low) / 2];
1544 arelent * rel = *rel_mid;
1546 if (rel->address == vma)
1548 /* Absolute relocations do not provide a more helpful
1549 symbolic address. Find a non-absolute relocation
1550 with the same address. */
1551 arelent **rel_vma = rel_mid;
1552 for (rel_mid--;
1553 rel_mid >= rel_low && rel_mid[0]->address == vma;
1554 rel_mid--)
1555 rel_vma = rel_mid;
1557 for (; rel_vma <= rel_high && rel_vma[0]->address == vma;
1558 rel_vma++)
1560 rel = *rel_vma;
1561 if (rel->sym_ptr_ptr != NULL
1562 && ! bfd_is_abs_section ((* rel->sym_ptr_ptr)->section))
1564 if (place != NULL)
1565 * place = thisplace;
1566 return * rel->sym_ptr_ptr;
1569 break;
1572 if (vma < rel->address)
1573 rel_high = rel_mid;
1574 else if (vma >= rel_mid[1]->address)
1575 rel_low = rel_mid + 1;
1576 else
1577 break;
1581 if (place != NULL)
1582 *place = thisplace;
1584 return sorted_syms[thisplace];
1587 /* Print an address and the offset to the nearest symbol. */
1589 static void
1590 objdump_print_addr_with_sym (bfd *abfd, asection *sec, asymbol *sym,
1591 bfd_vma vma, struct disassemble_info *inf,
1592 bool skip_zeroes)
1594 if (!no_addresses)
1596 objdump_print_value (vma, inf, skip_zeroes);
1597 (*inf->fprintf_styled_func) (inf->stream, dis_style_text, " ");
1600 if (sym == NULL)
1602 bfd_vma secaddr;
1604 (*inf->fprintf_styled_func) (inf->stream, dis_style_text,"<");
1605 (*inf->fprintf_styled_func) (inf->stream, dis_style_symbol, "%s",
1606 sanitize_string (bfd_section_name (sec)));
1607 secaddr = bfd_section_vma (sec);
1608 if (vma < secaddr)
1610 (*inf->fprintf_styled_func) (inf->stream, dis_style_immediate,
1611 "-0x");
1612 objdump_print_value (secaddr - vma, inf, true);
1614 else if (vma > secaddr)
1616 (*inf->fprintf_styled_func) (inf->stream, dis_style_immediate, "+0x");
1617 objdump_print_value (vma - secaddr, inf, true);
1619 (*inf->fprintf_styled_func) (inf->stream, dis_style_text, ">");
1621 else
1623 (*inf->fprintf_styled_func) (inf->stream, dis_style_text, "<");
1625 objdump_print_symname (abfd, inf, sym);
1627 if (bfd_asymbol_value (sym) == vma)
1629 /* Undefined symbols in an executables and dynamic objects do not have
1630 a value associated with them, so it does not make sense to display
1631 an offset relative to them. Normally we would not be provided with
1632 this kind of symbol, but the target backend might choose to do so,
1633 and the code in find_symbol_for_address might return an as yet
1634 unresolved symbol associated with a dynamic reloc. */
1635 else if ((bfd_get_file_flags (abfd) & (EXEC_P | DYNAMIC))
1636 && bfd_is_und_section (sym->section))
1638 else if (bfd_asymbol_value (sym) > vma)
1640 (*inf->fprintf_styled_func) (inf->stream, dis_style_immediate,"-0x");
1641 objdump_print_value (bfd_asymbol_value (sym) - vma, inf, true);
1643 else if (vma > bfd_asymbol_value (sym))
1645 (*inf->fprintf_styled_func) (inf->stream, dis_style_immediate, "+0x");
1646 objdump_print_value (vma - bfd_asymbol_value (sym), inf, true);
1649 (*inf->fprintf_styled_func) (inf->stream, dis_style_text, ">");
1652 if (display_file_offsets)
1653 inf->fprintf_styled_func (inf->stream, dis_style_text,
1654 _(" (File Offset: 0x%lx)"),
1655 (long int)(sec->filepos + (vma - sec->vma)));
1658 /* Displays all symbols in the sorted symbol table starting at PLACE
1659 which match the address VMA. Assumes that show_all_symbols == true. */
1661 static void
1662 display_extra_syms (long place,
1663 bfd_vma vma,
1664 struct disassemble_info *inf)
1666 struct objdump_disasm_info *aux = (struct objdump_disasm_info *) inf->application_data;
1668 if (place == 0)
1669 return;
1671 bool first = true;
1673 for (; place < sorted_symcount; place++)
1675 asymbol *sym = sorted_syms[place];
1677 if (bfd_asymbol_value (sym) != vma)
1678 break;
1680 if (! inf->symbol_is_valid (sym, inf))
1681 continue;
1683 if (first && ! do_wide)
1684 inf->fprintf_styled_func (inf->stream, dis_style_immediate, ",\n\t<");
1685 else
1686 inf->fprintf_styled_func (inf->stream, dis_style_immediate, ", <");
1688 objdump_print_symname (aux->abfd, inf, sym);
1689 inf->fprintf_styled_func (inf->stream, dis_style_immediate, ">");
1690 first = false;
1694 /* Print an address (VMA), symbolically if possible.
1695 If SKIP_ZEROES is TRUE, don't output leading zeroes. */
1697 static void
1698 objdump_print_addr (bfd_vma vma,
1699 struct disassemble_info *inf,
1700 bool skip_zeroes)
1702 struct objdump_disasm_info *aux;
1703 asymbol *sym = NULL;
1704 bool skip_find = false;
1705 long place = 0;
1707 aux = (struct objdump_disasm_info *) inf->application_data;
1709 if (sorted_symcount < 1)
1711 if (!no_addresses)
1713 (*inf->fprintf_styled_func) (inf->stream, dis_style_address, "0x");
1714 objdump_print_value (vma, inf, skip_zeroes);
1717 if (display_file_offsets)
1718 inf->fprintf_styled_func (inf->stream, dis_style_text,
1719 _(" (File Offset: 0x%lx)"),
1720 (long int) (inf->section->filepos
1721 + (vma - inf->section->vma)));
1722 return;
1725 if (aux->reloc != NULL
1726 && aux->reloc->sym_ptr_ptr != NULL
1727 && * aux->reloc->sym_ptr_ptr != NULL)
1729 sym = * aux->reloc->sym_ptr_ptr;
1731 /* Adjust the vma to the reloc. */
1732 vma += bfd_asymbol_value (sym);
1734 if (bfd_is_und_section (bfd_asymbol_section (sym)))
1735 skip_find = true;
1738 if (!skip_find)
1739 sym = find_symbol_for_address (vma, inf, &place);
1741 objdump_print_addr_with_sym (aux->abfd, inf->section, sym, vma, inf,
1742 skip_zeroes);
1744 /* If requested, display any extra symbols at this address. */
1745 if (sym == NULL || ! show_all_symbols)
1746 return;
1748 if (place)
1749 display_extra_syms (place + 1, vma, inf);
1751 /* If we found an absolute symbol in the reloc (ie: "*ABS*+0x....")
1752 and there is a valid symbol at the address contained in the absolute symbol
1753 then display any extra symbols that match this address. This helps
1754 particularly with relocations for PLT entries. */
1755 if (startswith (sym->name, BFD_ABS_SECTION_NAME "+"))
1757 bfd_vma addr = strtoul (sym->name + strlen (BFD_ABS_SECTION_NAME "+"), NULL, 0);
1759 if (addr && addr != vma)
1761 sym = find_symbol_for_address (addr, inf, &place);
1763 if (sym)
1764 display_extra_syms (place, addr, inf);
1769 /* Print VMA to INFO. This function is passed to the disassembler
1770 routine. */
1772 static void
1773 objdump_print_address (bfd_vma vma, struct disassemble_info *inf)
1775 objdump_print_addr (vma, inf, ! prefix_addresses);
1778 /* Determine if the given address has a symbol associated with it. */
1780 static asymbol *
1781 objdump_symbol_at_address (bfd_vma vma, struct disassemble_info * inf)
1783 asymbol * sym;
1785 sym = find_symbol_for_address (vma, inf, NULL);
1786 if (sym != NULL && bfd_asymbol_value (sym) == vma)
1787 return sym;
1789 return NULL;
1792 /* Hold the last function name and the last line number we displayed
1793 in a disassembly. */
1795 static char *prev_functionname;
1796 static unsigned int prev_line;
1797 static unsigned int prev_discriminator;
1799 /* We keep a list of all files that we have seen when doing a
1800 disassembly with source, so that we know how much of the file to
1801 display. This can be important for inlined functions. */
1803 struct print_file_list
1805 struct print_file_list *next;
1806 const char *filename;
1807 const char *modname;
1808 const char *map;
1809 size_t mapsize;
1810 const char **linemap;
1811 unsigned maxline;
1812 unsigned last_line;
1813 unsigned max_printed;
1814 int first;
1817 static struct print_file_list *print_files;
1819 /* The number of preceding context lines to show when we start
1820 displaying a file for the first time. */
1822 #define SHOW_PRECEDING_CONTEXT_LINES (5)
1824 #if HAVE_LIBDEBUGINFOD
1825 /* Return a hex string represention of the build-id. */
1827 unsigned char *
1828 get_build_id (void * data)
1830 unsigned i;
1831 char * build_id_str;
1832 bfd * abfd = (bfd *) data;
1833 const struct bfd_build_id * build_id;
1835 build_id = abfd->build_id;
1836 if (build_id == NULL)
1837 return NULL;
1839 build_id_str = malloc (build_id->size * 2 + 1);
1840 if (build_id_str == NULL)
1841 return NULL;
1843 for (i = 0; i < build_id->size; i++)
1844 sprintf (build_id_str + (i * 2), "%02x", build_id->data[i]);
1845 build_id_str[build_id->size * 2] = '\0';
1847 return (unsigned char *) build_id_str;
1850 /* Search for a separate debug file matching ABFD's build-id. */
1852 static bfd *
1853 find_separate_debug (const bfd * abfd)
1855 const struct bfd_build_id * build_id = abfd->build_id;
1856 separate_info * i = first_separate_info;
1858 if (build_id == NULL || i == NULL)
1859 return NULL;
1861 while (i != NULL)
1863 const bfd * i_bfd = (bfd *) i->handle;
1865 if (abfd != NULL && i_bfd->build_id != NULL)
1867 const unsigned char * data = i_bfd->build_id->data;
1868 size_t size = i_bfd->build_id->size;
1870 if (size == build_id->size
1871 && memcmp (data, build_id->data, size) == 0)
1872 return (bfd *) i->handle;
1875 i = i->next;
1878 return NULL;
1881 /* Search for a separate debug file matching ABFD's .gnu_debugaltlink
1882 build-id. */
1884 static bfd *
1885 find_alt_debug (const bfd * abfd)
1887 size_t namelen;
1888 size_t id_len;
1889 const char * name;
1890 struct dwarf_section * section;
1891 const struct bfd_build_id * build_id = abfd->build_id;
1892 separate_info * i = first_separate_info;
1894 if (i == NULL
1895 || build_id == NULL
1896 || !load_debug_section (gnu_debugaltlink, (void *) abfd))
1897 return NULL;
1899 section = &debug_displays[gnu_debugaltlink].section;
1900 if (section == NULL)
1901 return NULL;
1903 name = (const char *) section->start;
1904 namelen = strnlen (name, section->size) + 1;
1905 if (namelen == 1)
1906 return NULL;
1907 if (namelen >= section->size)
1908 return NULL;
1910 id_len = section->size - namelen;
1911 if (id_len < 0x14)
1912 return NULL;
1914 /* Compare the .gnu_debugaltlink build-id with the build-ids of the
1915 known separate_info files. */
1916 while (i != NULL)
1918 const bfd * i_bfd = (bfd *) i->handle;
1920 if (i_bfd != NULL && i_bfd->build_id != NULL)
1922 const unsigned char * data = i_bfd->build_id->data;
1923 size_t size = i_bfd->build_id->size;
1925 if (id_len == size
1926 && memcmp (section->start + namelen, data, size) == 0)
1927 return (bfd *) i->handle;
1930 i = i->next;
1933 return NULL;
1936 #endif /* HAVE_LIBDEBUGINFOD */
1938 /* Reads the contents of file FN into memory. Returns a pointer to the buffer.
1939 Also returns the size of the buffer in SIZE_RETURN and a filled out
1940 stat structure in FST_RETURN. Returns NULL upon failure. */
1942 static const char *
1943 slurp_file (const char * fn,
1944 size_t * size_return,
1945 struct stat * fst_return,
1946 bfd * abfd ATTRIBUTE_UNUSED)
1948 #ifdef HAVE_MMAP
1949 int ps;
1950 size_t msize;
1951 #endif
1952 const char *map;
1953 int fd;
1955 /* Paranoia. */
1956 if (fn == NULL || * fn == 0 || size_return == NULL || fst_return == NULL)
1957 return NULL;
1959 fd = open (fn, O_RDONLY | O_BINARY);
1961 #if HAVE_LIBDEBUGINFOD
1962 if (fd < 0 && use_debuginfod && fn[0] == '/' && abfd != NULL)
1964 unsigned char *build_id = get_build_id (abfd);
1966 if (build_id)
1968 debuginfod_client *client = debuginfod_begin ();
1970 if (client)
1972 fd = debuginfod_find_source (client, build_id, 0, fn, NULL);
1973 debuginfod_end (client);
1975 free (build_id);
1978 #endif
1980 if (fd < 0)
1981 return NULL;
1983 if (fstat (fd, fst_return) < 0)
1985 close (fd);
1986 return NULL;
1989 *size_return = fst_return->st_size;
1991 #ifdef HAVE_MMAP
1992 ps = getpagesize ();
1993 msize = (*size_return + ps - 1) & ~(ps - 1);
1994 map = mmap (NULL, msize, PROT_READ, MAP_SHARED, fd, 0);
1995 if (map != (char *) -1L)
1997 close (fd);
1998 return map;
2000 #endif
2002 map = (const char *) malloc (*size_return);
2003 if (!map || (size_t) read (fd, (char *) map, *size_return) != *size_return)
2005 free ((void *) map);
2006 map = NULL;
2008 close (fd);
2009 return map;
2012 #define line_map_decrease 5
2014 /* Precompute array of lines for a mapped file. */
2016 static const char **
2017 index_file (const char *map, size_t size, unsigned int *maxline)
2019 const char *p, *lstart, *end;
2020 int chars_per_line = 45; /* First iteration will use 40. */
2021 unsigned int lineno;
2022 const char **linemap = NULL;
2023 unsigned long line_map_size = 0;
2025 lineno = 0;
2026 lstart = map;
2027 end = map + size;
2029 for (p = map; p < end; p++)
2031 if (*p == '\n')
2033 if (p + 1 < end && p[1] == '\r')
2034 p++;
2036 else if (*p == '\r')
2038 if (p + 1 < end && p[1] == '\n')
2039 p++;
2041 else
2042 continue;
2044 /* End of line found. */
2046 if (linemap == NULL || line_map_size < lineno + 1)
2048 unsigned long newsize;
2050 chars_per_line -= line_map_decrease;
2051 if (chars_per_line <= 1)
2052 chars_per_line = 1;
2053 line_map_size = size / chars_per_line + 1;
2054 if (line_map_size < lineno + 1)
2055 line_map_size = lineno + 1;
2056 newsize = line_map_size * sizeof (char *);
2057 linemap = (const char **) xrealloc (linemap, newsize);
2060 linemap[lineno++] = lstart;
2061 lstart = p + 1;
2064 *maxline = lineno;
2065 return linemap;
2068 /* Tries to open MODNAME, and if successful adds a node to print_files
2069 linked list and returns that node. Also fills in the stat structure
2070 pointed to by FST_RETURN. Returns NULL on failure. */
2072 static struct print_file_list *
2073 try_print_file_open (const char * origname,
2074 const char * modname,
2075 struct stat * fst_return,
2076 bfd * abfd)
2078 struct print_file_list *p;
2080 p = (struct print_file_list *) xmalloc (sizeof (struct print_file_list));
2082 p->map = slurp_file (modname, &p->mapsize, fst_return, abfd);
2083 if (p->map == NULL)
2085 free (p);
2086 return NULL;
2089 p->linemap = index_file (p->map, p->mapsize, &p->maxline);
2090 p->last_line = 0;
2091 p->max_printed = 0;
2092 p->filename = origname;
2093 p->modname = modname;
2094 p->next = print_files;
2095 p->first = 1;
2096 print_files = p;
2097 return p;
2100 /* If the source file, as described in the symtab, is not found
2101 try to locate it in one of the paths specified with -I
2102 If found, add location to print_files linked list. */
2104 static struct print_file_list *
2105 update_source_path (const char *filename, bfd *abfd)
2107 struct print_file_list *p;
2108 const char *fname;
2109 struct stat fst;
2110 int i;
2112 p = try_print_file_open (filename, filename, &fst, abfd);
2113 if (p == NULL)
2115 if (include_path_count == 0)
2116 return NULL;
2118 /* Get the name of the file. */
2119 fname = lbasename (filename);
2121 /* If file exists under a new path, we need to add it to the list
2122 so that show_line knows about it. */
2123 for (i = 0; i < include_path_count; i++)
2125 char *modname = concat (include_paths[i], "/", fname,
2126 (const char *) 0);
2128 p = try_print_file_open (filename, modname, &fst, abfd);
2129 if (p)
2130 break;
2132 free (modname);
2136 if (p != NULL)
2138 long mtime = bfd_get_mtime (abfd);
2140 if (fst.st_mtime > mtime)
2141 warn (_("source file %s is more recent than object file\n"),
2142 filename);
2145 return p;
2148 /* Print a source file line. */
2150 static void
2151 print_line (struct print_file_list *p, unsigned int linenum)
2153 const char *l;
2154 size_t len;
2156 if (linenum >= p->maxline)
2157 return;
2158 l = p->linemap [linenum];
2159 if (source_comment != NULL && strlen (l) > 0)
2160 printf ("%s", source_comment);
2161 len = strcspn (l, "\n\r");
2162 /* Test fwrite return value to quiet glibc warning. */
2163 if (len == 0 || fwrite (l, len, 1, stdout) == 1)
2164 putchar ('\n');
2167 /* Print a range of source code lines. */
2169 static void
2170 dump_lines (struct print_file_list *p, unsigned int start, unsigned int end)
2172 if (p->map == NULL)
2173 return;
2174 if (start != 0)
2175 --start;
2176 while (start < end)
2178 print_line (p, start);
2179 start++;
2183 /* Show the line number, or the source line, in a disassembly
2184 listing. */
2186 static void
2187 show_line (bfd *abfd, asection *section, bfd_vma addr_offset)
2189 const char *filename;
2190 const char *functionname;
2191 unsigned int linenumber;
2192 unsigned int discriminator;
2193 bool reloc;
2194 char *path = NULL;
2196 if (! with_line_numbers && ! with_source_code)
2197 return;
2199 #ifdef HAVE_LIBDEBUGINFOD
2201 bfd *debug_bfd;
2202 const char *alt_filename = NULL;
2204 if (use_debuginfod)
2206 bfd *alt_bfd;
2208 /* PR 29075: Check for separate debuginfo and .gnu_debugaltlink files.
2209 They need to be passed to bfd_find_nearest_line_with_alt in case they
2210 were downloaded from debuginfod. Otherwise libbfd will attempt to
2211 search for them and fail to locate them. */
2212 debug_bfd = find_separate_debug (abfd);
2213 if (debug_bfd == NULL)
2214 debug_bfd = abfd;
2216 alt_bfd = find_alt_debug (debug_bfd);
2217 if (alt_bfd != NULL)
2218 alt_filename = bfd_get_filename (alt_bfd);
2220 else
2221 debug_bfd = abfd;
2223 bfd_set_error (bfd_error_no_error);
2224 if (! bfd_find_nearest_line_with_alt (debug_bfd, alt_filename,
2225 section, syms,
2226 addr_offset, &filename,
2227 &functionname, &linenumber,
2228 &discriminator))
2230 if (bfd_get_error () == bfd_error_no_error)
2231 return;
2232 if (! bfd_find_nearest_line_discriminator (abfd, section, syms,
2233 addr_offset, &filename,
2234 &functionname, &linenumber,
2235 &discriminator))
2236 return;
2239 #else
2240 if (! bfd_find_nearest_line_discriminator (abfd, section, syms, addr_offset,
2241 &filename, &functionname,
2242 &linenumber, &discriminator))
2243 return;
2244 #endif
2246 if (filename != NULL && *filename == '\0')
2247 filename = NULL;
2248 if (functionname != NULL && *functionname == '\0')
2249 functionname = NULL;
2251 if (filename
2252 && IS_ABSOLUTE_PATH (filename)
2253 && prefix)
2255 char *path_up;
2256 const char *fname = filename;
2258 path = xmalloc (prefix_length + 1 + strlen (filename));
2260 if (prefix_length)
2261 memcpy (path, prefix, prefix_length);
2262 path_up = path + prefix_length;
2264 /* Build relocated filename, stripping off leading directories
2265 from the initial filename if requested. */
2266 if (prefix_strip > 0)
2268 int level = 0;
2269 const char *s;
2271 /* Skip selected directory levels. */
2272 for (s = fname + 1; *s != '\0' && level < prefix_strip; s++)
2273 if (IS_DIR_SEPARATOR (*s))
2275 fname = s;
2276 level++;
2280 /* Update complete filename. */
2281 strcpy (path_up, fname);
2283 filename = path;
2284 reloc = true;
2286 else
2287 reloc = false;
2289 if (with_line_numbers)
2291 if (functionname != NULL
2292 && (prev_functionname == NULL
2293 || strcmp (functionname, prev_functionname) != 0))
2295 char *demangle_alloc = NULL;
2296 if (do_demangle && functionname[0] != '\0')
2298 /* Demangle the name. */
2299 demangle_alloc = bfd_demangle (abfd, functionname,
2300 demangle_flags);
2303 /* Demangling adds trailing parens, so don't print those. */
2304 if (demangle_alloc != NULL)
2305 printf ("%s:\n", sanitize_string (demangle_alloc));
2306 else
2307 printf ("%s():\n", sanitize_string (functionname));
2309 prev_line = -1;
2310 free (demangle_alloc);
2312 if (linenumber > 0
2313 && (linenumber != prev_line
2314 || discriminator != prev_discriminator))
2316 if (discriminator > 0)
2317 printf ("%s:%u (discriminator %u)\n",
2318 filename == NULL ? "???" : sanitize_string (filename),
2319 linenumber, discriminator);
2320 else
2321 printf ("%s:%u\n", filename == NULL
2322 ? "???" : sanitize_string (filename),
2323 linenumber);
2325 if (unwind_inlines)
2327 const char *filename2;
2328 const char *functionname2;
2329 unsigned line2;
2331 while (bfd_find_inliner_info (abfd, &filename2, &functionname2,
2332 &line2))
2334 printf ("inlined by %s:%u",
2335 sanitize_string (filename2), line2);
2336 printf (" (%s)\n", sanitize_string (functionname2));
2341 if (with_source_code
2342 && filename != NULL
2343 && linenumber > 0)
2345 struct print_file_list **pp, *p;
2346 unsigned l;
2348 for (pp = &print_files; *pp != NULL; pp = &(*pp)->next)
2349 if (filename_cmp ((*pp)->filename, filename) == 0)
2350 break;
2351 p = *pp;
2353 if (p == NULL)
2355 if (reloc)
2356 filename = xstrdup (filename);
2357 p = update_source_path (filename, abfd);
2360 if (p != NULL && linenumber != p->last_line)
2362 if (file_start_context && p->first)
2363 l = 1;
2364 else
2366 l = linenumber - SHOW_PRECEDING_CONTEXT_LINES;
2367 if (l >= linenumber)
2368 l = 1;
2369 if (p->max_printed >= l)
2371 if (p->max_printed < linenumber)
2372 l = p->max_printed + 1;
2373 else
2374 l = linenumber;
2377 dump_lines (p, l, linenumber);
2378 if (p->max_printed < linenumber)
2379 p->max_printed = linenumber;
2380 p->last_line = linenumber;
2381 p->first = 0;
2385 if (functionname != NULL
2386 && (prev_functionname == NULL
2387 || strcmp (functionname, prev_functionname) != 0))
2389 if (prev_functionname != NULL)
2390 free (prev_functionname);
2391 prev_functionname = (char *) xmalloc (strlen (functionname) + 1);
2392 strcpy (prev_functionname, functionname);
2395 if (linenumber > 0 && linenumber != prev_line)
2396 prev_line = linenumber;
2398 if (discriminator != prev_discriminator)
2399 prev_discriminator = discriminator;
2401 if (path)
2402 free (path);
2405 /* Pseudo FILE object for strings. */
2406 typedef struct
2408 char *buffer;
2409 size_t pos;
2410 size_t alloc;
2411 } SFILE;
2413 /* sprintf to a "stream". */
2415 static int ATTRIBUTE_PRINTF_2
2416 objdump_sprintf (SFILE *f, const char *format, ...)
2418 size_t n;
2419 va_list args;
2421 while (1)
2423 size_t space = f->alloc - f->pos;
2425 va_start (args, format);
2426 n = vsnprintf (f->buffer + f->pos, space, format, args);
2427 va_end (args);
2429 if (space > n)
2430 break;
2432 f->alloc = (f->alloc + n) * 2;
2433 f->buffer = (char *) xrealloc (f->buffer, f->alloc);
2435 f->pos += n;
2437 return n;
2440 /* Return an integer greater than, or equal to zero, representing the color
2441 for STYLE, or -1 if no color should be used. */
2443 static int
2444 objdump_color_for_disassembler_style (enum disassembler_style style)
2446 int color = -1;
2448 if (style == dis_style_comment_start)
2449 disassembler_in_comment = true;
2451 if (disassembler_color == on)
2453 if (disassembler_in_comment)
2454 return color;
2456 switch (style)
2458 case dis_style_symbol:
2459 color = 32;
2460 break;
2461 case dis_style_assembler_directive:
2462 case dis_style_sub_mnemonic:
2463 case dis_style_mnemonic:
2464 color = 33;
2465 break;
2466 case dis_style_register:
2467 color = 34;
2468 break;
2469 case dis_style_address:
2470 case dis_style_address_offset:
2471 case dis_style_immediate:
2472 color = 35;
2473 break;
2474 default:
2475 case dis_style_text:
2476 color = -1;
2477 break;
2480 else if (disassembler_color == extended)
2482 if (disassembler_in_comment)
2483 return 250;
2485 switch (style)
2487 case dis_style_symbol:
2488 color = 40;
2489 break;
2490 case dis_style_assembler_directive:
2491 case dis_style_sub_mnemonic:
2492 case dis_style_mnemonic:
2493 color = 142;
2494 break;
2495 case dis_style_register:
2496 color = 27;
2497 break;
2498 case dis_style_address:
2499 case dis_style_address_offset:
2500 case dis_style_immediate:
2501 color = 134;
2502 break;
2503 default:
2504 case dis_style_text:
2505 color = -1;
2506 break;
2509 else if (disassembler_color != off)
2510 bfd_fatal (_("disassembly color not correctly selected"));
2512 return color;
2515 /* Like objdump_sprintf, but add in escape sequences to highlight the
2516 content according to STYLE. */
2518 static int ATTRIBUTE_PRINTF_3
2519 objdump_styled_sprintf (SFILE *f, enum disassembler_style style,
2520 const char *format, ...)
2522 size_t n;
2523 va_list args;
2524 int color = objdump_color_for_disassembler_style (style);
2526 if (color >= 0)
2528 while (1)
2530 size_t space = f->alloc - f->pos;
2532 if (disassembler_color == on)
2533 n = snprintf (f->buffer + f->pos, space, "\033[%dm", color);
2534 else
2535 n = snprintf (f->buffer + f->pos, space, "\033[38;5;%dm", color);
2536 if (space > n)
2537 break;
2539 f->alloc = (f->alloc + n) * 2;
2540 f->buffer = (char *) xrealloc (f->buffer, f->alloc);
2542 f->pos += n;
2545 while (1)
2547 size_t space = f->alloc - f->pos;
2549 va_start (args, format);
2550 n = vsnprintf (f->buffer + f->pos, space, format, args);
2551 va_end (args);
2553 if (space > n)
2554 break;
2556 f->alloc = (f->alloc + n) * 2;
2557 f->buffer = (char *) xrealloc (f->buffer, f->alloc);
2559 f->pos += n;
2561 if (color >= 0)
2563 while (1)
2565 size_t space = f->alloc - f->pos;
2567 n = snprintf (f->buffer + f->pos, space, "\033[0m");
2569 if (space > n)
2570 break;
2572 f->alloc = (f->alloc + n) * 2;
2573 f->buffer = (char *) xrealloc (f->buffer, f->alloc);
2575 f->pos += n;
2578 return n;
2581 /* We discard the styling information here. This function is only used
2582 when objdump is printing auxiliary information, the symbol headers, and
2583 disassembly address, or the bytes of the disassembled instruction. We
2584 don't (currently) apply styling to any of this stuff, so, for now, just
2585 print the content with no additional style added. */
2587 static int ATTRIBUTE_PRINTF_3
2588 fprintf_styled (FILE *f, enum disassembler_style style ATTRIBUTE_UNUSED,
2589 const char *fmt, ...)
2591 int res;
2592 va_list ap;
2594 va_start (ap, fmt);
2595 res = vfprintf (f, fmt, ap);
2596 va_end (ap);
2598 return res;
2601 /* Code for generating (colored) diagrams of control flow start and end
2602 points. */
2604 /* Structure used to store the properties of a jump. */
2606 struct jump_info
2608 /* The next jump, or NULL if this is the last object. */
2609 struct jump_info *next;
2610 /* The previous jump, or NULL if this is the first object. */
2611 struct jump_info *prev;
2612 /* The start addresses of the jump. */
2613 struct
2615 /* The list of start addresses. */
2616 bfd_vma *addresses;
2617 /* The number of elements. */
2618 size_t count;
2619 /* The maximum number of elements that fit into the array. */
2620 size_t max_count;
2621 } start;
2622 /* The end address of the jump. */
2623 bfd_vma end;
2624 /* The drawing level of the jump. */
2625 int level;
2628 /* Construct a jump object for a jump from start
2629 to end with the corresponding level. */
2631 static struct jump_info *
2632 jump_info_new (bfd_vma start, bfd_vma end, int level)
2634 struct jump_info *result = xmalloc (sizeof (struct jump_info));
2636 result->next = NULL;
2637 result->prev = NULL;
2638 result->start.addresses = xmalloc (sizeof (bfd_vma *) * 2);
2639 result->start.addresses[0] = start;
2640 result->start.count = 1;
2641 result->start.max_count = 2;
2642 result->end = end;
2643 result->level = level;
2645 return result;
2648 /* Free a jump object and return the next object
2649 or NULL if this was the last one. */
2651 static struct jump_info *
2652 jump_info_free (struct jump_info *ji)
2654 struct jump_info *result = NULL;
2656 if (ji)
2658 result = ji->next;
2659 if (ji->start.addresses)
2660 free (ji->start.addresses);
2661 free (ji);
2664 return result;
2667 /* Get the smallest value of all start and end addresses. */
2669 static bfd_vma
2670 jump_info_min_address (const struct jump_info *ji)
2672 bfd_vma min_address = ji->end;
2673 size_t i;
2675 for (i = ji->start.count; i-- > 0;)
2676 if (ji->start.addresses[i] < min_address)
2677 min_address = ji->start.addresses[i];
2678 return min_address;
2681 /* Get the largest value of all start and end addresses. */
2683 static bfd_vma
2684 jump_info_max_address (const struct jump_info *ji)
2686 bfd_vma max_address = ji->end;
2687 size_t i;
2689 for (i = ji->start.count; i-- > 0;)
2690 if (ji->start.addresses[i] > max_address)
2691 max_address = ji->start.addresses[i];
2692 return max_address;
2695 /* Get the target address of a jump. */
2697 static bfd_vma
2698 jump_info_end_address (const struct jump_info *ji)
2700 return ji->end;
2703 /* Test if an address is one of the start addresses of a jump. */
2705 static bool
2706 jump_info_is_start_address (const struct jump_info *ji, bfd_vma address)
2708 bool result = false;
2709 size_t i;
2711 for (i = ji->start.count; i-- > 0;)
2712 if (address == ji->start.addresses[i])
2714 result = true;
2715 break;
2718 return result;
2721 /* Test if an address is the target address of a jump. */
2723 static bool
2724 jump_info_is_end_address (const struct jump_info *ji, bfd_vma address)
2726 return (address == ji->end);
2729 /* Get the difference between the smallest and largest address of a jump. */
2731 static bfd_vma
2732 jump_info_size (const struct jump_info *ji)
2734 return jump_info_max_address (ji) - jump_info_min_address (ji);
2737 /* Unlink a jump object from a list. */
2739 static void
2740 jump_info_unlink (struct jump_info *node,
2741 struct jump_info **base)
2743 if (node->next)
2744 node->next->prev = node->prev;
2745 if (node->prev)
2746 node->prev->next = node->next;
2747 else
2748 *base = node->next;
2749 node->next = NULL;
2750 node->prev = NULL;
2753 /* Insert unlinked jump info node into a list. */
2755 static void
2756 jump_info_insert (struct jump_info *node,
2757 struct jump_info *target,
2758 struct jump_info **base)
2760 node->next = target;
2761 node->prev = target->prev;
2762 target->prev = node;
2763 if (node->prev)
2764 node->prev->next = node;
2765 else
2766 *base = node;
2769 /* Add unlinked node to the front of a list. */
2771 static void
2772 jump_info_add_front (struct jump_info *node,
2773 struct jump_info **base)
2775 node->next = *base;
2776 if (node->next)
2777 node->next->prev = node;
2778 node->prev = NULL;
2779 *base = node;
2782 /* Move linked node to target position. */
2784 static void
2785 jump_info_move_linked (struct jump_info *node,
2786 struct jump_info *target,
2787 struct jump_info **base)
2789 /* Unlink node. */
2790 jump_info_unlink (node, base);
2791 /* Insert node at target position. */
2792 jump_info_insert (node, target, base);
2795 /* Test if two jumps intersect. */
2797 static bool
2798 jump_info_intersect (const struct jump_info *a,
2799 const struct jump_info *b)
2801 return ((jump_info_max_address (a) >= jump_info_min_address (b))
2802 && (jump_info_min_address (a) <= jump_info_max_address (b)));
2805 /* Merge two compatible jump info objects. */
2807 static void
2808 jump_info_merge (struct jump_info **base)
2810 struct jump_info *a;
2812 for (a = *base; a; a = a->next)
2814 struct jump_info *b;
2816 for (b = a->next; b; b = b->next)
2818 /* Merge both jumps into one. */
2819 if (a->end == b->end)
2821 /* Reallocate addresses. */
2822 size_t needed_size = a->start.count + b->start.count;
2823 size_t i;
2825 if (needed_size > a->start.max_count)
2827 a->start.max_count += b->start.max_count;
2828 a->start.addresses =
2829 xrealloc (a->start.addresses,
2830 a->start.max_count * sizeof (bfd_vma *));
2833 /* Append start addresses. */
2834 for (i = 0; i < b->start.count; ++i)
2835 a->start.addresses[a->start.count++] =
2836 b->start.addresses[i];
2838 /* Remove and delete jump. */
2839 struct jump_info *tmp = b->prev;
2840 jump_info_unlink (b, base);
2841 jump_info_free (b);
2842 b = tmp;
2848 /* Sort jumps by their size and starting point using a stable
2849 minsort. This could be improved if sorting performance is
2850 an issue, for example by using mergesort. */
2852 static void
2853 jump_info_sort (struct jump_info **base)
2855 struct jump_info *current_element = *base;
2857 while (current_element)
2859 struct jump_info *best_match = current_element;
2860 struct jump_info *runner = current_element->next;
2861 bfd_vma best_size = jump_info_size (best_match);
2863 while (runner)
2865 bfd_vma runner_size = jump_info_size (runner);
2867 if ((runner_size < best_size)
2868 || ((runner_size == best_size)
2869 && (jump_info_min_address (runner)
2870 < jump_info_min_address (best_match))))
2872 best_match = runner;
2873 best_size = runner_size;
2876 runner = runner->next;
2879 if (best_match == current_element)
2880 current_element = current_element->next;
2881 else
2882 jump_info_move_linked (best_match, current_element, base);
2886 /* Visualize all jumps at a given address. */
2888 static void
2889 jump_info_visualize_address (bfd_vma address,
2890 int max_level,
2891 char *line_buffer,
2892 uint8_t *color_buffer)
2894 struct jump_info *ji = detected_jumps;
2895 size_t len = (max_level + 1) * 3;
2897 /* Clear line buffer. */
2898 memset (line_buffer, ' ', len);
2899 memset (color_buffer, 0, len);
2901 /* Iterate over jumps and add their ASCII art. */
2902 while (ji)
2904 /* Discard jumps that are never needed again. */
2905 if (jump_info_max_address (ji) < address)
2907 struct jump_info *tmp = ji;
2909 ji = ji->next;
2910 jump_info_unlink (tmp, &detected_jumps);
2911 jump_info_free (tmp);
2912 continue;
2915 /* This jump intersects with the current address. */
2916 if (jump_info_min_address (ji) <= address)
2918 /* Hash target address to get an even
2919 distribution between all values. */
2920 bfd_vma hash_address = jump_info_end_address (ji);
2921 uint8_t color = iterative_hash_object (hash_address, 0);
2922 /* Fetch line offset. */
2923 int offset = (max_level - ji->level) * 3;
2925 /* Draw start line. */
2926 if (jump_info_is_start_address (ji, address))
2928 size_t i = offset + 1;
2930 for (; i < len - 1; ++i)
2931 if (line_buffer[i] == ' ')
2933 line_buffer[i] = '-';
2934 color_buffer[i] = color;
2937 if (line_buffer[i] == ' ')
2939 line_buffer[i] = '-';
2940 color_buffer[i] = color;
2942 else if (line_buffer[i] == '>')
2944 line_buffer[i] = 'X';
2945 color_buffer[i] = color;
2948 if (line_buffer[offset] == ' ')
2950 if (address <= ji->end)
2951 line_buffer[offset] =
2952 (jump_info_min_address (ji) == address) ? ',': '+';
2953 else
2954 line_buffer[offset] =
2955 (jump_info_max_address (ji) == address) ? '\'': '+';
2956 color_buffer[offset] = color;
2959 /* Draw jump target. */
2960 else if (jump_info_is_end_address (ji, address))
2962 size_t i = offset + 1;
2964 for (; i < len - 1; ++i)
2965 if (line_buffer[i] == ' ')
2967 line_buffer[i] = '-';
2968 color_buffer[i] = color;
2971 if (line_buffer[i] == ' ')
2973 line_buffer[i] = '>';
2974 color_buffer[i] = color;
2976 else if (line_buffer[i] == '-')
2978 line_buffer[i] = 'X';
2979 color_buffer[i] = color;
2982 if (line_buffer[offset] == ' ')
2984 if (jump_info_min_address (ji) < address)
2985 line_buffer[offset] =
2986 (jump_info_max_address (ji) > address) ? '>' : '\'';
2987 else
2988 line_buffer[offset] = ',';
2989 color_buffer[offset] = color;
2992 /* Draw intermediate line segment. */
2993 else if (line_buffer[offset] == ' ')
2995 line_buffer[offset] = '|';
2996 color_buffer[offset] = color;
3000 ji = ji->next;
3004 /* Clone of disassemble_bytes to detect jumps inside a function. */
3005 /* FIXME: is this correct? Can we strip it down even further? */
3007 static struct jump_info *
3008 disassemble_jumps (struct disassemble_info * inf,
3009 disassembler_ftype disassemble_fn,
3010 bfd_vma start_offset,
3011 bfd_vma stop_offset,
3012 bfd_vma rel_offset,
3013 arelent ** relpp,
3014 arelent ** relppend)
3016 struct objdump_disasm_info *aux;
3017 struct jump_info *jumps = NULL;
3018 asection *section;
3019 bfd_vma addr_offset;
3020 unsigned int opb = inf->octets_per_byte;
3021 int octets = opb;
3022 SFILE sfile;
3024 aux = (struct objdump_disasm_info *) inf->application_data;
3025 section = inf->section;
3027 sfile.alloc = 120;
3028 sfile.buffer = (char *) xmalloc (sfile.alloc);
3029 sfile.pos = 0;
3031 inf->insn_info_valid = 0;
3032 disassemble_set_printf (inf, &sfile, (fprintf_ftype) objdump_sprintf,
3033 (fprintf_styled_ftype) objdump_styled_sprintf);
3035 addr_offset = start_offset;
3036 while (addr_offset < stop_offset)
3038 int previous_octets;
3040 /* Remember the length of the previous instruction. */
3041 previous_octets = octets;
3042 octets = 0;
3044 sfile.pos = 0;
3045 inf->bytes_per_line = 0;
3046 inf->bytes_per_chunk = 0;
3047 inf->flags = ((disassemble_all ? DISASSEMBLE_DATA : 0)
3048 | (wide_output ? WIDE_OUTPUT : 0));
3049 if (machine)
3050 inf->flags |= USER_SPECIFIED_MACHINE_TYPE;
3052 if (inf->disassembler_needs_relocs
3053 && (bfd_get_file_flags (aux->abfd) & EXEC_P) == 0
3054 && (bfd_get_file_flags (aux->abfd) & DYNAMIC) == 0
3055 && relpp < relppend)
3057 bfd_signed_vma distance_to_rel;
3059 distance_to_rel = (*relpp)->address - (rel_offset + addr_offset);
3061 /* Check to see if the current reloc is associated with
3062 the instruction that we are about to disassemble. */
3063 if (distance_to_rel == 0
3064 /* FIXME: This is wrong. We are trying to catch
3065 relocs that are addressed part way through the
3066 current instruction, as might happen with a packed
3067 VLIW instruction. Unfortunately we do not know the
3068 length of the current instruction since we have not
3069 disassembled it yet. Instead we take a guess based
3070 upon the length of the previous instruction. The
3071 proper solution is to have a new target-specific
3072 disassembler function which just returns the length
3073 of an instruction at a given address without trying
3074 to display its disassembly. */
3075 || (distance_to_rel > 0
3076 && distance_to_rel < (bfd_signed_vma) (previous_octets/ opb)))
3078 inf->flags |= INSN_HAS_RELOC;
3082 if (! disassemble_all
3083 && (section->flags & (SEC_CODE | SEC_HAS_CONTENTS))
3084 == (SEC_CODE | SEC_HAS_CONTENTS))
3085 /* Set a stop_vma so that the disassembler will not read
3086 beyond the next symbol. We assume that symbols appear on
3087 the boundaries between instructions. We only do this when
3088 disassembling code of course, and when -D is in effect. */
3089 inf->stop_vma = section->vma + stop_offset;
3091 inf->stop_offset = stop_offset;
3093 /* Extract jump information. */
3094 inf->insn_info_valid = 0;
3095 disassembler_in_comment = false;
3096 octets = (*disassemble_fn) (section->vma + addr_offset, inf);
3097 /* Test if a jump was detected. */
3098 if (inf->insn_info_valid
3099 && ((inf->insn_type == dis_branch)
3100 || (inf->insn_type == dis_condbranch)
3101 || (inf->insn_type == dis_jsr)
3102 || (inf->insn_type == dis_condjsr))
3103 && (inf->target >= section->vma + start_offset)
3104 && (inf->target < section->vma + stop_offset))
3106 struct jump_info *ji =
3107 jump_info_new (section->vma + addr_offset, inf->target, -1);
3108 jump_info_add_front (ji, &jumps);
3111 inf->stop_vma = 0;
3113 addr_offset += octets / opb;
3116 disassemble_set_printf (inf, (void *) stdout, (fprintf_ftype) fprintf,
3117 (fprintf_styled_ftype) fprintf_styled);
3118 free (sfile.buffer);
3120 /* Merge jumps. */
3121 jump_info_merge (&jumps);
3122 /* Process jumps. */
3123 jump_info_sort (&jumps);
3125 /* Group jumps by level. */
3126 struct jump_info *last_jump = jumps;
3127 int max_level = -1;
3129 while (last_jump)
3131 /* The last jump is part of the next group. */
3132 struct jump_info *base = last_jump;
3133 /* Increment level. */
3134 base->level = ++max_level;
3136 /* Find jumps that can be combined on the same
3137 level, with the largest jumps tested first.
3138 This has the advantage that large jumps are on
3139 lower levels and do not intersect with small
3140 jumps that get grouped on higher levels. */
3141 struct jump_info *exchange_item = last_jump->next;
3142 struct jump_info *it = exchange_item;
3144 for (; it; it = it->next)
3146 /* Test if the jump intersects with any
3147 jump from current group. */
3148 bool ok = true;
3149 struct jump_info *it_collision;
3151 for (it_collision = base;
3152 it_collision != exchange_item;
3153 it_collision = it_collision->next)
3155 /* This jump intersects so we leave it out. */
3156 if (jump_info_intersect (it_collision, it))
3158 ok = false;
3159 break;
3163 /* Add jump to group. */
3164 if (ok)
3166 /* Move current element to the front. */
3167 if (it != exchange_item)
3169 struct jump_info *save = it->prev;
3170 jump_info_move_linked (it, exchange_item, &jumps);
3171 last_jump = it;
3172 it = save;
3174 else
3176 last_jump = exchange_item;
3177 exchange_item = exchange_item->next;
3179 last_jump->level = max_level;
3183 /* Move to next group. */
3184 last_jump = exchange_item;
3187 return jumps;
3190 /* The number of zeroes we want to see before we start skipping them.
3191 The number is arbitrarily chosen. */
3193 #define DEFAULT_SKIP_ZEROES 8
3195 /* The number of zeroes to skip at the end of a section. If the
3196 number of zeroes at the end is between SKIP_ZEROES_AT_END and
3197 SKIP_ZEROES, they will be disassembled. If there are fewer than
3198 SKIP_ZEROES_AT_END, they will be skipped. This is a heuristic
3199 attempt to avoid disassembling zeroes inserted by section
3200 alignment. */
3202 #define DEFAULT_SKIP_ZEROES_AT_END 3
3204 static int
3205 null_print (const void * stream ATTRIBUTE_UNUSED, const char * format ATTRIBUTE_UNUSED, ...)
3207 return 1;
3210 /* Like null_print, but takes the extra STYLE argument. As this is not
3211 going to print anything, the extra argument is just ignored. */
3213 static int
3214 null_styled_print (const void * stream ATTRIBUTE_UNUSED,
3215 enum disassembler_style style ATTRIBUTE_UNUSED,
3216 const char * format ATTRIBUTE_UNUSED, ...)
3218 return 1;
3221 /* Print out jump visualization. */
3223 static void
3224 print_jump_visualisation (bfd_vma addr, int max_level, char *line_buffer,
3225 uint8_t *color_buffer)
3227 if (!line_buffer)
3228 return;
3230 jump_info_visualize_address (addr, max_level, line_buffer, color_buffer);
3232 size_t line_buffer_size = strlen (line_buffer);
3233 char last_color = 0;
3234 size_t i;
3236 for (i = 0; i <= line_buffer_size; ++i)
3238 if (color_output)
3240 uint8_t color = (i < line_buffer_size) ? color_buffer[i]: 0;
3242 if (color != last_color)
3244 if (color)
3245 if (extended_color_output)
3246 /* Use extended 8bit color, but
3247 do not choose dark colors. */
3248 printf ("\033[38;5;%dm", 124 + (color % 108));
3249 else
3250 /* Use simple terminal colors. */
3251 printf ("\033[%dm", 31 + (color % 7));
3252 else
3253 /* Clear color. */
3254 printf ("\033[0m");
3255 last_color = color;
3258 putchar ((i < line_buffer_size) ? line_buffer[i]: ' ');
3262 /* Disassemble some data in memory between given values. */
3264 static void
3265 disassemble_bytes (struct disassemble_info *inf,
3266 disassembler_ftype disassemble_fn,
3267 bool insns,
3268 bfd_byte *data,
3269 bfd_vma start_offset,
3270 bfd_vma stop_offset,
3271 bfd_vma rel_offset,
3272 arelent **relpp,
3273 arelent **relppend)
3275 struct objdump_disasm_info *aux;
3276 asection *section;
3277 unsigned int octets_per_line;
3278 unsigned int skip_addr_chars;
3279 bfd_vma addr_offset;
3280 unsigned int opb = inf->octets_per_byte;
3281 unsigned int skip_zeroes = inf->skip_zeroes;
3282 unsigned int skip_zeroes_at_end = inf->skip_zeroes_at_end;
3283 size_t octets;
3284 SFILE sfile;
3286 aux = (struct objdump_disasm_info *) inf->application_data;
3287 section = inf->section;
3289 sfile.alloc = 120;
3290 sfile.buffer = (char *) xmalloc (sfile.alloc);
3291 sfile.pos = 0;
3293 if (insn_width)
3294 octets_per_line = insn_width;
3295 else if (insns)
3296 octets_per_line = 4;
3297 else
3298 octets_per_line = 16;
3300 /* Figure out how many characters to skip at the start of an
3301 address, to make the disassembly look nicer. We discard leading
3302 zeroes in chunks of 4, ensuring that there is always a leading
3303 zero remaining. */
3304 skip_addr_chars = 0;
3305 if (!no_addresses && !prefix_addresses)
3307 char buf[30];
3309 bfd_sprintf_vma (aux->abfd, buf, section->vma + section->size / opb);
3311 while (buf[skip_addr_chars] == '0')
3312 ++skip_addr_chars;
3314 /* Don't discard zeros on overflow. */
3315 if (buf[skip_addr_chars] == '\0' && section->vma != 0)
3316 skip_addr_chars = 0;
3318 if (skip_addr_chars != 0)
3319 skip_addr_chars = (skip_addr_chars - 1) & -4;
3322 inf->insn_info_valid = 0;
3324 /* Determine maximum level. */
3325 uint8_t *color_buffer = NULL;
3326 char *line_buffer = NULL;
3327 int max_level = -1;
3329 /* Some jumps were detected. */
3330 if (detected_jumps)
3332 struct jump_info *ji;
3334 /* Find maximum jump level. */
3335 for (ji = detected_jumps; ji; ji = ji->next)
3337 if (ji->level > max_level)
3338 max_level = ji->level;
3341 /* Allocate buffers. */
3342 size_t len = (max_level + 1) * 3 + 1;
3343 line_buffer = xmalloc (len);
3344 line_buffer[len - 1] = 0;
3345 color_buffer = xmalloc (len);
3346 color_buffer[len - 1] = 0;
3349 addr_offset = start_offset;
3350 while (addr_offset < stop_offset)
3352 bool need_nl = false;
3354 octets = 0;
3356 /* Make sure we don't use relocs from previous instructions. */
3357 aux->reloc = NULL;
3359 /* If we see more than SKIP_ZEROES octets of zeroes, we just
3360 print `...'. */
3361 if (! disassemble_zeroes)
3362 for (; octets < (stop_offset - addr_offset) * opb; octets++)
3363 if (data[addr_offset * opb + octets] != 0)
3364 break;
3365 if (! disassemble_zeroes
3366 && (inf->insn_info_valid == 0
3367 || inf->branch_delay_insns == 0)
3368 && (octets >= skip_zeroes
3369 || (octets == (stop_offset - addr_offset) * opb
3370 && octets < skip_zeroes_at_end)))
3372 /* If there are more nonzero octets to follow, we only skip
3373 zeroes in multiples of 4, to try to avoid running over
3374 the start of an instruction which happens to start with
3375 zero. */
3376 if (octets != (stop_offset - addr_offset) * opb)
3377 octets &= ~3;
3379 /* If we are going to display more data, and we are displaying
3380 file offsets, then tell the user how many zeroes we skip
3381 and the file offset from where we resume dumping. */
3382 if (display_file_offsets
3383 && octets / opb < stop_offset - addr_offset)
3384 printf (_("\t... (skipping %lu zeroes, "
3385 "resuming at file offset: 0x%lx)\n"),
3386 (unsigned long) (octets / opb),
3387 (unsigned long) (section->filepos
3388 + addr_offset + octets / opb));
3389 else
3390 printf ("\t...\n");
3392 else
3394 char buf[50];
3395 unsigned int bpc = 0;
3396 unsigned int pb = 0;
3398 if (with_line_numbers || with_source_code)
3399 show_line (aux->abfd, section, addr_offset);
3401 if (no_addresses)
3402 printf ("\t");
3403 else if (!prefix_addresses)
3405 char *s;
3407 bfd_sprintf_vma (aux->abfd, buf, section->vma + addr_offset);
3408 for (s = buf + skip_addr_chars; *s == '0'; s++)
3409 *s = ' ';
3410 if (*s == '\0')
3411 *--s = '0';
3412 printf ("%s:\t", buf + skip_addr_chars);
3414 else
3416 aux->require_sec = true;
3417 objdump_print_address (section->vma + addr_offset, inf);
3418 aux->require_sec = false;
3419 putchar (' ');
3422 print_jump_visualisation (section->vma + addr_offset,
3423 max_level, line_buffer,
3424 color_buffer);
3426 if (insns)
3428 int insn_size;
3430 sfile.pos = 0;
3431 disassemble_set_printf
3432 (inf, &sfile, (fprintf_ftype) objdump_sprintf,
3433 (fprintf_styled_ftype) objdump_styled_sprintf);
3434 inf->bytes_per_line = 0;
3435 inf->bytes_per_chunk = 0;
3436 inf->flags = ((disassemble_all ? DISASSEMBLE_DATA : 0)
3437 | (wide_output ? WIDE_OUTPUT : 0));
3438 if (machine)
3439 inf->flags |= USER_SPECIFIED_MACHINE_TYPE;
3441 if (inf->disassembler_needs_relocs
3442 && (bfd_get_file_flags (aux->abfd) & EXEC_P) == 0
3443 && (bfd_get_file_flags (aux->abfd) & DYNAMIC) == 0
3444 && relpp < relppend)
3446 bfd_signed_vma distance_to_rel;
3447 int max_reloc_offset
3448 = aux->abfd->arch_info->max_reloc_offset_into_insn;
3450 distance_to_rel = ((*relpp)->address - rel_offset
3451 - addr_offset);
3453 insn_size = 0;
3454 if (distance_to_rel > 0
3455 && (max_reloc_offset < 0
3456 || distance_to_rel <= max_reloc_offset))
3458 /* This reloc *might* apply to the current insn,
3459 starting somewhere inside it. Discover the length
3460 of the current insn so that the check below will
3461 work. */
3462 if (insn_width)
3463 insn_size = insn_width;
3464 else
3466 /* We find the length by calling the dissassembler
3467 function with a dummy print handler. This should
3468 work unless the disassembler is not expecting to
3469 be called multiple times for the same address.
3471 This does mean disassembling the instruction
3472 twice, but we only do this when there is a high
3473 probability that there is a reloc that will
3474 affect the instruction. */
3475 disassemble_set_printf
3476 (inf, inf->stream, (fprintf_ftype) null_print,
3477 (fprintf_styled_ftype) null_styled_print);
3478 insn_size = disassemble_fn (section->vma
3479 + addr_offset, inf);
3480 disassemble_set_printf
3481 (inf, inf->stream,
3482 (fprintf_ftype) objdump_sprintf,
3483 (fprintf_styled_ftype) objdump_styled_sprintf);
3487 /* Check to see if the current reloc is associated with
3488 the instruction that we are about to disassemble. */
3489 if (distance_to_rel == 0
3490 || (distance_to_rel > 0
3491 && distance_to_rel < insn_size / (int) opb))
3493 inf->flags |= INSN_HAS_RELOC;
3494 aux->reloc = *relpp;
3498 if (! disassemble_all
3499 && ((section->flags & (SEC_CODE | SEC_HAS_CONTENTS))
3500 == (SEC_CODE | SEC_HAS_CONTENTS)))
3501 /* Set a stop_vma so that the disassembler will not read
3502 beyond the next symbol. We assume that symbols appear on
3503 the boundaries between instructions. We only do this when
3504 disassembling code of course, and when -D is in effect. */
3505 inf->stop_vma = section->vma + stop_offset;
3507 inf->stop_offset = stop_offset;
3508 disassembler_in_comment = false;
3509 insn_size = (*disassemble_fn) (section->vma + addr_offset, inf);
3510 octets = insn_size;
3512 inf->stop_vma = 0;
3513 disassemble_set_printf (inf, stdout, (fprintf_ftype) fprintf,
3514 (fprintf_styled_ftype) fprintf_styled);
3515 if (insn_width == 0 && inf->bytes_per_line != 0)
3516 octets_per_line = inf->bytes_per_line;
3517 if (insn_size < (int) opb)
3519 if (sfile.pos)
3520 printf ("%s\n", sfile.buffer);
3521 if (insn_size >= 0)
3523 non_fatal (_("disassemble_fn returned length %d"),
3524 insn_size);
3525 exit_status = 1;
3527 break;
3530 else
3532 bfd_vma j;
3534 octets = octets_per_line;
3535 if (octets / opb > stop_offset - addr_offset)
3536 octets = (stop_offset - addr_offset) * opb;
3538 for (j = addr_offset * opb; j < addr_offset * opb + octets; ++j)
3540 if (ISPRINT (data[j]))
3541 buf[j - addr_offset * opb] = data[j];
3542 else
3543 buf[j - addr_offset * opb] = '.';
3545 buf[j - addr_offset * opb] = '\0';
3548 if (prefix_addresses
3549 ? show_raw_insn > 0
3550 : show_raw_insn >= 0)
3552 bfd_vma j;
3554 /* If ! prefix_addresses and ! wide_output, we print
3555 octets_per_line octets per line. */
3556 pb = octets;
3557 if (pb > octets_per_line && ! prefix_addresses && ! wide_output)
3558 pb = octets_per_line;
3560 if (inf->bytes_per_chunk)
3561 bpc = inf->bytes_per_chunk;
3562 else
3563 bpc = 1;
3565 for (j = addr_offset * opb; j < addr_offset * opb + pb; j += bpc)
3567 /* PR 21580: Check for a buffer ending early. */
3568 if (j + bpc <= stop_offset * opb)
3570 unsigned int k;
3572 if (inf->display_endian == BFD_ENDIAN_LITTLE)
3574 for (k = bpc; k-- != 0; )
3575 printf ("%02x", (unsigned) data[j + k]);
3577 else
3579 for (k = 0; k < bpc; k++)
3580 printf ("%02x", (unsigned) data[j + k]);
3583 putchar (' ');
3586 for (; pb < octets_per_line; pb += bpc)
3588 unsigned int k;
3590 for (k = 0; k < bpc; k++)
3591 printf (" ");
3592 putchar (' ');
3595 /* Separate raw data from instruction by extra space. */
3596 if (insns)
3597 putchar ('\t');
3598 else
3599 printf (" ");
3602 if (! insns)
3603 printf ("%s", buf);
3604 else if (sfile.pos)
3605 printf ("%s", sfile.buffer);
3607 if (prefix_addresses
3608 ? show_raw_insn > 0
3609 : show_raw_insn >= 0)
3611 while (pb < octets)
3613 bfd_vma j;
3614 char *s;
3616 putchar ('\n');
3617 j = addr_offset * opb + pb;
3619 if (no_addresses)
3620 printf ("\t");
3621 else
3623 bfd_sprintf_vma (aux->abfd, buf, section->vma + j / opb);
3624 for (s = buf + skip_addr_chars; *s == '0'; s++)
3625 *s = ' ';
3626 if (*s == '\0')
3627 *--s = '0';
3628 printf ("%s:\t", buf + skip_addr_chars);
3631 print_jump_visualisation (section->vma + j / opb,
3632 max_level, line_buffer,
3633 color_buffer);
3635 pb += octets_per_line;
3636 if (pb > octets)
3637 pb = octets;
3638 for (; j < addr_offset * opb + pb; j += bpc)
3640 /* PR 21619: Check for a buffer ending early. */
3641 if (j + bpc <= stop_offset * opb)
3643 unsigned int k;
3645 if (inf->display_endian == BFD_ENDIAN_LITTLE)
3647 for (k = bpc; k-- != 0; )
3648 printf ("%02x", (unsigned) data[j + k]);
3650 else
3652 for (k = 0; k < bpc; k++)
3653 printf ("%02x", (unsigned) data[j + k]);
3656 putchar (' ');
3661 if (!wide_output)
3662 putchar ('\n');
3663 else
3664 need_nl = true;
3667 while (relpp < relppend
3668 && (*relpp)->address < rel_offset + addr_offset + octets / opb)
3670 if (dump_reloc_info || dump_dynamic_reloc_info)
3672 arelent *q;
3674 q = *relpp;
3676 if (wide_output)
3677 putchar ('\t');
3678 else
3679 printf ("\t\t\t");
3681 if (!no_addresses)
3683 objdump_print_value (section->vma - rel_offset + q->address,
3684 inf, true);
3685 printf (": ");
3688 if (q->howto == NULL)
3689 printf ("*unknown*\t");
3690 else if (q->howto->name)
3691 printf ("%s\t", q->howto->name);
3692 else
3693 printf ("%d\t", q->howto->type);
3695 if (q->sym_ptr_ptr == NULL || *q->sym_ptr_ptr == NULL)
3696 printf ("*unknown*");
3697 else
3699 const char *sym_name;
3701 sym_name = bfd_asymbol_name (*q->sym_ptr_ptr);
3702 if (sym_name != NULL && *sym_name != '\0')
3703 objdump_print_symname (aux->abfd, inf, *q->sym_ptr_ptr);
3704 else
3706 asection *sym_sec;
3708 sym_sec = bfd_asymbol_section (*q->sym_ptr_ptr);
3709 sym_name = bfd_section_name (sym_sec);
3710 if (sym_name == NULL || *sym_name == '\0')
3711 sym_name = "*unknown*";
3712 printf ("%s", sanitize_string (sym_name));
3716 if (q->addend)
3718 bfd_vma addend = q->addend;
3719 if ((bfd_signed_vma) addend < 0)
3721 printf ("-0x");
3722 addend = -addend;
3724 else
3725 printf ("+0x");
3726 objdump_print_value (addend, inf, true);
3729 printf ("\n");
3730 need_nl = false;
3732 ++relpp;
3735 if (need_nl)
3736 printf ("\n");
3738 addr_offset += octets / opb;
3741 free (sfile.buffer);
3742 free (line_buffer);
3743 free (color_buffer);
3746 static void
3747 disassemble_section (bfd *abfd, asection *section, void *inf)
3749 const struct elf_backend_data *bed;
3750 bfd_vma sign_adjust = 0;
3751 struct disassemble_info *pinfo = (struct disassemble_info *) inf;
3752 struct objdump_disasm_info *paux;
3753 unsigned int opb = pinfo->octets_per_byte;
3754 bfd_byte *data = NULL;
3755 bfd_size_type datasize = 0;
3756 arelent **rel_pp = NULL;
3757 arelent **rel_ppstart = NULL;
3758 arelent **rel_ppend;
3759 bfd_vma stop_offset;
3760 asymbol *sym = NULL;
3761 long place = 0;
3762 long rel_count;
3763 bfd_vma rel_offset;
3764 unsigned long addr_offset;
3765 bool do_print;
3766 enum loop_control
3768 stop_offset_reached,
3769 function_sym,
3770 next_sym
3771 } loop_until;
3773 if (only_list == NULL)
3775 /* Sections that do not contain machine
3776 code are not normally disassembled. */
3777 if ((section->flags & SEC_HAS_CONTENTS) == 0)
3778 return;
3780 if (! disassemble_all
3781 && (section->flags & SEC_CODE) == 0)
3782 return;
3784 else if (!process_section_p (section))
3785 return;
3787 datasize = bfd_section_size (section);
3788 if (datasize == 0)
3789 return;
3791 if (start_address == (bfd_vma) -1
3792 || start_address < section->vma)
3793 addr_offset = 0;
3794 else
3795 addr_offset = start_address - section->vma;
3797 if (stop_address == (bfd_vma) -1)
3798 stop_offset = datasize / opb;
3799 else
3801 if (stop_address < section->vma)
3802 stop_offset = 0;
3803 else
3804 stop_offset = stop_address - section->vma;
3805 if (stop_offset > datasize / opb)
3806 stop_offset = datasize / opb;
3809 if (addr_offset >= stop_offset)
3810 return;
3812 /* Decide which set of relocs to use. Load them if necessary. */
3813 paux = (struct objdump_disasm_info *) pinfo->application_data;
3814 if (pinfo->dynrelbuf && dump_dynamic_reloc_info)
3816 rel_pp = pinfo->dynrelbuf;
3817 rel_count = pinfo->dynrelcount;
3818 /* Dynamic reloc addresses are absolute, non-dynamic are section
3819 relative. REL_OFFSET specifies the reloc address corresponding
3820 to the start of this section. */
3821 rel_offset = section->vma;
3823 else
3825 rel_count = 0;
3826 rel_pp = NULL;
3827 rel_offset = 0;
3829 if ((section->flags & SEC_RELOC) != 0
3830 && (dump_reloc_info || pinfo->disassembler_needs_relocs))
3832 long relsize;
3834 relsize = bfd_get_reloc_upper_bound (abfd, section);
3835 if (relsize < 0)
3836 my_bfd_nonfatal (bfd_get_filename (abfd));
3838 if (relsize > 0)
3840 rel_pp = (arelent **) xmalloc (relsize);
3841 rel_count = bfd_canonicalize_reloc (abfd, section, rel_pp, syms);
3842 if (rel_count < 0)
3844 my_bfd_nonfatal (bfd_get_filename (abfd));
3845 free (rel_pp);
3846 rel_pp = NULL;
3847 rel_count = 0;
3849 else if (rel_count > 1)
3850 /* Sort the relocs by address. */
3851 qsort (rel_pp, rel_count, sizeof (arelent *), compare_relocs);
3852 rel_ppstart = rel_pp;
3856 rel_ppend = PTR_ADD (rel_pp, rel_count);
3858 if (!bfd_malloc_and_get_section (abfd, section, &data))
3860 non_fatal (_("Reading section %s failed because: %s"),
3861 section->name, bfd_errmsg (bfd_get_error ()));
3862 free (rel_ppstart);
3863 return;
3866 pinfo->buffer = data;
3867 pinfo->buffer_vma = section->vma;
3868 pinfo->buffer_length = datasize;
3869 pinfo->section = section;
3871 /* Sort the symbols into value and section order. */
3872 compare_section = section;
3873 if (sorted_symcount > 1)
3874 qsort (sorted_syms, sorted_symcount, sizeof (asymbol *), compare_symbols);
3876 printf (_("\nDisassembly of section %s:\n"), sanitize_string (section->name));
3878 /* Find the nearest symbol forwards from our current position. */
3879 paux->require_sec = true;
3880 sym = (asymbol *) find_symbol_for_address (section->vma + addr_offset,
3881 (struct disassemble_info *) inf,
3882 &place);
3883 paux->require_sec = false;
3885 /* PR 9774: If the target used signed addresses then we must make
3886 sure that we sign extend the value that we calculate for 'addr'
3887 in the loop below. */
3888 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
3889 && (bed = get_elf_backend_data (abfd)) != NULL
3890 && bed->sign_extend_vma)
3891 sign_adjust = (bfd_vma) 1 << (bed->s->arch_size - 1);
3893 /* Disassemble a block of instructions up to the address associated with
3894 the symbol we have just found. Then print the symbol and find the
3895 next symbol on. Repeat until we have disassembled the entire section
3896 or we have reached the end of the address range we are interested in. */
3897 do_print = paux->symbol == NULL;
3898 loop_until = stop_offset_reached;
3900 while (addr_offset < stop_offset)
3902 bfd_vma addr;
3903 asymbol *nextsym;
3904 bfd_vma nextstop_offset;
3905 bool insns;
3907 /* Skip over the relocs belonging to addresses below the
3908 start address. */
3909 while (rel_pp < rel_ppend
3910 && (*rel_pp)->address < rel_offset + addr_offset)
3911 ++rel_pp;
3913 addr = section->vma + addr_offset;
3914 addr = ((addr & ((sign_adjust << 1) - 1)) ^ sign_adjust) - sign_adjust;
3916 if (sym != NULL && bfd_asymbol_value (sym) <= addr)
3918 int x;
3920 for (x = place;
3921 (x < sorted_symcount
3922 && (bfd_asymbol_value (sorted_syms[x]) <= addr));
3923 ++x)
3924 continue;
3926 pinfo->symbols = sorted_syms + place;
3927 pinfo->num_symbols = x - place;
3928 pinfo->symtab_pos = place;
3930 else
3932 pinfo->symbols = NULL;
3933 pinfo->num_symbols = 0;
3934 pinfo->symtab_pos = -1;
3937 /* If we are only disassembling from a specific symbol,
3938 check to see if we should start or stop displaying. */
3939 if (sym && paux->symbol)
3941 if (do_print)
3943 /* See if we should stop printing. */
3944 switch (loop_until)
3946 case function_sym:
3947 if (sym->flags & BSF_FUNCTION)
3948 do_print = false;
3949 break;
3951 case stop_offset_reached:
3952 /* Handled by the while loop. */
3953 break;
3955 case next_sym:
3956 /* FIXME: There is an implicit assumption here
3957 that the name of sym is different from
3958 paux->symbol. */
3959 if (! bfd_is_local_label (abfd, sym))
3960 do_print = false;
3961 break;
3964 else
3966 const char * name = bfd_asymbol_name (sym);
3967 char * alloc = NULL;
3969 if (do_demangle && name[0] != '\0')
3971 /* Demangle the name. */
3972 alloc = bfd_demangle (abfd, name, demangle_flags);
3973 if (alloc != NULL)
3974 name = alloc;
3977 /* We are not currently printing. Check to see
3978 if the current symbol matches the requested symbol. */
3979 if (streq (name, paux->symbol)
3980 && bfd_asymbol_value (sym) <= addr)
3982 do_print = true;
3984 loop_until = next_sym;
3985 if (sym->flags & BSF_FUNCTION)
3987 loop_until = function_sym;
3989 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
3991 bfd_size_type fsize =
3992 ((elf_symbol_type *) sym)->internal_elf_sym.st_size;
3993 bfd_vma fend =
3994 bfd_asymbol_value (sym) - section->vma + fsize;
3995 if (fend > addr_offset && fend <= stop_offset)
3997 /* Sym is a function symbol with a valid
3998 size associated with it. Disassemble
3999 to the end of the function. */
4000 stop_offset = fend;
4001 loop_until = stop_offset_reached;
4007 free (alloc);
4011 if (! prefix_addresses && do_print)
4013 pinfo->fprintf_func (pinfo->stream, "\n");
4014 objdump_print_addr_with_sym (abfd, section, sym, addr,
4015 pinfo, false);
4016 pinfo->fprintf_func (pinfo->stream, ":\n");
4018 if (sym != NULL && show_all_symbols)
4020 for (++place; place < sorted_symcount; place++)
4022 sym = sorted_syms[place];
4024 if (bfd_asymbol_value (sym) != addr)
4025 break;
4026 if (! pinfo->symbol_is_valid (sym, pinfo))
4027 continue;
4028 if (strcmp (bfd_section_name (sym->section), bfd_section_name (section)) != 0)
4029 break;
4031 objdump_print_addr_with_sym (abfd, section, sym, addr, pinfo, false);
4032 pinfo->fprintf_func (pinfo->stream, ":\n");
4037 if (sym != NULL && bfd_asymbol_value (sym) > addr)
4038 nextsym = sym;
4039 else if (sym == NULL)
4040 nextsym = NULL;
4041 else
4043 #define is_valid_next_sym(SYM) \
4044 (strcmp (bfd_section_name ((SYM)->section), bfd_section_name (section)) == 0 \
4045 && (bfd_asymbol_value (SYM) > bfd_asymbol_value (sym)) \
4046 && pinfo->symbol_is_valid (SYM, pinfo))
4048 /* Search forward for the next appropriate symbol in
4049 SECTION. Note that all the symbols are sorted
4050 together into one big array, and that some sections
4051 may have overlapping addresses. */
4052 while (place < sorted_symcount
4053 && ! is_valid_next_sym (sorted_syms [place]))
4054 ++place;
4056 if (place >= sorted_symcount)
4057 nextsym = NULL;
4058 else
4059 nextsym = sorted_syms[place];
4062 if (sym != NULL && bfd_asymbol_value (sym) > addr)
4063 nextstop_offset = bfd_asymbol_value (sym) - section->vma;
4064 else if (nextsym == NULL)
4065 nextstop_offset = stop_offset;
4066 else
4067 nextstop_offset = bfd_asymbol_value (nextsym) - section->vma;
4069 if (nextstop_offset > stop_offset
4070 || nextstop_offset <= addr_offset)
4071 nextstop_offset = stop_offset;
4073 /* If a symbol is explicitly marked as being an object
4074 rather than a function, just dump the bytes without
4075 disassembling them. */
4076 if (disassemble_all
4077 || sym == NULL
4078 || sym->section != section
4079 || bfd_asymbol_value (sym) > addr
4080 || ((sym->flags & BSF_OBJECT) == 0
4081 && (strstr (bfd_asymbol_name (sym), "gnu_compiled")
4082 == NULL)
4083 && (strstr (bfd_asymbol_name (sym), "gcc2_compiled")
4084 == NULL))
4085 || (sym->flags & BSF_FUNCTION) != 0)
4086 insns = true;
4087 else
4088 insns = false;
4090 if (do_print)
4092 /* Resolve symbol name. */
4093 if (visualize_jumps && abfd && sym && sym->name)
4095 struct disassemble_info di;
4096 SFILE sf;
4098 sf.alloc = strlen (sym->name) + 40;
4099 sf.buffer = (char*) xmalloc (sf.alloc);
4100 sf.pos = 0;
4101 disassemble_set_printf
4102 (&di, &sf, (fprintf_ftype) objdump_sprintf,
4103 (fprintf_styled_ftype) objdump_styled_sprintf);
4105 objdump_print_symname (abfd, &di, sym);
4107 /* Fetch jump information. */
4108 detected_jumps = disassemble_jumps (pinfo, paux->disassemble_fn,
4109 addr_offset, nextstop_offset,
4110 rel_offset, rel_pp, rel_ppend);
4111 /* Free symbol name. */
4112 free (sf.buffer);
4115 /* Add jumps to output. */
4116 disassemble_bytes (pinfo, paux->disassemble_fn, insns, data,
4117 addr_offset, nextstop_offset,
4118 rel_offset, rel_pp, rel_ppend);
4120 /* Free jumps. */
4121 while (detected_jumps)
4123 detected_jumps = jump_info_free (detected_jumps);
4127 addr_offset = nextstop_offset;
4128 sym = nextsym;
4131 free (data);
4132 free (rel_ppstart);
4135 /* Disassemble the contents of an object file. */
4137 static void
4138 disassemble_data (bfd *abfd)
4140 struct disassemble_info disasm_info;
4141 struct objdump_disasm_info aux;
4142 long i;
4144 print_files = NULL;
4145 prev_functionname = NULL;
4146 prev_line = -1;
4147 prev_discriminator = 0;
4149 /* We make a copy of syms to sort. We don't want to sort syms
4150 because that will screw up the relocs. */
4151 sorted_symcount = symcount ? symcount : dynsymcount;
4152 sorted_syms = (asymbol **) xmalloc ((sorted_symcount + synthcount)
4153 * sizeof (asymbol *));
4154 if (sorted_symcount != 0)
4156 memcpy (sorted_syms, symcount ? syms : dynsyms,
4157 sorted_symcount * sizeof (asymbol *));
4159 sorted_symcount = remove_useless_symbols (sorted_syms, sorted_symcount);
4162 for (i = 0; i < synthcount; ++i)
4164 sorted_syms[sorted_symcount] = synthsyms + i;
4165 ++sorted_symcount;
4168 init_disassemble_info (&disasm_info, stdout, (fprintf_ftype) fprintf,
4169 (fprintf_styled_ftype) fprintf_styled);
4170 disasm_info.application_data = (void *) &aux;
4171 aux.abfd = abfd;
4172 aux.require_sec = false;
4173 disasm_info.dynrelbuf = NULL;
4174 disasm_info.dynrelcount = 0;
4175 aux.reloc = NULL;
4176 aux.symbol = disasm_sym;
4178 disasm_info.print_address_func = objdump_print_address;
4179 disasm_info.symbol_at_address_func = objdump_symbol_at_address;
4181 if (machine != NULL)
4183 const bfd_arch_info_type *inf = bfd_scan_arch (machine);
4185 if (inf == NULL)
4187 non_fatal (_("can't use supplied machine %s"), machine);
4188 exit_status = 1;
4190 else
4191 abfd->arch_info = inf;
4194 if (endian != BFD_ENDIAN_UNKNOWN)
4196 struct bfd_target *xvec;
4198 xvec = (struct bfd_target *) xmalloc (sizeof (struct bfd_target));
4199 memcpy (xvec, abfd->xvec, sizeof (struct bfd_target));
4200 xvec->byteorder = endian;
4201 abfd->xvec = xvec;
4204 /* Use libopcodes to locate a suitable disassembler. */
4205 aux.disassemble_fn = disassembler (bfd_get_arch (abfd),
4206 bfd_big_endian (abfd),
4207 bfd_get_mach (abfd), abfd);
4208 if (!aux.disassemble_fn)
4210 non_fatal (_("can't disassemble for architecture %s\n"),
4211 bfd_printable_arch_mach (bfd_get_arch (abfd), 0));
4212 exit_status = 1;
4213 free (sorted_syms);
4214 return;
4217 disasm_info.flavour = bfd_get_flavour (abfd);
4218 disasm_info.arch = bfd_get_arch (abfd);
4219 disasm_info.mach = bfd_get_mach (abfd);
4220 disasm_info.disassembler_options = disassembler_options;
4221 disasm_info.octets_per_byte = bfd_octets_per_byte (abfd, NULL);
4222 disasm_info.skip_zeroes = DEFAULT_SKIP_ZEROES;
4223 disasm_info.skip_zeroes_at_end = DEFAULT_SKIP_ZEROES_AT_END;
4224 disasm_info.disassembler_needs_relocs = false;
4226 if (bfd_big_endian (abfd))
4227 disasm_info.display_endian = disasm_info.endian = BFD_ENDIAN_BIG;
4228 else if (bfd_little_endian (abfd))
4229 disasm_info.display_endian = disasm_info.endian = BFD_ENDIAN_LITTLE;
4230 else
4231 /* ??? Aborting here seems too drastic. We could default to big or little
4232 instead. */
4233 disasm_info.endian = BFD_ENDIAN_UNKNOWN;
4235 disasm_info.endian_code = disasm_info.endian;
4237 /* Allow the target to customize the info structure. */
4238 disassemble_init_for_target (& disasm_info);
4240 /* Pre-load the dynamic relocs as we may need them during the disassembly. */
4241 long relsize = bfd_get_dynamic_reloc_upper_bound (abfd);
4243 if (relsize > 0)
4245 disasm_info.dynrelbuf = (arelent **) xmalloc (relsize);
4246 disasm_info.dynrelcount
4247 = bfd_canonicalize_dynamic_reloc (abfd, disasm_info.dynrelbuf, dynsyms);
4248 if (disasm_info.dynrelcount < 0)
4250 my_bfd_nonfatal (bfd_get_filename (abfd));
4251 free (disasm_info.dynrelbuf);
4252 disasm_info.dynrelbuf = NULL;
4253 disasm_info.dynrelcount = 0;
4255 else if (disasm_info.dynrelcount > 1)
4256 /* Sort the relocs by address. */
4257 qsort (disasm_info.dynrelbuf, disasm_info.dynrelcount,
4258 sizeof (arelent *), compare_relocs);
4261 disasm_info.symtab = sorted_syms;
4262 disasm_info.symtab_size = sorted_symcount;
4264 bfd_map_over_sections (abfd, disassemble_section, & disasm_info);
4266 free (disasm_info.dynrelbuf);
4267 disasm_info.dynrelbuf = NULL;
4268 free (sorted_syms);
4269 disassemble_free_target (&disasm_info);
4272 static bool
4273 load_specific_debug_section (enum dwarf_section_display_enum debug,
4274 asection *sec, void *file)
4276 struct dwarf_section *section = &debug_displays [debug].section;
4277 bfd *abfd = (bfd *) file;
4278 bfd_byte *contents;
4279 bfd_size_type amt;
4280 size_t alloced;
4281 bool ret;
4283 if (section->start != NULL)
4285 /* If it is already loaded, do nothing. */
4286 if (streq (section->filename, bfd_get_filename (abfd)))
4287 return true;
4288 free (section->start);
4289 section->start = NULL;
4292 section->filename = bfd_get_filename (abfd);
4293 section->reloc_info = NULL;
4294 section->num_relocs = 0;
4295 section->address = bfd_section_vma (sec);
4296 section->size = bfd_section_size (sec);
4297 /* PR 24360: On 32-bit hosts sizeof (size_t) < sizeof (bfd_size_type). */
4298 alloced = amt = section->size + 1;
4299 if (alloced != amt
4300 || alloced == 0
4301 || bfd_section_size_insane (abfd, sec))
4303 printf (_("\nSection '%s' has an invalid size: %#" PRIx64 ".\n"),
4304 sanitize_string (section->name),
4305 section->size);
4306 free_debug_section (debug);
4307 return false;
4310 ret = false;
4311 if ((sec->flags & SEC_HAS_CONTENTS) != 0)
4313 section->start = contents = xmalloc (alloced);
4314 /* Ensure any string section has a terminating NUL. */
4315 section->start[section->size] = 0;
4317 if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0
4318 && debug_displays [debug].relocate)
4320 ret = bfd_simple_get_relocated_section_contents (abfd,
4321 sec,
4322 section->start,
4323 syms) != NULL;
4324 if (ret)
4326 long reloc_size = bfd_get_reloc_upper_bound (abfd, sec);
4328 if (reloc_size > 0)
4330 long reloc_count;
4331 arelent **relocs;
4333 relocs = (arelent **) xmalloc (reloc_size);
4335 reloc_count = bfd_canonicalize_reloc (abfd, sec, relocs, syms);
4336 if (reloc_count <= 0)
4337 free (relocs);
4338 else
4340 section->reloc_info = relocs;
4341 section->num_relocs = reloc_count;
4346 else
4347 ret = bfd_get_full_section_contents (abfd, sec, &contents);
4350 if (!ret)
4352 printf (_("\nCan't get contents for section '%s'.\n"),
4353 sanitize_string (section->name));
4354 free_debug_section (debug);
4355 return false;
4358 return true;
4361 bool
4362 reloc_at (struct dwarf_section * dsec, uint64_t offset)
4364 arelent ** relocs;
4365 arelent * rp;
4367 if (dsec == NULL || dsec->reloc_info == NULL)
4368 return false;
4370 relocs = (arelent **) dsec->reloc_info;
4372 for (; (rp = * relocs) != NULL; ++ relocs)
4373 if (rp->address == offset)
4374 return true;
4376 return false;
4379 bool
4380 load_debug_section (enum dwarf_section_display_enum debug, void *file)
4382 struct dwarf_section *section = &debug_displays [debug].section;
4383 bfd *abfd = (bfd *) file;
4384 asection *sec;
4385 const char *name;
4387 if (!dump_any_debugging)
4388 return false;
4390 /* If it is already loaded, do nothing. */
4391 if (section->start != NULL)
4393 if (streq (section->filename, bfd_get_filename (abfd)))
4394 return true;
4396 /* Locate the debug section. */
4397 name = section->uncompressed_name;
4398 sec = bfd_get_section_by_name (abfd, name);
4399 if (sec == NULL)
4401 name = section->compressed_name;
4402 if (*name)
4403 sec = bfd_get_section_by_name (abfd, name);
4405 if (sec == NULL)
4407 name = section->xcoff_name;
4408 if (*name)
4409 sec = bfd_get_section_by_name (abfd, name);
4411 if (sec == NULL)
4412 return false;
4414 section->name = name;
4415 return load_specific_debug_section (debug, sec, file);
4418 void
4419 free_debug_section (enum dwarf_section_display_enum debug)
4421 struct dwarf_section *section = &debug_displays [debug].section;
4423 free ((char *) section->start);
4424 section->start = NULL;
4425 section->address = 0;
4426 section->size = 0;
4427 free ((char*) section->reloc_info);
4428 section->reloc_info = NULL;
4429 section->num_relocs= 0;
4432 void
4433 close_debug_file (void * file)
4435 bfd * abfd = (bfd *) file;
4437 bfd_close (abfd);
4440 void *
4441 open_debug_file (const char * pathname)
4443 bfd * data;
4445 data = bfd_openr (pathname, NULL);
4446 if (data == NULL)
4447 return NULL;
4449 /* Decompress sections unless dumping the section contents. */
4450 if (!dump_section_contents || decompressed_dumps)
4451 data->flags |= BFD_DECOMPRESS;
4453 if (! bfd_check_format (data, bfd_object))
4454 return NULL;
4456 return data;
4459 static void
4460 dump_dwarf_section (bfd *abfd, asection *section,
4461 void *arg)
4463 const char *name = bfd_section_name (section);
4464 const char *match;
4465 int i;
4466 bool is_mainfile = *(bool *) arg;
4468 if (*name == 0)
4469 return;
4471 if (!is_mainfile && !process_links
4472 && (section->flags & SEC_DEBUGGING) == 0)
4473 return;
4475 if (startswith (name, ".gnu.linkonce.wi."))
4476 match = ".debug_info";
4477 else
4478 match = name;
4480 for (i = 0; i < max; i++)
4481 if ((strcmp (debug_displays [i].section.uncompressed_name, match) == 0
4482 || strcmp (debug_displays [i].section.compressed_name, match) == 0
4483 || strcmp (debug_displays [i].section.xcoff_name, match) == 0)
4484 && debug_displays [i].enabled != NULL
4485 && *debug_displays [i].enabled)
4487 struct dwarf_section *sec = &debug_displays [i].section;
4489 if (strcmp (sec->uncompressed_name, match) == 0)
4490 sec->name = sec->uncompressed_name;
4491 else if (strcmp (sec->compressed_name, match) == 0)
4492 sec->name = sec->compressed_name;
4493 else
4494 sec->name = sec->xcoff_name;
4495 if (load_specific_debug_section ((enum dwarf_section_display_enum) i,
4496 section, abfd))
4498 debug_displays [i].display (sec, abfd);
4500 if (i != info && i != abbrev)
4501 free_debug_section ((enum dwarf_section_display_enum) i);
4503 break;
4507 /* Dump the dwarf debugging information. */
4509 static void
4510 dump_dwarf (bfd *abfd, bool is_mainfile)
4512 /* The byte_get pointer should have been set at the start of dump_bfd(). */
4513 if (byte_get == NULL)
4515 warn (_("File %s does not contain any dwarf debug information\n"),
4516 bfd_get_filename (abfd));
4517 return;
4520 switch (bfd_get_arch (abfd))
4522 case bfd_arch_s12z:
4523 /* S12Z has a 24 bit address space. But the only known
4524 producer of dwarf_info encodes addresses into 32 bits. */
4525 eh_addr_size = 4;
4526 break;
4528 default:
4529 eh_addr_size = bfd_arch_bits_per_address (abfd) / 8;
4530 break;
4533 init_dwarf_regnames_by_bfd_arch_and_mach (bfd_get_arch (abfd),
4534 bfd_get_mach (abfd));
4536 bfd_map_over_sections (abfd, dump_dwarf_section, (void *) &is_mainfile);
4539 /* Read ABFD's section SECT_NAME into *CONTENTS, and return a pointer to
4540 the section. Return NULL on failure. */
4542 static asection *
4543 read_section (bfd *abfd, const char *sect_name, bfd_byte **contents)
4545 asection *sec;
4547 *contents = NULL;
4548 sec = bfd_get_section_by_name (abfd, sect_name);
4549 if (sec == NULL)
4551 printf (_("No %s section present\n\n"), sanitize_string (sect_name));
4552 return NULL;
4555 if ((bfd_section_flags (sec) & SEC_HAS_CONTENTS) == 0)
4556 bfd_set_error (bfd_error_no_contents);
4557 else if (bfd_malloc_and_get_section (abfd, sec, contents))
4558 return sec;
4560 non_fatal (_("reading %s section of %s failed: %s"),
4561 sect_name, bfd_get_filename (abfd),
4562 bfd_errmsg (bfd_get_error ()));
4563 exit_status = 1;
4564 return NULL;
4567 /* Stabs entries use a 12 byte format:
4568 4 byte string table index
4569 1 byte stab type
4570 1 byte stab other field
4571 2 byte stab desc field
4572 4 byte stab value
4573 FIXME: This will have to change for a 64 bit object format. */
4575 #define STRDXOFF (0)
4576 #define TYPEOFF (4)
4577 #define OTHEROFF (5)
4578 #define DESCOFF (6)
4579 #define VALOFF (8)
4580 #define STABSIZE (12)
4582 /* Print ABFD's stabs section STABSECT_NAME (in `stabs'),
4583 using string table section STRSECT_NAME (in `strtab'). */
4585 static void
4586 print_section_stabs (bfd *abfd,
4587 const char *stabsect_name,
4588 unsigned *string_offset_ptr)
4590 int i;
4591 unsigned file_string_table_offset = 0;
4592 unsigned next_file_string_table_offset = *string_offset_ptr;
4593 bfd_byte *stabp, *stabs_end;
4595 stabp = stabs;
4596 stabs_end = PTR_ADD (stabp, stab_size);
4598 printf (_("Contents of %s section:\n\n"), sanitize_string (stabsect_name));
4599 printf ("Symnum n_type n_othr n_desc n_value n_strx String\n");
4601 /* Loop through all symbols and print them.
4603 We start the index at -1 because there is a dummy symbol on
4604 the front of stabs-in-{coff,elf} sections that supplies sizes. */
4605 for (i = -1; (size_t) (stabs_end - stabp) >= STABSIZE; stabp += STABSIZE, i++)
4607 const char *name;
4608 unsigned long strx;
4609 unsigned char type, other;
4610 unsigned short desc;
4611 bfd_vma value;
4613 strx = bfd_h_get_32 (abfd, stabp + STRDXOFF);
4614 type = bfd_h_get_8 (abfd, stabp + TYPEOFF);
4615 other = bfd_h_get_8 (abfd, stabp + OTHEROFF);
4616 desc = bfd_h_get_16 (abfd, stabp + DESCOFF);
4617 value = bfd_h_get_32 (abfd, stabp + VALOFF);
4619 printf ("\n%-6d ", i);
4620 /* Either print the stab name, or, if unnamed, print its number
4621 again (makes consistent formatting for tools like awk). */
4622 name = bfd_get_stab_name (type);
4623 if (name != NULL)
4624 printf ("%-6s", sanitize_string (name));
4625 else if (type == N_UNDF)
4626 printf ("HdrSym");
4627 else
4628 printf ("%-6d", type);
4629 printf (" %-6d %-6d ", other, desc);
4630 bfd_printf_vma (abfd, value);
4631 printf (" %-6lu", strx);
4633 /* Symbols with type == 0 (N_UNDF) specify the length of the
4634 string table associated with this file. We use that info
4635 to know how to relocate the *next* file's string table indices. */
4636 if (type == N_UNDF)
4638 file_string_table_offset = next_file_string_table_offset;
4639 next_file_string_table_offset += value;
4641 else
4643 bfd_size_type amt = strx + file_string_table_offset;
4645 /* Using the (possibly updated) string table offset, print the
4646 string (if any) associated with this symbol. */
4647 if (amt < stabstr_size)
4648 /* PR 17512: file: 079-79389-0.001:0.1.
4649 FIXME: May need to sanitize this string before displaying. */
4650 printf (" %.*s", (int)(stabstr_size - amt), strtab + amt);
4651 else
4652 printf (" *");
4655 printf ("\n\n");
4656 *string_offset_ptr = next_file_string_table_offset;
4659 typedef struct
4661 const char * section_name;
4662 const char * string_section_name;
4663 unsigned string_offset;
4665 stab_section_names;
4667 static void
4668 find_stabs_section (bfd *abfd, asection *section, void *names)
4670 int len;
4671 stab_section_names * sought = (stab_section_names *) names;
4673 /* Check for section names for which stabsect_name is a prefix, to
4674 handle .stab.N, etc. */
4675 len = strlen (sought->section_name);
4677 /* If the prefix matches, and the files section name ends with a
4678 nul or a digit, then we match. I.e., we want either an exact
4679 match or a section followed by a number. */
4680 if (strncmp (sought->section_name, section->name, len) == 0
4681 && (section->name[len] == 0
4682 || (section->name[len] == '.' && ISDIGIT (section->name[len + 1]))))
4684 asection *s;
4685 if (strtab == NULL)
4687 s = read_section (abfd, sought->string_section_name, &strtab);
4688 if (s != NULL)
4689 stabstr_size = bfd_section_size (s);
4692 if (strtab)
4694 s = read_section (abfd, section->name, &stabs);
4695 if (s != NULL)
4697 stab_size = bfd_section_size (s);
4698 print_section_stabs (abfd, section->name, &sought->string_offset);
4699 free (stabs);
4705 static void
4706 dump_stabs_section (bfd *abfd, char *stabsect_name, char *strsect_name)
4708 stab_section_names s;
4710 s.section_name = stabsect_name;
4711 s.string_section_name = strsect_name;
4712 s.string_offset = 0;
4714 bfd_map_over_sections (abfd, find_stabs_section, & s);
4716 free (strtab);
4717 strtab = NULL;
4720 /* Dump the any sections containing stabs debugging information. */
4722 static void
4723 dump_stabs (bfd *abfd)
4725 dump_stabs_section (abfd, ".stab", ".stabstr");
4726 dump_stabs_section (abfd, ".stab.excl", ".stab.exclstr");
4727 dump_stabs_section (abfd, ".stab.index", ".stab.indexstr");
4729 /* For Darwin. */
4730 dump_stabs_section (abfd, "LC_SYMTAB.stabs", "LC_SYMTAB.stabstr");
4732 dump_stabs_section (abfd, "$GDB_SYMBOLS$", "$GDB_STRINGS$");
4735 static void
4736 dump_bfd_header (bfd *abfd)
4738 char *comma = "";
4740 printf (_("architecture: %s, "),
4741 bfd_printable_arch_mach (bfd_get_arch (abfd),
4742 bfd_get_mach (abfd)));
4743 printf (_("flags 0x%08x:\n"), abfd->flags & ~BFD_FLAGS_FOR_BFD_USE_MASK);
4745 #define PF(x, y) if (abfd->flags & x) {printf ("%s%s", comma, y); comma=", ";}
4746 PF (HAS_RELOC, "HAS_RELOC");
4747 PF (EXEC_P, "EXEC_P");
4748 PF (HAS_LINENO, "HAS_LINENO");
4749 PF (HAS_DEBUG, "HAS_DEBUG");
4750 PF (HAS_SYMS, "HAS_SYMS");
4751 PF (HAS_LOCALS, "HAS_LOCALS");
4752 PF (DYNAMIC, "DYNAMIC");
4753 PF (WP_TEXT, "WP_TEXT");
4754 PF (D_PAGED, "D_PAGED");
4755 PF (BFD_IS_RELAXABLE, "BFD_IS_RELAXABLE");
4756 printf (_("\nstart address 0x"));
4757 bfd_printf_vma (abfd, abfd->start_address);
4758 printf ("\n");
4762 #ifdef ENABLE_LIBCTF
4763 /* Formatting callback function passed to ctf_dump. Returns either the pointer
4764 it is passed, or a pointer to newly-allocated storage, in which case
4765 dump_ctf() will free it when it no longer needs it. */
4767 static char *
4768 dump_ctf_indent_lines (ctf_sect_names_t sect ATTRIBUTE_UNUSED,
4769 char *s, void *arg)
4771 const char *blanks = arg;
4772 char *new_s;
4774 if (asprintf (&new_s, "%s%s", blanks, s) < 0)
4775 return s;
4776 return new_s;
4779 /* Make a ctfsect suitable for ctf_bfdopen_ctfsect(). */
4780 static ctf_sect_t
4781 make_ctfsect (const char *name, bfd_byte *data,
4782 bfd_size_type size)
4784 ctf_sect_t ctfsect;
4786 ctfsect.cts_name = name;
4787 ctfsect.cts_entsize = 1;
4788 ctfsect.cts_size = size;
4789 ctfsect.cts_data = data;
4791 return ctfsect;
4794 /* Dump CTF errors/warnings. */
4795 static void
4796 dump_ctf_errs (ctf_dict_t *fp)
4798 ctf_next_t *it = NULL;
4799 char *errtext;
4800 int is_warning;
4801 int err;
4803 /* Dump accumulated errors and warnings. */
4804 while ((errtext = ctf_errwarning_next (fp, &it, &is_warning, &err)) != NULL)
4806 non_fatal (_("%s: %s"), is_warning ? _("warning"): _("error"),
4807 errtext);
4808 free (errtext);
4810 if (err != ECTF_NEXT_END)
4812 non_fatal (_("CTF error: cannot get CTF errors: `%s'"),
4813 ctf_errmsg (err));
4817 /* Dump one CTF archive member. */
4819 static void
4820 dump_ctf_archive_member (ctf_dict_t *ctf, const char *name, ctf_dict_t *parent,
4821 size_t member)
4823 const char *things[] = {"Header", "Labels", "Data objects",
4824 "Function objects", "Variables", "Types", "Strings",
4825 ""};
4826 const char **thing;
4827 size_t i;
4829 /* Don't print out the name of the default-named archive member if it appears
4830 first in the list. The name .ctf appears everywhere, even for things that
4831 aren't really archives, so printing it out is liable to be confusing; also,
4832 the common case by far is for only one archive member to exist, and hiding
4833 it in that case seems worthwhile. */
4835 if (strcmp (name, ".ctf") != 0 || member != 0)
4836 printf (_("\nCTF archive member: %s:\n"), sanitize_string (name));
4838 if (ctf_parent_name (ctf) != NULL)
4839 ctf_import (ctf, parent);
4841 for (i = 0, thing = things; *thing[0]; thing++, i++)
4843 ctf_dump_state_t *s = NULL;
4844 char *item;
4846 printf ("\n %s:\n", *thing);
4847 while ((item = ctf_dump (ctf, &s, i, dump_ctf_indent_lines,
4848 (void *) " ")) != NULL)
4850 printf ("%s\n", item);
4851 free (item);
4854 if (ctf_errno (ctf))
4856 non_fatal (_("Iteration failed: %s, %s"), *thing,
4857 ctf_errmsg (ctf_errno (ctf)));
4858 break;
4862 dump_ctf_errs (ctf);
4865 /* Dump the CTF debugging information. */
4867 static void
4868 dump_ctf (bfd *abfd, const char *sect_name, const char *parent_name,
4869 const char *parent_sect_name)
4871 asection *sec, *psec = NULL;
4872 ctf_archive_t *ctfa;
4873 ctf_archive_t *ctfpa = NULL;
4874 bfd_byte *ctfdata = NULL;
4875 bfd_byte *ctfpdata = NULL;
4876 ctf_sect_t ctfsect;
4877 ctf_dict_t *parent;
4878 ctf_dict_t *fp;
4879 ctf_next_t *i = NULL;
4880 const char *name;
4881 size_t member = 0;
4882 int err;
4884 if (sect_name == NULL)
4885 sect_name = ".ctf";
4887 sec = read_section (abfd, sect_name, &ctfdata);
4888 if (sec == NULL)
4890 my_bfd_nonfatal (bfd_get_filename (abfd));
4891 return;
4894 /* Load the CTF file and dump it. Preload the parent dict, since it will
4895 need to be imported into every child in turn. The parent dict may come
4896 from a different section entirely. */
4898 ctfsect = make_ctfsect (sect_name, ctfdata, bfd_section_size (sec));
4899 if ((ctfa = ctf_bfdopen_ctfsect (abfd, &ctfsect, &err)) == NULL)
4901 dump_ctf_errs (NULL);
4902 non_fatal (_("CTF open failure: %s"), ctf_errmsg (err));
4903 my_bfd_nonfatal (bfd_get_filename (abfd));
4904 free (ctfdata);
4905 return;
4908 if (parent_sect_name)
4910 psec = read_section (abfd, parent_sect_name, &ctfpdata);
4911 if (sec == NULL)
4913 my_bfd_nonfatal (bfd_get_filename (abfd));
4914 free (ctfdata);
4915 return;
4918 ctfsect = make_ctfsect (parent_sect_name, ctfpdata, bfd_section_size (psec));
4919 if ((ctfpa = ctf_bfdopen_ctfsect (abfd, &ctfsect, &err)) == NULL)
4921 dump_ctf_errs (NULL);
4922 non_fatal (_("CTF open failure: %s"), ctf_errmsg (err));
4923 my_bfd_nonfatal (bfd_get_filename (abfd));
4924 free (ctfdata);
4925 free (ctfpdata);
4926 return;
4929 else
4930 ctfpa = ctfa;
4932 if ((parent = ctf_dict_open (ctfpa, parent_name, &err)) == NULL)
4934 dump_ctf_errs (NULL);
4935 non_fatal (_("CTF open failure: %s"), ctf_errmsg (err));
4936 my_bfd_nonfatal (bfd_get_filename (abfd));
4937 ctf_close (ctfa);
4938 free (ctfdata);
4939 free (ctfpdata);
4940 return;
4943 printf (_("Contents of CTF section %s:\n"), sanitize_string (sect_name));
4945 while ((fp = ctf_archive_next (ctfa, &i, &name, 0, &err)) != NULL)
4946 dump_ctf_archive_member (fp, name, parent, member++);
4947 if (err != ECTF_NEXT_END)
4949 dump_ctf_errs (NULL);
4950 non_fatal (_("CTF archive member open failure: %s"), ctf_errmsg (err));
4951 my_bfd_nonfatal (bfd_get_filename (abfd));
4953 ctf_dict_close (parent);
4954 ctf_close (ctfa);
4955 free (ctfdata);
4956 if (parent_sect_name)
4958 ctf_close (ctfpa);
4959 free (ctfpdata);
4962 #else
4963 static void
4964 dump_ctf (bfd *abfd ATTRIBUTE_UNUSED, const char *sect_name ATTRIBUTE_UNUSED,
4965 const char *parent_name ATTRIBUTE_UNUSED,
4966 const char *parent_sect_name ATTRIBUTE_UNUSED) {}
4967 #endif
4969 static void
4970 dump_section_sframe (bfd *abfd ATTRIBUTE_UNUSED,
4971 const char * sect_name)
4973 asection *sec;
4974 sframe_decoder_ctx *sfd_ctx = NULL;
4975 bfd_size_type sf_size;
4976 bfd_byte *sframe_data;
4977 bfd_vma sf_vma;
4978 int err = 0;
4980 if (sect_name == NULL)
4981 sect_name = ".sframe";
4983 sec = read_section (abfd, sect_name, &sframe_data);
4984 if (sec == NULL)
4986 my_bfd_nonfatal (bfd_get_filename (abfd));
4987 return;
4989 sf_size = bfd_section_size (sec);
4990 sf_vma = bfd_section_vma (sec);
4992 /* Decode the contents of the section. */
4993 sfd_ctx = sframe_decode ((const char*)sframe_data, sf_size, &err);
4994 if (!sfd_ctx)
4996 my_bfd_nonfatal (bfd_get_filename (abfd));
4997 free (sframe_data);
4998 return;
5001 printf (_("Contents of the SFrame section %s:"),
5002 sanitize_string (sect_name));
5003 /* Dump the contents as text. */
5004 dump_sframe (sfd_ctx, sf_vma);
5006 sframe_decoder_free (&sfd_ctx);
5007 free (sframe_data);
5011 static void
5012 dump_bfd_private_header (bfd *abfd)
5014 if (!bfd_print_private_bfd_data (abfd, stdout))
5015 non_fatal (_("warning: private headers incomplete: %s"),
5016 bfd_errmsg (bfd_get_error ()));
5019 static void
5020 dump_target_specific (bfd *abfd)
5022 const struct objdump_private_desc * const *desc;
5023 struct objdump_private_option *opt;
5024 char *e, *b;
5026 /* Find the desc. */
5027 for (desc = objdump_private_vectors; *desc != NULL; desc++)
5028 if ((*desc)->filter (abfd))
5029 break;
5031 if (*desc == NULL)
5033 non_fatal (_("option -P/--private not supported by this file"));
5034 return;
5037 /* Clear all options. */
5038 for (opt = (*desc)->options; opt->name; opt++)
5039 opt->selected = false;
5041 /* Decode options. */
5042 b = dump_private_options;
5045 e = strchr (b, ',');
5047 if (e)
5048 *e = 0;
5050 for (opt = (*desc)->options; opt->name; opt++)
5051 if (strcmp (opt->name, b) == 0)
5053 opt->selected = true;
5054 break;
5056 if (opt->name == NULL)
5057 non_fatal (_("target specific dump '%s' not supported"), b);
5059 if (e)
5061 *e = ',';
5062 b = e + 1;
5065 while (e != NULL);
5067 /* Dump. */
5068 (*desc)->dump (abfd);
5071 /* Display a section in hexadecimal format with associated characters.
5072 Each line prefixed by the zero padded address. */
5074 static void
5075 dump_section (bfd *abfd, asection *section, void *dummy ATTRIBUTE_UNUSED)
5077 bfd_byte *data = NULL;
5078 bfd_size_type datasize;
5079 bfd_vma addr_offset;
5080 bfd_vma start_offset;
5081 bfd_vma stop_offset;
5082 unsigned int opb = bfd_octets_per_byte (abfd, section);
5083 /* Bytes per line. */
5084 const int onaline = 16;
5085 char buf[64];
5086 int count;
5087 int width;
5089 if (only_list == NULL)
5091 if ((section->flags & SEC_HAS_CONTENTS) == 0)
5092 return;
5094 else if (!process_section_p (section))
5095 return;
5097 if ((datasize = bfd_section_size (section)) == 0)
5098 return;
5100 /* Compute the address range to display. */
5101 if (start_address == (bfd_vma) -1
5102 || start_address < section->vma)
5103 start_offset = 0;
5104 else
5105 start_offset = start_address - section->vma;
5107 if (stop_address == (bfd_vma) -1)
5108 stop_offset = datasize / opb;
5109 else
5111 if (stop_address < section->vma)
5112 stop_offset = 0;
5113 else
5114 stop_offset = stop_address - section->vma;
5116 if (stop_offset > datasize / opb)
5117 stop_offset = datasize / opb;
5120 if (start_offset >= stop_offset)
5121 return;
5123 printf (_("Contents of section %s:"), sanitize_string (section->name));
5124 if (display_file_offsets)
5125 printf (_(" (Starting at file offset: 0x%lx)"),
5126 (unsigned long) (section->filepos + start_offset));
5127 printf ("\n");
5129 if (bfd_is_section_compressed (abfd, section) && ! decompressed_dumps)
5130 printf (_(" NOTE: This section is compressed, but its contents have NOT been expanded for this dump.\n"));
5132 if (!bfd_get_full_section_contents (abfd, section, &data))
5134 non_fatal (_("Reading section %s failed because: %s"),
5135 section->name, bfd_errmsg (bfd_get_error ()));
5136 return;
5139 width = 4;
5141 bfd_sprintf_vma (abfd, buf, start_offset + section->vma);
5142 if (strlen (buf) >= sizeof (buf))
5143 abort ();
5145 count = 0;
5146 while (buf[count] == '0' && buf[count+1] != '\0')
5147 count++;
5148 count = strlen (buf) - count;
5149 if (count > width)
5150 width = count;
5152 bfd_sprintf_vma (abfd, buf, stop_offset + section->vma - 1);
5153 if (strlen (buf) >= sizeof (buf))
5154 abort ();
5156 count = 0;
5157 while (buf[count] == '0' && buf[count+1] != '\0')
5158 count++;
5159 count = strlen (buf) - count;
5160 if (count > width)
5161 width = count;
5163 for (addr_offset = start_offset;
5164 addr_offset < stop_offset; addr_offset += onaline / opb)
5166 bfd_size_type j;
5168 bfd_sprintf_vma (abfd, buf, (addr_offset + section->vma));
5169 count = strlen (buf);
5170 if ((size_t) count >= sizeof (buf))
5171 abort ();
5173 putchar (' ');
5174 while (count < width)
5176 putchar ('0');
5177 count++;
5179 fputs (buf + count - width, stdout);
5180 putchar (' ');
5182 for (j = addr_offset * opb;
5183 j < addr_offset * opb + onaline; j++)
5185 if (j < stop_offset * opb)
5186 printf ("%02x", (unsigned) (data[j]));
5187 else
5188 printf (" ");
5189 if ((j & 3) == 3)
5190 printf (" ");
5193 printf (" ");
5194 for (j = addr_offset * opb;
5195 j < addr_offset * opb + onaline; j++)
5197 if (j >= stop_offset * opb)
5198 printf (" ");
5199 else
5200 printf ("%c", ISPRINT (data[j]) ? data[j] : '.');
5202 putchar ('\n');
5204 free (data);
5207 /* Actually display the various requested regions. */
5209 static void
5210 dump_data (bfd *abfd)
5212 bfd_map_over_sections (abfd, dump_section, NULL);
5215 /* Should perhaps share code and display with nm? */
5217 static void
5218 dump_symbols (bfd *abfd ATTRIBUTE_UNUSED, bool dynamic)
5220 asymbol **current;
5221 long max_count;
5222 long count;
5224 if (dynamic)
5226 current = dynsyms;
5227 max_count = dynsymcount;
5228 printf ("DYNAMIC SYMBOL TABLE:\n");
5230 else
5232 current = syms;
5233 max_count = symcount;
5234 printf ("SYMBOL TABLE:\n");
5237 if (max_count == 0)
5238 printf (_("no symbols\n"));
5240 for (count = 0; count < max_count; count++)
5242 bfd *cur_bfd;
5244 if (*current == NULL)
5245 printf (_("no information for symbol number %ld\n"), count);
5247 else if ((cur_bfd = bfd_asymbol_bfd (*current)) == NULL)
5248 printf (_("could not determine the type of symbol number %ld\n"),
5249 count);
5251 else if (process_section_p ((* current)->section)
5252 && (dump_special_syms
5253 || !bfd_is_target_special_symbol (cur_bfd, *current)))
5255 const char *name = (*current)->name;
5257 if (do_demangle && name != NULL && *name != '\0')
5259 char *alloc;
5261 /* If we want to demangle the name, we demangle it
5262 here, and temporarily clobber it while calling
5263 bfd_print_symbol. FIXME: This is a gross hack. */
5264 alloc = bfd_demangle (cur_bfd, name, demangle_flags);
5265 if (alloc != NULL)
5266 (*current)->name = alloc;
5267 bfd_print_symbol (cur_bfd, stdout, *current,
5268 bfd_print_symbol_all);
5269 if (alloc != NULL)
5271 (*current)->name = name;
5272 free (alloc);
5275 else if (unicode_display != unicode_default
5276 && name != NULL && *name != '\0')
5278 const char * sanitized_name;
5280 /* If we want to sanitize the name, we do it here, and
5281 temporarily clobber it while calling bfd_print_symbol.
5282 FIXME: This is a gross hack. */
5283 sanitized_name = sanitize_string (name);
5284 if (sanitized_name != name)
5285 (*current)->name = sanitized_name;
5286 else
5287 sanitized_name = NULL;
5288 bfd_print_symbol (cur_bfd, stdout, *current,
5289 bfd_print_symbol_all);
5290 if (sanitized_name != NULL)
5291 (*current)->name = name;
5293 else
5294 bfd_print_symbol (cur_bfd, stdout, *current,
5295 bfd_print_symbol_all);
5296 printf ("\n");
5299 current++;
5301 printf ("\n\n");
5304 static void
5305 dump_reloc_set (bfd *abfd, asection *sec, arelent **relpp, long relcount)
5307 arelent **p;
5308 char *last_filename, *last_functionname;
5309 unsigned int last_line;
5310 unsigned int last_discriminator;
5312 /* Get column headers lined up reasonably. */
5314 static int width;
5316 if (width == 0)
5318 char buf[30];
5320 bfd_sprintf_vma (abfd, buf, (bfd_vma) -1);
5321 width = strlen (buf) - 7;
5323 printf ("OFFSET %*s TYPE %*s VALUE\n", width, "", 12, "");
5326 last_filename = NULL;
5327 last_functionname = NULL;
5328 last_line = 0;
5329 last_discriminator = 0;
5331 for (p = relpp; relcount && *p != NULL; p++, relcount--)
5333 arelent *q = *p;
5334 const char *filename, *functionname;
5335 unsigned int linenumber;
5336 unsigned int discriminator;
5337 const char *sym_name;
5338 const char *section_name;
5339 bfd_vma addend2 = 0;
5341 if (start_address != (bfd_vma) -1
5342 && q->address < start_address)
5343 continue;
5344 if (stop_address != (bfd_vma) -1
5345 && q->address > stop_address)
5346 continue;
5348 if (with_line_numbers
5349 && sec != NULL
5350 && bfd_find_nearest_line_discriminator (abfd, sec, syms, q->address,
5351 &filename, &functionname,
5352 &linenumber, &discriminator))
5354 if (functionname != NULL
5355 && (last_functionname == NULL
5356 || strcmp (functionname, last_functionname) != 0))
5358 printf ("%s():\n", sanitize_string (functionname));
5359 if (last_functionname != NULL)
5360 free (last_functionname);
5361 last_functionname = xstrdup (functionname);
5364 if (linenumber > 0
5365 && (linenumber != last_line
5366 || (filename != NULL
5367 && last_filename != NULL
5368 && filename_cmp (filename, last_filename) != 0)
5369 || (discriminator != last_discriminator)))
5371 if (discriminator > 0)
5372 printf ("%s:%u\n", filename == NULL ? "???" :
5373 sanitize_string (filename), linenumber);
5374 else
5375 printf ("%s:%u (discriminator %u)\n",
5376 filename == NULL ? "???" : sanitize_string (filename),
5377 linenumber, discriminator);
5378 last_line = linenumber;
5379 last_discriminator = discriminator;
5380 if (last_filename != NULL)
5381 free (last_filename);
5382 if (filename == NULL)
5383 last_filename = NULL;
5384 else
5385 last_filename = xstrdup (filename);
5389 if (q->sym_ptr_ptr && *q->sym_ptr_ptr)
5391 sym_name = (*(q->sym_ptr_ptr))->name;
5392 section_name = (*(q->sym_ptr_ptr))->section->name;
5394 else
5396 sym_name = NULL;
5397 section_name = NULL;
5400 bfd_printf_vma (abfd, q->address);
5401 if (q->howto == NULL)
5402 printf (" *unknown* ");
5403 else if (q->howto->name)
5405 const char *name = q->howto->name;
5407 /* R_SPARC_OLO10 relocations contain two addends.
5408 But because 'arelent' lacks enough storage to
5409 store them both, the 64-bit ELF Sparc backend
5410 records this as two relocations. One R_SPARC_LO10
5411 and one R_SPARC_13, both pointing to the same
5412 address. This is merely so that we have some
5413 place to store both addend fields.
5415 Undo this transformation, otherwise the output
5416 will be confusing. */
5417 if (abfd->xvec->flavour == bfd_target_elf_flavour
5418 && elf_tdata (abfd)->elf_header->e_machine == EM_SPARCV9
5419 && relcount > 1
5420 && !strcmp (q->howto->name, "R_SPARC_LO10"))
5422 arelent *q2 = *(p + 1);
5423 if (q2 != NULL
5424 && q2->howto
5425 && q->address == q2->address
5426 && !strcmp (q2->howto->name, "R_SPARC_13"))
5428 name = "R_SPARC_OLO10";
5429 addend2 = q2->addend;
5430 p++;
5433 printf (" %-16s ", name);
5435 else
5436 printf (" %-16d ", q->howto->type);
5438 if (sym_name)
5440 objdump_print_symname (abfd, NULL, *q->sym_ptr_ptr);
5442 else
5444 if (section_name == NULL)
5445 section_name = "*unknown*";
5446 printf ("[%s]", sanitize_string (section_name));
5449 if (q->addend)
5451 bfd_signed_vma addend = q->addend;
5452 if (addend < 0)
5454 printf ("-0x");
5455 addend = -addend;
5457 else
5458 printf ("+0x");
5459 bfd_printf_vma (abfd, addend);
5461 if (addend2)
5463 printf ("+0x");
5464 bfd_printf_vma (abfd, addend2);
5467 printf ("\n");
5470 if (last_filename != NULL)
5471 free (last_filename);
5472 if (last_functionname != NULL)
5473 free (last_functionname);
5476 static void
5477 dump_relocs_in_section (bfd *abfd,
5478 asection *section,
5479 void *dummy ATTRIBUTE_UNUSED)
5481 arelent **relpp;
5482 long relcount;
5483 long relsize;
5485 if ( bfd_is_abs_section (section)
5486 || bfd_is_und_section (section)
5487 || bfd_is_com_section (section)
5488 || (! process_section_p (section))
5489 || ((section->flags & SEC_RELOC) == 0))
5490 return;
5492 printf ("RELOCATION RECORDS FOR [%s]:", sanitize_string (section->name));
5494 relsize = bfd_get_reloc_upper_bound (abfd, section);
5495 if (relsize == 0)
5497 printf (" (none)\n\n");
5498 return;
5501 if (relsize < 0)
5503 relpp = NULL;
5504 relcount = relsize;
5506 else
5508 relpp = (arelent **) xmalloc (relsize);
5509 relcount = bfd_canonicalize_reloc (abfd, section, relpp, syms);
5512 if (relcount < 0)
5514 printf ("\n");
5515 non_fatal (_("failed to read relocs in: %s"),
5516 sanitize_string (bfd_get_filename (abfd)));
5517 my_bfd_nonfatal (_("error message was"));
5519 else if (relcount == 0)
5520 printf (" (none)\n\n");
5521 else
5523 printf ("\n");
5524 dump_reloc_set (abfd, section, relpp, relcount);
5525 printf ("\n\n");
5527 free (relpp);
5530 static void
5531 dump_relocs (bfd *abfd)
5533 bfd_map_over_sections (abfd, dump_relocs_in_section, NULL);
5536 static void
5537 dump_dynamic_relocs (bfd *abfd)
5539 long relsize;
5540 arelent **relpp;
5541 long relcount;
5543 relsize = bfd_get_dynamic_reloc_upper_bound (abfd);
5545 printf ("DYNAMIC RELOCATION RECORDS");
5547 if (relsize == 0)
5549 printf (" (none)\n\n");
5550 return;
5553 if (relsize < 0)
5555 relpp = NULL;
5556 relcount = relsize;
5558 else
5560 relpp = (arelent **) xmalloc (relsize);
5561 relcount = bfd_canonicalize_dynamic_reloc (abfd, relpp, dynsyms);
5564 if (relcount < 0)
5566 printf ("\n");
5567 non_fatal (_("failed to read relocs in: %s"),
5568 sanitize_string (bfd_get_filename (abfd)));
5569 my_bfd_nonfatal (_("error message was"));
5571 else if (relcount == 0)
5572 printf (" (none)\n\n");
5573 else
5575 printf ("\n");
5576 dump_reloc_set (abfd, NULL, relpp, relcount);
5577 printf ("\n\n");
5579 free (relpp);
5582 /* Creates a table of paths, to search for source files. */
5584 static void
5585 add_include_path (const char *path)
5587 if (path[0] == 0)
5588 return;
5589 include_path_count++;
5590 include_paths = (const char **)
5591 xrealloc (include_paths, include_path_count * sizeof (*include_paths));
5592 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
5593 if (path[1] == ':' && path[2] == 0)
5594 path = concat (path, ".", (const char *) 0);
5595 #endif
5596 include_paths[include_path_count - 1] = path;
5599 static void
5600 adjust_addresses (bfd *abfd ATTRIBUTE_UNUSED,
5601 asection *section,
5602 void *arg)
5604 if ((section->flags & SEC_DEBUGGING) == 0)
5606 bool *has_reloc_p = (bool *) arg;
5607 section->vma += adjust_section_vma;
5608 if (*has_reloc_p)
5609 section->lma += adjust_section_vma;
5613 /* Return the sign-extended form of an ARCH_SIZE sized VMA. */
5615 static bfd_vma
5616 sign_extend_address (bfd *abfd ATTRIBUTE_UNUSED,
5617 bfd_vma vma,
5618 unsigned arch_size)
5620 bfd_vma mask;
5621 mask = (bfd_vma) 1 << (arch_size - 1);
5622 return (((vma & ((mask << 1) - 1)) ^ mask) - mask);
5625 static bool
5626 might_need_separate_debug_info (bool is_mainfile)
5628 /* We do not follow links from debug info files. */
5629 if (! is_mainfile)
5630 return false;
5632 /* Since do_follow_links might be enabled by default, only treat it as an
5633 indication that separate files should be loaded if setting it was a
5634 deliberate user action. */
5635 if (DEFAULT_FOR_FOLLOW_LINKS == 0 && do_follow_links)
5636 return true;
5638 if (process_links || dump_symtab || dump_debugging
5639 || dump_dwarf_section_info || with_source_code)
5640 return true;
5642 return false;
5645 /* Dump selected contents of ABFD. */
5647 static void
5648 dump_bfd (bfd *abfd, bool is_mainfile)
5650 const struct elf_backend_data * bed;
5652 if (bfd_big_endian (abfd))
5653 byte_get = byte_get_big_endian;
5654 else if (bfd_little_endian (abfd))
5655 byte_get = byte_get_little_endian;
5656 else
5657 byte_get = NULL;
5659 /* Load any separate debug information files. */
5660 if (byte_get != NULL && might_need_separate_debug_info (is_mainfile))
5662 load_separate_debug_files (abfd, bfd_get_filename (abfd));
5664 /* If asked to do so, recursively dump the separate files. */
5665 if (do_follow_links)
5667 separate_info * i;
5669 for (i = first_separate_info; i != NULL; i = i->next)
5670 dump_bfd (i->handle, false);
5674 /* Adjust user-specified start and stop limits for targets that use
5675 signed addresses. */
5676 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
5677 && (bed = get_elf_backend_data (abfd)) != NULL
5678 && bed->sign_extend_vma)
5680 start_address = sign_extend_address (abfd, start_address,
5681 bed->s->arch_size);
5682 stop_address = sign_extend_address (abfd, stop_address,
5683 bed->s->arch_size);
5686 /* If we are adjusting section VMA's, change them all now. Changing
5687 the BFD information is a hack. However, we must do it, or
5688 bfd_find_nearest_line will not do the right thing. */
5689 if (adjust_section_vma != 0)
5691 bool has_reloc = (abfd->flags & HAS_RELOC);
5692 bfd_map_over_sections (abfd, adjust_addresses, &has_reloc);
5695 if (is_mainfile || process_links)
5697 if (! dump_debugging_tags && ! suppress_bfd_header)
5698 printf (_("\n%s: file format %s\n"),
5699 sanitize_string (bfd_get_filename (abfd)),
5700 abfd->xvec->name);
5701 if (dump_ar_hdrs)
5702 print_arelt_descr (stdout, abfd, true, false);
5703 if (dump_file_header)
5704 dump_bfd_header (abfd);
5705 if (dump_private_headers)
5706 dump_bfd_private_header (abfd);
5707 if (dump_private_options != NULL)
5708 dump_target_specific (abfd);
5709 if (! dump_debugging_tags && ! suppress_bfd_header)
5710 putchar ('\n');
5713 if (dump_symtab
5714 || dump_reloc_info
5715 || disassemble
5716 || dump_debugging
5717 || dump_dwarf_section_info)
5719 syms = slurp_symtab (abfd);
5721 /* If following links, load any symbol tables from the linked files as well. */
5722 if (do_follow_links && is_mainfile)
5724 separate_info * i;
5726 for (i = first_separate_info; i != NULL; i = i->next)
5728 asymbol ** extra_syms;
5729 long old_symcount = symcount;
5731 extra_syms = slurp_symtab (i->handle);
5733 if (extra_syms)
5735 if (old_symcount == 0)
5737 syms = extra_syms;
5739 else
5741 syms = xrealloc (syms, ((symcount + old_symcount + 1)
5742 * sizeof (asymbol *)));
5743 memcpy (syms + old_symcount,
5744 extra_syms,
5745 (symcount + 1) * sizeof (asymbol *));
5749 symcount += old_symcount;
5754 if (is_mainfile || process_links)
5756 if (dump_section_headers)
5757 dump_headers (abfd);
5759 if (dump_dynamic_symtab || dump_dynamic_reloc_info
5760 || (disassemble && bfd_get_dynamic_symtab_upper_bound (abfd) > 0))
5761 dynsyms = slurp_dynamic_symtab (abfd);
5763 if (disassemble)
5765 synthcount = bfd_get_synthetic_symtab (abfd, symcount, syms,
5766 dynsymcount, dynsyms,
5767 &synthsyms);
5768 if (synthcount < 0)
5769 synthcount = 0;
5772 if (dump_symtab)
5773 dump_symbols (abfd, false);
5774 if (dump_dynamic_symtab)
5775 dump_symbols (abfd, true);
5777 if (dump_dwarf_section_info)
5778 dump_dwarf (abfd, is_mainfile);
5779 if (is_mainfile || process_links)
5781 if (dump_ctf_section_info)
5782 dump_ctf (abfd, dump_ctf_section_name, dump_ctf_parent_name,
5783 dump_ctf_parent_section_name);
5784 if (dump_sframe_section_info)
5785 dump_section_sframe (abfd, dump_sframe_section_name);
5786 if (dump_stab_section_info)
5787 dump_stabs (abfd);
5788 if (dump_reloc_info && ! disassemble)
5789 dump_relocs (abfd);
5790 if (dump_dynamic_reloc_info && ! disassemble)
5791 dump_dynamic_relocs (abfd);
5792 if (dump_section_contents)
5793 dump_data (abfd);
5794 if (disassemble)
5795 disassemble_data (abfd);
5798 if (dump_debugging)
5800 void *dhandle;
5802 dhandle = read_debugging_info (abfd, syms, symcount, true);
5803 if (dhandle != NULL)
5805 if (!print_debugging_info (stdout, dhandle, abfd, syms,
5806 bfd_demangle,
5807 dump_debugging_tags != 0))
5809 non_fatal (_("%s: printing debugging information failed"),
5810 bfd_get_filename (abfd));
5811 exit_status = 1;
5814 /* PR 6483: If there was no STABS debug info in the file, try
5815 DWARF instead. */
5816 else if (! dump_dwarf_section_info)
5818 dwarf_select_sections_all ();
5819 dump_dwarf (abfd, is_mainfile);
5823 if (syms)
5825 free (syms);
5826 syms = NULL;
5829 if (dynsyms)
5831 free (dynsyms);
5832 dynsyms = NULL;
5835 if (synthsyms)
5837 free (synthsyms);
5838 synthsyms = NULL;
5841 symcount = 0;
5842 dynsymcount = 0;
5843 synthcount = 0;
5845 if (is_mainfile)
5846 free_debug_memory ();
5849 static void
5850 display_object_bfd (bfd *abfd)
5852 char **matching;
5854 if (bfd_check_format_matches (abfd, bfd_object, &matching))
5856 dump_bfd (abfd, true);
5857 return;
5860 if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
5862 my_bfd_nonfatal (bfd_get_filename (abfd));
5863 list_matching_formats (matching);
5864 return;
5867 if (bfd_get_error () != bfd_error_file_not_recognized)
5869 my_bfd_nonfatal (bfd_get_filename (abfd));
5870 return;
5873 if (bfd_check_format_matches (abfd, bfd_core, &matching))
5875 dump_bfd (abfd, true);
5876 return;
5879 my_bfd_nonfatal (bfd_get_filename (abfd));
5881 if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
5882 list_matching_formats (matching);
5885 static void
5886 display_any_bfd (bfd *file, int level)
5888 /* Decompress sections unless dumping the section contents. */
5889 if (!dump_section_contents || decompressed_dumps)
5890 file->flags |= BFD_DECOMPRESS;
5892 /* If the file is an archive, process all of its elements. */
5893 if (bfd_check_format (file, bfd_archive))
5895 bfd *arfile = NULL;
5896 bfd *last_arfile = NULL;
5898 if (level == 0)
5899 printf (_("In archive %s:\n"), sanitize_string (bfd_get_filename (file)));
5900 else if (level > 100)
5902 /* Prevent corrupted files from spinning us into an
5903 infinite loop. 100 is an arbitrary heuristic. */
5904 non_fatal (_("Archive nesting is too deep"));
5905 exit_status = 1;
5906 return;
5908 else
5909 printf (_("In nested archive %s:\n"),
5910 sanitize_string (bfd_get_filename (file)));
5912 for (;;)
5914 bfd_set_error (bfd_error_no_error);
5916 arfile = bfd_openr_next_archived_file (file, arfile);
5917 if (arfile == NULL)
5919 if (bfd_get_error () != bfd_error_no_more_archived_files)
5920 my_bfd_nonfatal (bfd_get_filename (file));
5921 break;
5924 display_any_bfd (arfile, level + 1);
5926 if (last_arfile != NULL)
5928 bfd_close (last_arfile);
5929 /* PR 17512: file: ac585d01. */
5930 if (arfile == last_arfile)
5932 last_arfile = NULL;
5933 break;
5936 last_arfile = arfile;
5939 if (last_arfile != NULL)
5940 bfd_close (last_arfile);
5942 else
5943 display_object_bfd (file);
5946 static void
5947 display_file (char *filename, char *target, bool last_file)
5949 bfd *file;
5951 if (get_file_size (filename) < 1)
5953 exit_status = 1;
5954 return;
5957 file = bfd_openr (filename, target);
5958 if (file == NULL)
5960 my_bfd_nonfatal (filename);
5961 return;
5964 display_any_bfd (file, 0);
5966 /* This is an optimization to improve the speed of objdump, especially when
5967 dumping a file with lots of associated debug informatiom. Calling
5968 bfd_close on such a file can take a non-trivial amount of time as there
5969 are lots of lists to walk and buffers to free. This is only really
5970 necessary however if we are about to load another file and we need the
5971 memory back. Otherwise, if we are about to exit, then we can save (a lot
5972 of) time by only doing a quick close, and allowing the OS to reclaim the
5973 memory for us. */
5974 if (! last_file)
5975 bfd_close (file);
5976 else
5977 bfd_close_all_done (file);
5981 main (int argc, char **argv)
5983 int c;
5984 char *target = default_target;
5985 bool seenflag = false;
5987 #ifdef HAVE_LC_MESSAGES
5988 setlocale (LC_MESSAGES, "");
5989 #endif
5990 setlocale (LC_CTYPE, "");
5992 bindtextdomain (PACKAGE, LOCALEDIR);
5993 textdomain (PACKAGE);
5995 program_name = *argv;
5996 xmalloc_set_program_name (program_name);
5997 bfd_set_error_program_name (program_name);
5999 expandargv (&argc, &argv);
6001 if (bfd_init () != BFD_INIT_MAGIC)
6002 fatal (_("fatal error: libbfd ABI mismatch"));
6003 set_default_bfd_target ();
6005 while ((c = getopt_long (argc, argv,
6006 "CDE:FGHI:LM:P:RSTU:VW::Zab:defghij:lm:prstvwxz",
6007 long_options, (int *) 0))
6008 != EOF)
6010 switch (c)
6012 case 0:
6013 break; /* We've been given a long option. */
6014 case 'm':
6015 machine = optarg;
6016 break;
6017 case 'Z':
6018 decompressed_dumps = true;
6019 break;
6020 case 'M':
6022 char *options;
6023 if (disassembler_options)
6024 /* Ignore potential memory leak for now. */
6025 options = concat (disassembler_options, ",",
6026 optarg, (const char *) NULL);
6027 else
6028 options = optarg;
6029 disassembler_options = remove_whitespace_and_extra_commas (options);
6031 break;
6032 case 'j':
6033 add_only (optarg);
6034 break;
6035 case 'F':
6036 display_file_offsets = true;
6037 break;
6038 case 'l':
6039 with_line_numbers = true;
6040 break;
6041 case 'b':
6042 target = optarg;
6043 break;
6044 case 'C':
6045 do_demangle = true;
6046 if (optarg != NULL)
6048 enum demangling_styles style;
6050 style = cplus_demangle_name_to_style (optarg);
6051 if (style == unknown_demangling)
6052 fatal (_("unknown demangling style `%s'"),
6053 optarg);
6055 cplus_demangle_set_style (style);
6057 break;
6058 case OPTION_RECURSE_LIMIT:
6059 demangle_flags &= ~ DMGL_NO_RECURSE_LIMIT;
6060 break;
6061 case OPTION_NO_RECURSE_LIMIT:
6062 demangle_flags |= DMGL_NO_RECURSE_LIMIT;
6063 break;
6064 case 'w':
6065 do_wide = wide_output = true;
6066 break;
6067 case OPTION_ADJUST_VMA:
6068 adjust_section_vma = parse_vma (optarg, "--adjust-vma");
6069 break;
6070 case OPTION_START_ADDRESS:
6071 start_address = parse_vma (optarg, "--start-address");
6072 if ((stop_address != (bfd_vma) -1) && stop_address <= start_address)
6073 fatal (_("error: the start address should be before the end address"));
6074 break;
6075 case OPTION_STOP_ADDRESS:
6076 stop_address = parse_vma (optarg, "--stop-address");
6077 if ((start_address != (bfd_vma) -1) && stop_address <= start_address)
6078 fatal (_("error: the stop address should be after the start address"));
6079 break;
6080 case OPTION_PREFIX:
6081 prefix = optarg;
6082 prefix_length = strlen (prefix);
6083 /* Remove an unnecessary trailing '/' */
6084 while (IS_DIR_SEPARATOR (prefix[prefix_length - 1]))
6085 prefix_length--;
6086 break;
6087 case OPTION_PREFIX_STRIP:
6088 prefix_strip = atoi (optarg);
6089 if (prefix_strip < 0)
6090 fatal (_("error: prefix strip must be non-negative"));
6091 break;
6092 case OPTION_INSN_WIDTH:
6093 insn_width = strtoul (optarg, NULL, 0);
6094 if (insn_width <= 0)
6095 fatal (_("error: instruction width must be positive"));
6096 break;
6097 case OPTION_INLINES:
6098 unwind_inlines = true;
6099 break;
6100 case OPTION_VISUALIZE_JUMPS:
6101 visualize_jumps = true;
6102 color_output = false;
6103 extended_color_output = false;
6104 if (optarg != NULL)
6106 if (streq (optarg, "color"))
6107 color_output = true;
6108 else if (streq (optarg, "extended-color"))
6110 color_output = true;
6111 extended_color_output = true;
6113 else if (streq (optarg, "off"))
6114 visualize_jumps = false;
6115 else
6117 non_fatal (_("unrecognized argument to --visualize-option"));
6118 usage (stderr, 1);
6121 break;
6122 case OPTION_DISASSEMBLER_COLOR:
6123 if (streq (optarg, "off"))
6124 disassembler_color = off;
6125 else if (streq (optarg, "terminal"))
6126 disassembler_color = on_if_terminal_output;
6127 else if (streq (optarg, "color")
6128 || streq (optarg, "colour")
6129 || streq (optarg, "on"))
6130 disassembler_color = on;
6131 else if (streq (optarg, "extended")
6132 || streq (optarg, "extended-color")
6133 || streq (optarg, "extended-colour"))
6134 disassembler_color = extended;
6135 else
6137 non_fatal (_("unrecognized argument to --disassembler-color"));
6138 usage (stderr, 1);
6140 break;
6141 case 'E':
6142 if (strcmp (optarg, "B") == 0)
6143 endian = BFD_ENDIAN_BIG;
6144 else if (strcmp (optarg, "L") == 0)
6145 endian = BFD_ENDIAN_LITTLE;
6146 else
6148 non_fatal (_("unrecognized -E option"));
6149 usage (stderr, 1);
6151 break;
6152 case OPTION_ENDIAN:
6153 if (strncmp (optarg, "big", strlen (optarg)) == 0)
6154 endian = BFD_ENDIAN_BIG;
6155 else if (strncmp (optarg, "little", strlen (optarg)) == 0)
6156 endian = BFD_ENDIAN_LITTLE;
6157 else
6159 non_fatal (_("unrecognized --endian type `%s'"), optarg);
6160 usage (stderr, 1);
6162 break;
6164 case 'f':
6165 dump_file_header = true;
6166 seenflag = true;
6167 break;
6168 case 'i':
6169 formats_info = true;
6170 seenflag = true;
6171 break;
6172 case 'I':
6173 add_include_path (optarg);
6174 break;
6175 case 'p':
6176 dump_private_headers = true;
6177 seenflag = true;
6178 break;
6179 case 'P':
6180 dump_private_options = optarg;
6181 seenflag = true;
6182 break;
6183 case 'x':
6184 dump_private_headers = true;
6185 dump_symtab = true;
6186 dump_reloc_info = true;
6187 dump_file_header = true;
6188 dump_ar_hdrs = true;
6189 dump_section_headers = true;
6190 seenflag = true;
6191 break;
6192 case 't':
6193 dump_symtab = true;
6194 seenflag = true;
6195 break;
6196 case 'T':
6197 dump_dynamic_symtab = true;
6198 seenflag = true;
6199 break;
6200 case 'd':
6201 disassemble = true;
6202 seenflag = true;
6203 disasm_sym = optarg;
6204 break;
6205 case 'z':
6206 disassemble_zeroes = true;
6207 break;
6208 case 'D':
6209 disassemble = true;
6210 disassemble_all = true;
6211 seenflag = true;
6212 break;
6213 case 'S':
6214 disassemble = true;
6215 with_source_code = true;
6216 seenflag = true;
6217 break;
6218 case OPTION_SOURCE_COMMENT:
6219 disassemble = true;
6220 with_source_code = true;
6221 seenflag = true;
6222 if (optarg)
6223 source_comment = xstrdup (sanitize_string (optarg));
6224 else
6225 source_comment = xstrdup ("# ");
6226 break;
6227 case 'g':
6228 dump_debugging = 1;
6229 seenflag = true;
6230 break;
6231 case 'e':
6232 dump_debugging = 1;
6233 dump_debugging_tags = 1;
6234 do_demangle = true;
6235 seenflag = true;
6236 break;
6237 case 'L':
6238 process_links = true;
6239 do_follow_links = true;
6240 break;
6241 case 'W':
6242 seenflag = true;
6243 if (optarg)
6245 if (dwarf_select_sections_by_letters (optarg))
6246 dump_dwarf_section_info = true;
6248 else
6250 dump_dwarf_section_info = true;
6251 dwarf_select_sections_all ();
6253 break;
6254 case OPTION_DWARF:
6255 seenflag = true;
6256 if (optarg)
6258 if (dwarf_select_sections_by_names (optarg))
6259 dump_dwarf_section_info = true;
6261 else
6263 dwarf_select_sections_all ();
6264 dump_dwarf_section_info = true;
6266 break;
6267 case OPTION_DWARF_DEPTH:
6269 char *cp;
6270 dwarf_cutoff_level = strtoul (optarg, & cp, 0);
6272 break;
6273 case OPTION_DWARF_START:
6275 char *cp;
6276 dwarf_start_die = strtoul (optarg, & cp, 0);
6277 suppress_bfd_header = 1;
6279 break;
6280 case OPTION_DWARF_CHECK:
6281 dwarf_check = true;
6282 break;
6283 #ifdef ENABLE_LIBCTF
6284 case OPTION_CTF:
6285 dump_ctf_section_info = true;
6286 if (optarg)
6287 dump_ctf_section_name = xstrdup (optarg);
6288 seenflag = true;
6289 break;
6290 case OPTION_CTF_PARENT:
6291 dump_ctf_parent_name = xstrdup (optarg);
6292 break;
6293 case OPTION_CTF_PARENT_SECTION:
6294 dump_ctf_parent_section_name = xstrdup (optarg);
6295 break;
6296 #endif
6297 case OPTION_SFRAME:
6298 dump_sframe_section_info = true;
6299 if (optarg)
6300 dump_sframe_section_name = xstrdup (optarg);
6301 seenflag = true;
6302 break;
6303 case 'G':
6304 dump_stab_section_info = true;
6305 seenflag = true;
6306 break;
6307 case 's':
6308 dump_section_contents = true;
6309 seenflag = true;
6310 break;
6311 case 'r':
6312 dump_reloc_info = true;
6313 seenflag = true;
6314 break;
6315 case 'R':
6316 dump_dynamic_reloc_info = true;
6317 seenflag = true;
6318 break;
6319 case 'a':
6320 dump_ar_hdrs = true;
6321 seenflag = true;
6322 break;
6323 case 'h':
6324 dump_section_headers = true;
6325 seenflag = true;
6326 break;
6327 case 'v':
6328 case 'V':
6329 show_version = true;
6330 seenflag = true;
6331 break;
6333 case 'U':
6334 if (streq (optarg, "default") || streq (optarg, "d"))
6335 unicode_display = unicode_default;
6336 else if (streq (optarg, "locale") || streq (optarg, "l"))
6337 unicode_display = unicode_locale;
6338 else if (streq (optarg, "escape") || streq (optarg, "e"))
6339 unicode_display = unicode_escape;
6340 else if (streq (optarg, "invalid") || streq (optarg, "i"))
6341 unicode_display = unicode_invalid;
6342 else if (streq (optarg, "hex") || streq (optarg, "x"))
6343 unicode_display = unicode_hex;
6344 else if (streq (optarg, "highlight") || streq (optarg, "h"))
6345 unicode_display = unicode_highlight;
6346 else
6347 fatal (_("invalid argument to -U/--unicode: %s"), optarg);
6348 break;
6350 case 'H':
6351 usage (stdout, 0);
6352 /* No need to set seenflag or to break - usage() does not return. */
6353 default:
6354 usage (stderr, 1);
6358 if (disassembler_color == on_if_terminal_output)
6359 disassembler_color = isatty (1) ? on : off;
6361 if (show_version)
6362 print_version ("objdump");
6364 if (!seenflag)
6365 usage (stderr, 2);
6367 dump_any_debugging = (dump_debugging
6368 || dump_dwarf_section_info
6369 || process_links
6370 || with_source_code);
6372 if (formats_info)
6373 exit_status = display_info ();
6374 else
6376 if (optind == argc)
6377 display_file ("a.out", target, true);
6378 else
6379 for (; optind < argc;)
6381 display_file (argv[optind], target, optind == argc - 1);
6382 optind++;
6386 free_only_list ();
6387 free (dump_ctf_section_name);
6388 free (dump_ctf_parent_name);
6389 free ((void *) source_comment);
6390 free (dump_ctf_parent_section_name);
6392 return exit_status;