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