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