aarch64: Add an aarch64_nat_target mixin class.
[binutils-gdb.git] / binutils / objdump.c
1 /* objdump.c -- dump information about an object file.
2 Copyright (C) 1990-2022 Free Software Foundation, Inc.
3
4 This file is part of GNU Binutils.
5
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.
10
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.
15
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. */
20
21
22 /* Objdump overview.
23
24 Objdump displays information about one or more object files, either on
25 their own, or inside libraries. It is commonly used as a disassembler,
26 but it can also display information about file headers, symbol tables,
27 relocations, debugging directives and more.
28
29 The flow of execution is as follows:
30
31 1. Command line arguments are checked for control switches and the
32 information to be displayed is selected.
33
34 2. Any remaining arguments are assumed to be object files, and they are
35 processed in order by display_bfd(). If the file is an archive each
36 of its elements is processed in turn.
37
38 3. The file's target architecture and binary file format are determined
39 by bfd_check_format(). If they are recognised, then dump_bfd() is
40 called.
41
42 4. dump_bfd() in turn calls separate functions to display the requested
43 item(s) of information(s). For example disassemble_data() is called if
44 a disassembly has been requested.
45
46 When disassembling the code loops through blocks of instructions bounded
47 by symbols, calling disassemble_bytes() on each block. The actual
48 disassembling is done by the libopcodes library, via a function pointer
49 supplied by the disassembler() function. */
50
51 #include "sysdep.h"
52 #include "bfd.h"
53 #include "elf-bfd.h"
54 #include "coff-bfd.h"
55 #include "progress.h"
56 #include "bucomm.h"
57 #include "elfcomm.h"
58 #include "demanguse.h"
59 #include "dwarf.h"
60 #include "ctf-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"
70
71 #ifdef HAVE_MMAP
72 #include <sys/mman.h>
73 #endif
74
75 /* Internal headers for the ELF .stab-dump code - sorry. */
76 #define BYTES_IN_WORD 32
77 #include "aout/aout64.h"
78
79 /* Exit status. */
80 static int exit_status = 0;
81
82 static char *default_target = NULL; /* Default at runtime. */
83
84 /* The following variables are set based on arguments passed on the
85 command line. */
86 static int show_version = 0; /* Show the version number. */
87 static int dump_section_contents; /* -s */
88 static int dump_section_headers; /* -h */
89 static bool dump_file_header; /* -f */
90 static int dump_symtab; /* -t */
91 static int dump_dynamic_symtab; /* -T */
92 static int dump_reloc_info; /* -r */
93 static int dump_dynamic_reloc_info; /* -R */
94 static int dump_ar_hdrs; /* -a */
95 static int dump_private_headers; /* -p */
96 static char *dump_private_options; /* -P */
97 static int no_addresses; /* --no-addresses */
98 static int prefix_addresses; /* --prefix-addresses */
99 static int with_line_numbers; /* -l */
100 static bool with_source_code; /* -S */
101 static int show_raw_insn; /* --show-raw-insn */
102 static int dump_dwarf_section_info; /* --dwarf */
103 static int dump_stab_section_info; /* --stabs */
104 static int dump_ctf_section_info; /* --ctf */
105 static char *dump_ctf_section_name;
106 static char *dump_ctf_parent_name; /* --ctf-parent */
107 static int do_demangle; /* -C, --demangle */
108 static bool disassemble; /* -d */
109 static bool disassemble_all; /* -D */
110 static int disassemble_zeroes; /* --disassemble-zeroes */
111 static bool formats_info; /* -i */
112 static int wide_output; /* -w */
113 static int insn_width; /* --insn-width */
114 static bfd_vma start_address = (bfd_vma) -1; /* --start-address */
115 static bfd_vma stop_address = (bfd_vma) -1; /* --stop-address */
116 static int dump_debugging; /* --debugging */
117 static int dump_debugging_tags; /* --debugging-tags */
118 static int suppress_bfd_header;
119 static int dump_special_syms = 0; /* --special-syms */
120 static bfd_vma adjust_section_vma = 0; /* --adjust-vma */
121 static int file_start_context = 0; /* --file-start-context */
122 static bool display_file_offsets; /* -F */
123 static const char *prefix; /* --prefix */
124 static int prefix_strip; /* --prefix-strip */
125 static size_t prefix_length;
126 static bool unwind_inlines; /* --inlines. */
127 static const char * disasm_sym; /* Disassembly start symbol. */
128 static const char * source_comment; /* --source_comment. */
129 static bool visualize_jumps = false; /* --visualize-jumps. */
130 static bool color_output = false; /* --visualize-jumps=color. */
131 static bool extended_color_output = false; /* --visualize-jumps=extended-color. */
132 static int process_links = false; /* --process-links. */
133
134 static int dump_any_debugging;
135 static int demangle_flags = DMGL_ANSI | DMGL_PARAMS;
136
137 /* A structure to record the sections mentioned in -j switches. */
138 struct only
139 {
140 const char *name; /* The name of the section. */
141 bool seen; /* A flag to indicate that the section has been found in one or more input files. */
142 struct only *next; /* Pointer to the next structure in the list. */
143 };
144 /* Pointer to an array of 'only' structures.
145 This pointer is NULL if the -j switch has not been used. */
146 static struct only * only_list = NULL;
147
148 /* Variables for handling include file path table. */
149 static const char **include_paths;
150 static int include_path_count;
151
152 /* Extra info to pass to the section disassembler and address printing
153 function. */
154 struct objdump_disasm_info
155 {
156 bfd *abfd;
157 bool require_sec;
158 disassembler_ftype disassemble_fn;
159 arelent *reloc;
160 const char *symbol;
161 };
162
163 /* Architecture to disassemble for, or default if NULL. */
164 static char *machine = NULL;
165
166 /* Target specific options to the disassembler. */
167 static char *disassembler_options = NULL;
168
169 /* Endianness to disassemble for, or default if BFD_ENDIAN_UNKNOWN. */
170 static enum bfd_endian endian = BFD_ENDIAN_UNKNOWN;
171
172 /* The symbol table. */
173 static asymbol **syms;
174
175 /* Number of symbols in `syms'. */
176 static long symcount = 0;
177
178 /* The sorted symbol table. */
179 static asymbol **sorted_syms;
180
181 /* Number of symbols in `sorted_syms'. */
182 static long sorted_symcount = 0;
183
184 /* The dynamic symbol table. */
185 static asymbol **dynsyms;
186
187 /* The synthetic symbol table. */
188 static asymbol *synthsyms;
189 static long synthcount = 0;
190
191 /* Number of symbols in `dynsyms'. */
192 static long dynsymcount = 0;
193
194 static bfd_byte *stabs;
195 static bfd_size_type stab_size;
196
197 static bfd_byte *strtab;
198 static bfd_size_type stabstr_size;
199
200 /* Handlers for -P/--private. */
201 static const struct objdump_private_desc * const objdump_private_vectors[] =
202 {
203 OBJDUMP_PRIVATE_VECTORS
204 NULL
205 };
206
207 /* The list of detected jumps inside a function. */
208 static struct jump_info *detected_jumps = NULL;
209
210 typedef enum unicode_display_type
211 {
212 unicode_default = 0,
213 unicode_locale,
214 unicode_escape,
215 unicode_hex,
216 unicode_highlight,
217 unicode_invalid
218 } unicode_display_type;
219
220 static unicode_display_type unicode_display = unicode_default;
221 \f
222 static void usage (FILE *, int) ATTRIBUTE_NORETURN;
223 static void
224 usage (FILE *stream, int status)
225 {
226 fprintf (stream, _("Usage: %s <option(s)> <file(s)>\n"), program_name);
227 fprintf (stream, _(" Display information from object <file(s)>.\n"));
228 fprintf (stream, _(" At least one of the following switches must be given:\n"));
229 fprintf (stream, _("\
230 -a, --archive-headers Display archive header information\n"));
231 fprintf (stream, _("\
232 -f, --file-headers Display the contents of the overall file header\n"));
233 fprintf (stream, _("\
234 -p, --private-headers Display object format specific file header contents\n"));
235 fprintf (stream, _("\
236 -P, --private=OPT,OPT... Display object format specific contents\n"));
237 fprintf (stream, _("\
238 -h, --[section-]headers Display the contents of the section headers\n"));
239 fprintf (stream, _("\
240 -x, --all-headers Display the contents of all headers\n"));
241 fprintf (stream, _("\
242 -d, --disassemble Display assembler contents of executable sections\n"));
243 fprintf (stream, _("\
244 -D, --disassemble-all Display assembler contents of all sections\n"));
245 fprintf (stream, _("\
246 --disassemble=<sym> Display assembler contents from <sym>\n"));
247 fprintf (stream, _("\
248 -S, --source Intermix source code with disassembly\n"));
249 fprintf (stream, _("\
250 --source-comment[=<txt>] Prefix lines of source code with <txt>\n"));
251 fprintf (stream, _("\
252 -s, --full-contents Display the full contents of all sections requested\n"));
253 fprintf (stream, _("\
254 -g, --debugging Display debug information in object file\n"));
255 fprintf (stream, _("\
256 -e, --debugging-tags Display debug information using ctags style\n"));
257 fprintf (stream, _("\
258 -G, --stabs Display (in raw form) any STABS info in the file\n"));
259 fprintf (stream, _("\
260 -W, --dwarf[a/=abbrev, A/=addr, r/=aranges, c/=cu_index, L/=decodedline,\n\
261 f/=frames, F/=frames-interp, g/=gdb_index, i/=info, o/=loc,\n\
262 m/=macro, p/=pubnames, t/=pubtypes, R/=Ranges, l/=rawline,\n\
263 s/=str, O/=str-offsets, u/=trace_abbrev, T/=trace_aranges,\n\
264 U/=trace_info]\n\
265 Display the contents of DWARF debug sections\n"));
266 fprintf (stream, _("\
267 -Wk,--dwarf=links Display the contents of sections that link to\n\
268 separate debuginfo files\n"));
269 #if DEFAULT_FOR_FOLLOW_LINKS
270 fprintf (stream, _("\
271 -WK,--dwarf=follow-links\n\
272 Follow links to separate debug info files (default)\n"));
273 fprintf (stream, _("\
274 -WN,--dwarf=no-follow-links\n\
275 Do not follow links to separate debug info files\n"));
276 #else
277 fprintf (stream, _("\
278 -WK,--dwarf=follow-links\n\
279 Follow links to separate debug info files\n"));
280 fprintf (stream, _("\
281 -WN,--dwarf=no-follow-links\n\
282 Do not follow links to separate debug info files\n\
283 (default)\n"));
284 #endif
285 #if HAVE_LIBDEBUGINFOD
286 fprintf (stream, _("\
287 -WD --dwarf=use-debuginfod\n\
288 When following links, also query debuginfod servers (default)\n"));
289 fprintf (stream, _("\
290 -WE --dwarf=do-not-use-debuginfod\n\
291 When following links, do not query debuginfod servers\n"));
292 #endif
293 fprintf (stream, _("\
294 -L, --process-links Display the contents of non-debug sections in\n\
295 separate debuginfo files. (Implies -WK)\n"));
296 #ifdef ENABLE_LIBCTF
297 fprintf (stream, _("\
298 --ctf[=SECTION] Display CTF info from SECTION, (default `.ctf')\n"));
299 #endif
300 fprintf (stream, _("\
301 -t, --syms Display the contents of the symbol table(s)\n"));
302 fprintf (stream, _("\
303 -T, --dynamic-syms Display the contents of the dynamic symbol table\n"));
304 fprintf (stream, _("\
305 -r, --reloc Display the relocation entries in the file\n"));
306 fprintf (stream, _("\
307 -R, --dynamic-reloc Display the dynamic relocation entries in the file\n"));
308 fprintf (stream, _("\
309 @<file> Read options from <file>\n"));
310 fprintf (stream, _("\
311 -v, --version Display this program's version number\n"));
312 fprintf (stream, _("\
313 -i, --info List object formats and architectures supported\n"));
314 fprintf (stream, _("\
315 -H, --help Display this information\n"));
316
317 if (status != 2)
318 {
319 const struct objdump_private_desc * const *desc;
320
321 fprintf (stream, _("\n The following switches are optional:\n"));
322 fprintf (stream, _("\
323 -b, --target=BFDNAME Specify the target object format as BFDNAME\n"));
324 fprintf (stream, _("\
325 -m, --architecture=MACHINE Specify the target architecture as MACHINE\n"));
326 fprintf (stream, _("\
327 -j, --section=NAME Only display information for section NAME\n"));
328 fprintf (stream, _("\
329 -M, --disassembler-options=OPT Pass text OPT on to the disassembler\n"));
330 fprintf (stream, _("\
331 -EB --endian=big Assume big endian format when disassembling\n"));
332 fprintf (stream, _("\
333 -EL --endian=little Assume little endian format when disassembling\n"));
334 fprintf (stream, _("\
335 --file-start-context Include context from start of file (with -S)\n"));
336 fprintf (stream, _("\
337 -I, --include=DIR Add DIR to search list for source files\n"));
338 fprintf (stream, _("\
339 -l, --line-numbers Include line numbers and filenames in output\n"));
340 fprintf (stream, _("\
341 -F, --file-offsets Include file offsets when displaying information\n"));
342 fprintf (stream, _("\
343 -C, --demangle[=STYLE] Decode mangled/processed symbol names\n"));
344 display_demangler_styles (stream, _("\
345 STYLE can be "));
346 fprintf (stream, _("\
347 --recurse-limit Enable a limit on recursion whilst demangling\n\
348 (default)\n"));
349 fprintf (stream, _("\
350 --no-recurse-limit Disable a limit on recursion whilst demangling\n"));
351 fprintf (stream, _("\
352 -w, --wide Format output for more than 80 columns\n"));
353 fprintf (stream, _("\
354 -U[d|l|i|x|e|h] Controls the display of UTF-8 unicode characters\n\
355 --unicode=[default|locale|invalid|hex|escape|highlight]\n"));
356 fprintf (stream, _("\
357 -z, --disassemble-zeroes Do not skip blocks of zeroes when disassembling\n"));
358 fprintf (stream, _("\
359 --start-address=ADDR Only process data whose address is >= ADDR\n"));
360 fprintf (stream, _("\
361 --stop-address=ADDR Only process data whose address is < ADDR\n"));
362 fprintf (stream, _("\
363 --no-addresses Do not print address alongside disassembly\n"));
364 fprintf (stream, _("\
365 --prefix-addresses Print complete address alongside disassembly\n"));
366 fprintf (stream, _("\
367 --[no-]show-raw-insn Display hex alongside symbolic disassembly\n"));
368 fprintf (stream, _("\
369 --insn-width=WIDTH Display WIDTH bytes on a single line for -d\n"));
370 fprintf (stream, _("\
371 --adjust-vma=OFFSET Add OFFSET to all displayed section addresses\n"));
372 fprintf (stream, _("\
373 --special-syms Include special symbols in symbol dumps\n"));
374 fprintf (stream, _("\
375 --inlines Print all inlines for source line (with -l)\n"));
376 fprintf (stream, _("\
377 --prefix=PREFIX Add PREFIX to absolute paths for -S\n"));
378 fprintf (stream, _("\
379 --prefix-strip=LEVEL Strip initial directory names for -S\n"));
380 fprintf (stream, _("\
381 --dwarf-depth=N Do not display DIEs at depth N or greater\n"));
382 fprintf (stream, _("\
383 --dwarf-start=N Display DIEs starting at offset N\n"));
384 fprintf (stream, _("\
385 --dwarf-check Make additional dwarf consistency checks.\n"));
386 #ifdef ENABLE_LIBCTF
387 fprintf (stream, _("\
388 --ctf-parent=NAME Use CTF archive member NAME as the CTF parent\n"));
389 #endif
390 fprintf (stream, _("\
391 --visualize-jumps Visualize jumps by drawing ASCII art lines\n"));
392 fprintf (stream, _("\
393 --visualize-jumps=color Use colors in the ASCII art\n"));
394 fprintf (stream, _("\
395 --visualize-jumps=extended-color\n\
396 Use extended 8-bit color codes\n"));
397 fprintf (stream, _("\
398 --visualize-jumps=off Disable jump visualization\n\n"));
399
400 list_supported_targets (program_name, stream);
401 list_supported_architectures (program_name, stream);
402
403 disassembler_usage (stream);
404
405 if (objdump_private_vectors[0] != NULL)
406 {
407 fprintf (stream,
408 _("\nOptions supported for -P/--private switch:\n"));
409 for (desc = objdump_private_vectors; *desc != NULL; desc++)
410 (*desc)->help (stream);
411 }
412 }
413 if (REPORT_BUGS_TO[0] && status == 0)
414 fprintf (stream, _("Report bugs to %s.\n"), REPORT_BUGS_TO);
415 exit (status);
416 }
417
418 /* 150 isn't special; it's just an arbitrary non-ASCII char value. */
419 enum option_values
420 {
421 OPTION_ENDIAN=150,
422 OPTION_START_ADDRESS,
423 OPTION_STOP_ADDRESS,
424 OPTION_DWARF,
425 OPTION_PREFIX,
426 OPTION_PREFIX_STRIP,
427 OPTION_INSN_WIDTH,
428 OPTION_ADJUST_VMA,
429 OPTION_DWARF_DEPTH,
430 OPTION_DWARF_CHECK,
431 OPTION_DWARF_START,
432 OPTION_RECURSE_LIMIT,
433 OPTION_NO_RECURSE_LIMIT,
434 OPTION_INLINES,
435 OPTION_SOURCE_COMMENT,
436 #ifdef ENABLE_LIBCTF
437 OPTION_CTF,
438 OPTION_CTF_PARENT,
439 #endif
440 OPTION_VISUALIZE_JUMPS
441 };
442
443 static struct option long_options[]=
444 {
445 {"adjust-vma", required_argument, NULL, OPTION_ADJUST_VMA},
446 {"all-headers", no_argument, NULL, 'x'},
447 {"architecture", required_argument, NULL, 'm'},
448 {"archive-headers", no_argument, NULL, 'a'},
449 #ifdef ENABLE_LIBCTF
450 {"ctf", optional_argument, NULL, OPTION_CTF},
451 {"ctf-parent", required_argument, NULL, OPTION_CTF_PARENT},
452 #endif
453 {"debugging", no_argument, NULL, 'g'},
454 {"debugging-tags", no_argument, NULL, 'e'},
455 {"demangle", optional_argument, NULL, 'C'},
456 {"disassemble", optional_argument, NULL, 'd'},
457 {"disassemble-all", no_argument, NULL, 'D'},
458 {"disassemble-zeroes", no_argument, NULL, 'z'},
459 {"disassembler-options", required_argument, NULL, 'M'},
460 {"dwarf", optional_argument, NULL, OPTION_DWARF},
461 {"dwarf-check", no_argument, 0, OPTION_DWARF_CHECK},
462 {"dwarf-depth", required_argument, 0, OPTION_DWARF_DEPTH},
463 {"dwarf-start", required_argument, 0, OPTION_DWARF_START},
464 {"dynamic-reloc", no_argument, NULL, 'R'},
465 {"dynamic-syms", no_argument, NULL, 'T'},
466 {"endian", required_argument, NULL, OPTION_ENDIAN},
467 {"file-headers", no_argument, NULL, 'f'},
468 {"file-offsets", no_argument, NULL, 'F'},
469 {"file-start-context", no_argument, &file_start_context, 1},
470 {"full-contents", no_argument, NULL, 's'},
471 {"headers", no_argument, NULL, 'h'},
472 {"help", no_argument, NULL, 'H'},
473 {"include", required_argument, NULL, 'I'},
474 {"info", no_argument, NULL, 'i'},
475 {"inlines", no_argument, 0, OPTION_INLINES},
476 {"insn-width", required_argument, NULL, OPTION_INSN_WIDTH},
477 {"line-numbers", no_argument, NULL, 'l'},
478 {"no-addresses", no_argument, &no_addresses, 1},
479 {"no-recurse-limit", no_argument, NULL, OPTION_NO_RECURSE_LIMIT},
480 {"no-recursion-limit", no_argument, NULL, OPTION_NO_RECURSE_LIMIT},
481 {"no-show-raw-insn", no_argument, &show_raw_insn, -1},
482 {"prefix", required_argument, NULL, OPTION_PREFIX},
483 {"prefix-addresses", no_argument, &prefix_addresses, 1},
484 {"prefix-strip", required_argument, NULL, OPTION_PREFIX_STRIP},
485 {"private", required_argument, NULL, 'P'},
486 {"private-headers", no_argument, NULL, 'p'},
487 {"process-links", no_argument, &process_links, true},
488 {"recurse-limit", no_argument, NULL, OPTION_RECURSE_LIMIT},
489 {"recursion-limit", no_argument, NULL, OPTION_RECURSE_LIMIT},
490 {"reloc", no_argument, NULL, 'r'},
491 {"section", required_argument, NULL, 'j'},
492 {"section-headers", no_argument, NULL, 'h'},
493 {"show-raw-insn", no_argument, &show_raw_insn, 1},
494 {"source", no_argument, NULL, 'S'},
495 {"source-comment", optional_argument, NULL, OPTION_SOURCE_COMMENT},
496 {"special-syms", no_argument, &dump_special_syms, 1},
497 {"stabs", no_argument, NULL, 'G'},
498 {"start-address", required_argument, NULL, OPTION_START_ADDRESS},
499 {"stop-address", required_argument, NULL, OPTION_STOP_ADDRESS},
500 {"syms", no_argument, NULL, 't'},
501 {"target", required_argument, NULL, 'b'},
502 {"unicode", required_argument, NULL, 'U'},
503 {"version", no_argument, NULL, 'V'},
504 {"visualize-jumps", optional_argument, 0, OPTION_VISUALIZE_JUMPS},
505 {"wide", no_argument, NULL, 'w'},
506 {NULL, no_argument, NULL, 0}
507 };
508 \f
509 static void
510 nonfatal (const char *msg)
511 {
512 bfd_nonfatal (msg);
513 exit_status = 1;
514 }
515
516 /* Convert a potential UTF-8 encoded sequence in IN into characters in OUT.
517 The conversion format is controlled by the unicode_display variable.
518 Returns the number of characters added to OUT.
519 Returns the number of bytes consumed from IN in CONSUMED.
520 Always consumes at least one byte and displays at least one character. */
521
522 static unsigned int
523 display_utf8 (const unsigned char * in, char * out, unsigned int * consumed)
524 {
525 char * orig_out = out;
526 unsigned int nchars = 0;
527 unsigned int j;
528
529 if (unicode_display == unicode_default)
530 goto invalid;
531
532 if (in[0] < 0xc0)
533 goto invalid;
534
535 if ((in[1] & 0xc0) != 0x80)
536 goto invalid;
537
538 if ((in[0] & 0x20) == 0)
539 {
540 nchars = 2;
541 goto valid;
542 }
543
544 if ((in[2] & 0xc0) != 0x80)
545 goto invalid;
546
547 if ((in[0] & 0x10) == 0)
548 {
549 nchars = 3;
550 goto valid;
551 }
552
553 if ((in[3] & 0xc0) != 0x80)
554 goto invalid;
555
556 nchars = 4;
557
558 valid:
559 switch (unicode_display)
560 {
561 case unicode_locale:
562 /* Copy the bytes into the output buffer as is. */
563 memcpy (out, in, nchars);
564 out += nchars;
565 break;
566
567 case unicode_invalid:
568 case unicode_hex:
569 out += sprintf (out, "%c", unicode_display == unicode_hex ? '<' : '{');
570 out += sprintf (out, "0x");
571 for (j = 0; j < nchars; j++)
572 out += sprintf (out, "%02x", in [j]);
573 out += sprintf (out, "%c", unicode_display == unicode_hex ? '>' : '}');
574 break;
575
576 case unicode_highlight:
577 if (isatty (1))
578 out += sprintf (out, "\x1B[31;47m"); /* Red. */
579 /* Fall through. */
580 case unicode_escape:
581 switch (nchars)
582 {
583 case 2:
584 out += sprintf (out, "\\u%02x%02x",
585 ((in[0] & 0x1c) >> 2),
586 ((in[0] & 0x03) << 6) | (in[1] & 0x3f));
587 break;
588
589 case 3:
590 out += sprintf (out, "\\u%02x%02x",
591 ((in[0] & 0x0f) << 4) | ((in[1] & 0x3c) >> 2),
592 ((in[1] & 0x03) << 6) | ((in[2] & 0x3f)));
593 break;
594
595 case 4:
596 out += sprintf (out, "\\u%02x%02x%02x",
597 ((in[0] & 0x07) << 6) | ((in[1] & 0x3c) >> 2),
598 ((in[1] & 0x03) << 6) | ((in[2] & 0x3c) >> 2),
599 ((in[2] & 0x03) << 6) | ((in[3] & 0x3f)));
600 break;
601 default:
602 /* URG. */
603 break;
604 }
605
606 if (unicode_display == unicode_highlight && isatty (1))
607 out += sprintf (out, "\033[0m"); /* Default colour. */
608 break;
609
610 default:
611 /* URG */
612 break;
613 }
614
615 * consumed = nchars;
616 return out - orig_out;
617
618 invalid:
619 /* Not a valid UTF-8 sequence. */
620 *out = *in;
621 * consumed = 1;
622 return 1;
623 }
624
625 /* Returns a version of IN with any control characters
626 replaced by escape sequences. Uses a static buffer
627 if necessary.
628
629 If unicode display is enabled, then also handles the
630 conversion of unicode characters. */
631
632 static const char *
633 sanitize_string (const char * in)
634 {
635 static char * buffer = NULL;
636 static size_t buffer_len = 0;
637 const char * original = in;
638 char * out;
639
640 /* Paranoia. */
641 if (in == NULL)
642 return "";
643
644 /* See if any conversion is necessary. In the majority
645 of cases it will not be needed. */
646 do
647 {
648 unsigned char c = *in++;
649
650 if (c == 0)
651 return original;
652
653 if (ISCNTRL (c))
654 break;
655
656 if (unicode_display != unicode_default && c >= 0xc0)
657 break;
658 }
659 while (1);
660
661 /* Copy the input, translating as needed. */
662 in = original;
663 if (buffer_len < (strlen (in) * 9))
664 {
665 free ((void *) buffer);
666 buffer_len = strlen (in) * 9;
667 buffer = xmalloc (buffer_len + 1);
668 }
669
670 out = buffer;
671 do
672 {
673 unsigned char c = *in++;
674
675 if (c == 0)
676 break;
677
678 if (ISCNTRL (c))
679 {
680 *out++ = '^';
681 *out++ = c + 0x40;
682 }
683 else if (unicode_display != unicode_default && c >= 0xc0)
684 {
685 unsigned int num_consumed;
686
687 out += display_utf8 ((const unsigned char *)(in - 1), out, & num_consumed);
688 in += num_consumed - 1;
689 }
690 else
691 *out++ = c;
692 }
693 while (1);
694
695 *out = 0;
696 return buffer;
697 }
698
699 \f
700 /* Returns TRUE if the specified section should be dumped. */
701
702 static bool
703 process_section_p (asection * section)
704 {
705 struct only * only;
706
707 if (only_list == NULL)
708 return true;
709
710 for (only = only_list; only; only = only->next)
711 if (strcmp (only->name, section->name) == 0)
712 {
713 only->seen = true;
714 return true;
715 }
716
717 return false;
718 }
719
720 /* Add an entry to the 'only' list. */
721
722 static void
723 add_only (char * name)
724 {
725 struct only * only;
726
727 /* First check to make sure that we do not
728 already have an entry for this name. */
729 for (only = only_list; only; only = only->next)
730 if (strcmp (only->name, name) == 0)
731 return;
732
733 only = xmalloc (sizeof * only);
734 only->name = name;
735 only->seen = false;
736 only->next = only_list;
737 only_list = only;
738 }
739
740 /* Release the memory used by the 'only' list.
741 PR 11225: Issue a warning message for unseen sections.
742 Only do this if none of the sections were seen. This is mainly to support
743 tools like the GAS testsuite where an object file is dumped with a list of
744 generic section names known to be present in a range of different file
745 formats. */
746
747 static void
748 free_only_list (void)
749 {
750 bool at_least_one_seen = false;
751 struct only * only;
752 struct only * next;
753
754 if (only_list == NULL)
755 return;
756
757 for (only = only_list; only; only = only->next)
758 if (only->seen)
759 {
760 at_least_one_seen = true;
761 break;
762 }
763
764 for (only = only_list; only; only = next)
765 {
766 if (! at_least_one_seen)
767 {
768 non_fatal (_("section '%s' mentioned in a -j option, "
769 "but not found in any input file"),
770 only->name);
771 exit_status = 1;
772 }
773 next = only->next;
774 free (only);
775 }
776 }
777
778 \f
779 static void
780 dump_section_header (bfd *abfd, asection *section, void *data)
781 {
782 char *comma = "";
783 unsigned int opb = bfd_octets_per_byte (abfd, section);
784 int longest_section_name = *((int *) data);
785
786 /* Ignore linker created section. See elfNN_ia64_object_p in
787 bfd/elfxx-ia64.c. */
788 if (section->flags & SEC_LINKER_CREATED)
789 return;
790
791 /* PR 10413: Skip sections that we are ignoring. */
792 if (! process_section_p (section))
793 return;
794
795 printf ("%3d %-*s %08lx ", section->index, longest_section_name,
796 sanitize_string (bfd_section_name (section)),
797 (unsigned long) bfd_section_size (section) / opb);
798 bfd_printf_vma (abfd, bfd_section_vma (section));
799 printf (" ");
800 bfd_printf_vma (abfd, section->lma);
801 printf (" %08lx 2**%u", (unsigned long) section->filepos,
802 bfd_section_alignment (section));
803 if (! wide_output)
804 printf ("\n ");
805 printf (" ");
806
807 #define PF(x, y) \
808 if (section->flags & x) { printf ("%s%s", comma, y); comma = ", "; }
809
810 PF (SEC_HAS_CONTENTS, "CONTENTS");
811 PF (SEC_ALLOC, "ALLOC");
812 PF (SEC_CONSTRUCTOR, "CONSTRUCTOR");
813 PF (SEC_LOAD, "LOAD");
814 PF (SEC_RELOC, "RELOC");
815 PF (SEC_READONLY, "READONLY");
816 PF (SEC_CODE, "CODE");
817 PF (SEC_DATA, "DATA");
818 PF (SEC_ROM, "ROM");
819 PF (SEC_DEBUGGING, "DEBUGGING");
820 PF (SEC_NEVER_LOAD, "NEVER_LOAD");
821 PF (SEC_EXCLUDE, "EXCLUDE");
822 PF (SEC_SORT_ENTRIES, "SORT_ENTRIES");
823 if (bfd_get_arch (abfd) == bfd_arch_tic54x)
824 {
825 PF (SEC_TIC54X_BLOCK, "BLOCK");
826 PF (SEC_TIC54X_CLINK, "CLINK");
827 }
828 PF (SEC_SMALL_DATA, "SMALL_DATA");
829 if (bfd_get_flavour (abfd) == bfd_target_coff_flavour)
830 {
831 PF (SEC_COFF_SHARED, "SHARED");
832 PF (SEC_COFF_NOREAD, "NOREAD");
833 }
834 else if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
835 {
836 PF (SEC_ELF_OCTETS, "OCTETS");
837 PF (SEC_ELF_PURECODE, "PURECODE");
838 }
839 PF (SEC_THREAD_LOCAL, "THREAD_LOCAL");
840 PF (SEC_GROUP, "GROUP");
841 if (bfd_get_arch (abfd) == bfd_arch_mep)
842 {
843 PF (SEC_MEP_VLIW, "VLIW");
844 }
845
846 if ((section->flags & SEC_LINK_ONCE) != 0)
847 {
848 const char *ls;
849 struct coff_comdat_info *comdat;
850
851 switch (section->flags & SEC_LINK_DUPLICATES)
852 {
853 default:
854 abort ();
855 case SEC_LINK_DUPLICATES_DISCARD:
856 ls = "LINK_ONCE_DISCARD";
857 break;
858 case SEC_LINK_DUPLICATES_ONE_ONLY:
859 ls = "LINK_ONCE_ONE_ONLY";
860 break;
861 case SEC_LINK_DUPLICATES_SAME_SIZE:
862 ls = "LINK_ONCE_SAME_SIZE";
863 break;
864 case SEC_LINK_DUPLICATES_SAME_CONTENTS:
865 ls = "LINK_ONCE_SAME_CONTENTS";
866 break;
867 }
868 printf ("%s%s", comma, ls);
869
870 comdat = bfd_coff_get_comdat_section (abfd, section);
871 if (comdat != NULL)
872 printf (" (COMDAT %s %ld)", comdat->name, comdat->symbol);
873
874 comma = ", ";
875 }
876
877 printf ("\n");
878 #undef PF
879 }
880
881 /* Called on each SECTION in ABFD, update the int variable pointed to by
882 DATA which contains the string length of the longest section name. */
883
884 static void
885 find_longest_section_name (bfd *abfd ATTRIBUTE_UNUSED,
886 asection *section, void *data)
887 {
888 int *longest_so_far = (int *) data;
889 const char *name;
890 int len;
891
892 /* Ignore linker created section. */
893 if (section->flags & SEC_LINKER_CREATED)
894 return;
895
896 /* Skip sections that we are ignoring. */
897 if (! process_section_p (section))
898 return;
899
900 name = bfd_section_name (section);
901 len = (int) strlen (name);
902 if (len > *longest_so_far)
903 *longest_so_far = len;
904 }
905
906 static void
907 dump_headers (bfd *abfd)
908 {
909 /* The default width of 13 is just an arbitrary choice. */
910 int max_section_name_length = 13;
911 int bfd_vma_width;
912
913 #ifndef BFD64
914 bfd_vma_width = 10;
915 #else
916 /* With BFD64, non-ELF returns -1 and wants always 64 bit addresses. */
917 if (bfd_get_arch_size (abfd) == 32)
918 bfd_vma_width = 10;
919 else
920 bfd_vma_width = 18;
921 #endif
922
923 printf (_("Sections:\n"));
924
925 if (wide_output)
926 bfd_map_over_sections (abfd, find_longest_section_name,
927 &max_section_name_length);
928
929 printf (_("Idx %-*s Size %-*s%-*sFile off Algn"),
930 max_section_name_length, "Name",
931 bfd_vma_width, "VMA",
932 bfd_vma_width, "LMA");
933
934 if (wide_output)
935 printf (_(" Flags"));
936 printf ("\n");
937
938 bfd_map_over_sections (abfd, dump_section_header,
939 &max_section_name_length);
940 }
941 \f
942 static asymbol **
943 slurp_symtab (bfd *abfd)
944 {
945 asymbol **sy = NULL;
946 long storage;
947
948 if (!(bfd_get_file_flags (abfd) & HAS_SYMS))
949 {
950 symcount = 0;
951 return NULL;
952 }
953
954 storage = bfd_get_symtab_upper_bound (abfd);
955 if (storage < 0)
956 {
957 non_fatal (_("failed to read symbol table from: %s"), bfd_get_filename (abfd));
958 bfd_fatal (_("error message was"));
959 }
960
961 if (storage)
962 {
963 off_t filesize = bfd_get_file_size (abfd);
964
965 /* qv PR 24707. */
966 if (filesize > 0
967 && filesize < storage
968 /* The MMO file format supports its own special compression
969 technique, so its sections can be larger than the file size. */
970 && bfd_get_flavour (abfd) != bfd_target_mmo_flavour)
971 {
972 bfd_nonfatal_message (bfd_get_filename (abfd), abfd, NULL,
973 _("error: symbol table size (%#lx) "
974 "is larger than filesize (%#lx)"),
975 storage, (long) filesize);
976 exit_status = 1;
977 symcount = 0;
978 return NULL;
979 }
980
981 sy = (asymbol **) xmalloc (storage);
982 }
983
984 symcount = bfd_canonicalize_symtab (abfd, sy);
985 if (symcount < 0)
986 bfd_fatal (bfd_get_filename (abfd));
987 return sy;
988 }
989
990 /* Read in the dynamic symbols. */
991
992 static asymbol **
993 slurp_dynamic_symtab (bfd *abfd)
994 {
995 asymbol **sy = NULL;
996 long storage;
997
998 storage = bfd_get_dynamic_symtab_upper_bound (abfd);
999 if (storage < 0)
1000 {
1001 if (!(bfd_get_file_flags (abfd) & DYNAMIC))
1002 {
1003 non_fatal (_("%s: not a dynamic object"), bfd_get_filename (abfd));
1004 exit_status = 1;
1005 dynsymcount = 0;
1006 return NULL;
1007 }
1008
1009 bfd_fatal (bfd_get_filename (abfd));
1010 }
1011
1012 if (storage)
1013 sy = (asymbol **) xmalloc (storage);
1014
1015 dynsymcount = bfd_canonicalize_dynamic_symtab (abfd, sy);
1016 if (dynsymcount < 0)
1017 bfd_fatal (bfd_get_filename (abfd));
1018 return sy;
1019 }
1020
1021 /* Some symbol names are significant and should be kept in the
1022 table of sorted symbol names, even if they are marked as
1023 debugging/section symbols. */
1024
1025 static bool
1026 is_significant_symbol_name (const char * name)
1027 {
1028 return startswith (name, ".plt") || startswith (name, ".got");
1029 }
1030
1031 /* Filter out (in place) symbols that are useless for disassembly.
1032 COUNT is the number of elements in SYMBOLS.
1033 Return the number of useful symbols. */
1034
1035 static long
1036 remove_useless_symbols (asymbol **symbols, long count)
1037 {
1038 asymbol **in_ptr = symbols, **out_ptr = symbols;
1039
1040 while (--count >= 0)
1041 {
1042 asymbol *sym = *in_ptr++;
1043
1044 if (sym->name == NULL || sym->name[0] == '\0')
1045 continue;
1046 if ((sym->flags & (BSF_DEBUGGING | BSF_SECTION_SYM))
1047 && ! is_significant_symbol_name (sym->name))
1048 continue;
1049 if (bfd_is_und_section (sym->section)
1050 || bfd_is_com_section (sym->section))
1051 continue;
1052
1053 *out_ptr++ = sym;
1054 }
1055 return out_ptr - symbols;
1056 }
1057
1058 static const asection *compare_section;
1059
1060 /* Sort symbols into value order. */
1061
1062 static int
1063 compare_symbols (const void *ap, const void *bp)
1064 {
1065 const asymbol *a = * (const asymbol **) ap;
1066 const asymbol *b = * (const asymbol **) bp;
1067 const char *an;
1068 const char *bn;
1069 size_t anl;
1070 size_t bnl;
1071 bool as, af, bs, bf;
1072 flagword aflags;
1073 flagword bflags;
1074
1075 if (bfd_asymbol_value (a) > bfd_asymbol_value (b))
1076 return 1;
1077 else if (bfd_asymbol_value (a) < bfd_asymbol_value (b))
1078 return -1;
1079
1080 /* Prefer symbols from the section currently being disassembled.
1081 Don't sort symbols from other sections by section, since there
1082 isn't much reason to prefer one section over another otherwise.
1083 See sym_ok comment for why we compare by section name. */
1084 as = strcmp (compare_section->name, a->section->name) == 0;
1085 bs = strcmp (compare_section->name, b->section->name) == 0;
1086 if (as && !bs)
1087 return -1;
1088 if (!as && bs)
1089 return 1;
1090
1091 an = bfd_asymbol_name (a);
1092 bn = bfd_asymbol_name (b);
1093 anl = strlen (an);
1094 bnl = strlen (bn);
1095
1096 /* The symbols gnu_compiled and gcc2_compiled convey no real
1097 information, so put them after other symbols with the same value. */
1098 af = (strstr (an, "gnu_compiled") != NULL
1099 || strstr (an, "gcc2_compiled") != NULL);
1100 bf = (strstr (bn, "gnu_compiled") != NULL
1101 || strstr (bn, "gcc2_compiled") != NULL);
1102
1103 if (af && ! bf)
1104 return 1;
1105 if (! af && bf)
1106 return -1;
1107
1108 /* We use a heuristic for the file name, to try to sort it after
1109 more useful symbols. It may not work on non Unix systems, but it
1110 doesn't really matter; the only difference is precisely which
1111 symbol names get printed. */
1112
1113 #define file_symbol(s, sn, snl) \
1114 (((s)->flags & BSF_FILE) != 0 \
1115 || ((snl) > 2 \
1116 && (sn)[(snl) - 2] == '.' \
1117 && ((sn)[(snl) - 1] == 'o' \
1118 || (sn)[(snl) - 1] == 'a')))
1119
1120 af = file_symbol (a, an, anl);
1121 bf = file_symbol (b, bn, bnl);
1122
1123 if (af && ! bf)
1124 return 1;
1125 if (! af && bf)
1126 return -1;
1127
1128 /* Sort function and object symbols before global symbols before
1129 local symbols before section symbols before debugging symbols. */
1130
1131 aflags = a->flags;
1132 bflags = b->flags;
1133
1134 if ((aflags & BSF_DEBUGGING) != (bflags & BSF_DEBUGGING))
1135 {
1136 if ((aflags & BSF_DEBUGGING) != 0)
1137 return 1;
1138 else
1139 return -1;
1140 }
1141 if ((aflags & BSF_SECTION_SYM) != (bflags & BSF_SECTION_SYM))
1142 {
1143 if ((aflags & BSF_SECTION_SYM) != 0)
1144 return 1;
1145 else
1146 return -1;
1147 }
1148 if ((aflags & BSF_FUNCTION) != (bflags & BSF_FUNCTION))
1149 {
1150 if ((aflags & BSF_FUNCTION) != 0)
1151 return -1;
1152 else
1153 return 1;
1154 }
1155 if ((aflags & BSF_OBJECT) != (bflags & BSF_OBJECT))
1156 {
1157 if ((aflags & BSF_OBJECT) != 0)
1158 return -1;
1159 else
1160 return 1;
1161 }
1162 if ((aflags & BSF_LOCAL) != (bflags & BSF_LOCAL))
1163 {
1164 if ((aflags & BSF_LOCAL) != 0)
1165 return 1;
1166 else
1167 return -1;
1168 }
1169 if ((aflags & BSF_GLOBAL) != (bflags & BSF_GLOBAL))
1170 {
1171 if ((aflags & BSF_GLOBAL) != 0)
1172 return -1;
1173 else
1174 return 1;
1175 }
1176
1177 if (bfd_get_flavour (bfd_asymbol_bfd (a)) == bfd_target_elf_flavour
1178 && bfd_get_flavour (bfd_asymbol_bfd (b)) == bfd_target_elf_flavour)
1179 {
1180 bfd_vma asz, bsz;
1181
1182 asz = 0;
1183 if ((a->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) == 0)
1184 asz = ((elf_symbol_type *) a)->internal_elf_sym.st_size;
1185 bsz = 0;
1186 if ((b->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) == 0)
1187 bsz = ((elf_symbol_type *) b)->internal_elf_sym.st_size;
1188 if (asz != bsz)
1189 return asz > bsz ? -1 : 1;
1190 }
1191
1192 /* Symbols that start with '.' might be section names, so sort them
1193 after symbols that don't start with '.'. */
1194 if (an[0] == '.' && bn[0] != '.')
1195 return 1;
1196 if (an[0] != '.' && bn[0] == '.')
1197 return -1;
1198
1199 /* Finally, if we can't distinguish them in any other way, try to
1200 get consistent results by sorting the symbols by name. */
1201 return strcmp (an, bn);
1202 }
1203
1204 /* Sort relocs into address order. */
1205
1206 static int
1207 compare_relocs (const void *ap, const void *bp)
1208 {
1209 const arelent *a = * (const arelent **) ap;
1210 const arelent *b = * (const arelent **) bp;
1211
1212 if (a->address > b->address)
1213 return 1;
1214 else if (a->address < b->address)
1215 return -1;
1216
1217 /* So that associated relocations tied to the same address show up
1218 in the correct order, we don't do any further sorting. */
1219 if (a > b)
1220 return 1;
1221 else if (a < b)
1222 return -1;
1223 else
1224 return 0;
1225 }
1226
1227 /* Print an address (VMA) to the output stream in INFO.
1228 If SKIP_ZEROES is TRUE, omit leading zeroes. */
1229
1230 static void
1231 objdump_print_value (bfd_vma vma, struct disassemble_info *inf,
1232 bool skip_zeroes)
1233 {
1234 char buf[30];
1235 char *p;
1236 struct objdump_disasm_info *aux;
1237
1238 aux = (struct objdump_disasm_info *) inf->application_data;
1239 bfd_sprintf_vma (aux->abfd, buf, vma);
1240 if (! skip_zeroes)
1241 p = buf;
1242 else
1243 {
1244 for (p = buf; *p == '0'; ++p)
1245 ;
1246 if (*p == '\0')
1247 --p;
1248 }
1249 (*inf->fprintf_func) (inf->stream, "%s", p);
1250 }
1251
1252 /* Print the name of a symbol. */
1253
1254 static void
1255 objdump_print_symname (bfd *abfd, struct disassemble_info *inf,
1256 asymbol *sym)
1257 {
1258 char *alloc;
1259 const char *name, *version_string = NULL;
1260 bool hidden = false;
1261
1262 alloc = NULL;
1263 name = bfd_asymbol_name (sym);
1264 if (do_demangle && name[0] != '\0')
1265 {
1266 /* Demangle the name. */
1267 alloc = bfd_demangle (abfd, name, demangle_flags);
1268 if (alloc != NULL)
1269 name = alloc;
1270 }
1271
1272 if ((sym->flags & (BSF_SECTION_SYM | BSF_SYNTHETIC)) == 0)
1273 version_string = bfd_get_symbol_version_string (abfd, sym, true,
1274 &hidden);
1275
1276 if (bfd_is_und_section (bfd_asymbol_section (sym)))
1277 hidden = true;
1278
1279 name = sanitize_string (name);
1280
1281 if (inf != NULL)
1282 {
1283 (*inf->fprintf_func) (inf->stream, "%s", name);
1284 if (version_string && *version_string != '\0')
1285 (*inf->fprintf_func) (inf->stream, hidden ? "@%s" : "@@%s",
1286 version_string);
1287 }
1288 else
1289 {
1290 printf ("%s", name);
1291 if (version_string && *version_string != '\0')
1292 printf (hidden ? "@%s" : "@@%s", version_string);
1293 }
1294
1295 if (alloc != NULL)
1296 free (alloc);
1297 }
1298
1299 static inline bool
1300 sym_ok (bool want_section,
1301 bfd *abfd ATTRIBUTE_UNUSED,
1302 long place,
1303 asection *sec,
1304 struct disassemble_info *inf)
1305 {
1306 if (want_section)
1307 {
1308 /* NB: An object file can have different sections with the same
1309 section name. Compare compare section pointers if they have
1310 the same owner. */
1311 if (sorted_syms[place]->section->owner == sec->owner
1312 && sorted_syms[place]->section != sec)
1313 return false;
1314
1315 /* Note - we cannot just compare section pointers because they could
1316 be different, but the same... Ie the symbol that we are trying to
1317 find could have come from a separate debug info file. Under such
1318 circumstances the symbol will be associated with a section in the
1319 debug info file, whilst the section we want is in a normal file.
1320 So the section pointers will be different, but the section names
1321 will be the same. */
1322 if (strcmp (bfd_section_name (sorted_syms[place]->section),
1323 bfd_section_name (sec)) != 0)
1324 return false;
1325 }
1326
1327 return inf->symbol_is_valid (sorted_syms[place], inf);
1328 }
1329
1330 /* Locate a symbol given a bfd and a section (from INFO->application_data),
1331 and a VMA. If INFO->application_data->require_sec is TRUE, then always
1332 require the symbol to be in the section. Returns NULL if there is no
1333 suitable symbol. If PLACE is not NULL, then *PLACE is set to the index
1334 of the symbol in sorted_syms. */
1335
1336 static asymbol *
1337 find_symbol_for_address (bfd_vma vma,
1338 struct disassemble_info *inf,
1339 long *place)
1340 {
1341 /* @@ Would it speed things up to cache the last two symbols returned,
1342 and maybe their address ranges? For many processors, only one memory
1343 operand can be present at a time, so the 2-entry cache wouldn't be
1344 constantly churned by code doing heavy memory accesses. */
1345
1346 /* Indices in `sorted_syms'. */
1347 long min = 0;
1348 long max_count = sorted_symcount;
1349 long thisplace;
1350 struct objdump_disasm_info *aux;
1351 bfd *abfd;
1352 asection *sec;
1353 unsigned int opb;
1354 bool want_section;
1355 long rel_count;
1356
1357 if (sorted_symcount < 1)
1358 return NULL;
1359
1360 aux = (struct objdump_disasm_info *) inf->application_data;
1361 abfd = aux->abfd;
1362 sec = inf->section;
1363 opb = inf->octets_per_byte;
1364
1365 /* Perform a binary search looking for the closest symbol to the
1366 required value. We are searching the range (min, max_count]. */
1367 while (min + 1 < max_count)
1368 {
1369 asymbol *sym;
1370
1371 thisplace = (max_count + min) / 2;
1372 sym = sorted_syms[thisplace];
1373
1374 if (bfd_asymbol_value (sym) > vma)
1375 max_count = thisplace;
1376 else if (bfd_asymbol_value (sym) < vma)
1377 min = thisplace;
1378 else
1379 {
1380 min = thisplace;
1381 break;
1382 }
1383 }
1384
1385 /* The symbol we want is now in min, the low end of the range we
1386 were searching. If there are several symbols with the same
1387 value, we want the first one. */
1388 thisplace = min;
1389 while (thisplace > 0
1390 && (bfd_asymbol_value (sorted_syms[thisplace])
1391 == bfd_asymbol_value (sorted_syms[thisplace - 1])))
1392 --thisplace;
1393
1394 /* Prefer a symbol in the current section if we have multple symbols
1395 with the same value, as can occur with overlays or zero size
1396 sections. */
1397 min = thisplace;
1398 while (min < max_count
1399 && (bfd_asymbol_value (sorted_syms[min])
1400 == bfd_asymbol_value (sorted_syms[thisplace])))
1401 {
1402 if (sym_ok (true, abfd, min, sec, inf))
1403 {
1404 thisplace = min;
1405
1406 if (place != NULL)
1407 *place = thisplace;
1408
1409 return sorted_syms[thisplace];
1410 }
1411 ++min;
1412 }
1413
1414 /* If the file is relocatable, and the symbol could be from this
1415 section, prefer a symbol from this section over symbols from
1416 others, even if the other symbol's value might be closer.
1417
1418 Note that this may be wrong for some symbol references if the
1419 sections have overlapping memory ranges, but in that case there's
1420 no way to tell what's desired without looking at the relocation
1421 table.
1422
1423 Also give the target a chance to reject symbols. */
1424 want_section = (aux->require_sec
1425 || ((abfd->flags & HAS_RELOC) != 0
1426 && vma >= bfd_section_vma (sec)
1427 && vma < (bfd_section_vma (sec)
1428 + bfd_section_size (sec) / opb)));
1429
1430 if (! sym_ok (want_section, abfd, thisplace, sec, inf))
1431 {
1432 long i;
1433 long newplace = sorted_symcount;
1434
1435 for (i = min - 1; i >= 0; i--)
1436 {
1437 if (sym_ok (want_section, abfd, i, sec, inf))
1438 {
1439 if (newplace == sorted_symcount)
1440 newplace = i;
1441
1442 if (bfd_asymbol_value (sorted_syms[i])
1443 != bfd_asymbol_value (sorted_syms[newplace]))
1444 break;
1445
1446 /* Remember this symbol and keep searching until we reach
1447 an earlier address. */
1448 newplace = i;
1449 }
1450 }
1451
1452 if (newplace != sorted_symcount)
1453 thisplace = newplace;
1454 else
1455 {
1456 /* We didn't find a good symbol with a smaller value.
1457 Look for one with a larger value. */
1458 for (i = thisplace + 1; i < sorted_symcount; i++)
1459 {
1460 if (sym_ok (want_section, abfd, i, sec, inf))
1461 {
1462 thisplace = i;
1463 break;
1464 }
1465 }
1466 }
1467
1468 if (! sym_ok (want_section, abfd, thisplace, sec, inf))
1469 /* There is no suitable symbol. */
1470 return NULL;
1471 }
1472
1473 /* If we have not found an exact match for the specified address
1474 and we have dynamic relocations available, then we can produce
1475 a better result by matching a relocation to the address and
1476 using the symbol associated with that relocation. */
1477 rel_count = inf->dynrelcount;
1478 if (!want_section
1479 && sorted_syms[thisplace]->value != vma
1480 && rel_count > 0
1481 && inf->dynrelbuf != NULL
1482 && inf->dynrelbuf[0]->address <= vma
1483 && inf->dynrelbuf[rel_count - 1]->address >= vma
1484 /* If we have matched a synthetic symbol, then stick with that. */
1485 && (sorted_syms[thisplace]->flags & BSF_SYNTHETIC) == 0)
1486 {
1487 arelent ** rel_low;
1488 arelent ** rel_high;
1489
1490 rel_low = inf->dynrelbuf;
1491 rel_high = rel_low + rel_count - 1;
1492 while (rel_low <= rel_high)
1493 {
1494 arelent **rel_mid = &rel_low[(rel_high - rel_low) / 2];
1495 arelent * rel = *rel_mid;
1496
1497 if (rel->address == vma)
1498 {
1499 /* Absolute relocations do not provide a more helpful
1500 symbolic address. Find a non-absolute relocation
1501 with the same address. */
1502 arelent **rel_vma = rel_mid;
1503 for (rel_mid--;
1504 rel_mid >= rel_low && rel_mid[0]->address == vma;
1505 rel_mid--)
1506 rel_vma = rel_mid;
1507
1508 for (; rel_vma <= rel_high && rel_vma[0]->address == vma;
1509 rel_vma++)
1510 {
1511 rel = *rel_vma;
1512 if (rel->sym_ptr_ptr != NULL
1513 && ! bfd_is_abs_section ((* rel->sym_ptr_ptr)->section))
1514 {
1515 if (place != NULL)
1516 * place = thisplace;
1517 return * rel->sym_ptr_ptr;
1518 }
1519 }
1520 break;
1521 }
1522
1523 if (vma < rel->address)
1524 rel_high = rel_mid;
1525 else if (vma >= rel_mid[1]->address)
1526 rel_low = rel_mid + 1;
1527 else
1528 break;
1529 }
1530 }
1531
1532 if (place != NULL)
1533 *place = thisplace;
1534
1535 return sorted_syms[thisplace];
1536 }
1537
1538 /* Print an address and the offset to the nearest symbol. */
1539
1540 static void
1541 objdump_print_addr_with_sym (bfd *abfd, asection *sec, asymbol *sym,
1542 bfd_vma vma, struct disassemble_info *inf,
1543 bool skip_zeroes)
1544 {
1545 if (!no_addresses)
1546 {
1547 objdump_print_value (vma, inf, skip_zeroes);
1548 (*inf->fprintf_func) (inf->stream, " ");
1549 }
1550
1551 if (sym == NULL)
1552 {
1553 bfd_vma secaddr;
1554
1555 (*inf->fprintf_func) (inf->stream, "<%s",
1556 sanitize_string (bfd_section_name (sec)));
1557 secaddr = bfd_section_vma (sec);
1558 if (vma < secaddr)
1559 {
1560 (*inf->fprintf_func) (inf->stream, "-0x");
1561 objdump_print_value (secaddr - vma, inf, true);
1562 }
1563 else if (vma > secaddr)
1564 {
1565 (*inf->fprintf_func) (inf->stream, "+0x");
1566 objdump_print_value (vma - secaddr, inf, true);
1567 }
1568 (*inf->fprintf_func) (inf->stream, ">");
1569 }
1570 else
1571 {
1572 (*inf->fprintf_func) (inf->stream, "<");
1573
1574 objdump_print_symname (abfd, inf, sym);
1575
1576 if (bfd_asymbol_value (sym) == vma)
1577 ;
1578 /* Undefined symbols in an executables and dynamic objects do not have
1579 a value associated with them, so it does not make sense to display
1580 an offset relative to them. Normally we would not be provided with
1581 this kind of symbol, but the target backend might choose to do so,
1582 and the code in find_symbol_for_address might return an as yet
1583 unresolved symbol associated with a dynamic reloc. */
1584 else if ((bfd_get_file_flags (abfd) & (EXEC_P | DYNAMIC))
1585 && bfd_is_und_section (sym->section))
1586 ;
1587 else if (bfd_asymbol_value (sym) > vma)
1588 {
1589 (*inf->fprintf_func) (inf->stream, "-0x");
1590 objdump_print_value (bfd_asymbol_value (sym) - vma, inf, true);
1591 }
1592 else if (vma > bfd_asymbol_value (sym))
1593 {
1594 (*inf->fprintf_func) (inf->stream, "+0x");
1595 objdump_print_value (vma - bfd_asymbol_value (sym), inf, true);
1596 }
1597
1598 (*inf->fprintf_func) (inf->stream, ">");
1599 }
1600
1601 if (display_file_offsets)
1602 inf->fprintf_func (inf->stream, _(" (File Offset: 0x%lx)"),
1603 (long int)(sec->filepos + (vma - sec->vma)));
1604 }
1605
1606 /* Print an address (VMA), symbolically if possible.
1607 If SKIP_ZEROES is TRUE, don't output leading zeroes. */
1608
1609 static void
1610 objdump_print_addr (bfd_vma vma,
1611 struct disassemble_info *inf,
1612 bool skip_zeroes)
1613 {
1614 struct objdump_disasm_info *aux;
1615 asymbol *sym = NULL;
1616 bool skip_find = false;
1617
1618 aux = (struct objdump_disasm_info *) inf->application_data;
1619
1620 if (sorted_symcount < 1)
1621 {
1622 if (!no_addresses)
1623 {
1624 (*inf->fprintf_func) (inf->stream, "0x");
1625 objdump_print_value (vma, inf, skip_zeroes);
1626 }
1627
1628 if (display_file_offsets)
1629 inf->fprintf_func (inf->stream, _(" (File Offset: 0x%lx)"),
1630 (long int) (inf->section->filepos
1631 + (vma - inf->section->vma)));
1632 return;
1633 }
1634
1635 if (aux->reloc != NULL
1636 && aux->reloc->sym_ptr_ptr != NULL
1637 && * aux->reloc->sym_ptr_ptr != NULL)
1638 {
1639 sym = * aux->reloc->sym_ptr_ptr;
1640
1641 /* Adjust the vma to the reloc. */
1642 vma += bfd_asymbol_value (sym);
1643
1644 if (bfd_is_und_section (bfd_asymbol_section (sym)))
1645 skip_find = true;
1646 }
1647
1648 if (!skip_find)
1649 sym = find_symbol_for_address (vma, inf, NULL);
1650
1651 objdump_print_addr_with_sym (aux->abfd, inf->section, sym, vma, inf,
1652 skip_zeroes);
1653 }
1654
1655 /* Print VMA to INFO. This function is passed to the disassembler
1656 routine. */
1657
1658 static void
1659 objdump_print_address (bfd_vma vma, struct disassemble_info *inf)
1660 {
1661 objdump_print_addr (vma, inf, ! prefix_addresses);
1662 }
1663
1664 /* Determine if the given address has a symbol associated with it. */
1665
1666 static asymbol *
1667 objdump_symbol_at_address (bfd_vma vma, struct disassemble_info * inf)
1668 {
1669 asymbol * sym;
1670
1671 sym = find_symbol_for_address (vma, inf, NULL);
1672 if (sym != NULL && bfd_asymbol_value (sym) == vma)
1673 return sym;
1674
1675 return NULL;
1676 }
1677
1678 /* Hold the last function name and the last line number we displayed
1679 in a disassembly. */
1680
1681 static char *prev_functionname;
1682 static unsigned int prev_line;
1683 static unsigned int prev_discriminator;
1684
1685 /* We keep a list of all files that we have seen when doing a
1686 disassembly with source, so that we know how much of the file to
1687 display. This can be important for inlined functions. */
1688
1689 struct print_file_list
1690 {
1691 struct print_file_list *next;
1692 const char *filename;
1693 const char *modname;
1694 const char *map;
1695 size_t mapsize;
1696 const char **linemap;
1697 unsigned maxline;
1698 unsigned last_line;
1699 unsigned max_printed;
1700 int first;
1701 };
1702
1703 static struct print_file_list *print_files;
1704
1705 /* The number of preceding context lines to show when we start
1706 displaying a file for the first time. */
1707
1708 #define SHOW_PRECEDING_CONTEXT_LINES (5)
1709
1710 /* Read a complete file into memory. */
1711
1712 static const char *
1713 slurp_file (const char *fn, size_t *size, struct stat *fst)
1714 {
1715 #ifdef HAVE_MMAP
1716 int ps = getpagesize ();
1717 size_t msize;
1718 #endif
1719 const char *map;
1720 int fd = open (fn, O_RDONLY | O_BINARY);
1721
1722 if (fd < 0)
1723 return NULL;
1724 if (fstat (fd, fst) < 0)
1725 {
1726 close (fd);
1727 return NULL;
1728 }
1729 *size = fst->st_size;
1730 #ifdef HAVE_MMAP
1731 msize = (*size + ps - 1) & ~(ps - 1);
1732 map = mmap (NULL, msize, PROT_READ, MAP_SHARED, fd, 0);
1733 if (map != (char *) -1L)
1734 {
1735 close (fd);
1736 return map;
1737 }
1738 #endif
1739 map = (const char *) malloc (*size);
1740 if (!map || (size_t) read (fd, (char *) map, *size) != *size)
1741 {
1742 free ((void *) map);
1743 map = NULL;
1744 }
1745 close (fd);
1746 return map;
1747 }
1748
1749 #define line_map_decrease 5
1750
1751 /* Precompute array of lines for a mapped file. */
1752
1753 static const char **
1754 index_file (const char *map, size_t size, unsigned int *maxline)
1755 {
1756 const char *p, *lstart, *end;
1757 int chars_per_line = 45; /* First iteration will use 40. */
1758 unsigned int lineno;
1759 const char **linemap = NULL;
1760 unsigned long line_map_size = 0;
1761
1762 lineno = 0;
1763 lstart = map;
1764 end = map + size;
1765
1766 for (p = map; p < end; p++)
1767 {
1768 if (*p == '\n')
1769 {
1770 if (p + 1 < end && p[1] == '\r')
1771 p++;
1772 }
1773 else if (*p == '\r')
1774 {
1775 if (p + 1 < end && p[1] == '\n')
1776 p++;
1777 }
1778 else
1779 continue;
1780
1781 /* End of line found. */
1782
1783 if (linemap == NULL || line_map_size < lineno + 1)
1784 {
1785 unsigned long newsize;
1786
1787 chars_per_line -= line_map_decrease;
1788 if (chars_per_line <= 1)
1789 chars_per_line = 1;
1790 line_map_size = size / chars_per_line + 1;
1791 if (line_map_size < lineno + 1)
1792 line_map_size = lineno + 1;
1793 newsize = line_map_size * sizeof (char *);
1794 linemap = (const char **) xrealloc (linemap, newsize);
1795 }
1796
1797 linemap[lineno++] = lstart;
1798 lstart = p + 1;
1799 }
1800
1801 *maxline = lineno;
1802 return linemap;
1803 }
1804
1805 /* Tries to open MODNAME, and if successful adds a node to print_files
1806 linked list and returns that node. Returns NULL on failure. */
1807
1808 static struct print_file_list *
1809 try_print_file_open (const char *origname, const char *modname, struct stat *fst)
1810 {
1811 struct print_file_list *p;
1812
1813 p = (struct print_file_list *) xmalloc (sizeof (struct print_file_list));
1814
1815 p->map = slurp_file (modname, &p->mapsize, fst);
1816 if (p->map == NULL)
1817 {
1818 free (p);
1819 return NULL;
1820 }
1821
1822 p->linemap = index_file (p->map, p->mapsize, &p->maxline);
1823 p->last_line = 0;
1824 p->max_printed = 0;
1825 p->filename = origname;
1826 p->modname = modname;
1827 p->next = print_files;
1828 p->first = 1;
1829 print_files = p;
1830 return p;
1831 }
1832
1833 /* If the source file, as described in the symtab, is not found
1834 try to locate it in one of the paths specified with -I
1835 If found, add location to print_files linked list. */
1836
1837 static struct print_file_list *
1838 update_source_path (const char *filename, bfd *abfd)
1839 {
1840 struct print_file_list *p;
1841 const char *fname;
1842 struct stat fst;
1843 int i;
1844
1845 p = try_print_file_open (filename, filename, &fst);
1846 if (p == NULL)
1847 {
1848 if (include_path_count == 0)
1849 return NULL;
1850
1851 /* Get the name of the file. */
1852 fname = lbasename (filename);
1853
1854 /* If file exists under a new path, we need to add it to the list
1855 so that show_line knows about it. */
1856 for (i = 0; i < include_path_count; i++)
1857 {
1858 char *modname = concat (include_paths[i], "/", fname,
1859 (const char *) 0);
1860
1861 p = try_print_file_open (filename, modname, &fst);
1862 if (p)
1863 break;
1864
1865 free (modname);
1866 }
1867 }
1868
1869 if (p != NULL)
1870 {
1871 long mtime = bfd_get_mtime (abfd);
1872
1873 if (fst.st_mtime > mtime)
1874 warn (_("source file %s is more recent than object file\n"),
1875 filename);
1876 }
1877
1878 return p;
1879 }
1880
1881 /* Print a source file line. */
1882
1883 static void
1884 print_line (struct print_file_list *p, unsigned int linenum)
1885 {
1886 const char *l;
1887 size_t len;
1888
1889 --linenum;
1890 if (linenum >= p->maxline)
1891 return;
1892 l = p->linemap [linenum];
1893 if (source_comment != NULL && strlen (l) > 0)
1894 printf ("%s", source_comment);
1895 len = strcspn (l, "\n\r");
1896 /* Test fwrite return value to quiet glibc warning. */
1897 if (len == 0 || fwrite (l, len, 1, stdout) == 1)
1898 putchar ('\n');
1899 }
1900
1901 /* Print a range of source code lines. */
1902
1903 static void
1904 dump_lines (struct print_file_list *p, unsigned int start, unsigned int end)
1905 {
1906 if (p->map == NULL)
1907 return;
1908 while (start <= end)
1909 {
1910 print_line (p, start);
1911 start++;
1912 }
1913 }
1914
1915 /* Show the line number, or the source line, in a disassembly
1916 listing. */
1917
1918 static void
1919 show_line (bfd *abfd, asection *section, bfd_vma addr_offset)
1920 {
1921 const char *filename;
1922 const char *functionname;
1923 unsigned int linenumber;
1924 unsigned int discriminator;
1925 bool reloc;
1926 char *path = NULL;
1927
1928 if (! with_line_numbers && ! with_source_code)
1929 return;
1930
1931 if (! bfd_find_nearest_line_discriminator (abfd, section, syms, addr_offset,
1932 &filename, &functionname,
1933 &linenumber, &discriminator))
1934 return;
1935
1936 if (filename != NULL && *filename == '\0')
1937 filename = NULL;
1938 if (functionname != NULL && *functionname == '\0')
1939 functionname = NULL;
1940
1941 if (filename
1942 && IS_ABSOLUTE_PATH (filename)
1943 && prefix)
1944 {
1945 char *path_up;
1946 const char *fname = filename;
1947
1948 path = xmalloc (prefix_length + 1 + strlen (filename));
1949
1950 if (prefix_length)
1951 memcpy (path, prefix, prefix_length);
1952 path_up = path + prefix_length;
1953
1954 /* Build relocated filename, stripping off leading directories
1955 from the initial filename if requested. */
1956 if (prefix_strip > 0)
1957 {
1958 int level = 0;
1959 const char *s;
1960
1961 /* Skip selected directory levels. */
1962 for (s = fname + 1; *s != '\0' && level < prefix_strip; s++)
1963 if (IS_DIR_SEPARATOR (*s))
1964 {
1965 fname = s;
1966 level++;
1967 }
1968 }
1969
1970 /* Update complete filename. */
1971 strcpy (path_up, fname);
1972
1973 filename = path;
1974 reloc = true;
1975 }
1976 else
1977 reloc = false;
1978
1979 if (with_line_numbers)
1980 {
1981 if (functionname != NULL
1982 && (prev_functionname == NULL
1983 || strcmp (functionname, prev_functionname) != 0))
1984 {
1985 char *demangle_alloc = NULL;
1986 if (do_demangle && functionname[0] != '\0')
1987 {
1988 /* Demangle the name. */
1989 demangle_alloc = bfd_demangle (abfd, functionname,
1990 demangle_flags);
1991 }
1992
1993 /* Demangling adds trailing parens, so don't print those. */
1994 if (demangle_alloc != NULL)
1995 printf ("%s:\n", sanitize_string (demangle_alloc));
1996 else
1997 printf ("%s():\n", sanitize_string (functionname));
1998
1999 prev_line = -1;
2000 free (demangle_alloc);
2001 }
2002 if (linenumber > 0
2003 && (linenumber != prev_line
2004 || discriminator != prev_discriminator))
2005 {
2006 if (discriminator > 0)
2007 printf ("%s:%u (discriminator %u)\n",
2008 filename == NULL ? "???" : sanitize_string (filename),
2009 linenumber, discriminator);
2010 else
2011 printf ("%s:%u\n", filename == NULL
2012 ? "???" : sanitize_string (filename),
2013 linenumber);
2014 }
2015 if (unwind_inlines)
2016 {
2017 const char *filename2;
2018 const char *functionname2;
2019 unsigned line2;
2020
2021 while (bfd_find_inliner_info (abfd, &filename2, &functionname2,
2022 &line2))
2023 {
2024 printf ("inlined by %s:%u",
2025 sanitize_string (filename2), line2);
2026 printf (" (%s)\n", sanitize_string (functionname2));
2027 }
2028 }
2029 }
2030
2031 if (with_source_code
2032 && filename != NULL
2033 && linenumber > 0)
2034 {
2035 struct print_file_list **pp, *p;
2036 unsigned l;
2037
2038 for (pp = &print_files; *pp != NULL; pp = &(*pp)->next)
2039 if (filename_cmp ((*pp)->filename, filename) == 0)
2040 break;
2041 p = *pp;
2042
2043 if (p == NULL)
2044 {
2045 if (reloc)
2046 filename = xstrdup (filename);
2047 p = update_source_path (filename, abfd);
2048 }
2049
2050 if (p != NULL && linenumber != p->last_line)
2051 {
2052 if (file_start_context && p->first)
2053 l = 1;
2054 else
2055 {
2056 l = linenumber - SHOW_PRECEDING_CONTEXT_LINES;
2057 if (l >= linenumber)
2058 l = 1;
2059 if (p->max_printed >= l)
2060 {
2061 if (p->max_printed < linenumber)
2062 l = p->max_printed + 1;
2063 else
2064 l = linenumber;
2065 }
2066 }
2067 dump_lines (p, l, linenumber);
2068 if (p->max_printed < linenumber)
2069 p->max_printed = linenumber;
2070 p->last_line = linenumber;
2071 p->first = 0;
2072 }
2073 }
2074
2075 if (functionname != NULL
2076 && (prev_functionname == NULL
2077 || strcmp (functionname, prev_functionname) != 0))
2078 {
2079 if (prev_functionname != NULL)
2080 free (prev_functionname);
2081 prev_functionname = (char *) xmalloc (strlen (functionname) + 1);
2082 strcpy (prev_functionname, functionname);
2083 }
2084
2085 if (linenumber > 0 && linenumber != prev_line)
2086 prev_line = linenumber;
2087
2088 if (discriminator != prev_discriminator)
2089 prev_discriminator = discriminator;
2090
2091 if (path)
2092 free (path);
2093 }
2094
2095 /* Pseudo FILE object for strings. */
2096 typedef struct
2097 {
2098 char *buffer;
2099 size_t pos;
2100 size_t alloc;
2101 } SFILE;
2102
2103 /* sprintf to a "stream". */
2104
2105 static int ATTRIBUTE_PRINTF_2
2106 objdump_sprintf (SFILE *f, const char *format, ...)
2107 {
2108 size_t n;
2109 va_list args;
2110
2111 while (1)
2112 {
2113 size_t space = f->alloc - f->pos;
2114
2115 va_start (args, format);
2116 n = vsnprintf (f->buffer + f->pos, space, format, args);
2117 va_end (args);
2118
2119 if (space > n)
2120 break;
2121
2122 f->alloc = (f->alloc + n) * 2;
2123 f->buffer = (char *) xrealloc (f->buffer, f->alloc);
2124 }
2125 f->pos += n;
2126
2127 return n;
2128 }
2129
2130 /* Code for generating (colored) diagrams of control flow start and end
2131 points. */
2132
2133 /* Structure used to store the properties of a jump. */
2134
2135 struct jump_info
2136 {
2137 /* The next jump, or NULL if this is the last object. */
2138 struct jump_info *next;
2139 /* The previous jump, or NULL if this is the first object. */
2140 struct jump_info *prev;
2141 /* The start addresses of the jump. */
2142 struct
2143 {
2144 /* The list of start addresses. */
2145 bfd_vma *addresses;
2146 /* The number of elements. */
2147 size_t count;
2148 /* The maximum number of elements that fit into the array. */
2149 size_t max_count;
2150 } start;
2151 /* The end address of the jump. */
2152 bfd_vma end;
2153 /* The drawing level of the jump. */
2154 int level;
2155 };
2156
2157 /* Construct a jump object for a jump from start
2158 to end with the corresponding level. */
2159
2160 static struct jump_info *
2161 jump_info_new (bfd_vma start, bfd_vma end, int level)
2162 {
2163 struct jump_info *result = xmalloc (sizeof (struct jump_info));
2164
2165 result->next = NULL;
2166 result->prev = NULL;
2167 result->start.addresses = xmalloc (sizeof (bfd_vma *) * 2);
2168 result->start.addresses[0] = start;
2169 result->start.count = 1;
2170 result->start.max_count = 2;
2171 result->end = end;
2172 result->level = level;
2173
2174 return result;
2175 }
2176
2177 /* Free a jump object and return the next object
2178 or NULL if this was the last one. */
2179
2180 static struct jump_info *
2181 jump_info_free (struct jump_info *ji)
2182 {
2183 struct jump_info *result = NULL;
2184
2185 if (ji)
2186 {
2187 result = ji->next;
2188 if (ji->start.addresses)
2189 free (ji->start.addresses);
2190 free (ji);
2191 }
2192
2193 return result;
2194 }
2195
2196 /* Get the smallest value of all start and end addresses. */
2197
2198 static bfd_vma
2199 jump_info_min_address (const struct jump_info *ji)
2200 {
2201 bfd_vma min_address = ji->end;
2202 size_t i;
2203
2204 for (i = ji->start.count; i-- > 0;)
2205 if (ji->start.addresses[i] < min_address)
2206 min_address = ji->start.addresses[i];
2207 return min_address;
2208 }
2209
2210 /* Get the largest value of all start and end addresses. */
2211
2212 static bfd_vma
2213 jump_info_max_address (const struct jump_info *ji)
2214 {
2215 bfd_vma max_address = ji->end;
2216 size_t i;
2217
2218 for (i = ji->start.count; i-- > 0;)
2219 if (ji->start.addresses[i] > max_address)
2220 max_address = ji->start.addresses[i];
2221 return max_address;
2222 }
2223
2224 /* Get the target address of a jump. */
2225
2226 static bfd_vma
2227 jump_info_end_address (const struct jump_info *ji)
2228 {
2229 return ji->end;
2230 }
2231
2232 /* Test if an address is one of the start addresses of a jump. */
2233
2234 static bool
2235 jump_info_is_start_address (const struct jump_info *ji, bfd_vma address)
2236 {
2237 bool result = false;
2238 size_t i;
2239
2240 for (i = ji->start.count; i-- > 0;)
2241 if (address == ji->start.addresses[i])
2242 {
2243 result = true;
2244 break;
2245 }
2246
2247 return result;
2248 }
2249
2250 /* Test if an address is the target address of a jump. */
2251
2252 static bool
2253 jump_info_is_end_address (const struct jump_info *ji, bfd_vma address)
2254 {
2255 return (address == ji->end);
2256 }
2257
2258 /* Get the difference between the smallest and largest address of a jump. */
2259
2260 static bfd_vma
2261 jump_info_size (const struct jump_info *ji)
2262 {
2263 return jump_info_max_address (ji) - jump_info_min_address (ji);
2264 }
2265
2266 /* Unlink a jump object from a list. */
2267
2268 static void
2269 jump_info_unlink (struct jump_info *node,
2270 struct jump_info **base)
2271 {
2272 if (node->next)
2273 node->next->prev = node->prev;
2274 if (node->prev)
2275 node->prev->next = node->next;
2276 else
2277 *base = node->next;
2278 node->next = NULL;
2279 node->prev = NULL;
2280 }
2281
2282 /* Insert unlinked jump info node into a list. */
2283
2284 static void
2285 jump_info_insert (struct jump_info *node,
2286 struct jump_info *target,
2287 struct jump_info **base)
2288 {
2289 node->next = target;
2290 node->prev = target->prev;
2291 target->prev = node;
2292 if (node->prev)
2293 node->prev->next = node;
2294 else
2295 *base = node;
2296 }
2297
2298 /* Add unlinked node to the front of a list. */
2299
2300 static void
2301 jump_info_add_front (struct jump_info *node,
2302 struct jump_info **base)
2303 {
2304 node->next = *base;
2305 if (node->next)
2306 node->next->prev = node;
2307 node->prev = NULL;
2308 *base = node;
2309 }
2310
2311 /* Move linked node to target position. */
2312
2313 static void
2314 jump_info_move_linked (struct jump_info *node,
2315 struct jump_info *target,
2316 struct jump_info **base)
2317 {
2318 /* Unlink node. */
2319 jump_info_unlink (node, base);
2320 /* Insert node at target position. */
2321 jump_info_insert (node, target, base);
2322 }
2323
2324 /* Test if two jumps intersect. */
2325
2326 static bool
2327 jump_info_intersect (const struct jump_info *a,
2328 const struct jump_info *b)
2329 {
2330 return ((jump_info_max_address (a) >= jump_info_min_address (b))
2331 && (jump_info_min_address (a) <= jump_info_max_address (b)));
2332 }
2333
2334 /* Merge two compatible jump info objects. */
2335
2336 static void
2337 jump_info_merge (struct jump_info **base)
2338 {
2339 struct jump_info *a;
2340
2341 for (a = *base; a; a = a->next)
2342 {
2343 struct jump_info *b;
2344
2345 for (b = a->next; b; b = b->next)
2346 {
2347 /* Merge both jumps into one. */
2348 if (a->end == b->end)
2349 {
2350 /* Reallocate addresses. */
2351 size_t needed_size = a->start.count + b->start.count;
2352 size_t i;
2353
2354 if (needed_size > a->start.max_count)
2355 {
2356 a->start.max_count += b->start.max_count;
2357 a->start.addresses =
2358 xrealloc (a->start.addresses,
2359 a->start.max_count * sizeof (bfd_vma *));
2360 }
2361
2362 /* Append start addresses. */
2363 for (i = 0; i < b->start.count; ++i)
2364 a->start.addresses[a->start.count++] =
2365 b->start.addresses[i];
2366
2367 /* Remove and delete jump. */
2368 struct jump_info *tmp = b->prev;
2369 jump_info_unlink (b, base);
2370 jump_info_free (b);
2371 b = tmp;
2372 }
2373 }
2374 }
2375 }
2376
2377 /* Sort jumps by their size and starting point using a stable
2378 minsort. This could be improved if sorting performance is
2379 an issue, for example by using mergesort. */
2380
2381 static void
2382 jump_info_sort (struct jump_info **base)
2383 {
2384 struct jump_info *current_element = *base;
2385
2386 while (current_element)
2387 {
2388 struct jump_info *best_match = current_element;
2389 struct jump_info *runner = current_element->next;
2390 bfd_vma best_size = jump_info_size (best_match);
2391
2392 while (runner)
2393 {
2394 bfd_vma runner_size = jump_info_size (runner);
2395
2396 if ((runner_size < best_size)
2397 || ((runner_size == best_size)
2398 && (jump_info_min_address (runner)
2399 < jump_info_min_address (best_match))))
2400 {
2401 best_match = runner;
2402 best_size = runner_size;
2403 }
2404
2405 runner = runner->next;
2406 }
2407
2408 if (best_match == current_element)
2409 current_element = current_element->next;
2410 else
2411 jump_info_move_linked (best_match, current_element, base);
2412 }
2413 }
2414
2415 /* Visualize all jumps at a given address. */
2416
2417 static void
2418 jump_info_visualize_address (bfd_vma address,
2419 int max_level,
2420 char *line_buffer,
2421 uint8_t *color_buffer)
2422 {
2423 struct jump_info *ji = detected_jumps;
2424 size_t len = (max_level + 1) * 3;
2425
2426 /* Clear line buffer. */
2427 memset (line_buffer, ' ', len);
2428 memset (color_buffer, 0, len);
2429
2430 /* Iterate over jumps and add their ASCII art. */
2431 while (ji)
2432 {
2433 /* Discard jumps that are never needed again. */
2434 if (jump_info_max_address (ji) < address)
2435 {
2436 struct jump_info *tmp = ji;
2437
2438 ji = ji->next;
2439 jump_info_unlink (tmp, &detected_jumps);
2440 jump_info_free (tmp);
2441 continue;
2442 }
2443
2444 /* This jump intersects with the current address. */
2445 if (jump_info_min_address (ji) <= address)
2446 {
2447 /* Hash target address to get an even
2448 distribution between all values. */
2449 bfd_vma hash_address = jump_info_end_address (ji);
2450 uint8_t color = iterative_hash_object (hash_address, 0);
2451 /* Fetch line offset. */
2452 int offset = (max_level - ji->level) * 3;
2453
2454 /* Draw start line. */
2455 if (jump_info_is_start_address (ji, address))
2456 {
2457 size_t i = offset + 1;
2458
2459 for (; i < len - 1; ++i)
2460 if (line_buffer[i] == ' ')
2461 {
2462 line_buffer[i] = '-';
2463 color_buffer[i] = color;
2464 }
2465
2466 if (line_buffer[i] == ' ')
2467 {
2468 line_buffer[i] = '-';
2469 color_buffer[i] = color;
2470 }
2471 else if (line_buffer[i] == '>')
2472 {
2473 line_buffer[i] = 'X';
2474 color_buffer[i] = color;
2475 }
2476
2477 if (line_buffer[offset] == ' ')
2478 {
2479 if (address <= ji->end)
2480 line_buffer[offset] =
2481 (jump_info_min_address (ji) == address) ? '/': '+';
2482 else
2483 line_buffer[offset] =
2484 (jump_info_max_address (ji) == address) ? '\\': '+';
2485 color_buffer[offset] = color;
2486 }
2487 }
2488 /* Draw jump target. */
2489 else if (jump_info_is_end_address (ji, address))
2490 {
2491 size_t i = offset + 1;
2492
2493 for (; i < len - 1; ++i)
2494 if (line_buffer[i] == ' ')
2495 {
2496 line_buffer[i] = '-';
2497 color_buffer[i] = color;
2498 }
2499
2500 if (line_buffer[i] == ' ')
2501 {
2502 line_buffer[i] = '>';
2503 color_buffer[i] = color;
2504 }
2505 else if (line_buffer[i] == '-')
2506 {
2507 line_buffer[i] = 'X';
2508 color_buffer[i] = color;
2509 }
2510
2511 if (line_buffer[offset] == ' ')
2512 {
2513 if (jump_info_min_address (ji) < address)
2514 line_buffer[offset] =
2515 (jump_info_max_address (ji) > address) ? '>' : '\\';
2516 else
2517 line_buffer[offset] = '/';
2518 color_buffer[offset] = color;
2519 }
2520 }
2521 /* Draw intermediate line segment. */
2522 else if (line_buffer[offset] == ' ')
2523 {
2524 line_buffer[offset] = '|';
2525 color_buffer[offset] = color;
2526 }
2527 }
2528
2529 ji = ji->next;
2530 }
2531 }
2532
2533 /* Clone of disassemble_bytes to detect jumps inside a function. */
2534 /* FIXME: is this correct? Can we strip it down even further? */
2535
2536 static struct jump_info *
2537 disassemble_jumps (struct disassemble_info * inf,
2538 disassembler_ftype disassemble_fn,
2539 bfd_vma start_offset,
2540 bfd_vma stop_offset,
2541 bfd_vma rel_offset,
2542 arelent *** relppp,
2543 arelent ** relppend)
2544 {
2545 struct objdump_disasm_info *aux;
2546 struct jump_info *jumps = NULL;
2547 asection *section;
2548 bfd_vma addr_offset;
2549 unsigned int opb = inf->octets_per_byte;
2550 int octets = opb;
2551 SFILE sfile;
2552
2553 aux = (struct objdump_disasm_info *) inf->application_data;
2554 section = inf->section;
2555
2556 sfile.alloc = 120;
2557 sfile.buffer = (char *) xmalloc (sfile.alloc);
2558 sfile.pos = 0;
2559
2560 inf->insn_info_valid = 0;
2561 inf->fprintf_func = (fprintf_ftype) objdump_sprintf;
2562 inf->stream = &sfile;
2563
2564 addr_offset = start_offset;
2565 while (addr_offset < stop_offset)
2566 {
2567 int previous_octets;
2568
2569 /* Remember the length of the previous instruction. */
2570 previous_octets = octets;
2571 octets = 0;
2572
2573 sfile.pos = 0;
2574 inf->bytes_per_line = 0;
2575 inf->bytes_per_chunk = 0;
2576 inf->flags = ((disassemble_all ? DISASSEMBLE_DATA : 0)
2577 | (wide_output ? WIDE_OUTPUT : 0));
2578 if (machine)
2579 inf->flags |= USER_SPECIFIED_MACHINE_TYPE;
2580
2581 if (inf->disassembler_needs_relocs
2582 && (bfd_get_file_flags (aux->abfd) & EXEC_P) == 0
2583 && (bfd_get_file_flags (aux->abfd) & DYNAMIC) == 0
2584 && *relppp < relppend)
2585 {
2586 bfd_signed_vma distance_to_rel;
2587
2588 distance_to_rel = (**relppp)->address - (rel_offset + addr_offset);
2589
2590 /* Check to see if the current reloc is associated with
2591 the instruction that we are about to disassemble. */
2592 if (distance_to_rel == 0
2593 /* FIXME: This is wrong. We are trying to catch
2594 relocs that are addressed part way through the
2595 current instruction, as might happen with a packed
2596 VLIW instruction. Unfortunately we do not know the
2597 length of the current instruction since we have not
2598 disassembled it yet. Instead we take a guess based
2599 upon the length of the previous instruction. The
2600 proper solution is to have a new target-specific
2601 disassembler function which just returns the length
2602 of an instruction at a given address without trying
2603 to display its disassembly. */
2604 || (distance_to_rel > 0
2605 && distance_to_rel < (bfd_signed_vma) (previous_octets/ opb)))
2606 {
2607 inf->flags |= INSN_HAS_RELOC;
2608 }
2609 }
2610
2611 if (! disassemble_all
2612 && (section->flags & (SEC_CODE | SEC_HAS_CONTENTS))
2613 == (SEC_CODE | SEC_HAS_CONTENTS))
2614 /* Set a stop_vma so that the disassembler will not read
2615 beyond the next symbol. We assume that symbols appear on
2616 the boundaries between instructions. We only do this when
2617 disassembling code of course, and when -D is in effect. */
2618 inf->stop_vma = section->vma + stop_offset;
2619
2620 inf->stop_offset = stop_offset;
2621
2622 /* Extract jump information. */
2623 inf->insn_info_valid = 0;
2624 octets = (*disassemble_fn) (section->vma + addr_offset, inf);
2625 /* Test if a jump was detected. */
2626 if (inf->insn_info_valid
2627 && ((inf->insn_type == dis_branch)
2628 || (inf->insn_type == dis_condbranch)
2629 || (inf->insn_type == dis_jsr)
2630 || (inf->insn_type == dis_condjsr))
2631 && (inf->target >= section->vma + start_offset)
2632 && (inf->target < section->vma + stop_offset))
2633 {
2634 struct jump_info *ji =
2635 jump_info_new (section->vma + addr_offset, inf->target, -1);
2636 jump_info_add_front (ji, &jumps);
2637 }
2638
2639 inf->stop_vma = 0;
2640
2641 addr_offset += octets / opb;
2642 }
2643
2644 inf->fprintf_func = (fprintf_ftype) fprintf;
2645 inf->stream = stdout;
2646
2647 free (sfile.buffer);
2648
2649 /* Merge jumps. */
2650 jump_info_merge (&jumps);
2651 /* Process jumps. */
2652 jump_info_sort (&jumps);
2653
2654 /* Group jumps by level. */
2655 struct jump_info *last_jump = jumps;
2656 int max_level = -1;
2657
2658 while (last_jump)
2659 {
2660 /* The last jump is part of the next group. */
2661 struct jump_info *base = last_jump;
2662 /* Increment level. */
2663 base->level = ++max_level;
2664
2665 /* Find jumps that can be combined on the same
2666 level, with the largest jumps tested first.
2667 This has the advantage that large jumps are on
2668 lower levels and do not intersect with small
2669 jumps that get grouped on higher levels. */
2670 struct jump_info *exchange_item = last_jump->next;
2671 struct jump_info *it = exchange_item;
2672
2673 for (; it; it = it->next)
2674 {
2675 /* Test if the jump intersects with any
2676 jump from current group. */
2677 bool ok = true;
2678 struct jump_info *it_collision;
2679
2680 for (it_collision = base;
2681 it_collision != exchange_item;
2682 it_collision = it_collision->next)
2683 {
2684 /* This jump intersects so we leave it out. */
2685 if (jump_info_intersect (it_collision, it))
2686 {
2687 ok = false;
2688 break;
2689 }
2690 }
2691
2692 /* Add jump to group. */
2693 if (ok)
2694 {
2695 /* Move current element to the front. */
2696 if (it != exchange_item)
2697 {
2698 struct jump_info *save = it->prev;
2699 jump_info_move_linked (it, exchange_item, &jumps);
2700 last_jump = it;
2701 it = save;
2702 }
2703 else
2704 {
2705 last_jump = exchange_item;
2706 exchange_item = exchange_item->next;
2707 }
2708 last_jump->level = max_level;
2709 }
2710 }
2711
2712 /* Move to next group. */
2713 last_jump = exchange_item;
2714 }
2715
2716 return jumps;
2717 }
2718
2719 /* The number of zeroes we want to see before we start skipping them.
2720 The number is arbitrarily chosen. */
2721
2722 #define DEFAULT_SKIP_ZEROES 8
2723
2724 /* The number of zeroes to skip at the end of a section. If the
2725 number of zeroes at the end is between SKIP_ZEROES_AT_END and
2726 SKIP_ZEROES, they will be disassembled. If there are fewer than
2727 SKIP_ZEROES_AT_END, they will be skipped. This is a heuristic
2728 attempt to avoid disassembling zeroes inserted by section
2729 alignment. */
2730
2731 #define DEFAULT_SKIP_ZEROES_AT_END 3
2732
2733 static int
2734 null_print (const void * stream ATTRIBUTE_UNUSED, const char * format ATTRIBUTE_UNUSED, ...)
2735 {
2736 return 1;
2737 }
2738
2739 /* Print out jump visualization. */
2740
2741 static void
2742 print_jump_visualisation (bfd_vma addr, int max_level, char *line_buffer,
2743 uint8_t *color_buffer)
2744 {
2745 if (!line_buffer)
2746 return;
2747
2748 jump_info_visualize_address (addr, max_level, line_buffer, color_buffer);
2749
2750 size_t line_buffer_size = strlen (line_buffer);
2751 char last_color = 0;
2752 size_t i;
2753
2754 for (i = 0; i <= line_buffer_size; ++i)
2755 {
2756 if (color_output)
2757 {
2758 uint8_t color = (i < line_buffer_size) ? color_buffer[i]: 0;
2759
2760 if (color != last_color)
2761 {
2762 if (color)
2763 if (extended_color_output)
2764 /* Use extended 8bit color, but
2765 do not choose dark colors. */
2766 printf ("\033[38;5;%dm", 124 + (color % 108));
2767 else
2768 /* Use simple terminal colors. */
2769 printf ("\033[%dm", 31 + (color % 7));
2770 else
2771 /* Clear color. */
2772 printf ("\033[0m");
2773 last_color = color;
2774 }
2775 }
2776 putchar ((i < line_buffer_size) ? line_buffer[i]: ' ');
2777 }
2778 }
2779
2780 /* Disassemble some data in memory between given values. */
2781
2782 static void
2783 disassemble_bytes (struct disassemble_info *inf,
2784 disassembler_ftype disassemble_fn,
2785 bool insns,
2786 bfd_byte *data,
2787 bfd_vma start_offset,
2788 bfd_vma stop_offset,
2789 bfd_vma rel_offset,
2790 arelent ***relppp,
2791 arelent **relppend)
2792 {
2793 struct objdump_disasm_info *aux;
2794 asection *section;
2795 unsigned int octets_per_line;
2796 unsigned int skip_addr_chars;
2797 bfd_vma addr_offset;
2798 unsigned int opb = inf->octets_per_byte;
2799 unsigned int skip_zeroes = inf->skip_zeroes;
2800 unsigned int skip_zeroes_at_end = inf->skip_zeroes_at_end;
2801 size_t octets;
2802 SFILE sfile;
2803
2804 aux = (struct objdump_disasm_info *) inf->application_data;
2805 section = inf->section;
2806
2807 sfile.alloc = 120;
2808 sfile.buffer = (char *) xmalloc (sfile.alloc);
2809 sfile.pos = 0;
2810
2811 if (insn_width)
2812 octets_per_line = insn_width;
2813 else if (insns)
2814 octets_per_line = 4;
2815 else
2816 octets_per_line = 16;
2817
2818 /* Figure out how many characters to skip at the start of an
2819 address, to make the disassembly look nicer. We discard leading
2820 zeroes in chunks of 4, ensuring that there is always a leading
2821 zero remaining. */
2822 skip_addr_chars = 0;
2823 if (!no_addresses && !prefix_addresses)
2824 {
2825 char buf[30];
2826
2827 bfd_sprintf_vma (aux->abfd, buf, section->vma + section->size / opb);
2828
2829 while (buf[skip_addr_chars] == '0')
2830 ++skip_addr_chars;
2831
2832 /* Don't discard zeros on overflow. */
2833 if (buf[skip_addr_chars] == '\0' && section->vma != 0)
2834 skip_addr_chars = 0;
2835
2836 if (skip_addr_chars != 0)
2837 skip_addr_chars = (skip_addr_chars - 1) & -4;
2838 }
2839
2840 inf->insn_info_valid = 0;
2841
2842 /* Determine maximum level. */
2843 uint8_t *color_buffer = NULL;
2844 char *line_buffer = NULL;
2845 int max_level = -1;
2846
2847 /* Some jumps were detected. */
2848 if (detected_jumps)
2849 {
2850 struct jump_info *ji;
2851
2852 /* Find maximum jump level. */
2853 for (ji = detected_jumps; ji; ji = ji->next)
2854 {
2855 if (ji->level > max_level)
2856 max_level = ji->level;
2857 }
2858
2859 /* Allocate buffers. */
2860 size_t len = (max_level + 1) * 3 + 1;
2861 line_buffer = xmalloc (len);
2862 line_buffer[len - 1] = 0;
2863 color_buffer = xmalloc (len);
2864 color_buffer[len - 1] = 0;
2865 }
2866
2867 addr_offset = start_offset;
2868 while (addr_offset < stop_offset)
2869 {
2870 bool need_nl = false;
2871
2872 octets = 0;
2873
2874 /* Make sure we don't use relocs from previous instructions. */
2875 aux->reloc = NULL;
2876
2877 /* If we see more than SKIP_ZEROES octets of zeroes, we just
2878 print `...'. */
2879 if (! disassemble_zeroes)
2880 for (; addr_offset * opb + octets < stop_offset * opb; octets++)
2881 if (data[addr_offset * opb + octets] != 0)
2882 break;
2883 if (! disassemble_zeroes
2884 && (inf->insn_info_valid == 0
2885 || inf->branch_delay_insns == 0)
2886 && (octets >= skip_zeroes
2887 || (addr_offset * opb + octets == stop_offset * opb
2888 && octets < skip_zeroes_at_end)))
2889 {
2890 /* If there are more nonzero octets to follow, we only skip
2891 zeroes in multiples of 4, to try to avoid running over
2892 the start of an instruction which happens to start with
2893 zero. */
2894 if (addr_offset * opb + octets != stop_offset * opb)
2895 octets &= ~3;
2896
2897 /* If we are going to display more data, and we are displaying
2898 file offsets, then tell the user how many zeroes we skip
2899 and the file offset from where we resume dumping. */
2900 if (display_file_offsets
2901 && addr_offset + octets / opb < stop_offset)
2902 printf (_("\t... (skipping %lu zeroes, "
2903 "resuming at file offset: 0x%lx)\n"),
2904 (unsigned long) (octets / opb),
2905 (unsigned long) (section->filepos
2906 + addr_offset + octets / opb));
2907 else
2908 printf ("\t...\n");
2909 }
2910 else
2911 {
2912 char buf[50];
2913 unsigned int bpc = 0;
2914 unsigned int pb = 0;
2915
2916 if (with_line_numbers || with_source_code)
2917 show_line (aux->abfd, section, addr_offset);
2918
2919 if (no_addresses)
2920 printf ("\t");
2921 else if (!prefix_addresses)
2922 {
2923 char *s;
2924
2925 bfd_sprintf_vma (aux->abfd, buf, section->vma + addr_offset);
2926 for (s = buf + skip_addr_chars; *s == '0'; s++)
2927 *s = ' ';
2928 if (*s == '\0')
2929 *--s = '0';
2930 printf ("%s:\t", buf + skip_addr_chars);
2931 }
2932 else
2933 {
2934 aux->require_sec = true;
2935 objdump_print_address (section->vma + addr_offset, inf);
2936 aux->require_sec = false;
2937 putchar (' ');
2938 }
2939
2940 print_jump_visualisation (section->vma + addr_offset,
2941 max_level, line_buffer,
2942 color_buffer);
2943
2944 if (insns)
2945 {
2946 int insn_size;
2947
2948 sfile.pos = 0;
2949 inf->fprintf_func = (fprintf_ftype) objdump_sprintf;
2950 inf->stream = &sfile;
2951 inf->bytes_per_line = 0;
2952 inf->bytes_per_chunk = 0;
2953 inf->flags = ((disassemble_all ? DISASSEMBLE_DATA : 0)
2954 | (wide_output ? WIDE_OUTPUT : 0));
2955 if (machine)
2956 inf->flags |= USER_SPECIFIED_MACHINE_TYPE;
2957
2958 if (inf->disassembler_needs_relocs
2959 && (bfd_get_file_flags (aux->abfd) & EXEC_P) == 0
2960 && (bfd_get_file_flags (aux->abfd) & DYNAMIC) == 0
2961 && *relppp < relppend)
2962 {
2963 bfd_signed_vma distance_to_rel;
2964 int max_reloc_offset
2965 = aux->abfd->arch_info->max_reloc_offset_into_insn;
2966
2967 distance_to_rel = ((**relppp)->address - rel_offset
2968 - addr_offset);
2969
2970 insn_size = 0;
2971 if (distance_to_rel > 0
2972 && (max_reloc_offset < 0
2973 || distance_to_rel <= max_reloc_offset))
2974 {
2975 /* This reloc *might* apply to the current insn,
2976 starting somewhere inside it. Discover the length
2977 of the current insn so that the check below will
2978 work. */
2979 if (insn_width)
2980 insn_size = insn_width;
2981 else
2982 {
2983 /* We find the length by calling the dissassembler
2984 function with a dummy print handler. This should
2985 work unless the disassembler is not expecting to
2986 be called multiple times for the same address.
2987
2988 This does mean disassembling the instruction
2989 twice, but we only do this when there is a high
2990 probability that there is a reloc that will
2991 affect the instruction. */
2992 inf->fprintf_func = (fprintf_ftype) null_print;
2993 insn_size = disassemble_fn (section->vma
2994 + addr_offset, inf);
2995 inf->fprintf_func = (fprintf_ftype) objdump_sprintf;
2996 }
2997 }
2998
2999 /* Check to see if the current reloc is associated with
3000 the instruction that we are about to disassemble. */
3001 if (distance_to_rel == 0
3002 || (distance_to_rel > 0
3003 && distance_to_rel < insn_size / (int) opb))
3004 {
3005 inf->flags |= INSN_HAS_RELOC;
3006 aux->reloc = **relppp;
3007 }
3008 }
3009
3010 if (! disassemble_all
3011 && ((section->flags & (SEC_CODE | SEC_HAS_CONTENTS))
3012 == (SEC_CODE | SEC_HAS_CONTENTS)))
3013 /* Set a stop_vma so that the disassembler will not read
3014 beyond the next symbol. We assume that symbols appear on
3015 the boundaries between instructions. We only do this when
3016 disassembling code of course, and when -D is in effect. */
3017 inf->stop_vma = section->vma + stop_offset;
3018
3019 inf->stop_offset = stop_offset;
3020 insn_size = (*disassemble_fn) (section->vma + addr_offset, inf);
3021 octets = insn_size;
3022
3023 inf->stop_vma = 0;
3024 inf->fprintf_func = (fprintf_ftype) fprintf;
3025 inf->stream = stdout;
3026 if (insn_width == 0 && inf->bytes_per_line != 0)
3027 octets_per_line = inf->bytes_per_line;
3028 if (insn_size < (int) opb)
3029 {
3030 if (sfile.pos)
3031 printf ("%s\n", sfile.buffer);
3032 if (insn_size >= 0)
3033 {
3034 non_fatal (_("disassemble_fn returned length %d"),
3035 insn_size);
3036 exit_status = 1;
3037 }
3038 break;
3039 }
3040 }
3041 else
3042 {
3043 bfd_vma j;
3044
3045 octets = octets_per_line;
3046 if (addr_offset + octets / opb > stop_offset)
3047 octets = (stop_offset - addr_offset) * opb;
3048
3049 for (j = addr_offset * opb; j < addr_offset * opb + octets; ++j)
3050 {
3051 if (ISPRINT (data[j]))
3052 buf[j - addr_offset * opb] = data[j];
3053 else
3054 buf[j - addr_offset * opb] = '.';
3055 }
3056 buf[j - addr_offset * opb] = '\0';
3057 }
3058
3059 if (prefix_addresses
3060 ? show_raw_insn > 0
3061 : show_raw_insn >= 0)
3062 {
3063 bfd_vma j;
3064
3065 /* If ! prefix_addresses and ! wide_output, we print
3066 octets_per_line octets per line. */
3067 pb = octets;
3068 if (pb > octets_per_line && ! prefix_addresses && ! wide_output)
3069 pb = octets_per_line;
3070
3071 if (inf->bytes_per_chunk)
3072 bpc = inf->bytes_per_chunk;
3073 else
3074 bpc = 1;
3075
3076 for (j = addr_offset * opb; j < addr_offset * opb + pb; j += bpc)
3077 {
3078 /* PR 21580: Check for a buffer ending early. */
3079 if (j + bpc <= stop_offset * opb)
3080 {
3081 unsigned int k;
3082
3083 if (inf->display_endian == BFD_ENDIAN_LITTLE)
3084 {
3085 for (k = bpc; k-- != 0; )
3086 printf ("%02x", (unsigned) data[j + k]);
3087 }
3088 else
3089 {
3090 for (k = 0; k < bpc; k++)
3091 printf ("%02x", (unsigned) data[j + k]);
3092 }
3093 }
3094 putchar (' ');
3095 }
3096
3097 for (; pb < octets_per_line; pb += bpc)
3098 {
3099 unsigned int k;
3100
3101 for (k = 0; k < bpc; k++)
3102 printf (" ");
3103 putchar (' ');
3104 }
3105
3106 /* Separate raw data from instruction by extra space. */
3107 if (insns)
3108 putchar ('\t');
3109 else
3110 printf (" ");
3111 }
3112
3113 if (! insns)
3114 printf ("%s", buf);
3115 else if (sfile.pos)
3116 printf ("%s", sfile.buffer);
3117
3118 if (prefix_addresses
3119 ? show_raw_insn > 0
3120 : show_raw_insn >= 0)
3121 {
3122 while (pb < octets)
3123 {
3124 bfd_vma j;
3125 char *s;
3126
3127 putchar ('\n');
3128 j = addr_offset * opb + pb;
3129
3130 if (no_addresses)
3131 printf ("\t");
3132 else
3133 {
3134 bfd_sprintf_vma (aux->abfd, buf, section->vma + j / opb);
3135 for (s = buf + skip_addr_chars; *s == '0'; s++)
3136 *s = ' ';
3137 if (*s == '\0')
3138 *--s = '0';
3139 printf ("%s:\t", buf + skip_addr_chars);
3140 }
3141
3142 print_jump_visualisation (section->vma + j / opb,
3143 max_level, line_buffer,
3144 color_buffer);
3145
3146 pb += octets_per_line;
3147 if (pb > octets)
3148 pb = octets;
3149 for (; j < addr_offset * opb + pb; j += bpc)
3150 {
3151 /* PR 21619: Check for a buffer ending early. */
3152 if (j + bpc <= stop_offset * opb)
3153 {
3154 unsigned int k;
3155
3156 if (inf->display_endian == BFD_ENDIAN_LITTLE)
3157 {
3158 for (k = bpc; k-- != 0; )
3159 printf ("%02x", (unsigned) data[j + k]);
3160 }
3161 else
3162 {
3163 for (k = 0; k < bpc; k++)
3164 printf ("%02x", (unsigned) data[j + k]);
3165 }
3166 }
3167 putchar (' ');
3168 }
3169 }
3170 }
3171
3172 if (!wide_output)
3173 putchar ('\n');
3174 else
3175 need_nl = true;
3176 }
3177
3178 while ((*relppp) < relppend
3179 && (**relppp)->address < rel_offset + addr_offset + octets / opb)
3180 {
3181 if (dump_reloc_info || dump_dynamic_reloc_info)
3182 {
3183 arelent *q;
3184
3185 q = **relppp;
3186
3187 if (wide_output)
3188 putchar ('\t');
3189 else
3190 printf ("\t\t\t");
3191
3192 if (!no_addresses)
3193 {
3194 objdump_print_value (section->vma - rel_offset + q->address,
3195 inf, true);
3196 printf (": ");
3197 }
3198
3199 if (q->howto == NULL)
3200 printf ("*unknown*\t");
3201 else if (q->howto->name)
3202 printf ("%s\t", q->howto->name);
3203 else
3204 printf ("%d\t", q->howto->type);
3205
3206 if (q->sym_ptr_ptr == NULL || *q->sym_ptr_ptr == NULL)
3207 printf ("*unknown*");
3208 else
3209 {
3210 const char *sym_name;
3211
3212 sym_name = bfd_asymbol_name (*q->sym_ptr_ptr);
3213 if (sym_name != NULL && *sym_name != '\0')
3214 objdump_print_symname (aux->abfd, inf, *q->sym_ptr_ptr);
3215 else
3216 {
3217 asection *sym_sec;
3218
3219 sym_sec = bfd_asymbol_section (*q->sym_ptr_ptr);
3220 sym_name = bfd_section_name (sym_sec);
3221 if (sym_name == NULL || *sym_name == '\0')
3222 sym_name = "*unknown*";
3223 printf ("%s", sanitize_string (sym_name));
3224 }
3225 }
3226
3227 if (q->addend)
3228 {
3229 bfd_vma addend = q->addend;
3230 if ((bfd_signed_vma) addend < 0)
3231 {
3232 printf ("-0x");
3233 addend = -addend;
3234 }
3235 else
3236 printf ("+0x");
3237 objdump_print_value (addend, inf, true);
3238 }
3239
3240 printf ("\n");
3241 need_nl = false;
3242 }
3243 ++(*relppp);
3244 }
3245
3246 if (need_nl)
3247 printf ("\n");
3248
3249 addr_offset += octets / opb;
3250 }
3251
3252 free (sfile.buffer);
3253 free (line_buffer);
3254 free (color_buffer);
3255 }
3256
3257 static void
3258 disassemble_section (bfd *abfd, asection *section, void *inf)
3259 {
3260 const struct elf_backend_data *bed;
3261 bfd_vma sign_adjust = 0;
3262 struct disassemble_info *pinfo = (struct disassemble_info *) inf;
3263 struct objdump_disasm_info *paux;
3264 unsigned int opb = pinfo->octets_per_byte;
3265 bfd_byte *data = NULL;
3266 bfd_size_type datasize = 0;
3267 arelent **rel_pp = NULL;
3268 arelent **rel_ppstart = NULL;
3269 arelent **rel_ppend;
3270 bfd_vma stop_offset;
3271 asymbol *sym = NULL;
3272 long place = 0;
3273 long rel_count;
3274 bfd_vma rel_offset;
3275 unsigned long addr_offset;
3276 bool do_print;
3277 enum loop_control
3278 {
3279 stop_offset_reached,
3280 function_sym,
3281 next_sym
3282 } loop_until;
3283
3284 /* Sections that do not contain machine
3285 code are not normally disassembled. */
3286 if (! disassemble_all
3287 && only_list == NULL
3288 && ((section->flags & (SEC_CODE | SEC_HAS_CONTENTS))
3289 != (SEC_CODE | SEC_HAS_CONTENTS)))
3290 return;
3291
3292 if (! process_section_p (section))
3293 return;
3294
3295 datasize = bfd_section_size (section);
3296 if (datasize == 0)
3297 return;
3298
3299 if (start_address == (bfd_vma) -1
3300 || start_address < section->vma)
3301 addr_offset = 0;
3302 else
3303 addr_offset = start_address - section->vma;
3304
3305 if (stop_address == (bfd_vma) -1)
3306 stop_offset = datasize / opb;
3307 else
3308 {
3309 if (stop_address < section->vma)
3310 stop_offset = 0;
3311 else
3312 stop_offset = stop_address - section->vma;
3313 if (stop_offset > datasize / opb)
3314 stop_offset = datasize / opb;
3315 }
3316
3317 if (addr_offset >= stop_offset)
3318 return;
3319
3320 /* Decide which set of relocs to use. Load them if necessary. */
3321 paux = (struct objdump_disasm_info *) pinfo->application_data;
3322 if (pinfo->dynrelbuf && dump_dynamic_reloc_info)
3323 {
3324 rel_pp = pinfo->dynrelbuf;
3325 rel_count = pinfo->dynrelcount;
3326 /* Dynamic reloc addresses are absolute, non-dynamic are section
3327 relative. REL_OFFSET specifies the reloc address corresponding
3328 to the start of this section. */
3329 rel_offset = section->vma;
3330 }
3331 else
3332 {
3333 rel_count = 0;
3334 rel_pp = NULL;
3335 rel_offset = 0;
3336
3337 if ((section->flags & SEC_RELOC) != 0
3338 && (dump_reloc_info || pinfo->disassembler_needs_relocs))
3339 {
3340 long relsize;
3341
3342 relsize = bfd_get_reloc_upper_bound (abfd, section);
3343 if (relsize < 0)
3344 bfd_fatal (bfd_get_filename (abfd));
3345
3346 if (relsize > 0)
3347 {
3348 rel_ppstart = rel_pp = (arelent **) xmalloc (relsize);
3349 rel_count = bfd_canonicalize_reloc (abfd, section, rel_pp, syms);
3350 if (rel_count < 0)
3351 bfd_fatal (bfd_get_filename (abfd));
3352
3353 /* Sort the relocs by address. */
3354 qsort (rel_pp, rel_count, sizeof (arelent *), compare_relocs);
3355 }
3356 }
3357 }
3358 rel_ppend = PTR_ADD (rel_pp, rel_count);
3359
3360 if (!bfd_malloc_and_get_section (abfd, section, &data))
3361 {
3362 non_fatal (_("Reading section %s failed because: %s"),
3363 section->name, bfd_errmsg (bfd_get_error ()));
3364 return;
3365 }
3366
3367 pinfo->buffer = data;
3368 pinfo->buffer_vma = section->vma;
3369 pinfo->buffer_length = datasize;
3370 pinfo->section = section;
3371
3372 /* Sort the symbols into value and section order. */
3373 compare_section = section;
3374 if (sorted_symcount > 1)
3375 qsort (sorted_syms, sorted_symcount, sizeof (asymbol *), compare_symbols);
3376
3377 /* Skip over the relocs belonging to addresses below the
3378 start address. */
3379 while (rel_pp < rel_ppend
3380 && (*rel_pp)->address < rel_offset + addr_offset)
3381 ++rel_pp;
3382
3383 printf (_("\nDisassembly of section %s:\n"), sanitize_string (section->name));
3384
3385 /* Find the nearest symbol forwards from our current position. */
3386 paux->require_sec = true;
3387 sym = (asymbol *) find_symbol_for_address (section->vma + addr_offset,
3388 (struct disassemble_info *) inf,
3389 &place);
3390 paux->require_sec = false;
3391
3392 /* PR 9774: If the target used signed addresses then we must make
3393 sure that we sign extend the value that we calculate for 'addr'
3394 in the loop below. */
3395 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
3396 && (bed = get_elf_backend_data (abfd)) != NULL
3397 && bed->sign_extend_vma)
3398 sign_adjust = (bfd_vma) 1 << (bed->s->arch_size - 1);
3399
3400 /* Disassemble a block of instructions up to the address associated with
3401 the symbol we have just found. Then print the symbol and find the
3402 next symbol on. Repeat until we have disassembled the entire section
3403 or we have reached the end of the address range we are interested in. */
3404 do_print = paux->symbol == NULL;
3405 loop_until = stop_offset_reached;
3406
3407 while (addr_offset < stop_offset)
3408 {
3409 bfd_vma addr;
3410 asymbol *nextsym;
3411 bfd_vma nextstop_offset;
3412 bool insns;
3413
3414 addr = section->vma + addr_offset;
3415 addr = ((addr & ((sign_adjust << 1) - 1)) ^ sign_adjust) - sign_adjust;
3416
3417 if (sym != NULL && bfd_asymbol_value (sym) <= addr)
3418 {
3419 int x;
3420
3421 for (x = place;
3422 (x < sorted_symcount
3423 && (bfd_asymbol_value (sorted_syms[x]) <= addr));
3424 ++x)
3425 continue;
3426
3427 pinfo->symbols = sorted_syms + place;
3428 pinfo->num_symbols = x - place;
3429 pinfo->symtab_pos = place;
3430 }
3431 else
3432 {
3433 pinfo->symbols = NULL;
3434 pinfo->num_symbols = 0;
3435 pinfo->symtab_pos = -1;
3436 }
3437
3438 /* If we are only disassembling from a specific symbol,
3439 check to see if we should start or stop displaying. */
3440 if (sym && paux->symbol)
3441 {
3442 if (do_print)
3443 {
3444 /* See if we should stop printing. */
3445 switch (loop_until)
3446 {
3447 case function_sym:
3448 if (sym->flags & BSF_FUNCTION)
3449 do_print = false;
3450 break;
3451
3452 case stop_offset_reached:
3453 /* Handled by the while loop. */
3454 break;
3455
3456 case next_sym:
3457 /* FIXME: There is an implicit assumption here
3458 that the name of sym is different from
3459 paux->symbol. */
3460 if (! bfd_is_local_label (abfd, sym))
3461 do_print = false;
3462 break;
3463 }
3464 }
3465 else
3466 {
3467 const char * name = bfd_asymbol_name (sym);
3468 char * alloc = NULL;
3469
3470 if (do_demangle && name[0] != '\0')
3471 {
3472 /* Demangle the name. */
3473 alloc = bfd_demangle (abfd, name, demangle_flags);
3474 if (alloc != NULL)
3475 name = alloc;
3476 }
3477
3478 /* We are not currently printing. Check to see
3479 if the current symbol matches the requested symbol. */
3480 if (streq (name, paux->symbol))
3481 {
3482 do_print = true;
3483
3484 if (sym->flags & BSF_FUNCTION)
3485 {
3486 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
3487 && ((elf_symbol_type *) sym)->internal_elf_sym.st_size > 0)
3488 {
3489 /* Sym is a function symbol with a size associated
3490 with it. Turn on automatic disassembly for the
3491 next VALUE bytes. */
3492 stop_offset = addr_offset
3493 + ((elf_symbol_type *) sym)->internal_elf_sym.st_size;
3494 loop_until = stop_offset_reached;
3495 }
3496 else
3497 {
3498 /* Otherwise we need to tell the loop heuristic to
3499 loop until the next function symbol is encountered. */
3500 loop_until = function_sym;
3501 }
3502 }
3503 else
3504 {
3505 /* Otherwise loop until the next symbol is encountered. */
3506 loop_until = next_sym;
3507 }
3508 }
3509
3510 free (alloc);
3511 }
3512 }
3513
3514 if (! prefix_addresses && do_print)
3515 {
3516 pinfo->fprintf_func (pinfo->stream, "\n");
3517 objdump_print_addr_with_sym (abfd, section, sym, addr,
3518 pinfo, false);
3519 pinfo->fprintf_func (pinfo->stream, ":\n");
3520 }
3521
3522 if (sym != NULL && bfd_asymbol_value (sym) > addr)
3523 nextsym = sym;
3524 else if (sym == NULL)
3525 nextsym = NULL;
3526 else
3527 {
3528 #define is_valid_next_sym(SYM) \
3529 (strcmp (bfd_section_name ((SYM)->section), bfd_section_name (section)) == 0 \
3530 && (bfd_asymbol_value (SYM) > bfd_asymbol_value (sym)) \
3531 && pinfo->symbol_is_valid (SYM, pinfo))
3532
3533 /* Search forward for the next appropriate symbol in
3534 SECTION. Note that all the symbols are sorted
3535 together into one big array, and that some sections
3536 may have overlapping addresses. */
3537 while (place < sorted_symcount
3538 && ! is_valid_next_sym (sorted_syms [place]))
3539 ++place;
3540
3541 if (place >= sorted_symcount)
3542 nextsym = NULL;
3543 else
3544 nextsym = sorted_syms[place];
3545 }
3546
3547 if (sym != NULL && bfd_asymbol_value (sym) > addr)
3548 nextstop_offset = bfd_asymbol_value (sym) - section->vma;
3549 else if (nextsym == NULL)
3550 nextstop_offset = stop_offset;
3551 else
3552 nextstop_offset = bfd_asymbol_value (nextsym) - section->vma;
3553
3554 if (nextstop_offset > stop_offset
3555 || nextstop_offset <= addr_offset)
3556 nextstop_offset = stop_offset;
3557
3558 /* If a symbol is explicitly marked as being an object
3559 rather than a function, just dump the bytes without
3560 disassembling them. */
3561 if (disassemble_all
3562 || sym == NULL
3563 || sym->section != section
3564 || bfd_asymbol_value (sym) > addr
3565 || ((sym->flags & BSF_OBJECT) == 0
3566 && (strstr (bfd_asymbol_name (sym), "gnu_compiled")
3567 == NULL)
3568 && (strstr (bfd_asymbol_name (sym), "gcc2_compiled")
3569 == NULL))
3570 || (sym->flags & BSF_FUNCTION) != 0)
3571 insns = true;
3572 else
3573 insns = false;
3574
3575 if (do_print)
3576 {
3577 /* Resolve symbol name. */
3578 if (visualize_jumps && abfd && sym && sym->name)
3579 {
3580 struct disassemble_info di;
3581 SFILE sf;
3582
3583 sf.alloc = strlen (sym->name) + 40;
3584 sf.buffer = (char*) xmalloc (sf.alloc);
3585 sf.pos = 0;
3586 di.fprintf_func = (fprintf_ftype) objdump_sprintf;
3587 di.stream = &sf;
3588
3589 objdump_print_symname (abfd, &di, sym);
3590
3591 /* Fetch jump information. */
3592 detected_jumps = disassemble_jumps
3593 (pinfo, paux->disassemble_fn,
3594 addr_offset, nextstop_offset,
3595 rel_offset, &rel_pp, rel_ppend);
3596
3597 /* Free symbol name. */
3598 free (sf.buffer);
3599 }
3600
3601 /* Add jumps to output. */
3602 disassemble_bytes (pinfo, paux->disassemble_fn, insns, data,
3603 addr_offset, nextstop_offset,
3604 rel_offset, &rel_pp, rel_ppend);
3605
3606 /* Free jumps. */
3607 while (detected_jumps)
3608 {
3609 detected_jumps = jump_info_free (detected_jumps);
3610 }
3611 }
3612
3613 addr_offset = nextstop_offset;
3614 sym = nextsym;
3615 }
3616
3617 free (data);
3618
3619 if (rel_ppstart != NULL)
3620 free (rel_ppstart);
3621 }
3622
3623 /* Disassemble the contents of an object file. */
3624
3625 static void
3626 disassemble_data (bfd *abfd)
3627 {
3628 struct disassemble_info disasm_info;
3629 struct objdump_disasm_info aux;
3630 long i;
3631
3632 print_files = NULL;
3633 prev_functionname = NULL;
3634 prev_line = -1;
3635 prev_discriminator = 0;
3636
3637 /* We make a copy of syms to sort. We don't want to sort syms
3638 because that will screw up the relocs. */
3639 sorted_symcount = symcount ? symcount : dynsymcount;
3640 sorted_syms = (asymbol **) xmalloc ((sorted_symcount + synthcount)
3641 * sizeof (asymbol *));
3642 if (sorted_symcount != 0)
3643 {
3644 memcpy (sorted_syms, symcount ? syms : dynsyms,
3645 sorted_symcount * sizeof (asymbol *));
3646
3647 sorted_symcount = remove_useless_symbols (sorted_syms, sorted_symcount);
3648 }
3649
3650 for (i = 0; i < synthcount; ++i)
3651 {
3652 sorted_syms[sorted_symcount] = synthsyms + i;
3653 ++sorted_symcount;
3654 }
3655
3656 init_disassemble_info (&disasm_info, stdout, (fprintf_ftype) fprintf);
3657
3658 disasm_info.application_data = (void *) &aux;
3659 aux.abfd = abfd;
3660 aux.require_sec = false;
3661 disasm_info.dynrelbuf = NULL;
3662 disasm_info.dynrelcount = 0;
3663 aux.reloc = NULL;
3664 aux.symbol = disasm_sym;
3665
3666 disasm_info.print_address_func = objdump_print_address;
3667 disasm_info.symbol_at_address_func = objdump_symbol_at_address;
3668
3669 if (machine != NULL)
3670 {
3671 const bfd_arch_info_type *inf = bfd_scan_arch (machine);
3672
3673 if (inf == NULL)
3674 fatal (_("can't use supplied machine %s"), machine);
3675
3676 abfd->arch_info = inf;
3677 }
3678
3679 if (endian != BFD_ENDIAN_UNKNOWN)
3680 {
3681 struct bfd_target *xvec;
3682
3683 xvec = (struct bfd_target *) xmalloc (sizeof (struct bfd_target));
3684 memcpy (xvec, abfd->xvec, sizeof (struct bfd_target));
3685 xvec->byteorder = endian;
3686 abfd->xvec = xvec;
3687 }
3688
3689 /* Use libopcodes to locate a suitable disassembler. */
3690 aux.disassemble_fn = disassembler (bfd_get_arch (abfd),
3691 bfd_big_endian (abfd),
3692 bfd_get_mach (abfd), abfd);
3693 if (!aux.disassemble_fn)
3694 {
3695 non_fatal (_("can't disassemble for architecture %s\n"),
3696 bfd_printable_arch_mach (bfd_get_arch (abfd), 0));
3697 exit_status = 1;
3698 return;
3699 }
3700
3701 disasm_info.flavour = bfd_get_flavour (abfd);
3702 disasm_info.arch = bfd_get_arch (abfd);
3703 disasm_info.mach = bfd_get_mach (abfd);
3704 disasm_info.disassembler_options = disassembler_options;
3705 disasm_info.octets_per_byte = bfd_octets_per_byte (abfd, NULL);
3706 disasm_info.skip_zeroes = DEFAULT_SKIP_ZEROES;
3707 disasm_info.skip_zeroes_at_end = DEFAULT_SKIP_ZEROES_AT_END;
3708 disasm_info.disassembler_needs_relocs = false;
3709
3710 if (bfd_big_endian (abfd))
3711 disasm_info.display_endian = disasm_info.endian = BFD_ENDIAN_BIG;
3712 else if (bfd_little_endian (abfd))
3713 disasm_info.display_endian = disasm_info.endian = BFD_ENDIAN_LITTLE;
3714 else
3715 /* ??? Aborting here seems too drastic. We could default to big or little
3716 instead. */
3717 disasm_info.endian = BFD_ENDIAN_UNKNOWN;
3718
3719 disasm_info.endian_code = disasm_info.endian;
3720
3721 /* Allow the target to customize the info structure. */
3722 disassemble_init_for_target (& disasm_info);
3723
3724 /* Pre-load the dynamic relocs as we may need them during the disassembly. */
3725 long relsize = bfd_get_dynamic_reloc_upper_bound (abfd);
3726
3727 if (relsize < 0 && dump_dynamic_reloc_info)
3728 bfd_fatal (bfd_get_filename (abfd));
3729
3730 if (relsize > 0)
3731 {
3732 disasm_info.dynrelbuf = (arelent **) xmalloc (relsize);
3733 disasm_info.dynrelcount
3734 = bfd_canonicalize_dynamic_reloc (abfd, disasm_info.dynrelbuf, dynsyms);
3735 if (disasm_info.dynrelcount < 0)
3736 bfd_fatal (bfd_get_filename (abfd));
3737
3738 /* Sort the relocs by address. */
3739 qsort (disasm_info.dynrelbuf, disasm_info.dynrelcount, sizeof (arelent *),
3740 compare_relocs);
3741 }
3742
3743 disasm_info.symtab = sorted_syms;
3744 disasm_info.symtab_size = sorted_symcount;
3745
3746 bfd_map_over_sections (abfd, disassemble_section, & disasm_info);
3747
3748 free (disasm_info.dynrelbuf);
3749 disasm_info.dynrelbuf = NULL;
3750 free (sorted_syms);
3751 disassemble_free_target (&disasm_info);
3752 }
3753 \f
3754 static bool
3755 load_specific_debug_section (enum dwarf_section_display_enum debug,
3756 asection *sec, void *file)
3757 {
3758 struct dwarf_section *section = &debug_displays [debug].section;
3759 bfd *abfd = (bfd *) file;
3760 bfd_byte *contents;
3761 bfd_size_type amt;
3762 size_t alloced;
3763 bool ret;
3764
3765 if (section->start != NULL)
3766 {
3767 /* If it is already loaded, do nothing. */
3768 if (streq (section->filename, bfd_get_filename (abfd)))
3769 return true;
3770 free (section->start);
3771 }
3772
3773 section->filename = bfd_get_filename (abfd);
3774 section->reloc_info = NULL;
3775 section->num_relocs = 0;
3776 section->address = bfd_section_vma (sec);
3777 section->size = bfd_section_size (sec);
3778 /* PR 24360: On 32-bit hosts sizeof (size_t) < sizeof (bfd_size_type). */
3779 alloced = amt = section->size + 1;
3780 if (alloced != amt || alloced == 0)
3781 {
3782 section->start = NULL;
3783 free_debug_section (debug);
3784 printf (_("\nSection '%s' has an invalid size: %#llx.\n"),
3785 sanitize_string (section->name),
3786 (unsigned long long) section->size);
3787 return false;
3788 }
3789
3790 section->start = contents = xmalloc (alloced);
3791 /* Ensure any string section has a terminating NUL. */
3792 section->start[section->size] = 0;
3793
3794 if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0
3795 && debug_displays [debug].relocate)
3796 {
3797 ret = bfd_simple_get_relocated_section_contents (abfd,
3798 sec,
3799 section->start,
3800 syms) != NULL;
3801 if (ret)
3802 {
3803 long reloc_size = bfd_get_reloc_upper_bound (abfd, sec);
3804
3805 if (reloc_size > 0)
3806 {
3807 unsigned long reloc_count;
3808 arelent **relocs;
3809
3810 relocs = (arelent **) xmalloc (reloc_size);
3811
3812 reloc_count = bfd_canonicalize_reloc (abfd, sec, relocs, NULL);
3813 if (reloc_count == 0)
3814 free (relocs);
3815 else
3816 {
3817 section->reloc_info = relocs;
3818 section->num_relocs = reloc_count;
3819 }
3820 }
3821 }
3822 }
3823 else
3824 ret = bfd_get_full_section_contents (abfd, sec, &contents);
3825
3826 if (!ret)
3827 {
3828 free_debug_section (debug);
3829 printf (_("\nCan't get contents for section '%s'.\n"),
3830 sanitize_string (section->name));
3831 return false;
3832 }
3833
3834 return true;
3835 }
3836
3837 bool
3838 reloc_at (struct dwarf_section * dsec, dwarf_vma offset)
3839 {
3840 arelent ** relocs;
3841 arelent * rp;
3842
3843 if (dsec == NULL || dsec->reloc_info == NULL)
3844 return false;
3845
3846 relocs = (arelent **) dsec->reloc_info;
3847
3848 for (; (rp = * relocs) != NULL; ++ relocs)
3849 if (rp->address == offset)
3850 return true;
3851
3852 return false;
3853 }
3854
3855 bool
3856 load_debug_section (enum dwarf_section_display_enum debug, void *file)
3857 {
3858 struct dwarf_section *section = &debug_displays [debug].section;
3859 bfd *abfd = (bfd *) file;
3860 asection *sec;
3861 const char *name;
3862
3863 if (!dump_any_debugging)
3864 return false;
3865
3866 /* If it is already loaded, do nothing. */
3867 if (section->start != NULL)
3868 {
3869 if (streq (section->filename, bfd_get_filename (abfd)))
3870 return true;
3871 }
3872 /* Locate the debug section. */
3873 name = section->uncompressed_name;
3874 sec = bfd_get_section_by_name (abfd, name);
3875 if (sec == NULL)
3876 {
3877 name = section->compressed_name;
3878 if (*name)
3879 sec = bfd_get_section_by_name (abfd, name);
3880 }
3881 if (sec == NULL)
3882 {
3883 name = section->xcoff_name;
3884 if (*name)
3885 sec = bfd_get_section_by_name (abfd, name);
3886 }
3887 if (sec == NULL)
3888 return false;
3889
3890 section->name = name;
3891 return load_specific_debug_section (debug, sec, file);
3892 }
3893
3894 void
3895 free_debug_section (enum dwarf_section_display_enum debug)
3896 {
3897 struct dwarf_section *section = &debug_displays [debug].section;
3898
3899 free ((char *) section->start);
3900 section->start = NULL;
3901 section->address = 0;
3902 section->size = 0;
3903 }
3904
3905 void
3906 close_debug_file (void * file)
3907 {
3908 bfd * abfd = (bfd *) file;
3909
3910 bfd_close (abfd);
3911 }
3912
3913 void *
3914 open_debug_file (const char * pathname)
3915 {
3916 bfd * data;
3917
3918 data = bfd_openr (pathname, NULL);
3919 if (data == NULL)
3920 return NULL;
3921
3922 if (! bfd_check_format (data, bfd_object))
3923 return NULL;
3924
3925 return data;
3926 }
3927
3928 #if HAVE_LIBDEBUGINFOD
3929 /* Return a hex string represention of the build-id. */
3930
3931 unsigned char *
3932 get_build_id (void * data)
3933 {
3934 unsigned i;
3935 char * build_id_str;
3936 bfd * abfd = (bfd *) data;
3937 const struct bfd_build_id * build_id;
3938
3939 build_id = abfd->build_id;
3940 if (build_id == NULL)
3941 return NULL;
3942
3943 build_id_str = malloc (build_id->size * 2 + 1);
3944 if (build_id_str == NULL)
3945 return NULL;
3946
3947 for (i = 0; i < build_id->size; i++)
3948 sprintf (build_id_str + (i * 2), "%02x", build_id->data[i]);
3949 build_id_str[build_id->size * 2] = '\0';
3950
3951 return (unsigned char *)build_id_str;
3952 }
3953 #endif /* HAVE_LIBDEBUGINFOD */
3954
3955 static void
3956 dump_dwarf_section (bfd *abfd, asection *section,
3957 void *arg)
3958 {
3959 const char *name = bfd_section_name (section);
3960 const char *match;
3961 int i;
3962 bool is_mainfile = *(bool *) arg;
3963
3964 if (*name == 0)
3965 return;
3966
3967 if (!is_mainfile && !process_links
3968 && (section->flags & SEC_DEBUGGING) == 0)
3969 return;
3970
3971 if (startswith (name, ".gnu.linkonce.wi."))
3972 match = ".debug_info";
3973 else
3974 match = name;
3975
3976 for (i = 0; i < max; i++)
3977 if ((strcmp (debug_displays [i].section.uncompressed_name, match) == 0
3978 || strcmp (debug_displays [i].section.compressed_name, match) == 0
3979 || strcmp (debug_displays [i].section.xcoff_name, match) == 0)
3980 && debug_displays [i].enabled != NULL
3981 && *debug_displays [i].enabled)
3982 {
3983 struct dwarf_section *sec = &debug_displays [i].section;
3984
3985 if (strcmp (sec->uncompressed_name, match) == 0)
3986 sec->name = sec->uncompressed_name;
3987 else if (strcmp (sec->compressed_name, match) == 0)
3988 sec->name = sec->compressed_name;
3989 else
3990 sec->name = sec->xcoff_name;
3991 if (load_specific_debug_section ((enum dwarf_section_display_enum) i,
3992 section, abfd))
3993 {
3994 debug_displays [i].display (sec, abfd);
3995
3996 if (i != info && i != abbrev)
3997 free_debug_section ((enum dwarf_section_display_enum) i);
3998 }
3999 break;
4000 }
4001 }
4002
4003 /* Dump the dwarf debugging information. */
4004
4005 static void
4006 dump_dwarf (bfd *abfd, bool is_mainfile)
4007 {
4008 /* The byte_get pointer should have been set at the start of dump_bfd(). */
4009 if (byte_get == NULL)
4010 {
4011 warn (_("File %s does not contain any dwarf debug information\n"),
4012 bfd_get_filename (abfd));
4013 return;
4014 }
4015
4016 switch (bfd_get_arch (abfd))
4017 {
4018 case bfd_arch_s12z:
4019 /* S12Z has a 24 bit address space. But the only known
4020 producer of dwarf_info encodes addresses into 32 bits. */
4021 eh_addr_size = 4;
4022 break;
4023
4024 default:
4025 eh_addr_size = bfd_arch_bits_per_address (abfd) / 8;
4026 break;
4027 }
4028
4029 init_dwarf_regnames_by_bfd_arch_and_mach (bfd_get_arch (abfd),
4030 bfd_get_mach (abfd));
4031
4032 bfd_map_over_sections (abfd, dump_dwarf_section, (void *) &is_mainfile);
4033 }
4034 \f
4035 /* Read ABFD's stabs section STABSECT_NAME, and return a pointer to
4036 it. Return NULL on failure. */
4037
4038 static bfd_byte *
4039 read_section_stabs (bfd *abfd, const char *sect_name, bfd_size_type *size_ptr,
4040 bfd_size_type *entsize_ptr)
4041 {
4042 asection *stabsect;
4043 bfd_byte *contents;
4044
4045 stabsect = bfd_get_section_by_name (abfd, sect_name);
4046 if (stabsect == NULL)
4047 {
4048 printf (_("No %s section present\n\n"),
4049 sanitize_string (sect_name));
4050 return false;
4051 }
4052
4053 if (!bfd_malloc_and_get_section (abfd, stabsect, &contents))
4054 {
4055 non_fatal (_("reading %s section of %s failed: %s"),
4056 sect_name, bfd_get_filename (abfd),
4057 bfd_errmsg (bfd_get_error ()));
4058 exit_status = 1;
4059 free (contents);
4060 return NULL;
4061 }
4062
4063 *size_ptr = bfd_section_size (stabsect);
4064 if (entsize_ptr)
4065 *entsize_ptr = stabsect->entsize;
4066
4067 return contents;
4068 }
4069
4070 /* Stabs entries use a 12 byte format:
4071 4 byte string table index
4072 1 byte stab type
4073 1 byte stab other field
4074 2 byte stab desc field
4075 4 byte stab value
4076 FIXME: This will have to change for a 64 bit object format. */
4077
4078 #define STRDXOFF (0)
4079 #define TYPEOFF (4)
4080 #define OTHEROFF (5)
4081 #define DESCOFF (6)
4082 #define VALOFF (8)
4083 #define STABSIZE (12)
4084
4085 /* Print ABFD's stabs section STABSECT_NAME (in `stabs'),
4086 using string table section STRSECT_NAME (in `strtab'). */
4087
4088 static void
4089 print_section_stabs (bfd *abfd,
4090 const char *stabsect_name,
4091 unsigned *string_offset_ptr)
4092 {
4093 int i;
4094 unsigned file_string_table_offset = 0;
4095 unsigned next_file_string_table_offset = *string_offset_ptr;
4096 bfd_byte *stabp, *stabs_end;
4097
4098 stabp = stabs;
4099 stabs_end = stabp + stab_size;
4100
4101 printf (_("Contents of %s section:\n\n"), sanitize_string (stabsect_name));
4102 printf ("Symnum n_type n_othr n_desc n_value n_strx String\n");
4103
4104 /* Loop through all symbols and print them.
4105
4106 We start the index at -1 because there is a dummy symbol on
4107 the front of stabs-in-{coff,elf} sections that supplies sizes. */
4108 for (i = -1; stabp <= stabs_end - STABSIZE; stabp += STABSIZE, i++)
4109 {
4110 const char *name;
4111 unsigned long strx;
4112 unsigned char type, other;
4113 unsigned short desc;
4114 bfd_vma value;
4115
4116 strx = bfd_h_get_32 (abfd, stabp + STRDXOFF);
4117 type = bfd_h_get_8 (abfd, stabp + TYPEOFF);
4118 other = bfd_h_get_8 (abfd, stabp + OTHEROFF);
4119 desc = bfd_h_get_16 (abfd, stabp + DESCOFF);
4120 value = bfd_h_get_32 (abfd, stabp + VALOFF);
4121
4122 printf ("\n%-6d ", i);
4123 /* Either print the stab name, or, if unnamed, print its number
4124 again (makes consistent formatting for tools like awk). */
4125 name = bfd_get_stab_name (type);
4126 if (name != NULL)
4127 printf ("%-6s", sanitize_string (name));
4128 else if (type == N_UNDF)
4129 printf ("HdrSym");
4130 else
4131 printf ("%-6d", type);
4132 printf (" %-6d %-6d ", other, desc);
4133 bfd_printf_vma (abfd, value);
4134 printf (" %-6lu", strx);
4135
4136 /* Symbols with type == 0 (N_UNDF) specify the length of the
4137 string table associated with this file. We use that info
4138 to know how to relocate the *next* file's string table indices. */
4139 if (type == N_UNDF)
4140 {
4141 file_string_table_offset = next_file_string_table_offset;
4142 next_file_string_table_offset += value;
4143 }
4144 else
4145 {
4146 bfd_size_type amt = strx + file_string_table_offset;
4147
4148 /* Using the (possibly updated) string table offset, print the
4149 string (if any) associated with this symbol. */
4150 if (amt < stabstr_size)
4151 /* PR 17512: file: 079-79389-0.001:0.1.
4152 FIXME: May need to sanitize this string before displaying. */
4153 printf (" %.*s", (int)(stabstr_size - amt), strtab + amt);
4154 else
4155 printf (" *");
4156 }
4157 }
4158 printf ("\n\n");
4159 *string_offset_ptr = next_file_string_table_offset;
4160 }
4161
4162 typedef struct
4163 {
4164 const char * section_name;
4165 const char * string_section_name;
4166 unsigned string_offset;
4167 }
4168 stab_section_names;
4169
4170 static void
4171 find_stabs_section (bfd *abfd, asection *section, void *names)
4172 {
4173 int len;
4174 stab_section_names * sought = (stab_section_names *) names;
4175
4176 /* Check for section names for which stabsect_name is a prefix, to
4177 handle .stab.N, etc. */
4178 len = strlen (sought->section_name);
4179
4180 /* If the prefix matches, and the files section name ends with a
4181 nul or a digit, then we match. I.e., we want either an exact
4182 match or a section followed by a number. */
4183 if (strncmp (sought->section_name, section->name, len) == 0
4184 && (section->name[len] == 0
4185 || (section->name[len] == '.' && ISDIGIT (section->name[len + 1]))))
4186 {
4187 if (strtab == NULL)
4188 strtab = read_section_stabs (abfd, sought->string_section_name,
4189 &stabstr_size, NULL);
4190
4191 if (strtab)
4192 {
4193 stabs = read_section_stabs (abfd, section->name, &stab_size, NULL);
4194 if (stabs)
4195 print_section_stabs (abfd, section->name, &sought->string_offset);
4196 }
4197 }
4198 }
4199
4200 static void
4201 dump_stabs_section (bfd *abfd, char *stabsect_name, char *strsect_name)
4202 {
4203 stab_section_names s;
4204
4205 s.section_name = stabsect_name;
4206 s.string_section_name = strsect_name;
4207 s.string_offset = 0;
4208
4209 bfd_map_over_sections (abfd, find_stabs_section, & s);
4210
4211 free (strtab);
4212 strtab = NULL;
4213 }
4214
4215 /* Dump the any sections containing stabs debugging information. */
4216
4217 static void
4218 dump_stabs (bfd *abfd)
4219 {
4220 dump_stabs_section (abfd, ".stab", ".stabstr");
4221 dump_stabs_section (abfd, ".stab.excl", ".stab.exclstr");
4222 dump_stabs_section (abfd, ".stab.index", ".stab.indexstr");
4223
4224 /* For Darwin. */
4225 dump_stabs_section (abfd, "LC_SYMTAB.stabs", "LC_SYMTAB.stabstr");
4226
4227 dump_stabs_section (abfd, "$GDB_SYMBOLS$", "$GDB_STRINGS$");
4228 }
4229 \f
4230 static void
4231 dump_bfd_header (bfd *abfd)
4232 {
4233 char *comma = "";
4234
4235 printf (_("architecture: %s, "),
4236 bfd_printable_arch_mach (bfd_get_arch (abfd),
4237 bfd_get_mach (abfd)));
4238 printf (_("flags 0x%08x:\n"), abfd->flags & ~BFD_FLAGS_FOR_BFD_USE_MASK);
4239
4240 #define PF(x, y) if (abfd->flags & x) {printf ("%s%s", comma, y); comma=", ";}
4241 PF (HAS_RELOC, "HAS_RELOC");
4242 PF (EXEC_P, "EXEC_P");
4243 PF (HAS_LINENO, "HAS_LINENO");
4244 PF (HAS_DEBUG, "HAS_DEBUG");
4245 PF (HAS_SYMS, "HAS_SYMS");
4246 PF (HAS_LOCALS, "HAS_LOCALS");
4247 PF (DYNAMIC, "DYNAMIC");
4248 PF (WP_TEXT, "WP_TEXT");
4249 PF (D_PAGED, "D_PAGED");
4250 PF (BFD_IS_RELAXABLE, "BFD_IS_RELAXABLE");
4251 printf (_("\nstart address 0x"));
4252 bfd_printf_vma (abfd, abfd->start_address);
4253 printf ("\n");
4254 }
4255 \f
4256
4257 #ifdef ENABLE_LIBCTF
4258 /* Formatting callback function passed to ctf_dump. Returns either the pointer
4259 it is passed, or a pointer to newly-allocated storage, in which case
4260 dump_ctf() will free it when it no longer needs it. */
4261
4262 static char *
4263 dump_ctf_indent_lines (ctf_sect_names_t sect ATTRIBUTE_UNUSED,
4264 char *s, void *arg)
4265 {
4266 const char *blanks = arg;
4267 char *new_s;
4268
4269 if (asprintf (&new_s, "%s%s", blanks, s) < 0)
4270 return s;
4271 return new_s;
4272 }
4273
4274 /* Make a ctfsect suitable for ctf_bfdopen_ctfsect(). */
4275 static ctf_sect_t
4276 make_ctfsect (const char *name, bfd_byte *data,
4277 bfd_size_type size)
4278 {
4279 ctf_sect_t ctfsect;
4280
4281 ctfsect.cts_name = name;
4282 ctfsect.cts_entsize = 1;
4283 ctfsect.cts_size = size;
4284 ctfsect.cts_data = data;
4285
4286 return ctfsect;
4287 }
4288
4289 /* Dump CTF errors/warnings. */
4290 static void
4291 dump_ctf_errs (ctf_dict_t *fp)
4292 {
4293 ctf_next_t *it = NULL;
4294 char *errtext;
4295 int is_warning;
4296 int err;
4297
4298 /* Dump accumulated errors and warnings. */
4299 while ((errtext = ctf_errwarning_next (fp, &it, &is_warning, &err)) != NULL)
4300 {
4301 non_fatal (_("%s: %s"), is_warning ? _("warning"): _("error"),
4302 errtext);
4303 free (errtext);
4304 }
4305 if (err != ECTF_NEXT_END)
4306 {
4307 non_fatal (_("CTF error: cannot get CTF errors: `%s'"),
4308 ctf_errmsg (err));
4309 }
4310 }
4311
4312 /* Dump one CTF archive member. */
4313
4314 static void
4315 dump_ctf_archive_member (ctf_dict_t *ctf, const char *name, ctf_dict_t *parent,
4316 size_t member)
4317 {
4318 const char *things[] = {"Header", "Labels", "Data objects",
4319 "Function objects", "Variables", "Types", "Strings",
4320 ""};
4321 const char **thing;
4322 size_t i;
4323
4324 /* Don't print out the name of the default-named archive member if it appears
4325 first in the list. The name .ctf appears everywhere, even for things that
4326 aren't really archives, so printing it out is liable to be confusing; also,
4327 the common case by far is for only one archive member to exist, and hiding
4328 it in that case seems worthwhile. */
4329
4330 if (strcmp (name, ".ctf") != 0 || member != 0)
4331 printf (_("\nCTF archive member: %s:\n"), sanitize_string (name));
4332
4333 if (ctf_parent_name (ctf) != NULL)
4334 ctf_import (ctf, parent);
4335
4336 for (i = 0, thing = things; *thing[0]; thing++, i++)
4337 {
4338 ctf_dump_state_t *s = NULL;
4339 char *item;
4340
4341 printf ("\n %s:\n", *thing);
4342 while ((item = ctf_dump (ctf, &s, i, dump_ctf_indent_lines,
4343 (void *) " ")) != NULL)
4344 {
4345 printf ("%s\n", item);
4346 free (item);
4347 }
4348
4349 if (ctf_errno (ctf))
4350 {
4351 non_fatal (_("Iteration failed: %s, %s"), *thing,
4352 ctf_errmsg (ctf_errno (ctf)));
4353 break;
4354 }
4355 }
4356
4357 dump_ctf_errs (ctf);
4358 }
4359
4360 /* Dump the CTF debugging information. */
4361
4362 static void
4363 dump_ctf (bfd *abfd, const char *sect_name, const char *parent_name)
4364 {
4365 ctf_archive_t *ctfa = NULL;
4366 bfd_byte *ctfdata = NULL;
4367 bfd_size_type ctfsize;
4368 ctf_sect_t ctfsect;
4369 ctf_dict_t *parent;
4370 ctf_dict_t *fp;
4371 ctf_next_t *i = NULL;
4372 const char *name;
4373 size_t member = 0;
4374 int err;
4375
4376 if (sect_name == NULL)
4377 sect_name = ".ctf";
4378
4379 if ((ctfdata = read_section_stabs (abfd, sect_name, &ctfsize, NULL)) == NULL)
4380 bfd_fatal (bfd_get_filename (abfd));
4381
4382 /* Load the CTF file and dump it. Preload the parent dict, since it will
4383 need to be imported into every child in turn. */
4384
4385 ctfsect = make_ctfsect (sect_name, ctfdata, ctfsize);
4386 if ((ctfa = ctf_bfdopen_ctfsect (abfd, &ctfsect, &err)) == NULL)
4387 {
4388 dump_ctf_errs (NULL);
4389 non_fatal (_("CTF open failure: %s"), ctf_errmsg (err));
4390 bfd_fatal (bfd_get_filename (abfd));
4391 }
4392
4393 if ((parent = ctf_dict_open (ctfa, parent_name, &err)) == NULL)
4394 {
4395 dump_ctf_errs (NULL);
4396 non_fatal (_("CTF open failure: %s"), ctf_errmsg (err));
4397 bfd_fatal (bfd_get_filename (abfd));
4398 }
4399
4400 printf (_("Contents of CTF section %s:\n"), sanitize_string (sect_name));
4401
4402 while ((fp = ctf_archive_next (ctfa, &i, &name, 0, &err)) != NULL)
4403 dump_ctf_archive_member (fp, name, parent, member++);
4404 if (err != ECTF_NEXT_END)
4405 {
4406 dump_ctf_errs (NULL);
4407 non_fatal (_("CTF archive member open failure: %s"), ctf_errmsg (err));
4408 bfd_fatal (bfd_get_filename (abfd));
4409 }
4410 ctf_dict_close (parent);
4411 ctf_close (ctfa);
4412 free (ctfdata);
4413 }
4414 #else
4415 static void
4416 dump_ctf (bfd *abfd ATTRIBUTE_UNUSED, const char *sect_name ATTRIBUTE_UNUSED,
4417 const char *parent_name ATTRIBUTE_UNUSED) {}
4418 #endif
4419
4420 \f
4421 static void
4422 dump_bfd_private_header (bfd *abfd)
4423 {
4424 if (!bfd_print_private_bfd_data (abfd, stdout))
4425 non_fatal (_("warning: private headers incomplete: %s"),
4426 bfd_errmsg (bfd_get_error ()));
4427 }
4428
4429 static void
4430 dump_target_specific (bfd *abfd)
4431 {
4432 const struct objdump_private_desc * const *desc;
4433 struct objdump_private_option *opt;
4434 char *e, *b;
4435
4436 /* Find the desc. */
4437 for (desc = objdump_private_vectors; *desc != NULL; desc++)
4438 if ((*desc)->filter (abfd))
4439 break;
4440
4441 if (*desc == NULL)
4442 {
4443 non_fatal (_("option -P/--private not supported by this file"));
4444 return;
4445 }
4446
4447 /* Clear all options. */
4448 for (opt = (*desc)->options; opt->name; opt++)
4449 opt->selected = false;
4450
4451 /* Decode options. */
4452 b = dump_private_options;
4453 do
4454 {
4455 e = strchr (b, ',');
4456
4457 if (e)
4458 *e = 0;
4459
4460 for (opt = (*desc)->options; opt->name; opt++)
4461 if (strcmp (opt->name, b) == 0)
4462 {
4463 opt->selected = true;
4464 break;
4465 }
4466 if (opt->name == NULL)
4467 non_fatal (_("target specific dump '%s' not supported"), b);
4468
4469 if (e)
4470 {
4471 *e = ',';
4472 b = e + 1;
4473 }
4474 }
4475 while (e != NULL);
4476
4477 /* Dump. */
4478 (*desc)->dump (abfd);
4479 }
4480 \f
4481 /* Display a section in hexadecimal format with associated characters.
4482 Each line prefixed by the zero padded address. */
4483
4484 static void
4485 dump_section (bfd *abfd, asection *section, void *dummy ATTRIBUTE_UNUSED)
4486 {
4487 bfd_byte *data = NULL;
4488 bfd_size_type datasize;
4489 bfd_vma addr_offset;
4490 bfd_vma start_offset;
4491 bfd_vma stop_offset;
4492 unsigned int opb = bfd_octets_per_byte (abfd, section);
4493 /* Bytes per line. */
4494 const int onaline = 16;
4495 char buf[64];
4496 int count;
4497 int width;
4498
4499 if (! process_section_p (section))
4500 return;
4501
4502 if ((section->flags & SEC_HAS_CONTENTS) == 0)
4503 return;
4504
4505 if ((datasize = bfd_section_size (section)) == 0)
4506 return;
4507
4508 /* Compute the address range to display. */
4509 if (start_address == (bfd_vma) -1
4510 || start_address < section->vma)
4511 start_offset = 0;
4512 else
4513 start_offset = start_address - section->vma;
4514
4515 if (stop_address == (bfd_vma) -1)
4516 stop_offset = datasize / opb;
4517 else
4518 {
4519 if (stop_address < section->vma)
4520 stop_offset = 0;
4521 else
4522 stop_offset = stop_address - section->vma;
4523
4524 if (stop_offset > datasize / opb)
4525 stop_offset = datasize / opb;
4526 }
4527
4528 if (start_offset >= stop_offset)
4529 return;
4530
4531 printf (_("Contents of section %s:"), sanitize_string (section->name));
4532 if (display_file_offsets)
4533 printf (_(" (Starting at file offset: 0x%lx)"),
4534 (unsigned long) (section->filepos + start_offset));
4535 printf ("\n");
4536
4537 if (!bfd_get_full_section_contents (abfd, section, &data))
4538 {
4539 non_fatal (_("Reading section %s failed because: %s"),
4540 section->name, bfd_errmsg (bfd_get_error ()));
4541 return;
4542 }
4543
4544 width = 4;
4545
4546 bfd_sprintf_vma (abfd, buf, start_offset + section->vma);
4547 if (strlen (buf) >= sizeof (buf))
4548 abort ();
4549
4550 count = 0;
4551 while (buf[count] == '0' && buf[count+1] != '\0')
4552 count++;
4553 count = strlen (buf) - count;
4554 if (count > width)
4555 width = count;
4556
4557 bfd_sprintf_vma (abfd, buf, stop_offset + section->vma - 1);
4558 if (strlen (buf) >= sizeof (buf))
4559 abort ();
4560
4561 count = 0;
4562 while (buf[count] == '0' && buf[count+1] != '\0')
4563 count++;
4564 count = strlen (buf) - count;
4565 if (count > width)
4566 width = count;
4567
4568 for (addr_offset = start_offset;
4569 addr_offset < stop_offset; addr_offset += onaline / opb)
4570 {
4571 bfd_size_type j;
4572
4573 bfd_sprintf_vma (abfd, buf, (addr_offset + section->vma));
4574 count = strlen (buf);
4575 if ((size_t) count >= sizeof (buf))
4576 abort ();
4577
4578 putchar (' ');
4579 while (count < width)
4580 {
4581 putchar ('0');
4582 count++;
4583 }
4584 fputs (buf + count - width, stdout);
4585 putchar (' ');
4586
4587 for (j = addr_offset * opb;
4588 j < addr_offset * opb + onaline; j++)
4589 {
4590 if (j < stop_offset * opb)
4591 printf ("%02x", (unsigned) (data[j]));
4592 else
4593 printf (" ");
4594 if ((j & 3) == 3)
4595 printf (" ");
4596 }
4597
4598 printf (" ");
4599 for (j = addr_offset * opb;
4600 j < addr_offset * opb + onaline; j++)
4601 {
4602 if (j >= stop_offset * opb)
4603 printf (" ");
4604 else
4605 printf ("%c", ISPRINT (data[j]) ? data[j] : '.');
4606 }
4607 putchar ('\n');
4608 }
4609 free (data);
4610 }
4611
4612 /* Actually display the various requested regions. */
4613
4614 static void
4615 dump_data (bfd *abfd)
4616 {
4617 bfd_map_over_sections (abfd, dump_section, NULL);
4618 }
4619
4620 /* Should perhaps share code and display with nm? */
4621
4622 static void
4623 dump_symbols (bfd *abfd ATTRIBUTE_UNUSED, bool dynamic)
4624 {
4625 asymbol **current;
4626 long max_count;
4627 long count;
4628
4629 if (dynamic)
4630 {
4631 current = dynsyms;
4632 max_count = dynsymcount;
4633 printf ("DYNAMIC SYMBOL TABLE:\n");
4634 }
4635 else
4636 {
4637 current = syms;
4638 max_count = symcount;
4639 printf ("SYMBOL TABLE:\n");
4640 }
4641
4642 if (max_count == 0)
4643 printf (_("no symbols\n"));
4644
4645 for (count = 0; count < max_count; count++)
4646 {
4647 bfd *cur_bfd;
4648
4649 if (*current == NULL)
4650 printf (_("no information for symbol number %ld\n"), count);
4651
4652 else if ((cur_bfd = bfd_asymbol_bfd (*current)) == NULL)
4653 printf (_("could not determine the type of symbol number %ld\n"),
4654 count);
4655
4656 else if (process_section_p ((* current)->section)
4657 && (dump_special_syms
4658 || !bfd_is_target_special_symbol (cur_bfd, *current)))
4659 {
4660 const char *name = (*current)->name;
4661
4662 if (do_demangle && name != NULL && *name != '\0')
4663 {
4664 char *alloc;
4665
4666 /* If we want to demangle the name, we demangle it
4667 here, and temporarily clobber it while calling
4668 bfd_print_symbol. FIXME: This is a gross hack. */
4669 alloc = bfd_demangle (cur_bfd, name, demangle_flags);
4670 if (alloc != NULL)
4671 (*current)->name = alloc;
4672 bfd_print_symbol (cur_bfd, stdout, *current,
4673 bfd_print_symbol_all);
4674 if (alloc != NULL)
4675 {
4676 (*current)->name = name;
4677 free (alloc);
4678 }
4679 }
4680 else if (unicode_display != unicode_default
4681 && name != NULL && *name != '\0')
4682 {
4683 const char * sanitized_name;
4684
4685 /* If we want to sanitize the name, we do it here, and
4686 temporarily clobber it while calling bfd_print_symbol.
4687 FIXME: This is a gross hack. */
4688 sanitized_name = sanitize_string (name);
4689 if (sanitized_name != name)
4690 (*current)->name = sanitized_name;
4691 else
4692 sanitized_name = NULL;
4693 bfd_print_symbol (cur_bfd, stdout, *current,
4694 bfd_print_symbol_all);
4695 if (sanitized_name != NULL)
4696 (*current)->name = name;
4697 }
4698 else
4699 bfd_print_symbol (cur_bfd, stdout, *current,
4700 bfd_print_symbol_all);
4701 printf ("\n");
4702 }
4703
4704 current++;
4705 }
4706 printf ("\n\n");
4707 }
4708 \f
4709 static void
4710 dump_reloc_set (bfd *abfd, asection *sec, arelent **relpp, long relcount)
4711 {
4712 arelent **p;
4713 char *last_filename, *last_functionname;
4714 unsigned int last_line;
4715 unsigned int last_discriminator;
4716
4717 /* Get column headers lined up reasonably. */
4718 {
4719 static int width;
4720
4721 if (width == 0)
4722 {
4723 char buf[30];
4724
4725 bfd_sprintf_vma (abfd, buf, (bfd_vma) -1);
4726 width = strlen (buf) - 7;
4727 }
4728 printf ("OFFSET %*s TYPE %*s VALUE \n", width, "", 12, "");
4729 }
4730
4731 last_filename = NULL;
4732 last_functionname = NULL;
4733 last_line = 0;
4734 last_discriminator = 0;
4735
4736 for (p = relpp; relcount && *p != NULL; p++, relcount--)
4737 {
4738 arelent *q = *p;
4739 const char *filename, *functionname;
4740 unsigned int linenumber;
4741 unsigned int discriminator;
4742 const char *sym_name;
4743 const char *section_name;
4744 bfd_vma addend2 = 0;
4745
4746 if (start_address != (bfd_vma) -1
4747 && q->address < start_address)
4748 continue;
4749 if (stop_address != (bfd_vma) -1
4750 && q->address > stop_address)
4751 continue;
4752
4753 if (with_line_numbers
4754 && sec != NULL
4755 && bfd_find_nearest_line_discriminator (abfd, sec, syms, q->address,
4756 &filename, &functionname,
4757 &linenumber, &discriminator))
4758 {
4759 if (functionname != NULL
4760 && (last_functionname == NULL
4761 || strcmp (functionname, last_functionname) != 0))
4762 {
4763 printf ("%s():\n", sanitize_string (functionname));
4764 if (last_functionname != NULL)
4765 free (last_functionname);
4766 last_functionname = xstrdup (functionname);
4767 }
4768
4769 if (linenumber > 0
4770 && (linenumber != last_line
4771 || (filename != NULL
4772 && last_filename != NULL
4773 && filename_cmp (filename, last_filename) != 0)
4774 || (discriminator != last_discriminator)))
4775 {
4776 if (discriminator > 0)
4777 printf ("%s:%u\n", filename == NULL ? "???" :
4778 sanitize_string (filename), linenumber);
4779 else
4780 printf ("%s:%u (discriminator %u)\n",
4781 filename == NULL ? "???" : sanitize_string (filename),
4782 linenumber, discriminator);
4783 last_line = linenumber;
4784 last_discriminator = discriminator;
4785 if (last_filename != NULL)
4786 free (last_filename);
4787 if (filename == NULL)
4788 last_filename = NULL;
4789 else
4790 last_filename = xstrdup (filename);
4791 }
4792 }
4793
4794 if (q->sym_ptr_ptr && *q->sym_ptr_ptr)
4795 {
4796 sym_name = (*(q->sym_ptr_ptr))->name;
4797 section_name = (*(q->sym_ptr_ptr))->section->name;
4798 }
4799 else
4800 {
4801 sym_name = NULL;
4802 section_name = NULL;
4803 }
4804
4805 bfd_printf_vma (abfd, q->address);
4806 if (q->howto == NULL)
4807 printf (" *unknown* ");
4808 else if (q->howto->name)
4809 {
4810 const char *name = q->howto->name;
4811
4812 /* R_SPARC_OLO10 relocations contain two addends.
4813 But because 'arelent' lacks enough storage to
4814 store them both, the 64-bit ELF Sparc backend
4815 records this as two relocations. One R_SPARC_LO10
4816 and one R_SPARC_13, both pointing to the same
4817 address. This is merely so that we have some
4818 place to store both addend fields.
4819
4820 Undo this transformation, otherwise the output
4821 will be confusing. */
4822 if (abfd->xvec->flavour == bfd_target_elf_flavour
4823 && elf_tdata (abfd)->elf_header->e_machine == EM_SPARCV9
4824 && relcount > 1
4825 && !strcmp (q->howto->name, "R_SPARC_LO10"))
4826 {
4827 arelent *q2 = *(p + 1);
4828 if (q2 != NULL
4829 && q2->howto
4830 && q->address == q2->address
4831 && !strcmp (q2->howto->name, "R_SPARC_13"))
4832 {
4833 name = "R_SPARC_OLO10";
4834 addend2 = q2->addend;
4835 p++;
4836 }
4837 }
4838 printf (" %-16s ", name);
4839 }
4840 else
4841 printf (" %-16d ", q->howto->type);
4842
4843 if (sym_name)
4844 {
4845 objdump_print_symname (abfd, NULL, *q->sym_ptr_ptr);
4846 }
4847 else
4848 {
4849 if (section_name == NULL)
4850 section_name = "*unknown*";
4851 printf ("[%s]", sanitize_string (section_name));
4852 }
4853
4854 if (q->addend)
4855 {
4856 bfd_signed_vma addend = q->addend;
4857 if (addend < 0)
4858 {
4859 printf ("-0x");
4860 addend = -addend;
4861 }
4862 else
4863 printf ("+0x");
4864 bfd_printf_vma (abfd, addend);
4865 }
4866 if (addend2)
4867 {
4868 printf ("+0x");
4869 bfd_printf_vma (abfd, addend2);
4870 }
4871
4872 printf ("\n");
4873 }
4874
4875 if (last_filename != NULL)
4876 free (last_filename);
4877 if (last_functionname != NULL)
4878 free (last_functionname);
4879 }
4880
4881 static void
4882 dump_relocs_in_section (bfd *abfd,
4883 asection *section,
4884 void *dummy ATTRIBUTE_UNUSED)
4885 {
4886 arelent **relpp = NULL;
4887 long relcount;
4888 long relsize;
4889
4890 if ( bfd_is_abs_section (section)
4891 || bfd_is_und_section (section)
4892 || bfd_is_com_section (section)
4893 || (! process_section_p (section))
4894 || ((section->flags & SEC_RELOC) == 0))
4895 return;
4896
4897 printf ("RELOCATION RECORDS FOR [%s]:", sanitize_string (section->name));
4898
4899 relsize = bfd_get_reloc_upper_bound (abfd, section);
4900 if (relsize == 0)
4901 {
4902 printf (" (none)\n\n");
4903 return;
4904 }
4905
4906 if (relsize < 0)
4907 relcount = relsize;
4908 else
4909 {
4910 relpp = (arelent **) xmalloc (relsize);
4911 relcount = bfd_canonicalize_reloc (abfd, section, relpp, syms);
4912 }
4913
4914 if (relcount < 0)
4915 {
4916 printf ("\n");
4917 non_fatal (_("failed to read relocs in: %s"),
4918 sanitize_string (bfd_get_filename (abfd)));
4919 bfd_fatal (_("error message was"));
4920 }
4921 else if (relcount == 0)
4922 printf (" (none)\n\n");
4923 else
4924 {
4925 printf ("\n");
4926 dump_reloc_set (abfd, section, relpp, relcount);
4927 printf ("\n\n");
4928 }
4929 free (relpp);
4930 }
4931
4932 static void
4933 dump_relocs (bfd *abfd)
4934 {
4935 bfd_map_over_sections (abfd, dump_relocs_in_section, NULL);
4936 }
4937
4938 static void
4939 dump_dynamic_relocs (bfd *abfd)
4940 {
4941 long relsize;
4942 arelent **relpp;
4943 long relcount;
4944
4945 relsize = bfd_get_dynamic_reloc_upper_bound (abfd);
4946 if (relsize < 0)
4947 bfd_fatal (bfd_get_filename (abfd));
4948
4949 printf ("DYNAMIC RELOCATION RECORDS");
4950
4951 if (relsize == 0)
4952 printf (" (none)\n\n");
4953 else
4954 {
4955 relpp = (arelent **) xmalloc (relsize);
4956 relcount = bfd_canonicalize_dynamic_reloc (abfd, relpp, dynsyms);
4957
4958 if (relcount < 0)
4959 bfd_fatal (bfd_get_filename (abfd));
4960 else if (relcount == 0)
4961 printf (" (none)\n\n");
4962 else
4963 {
4964 printf ("\n");
4965 dump_reloc_set (abfd, NULL, relpp, relcount);
4966 printf ("\n\n");
4967 }
4968 free (relpp);
4969 }
4970 }
4971
4972 /* Creates a table of paths, to search for source files. */
4973
4974 static void
4975 add_include_path (const char *path)
4976 {
4977 if (path[0] == 0)
4978 return;
4979 include_path_count++;
4980 include_paths = (const char **)
4981 xrealloc (include_paths, include_path_count * sizeof (*include_paths));
4982 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
4983 if (path[1] == ':' && path[2] == 0)
4984 path = concat (path, ".", (const char *) 0);
4985 #endif
4986 include_paths[include_path_count - 1] = path;
4987 }
4988
4989 static void
4990 adjust_addresses (bfd *abfd ATTRIBUTE_UNUSED,
4991 asection *section,
4992 void *arg)
4993 {
4994 if ((section->flags & SEC_DEBUGGING) == 0)
4995 {
4996 bool *has_reloc_p = (bool *) arg;
4997 section->vma += adjust_section_vma;
4998 if (*has_reloc_p)
4999 section->lma += adjust_section_vma;
5000 }
5001 }
5002
5003 /* Return the sign-extended form of an ARCH_SIZE sized VMA. */
5004
5005 static bfd_vma
5006 sign_extend_address (bfd *abfd ATTRIBUTE_UNUSED,
5007 bfd_vma vma,
5008 unsigned arch_size)
5009 {
5010 bfd_vma mask;
5011 mask = (bfd_vma) 1 << (arch_size - 1);
5012 return (((vma & ((mask << 1) - 1)) ^ mask) - mask);
5013 }
5014
5015 /* Dump selected contents of ABFD. */
5016
5017 static void
5018 dump_bfd (bfd *abfd, bool is_mainfile)
5019 {
5020 const struct elf_backend_data * bed;
5021
5022 if (bfd_big_endian (abfd))
5023 byte_get = byte_get_big_endian;
5024 else if (bfd_little_endian (abfd))
5025 byte_get = byte_get_little_endian;
5026 else
5027 byte_get = NULL;
5028
5029 /* Load any separate debug information files.
5030 We do this now and without checking do_follow_links because separate
5031 debug info files may contain symbol tables that we will need when
5032 displaying information about the main file. Any memory allocated by
5033 load_separate_debug_files will be released when we call
5034 free_debug_memory below.
5035
5036 The test on is_mainfile is there because the chain of separate debug
5037 info files is a global variable shared by all invocations of dump_bfd. */
5038 if (byte_get != NULL && is_mainfile)
5039 {
5040 load_separate_debug_files (abfd, bfd_get_filename (abfd));
5041
5042 /* If asked to do so, recursively dump the separate files. */
5043 if (do_follow_links)
5044 {
5045 separate_info * i;
5046
5047 for (i = first_separate_info; i != NULL; i = i->next)
5048 dump_bfd (i->handle, false);
5049 }
5050 }
5051
5052 /* Adjust user-specified start and stop limits for targets that use
5053 signed addresses. */
5054 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
5055 && (bed = get_elf_backend_data (abfd)) != NULL
5056 && bed->sign_extend_vma)
5057 {
5058 start_address = sign_extend_address (abfd, start_address,
5059 bed->s->arch_size);
5060 stop_address = sign_extend_address (abfd, stop_address,
5061 bed->s->arch_size);
5062 }
5063
5064 /* If we are adjusting section VMA's, change them all now. Changing
5065 the BFD information is a hack. However, we must do it, or
5066 bfd_find_nearest_line will not do the right thing. */
5067 if (adjust_section_vma != 0)
5068 {
5069 bool has_reloc = (abfd->flags & HAS_RELOC);
5070 bfd_map_over_sections (abfd, adjust_addresses, &has_reloc);
5071 }
5072
5073 if (is_mainfile || process_links)
5074 {
5075 if (! dump_debugging_tags && ! suppress_bfd_header)
5076 printf (_("\n%s: file format %s\n"),
5077 sanitize_string (bfd_get_filename (abfd)),
5078 abfd->xvec->name);
5079 if (dump_ar_hdrs)
5080 print_arelt_descr (stdout, abfd, true, false);
5081 if (dump_file_header)
5082 dump_bfd_header (abfd);
5083 if (dump_private_headers)
5084 dump_bfd_private_header (abfd);
5085 if (dump_private_options != NULL)
5086 dump_target_specific (abfd);
5087 if (! dump_debugging_tags && ! suppress_bfd_header)
5088 putchar ('\n');
5089 }
5090
5091 if (dump_symtab
5092 || dump_reloc_info
5093 || disassemble
5094 || dump_debugging
5095 || dump_dwarf_section_info)
5096 {
5097 syms = slurp_symtab (abfd);
5098
5099 /* If following links, load any symbol tables from the linked files as well. */
5100 if (do_follow_links && is_mainfile)
5101 {
5102 separate_info * i;
5103
5104 for (i = first_separate_info; i != NULL; i = i->next)
5105 {
5106 asymbol ** extra_syms;
5107 long old_symcount = symcount;
5108
5109 extra_syms = slurp_symtab (i->handle);
5110
5111 if (extra_syms)
5112 {
5113 if (old_symcount == 0)
5114 {
5115 syms = extra_syms;
5116 }
5117 else
5118 {
5119 syms = xrealloc (syms, ((symcount + old_symcount + 1)
5120 * sizeof (asymbol *)));
5121 memcpy (syms + old_symcount,
5122 extra_syms,
5123 (symcount + 1) * sizeof (asymbol *));
5124 }
5125 }
5126
5127 symcount += old_symcount;
5128 }
5129 }
5130 }
5131
5132 if (is_mainfile || process_links)
5133 {
5134 if (dump_section_headers)
5135 dump_headers (abfd);
5136
5137 if (dump_dynamic_symtab || dump_dynamic_reloc_info
5138 || (disassemble && bfd_get_dynamic_symtab_upper_bound (abfd) > 0))
5139 dynsyms = slurp_dynamic_symtab (abfd);
5140
5141 if (disassemble)
5142 {
5143 synthcount = bfd_get_synthetic_symtab (abfd, symcount, syms,
5144 dynsymcount, dynsyms,
5145 &synthsyms);
5146 if (synthcount < 0)
5147 synthcount = 0;
5148 }
5149
5150 if (dump_symtab)
5151 dump_symbols (abfd, false);
5152 if (dump_dynamic_symtab)
5153 dump_symbols (abfd, true);
5154 }
5155 if (dump_dwarf_section_info)
5156 dump_dwarf (abfd, is_mainfile);
5157 if (is_mainfile || process_links)
5158 {
5159 if (dump_ctf_section_info)
5160 dump_ctf (abfd, dump_ctf_section_name, dump_ctf_parent_name);
5161 if (dump_stab_section_info)
5162 dump_stabs (abfd);
5163 if (dump_reloc_info && ! disassemble)
5164 dump_relocs (abfd);
5165 if (dump_dynamic_reloc_info && ! disassemble)
5166 dump_dynamic_relocs (abfd);
5167 if (dump_section_contents)
5168 dump_data (abfd);
5169 if (disassemble)
5170 disassemble_data (abfd);
5171 }
5172
5173 if (dump_debugging)
5174 {
5175 void *dhandle;
5176
5177 dhandle = read_debugging_info (abfd, syms, symcount, true);
5178 if (dhandle != NULL)
5179 {
5180 if (!print_debugging_info (stdout, dhandle, abfd, syms,
5181 bfd_demangle,
5182 dump_debugging_tags != 0))
5183 {
5184 non_fatal (_("%s: printing debugging information failed"),
5185 bfd_get_filename (abfd));
5186 exit_status = 1;
5187 }
5188
5189 free (dhandle);
5190 }
5191 /* PR 6483: If there was no STABS debug info in the file, try
5192 DWARF instead. */
5193 else if (! dump_dwarf_section_info)
5194 {
5195 dwarf_select_sections_all ();
5196 dump_dwarf (abfd, is_mainfile);
5197 }
5198 }
5199
5200 if (syms)
5201 {
5202 free (syms);
5203 syms = NULL;
5204 }
5205
5206 if (dynsyms)
5207 {
5208 free (dynsyms);
5209 dynsyms = NULL;
5210 }
5211
5212 if (synthsyms)
5213 {
5214 free (synthsyms);
5215 synthsyms = NULL;
5216 }
5217
5218 symcount = 0;
5219 dynsymcount = 0;
5220 synthcount = 0;
5221
5222 if (is_mainfile)
5223 free_debug_memory ();
5224 }
5225
5226 static void
5227 display_object_bfd (bfd *abfd)
5228 {
5229 char **matching;
5230
5231 if (bfd_check_format_matches (abfd, bfd_object, &matching))
5232 {
5233 dump_bfd (abfd, true);
5234 return;
5235 }
5236
5237 if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
5238 {
5239 nonfatal (bfd_get_filename (abfd));
5240 list_matching_formats (matching);
5241 free (matching);
5242 return;
5243 }
5244
5245 if (bfd_get_error () != bfd_error_file_not_recognized)
5246 {
5247 nonfatal (bfd_get_filename (abfd));
5248 return;
5249 }
5250
5251 if (bfd_check_format_matches (abfd, bfd_core, &matching))
5252 {
5253 dump_bfd (abfd, true);
5254 return;
5255 }
5256
5257 nonfatal (bfd_get_filename (abfd));
5258
5259 if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
5260 {
5261 list_matching_formats (matching);
5262 free (matching);
5263 }
5264 }
5265
5266 static void
5267 display_any_bfd (bfd *file, int level)
5268 {
5269 /* Decompress sections unless dumping the section contents. */
5270 if (!dump_section_contents)
5271 file->flags |= BFD_DECOMPRESS;
5272
5273 /* If the file is an archive, process all of its elements. */
5274 if (bfd_check_format (file, bfd_archive))
5275 {
5276 bfd *arfile = NULL;
5277 bfd *last_arfile = NULL;
5278
5279 if (level == 0)
5280 printf (_("In archive %s:\n"), sanitize_string (bfd_get_filename (file)));
5281 else if (level > 100)
5282 {
5283 /* Prevent corrupted files from spinning us into an
5284 infinite loop. 100 is an arbitrary heuristic. */
5285 fatal (_("Archive nesting is too deep"));
5286 return;
5287 }
5288 else
5289 printf (_("In nested archive %s:\n"),
5290 sanitize_string (bfd_get_filename (file)));
5291
5292 for (;;)
5293 {
5294 bfd_set_error (bfd_error_no_error);
5295
5296 arfile = bfd_openr_next_archived_file (file, arfile);
5297 if (arfile == NULL)
5298 {
5299 if (bfd_get_error () != bfd_error_no_more_archived_files)
5300 nonfatal (bfd_get_filename (file));
5301 break;
5302 }
5303
5304 display_any_bfd (arfile, level + 1);
5305
5306 if (last_arfile != NULL)
5307 {
5308 bfd_close (last_arfile);
5309 /* PR 17512: file: ac585d01. */
5310 if (arfile == last_arfile)
5311 {
5312 last_arfile = NULL;
5313 break;
5314 }
5315 }
5316 last_arfile = arfile;
5317 }
5318
5319 if (last_arfile != NULL)
5320 bfd_close (last_arfile);
5321 }
5322 else
5323 display_object_bfd (file);
5324 }
5325
5326 static void
5327 display_file (char *filename, char *target, bool last_file)
5328 {
5329 bfd *file;
5330
5331 if (get_file_size (filename) < 1)
5332 {
5333 exit_status = 1;
5334 return;
5335 }
5336
5337 file = bfd_openr (filename, target);
5338 if (file == NULL)
5339 {
5340 nonfatal (filename);
5341 return;
5342 }
5343
5344 display_any_bfd (file, 0);
5345
5346 /* This is an optimization to improve the speed of objdump, especially when
5347 dumping a file with lots of associated debug informatiom. Calling
5348 bfd_close on such a file can take a non-trivial amount of time as there
5349 are lots of lists to walk and buffers to free. This is only really
5350 necessary however if we are about to load another file and we need the
5351 memory back. Otherwise, if we are about to exit, then we can save (a lot
5352 of) time by only doing a quick close, and allowing the OS to reclaim the
5353 memory for us. */
5354 if (! last_file)
5355 bfd_close (file);
5356 else
5357 bfd_close_all_done (file);
5358 }
5359 \f
5360 int
5361 main (int argc, char **argv)
5362 {
5363 int c;
5364 char *target = default_target;
5365 bool seenflag = false;
5366
5367 #ifdef HAVE_LC_MESSAGES
5368 setlocale (LC_MESSAGES, "");
5369 #endif
5370 setlocale (LC_CTYPE, "");
5371
5372 bindtextdomain (PACKAGE, LOCALEDIR);
5373 textdomain (PACKAGE);
5374
5375 program_name = *argv;
5376 xmalloc_set_program_name (program_name);
5377 bfd_set_error_program_name (program_name);
5378
5379 START_PROGRESS (program_name, 0);
5380
5381 expandargv (&argc, &argv);
5382
5383 if (bfd_init () != BFD_INIT_MAGIC)
5384 fatal (_("fatal error: libbfd ABI mismatch"));
5385 set_default_bfd_target ();
5386
5387 while ((c = getopt_long (argc, argv,
5388 "CDE:FGHI:LM:P:RSTU:VW::ab:defghij:lm:prstvwxz",
5389 long_options, (int *) 0))
5390 != EOF)
5391 {
5392 switch (c)
5393 {
5394 case 0:
5395 break; /* We've been given a long option. */
5396 case 'm':
5397 machine = optarg;
5398 break;
5399 case 'M':
5400 {
5401 char *options;
5402 if (disassembler_options)
5403 /* Ignore potential memory leak for now. */
5404 options = concat (disassembler_options, ",",
5405 optarg, (const char *) NULL);
5406 else
5407 options = optarg;
5408 disassembler_options = remove_whitespace_and_extra_commas (options);
5409 }
5410 break;
5411 case 'j':
5412 add_only (optarg);
5413 break;
5414 case 'F':
5415 display_file_offsets = true;
5416 break;
5417 case 'l':
5418 with_line_numbers = true;
5419 break;
5420 case 'b':
5421 target = optarg;
5422 break;
5423 case 'C':
5424 do_demangle = true;
5425 if (optarg != NULL)
5426 {
5427 enum demangling_styles style;
5428
5429 style = cplus_demangle_name_to_style (optarg);
5430 if (style == unknown_demangling)
5431 fatal (_("unknown demangling style `%s'"),
5432 optarg);
5433
5434 cplus_demangle_set_style (style);
5435 }
5436 break;
5437 case OPTION_RECURSE_LIMIT:
5438 demangle_flags &= ~ DMGL_NO_RECURSE_LIMIT;
5439 break;
5440 case OPTION_NO_RECURSE_LIMIT:
5441 demangle_flags |= DMGL_NO_RECURSE_LIMIT;
5442 break;
5443 case 'w':
5444 do_wide = wide_output = true;
5445 break;
5446 case OPTION_ADJUST_VMA:
5447 adjust_section_vma = parse_vma (optarg, "--adjust-vma");
5448 break;
5449 case OPTION_START_ADDRESS:
5450 start_address = parse_vma (optarg, "--start-address");
5451 if ((stop_address != (bfd_vma) -1) && stop_address <= start_address)
5452 fatal (_("error: the start address should be before the end address"));
5453 break;
5454 case OPTION_STOP_ADDRESS:
5455 stop_address = parse_vma (optarg, "--stop-address");
5456 if ((start_address != (bfd_vma) -1) && stop_address <= start_address)
5457 fatal (_("error: the stop address should be after the start address"));
5458 break;
5459 case OPTION_PREFIX:
5460 prefix = optarg;
5461 prefix_length = strlen (prefix);
5462 /* Remove an unnecessary trailing '/' */
5463 while (IS_DIR_SEPARATOR (prefix[prefix_length - 1]))
5464 prefix_length--;
5465 break;
5466 case OPTION_PREFIX_STRIP:
5467 prefix_strip = atoi (optarg);
5468 if (prefix_strip < 0)
5469 fatal (_("error: prefix strip must be non-negative"));
5470 break;
5471 case OPTION_INSN_WIDTH:
5472 insn_width = strtoul (optarg, NULL, 0);
5473 if (insn_width <= 0)
5474 fatal (_("error: instruction width must be positive"));
5475 break;
5476 case OPTION_INLINES:
5477 unwind_inlines = true;
5478 break;
5479 case OPTION_VISUALIZE_JUMPS:
5480 visualize_jumps = true;
5481 color_output = false;
5482 extended_color_output = false;
5483 if (optarg != NULL)
5484 {
5485 if (streq (optarg, "color"))
5486 color_output = true;
5487 else if (streq (optarg, "extended-color"))
5488 {
5489 color_output = true;
5490 extended_color_output = true;
5491 }
5492 else if (streq (optarg, "off"))
5493 visualize_jumps = false;
5494 else
5495 nonfatal (_("unrecognized argument to --visualize-option"));
5496 }
5497 break;
5498 case 'E':
5499 if (strcmp (optarg, "B") == 0)
5500 endian = BFD_ENDIAN_BIG;
5501 else if (strcmp (optarg, "L") == 0)
5502 endian = BFD_ENDIAN_LITTLE;
5503 else
5504 {
5505 nonfatal (_("unrecognized -E option"));
5506 usage (stderr, 1);
5507 }
5508 break;
5509 case OPTION_ENDIAN:
5510 if (strncmp (optarg, "big", strlen (optarg)) == 0)
5511 endian = BFD_ENDIAN_BIG;
5512 else if (strncmp (optarg, "little", strlen (optarg)) == 0)
5513 endian = BFD_ENDIAN_LITTLE;
5514 else
5515 {
5516 non_fatal (_("unrecognized --endian type `%s'"), optarg);
5517 exit_status = 1;
5518 usage (stderr, 1);
5519 }
5520 break;
5521
5522 case 'f':
5523 dump_file_header = true;
5524 seenflag = true;
5525 break;
5526 case 'i':
5527 formats_info = true;
5528 seenflag = true;
5529 break;
5530 case 'I':
5531 add_include_path (optarg);
5532 break;
5533 case 'p':
5534 dump_private_headers = true;
5535 seenflag = true;
5536 break;
5537 case 'P':
5538 dump_private_options = optarg;
5539 seenflag = true;
5540 break;
5541 case 'x':
5542 dump_private_headers = true;
5543 dump_symtab = true;
5544 dump_reloc_info = true;
5545 dump_file_header = true;
5546 dump_ar_hdrs = true;
5547 dump_section_headers = true;
5548 seenflag = true;
5549 break;
5550 case 't':
5551 dump_symtab = true;
5552 seenflag = true;
5553 break;
5554 case 'T':
5555 dump_dynamic_symtab = true;
5556 seenflag = true;
5557 break;
5558 case 'd':
5559 disassemble = true;
5560 seenflag = true;
5561 disasm_sym = optarg;
5562 break;
5563 case 'z':
5564 disassemble_zeroes = true;
5565 break;
5566 case 'D':
5567 disassemble = true;
5568 disassemble_all = true;
5569 seenflag = true;
5570 break;
5571 case 'S':
5572 disassemble = true;
5573 with_source_code = true;
5574 seenflag = true;
5575 break;
5576 case OPTION_SOURCE_COMMENT:
5577 disassemble = true;
5578 with_source_code = true;
5579 seenflag = true;
5580 if (optarg)
5581 source_comment = xstrdup (sanitize_string (optarg));
5582 else
5583 source_comment = xstrdup ("# ");
5584 break;
5585 case 'g':
5586 dump_debugging = 1;
5587 seenflag = true;
5588 break;
5589 case 'e':
5590 dump_debugging = 1;
5591 dump_debugging_tags = 1;
5592 do_demangle = true;
5593 seenflag = true;
5594 break;
5595 case 'L':
5596 process_links = true;
5597 do_follow_links = true;
5598 break;
5599 case 'W':
5600 dump_dwarf_section_info = true;
5601 seenflag = true;
5602 if (optarg)
5603 dwarf_select_sections_by_letters (optarg);
5604 else
5605 dwarf_select_sections_all ();
5606 break;
5607 case OPTION_DWARF:
5608 dump_dwarf_section_info = true;
5609 seenflag = true;
5610 if (optarg)
5611 dwarf_select_sections_by_names (optarg);
5612 else
5613 dwarf_select_sections_all ();
5614 break;
5615 case OPTION_DWARF_DEPTH:
5616 {
5617 char *cp;
5618 dwarf_cutoff_level = strtoul (optarg, & cp, 0);
5619 }
5620 break;
5621 case OPTION_DWARF_START:
5622 {
5623 char *cp;
5624 dwarf_start_die = strtoul (optarg, & cp, 0);
5625 suppress_bfd_header = 1;
5626 }
5627 break;
5628 case OPTION_DWARF_CHECK:
5629 dwarf_check = true;
5630 break;
5631 #ifdef ENABLE_LIBCTF
5632 case OPTION_CTF:
5633 dump_ctf_section_info = true;
5634 if (optarg)
5635 dump_ctf_section_name = xstrdup (optarg);
5636 seenflag = true;
5637 break;
5638 case OPTION_CTF_PARENT:
5639 dump_ctf_parent_name = xstrdup (optarg);
5640 break;
5641 #endif
5642 case 'G':
5643 dump_stab_section_info = true;
5644 seenflag = true;
5645 break;
5646 case 's':
5647 dump_section_contents = true;
5648 seenflag = true;
5649 break;
5650 case 'r':
5651 dump_reloc_info = true;
5652 seenflag = true;
5653 break;
5654 case 'R':
5655 dump_dynamic_reloc_info = true;
5656 seenflag = true;
5657 break;
5658 case 'a':
5659 dump_ar_hdrs = true;
5660 seenflag = true;
5661 break;
5662 case 'h':
5663 dump_section_headers = true;
5664 seenflag = true;
5665 break;
5666 case 'v':
5667 case 'V':
5668 show_version = true;
5669 seenflag = true;
5670 break;
5671
5672 case 'U':
5673 if (streq (optarg, "default") || streq (optarg, "d"))
5674 unicode_display = unicode_default;
5675 else if (streq (optarg, "locale") || streq (optarg, "l"))
5676 unicode_display = unicode_locale;
5677 else if (streq (optarg, "escape") || streq (optarg, "e"))
5678 unicode_display = unicode_escape;
5679 else if (streq (optarg, "invalid") || streq (optarg, "i"))
5680 unicode_display = unicode_invalid;
5681 else if (streq (optarg, "hex") || streq (optarg, "x"))
5682 unicode_display = unicode_hex;
5683 else if (streq (optarg, "highlight") || streq (optarg, "h"))
5684 unicode_display = unicode_highlight;
5685 else
5686 fatal (_("invalid argument to -U/--unicode: %s"), optarg);
5687 break;
5688
5689 case 'H':
5690 usage (stdout, 0);
5691 /* No need to set seenflag or to break - usage() does not return. */
5692 default:
5693 usage (stderr, 1);
5694 }
5695 }
5696
5697 if (show_version)
5698 print_version ("objdump");
5699
5700 if (!seenflag)
5701 usage (stderr, 2);
5702
5703 dump_any_debugging = (dump_debugging
5704 || dump_dwarf_section_info
5705 || process_links);
5706
5707 if (formats_info)
5708 exit_status = display_info ();
5709 else
5710 {
5711 if (optind == argc)
5712 display_file ("a.out", target, true);
5713 else
5714 for (; optind < argc;)
5715 {
5716 display_file (argv[optind], target, optind == argc - 1);
5717 optind++;
5718 }
5719 }
5720
5721 free_only_list ();
5722 free (dump_ctf_section_name);
5723 free (dump_ctf_parent_name);
5724 free ((void *) source_comment);
5725
5726 END_PROGRESS (program_name);
5727
5728 return exit_status;
5729 }