objdump/opcodes: add syntax highlighting to disassembler output
[binutils-gdb.git] / gdb / disasm.c
1 /* Disassemble support for GDB.
2
3 Copyright (C) 2000-2022 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include "target.h"
23 #include "value.h"
24 #include "ui-out.h"
25 #include "disasm.h"
26 #include "gdbcore.h"
27 #include "gdbcmd.h"
28 #include "dis-asm.h"
29 #include "source.h"
30 #include "safe-ctype.h"
31 #include <algorithm>
32 #include "gdbsupport/gdb_optional.h"
33 #include "valprint.h"
34 #include "cli/cli-style.h"
35
36 /* Disassemble functions.
37 FIXME: We should get rid of all the duplicate code in gdb that does
38 the same thing: disassemble_command() and the gdbtk variation. */
39
40 /* This variable is used to hold the prospective disassembler_options value
41 which is set by the "set disassembler_options" command. */
42 static std::string prospective_options;
43
44 /* This structure is used to store line number information for the
45 deprecated /m option.
46 We need a different sort of line table from the normal one cuz we can't
47 depend upon implicit line-end pc's for lines to do the
48 reordering in this function. */
49
50 struct deprecated_dis_line_entry
51 {
52 int line;
53 CORE_ADDR start_pc;
54 CORE_ADDR end_pc;
55 };
56
57 /* This Structure is used to store line number information.
58 We need a different sort of line table from the normal one cuz we can't
59 depend upon implicit line-end pc's for lines to do the
60 reordering in this function. */
61
62 struct dis_line_entry
63 {
64 struct symtab *symtab;
65 int line;
66 };
67
68 /* Hash function for dis_line_entry. */
69
70 static hashval_t
71 hash_dis_line_entry (const void *item)
72 {
73 const struct dis_line_entry *dle = (const struct dis_line_entry *) item;
74
75 return htab_hash_pointer (dle->symtab) + dle->line;
76 }
77
78 /* Equal function for dis_line_entry. */
79
80 static int
81 eq_dis_line_entry (const void *item_lhs, const void *item_rhs)
82 {
83 const struct dis_line_entry *lhs = (const struct dis_line_entry *) item_lhs;
84 const struct dis_line_entry *rhs = (const struct dis_line_entry *) item_rhs;
85
86 return (lhs->symtab == rhs->symtab
87 && lhs->line == rhs->line);
88 }
89
90 /* Create the table to manage lines for mixed source/disassembly. */
91
92 static htab_t
93 allocate_dis_line_table (void)
94 {
95 return htab_create_alloc (41,
96 hash_dis_line_entry, eq_dis_line_entry,
97 xfree, xcalloc, xfree);
98 }
99
100 /* Add a new dis_line_entry containing SYMTAB and LINE to TABLE. */
101
102 static void
103 add_dis_line_entry (htab_t table, struct symtab *symtab, int line)
104 {
105 void **slot;
106 struct dis_line_entry dle, *dlep;
107
108 dle.symtab = symtab;
109 dle.line = line;
110 slot = htab_find_slot (table, &dle, INSERT);
111 if (*slot == NULL)
112 {
113 dlep = XNEW (struct dis_line_entry);
114 dlep->symtab = symtab;
115 dlep->line = line;
116 *slot = dlep;
117 }
118 }
119
120 /* Return non-zero if SYMTAB, LINE are in TABLE. */
121
122 static int
123 line_has_code_p (htab_t table, struct symtab *symtab, int line)
124 {
125 struct dis_line_entry dle;
126
127 dle.symtab = symtab;
128 dle.line = line;
129 return htab_find (table, &dle) != NULL;
130 }
131
132 /* Wrapper of target_read_code. */
133
134 int
135 gdb_disassembler::dis_asm_read_memory (bfd_vma memaddr, gdb_byte *myaddr,
136 unsigned int len,
137 struct disassemble_info *info)
138 {
139 return target_read_code (memaddr, myaddr, len);
140 }
141
142 /* Wrapper of memory_error. */
143
144 void
145 gdb_disassembler::dis_asm_memory_error (int err, bfd_vma memaddr,
146 struct disassemble_info *info)
147 {
148 gdb_disassembler *self
149 = static_cast<gdb_disassembler *>(info->application_data);
150
151 self->m_err_memaddr.emplace (memaddr);
152 }
153
154 /* Wrapper of print_address. */
155
156 void
157 gdb_disassembler::dis_asm_print_address (bfd_vma addr,
158 struct disassemble_info *info)
159 {
160 gdb_disassembler *self
161 = static_cast<gdb_disassembler *>(info->application_data);
162
163 print_address (self->arch (), addr, self->stream ());
164 }
165
166 /* Format disassembler output to STREAM. */
167
168 int
169 gdb_disassembler::dis_asm_fprintf (void *stream, const char *format, ...)
170 {
171 va_list args;
172
173 va_start (args, format);
174 gdb_vprintf ((struct ui_file *) stream, format, args);
175 va_end (args);
176 /* Something non -ve. */
177 return 0;
178 }
179
180 /* See disasm.h. */
181
182 int
183 gdb_disassembler::dis_asm_styled_fprintf (void *stream,
184 enum disassembler_style style,
185 const char *format, ...)
186 {
187 va_list args;
188
189 va_start (args, format);
190 vfprintf_filtered ((struct ui_file *) stream, format, args);
191 va_end (args);
192 /* Something non -ve. */
193 return 0;
194 }
195
196 static bool
197 line_is_less_than (const deprecated_dis_line_entry &mle1,
198 const deprecated_dis_line_entry &mle2)
199 {
200 bool val;
201
202 /* End of sequence markers have a line number of 0 but don't want to
203 be sorted to the head of the list, instead sort by PC. */
204 if (mle1.line == 0 || mle2.line == 0)
205 {
206 if (mle1.start_pc != mle2.start_pc)
207 val = mle1.start_pc < mle2.start_pc;
208 else
209 val = mle1.line < mle2.line;
210 }
211 else
212 {
213 if (mle1.line != mle2.line)
214 val = mle1.line < mle2.line;
215 else
216 val = mle1.start_pc < mle2.start_pc;
217 }
218 return val;
219 }
220
221 /* See disasm.h. */
222
223 int
224 gdb_pretty_print_disassembler::pretty_print_insn (const struct disasm_insn *insn,
225 gdb_disassembly_flags flags)
226 {
227 /* parts of the symbolic representation of the address */
228 int unmapped;
229 int offset;
230 int line;
231 int size;
232 CORE_ADDR pc;
233 struct gdbarch *gdbarch = arch ();
234
235 {
236 ui_out_emit_tuple tuple_emitter (m_uiout, NULL);
237 pc = insn->addr;
238
239 if (insn->number != 0)
240 {
241 m_uiout->field_unsigned ("insn-number", insn->number);
242 m_uiout->text ("\t");
243 }
244
245 if ((flags & DISASSEMBLY_SPECULATIVE) != 0)
246 {
247 if (insn->is_speculative)
248 {
249 m_uiout->field_string ("is-speculative", "?");
250
251 /* The speculative execution indication overwrites the first
252 character of the PC prefix.
253 We assume a PC prefix length of 3 characters. */
254 if ((flags & DISASSEMBLY_OMIT_PC) == 0)
255 m_uiout->text (pc_prefix (pc) + 1);
256 else
257 m_uiout->text (" ");
258 }
259 else if ((flags & DISASSEMBLY_OMIT_PC) == 0)
260 m_uiout->text (pc_prefix (pc));
261 else
262 m_uiout->text (" ");
263 }
264 else if ((flags & DISASSEMBLY_OMIT_PC) == 0)
265 m_uiout->text (pc_prefix (pc));
266 m_uiout->field_core_addr ("address", gdbarch, pc);
267
268 std::string name, filename;
269 bool omit_fname = ((flags & DISASSEMBLY_OMIT_FNAME) != 0);
270 if (!build_address_symbolic (gdbarch, pc, false, omit_fname, &name,
271 &offset, &filename, &line, &unmapped))
272 {
273 /* We don't care now about line, filename and unmapped. But we might in
274 the future. */
275 m_uiout->text (" <");
276 if (!omit_fname)
277 m_uiout->field_string ("func-name", name,
278 function_name_style.style ());
279 /* For negative offsets, avoid displaying them as +-N; the sign of
280 the offset takes the place of the "+" here. */
281 if (offset >= 0)
282 m_uiout->text ("+");
283 m_uiout->field_signed ("offset", offset);
284 m_uiout->text (">:\t");
285 }
286 else
287 m_uiout->text (":\t");
288
289 /* Clear the buffer into which we will disassemble the instruction. */
290 m_insn_stb.clear ();
291
292 /* A helper function to write the M_INSN_STB buffer, followed by a
293 newline. This can be called in a couple of situations. */
294 auto write_out_insn_buffer = [&] ()
295 {
296 m_uiout->field_stream ("inst", m_insn_stb);
297 m_uiout->text ("\n");
298 };
299
300 try
301 {
302 /* Now we can disassemble the instruction. If the disassembler
303 returns a negative value this indicates an error and is handled
304 within the print_insn call, resulting in an exception being
305 thrown. Returning zero makes no sense, as this indicates we
306 disassembled something successfully, but it was something of no
307 size? */
308 size = m_di.print_insn (pc);
309 gdb_assert (size > 0);
310 }
311 catch (const gdb_exception &ex)
312 {
313 /* An exception was thrown while disassembling the instruction.
314 However, the disassembler might still have written something
315 out, so ensure that we flush the instruction buffer before
316 rethrowing the exception. We can't perform this write from an
317 object destructor as the write itself might throw an exception
318 if the pager kicks in, and the user selects quit. */
319 write_out_insn_buffer ();
320 throw ex;
321 }
322
323 if (flags & DISASSEMBLY_RAW_INSN)
324 {
325 CORE_ADDR end_pc;
326 bfd_byte data;
327 const char *spacer = "";
328
329 /* Build the opcodes using a temporary stream so we can
330 write them out in a single go for the MI. */
331 m_opcode_stb.clear ();
332
333 end_pc = pc + size;
334
335 for (;pc < end_pc; ++pc)
336 {
337 read_code (pc, &data, 1);
338 m_opcode_stb.printf ("%s%02x", spacer, (unsigned) data);
339 spacer = " ";
340 }
341
342 m_uiout->field_stream ("opcodes", m_opcode_stb);
343 m_uiout->text ("\t");
344 }
345
346 /* Disassembly was a success, write out the instruction buffer. */
347 write_out_insn_buffer ();
348 }
349
350 return size;
351 }
352
353 static int
354 dump_insns (struct gdbarch *gdbarch,
355 struct ui_out *uiout, CORE_ADDR low, CORE_ADDR high,
356 int how_many, gdb_disassembly_flags flags, CORE_ADDR *end_pc)
357 {
358 struct disasm_insn insn;
359 int num_displayed = 0;
360
361 memset (&insn, 0, sizeof (insn));
362 insn.addr = low;
363
364 gdb_pretty_print_disassembler disasm (gdbarch, uiout);
365
366 while (insn.addr < high && (how_many < 0 || num_displayed < how_many))
367 {
368 int size;
369
370 size = disasm.pretty_print_insn (&insn, flags);
371 if (size <= 0)
372 break;
373
374 ++num_displayed;
375 insn.addr += size;
376
377 /* Allow user to bail out with ^C. */
378 QUIT;
379 }
380
381 if (end_pc != NULL)
382 *end_pc = insn.addr;
383
384 return num_displayed;
385 }
386
387 /* The idea here is to present a source-O-centric view of a
388 function to the user. This means that things are presented
389 in source order, with (possibly) out of order assembly
390 immediately following.
391
392 N.B. This view is deprecated. */
393
394 static void
395 do_mixed_source_and_assembly_deprecated
396 (struct gdbarch *gdbarch, struct ui_out *uiout,
397 struct symtab *symtab,
398 CORE_ADDR low, CORE_ADDR high,
399 int how_many, gdb_disassembly_flags flags)
400 {
401 int newlines = 0;
402 int nlines;
403 struct linetable_entry *le;
404 struct deprecated_dis_line_entry *mle;
405 struct symtab_and_line sal;
406 int i;
407 int out_of_order = 0;
408 int next_line = 0;
409 int num_displayed = 0;
410 print_source_lines_flags psl_flags = 0;
411
412 gdb_assert (symtab != nullptr && symtab->linetable () != nullptr);
413
414 nlines = symtab->linetable ()->nitems;
415 le = symtab->linetable ()->item;
416
417 if (flags & DISASSEMBLY_FILENAME)
418 psl_flags |= PRINT_SOURCE_LINES_FILENAME;
419
420 mle = (struct deprecated_dis_line_entry *)
421 alloca (nlines * sizeof (struct deprecated_dis_line_entry));
422
423 /* Copy linetable entries for this function into our data
424 structure, creating end_pc's and setting out_of_order as
425 appropriate. */
426
427 /* First, skip all the preceding functions. */
428
429 for (i = 0; i < nlines - 1 && le[i].pc < low; i++);
430
431 /* Now, copy all entries before the end of this function. */
432
433 for (; i < nlines - 1 && le[i].pc < high; i++)
434 {
435 if (le[i].line == le[i + 1].line && le[i].pc == le[i + 1].pc)
436 continue; /* Ignore duplicates. */
437
438 /* Skip any end-of-function markers. */
439 if (le[i].line == 0)
440 continue;
441
442 mle[newlines].line = le[i].line;
443 if (le[i].line > le[i + 1].line)
444 out_of_order = 1;
445 mle[newlines].start_pc = le[i].pc;
446 mle[newlines].end_pc = le[i + 1].pc;
447 newlines++;
448 }
449
450 /* If we're on the last line, and it's part of the function,
451 then we need to get the end pc in a special way. */
452
453 if (i == nlines - 1 && le[i].pc < high)
454 {
455 mle[newlines].line = le[i].line;
456 mle[newlines].start_pc = le[i].pc;
457 sal = find_pc_line (le[i].pc, 0);
458 mle[newlines].end_pc = sal.end;
459 newlines++;
460 }
461
462 /* Now, sort mle by line #s (and, then by addresses within lines). */
463
464 if (out_of_order)
465 std::sort (mle, mle + newlines, line_is_less_than);
466
467 /* Now, for each line entry, emit the specified lines (unless
468 they have been emitted before), followed by the assembly code
469 for that line. */
470
471 ui_out_emit_list asm_insns_list (uiout, "asm_insns");
472
473 gdb::optional<ui_out_emit_tuple> outer_tuple_emitter;
474 gdb::optional<ui_out_emit_list> inner_list_emitter;
475
476 for (i = 0; i < newlines; i++)
477 {
478 /* Print out everything from next_line to the current line. */
479 if (mle[i].line >= next_line)
480 {
481 if (next_line != 0)
482 {
483 /* Just one line to print. */
484 if (next_line == mle[i].line)
485 {
486 outer_tuple_emitter.emplace (uiout, "src_and_asm_line");
487 print_source_lines (symtab, next_line, mle[i].line + 1, psl_flags);
488 }
489 else
490 {
491 /* Several source lines w/o asm instructions associated. */
492 for (; next_line < mle[i].line; next_line++)
493 {
494 ui_out_emit_tuple tuple_emitter (uiout,
495 "src_and_asm_line");
496 print_source_lines (symtab, next_line, next_line + 1,
497 psl_flags);
498 ui_out_emit_list temp_list_emitter (uiout,
499 "line_asm_insn");
500 }
501 /* Print the last line and leave list open for
502 asm instructions to be added. */
503 outer_tuple_emitter.emplace (uiout, "src_and_asm_line");
504 print_source_lines (symtab, next_line, mle[i].line + 1, psl_flags);
505 }
506 }
507 else
508 {
509 outer_tuple_emitter.emplace (uiout, "src_and_asm_line");
510 print_source_lines (symtab, mle[i].line, mle[i].line + 1, psl_flags);
511 }
512
513 next_line = mle[i].line + 1;
514 inner_list_emitter.emplace (uiout, "line_asm_insn");
515 }
516
517 num_displayed += dump_insns (gdbarch, uiout,
518 mle[i].start_pc, mle[i].end_pc,
519 how_many, flags, NULL);
520
521 /* When we've reached the end of the mle array, or we've seen the last
522 assembly range for this source line, close out the list/tuple. */
523 if (i == (newlines - 1) || mle[i + 1].line > mle[i].line)
524 {
525 inner_list_emitter.reset ();
526 outer_tuple_emitter.reset ();
527 uiout->text ("\n");
528 }
529 if (how_many >= 0 && num_displayed >= how_many)
530 break;
531 }
532 }
533
534 /* The idea here is to present a source-O-centric view of a
535 function to the user. This means that things are presented
536 in source order, with (possibly) out of order assembly
537 immediately following. */
538
539 static void
540 do_mixed_source_and_assembly (struct gdbarch *gdbarch,
541 struct ui_out *uiout,
542 struct symtab *main_symtab,
543 CORE_ADDR low, CORE_ADDR high,
544 int how_many, gdb_disassembly_flags flags)
545 {
546 const struct linetable_entry *le, *first_le;
547 int i, nlines;
548 int num_displayed = 0;
549 print_source_lines_flags psl_flags = 0;
550 CORE_ADDR pc;
551 struct symtab *last_symtab;
552 int last_line;
553
554 gdb_assert (main_symtab != NULL && main_symtab->linetable () != NULL);
555
556 /* First pass: collect the list of all source files and lines.
557 We do this so that we can only print lines containing code once.
558 We try to print the source text leading up to the next instruction,
559 but if that text is for code that will be disassembled later, then
560 we'll want to defer printing it until later with its associated code. */
561
562 htab_up dis_line_table (allocate_dis_line_table ());
563
564 pc = low;
565
566 /* The prologue may be empty, but there may still be a line number entry
567 for the opening brace which is distinct from the first line of code.
568 If the prologue has been eliminated find_pc_line may return the source
569 line after the opening brace. We still want to print this opening brace.
570 first_le is used to implement this. */
571
572 nlines = main_symtab->linetable ()->nitems;
573 le = main_symtab->linetable ()->item;
574 first_le = NULL;
575
576 /* Skip all the preceding functions. */
577 for (i = 0; i < nlines && le[i].pc < low; i++)
578 continue;
579
580 if (i < nlines && le[i].pc < high)
581 first_le = &le[i];
582
583 /* Add lines for every pc value. */
584 while (pc < high)
585 {
586 struct symtab_and_line sal;
587 int length;
588
589 sal = find_pc_line (pc, 0);
590 length = gdb_insn_length (gdbarch, pc);
591 pc += length;
592
593 if (sal.symtab != NULL)
594 add_dis_line_entry (dis_line_table.get (), sal.symtab, sal.line);
595 }
596
597 /* Second pass: print the disassembly.
598
599 Output format, from an MI perspective:
600 The result is a ui_out list, field name "asm_insns", where elements have
601 name "src_and_asm_line".
602 Each element is a tuple of source line specs (field names line, file,
603 fullname), and field "line_asm_insn" which contains the disassembly.
604 Field "line_asm_insn" is a list of tuples: address, func-name, offset,
605 opcodes, inst.
606
607 CLI output works on top of this because MI ignores ui_out_text output,
608 which is where we put file name and source line contents output.
609
610 Emitter usage:
611 asm_insns_emitter
612 Handles the outer "asm_insns" list.
613 tuple_emitter
614 The tuples for each group of consecutive disassemblies.
615 list_emitter
616 List of consecutive source lines or disassembled insns. */
617
618 if (flags & DISASSEMBLY_FILENAME)
619 psl_flags |= PRINT_SOURCE_LINES_FILENAME;
620
621 ui_out_emit_list asm_insns_emitter (uiout, "asm_insns");
622
623 gdb::optional<ui_out_emit_tuple> tuple_emitter;
624 gdb::optional<ui_out_emit_list> list_emitter;
625
626 last_symtab = NULL;
627 last_line = 0;
628 pc = low;
629
630 while (pc < high)
631 {
632 struct symtab_and_line sal;
633 CORE_ADDR end_pc;
634 int start_preceding_line_to_display = 0;
635 int end_preceding_line_to_display = 0;
636 int new_source_line = 0;
637
638 sal = find_pc_line (pc, 0);
639
640 if (sal.symtab != last_symtab)
641 {
642 /* New source file. */
643 new_source_line = 1;
644
645 /* If this is the first line of output, check for any preceding
646 lines. */
647 if (last_line == 0
648 && first_le != NULL
649 && first_le->line < sal.line)
650 {
651 start_preceding_line_to_display = first_le->line;
652 end_preceding_line_to_display = sal.line;
653 }
654 }
655 else
656 {
657 /* Same source file as last time. */
658 if (sal.symtab != NULL)
659 {
660 if (sal.line > last_line + 1 && last_line != 0)
661 {
662 int l;
663
664 /* Several preceding source lines. Print the trailing ones
665 not associated with code that we'll print later. */
666 for (l = sal.line - 1; l > last_line; --l)
667 {
668 if (line_has_code_p (dis_line_table.get (),
669 sal.symtab, l))
670 break;
671 }
672 if (l < sal.line - 1)
673 {
674 start_preceding_line_to_display = l + 1;
675 end_preceding_line_to_display = sal.line;
676 }
677 }
678 if (sal.line != last_line)
679 new_source_line = 1;
680 else
681 {
682 /* Same source line as last time. This can happen, depending
683 on the debug info. */
684 }
685 }
686 }
687
688 if (new_source_line)
689 {
690 /* Skip the newline if this is the first instruction. */
691 if (pc > low)
692 uiout->text ("\n");
693 if (tuple_emitter.has_value ())
694 {
695 gdb_assert (list_emitter.has_value ());
696 list_emitter.reset ();
697 tuple_emitter.reset ();
698 }
699 if (sal.symtab != last_symtab
700 && !(flags & DISASSEMBLY_FILENAME))
701 {
702 /* Remember MI ignores ui_out_text.
703 We don't have to do anything here for MI because MI
704 output includes the source specs for each line. */
705 if (sal.symtab != NULL)
706 {
707 uiout->text (symtab_to_filename_for_display (sal.symtab));
708 }
709 else
710 uiout->text ("unknown");
711 uiout->text (":\n");
712 }
713 if (start_preceding_line_to_display > 0)
714 {
715 /* Several source lines w/o asm instructions associated.
716 We need to preserve the structure of the output, so output
717 a bunch of line tuples with no asm entries. */
718 int l;
719
720 gdb_assert (sal.symtab != NULL);
721 for (l = start_preceding_line_to_display;
722 l < end_preceding_line_to_display;
723 ++l)
724 {
725 ui_out_emit_tuple line_tuple_emitter (uiout,
726 "src_and_asm_line");
727 print_source_lines (sal.symtab, l, l + 1, psl_flags);
728 ui_out_emit_list chain_line_emitter (uiout, "line_asm_insn");
729 }
730 }
731 tuple_emitter.emplace (uiout, "src_and_asm_line");
732 if (sal.symtab != NULL)
733 print_source_lines (sal.symtab, sal.line, sal.line + 1, psl_flags);
734 else
735 uiout->text (_("--- no source info for this pc ---\n"));
736 list_emitter.emplace (uiout, "line_asm_insn");
737 }
738 else
739 {
740 /* Here we're appending instructions to an existing line.
741 By construction the very first insn will have a symtab
742 and follow the new_source_line path above. */
743 gdb_assert (tuple_emitter.has_value ());
744 gdb_assert (list_emitter.has_value ());
745 }
746
747 if (sal.end != 0)
748 end_pc = std::min (sal.end, high);
749 else
750 end_pc = pc + 1;
751 num_displayed += dump_insns (gdbarch, uiout, pc, end_pc,
752 how_many, flags, &end_pc);
753 pc = end_pc;
754
755 if (how_many >= 0 && num_displayed >= how_many)
756 break;
757
758 last_symtab = sal.symtab;
759 last_line = sal.line;
760 }
761 }
762
763 static void
764 do_assembly_only (struct gdbarch *gdbarch, struct ui_out *uiout,
765 CORE_ADDR low, CORE_ADDR high,
766 int how_many, gdb_disassembly_flags flags)
767 {
768 ui_out_emit_list list_emitter (uiout, "asm_insns");
769
770 dump_insns (gdbarch, uiout, low, high, how_many, flags, NULL);
771 }
772
773 /* Combine implicit and user disassembler options and return them
774 in a newly-created string. */
775
776 static std::string
777 get_all_disassembler_options (struct gdbarch *gdbarch)
778 {
779 const char *implicit = gdbarch_disassembler_options_implicit (gdbarch);
780 const char *options = get_disassembler_options (gdbarch);
781 const char *comma = ",";
782
783 if (implicit == nullptr)
784 {
785 implicit = "";
786 comma = "";
787 }
788
789 if (options == nullptr)
790 {
791 options = "";
792 comma = "";
793 }
794
795 return string_printf ("%s%s%s", implicit, comma, options);
796 }
797
798 gdb_disassembler::gdb_disassembler (struct gdbarch *gdbarch,
799 struct ui_file *file,
800 di_read_memory_ftype read_memory_func)
801 : m_gdbarch (gdbarch),
802 m_buffer (!use_ext_lang_colorization_p && disassembler_styling
803 && file->can_emit_style_escape ()),
804 m_dest (file)
805 {
806 init_disassemble_info (&m_di, &m_buffer, dis_asm_fprintf,
807 dis_asm_styled_fprintf);
808 m_di.flavour = bfd_target_unknown_flavour;
809 m_di.memory_error_func = dis_asm_memory_error;
810 m_di.print_address_func = dis_asm_print_address;
811 /* NOTE: cagney/2003-04-28: The original code, from the old Insight
812 disassembler had a local optimization here. By default it would
813 access the executable file, instead of the target memory (there
814 was a growing list of exceptions though). Unfortunately, the
815 heuristic was flawed. Commands like "disassemble &variable"
816 didn't work as they relied on the access going to the target.
817 Further, it has been superseeded by trust-read-only-sections
818 (although that should be superseeded by target_trust..._p()). */
819 m_di.read_memory_func = read_memory_func;
820 m_di.arch = gdbarch_bfd_arch_info (gdbarch)->arch;
821 m_di.mach = gdbarch_bfd_arch_info (gdbarch)->mach;
822 m_di.endian = gdbarch_byte_order (gdbarch);
823 m_di.endian_code = gdbarch_byte_order_for_code (gdbarch);
824 m_di.application_data = this;
825 m_disassembler_options_holder = get_all_disassembler_options (gdbarch);
826 if (!m_disassembler_options_holder.empty ())
827 m_di.disassembler_options = m_disassembler_options_holder.c_str ();
828 disassemble_init_for_target (&m_di);
829 }
830
831 gdb_disassembler::~gdb_disassembler ()
832 {
833 disassemble_free_target (&m_di);
834 }
835
836 /* See disasm.h. */
837
838 bool gdb_disassembler::use_ext_lang_colorization_p = true;
839
840 /* See disasm.h. */
841
842 int
843 gdb_disassembler::print_insn (CORE_ADDR memaddr,
844 int *branch_delay_insns)
845 {
846 m_err_memaddr.reset ();
847 m_buffer.clear ();
848
849 int length = gdbarch_print_insn (arch (), memaddr, &m_di);
850
851 /* If we have successfully disassembled an instruction, styling is on, we
852 think that the extension language might be able to perform styling for
853 us, and the destination can support styling, then lets call into the
854 extension languages in order to style this output. */
855 if (length > 0 && disassembler_styling
856 && use_ext_lang_colorization_p
857 && m_dest->can_emit_style_escape ())
858 {
859 gdb::optional<std::string> ext_contents;
860 ext_contents = ext_lang_colorize_disasm (m_buffer.string (), arch ());
861 if (ext_contents.has_value ())
862 m_buffer = std::move (*ext_contents);
863 else
864 {
865 /* The extension language failed to add styling to the
866 disassembly output. Set the static flag so that next time we
867 disassemble we don't even bother attempting to use the
868 extension language for styling. */
869 use_ext_lang_colorization_p = false;
870
871 /* The instruction we just disassembled, and the extension
872 languages failed to style, might have otherwise had some
873 minimal styling applied by GDB. To regain that styling we
874 need to recreate m_buffer, but this time with styling support.
875
876 To do this we perform an in-place new, but this time turn on
877 the styling support, then we can re-disassembly the
878 instruction, and gain any minimal styling GDB might add. */
879 gdb_static_assert ((std::is_same<decltype (m_buffer),
880 string_file>::value));
881 gdb_assert (!m_buffer.term_out ());
882 m_buffer.~string_file ();
883 new (&m_buffer) string_file (true);
884 length = gdbarch_print_insn (arch (), memaddr, &m_di);
885 gdb_assert (length > 0);
886 }
887 }
888
889 /* Push any disassemble output to the real destination stream. We do
890 this even if the disassembler reported failure (-1) as the
891 disassembler may have printed something to its output stream. */
892 m_di.fprintf_func (m_dest, "%s", m_buffer.c_str ());
893
894 /* If the disassembler failed then report an appropriate error. */
895 if (length < 0)
896 {
897 if (m_err_memaddr.has_value ())
898 memory_error (TARGET_XFER_E_IO, *m_err_memaddr);
899 else
900 error (_("unknown disassembler error (error = %d)"), length);
901 }
902
903 if (branch_delay_insns != NULL)
904 {
905 if (m_di.insn_info_valid)
906 *branch_delay_insns = m_di.branch_delay_insns;
907 else
908 *branch_delay_insns = 0;
909 }
910 return length;
911 }
912
913 void
914 gdb_disassembly (struct gdbarch *gdbarch, struct ui_out *uiout,
915 gdb_disassembly_flags flags, int how_many,
916 CORE_ADDR low, CORE_ADDR high)
917 {
918 struct symtab *symtab;
919 int nlines = -1;
920
921 /* Assume symtab is valid for whole PC range. */
922 symtab = find_pc_line_symtab (low);
923
924 if (symtab != NULL && symtab->linetable () != NULL)
925 nlines = symtab->linetable ()->nitems;
926
927 if (!(flags & (DISASSEMBLY_SOURCE_DEPRECATED | DISASSEMBLY_SOURCE))
928 || nlines <= 0)
929 do_assembly_only (gdbarch, uiout, low, high, how_many, flags);
930
931 else if (flags & DISASSEMBLY_SOURCE)
932 do_mixed_source_and_assembly (gdbarch, uiout, symtab, low, high,
933 how_many, flags);
934
935 else if (flags & DISASSEMBLY_SOURCE_DEPRECATED)
936 do_mixed_source_and_assembly_deprecated (gdbarch, uiout, symtab,
937 low, high, how_many, flags);
938
939 gdb_flush (gdb_stdout);
940 }
941
942 /* Print the instruction at address MEMADDR in debugged memory,
943 on STREAM. Returns the length of the instruction, in bytes,
944 and, if requested, the number of branch delay slot instructions. */
945
946 int
947 gdb_print_insn (struct gdbarch *gdbarch, CORE_ADDR memaddr,
948 struct ui_file *stream, int *branch_delay_insns)
949 {
950
951 gdb_disassembler di (gdbarch, stream);
952
953 return di.print_insn (memaddr, branch_delay_insns);
954 }
955
956 /* Return the length in bytes of the instruction at address MEMADDR in
957 debugged memory. */
958
959 int
960 gdb_insn_length (struct gdbarch *gdbarch, CORE_ADDR addr)
961 {
962 return gdb_print_insn (gdbarch, addr, &null_stream, NULL);
963 }
964
965 /* An fprintf-function for use by the disassembler when we know we don't
966 want to print anything. Always returns success. */
967
968 static int ATTRIBUTE_PRINTF (2, 3)
969 gdb_disasm_null_printf (void *stream, const char *format, ...)
970 {
971 return 0;
972 }
973
974 /* An fprintf-function for use by the disassembler when we know we don't
975 want to print anything, and the disassembler is using style. Always
976 returns success. */
977
978 static int ATTRIBUTE_PRINTF (3, 4)
979 gdb_disasm_null_styled_printf (void *stream,
980 enum disassembler_style style,
981 const char *format, ...)
982 {
983 return 0;
984 }
985
986 /* See disasm.h. */
987
988 void
989 init_disassemble_info_for_no_printing (struct disassemble_info *dinfo)
990 {
991 init_disassemble_info (dinfo, nullptr, gdb_disasm_null_printf,
992 gdb_disasm_null_styled_printf);
993 }
994
995 /* Initialize a struct disassemble_info for gdb_buffered_insn_length.
996 Upon return, *DISASSEMBLER_OPTIONS_HOLDER owns the string pointed
997 to by DI.DISASSEMBLER_OPTIONS. */
998
999 static void
1000 gdb_buffered_insn_length_init_dis (struct gdbarch *gdbarch,
1001 struct disassemble_info *di,
1002 const gdb_byte *insn, int max_len,
1003 CORE_ADDR addr,
1004 std::string *disassembler_options_holder)
1005 {
1006 init_disassemble_info_for_no_printing (di);
1007
1008 /* init_disassemble_info installs buffer_read_memory, etc.
1009 so we don't need to do that here.
1010 The cast is necessary until disassemble_info is const-ified. */
1011 di->buffer = (gdb_byte *) insn;
1012 di->buffer_length = max_len;
1013 di->buffer_vma = addr;
1014
1015 di->arch = gdbarch_bfd_arch_info (gdbarch)->arch;
1016 di->mach = gdbarch_bfd_arch_info (gdbarch)->mach;
1017 di->endian = gdbarch_byte_order (gdbarch);
1018 di->endian_code = gdbarch_byte_order_for_code (gdbarch);
1019
1020 *disassembler_options_holder = get_all_disassembler_options (gdbarch);
1021 if (!disassembler_options_holder->empty ())
1022 di->disassembler_options = disassembler_options_holder->c_str ();
1023 disassemble_init_for_target (di);
1024 }
1025
1026 /* Return the length in bytes of INSN. MAX_LEN is the size of the
1027 buffer containing INSN. */
1028
1029 int
1030 gdb_buffered_insn_length (struct gdbarch *gdbarch,
1031 const gdb_byte *insn, int max_len, CORE_ADDR addr)
1032 {
1033 struct disassemble_info di;
1034 std::string disassembler_options_holder;
1035
1036 gdb_buffered_insn_length_init_dis (gdbarch, &di, insn, max_len, addr,
1037 &disassembler_options_holder);
1038
1039 int result = gdbarch_print_insn (gdbarch, addr, &di);
1040 disassemble_free_target (&di);
1041 return result;
1042 }
1043
1044 char *
1045 get_disassembler_options (struct gdbarch *gdbarch)
1046 {
1047 char **disassembler_options = gdbarch_disassembler_options (gdbarch);
1048 if (disassembler_options == NULL)
1049 return NULL;
1050 return *disassembler_options;
1051 }
1052
1053 void
1054 set_disassembler_options (const char *prospective_options)
1055 {
1056 struct gdbarch *gdbarch = get_current_arch ();
1057 char **disassembler_options = gdbarch_disassembler_options (gdbarch);
1058 const disasm_options_and_args_t *valid_options_and_args;
1059 const disasm_options_t *valid_options;
1060 gdb::unique_xmalloc_ptr<char> prospective_options_local
1061 = make_unique_xstrdup (prospective_options);
1062 char *options = remove_whitespace_and_extra_commas
1063 (prospective_options_local.get ());
1064 const char *opt;
1065
1066 /* Allow all architectures, even ones that do not support 'set disassembler',
1067 to reset their disassembler options to NULL. */
1068 if (options == NULL)
1069 {
1070 if (disassembler_options != NULL)
1071 {
1072 free (*disassembler_options);
1073 *disassembler_options = NULL;
1074 }
1075 return;
1076 }
1077
1078 valid_options_and_args = gdbarch_valid_disassembler_options (gdbarch);
1079 if (valid_options_and_args == NULL)
1080 {
1081 gdb_printf (gdb_stderr, _("\
1082 'set disassembler-options ...' is not supported on this architecture.\n"));
1083 return;
1084 }
1085
1086 valid_options = &valid_options_and_args->options;
1087
1088 /* Verify we have valid disassembler options. */
1089 FOR_EACH_DISASSEMBLER_OPTION (opt, options)
1090 {
1091 size_t i;
1092 for (i = 0; valid_options->name[i] != NULL; i++)
1093 if (valid_options->arg != NULL && valid_options->arg[i] != NULL)
1094 {
1095 size_t len = strlen (valid_options->name[i]);
1096 bool found = false;
1097 const char *arg;
1098 size_t j;
1099
1100 if (memcmp (opt, valid_options->name[i], len) != 0)
1101 continue;
1102 arg = opt + len;
1103 for (j = 0; valid_options->arg[i]->values[j] != NULL; j++)
1104 if (disassembler_options_cmp
1105 (arg, valid_options->arg[i]->values[j]) == 0)
1106 {
1107 found = true;
1108 break;
1109 }
1110 if (found)
1111 break;
1112 }
1113 else if (disassembler_options_cmp (opt, valid_options->name[i]) == 0)
1114 break;
1115 if (valid_options->name[i] == NULL)
1116 {
1117 gdb_printf (gdb_stderr,
1118 _("Invalid disassembler option value: '%s'.\n"),
1119 opt);
1120 return;
1121 }
1122 }
1123
1124 free (*disassembler_options);
1125 *disassembler_options = xstrdup (options);
1126 }
1127
1128 static void
1129 set_disassembler_options_sfunc (const char *args, int from_tty,
1130 struct cmd_list_element *c)
1131 {
1132 set_disassembler_options (prospective_options.c_str ());
1133 }
1134
1135 static void
1136 show_disassembler_options_sfunc (struct ui_file *file, int from_tty,
1137 struct cmd_list_element *c, const char *value)
1138 {
1139 struct gdbarch *gdbarch = get_current_arch ();
1140 const disasm_options_and_args_t *valid_options_and_args;
1141 const disasm_option_arg_t *valid_args;
1142 const disasm_options_t *valid_options;
1143
1144 const char *options = get_disassembler_options (gdbarch);
1145 if (options == NULL)
1146 options = "";
1147
1148 gdb_printf (file, _("The current disassembler options are '%s'\n\n"),
1149 options);
1150
1151 valid_options_and_args = gdbarch_valid_disassembler_options (gdbarch);
1152
1153 if (valid_options_and_args == NULL)
1154 {
1155 gdb_puts (_("There are no disassembler options available "
1156 "for this architecture.\n"),
1157 file);
1158 return;
1159 }
1160
1161 valid_options = &valid_options_and_args->options;
1162
1163 gdb_printf (file, _("\
1164 The following disassembler options are supported for use with the\n\
1165 'set disassembler-options OPTION [,OPTION]...' command:\n"));
1166
1167 if (valid_options->description != NULL)
1168 {
1169 size_t i, max_len = 0;
1170
1171 gdb_printf (file, "\n");
1172
1173 /* Compute the length of the longest option name. */
1174 for (i = 0; valid_options->name[i] != NULL; i++)
1175 {
1176 size_t len = strlen (valid_options->name[i]);
1177
1178 if (valid_options->arg != NULL && valid_options->arg[i] != NULL)
1179 len += strlen (valid_options->arg[i]->name);
1180 if (max_len < len)
1181 max_len = len;
1182 }
1183
1184 for (i = 0, max_len++; valid_options->name[i] != NULL; i++)
1185 {
1186 gdb_printf (file, " %s", valid_options->name[i]);
1187 if (valid_options->arg != NULL && valid_options->arg[i] != NULL)
1188 gdb_printf (file, "%s", valid_options->arg[i]->name);
1189 if (valid_options->description[i] != NULL)
1190 {
1191 size_t len = strlen (valid_options->name[i]);
1192
1193 if (valid_options->arg != NULL && valid_options->arg[i] != NULL)
1194 len += strlen (valid_options->arg[i]->name);
1195 gdb_printf (file, "%*c %s", (int) (max_len - len), ' ',
1196 valid_options->description[i]);
1197 }
1198 gdb_printf (file, "\n");
1199 }
1200 }
1201 else
1202 {
1203 size_t i;
1204 gdb_printf (file, " ");
1205 for (i = 0; valid_options->name[i] != NULL; i++)
1206 {
1207 gdb_printf (file, "%s", valid_options->name[i]);
1208 if (valid_options->arg != NULL && valid_options->arg[i] != NULL)
1209 gdb_printf (file, "%s", valid_options->arg[i]->name);
1210 if (valid_options->name[i + 1] != NULL)
1211 gdb_printf (file, ", ");
1212 file->wrap_here (2);
1213 }
1214 gdb_printf (file, "\n");
1215 }
1216
1217 valid_args = valid_options_and_args->args;
1218 if (valid_args != NULL)
1219 {
1220 size_t i, j;
1221
1222 for (i = 0; valid_args[i].name != NULL; i++)
1223 {
1224 gdb_printf (file, _("\n\
1225 For the options above, the following values are supported for \"%s\":\n "),
1226 valid_args[i].name);
1227 for (j = 0; valid_args[i].values[j] != NULL; j++)
1228 {
1229 gdb_printf (file, " %s", valid_args[i].values[j]);
1230 file->wrap_here (3);
1231 }
1232 gdb_printf (file, "\n");
1233 }
1234 }
1235 }
1236
1237 /* A completion function for "set disassembler". */
1238
1239 static void
1240 disassembler_options_completer (struct cmd_list_element *ignore,
1241 completion_tracker &tracker,
1242 const char *text, const char *word)
1243 {
1244 struct gdbarch *gdbarch = get_current_arch ();
1245 const disasm_options_and_args_t *opts_and_args
1246 = gdbarch_valid_disassembler_options (gdbarch);
1247
1248 if (opts_and_args != NULL)
1249 {
1250 const disasm_options_t *opts = &opts_and_args->options;
1251
1252 /* Only attempt to complete on the last option text. */
1253 const char *separator = strrchr (text, ',');
1254 if (separator != NULL)
1255 text = separator + 1;
1256 text = skip_spaces (text);
1257 complete_on_enum (tracker, opts->name, text, word);
1258 }
1259 }
1260
1261
1262 /* Initialization code. */
1263
1264 void _initialize_disasm ();
1265 void
1266 _initialize_disasm ()
1267 {
1268 /* Add the command that controls the disassembler options. */
1269 set_show_commands set_show_disas_opts
1270 = add_setshow_string_noescape_cmd ("disassembler-options", no_class,
1271 &prospective_options, _("\
1272 Set the disassembler options.\n\
1273 Usage: set disassembler-options OPTION [,OPTION]...\n\n\
1274 See: 'show disassembler-options' for valid option values."), _("\
1275 Show the disassembler options."), NULL,
1276 set_disassembler_options_sfunc,
1277 show_disassembler_options_sfunc,
1278 &setlist, &showlist);
1279 set_cmd_completer (set_show_disas_opts.set, disassembler_options_completer);
1280 }