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