Automatic date update in version.in
[binutils-gdb.git] / gdb / disasm.c
blob989120e05b18998cf7e923af340c34958a12f8af
1 /* Disassemble support for GDB.
3 Copyright (C) 2000-2022 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
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"
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. */
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;
44 /* When this is true we will try to use libopcodes to provide styling to
45 the disassembler output. */
47 static bool use_libopcodes_styling = true;
49 /* To support the set_use_libopcodes_styling function we have a second
50 variable which is connected to the actual set/show option. */
52 static bool use_libopcodes_styling_option = use_libopcodes_styling;
54 /* The "maint show libopcodes-styling enabled" command. */
56 static void
57 show_use_libopcodes_styling (struct ui_file *file, int from_tty,
58 struct cmd_list_element *c,
59 const char *value)
61 gdb_non_printing_memory_disassembler dis (target_gdbarch ());
62 bool supported = dis.disasm_info ()->created_styled_output;
64 if (supported || !use_libopcodes_styling)
65 gdb_printf (file, _("Use of libopcodes styling support is \"%s\".\n"),
66 value);
67 else
69 /* Use of libopcodes styling is not supported, and the user has this
70 turned on! */
71 gdb_printf (file, _("Use of libopcodes styling support is \"off\""
72 " (not supported on architecture \"%s\")\n"),
73 gdbarch_bfd_arch_info (target_gdbarch ())->printable_name);
77 /* The "maint set libopcodes-styling enabled" command. */
79 static void
80 set_use_libopcodes_styling (const char *args, int from_tty,
81 struct cmd_list_element *c)
83 gdb_non_printing_memory_disassembler dis (target_gdbarch ());
84 bool supported = dis.disasm_info ()->created_styled_output;
86 /* If the current architecture doesn't support libopcodes styling then we
87 give an error here, but leave the underlying setting enabled. This
88 means that if the user switches to an architecture that does support
89 libopcodes styling the setting will be enabled. */
91 if (use_libopcodes_styling_option && !supported)
93 use_libopcodes_styling_option = use_libopcodes_styling;
94 error (_("Use of libopcodes styling not supported on architecture \"%s\"."),
95 gdbarch_bfd_arch_info (target_gdbarch ())->printable_name);
97 else
98 use_libopcodes_styling = use_libopcodes_styling_option;
101 /* This structure is used to store line number information for the
102 deprecated /m option.
103 We need a different sort of line table from the normal one cuz we can't
104 depend upon implicit line-end pc's for lines to do the
105 reordering in this function. */
107 struct deprecated_dis_line_entry
109 int line;
110 CORE_ADDR start_pc;
111 CORE_ADDR end_pc;
114 /* This Structure is used to store line number information.
115 We need a different sort of line table from the normal one cuz we can't
116 depend upon implicit line-end pc's for lines to do the
117 reordering in this function. */
119 struct dis_line_entry
121 struct symtab *symtab;
122 int line;
125 /* Hash function for dis_line_entry. */
127 static hashval_t
128 hash_dis_line_entry (const void *item)
130 const struct dis_line_entry *dle = (const struct dis_line_entry *) item;
132 return htab_hash_pointer (dle->symtab) + dle->line;
135 /* Equal function for dis_line_entry. */
137 static int
138 eq_dis_line_entry (const void *item_lhs, const void *item_rhs)
140 const struct dis_line_entry *lhs = (const struct dis_line_entry *) item_lhs;
141 const struct dis_line_entry *rhs = (const struct dis_line_entry *) item_rhs;
143 return (lhs->symtab == rhs->symtab
144 && lhs->line == rhs->line);
147 /* Create the table to manage lines for mixed source/disassembly. */
149 static htab_t
150 allocate_dis_line_table (void)
152 return htab_create_alloc (41,
153 hash_dis_line_entry, eq_dis_line_entry,
154 xfree, xcalloc, xfree);
157 /* Add a new dis_line_entry containing SYMTAB and LINE to TABLE. */
159 static void
160 add_dis_line_entry (htab_t table, struct symtab *symtab, int line)
162 void **slot;
163 struct dis_line_entry dle, *dlep;
165 dle.symtab = symtab;
166 dle.line = line;
167 slot = htab_find_slot (table, &dle, INSERT);
168 if (*slot == NULL)
170 dlep = XNEW (struct dis_line_entry);
171 dlep->symtab = symtab;
172 dlep->line = line;
173 *slot = dlep;
177 /* Return non-zero if SYMTAB, LINE are in TABLE. */
179 static int
180 line_has_code_p (htab_t table, struct symtab *symtab, int line)
182 struct dis_line_entry dle;
184 dle.symtab = symtab;
185 dle.line = line;
186 return htab_find (table, &dle) != NULL;
189 /* Wrapper of target_read_code. */
192 gdb_disassembler_memory_reader::dis_asm_read_memory
193 (bfd_vma memaddr, gdb_byte *myaddr, unsigned int len,
194 struct disassemble_info *info)
196 return target_read_code (memaddr, myaddr, len);
199 /* Wrapper of memory_error. */
201 void
202 gdb_disassembler::dis_asm_memory_error (int err, bfd_vma memaddr,
203 struct disassemble_info *info)
205 gdb_disassembler *self
206 = static_cast<gdb_disassembler *>(info->application_data);
208 self->m_err_memaddr.emplace (memaddr);
211 /* Wrapper of print_address. */
213 void
214 gdb_disassembler::dis_asm_print_address (bfd_vma addr,
215 struct disassemble_info *info)
217 gdb_disassembler *self
218 = static_cast<gdb_disassembler *>(info->application_data);
220 if (self->in_comment_p ())
222 /* Calling 'print_address' might add styling to the output (based on
223 the properties of the stream we're writing too). This is usually
224 fine, but if we are in an assembler comment then we'd prefer to
225 have the comment style, rather than the default address style.
227 Print the address into a temporary buffer which doesn't support
228 styling, then reprint this unstyled address with the default text
229 style.
231 As we are inside a comment right now, the standard print routine
232 will ensure that the comment is printed to the user with a
233 suitable comment style. */
234 string_file tmp;
235 print_address (self->arch (), addr, &tmp);
236 self->fprintf_styled_func (self, dis_style_text, "%s", tmp.c_str ());
238 else
239 print_address (self->arch (), addr, self->stream ());
242 /* See disasm.h. */
244 ui_file *
245 gdb_printing_disassembler::stream_from_gdb_disassemble_info (void *dis_info)
247 gdb_disassemble_info *di = (gdb_disassemble_info *) dis_info;
248 gdb_printing_disassembler *dis
249 = gdb::checked_static_cast<gdb_printing_disassembler *> (di);
250 ui_file *stream = dis->stream ();
251 gdb_assert (stream != nullptr);
252 return stream;
255 /* Format disassembler output to STREAM. */
258 gdb_printing_disassembler::fprintf_func (void *dis_info,
259 const char *format, ...)
261 ui_file *stream = stream_from_gdb_disassemble_info (dis_info);
263 va_list args;
264 va_start (args, format);
265 gdb_vprintf (stream, format, args);
266 va_end (args);
268 /* Something non -ve. */
269 return 0;
272 /* See disasm.h. */
275 gdb_printing_disassembler::fprintf_styled_func (void *dis_info,
276 enum disassembler_style style,
277 const char *format, ...)
279 ui_file *stream = stream_from_gdb_disassemble_info (dis_info);
280 gdb_printing_disassembler *dis = (gdb_printing_disassembler *) dis_info;
282 va_list args;
283 va_start (args, format);
284 std::string content = string_vprintf (format, args);
285 va_end (args);
287 /* Once in a comment then everything should be styled as a comment. */
288 if (style == dis_style_comment_start)
289 dis->set_in_comment (true);
290 if (dis->in_comment_p ())
291 style = dis_style_comment_start;
293 /* Now print the content with the correct style. */
294 const char *txt = content.c_str ();
295 switch (style)
297 case dis_style_mnemonic:
298 case dis_style_sub_mnemonic:
299 case dis_style_assembler_directive:
300 fputs_styled (txt, disasm_mnemonic_style.style (), stream);
301 break;
303 case dis_style_register:
304 fputs_styled (txt, disasm_register_style.style (), stream);
305 break;
307 case dis_style_immediate:
308 case dis_style_address_offset:
309 fputs_styled (txt, disasm_immediate_style.style (), stream);
310 break;
312 case dis_style_address:
313 fputs_styled (txt, address_style.style (), stream);
314 break;
316 case dis_style_symbol:
317 fputs_styled (txt, function_name_style.style (), stream);
318 break;
320 case dis_style_comment_start:
321 fputs_styled (txt, disasm_comment_style.style (), stream);
322 break;
324 case dis_style_text:
325 gdb_puts (txt, stream);
326 break;
329 /* Something non -ve. */
330 return 0;
333 static bool
334 line_is_less_than (const deprecated_dis_line_entry &mle1,
335 const deprecated_dis_line_entry &mle2)
337 bool val;
339 /* End of sequence markers have a line number of 0 but don't want to
340 be sorted to the head of the list, instead sort by PC. */
341 if (mle1.line == 0 || mle2.line == 0)
343 if (mle1.start_pc != mle2.start_pc)
344 val = mle1.start_pc < mle2.start_pc;
345 else
346 val = mle1.line < mle2.line;
348 else
350 if (mle1.line != mle2.line)
351 val = mle1.line < mle2.line;
352 else
353 val = mle1.start_pc < mle2.start_pc;
355 return val;
358 /* See disasm.h. */
361 gdb_pretty_print_disassembler::pretty_print_insn (const struct disasm_insn *insn,
362 gdb_disassembly_flags flags)
364 /* parts of the symbolic representation of the address */
365 int unmapped;
366 int offset;
367 int line;
368 int size;
369 CORE_ADDR pc;
370 struct gdbarch *gdbarch = arch ();
373 ui_out_emit_tuple tuple_emitter (m_uiout, NULL);
374 pc = insn->addr;
376 if (insn->number != 0)
378 m_uiout->field_unsigned ("insn-number", insn->number);
379 m_uiout->text ("\t");
382 if ((flags & DISASSEMBLY_SPECULATIVE) != 0)
384 if (insn->is_speculative)
386 m_uiout->field_string ("is-speculative", "?");
388 /* The speculative execution indication overwrites the first
389 character of the PC prefix.
390 We assume a PC prefix length of 3 characters. */
391 if ((flags & DISASSEMBLY_OMIT_PC) == 0)
392 m_uiout->text (pc_prefix (pc) + 1);
393 else
394 m_uiout->text (" ");
396 else if ((flags & DISASSEMBLY_OMIT_PC) == 0)
397 m_uiout->text (pc_prefix (pc));
398 else
399 m_uiout->text (" ");
401 else if ((flags & DISASSEMBLY_OMIT_PC) == 0)
402 m_uiout->text (pc_prefix (pc));
403 m_uiout->field_core_addr ("address", gdbarch, pc);
405 std::string name, filename;
406 bool omit_fname = ((flags & DISASSEMBLY_OMIT_FNAME) != 0);
407 if (!build_address_symbolic (gdbarch, pc, false, omit_fname, &name,
408 &offset, &filename, &line, &unmapped))
410 /* We don't care now about line, filename and unmapped. But we might in
411 the future. */
412 m_uiout->text (" <");
413 if (!omit_fname)
414 m_uiout->field_string ("func-name", name,
415 function_name_style.style ());
416 /* For negative offsets, avoid displaying them as +-N; the sign of
417 the offset takes the place of the "+" here. */
418 if (offset >= 0)
419 m_uiout->text ("+");
420 m_uiout->field_signed ("offset", offset);
421 m_uiout->text (">:\t");
423 else
424 m_uiout->text (":\t");
426 /* Clear the buffer into which we will disassemble the instruction. */
427 m_insn_stb.clear ();
429 /* A helper function to write the M_INSN_STB buffer, followed by a
430 newline. This can be called in a couple of situations. */
431 auto write_out_insn_buffer = [&] ()
433 m_uiout->field_stream ("inst", m_insn_stb);
434 m_uiout->text ("\n");
439 /* Now we can disassemble the instruction. If the disassembler
440 returns a negative value this indicates an error and is handled
441 within the print_insn call, resulting in an exception being
442 thrown. Returning zero makes no sense, as this indicates we
443 disassembled something successfully, but it was something of no
444 size? */
445 size = m_di.print_insn (pc);
446 gdb_assert (size > 0);
448 catch (const gdb_exception &ex)
450 /* An exception was thrown while disassembling the instruction.
451 However, the disassembler might still have written something
452 out, so ensure that we flush the instruction buffer before
453 rethrowing the exception. We can't perform this write from an
454 object destructor as the write itself might throw an exception
455 if the pager kicks in, and the user selects quit. */
456 write_out_insn_buffer ();
457 throw ex;
460 if (flags & DISASSEMBLY_RAW_INSN)
462 CORE_ADDR end_pc;
463 bfd_byte data;
464 const char *spacer = "";
466 /* Build the opcodes using a temporary stream so we can
467 write them out in a single go for the MI. */
468 m_opcode_stb.clear ();
470 end_pc = pc + size;
472 for (;pc < end_pc; ++pc)
474 read_code (pc, &data, 1);
475 m_opcode_stb.printf ("%s%02x", spacer, (unsigned) data);
476 spacer = " ";
479 m_uiout->field_stream ("opcodes", m_opcode_stb);
480 m_uiout->text ("\t");
483 /* Disassembly was a success, write out the instruction buffer. */
484 write_out_insn_buffer ();
487 return size;
490 static int
491 dump_insns (struct gdbarch *gdbarch,
492 struct ui_out *uiout, CORE_ADDR low, CORE_ADDR high,
493 int how_many, gdb_disassembly_flags flags, CORE_ADDR *end_pc)
495 struct disasm_insn insn;
496 int num_displayed = 0;
498 memset (&insn, 0, sizeof (insn));
499 insn.addr = low;
501 gdb_pretty_print_disassembler disasm (gdbarch, uiout);
503 while (insn.addr < high && (how_many < 0 || num_displayed < how_many))
505 int size;
507 size = disasm.pretty_print_insn (&insn, flags);
508 if (size <= 0)
509 break;
511 ++num_displayed;
512 insn.addr += size;
514 /* Allow user to bail out with ^C. */
515 QUIT;
518 if (end_pc != NULL)
519 *end_pc = insn.addr;
521 return num_displayed;
524 /* The idea here is to present a source-O-centric view of a
525 function to the user. This means that things are presented
526 in source order, with (possibly) out of order assembly
527 immediately following.
529 N.B. This view is deprecated. */
531 static void
532 do_mixed_source_and_assembly_deprecated
533 (struct gdbarch *gdbarch, struct ui_out *uiout,
534 struct symtab *symtab,
535 CORE_ADDR low, CORE_ADDR high,
536 int how_many, gdb_disassembly_flags flags)
538 int newlines = 0;
539 int nlines;
540 struct linetable_entry *le;
541 struct deprecated_dis_line_entry *mle;
542 struct symtab_and_line sal;
543 int i;
544 int out_of_order = 0;
545 int next_line = 0;
546 int num_displayed = 0;
547 print_source_lines_flags psl_flags = 0;
549 gdb_assert (symtab != nullptr && symtab->linetable () != nullptr);
551 nlines = symtab->linetable ()->nitems;
552 le = symtab->linetable ()->item;
554 if (flags & DISASSEMBLY_FILENAME)
555 psl_flags |= PRINT_SOURCE_LINES_FILENAME;
557 mle = (struct deprecated_dis_line_entry *)
558 alloca (nlines * sizeof (struct deprecated_dis_line_entry));
560 /* Copy linetable entries for this function into our data
561 structure, creating end_pc's and setting out_of_order as
562 appropriate. */
564 /* First, skip all the preceding functions. */
566 for (i = 0; i < nlines - 1 && le[i].pc < low; i++);
568 /* Now, copy all entries before the end of this function. */
570 for (; i < nlines - 1 && le[i].pc < high; i++)
572 if (le[i].line == le[i + 1].line && le[i].pc == le[i + 1].pc)
573 continue; /* Ignore duplicates. */
575 /* Skip any end-of-function markers. */
576 if (le[i].line == 0)
577 continue;
579 mle[newlines].line = le[i].line;
580 if (le[i].line > le[i + 1].line)
581 out_of_order = 1;
582 mle[newlines].start_pc = le[i].pc;
583 mle[newlines].end_pc = le[i + 1].pc;
584 newlines++;
587 /* If we're on the last line, and it's part of the function,
588 then we need to get the end pc in a special way. */
590 if (i == nlines - 1 && le[i].pc < high)
592 mle[newlines].line = le[i].line;
593 mle[newlines].start_pc = le[i].pc;
594 sal = find_pc_line (le[i].pc, 0);
595 mle[newlines].end_pc = sal.end;
596 newlines++;
599 /* Now, sort mle by line #s (and, then by addresses within lines). */
601 if (out_of_order)
602 std::sort (mle, mle + newlines, line_is_less_than);
604 /* Now, for each line entry, emit the specified lines (unless
605 they have been emitted before), followed by the assembly code
606 for that line. */
608 ui_out_emit_list asm_insns_list (uiout, "asm_insns");
610 gdb::optional<ui_out_emit_tuple> outer_tuple_emitter;
611 gdb::optional<ui_out_emit_list> inner_list_emitter;
613 for (i = 0; i < newlines; i++)
615 /* Print out everything from next_line to the current line. */
616 if (mle[i].line >= next_line)
618 if (next_line != 0)
620 /* Just one line to print. */
621 if (next_line == mle[i].line)
623 outer_tuple_emitter.emplace (uiout, "src_and_asm_line");
624 print_source_lines (symtab, next_line, mle[i].line + 1, psl_flags);
626 else
628 /* Several source lines w/o asm instructions associated. */
629 for (; next_line < mle[i].line; next_line++)
631 ui_out_emit_tuple tuple_emitter (uiout,
632 "src_and_asm_line");
633 print_source_lines (symtab, next_line, next_line + 1,
634 psl_flags);
635 ui_out_emit_list temp_list_emitter (uiout,
636 "line_asm_insn");
638 /* Print the last line and leave list open for
639 asm instructions to be added. */
640 outer_tuple_emitter.emplace (uiout, "src_and_asm_line");
641 print_source_lines (symtab, next_line, mle[i].line + 1, psl_flags);
644 else
646 outer_tuple_emitter.emplace (uiout, "src_and_asm_line");
647 print_source_lines (symtab, mle[i].line, mle[i].line + 1, psl_flags);
650 next_line = mle[i].line + 1;
651 inner_list_emitter.emplace (uiout, "line_asm_insn");
654 num_displayed += dump_insns (gdbarch, uiout,
655 mle[i].start_pc, mle[i].end_pc,
656 how_many, flags, NULL);
658 /* When we've reached the end of the mle array, or we've seen the last
659 assembly range for this source line, close out the list/tuple. */
660 if (i == (newlines - 1) || mle[i + 1].line > mle[i].line)
662 inner_list_emitter.reset ();
663 outer_tuple_emitter.reset ();
664 uiout->text ("\n");
666 if (how_many >= 0 && num_displayed >= how_many)
667 break;
671 /* The idea here is to present a source-O-centric view of a
672 function to the user. This means that things are presented
673 in source order, with (possibly) out of order assembly
674 immediately following. */
676 static void
677 do_mixed_source_and_assembly (struct gdbarch *gdbarch,
678 struct ui_out *uiout,
679 struct symtab *main_symtab,
680 CORE_ADDR low, CORE_ADDR high,
681 int how_many, gdb_disassembly_flags flags)
683 const struct linetable_entry *le, *first_le;
684 int i, nlines;
685 int num_displayed = 0;
686 print_source_lines_flags psl_flags = 0;
687 CORE_ADDR pc;
688 struct symtab *last_symtab;
689 int last_line;
691 gdb_assert (main_symtab != NULL && main_symtab->linetable () != NULL);
693 /* First pass: collect the list of all source files and lines.
694 We do this so that we can only print lines containing code once.
695 We try to print the source text leading up to the next instruction,
696 but if that text is for code that will be disassembled later, then
697 we'll want to defer printing it until later with its associated code. */
699 htab_up dis_line_table (allocate_dis_line_table ());
701 pc = low;
703 /* The prologue may be empty, but there may still be a line number entry
704 for the opening brace which is distinct from the first line of code.
705 If the prologue has been eliminated find_pc_line may return the source
706 line after the opening brace. We still want to print this opening brace.
707 first_le is used to implement this. */
709 nlines = main_symtab->linetable ()->nitems;
710 le = main_symtab->linetable ()->item;
711 first_le = NULL;
713 /* Skip all the preceding functions. */
714 for (i = 0; i < nlines && le[i].pc < low; i++)
715 continue;
717 if (i < nlines && le[i].pc < high)
718 first_le = &le[i];
720 /* Add lines for every pc value. */
721 while (pc < high)
723 struct symtab_and_line sal;
724 int length;
726 sal = find_pc_line (pc, 0);
727 length = gdb_insn_length (gdbarch, pc);
728 pc += length;
730 if (sal.symtab != NULL)
731 add_dis_line_entry (dis_line_table.get (), sal.symtab, sal.line);
734 /* Second pass: print the disassembly.
736 Output format, from an MI perspective:
737 The result is a ui_out list, field name "asm_insns", where elements have
738 name "src_and_asm_line".
739 Each element is a tuple of source line specs (field names line, file,
740 fullname), and field "line_asm_insn" which contains the disassembly.
741 Field "line_asm_insn" is a list of tuples: address, func-name, offset,
742 opcodes, inst.
744 CLI output works on top of this because MI ignores ui_out_text output,
745 which is where we put file name and source line contents output.
747 Emitter usage:
748 asm_insns_emitter
749 Handles the outer "asm_insns" list.
750 tuple_emitter
751 The tuples for each group of consecutive disassemblies.
752 list_emitter
753 List of consecutive source lines or disassembled insns. */
755 if (flags & DISASSEMBLY_FILENAME)
756 psl_flags |= PRINT_SOURCE_LINES_FILENAME;
758 ui_out_emit_list asm_insns_emitter (uiout, "asm_insns");
760 gdb::optional<ui_out_emit_tuple> tuple_emitter;
761 gdb::optional<ui_out_emit_list> list_emitter;
763 last_symtab = NULL;
764 last_line = 0;
765 pc = low;
767 while (pc < high)
769 struct symtab_and_line sal;
770 CORE_ADDR end_pc;
771 int start_preceding_line_to_display = 0;
772 int end_preceding_line_to_display = 0;
773 int new_source_line = 0;
775 sal = find_pc_line (pc, 0);
777 if (sal.symtab != last_symtab)
779 /* New source file. */
780 new_source_line = 1;
782 /* If this is the first line of output, check for any preceding
783 lines. */
784 if (last_line == 0
785 && first_le != NULL
786 && first_le->line < sal.line)
788 start_preceding_line_to_display = first_le->line;
789 end_preceding_line_to_display = sal.line;
792 else
794 /* Same source file as last time. */
795 if (sal.symtab != NULL)
797 if (sal.line > last_line + 1 && last_line != 0)
799 int l;
801 /* Several preceding source lines. Print the trailing ones
802 not associated with code that we'll print later. */
803 for (l = sal.line - 1; l > last_line; --l)
805 if (line_has_code_p (dis_line_table.get (),
806 sal.symtab, l))
807 break;
809 if (l < sal.line - 1)
811 start_preceding_line_to_display = l + 1;
812 end_preceding_line_to_display = sal.line;
815 if (sal.line != last_line)
816 new_source_line = 1;
817 else
819 /* Same source line as last time. This can happen, depending
820 on the debug info. */
825 if (new_source_line)
827 /* Skip the newline if this is the first instruction. */
828 if (pc > low)
829 uiout->text ("\n");
830 if (tuple_emitter.has_value ())
832 gdb_assert (list_emitter.has_value ());
833 list_emitter.reset ();
834 tuple_emitter.reset ();
836 if (sal.symtab != last_symtab
837 && !(flags & DISASSEMBLY_FILENAME))
839 /* Remember MI ignores ui_out_text.
840 We don't have to do anything here for MI because MI
841 output includes the source specs for each line. */
842 if (sal.symtab != NULL)
844 uiout->text (symtab_to_filename_for_display (sal.symtab));
846 else
847 uiout->text ("unknown");
848 uiout->text (":\n");
850 if (start_preceding_line_to_display > 0)
852 /* Several source lines w/o asm instructions associated.
853 We need to preserve the structure of the output, so output
854 a bunch of line tuples with no asm entries. */
855 int l;
857 gdb_assert (sal.symtab != NULL);
858 for (l = start_preceding_line_to_display;
859 l < end_preceding_line_to_display;
860 ++l)
862 ui_out_emit_tuple line_tuple_emitter (uiout,
863 "src_and_asm_line");
864 print_source_lines (sal.symtab, l, l + 1, psl_flags);
865 ui_out_emit_list chain_line_emitter (uiout, "line_asm_insn");
868 tuple_emitter.emplace (uiout, "src_and_asm_line");
869 if (sal.symtab != NULL)
870 print_source_lines (sal.symtab, sal.line, sal.line + 1, psl_flags);
871 else
872 uiout->text (_("--- no source info for this pc ---\n"));
873 list_emitter.emplace (uiout, "line_asm_insn");
875 else
877 /* Here we're appending instructions to an existing line.
878 By construction the very first insn will have a symtab
879 and follow the new_source_line path above. */
880 gdb_assert (tuple_emitter.has_value ());
881 gdb_assert (list_emitter.has_value ());
884 if (sal.end != 0)
885 end_pc = std::min (sal.end, high);
886 else
887 end_pc = pc + 1;
888 num_displayed += dump_insns (gdbarch, uiout, pc, end_pc,
889 how_many, flags, &end_pc);
890 pc = end_pc;
892 if (how_many >= 0 && num_displayed >= how_many)
893 break;
895 last_symtab = sal.symtab;
896 last_line = sal.line;
900 static void
901 do_assembly_only (struct gdbarch *gdbarch, struct ui_out *uiout,
902 CORE_ADDR low, CORE_ADDR high,
903 int how_many, gdb_disassembly_flags flags)
905 ui_out_emit_list list_emitter (uiout, "asm_insns");
907 dump_insns (gdbarch, uiout, low, high, how_many, flags, NULL);
910 /* Combine implicit and user disassembler options and return them
911 in a newly-created string. */
913 static std::string
914 get_all_disassembler_options (struct gdbarch *gdbarch)
916 const char *implicit = gdbarch_disassembler_options_implicit (gdbarch);
917 const char *options = get_disassembler_options (gdbarch);
918 const char *comma = ",";
920 if (implicit == nullptr)
922 implicit = "";
923 comma = "";
926 if (options == nullptr)
928 options = "";
929 comma = "";
932 return string_printf ("%s%s%s", implicit, comma, options);
935 gdb_disassembler::gdb_disassembler (struct gdbarch *gdbarch,
936 struct ui_file *file,
937 read_memory_ftype func)
938 : gdb_printing_disassembler (gdbarch, &m_buffer, func,
939 dis_asm_memory_error, dis_asm_print_address),
940 /* The use of m_di.created_styled_output here is a bit of a cheat, but
941 it works fine for now. Currently, for all targets that support
942 libopcodes styling, this field is set during the call to
943 disassemble_init_for_target, which was called as part of the
944 initialization of gdb_printing_disassembler. And so, we are able to
945 spot if a target supports libopcodes styling, and create m_buffer in
946 the correct styling mode.
948 If there's ever a target that only sets created_styled_output during
949 the actual disassemble phase, then the logic here will have to
950 change. */
951 m_buffer ((!use_ext_lang_colorization_p
952 || (use_libopcodes_styling && m_di.created_styled_output))
953 && disassembler_styling
954 && file->can_emit_style_escape ()),
955 m_dest (file)
956 { /* Nothing. */ }
958 /* See disasm.h. */
960 gdb_disassemble_info::gdb_disassemble_info
961 (struct gdbarch *gdbarch,
962 read_memory_ftype read_memory_func, memory_error_ftype memory_error_func,
963 print_address_ftype print_address_func, fprintf_ftype fprintf_func,
964 fprintf_styled_ftype fprintf_styled_func)
965 : m_gdbarch (gdbarch)
967 gdb_assert (fprintf_func != nullptr);
968 gdb_assert (fprintf_styled_func != nullptr);
969 init_disassemble_info (&m_di, (void *) this, fprintf_func,
970 fprintf_styled_func);
971 m_di.flavour = bfd_target_unknown_flavour;
973 /* The memory_error_func, print_address_func, and read_memory_func are
974 all initialized to a default (non-nullptr) value by the call to
975 init_disassemble_info above. If the user is overriding these fields
976 (by passing non-nullptr values) then do that now, otherwise, leave
977 these fields as the defaults. */
978 if (memory_error_func != nullptr)
979 m_di.memory_error_func = memory_error_func;
980 if (print_address_func != nullptr)
981 m_di.print_address_func = print_address_func;
982 if (read_memory_func != nullptr)
983 m_di.read_memory_func = read_memory_func;
985 m_di.arch = gdbarch_bfd_arch_info (gdbarch)->arch;
986 m_di.mach = gdbarch_bfd_arch_info (gdbarch)->mach;
987 m_di.endian = gdbarch_byte_order (gdbarch);
988 m_di.endian_code = gdbarch_byte_order_for_code (gdbarch);
989 m_di.application_data = this;
990 m_disassembler_options_holder = get_all_disassembler_options (gdbarch);
991 if (!m_disassembler_options_holder.empty ())
992 m_di.disassembler_options = m_disassembler_options_holder.c_str ();
993 disassemble_init_for_target (&m_di);
996 /* See disasm.h. */
998 gdb_disassemble_info::~gdb_disassemble_info ()
1000 disassemble_free_target (&m_di);
1003 /* Wrapper around calling gdbarch_print_insn. This function takes care of
1004 first calling the extension language hooks for print_insn, and, if none
1005 of the extension languages can print this instruction, calls
1006 gdbarch_print_insn to do the work.
1008 GDBARCH is the architecture to disassemble in, VMA is the address of the
1009 instruction being disassembled, and INFO is the libopcodes disassembler
1010 related information. */
1012 static int
1013 gdb_print_insn_1 (struct gdbarch *gdbarch, CORE_ADDR vma,
1014 struct disassemble_info *info)
1016 /* Call into the extension languages to do the disassembly. */
1017 gdb::optional<int> length = ext_lang_print_insn (gdbarch, vma, info);
1018 if (length.has_value ())
1019 return *length;
1021 /* No extension language wanted to do the disassembly, so do it
1022 manually. */
1023 return gdbarch_print_insn (gdbarch, vma, info);
1026 /* See disasm.h. */
1028 bool gdb_disassembler::use_ext_lang_colorization_p = true;
1030 /* See disasm.h. */
1033 gdb_disassembler::print_insn (CORE_ADDR memaddr,
1034 int *branch_delay_insns)
1036 m_err_memaddr.reset ();
1037 m_buffer.clear ();
1038 this->set_in_comment (false);
1040 int length = gdb_print_insn_1 (arch (), memaddr, &m_di);
1042 /* If we have successfully disassembled an instruction, disassembler
1043 styling using the extension language is on, and libopcodes hasn't
1044 already styled the output for us, and, if the destination can support
1045 styling, then lets call into the extension languages in order to style
1046 this output. */
1047 if (length > 0 && disassembler_styling
1048 && (!m_di.created_styled_output || !use_libopcodes_styling)
1049 && use_ext_lang_colorization_p
1050 && m_dest->can_emit_style_escape ())
1052 gdb::optional<std::string> ext_contents;
1053 ext_contents = ext_lang_colorize_disasm (m_buffer.string (), arch ());
1054 if (ext_contents.has_value ())
1055 m_buffer = std::move (*ext_contents);
1056 else
1058 /* The extension language failed to add styling to the
1059 disassembly output. Set the static flag so that next time we
1060 disassemble we don't even bother attempting to use the
1061 extension language for styling. */
1062 use_ext_lang_colorization_p = false;
1064 /* The instruction we just disassembled, and the extension
1065 languages failed to style, might have otherwise had some
1066 minimal styling applied by GDB. To regain that styling we
1067 need to recreate m_buffer, but this time with styling support.
1069 To do this we perform an in-place new, but this time turn on
1070 the styling support, then we can re-disassembly the
1071 instruction, and gain any minimal styling GDB might add. */
1072 gdb_static_assert ((std::is_same<decltype (m_buffer),
1073 string_file>::value));
1074 gdb_assert (!m_buffer.term_out ());
1075 m_buffer.~string_file ();
1076 new (&m_buffer) string_file (true);
1077 length = gdb_print_insn_1 (arch (), memaddr, &m_di);
1078 gdb_assert (length > 0);
1082 /* Push any disassemble output to the real destination stream. We do
1083 this even if the disassembler reported failure (-1) as the
1084 disassembler may have printed something to its output stream. */
1085 gdb_printf (m_dest, "%s", m_buffer.c_str ());
1087 /* If the disassembler failed then report an appropriate error. */
1088 if (length < 0)
1090 if (m_err_memaddr.has_value ())
1091 memory_error (TARGET_XFER_E_IO, *m_err_memaddr);
1092 else
1093 error (_("unknown disassembler error (error = %d)"), length);
1096 if (branch_delay_insns != NULL)
1098 if (m_di.insn_info_valid)
1099 *branch_delay_insns = m_di.branch_delay_insns;
1100 else
1101 *branch_delay_insns = 0;
1103 return length;
1106 void
1107 gdb_disassembly (struct gdbarch *gdbarch, struct ui_out *uiout,
1108 gdb_disassembly_flags flags, int how_many,
1109 CORE_ADDR low, CORE_ADDR high)
1111 struct symtab *symtab;
1112 int nlines = -1;
1114 /* Assume symtab is valid for whole PC range. */
1115 symtab = find_pc_line_symtab (low);
1117 if (symtab != NULL && symtab->linetable () != NULL)
1118 nlines = symtab->linetable ()->nitems;
1120 if (!(flags & (DISASSEMBLY_SOURCE_DEPRECATED | DISASSEMBLY_SOURCE))
1121 || nlines <= 0)
1122 do_assembly_only (gdbarch, uiout, low, high, how_many, flags);
1124 else if (flags & DISASSEMBLY_SOURCE)
1125 do_mixed_source_and_assembly (gdbarch, uiout, symtab, low, high,
1126 how_many, flags);
1128 else if (flags & DISASSEMBLY_SOURCE_DEPRECATED)
1129 do_mixed_source_and_assembly_deprecated (gdbarch, uiout, symtab,
1130 low, high, how_many, flags);
1132 gdb_flush (gdb_stdout);
1135 /* Print the instruction at address MEMADDR in debugged memory,
1136 on STREAM. Returns the length of the instruction, in bytes,
1137 and, if requested, the number of branch delay slot instructions. */
1140 gdb_print_insn (struct gdbarch *gdbarch, CORE_ADDR memaddr,
1141 struct ui_file *stream, int *branch_delay_insns)
1144 gdb_disassembler di (gdbarch, stream);
1146 return di.print_insn (memaddr, branch_delay_insns);
1149 /* Return the length in bytes of the instruction at address MEMADDR in
1150 debugged memory. */
1153 gdb_insn_length (struct gdbarch *gdbarch, CORE_ADDR addr)
1155 return gdb_print_insn (gdbarch, addr, &null_stream, NULL);
1158 /* See disasm.h. */
1161 gdb_non_printing_disassembler::null_fprintf_func (void *stream,
1162 const char *format, ...)
1164 return 0;
1167 /* See disasm.h. */
1170 gdb_non_printing_disassembler::null_fprintf_styled_func
1171 (void *stream, enum disassembler_style style, const char *format, ...)
1173 return 0;
1176 /* A non-printing disassemble_info management class. The disassemble_info
1177 setup by this class will not print anything to the output stream (there
1178 is no output stream), and the instruction to be disassembled will be
1179 read from a buffer passed to the constructor. */
1181 struct gdb_non_printing_buffer_disassembler
1182 : public gdb_non_printing_disassembler
1184 /* Constructor. GDBARCH is the architecture to disassemble for, BUFFER
1185 contains the instruction to disassemble, and INSN_ADDRESS is the
1186 address (in target memory) of the instruction to disassemble. */
1187 gdb_non_printing_buffer_disassembler (struct gdbarch *gdbarch,
1188 gdb::array_view<const gdb_byte> buffer,
1189 CORE_ADDR insn_address)
1190 : gdb_non_printing_disassembler (gdbarch, nullptr)
1192 /* The cast is necessary until disassemble_info is const-ified. */
1193 m_di.buffer = (gdb_byte *) buffer.data ();
1194 m_di.buffer_length = buffer.size ();
1195 m_di.buffer_vma = insn_address;
1199 /* Return the length in bytes of INSN. MAX_LEN is the size of the
1200 buffer containing INSN. */
1203 gdb_buffered_insn_length (struct gdbarch *gdbarch,
1204 const gdb_byte *insn, int max_len, CORE_ADDR addr)
1206 gdb::array_view<const gdb_byte> buffer
1207 = gdb::make_array_view (insn, max_len);
1208 gdb_non_printing_buffer_disassembler dis (gdbarch, buffer, addr);
1209 int result = gdb_print_insn_1 (gdbarch, addr, dis.disasm_info ());
1210 return result;
1213 char *
1214 get_disassembler_options (struct gdbarch *gdbarch)
1216 char **disassembler_options = gdbarch_disassembler_options (gdbarch);
1217 if (disassembler_options == NULL)
1218 return NULL;
1219 return *disassembler_options;
1222 void
1223 set_disassembler_options (const char *prospective_options)
1225 struct gdbarch *gdbarch = get_current_arch ();
1226 char **disassembler_options = gdbarch_disassembler_options (gdbarch);
1227 const disasm_options_and_args_t *valid_options_and_args;
1228 const disasm_options_t *valid_options;
1229 gdb::unique_xmalloc_ptr<char> prospective_options_local
1230 = make_unique_xstrdup (prospective_options);
1231 char *options = remove_whitespace_and_extra_commas
1232 (prospective_options_local.get ());
1233 const char *opt;
1235 /* Allow all architectures, even ones that do not support 'set disassembler',
1236 to reset their disassembler options to NULL. */
1237 if (options == NULL)
1239 if (disassembler_options != NULL)
1241 free (*disassembler_options);
1242 *disassembler_options = NULL;
1244 return;
1247 valid_options_and_args = gdbarch_valid_disassembler_options (gdbarch);
1248 if (valid_options_and_args == NULL)
1250 gdb_printf (gdb_stderr, _("\
1251 'set disassembler-options ...' is not supported on this architecture.\n"));
1252 return;
1255 valid_options = &valid_options_and_args->options;
1257 /* Verify we have valid disassembler options. */
1258 FOR_EACH_DISASSEMBLER_OPTION (opt, options)
1260 size_t i;
1261 for (i = 0; valid_options->name[i] != NULL; i++)
1262 if (valid_options->arg != NULL && valid_options->arg[i] != NULL)
1264 size_t len = strlen (valid_options->name[i]);
1265 bool found = false;
1266 const char *arg;
1267 size_t j;
1269 if (memcmp (opt, valid_options->name[i], len) != 0)
1270 continue;
1271 arg = opt + len;
1272 if (valid_options->arg[i]->values == NULL)
1273 break;
1274 for (j = 0; valid_options->arg[i]->values[j] != NULL; j++)
1275 if (disassembler_options_cmp
1276 (arg, valid_options->arg[i]->values[j]) == 0)
1278 found = true;
1279 break;
1281 if (found)
1282 break;
1284 else if (disassembler_options_cmp (opt, valid_options->name[i]) == 0)
1285 break;
1286 if (valid_options->name[i] == NULL)
1288 gdb_printf (gdb_stderr,
1289 _("Invalid disassembler option value: '%s'.\n"),
1290 opt);
1291 return;
1295 free (*disassembler_options);
1296 *disassembler_options = xstrdup (options);
1299 static void
1300 set_disassembler_options_sfunc (const char *args, int from_tty,
1301 struct cmd_list_element *c)
1303 set_disassembler_options (prospective_options.c_str ());
1306 static void
1307 show_disassembler_options_sfunc (struct ui_file *file, int from_tty,
1308 struct cmd_list_element *c, const char *value)
1310 struct gdbarch *gdbarch = get_current_arch ();
1311 const disasm_options_and_args_t *valid_options_and_args;
1312 const disasm_option_arg_t *valid_args;
1313 const disasm_options_t *valid_options;
1315 const char *options = get_disassembler_options (gdbarch);
1316 if (options == NULL)
1317 options = "";
1319 gdb_printf (file, _("The current disassembler options are '%s'\n\n"),
1320 options);
1322 valid_options_and_args = gdbarch_valid_disassembler_options (gdbarch);
1324 if (valid_options_and_args == NULL)
1326 gdb_puts (_("There are no disassembler options available "
1327 "for this architecture.\n"),
1328 file);
1329 return;
1332 valid_options = &valid_options_and_args->options;
1334 gdb_printf (file, _("\
1335 The following disassembler options are supported for use with the\n\
1336 'set disassembler-options OPTION [,OPTION]...' command:\n"));
1338 if (valid_options->description != NULL)
1340 size_t i, max_len = 0;
1342 gdb_printf (file, "\n");
1344 /* Compute the length of the longest option name. */
1345 for (i = 0; valid_options->name[i] != NULL; i++)
1347 size_t len = strlen (valid_options->name[i]);
1349 if (valid_options->arg != NULL && valid_options->arg[i] != NULL)
1350 len += strlen (valid_options->arg[i]->name);
1351 if (max_len < len)
1352 max_len = len;
1355 for (i = 0, max_len++; valid_options->name[i] != NULL; i++)
1357 gdb_printf (file, " %s", valid_options->name[i]);
1358 if (valid_options->arg != NULL && valid_options->arg[i] != NULL)
1359 gdb_printf (file, "%s", valid_options->arg[i]->name);
1360 if (valid_options->description[i] != NULL)
1362 size_t len = strlen (valid_options->name[i]);
1364 if (valid_options->arg != NULL && valid_options->arg[i] != NULL)
1365 len += strlen (valid_options->arg[i]->name);
1366 gdb_printf (file, "%*c %s", (int) (max_len - len), ' ',
1367 valid_options->description[i]);
1369 gdb_printf (file, "\n");
1372 else
1374 size_t i;
1375 gdb_printf (file, " ");
1376 for (i = 0; valid_options->name[i] != NULL; i++)
1378 gdb_printf (file, "%s", valid_options->name[i]);
1379 if (valid_options->arg != NULL && valid_options->arg[i] != NULL)
1380 gdb_printf (file, "%s", valid_options->arg[i]->name);
1381 if (valid_options->name[i + 1] != NULL)
1382 gdb_printf (file, ", ");
1383 file->wrap_here (2);
1385 gdb_printf (file, "\n");
1388 valid_args = valid_options_and_args->args;
1389 if (valid_args != NULL)
1391 size_t i, j;
1393 for (i = 0; valid_args[i].name != NULL; i++)
1395 if (valid_args[i].values == NULL)
1396 continue;
1397 gdb_printf (file, _("\n\
1398 For the options above, the following values are supported for \"%s\":\n "),
1399 valid_args[i].name);
1400 for (j = 0; valid_args[i].values[j] != NULL; j++)
1402 gdb_printf (file, " %s", valid_args[i].values[j]);
1403 file->wrap_here (3);
1405 gdb_printf (file, "\n");
1410 /* A completion function for "set disassembler". */
1412 static void
1413 disassembler_options_completer (struct cmd_list_element *ignore,
1414 completion_tracker &tracker,
1415 const char *text, const char *word)
1417 struct gdbarch *gdbarch = get_current_arch ();
1418 const disasm_options_and_args_t *opts_and_args
1419 = gdbarch_valid_disassembler_options (gdbarch);
1421 if (opts_and_args != NULL)
1423 const disasm_options_t *opts = &opts_and_args->options;
1425 /* Only attempt to complete on the last option text. */
1426 const char *separator = strrchr (text, ',');
1427 if (separator != NULL)
1428 text = separator + 1;
1429 text = skip_spaces (text);
1430 complete_on_enum (tracker, opts->name, text, word);
1435 /* Initialization code. */
1437 void _initialize_disasm ();
1438 void
1439 _initialize_disasm ()
1441 /* Add the command that controls the disassembler options. */
1442 set_show_commands set_show_disas_opts
1443 = add_setshow_string_noescape_cmd ("disassembler-options", no_class,
1444 &prospective_options, _("\
1445 Set the disassembler options.\n\
1446 Usage: set disassembler-options OPTION [,OPTION]...\n\n\
1447 See: 'show disassembler-options' for valid option values."), _("\
1448 Show the disassembler options."), NULL,
1449 set_disassembler_options_sfunc,
1450 show_disassembler_options_sfunc,
1451 &setlist, &showlist);
1452 set_cmd_completer (set_show_disas_opts.set, disassembler_options_completer);
1455 /* All the 'maint set|show libopcodes-styling' sub-commands. */
1456 static struct cmd_list_element *maint_set_libopcodes_styling_cmdlist;
1457 static struct cmd_list_element *maint_show_libopcodes_styling_cmdlist;
1459 /* Adds 'maint set|show libopcodes-styling'. */
1460 add_setshow_prefix_cmd ("libopcodes-styling", class_maintenance,
1461 _("Set libopcodes-styling specific variables."),
1462 _("Show libopcodes-styling specific variables."),
1463 &maint_set_libopcodes_styling_cmdlist,
1464 &maint_show_libopcodes_styling_cmdlist,
1465 &maintenance_set_cmdlist,
1466 &maintenance_show_cmdlist);
1468 /* Adds 'maint set|show gnu-source-highlight enabled'. */
1469 add_setshow_boolean_cmd ("enabled", class_maintenance,
1470 &use_libopcodes_styling_option, _("\
1471 Set whether the libopcodes styling support should be used."), _("\
1472 Show whether the libopcodes styling support should be used."),_("\
1473 When enabled, GDB will try to make use of the builtin libopcodes styling\n\
1474 support, to style the disassembler output. Not every architecture has\n\
1475 styling support within libopcodes, so enabling this is not a guarantee\n\
1476 that libopcodes styling will be available.\n\
1478 When this option is disabled, GDB will make use of the Python Pygments\n\
1479 package (if available) to style the disassembler output.\n\
1481 All disassembler styling can be disabled with:\n\
1483 set style disassembler enabled off"),
1484 set_use_libopcodes_styling,
1485 show_use_libopcodes_styling,
1486 &maint_set_libopcodes_styling_cmdlist,
1487 &maint_show_libopcodes_styling_cmdlist);