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