1 //===-- Disassembler.cpp ----------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/lldb-python.h"
11 
12 #include "lldb/Core/Disassembler.h"
13 
14 // C Includes
15 // C++ Includes
16 // Other libraries and framework includes
17 // Project includes
18 #include "lldb/lldb-private.h"
19 #include "lldb/Core/Error.h"
20 #include "lldb/Core/DataBufferHeap.h"
21 #include "lldb/Core/DataExtractor.h"
22 #include "lldb/Core/Debugger.h"
23 #include "lldb/Core/EmulateInstruction.h"
24 #include "lldb/Core/Module.h"
25 #include "lldb/Core/PluginManager.h"
26 #include "lldb/Core/RegularExpression.h"
27 #include "lldb/Core/Timer.h"
28 #include "lldb/Interpreter/OptionValue.h"
29 #include "lldb/Interpreter/OptionValueArray.h"
30 #include "lldb/Interpreter/OptionValueDictionary.h"
31 #include "lldb/Interpreter/OptionValueString.h"
32 #include "lldb/Interpreter/OptionValueUInt64.h"
33 #include "lldb/Symbol/ClangNamespaceDecl.h"
34 #include "lldb/Symbol/Function.h"
35 #include "lldb/Symbol/ObjectFile.h"
36 #include "lldb/Target/ExecutionContext.h"
37 #include "lldb/Target/Process.h"
38 #include "lldb/Target/StackFrame.h"
39 #include "lldb/Target/Target.h"
40 
41 #define DEFAULT_DISASM_BYTE_SIZE 32
42 
43 using namespace lldb;
44 using namespace lldb_private;
45 
46 
47 DisassemblerSP
48 Disassembler::FindPlugin (const ArchSpec &arch, const char *plugin_name)
49 {
50     Timer scoped_timer (__PRETTY_FUNCTION__,
51                         "Disassembler::FindPlugin (arch = %s, plugin_name = %s)",
52                         arch.GetArchitectureName(),
53                         plugin_name);
54 
55     DisassemblerCreateInstance create_callback = NULL;
56 
57     if (plugin_name)
58     {
59         create_callback = PluginManager::GetDisassemblerCreateCallbackForPluginName (plugin_name);
60         if (create_callback)
61         {
62             DisassemblerSP disassembler_sp(create_callback(arch));
63 
64             if (disassembler_sp.get())
65                 return disassembler_sp;
66         }
67     }
68     else
69     {
70         for (uint32_t idx = 0; (create_callback = PluginManager::GetDisassemblerCreateCallbackAtIndex(idx)) != NULL; ++idx)
71         {
72             DisassemblerSP disassembler_sp(create_callback(arch));
73 
74             if (disassembler_sp.get())
75                 return disassembler_sp;
76         }
77     }
78     return DisassemblerSP();
79 }
80 
81 
82 static void
83 ResolveAddress (const ExecutionContext &exe_ctx,
84                 const Address &addr,
85                 Address &resolved_addr)
86 {
87     if (!addr.IsSectionOffset())
88     {
89         // If we weren't passed in a section offset address range,
90         // try and resolve it to something
91         Target *target = exe_ctx.GetTargetPtr();
92         if (target)
93         {
94             if (target->GetSectionLoadList().IsEmpty())
95             {
96                 target->GetImages().ResolveFileAddress (addr.GetOffset(), resolved_addr);
97             }
98             else
99             {
100                 target->GetSectionLoadList().ResolveLoadAddress (addr.GetOffset(), resolved_addr);
101             }
102             // We weren't able to resolve the address, just treat it as a
103             // raw address
104             if (resolved_addr.IsValid())
105                 return;
106         }
107     }
108     resolved_addr = addr;
109 }
110 
111 size_t
112 Disassembler::Disassemble
113 (
114     Debugger &debugger,
115     const ArchSpec &arch,
116     const char *plugin_name,
117     const ExecutionContext &exe_ctx,
118     SymbolContextList &sc_list,
119     uint32_t num_instructions,
120     uint32_t num_mixed_context_lines,
121     uint32_t options,
122     Stream &strm
123 )
124 {
125     size_t success_count = 0;
126     const size_t count = sc_list.GetSize();
127     SymbolContext sc;
128     AddressRange range;
129     const uint32_t scope = eSymbolContextBlock | eSymbolContextFunction | eSymbolContextSymbol;
130     const bool use_inline_block_range = true;
131     for (size_t i=0; i<count; ++i)
132     {
133         if (sc_list.GetContextAtIndex(i, sc) == false)
134             break;
135         for (uint32_t range_idx = 0; sc.GetAddressRange(scope, range_idx, use_inline_block_range, range); ++range_idx)
136         {
137             if (Disassemble (debugger,
138                              arch,
139                              plugin_name,
140                              exe_ctx,
141                              range,
142                              num_instructions,
143                              num_mixed_context_lines,
144                              options,
145                              strm))
146             {
147                 ++success_count;
148                 strm.EOL();
149             }
150         }
151     }
152     return success_count;
153 }
154 
155 bool
156 Disassembler::Disassemble
157 (
158     Debugger &debugger,
159     const ArchSpec &arch,
160     const char *plugin_name,
161     const ExecutionContext &exe_ctx,
162     const ConstString &name,
163     Module *module,
164     uint32_t num_instructions,
165     uint32_t num_mixed_context_lines,
166     uint32_t options,
167     Stream &strm
168 )
169 {
170     SymbolContextList sc_list;
171     if (name)
172     {
173         const bool include_symbols = true;
174         const bool include_inlines = true;
175         if (module)
176         {
177             module->FindFunctions (name,
178                                    NULL,
179                                    eFunctionNameTypeBase |
180                                    eFunctionNameTypeFull |
181                                    eFunctionNameTypeMethod |
182                                    eFunctionNameTypeSelector,
183                                    include_symbols,
184                                    include_inlines,
185                                    true,
186                                    sc_list);
187         }
188         else if (exe_ctx.GetTargetPtr())
189         {
190             exe_ctx.GetTargetPtr()->GetImages().FindFunctions (name,
191                                                                eFunctionNameTypeBase |
192                                                                eFunctionNameTypeFull |
193                                                                eFunctionNameTypeMethod |
194                                                                eFunctionNameTypeSelector,
195                                                                include_symbols,
196                                                                include_inlines,
197                                                                false,
198                                                                sc_list);
199         }
200     }
201 
202     if (sc_list.GetSize ())
203     {
204         return Disassemble (debugger,
205                             arch,
206                             plugin_name,
207                             exe_ctx,
208                             sc_list,
209                             num_instructions,
210                             num_mixed_context_lines,
211                             options,
212                             strm);
213     }
214     return false;
215 }
216 
217 
218 lldb::DisassemblerSP
219 Disassembler::DisassembleRange
220 (
221     const ArchSpec &arch,
222     const char *plugin_name,
223     const ExecutionContext &exe_ctx,
224     const AddressRange &range
225 )
226 {
227     lldb::DisassemblerSP disasm_sp;
228     if (range.GetByteSize() > 0 && range.GetBaseAddress().IsValid())
229     {
230         disasm_sp = Disassembler::FindPlugin(arch, plugin_name);
231 
232         if (disasm_sp)
233         {
234             size_t bytes_disassembled = disasm_sp->ParseInstructions (&exe_ctx, range, NULL);
235             if (bytes_disassembled == 0)
236                 disasm_sp.reset();
237         }
238     }
239     return disasm_sp;
240 }
241 
242 lldb::DisassemblerSP
243 Disassembler::DisassembleBytes
244 (
245     const ArchSpec &arch,
246     const char *plugin_name,
247     const Address &start,
248     const void *bytes,
249     size_t length,
250     uint32_t num_instructions
251 )
252 {
253     lldb::DisassemblerSP disasm_sp;
254 
255     if (bytes)
256     {
257         disasm_sp = Disassembler::FindPlugin(arch, plugin_name);
258 
259         if (disasm_sp)
260         {
261             DataExtractor data(bytes, length, arch.GetByteOrder(), arch.GetAddressByteSize());
262 
263             (void)disasm_sp->DecodeInstructions (start,
264                                                  data,
265                                                  0,
266                                                  num_instructions,
267                                                  false);
268         }
269     }
270 
271     return disasm_sp;
272 }
273 
274 
275 bool
276 Disassembler::Disassemble
277 (
278     Debugger &debugger,
279     const ArchSpec &arch,
280     const char *plugin_name,
281     const ExecutionContext &exe_ctx,
282     const AddressRange &disasm_range,
283     uint32_t num_instructions,
284     uint32_t num_mixed_context_lines,
285     uint32_t options,
286     Stream &strm
287 )
288 {
289     if (disasm_range.GetByteSize())
290     {
291         lldb::DisassemblerSP disasm_sp (Disassembler::FindPlugin(arch, plugin_name));
292 
293         if (disasm_sp.get())
294         {
295             AddressRange range;
296             ResolveAddress (exe_ctx, disasm_range.GetBaseAddress(), range.GetBaseAddress());
297             range.SetByteSize (disasm_range.GetByteSize());
298 
299             size_t bytes_disassembled = disasm_sp->ParseInstructions (&exe_ctx, range, &strm);
300             if (bytes_disassembled == 0)
301                 return false;
302 
303             return PrintInstructions (disasm_sp.get(),
304                                       debugger,
305                                       arch,
306                                       exe_ctx,
307                                       num_instructions,
308                                       num_mixed_context_lines,
309                                       options,
310                                       strm);
311         }
312     }
313     return false;
314 }
315 
316 bool
317 Disassembler::Disassemble
318 (
319     Debugger &debugger,
320     const ArchSpec &arch,
321     const char *plugin_name,
322     const ExecutionContext &exe_ctx,
323     const Address &start_address,
324     uint32_t num_instructions,
325     uint32_t num_mixed_context_lines,
326     uint32_t options,
327     Stream &strm
328 )
329 {
330     if (num_instructions > 0)
331     {
332         lldb::DisassemblerSP disasm_sp (Disassembler::FindPlugin(arch, plugin_name));
333         if (disasm_sp.get())
334         {
335             Address addr;
336             ResolveAddress (exe_ctx, start_address, addr);
337 
338             size_t bytes_disassembled = disasm_sp->ParseInstructions (&exe_ctx, addr, num_instructions);
339             if (bytes_disassembled == 0)
340                 return false;
341             return PrintInstructions (disasm_sp.get(),
342                                       debugger,
343                                       arch,
344                                       exe_ctx,
345                                       num_instructions,
346                                       num_mixed_context_lines,
347                                       options,
348                                       strm);
349         }
350     }
351     return false;
352 }
353 
354 bool
355 Disassembler::PrintInstructions
356 (
357     Disassembler *disasm_ptr,
358     Debugger &debugger,
359     const ArchSpec &arch,
360     const ExecutionContext &exe_ctx,
361     uint32_t num_instructions,
362     uint32_t num_mixed_context_lines,
363     uint32_t options,
364     Stream &strm
365 )
366 {
367     // We got some things disassembled...
368     size_t num_instructions_found = disasm_ptr->GetInstructionList().GetSize();
369 
370     if (num_instructions > 0 && num_instructions < num_instructions_found)
371         num_instructions_found = num_instructions;
372 
373     const uint32_t max_opcode_byte_size = disasm_ptr->GetInstructionList().GetMaxOpcocdeByteSize ();
374     uint32_t offset = 0;
375     SymbolContext sc;
376     SymbolContext prev_sc;
377     AddressRange sc_range;
378     const Address *pc_addr_ptr = NULL;
379     ExecutionContextScope *exe_scope = exe_ctx.GetBestExecutionContextScope();
380     StackFrame *frame = exe_ctx.GetFramePtr();
381 
382     if (frame)
383         pc_addr_ptr = &frame->GetFrameCodeAddress();
384     const uint32_t scope = eSymbolContextLineEntry | eSymbolContextFunction | eSymbolContextSymbol;
385     const bool use_inline_block_range = false;
386     for (size_t i=0; i<num_instructions_found; ++i)
387     {
388         Instruction *inst = disasm_ptr->GetInstructionList().GetInstructionAtIndex (i).get();
389         if (inst)
390         {
391             const Address &addr = inst->GetAddress();
392             const bool inst_is_at_pc = pc_addr_ptr && addr == *pc_addr_ptr;
393 
394             prev_sc = sc;
395 
396             ModuleSP module_sp (addr.GetModule());
397             if (module_sp)
398             {
399                 uint32_t resolved_mask = module_sp->ResolveSymbolContextForAddress(addr, eSymbolContextEverything, sc);
400                 if (resolved_mask)
401                 {
402                     if (num_mixed_context_lines)
403                     {
404                         if (!sc_range.ContainsFileAddress (addr))
405                         {
406                             sc.GetAddressRange (scope, 0, use_inline_block_range, sc_range);
407 
408                             if (sc != prev_sc)
409                             {
410                                 if (offset != 0)
411                                     strm.EOL();
412 
413                                 sc.DumpStopContext(&strm, exe_ctx.GetProcessPtr(), addr, false, true, false);
414                                 strm.EOL();
415 
416                                 if (sc.comp_unit && sc.line_entry.IsValid())
417                                 {
418                                     debugger.GetSourceManager().DisplaySourceLinesWithLineNumbers (sc.line_entry.file,
419                                                                                                    sc.line_entry.line,
420                                                                                                    num_mixed_context_lines,
421                                                                                                    num_mixed_context_lines,
422                                                                                                    ((inst_is_at_pc && (options & eOptionMarkPCSourceLine)) ? "->" : ""),
423                                                                                                    &strm);
424                                 }
425                             }
426                         }
427                     }
428                     else if ((sc.function || sc.symbol) && (sc.function != prev_sc.function || sc.symbol != prev_sc.symbol))
429                     {
430                         if (prev_sc.function || prev_sc.symbol)
431                             strm.EOL();
432 
433                         bool show_fullpaths = false;
434                         bool show_module = true;
435                         bool show_inlined_frames = true;
436                         sc.DumpStopContext (&strm,
437                                             exe_scope,
438                                             addr,
439                                             show_fullpaths,
440                                             show_module,
441                                             show_inlined_frames);
442 
443                         strm << ":\n";
444                     }
445                 }
446                 else
447                 {
448                     sc.Clear();
449                 }
450             }
451 
452             if ((options & eOptionMarkPCAddress) && pc_addr_ptr)
453             {
454                 strm.PutCString(inst_is_at_pc ? "-> " : "   ");
455             }
456             const bool show_bytes = (options & eOptionShowBytes) != 0;
457             inst->Dump(&strm, max_opcode_byte_size, true, show_bytes, &exe_ctx);
458             strm.EOL();
459         }
460         else
461         {
462             break;
463         }
464     }
465 
466     return true;
467 }
468 
469 
470 bool
471 Disassembler::Disassemble
472 (
473     Debugger &debugger,
474     const ArchSpec &arch,
475     const char *plugin_name,
476     const ExecutionContext &exe_ctx,
477     uint32_t num_instructions,
478     uint32_t num_mixed_context_lines,
479     uint32_t options,
480     Stream &strm
481 )
482 {
483     AddressRange range;
484     StackFrame *frame = exe_ctx.GetFramePtr();
485     if (frame)
486     {
487         SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol));
488         if (sc.function)
489         {
490             range = sc.function->GetAddressRange();
491         }
492         else if (sc.symbol && sc.symbol->ValueIsAddress())
493         {
494             range.GetBaseAddress() = sc.symbol->GetAddress();
495             range.SetByteSize (sc.symbol->GetByteSize());
496         }
497         else
498         {
499             range.GetBaseAddress() = frame->GetFrameCodeAddress();
500         }
501 
502         if (range.GetBaseAddress().IsValid() && range.GetByteSize() == 0)
503             range.SetByteSize (DEFAULT_DISASM_BYTE_SIZE);
504     }
505 
506     return Disassemble (debugger,
507                         arch,
508                         plugin_name,
509                         exe_ctx,
510                         range,
511                         num_instructions,
512                         num_mixed_context_lines,
513                         options,
514                         strm);
515 }
516 
517 Instruction::Instruction(const Address &address, AddressClass addr_class) :
518     m_address (address),
519     m_address_class (addr_class),
520     m_opcode(),
521     m_calculated_strings(false)
522 {
523 }
524 
525 Instruction::~Instruction()
526 {
527 }
528 
529 AddressClass
530 Instruction::GetAddressClass ()
531 {
532     if (m_address_class == eAddressClassInvalid)
533         m_address_class = m_address.GetAddressClass();
534     return m_address_class;
535 }
536 
537 void
538 Instruction::Dump (lldb_private::Stream *s,
539                    uint32_t max_opcode_byte_size,
540                    bool show_address,
541                    bool show_bytes,
542                    const ExecutionContext* exe_ctx)
543 {
544     const size_t opcode_column_width = 7;
545     const size_t operand_column_width = 25;
546 
547     CalculateMnemonicOperandsAndCommentIfNeeded (exe_ctx);
548 
549     StreamString ss;
550 
551     if (show_address)
552     {
553         m_address.Dump(&ss,
554                        exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL,
555                        Address::DumpStyleLoadAddress,
556                        Address::DumpStyleModuleWithFileAddress,
557                        0);
558 
559         ss.PutCString(":  ");
560     }
561 
562     if (show_bytes)
563     {
564         if (m_opcode.GetType() == Opcode::eTypeBytes)
565         {
566             // x86_64 and i386 are the only ones that use bytes right now so
567             // pad out the byte dump to be able to always show 15 bytes (3 chars each)
568             // plus a space
569             if (max_opcode_byte_size > 0)
570                 m_opcode.Dump (&ss, max_opcode_byte_size * 3 + 1);
571             else
572                 m_opcode.Dump (&ss, 15 * 3 + 1);
573         }
574         else
575         {
576             // Else, we have ARM which can show up to a uint32_t 0x00000000 (10 spaces)
577             // plus two for padding...
578             if (max_opcode_byte_size > 0)
579                 m_opcode.Dump (&ss, max_opcode_byte_size * 3 + 1);
580             else
581                 m_opcode.Dump (&ss, 12);
582         }
583     }
584 
585     const size_t opcode_pos = ss.GetSize();
586 
587     ss.PutCString (m_opcode_name.c_str());
588     ss.FillLastLineToColumn (opcode_pos + opcode_column_width, ' ');
589     ss.PutCString (m_mnemocics.c_str());
590 
591     if (!m_comment.empty())
592     {
593         ss.FillLastLineToColumn (opcode_pos + opcode_column_width + operand_column_width, ' ');
594         ss.PutCString (" ; ");
595         ss.PutCString (m_comment.c_str());
596     }
597     s->Write (ss.GetData(), ss.GetSize());
598 }
599 
600 bool
601 Instruction::DumpEmulation (const ArchSpec &arch)
602 {
603 	std::auto_ptr<EmulateInstruction> insn_emulator_ap (EmulateInstruction::FindPlugin (arch, eInstructionTypeAny, NULL));
604 	if (insn_emulator_ap.get())
605 	{
606         insn_emulator_ap->SetInstruction (GetOpcode(), GetAddress(), NULL);
607         return insn_emulator_ap->EvaluateInstruction (0);
608 	}
609 
610     return false;
611 }
612 
613 OptionValueSP
614 Instruction::ReadArray (FILE *in_file, Stream *out_stream, OptionValue::Type data_type)
615 {
616     bool done = false;
617     char buffer[1024];
618 
619     OptionValueSP option_value_sp (new OptionValueArray (1u << data_type));
620 
621     int idx = 0;
622     while (!done)
623     {
624         if (!fgets (buffer, 1023, in_file))
625         {
626             out_stream->Printf ("Instruction::ReadArray:  Error reading file (fgets).\n");
627             option_value_sp.reset ();
628             return option_value_sp;
629         }
630 
631         std::string line (buffer);
632 
633         int len = line.size();
634         if (line[len-1] == '\n')
635         {
636             line[len-1] = '\0';
637             line.resize (len-1);
638         }
639 
640         if ((line.size() == 1) && line[0] == ']')
641         {
642             done = true;
643             line.clear();
644         }
645 
646         if (line.size() > 0)
647         {
648             std::string value;
649             RegularExpression reg_exp ("^[ \t]*([^ \t]+)[ \t]*$");
650             bool reg_exp_success = reg_exp.Execute (line.c_str(), 1);
651             if (reg_exp_success)
652                 reg_exp.GetMatchAtIndex (line.c_str(), 1, value);
653             else
654                 value = line;
655 
656             OptionValueSP data_value_sp;
657             switch (data_type)
658             {
659             case OptionValue::eTypeUInt64:
660                 data_value_sp.reset (new OptionValueUInt64 (0, 0));
661                 data_value_sp->SetValueFromCString (value.c_str());
662                 break;
663             // Other types can be added later as needed.
664             default:
665                 data_value_sp.reset (new OptionValueString (value.c_str(), ""));
666                 break;
667             }
668 
669             option_value_sp->GetAsArray()->InsertValue (idx, data_value_sp);
670             ++idx;
671         }
672     }
673 
674     return option_value_sp;
675 }
676 
677 OptionValueSP
678 Instruction::ReadDictionary (FILE *in_file, Stream *out_stream)
679 {
680     bool done = false;
681     char buffer[1024];
682 
683     OptionValueSP option_value_sp (new OptionValueDictionary());
684     static ConstString encoding_key ("data_encoding");
685     OptionValue::Type data_type = OptionValue::eTypeInvalid;
686 
687 
688     while (!done)
689     {
690         // Read the next line in the file
691         if (!fgets (buffer, 1023, in_file))
692         {
693             out_stream->Printf ("Instruction::ReadDictionary: Error reading file (fgets).\n");
694             option_value_sp.reset ();
695             return option_value_sp;
696         }
697 
698         // Check to see if the line contains the end-of-dictionary marker ("}")
699         std::string line (buffer);
700 
701         int len = line.size();
702         if (line[len-1] == '\n')
703         {
704             line[len-1] = '\0';
705             line.resize (len-1);
706         }
707 
708         if ((line.size() == 1) && (line[0] == '}'))
709         {
710             done = true;
711             line.clear();
712         }
713 
714         // Try to find a key-value pair in the current line and add it to the dictionary.
715         if (line.size() > 0)
716         {
717             RegularExpression reg_exp ("^[ \t]*([a-zA-Z_][a-zA-Z0-9_]*)[ \t]*=[ \t]*(.*)[ \t]*$");
718             bool reg_exp_success = reg_exp.Execute (line.c_str(), 2);
719             std::string key;
720             std::string value;
721             if (reg_exp_success)
722             {
723                 reg_exp.GetMatchAtIndex (line.c_str(), 1, key);
724                 reg_exp.GetMatchAtIndex (line.c_str(), 2, value);
725             }
726             else
727             {
728                 out_stream->Printf ("Instruction::ReadDictionary: Failure executing regular expression.\n");
729                 option_value_sp.reset();
730                 return option_value_sp;
731             }
732 
733             ConstString const_key (key.c_str());
734             // Check value to see if it's the start of an array or dictionary.
735 
736             lldb::OptionValueSP value_sp;
737             assert (value.empty() == false);
738             assert (key.empty() == false);
739 
740             if (value[0] == '{')
741             {
742                 assert (value.size() == 1);
743                 // value is a dictionary
744                 value_sp = ReadDictionary (in_file, out_stream);
745                 if (value_sp.get() == NULL)
746                 {
747                     option_value_sp.reset ();
748                     return option_value_sp;
749                 }
750             }
751             else if (value[0] == '[')
752             {
753                 assert (value.size() == 1);
754                 // value is an array
755                 value_sp = ReadArray (in_file, out_stream, data_type);
756                 if (value_sp.get() == NULL)
757                 {
758                     option_value_sp.reset ();
759                     return option_value_sp;
760                 }
761                 // We've used the data_type to read an array; re-set the type to Invalid
762                 data_type = OptionValue::eTypeInvalid;
763             }
764             else if ((value[0] == '0') && (value[1] == 'x'))
765             {
766                 value_sp.reset (new OptionValueUInt64 (0, 0));
767                 value_sp->SetValueFromCString (value.c_str());
768             }
769             else
770             {
771                 int len = value.size();
772                 if ((value[0] == '"') && (value[len-1] == '"'))
773                     value = value.substr (1, len-2);
774                 value_sp.reset (new OptionValueString (value.c_str(), ""));
775             }
776 
777 
778 
779             if (const_key == encoding_key)
780             {
781                 // A 'data_encoding=..." is NOT a normal key-value pair; it is meta-data indicating the
782                 // data type of an upcoming array (usually the next bit of data to be read in).
783                 if (strcmp (value.c_str(), "uint32_t") == 0)
784                     data_type = OptionValue::eTypeUInt64;
785             }
786             else
787                 option_value_sp->GetAsDictionary()->SetValueForKey (const_key, value_sp, false);
788         }
789     }
790 
791     return option_value_sp;
792 }
793 
794 bool
795 Instruction::TestEmulation (Stream *out_stream, const char *file_name)
796 {
797     if (!out_stream)
798         return false;
799 
800     if (!file_name)
801     {
802         out_stream->Printf ("Instruction::TestEmulation:  Missing file_name.");
803         return false;
804     }
805 
806     FILE *test_file = fopen (file_name, "r");
807     if (!test_file)
808     {
809         out_stream->Printf ("Instruction::TestEmulation: Attempt to open test file failed.");
810         return false;
811     }
812 
813     char buffer[256];
814     if (!fgets (buffer, 255, test_file))
815     {
816         out_stream->Printf ("Instruction::TestEmulation: Error reading first line of test file.\n");
817         fclose (test_file);
818         return false;
819     }
820 
821     if (strncmp (buffer, "InstructionEmulationState={", 27) != 0)
822     {
823         out_stream->Printf ("Instructin::TestEmulation: Test file does not contain emulation state dictionary\n");
824         fclose (test_file);
825         return false;
826     }
827 
828     // Read all the test information from the test file into an OptionValueDictionary.
829 
830     OptionValueSP data_dictionary_sp (ReadDictionary (test_file, out_stream));
831     if (data_dictionary_sp.get() == NULL)
832     {
833         out_stream->Printf ("Instruction::TestEmulation:  Error reading Dictionary Object.\n");
834         fclose (test_file);
835         return false;
836     }
837 
838     fclose (test_file);
839 
840     OptionValueDictionary *data_dictionary = data_dictionary_sp->GetAsDictionary();
841     static ConstString description_key ("assembly_string");
842     static ConstString triple_key ("triple");
843 
844     OptionValueSP value_sp = data_dictionary->GetValueForKey (description_key);
845 
846     if (value_sp.get() == NULL)
847     {
848         out_stream->Printf ("Instruction::TestEmulation:  Test file does not contain description string.\n");
849         return false;
850     }
851 
852     SetDescription (value_sp->GetStringValue());
853 
854 
855     value_sp = data_dictionary->GetValueForKey (triple_key);
856     if (value_sp.get() == NULL)
857     {
858         out_stream->Printf ("Instruction::TestEmulation: Test file does not contain triple.\n");
859         return false;
860     }
861 
862     ArchSpec arch;
863     arch.SetTriple (llvm::Triple (value_sp->GetStringValue()));
864 
865     bool success = false;
866     std::auto_ptr<EmulateInstruction> insn_emulator_ap (EmulateInstruction::FindPlugin (arch, eInstructionTypeAny, NULL));
867     if (insn_emulator_ap.get())
868         success = insn_emulator_ap->TestEmulation (out_stream, arch, data_dictionary);
869 
870     if (success)
871         out_stream->Printf ("Emulation test succeeded.");
872     else
873         out_stream->Printf ("Emulation test failed.");
874 
875     return success;
876 }
877 
878 bool
879 Instruction::Emulate (const ArchSpec &arch,
880                       uint32_t evaluate_options,
881                       void *baton,
882                       EmulateInstruction::ReadMemoryCallback read_mem_callback,
883                       EmulateInstruction::WriteMemoryCallback write_mem_callback,
884                       EmulateInstruction::ReadRegisterCallback read_reg_callback,
885                       EmulateInstruction::WriteRegisterCallback write_reg_callback)
886 {
887 	std::auto_ptr<EmulateInstruction> insn_emulator_ap (EmulateInstruction::FindPlugin (arch, eInstructionTypeAny, NULL));
888 	if (insn_emulator_ap.get())
889 	{
890 		insn_emulator_ap->SetBaton (baton);
891 		insn_emulator_ap->SetCallbacks (read_mem_callback, write_mem_callback, read_reg_callback, write_reg_callback);
892         insn_emulator_ap->SetInstruction (GetOpcode(), GetAddress(), NULL);
893         return insn_emulator_ap->EvaluateInstruction (evaluate_options);
894 	}
895 
896     return false;
897 }
898 
899 
900 uint32_t
901 Instruction::GetData (DataExtractor &data)
902 {
903     return m_opcode.GetData(data);
904 }
905 
906 InstructionList::InstructionList() :
907     m_instructions()
908 {
909 }
910 
911 InstructionList::~InstructionList()
912 {
913 }
914 
915 size_t
916 InstructionList::GetSize() const
917 {
918     return m_instructions.size();
919 }
920 
921 uint32_t
922 InstructionList::GetMaxOpcocdeByteSize () const
923 {
924     uint32_t max_inst_size = 0;
925     collection::const_iterator pos, end;
926     for (pos = m_instructions.begin(), end = m_instructions.end();
927          pos != end;
928          ++pos)
929     {
930         uint32_t inst_size = (*pos)->GetOpcode().GetByteSize();
931         if (max_inst_size < inst_size)
932             max_inst_size = inst_size;
933     }
934     return max_inst_size;
935 }
936 
937 
938 
939 InstructionSP
940 InstructionList::GetInstructionAtIndex (uint32_t idx) const
941 {
942     InstructionSP inst_sp;
943     if (idx < m_instructions.size())
944         inst_sp = m_instructions[idx];
945     return inst_sp;
946 }
947 
948 void
949 InstructionList::Dump (Stream *s,
950                        bool show_address,
951                        bool show_bytes,
952                        const ExecutionContext* exe_ctx)
953 {
954     const uint32_t max_opcode_byte_size = GetMaxOpcocdeByteSize();
955     collection::const_iterator pos, begin, end;
956     for (begin = m_instructions.begin(), end = m_instructions.end(), pos = begin;
957          pos != end;
958          ++pos)
959     {
960         if (pos != begin)
961             s->EOL();
962         (*pos)->Dump(s, max_opcode_byte_size, show_address, show_bytes, exe_ctx);
963     }
964 }
965 
966 
967 void
968 InstructionList::Clear()
969 {
970   m_instructions.clear();
971 }
972 
973 void
974 InstructionList::Append (lldb::InstructionSP &inst_sp)
975 {
976     if (inst_sp)
977         m_instructions.push_back(inst_sp);
978 }
979 
980 uint32_t
981 InstructionList::GetIndexOfNextBranchInstruction(uint32_t start) const
982 {
983     size_t num_instructions = m_instructions.size();
984 
985     uint32_t next_branch = UINT32_MAX;
986     for (size_t i = start; i < num_instructions; i++)
987     {
988         if (m_instructions[i]->DoesBranch())
989         {
990             next_branch = i;
991             break;
992         }
993     }
994     return next_branch;
995 }
996 
997 uint32_t
998 InstructionList::GetIndexOfInstructionAtLoadAddress (lldb::addr_t load_addr, Target &target)
999 {
1000     Address address;
1001     address.SetLoadAddress(load_addr, &target);
1002     uint32_t num_instructions = m_instructions.size();
1003     uint32_t index = UINT32_MAX;
1004     for (int i = 0; i < num_instructions; i++)
1005     {
1006         if (m_instructions[i]->GetAddress() == address)
1007         {
1008             index = i;
1009             break;
1010         }
1011     }
1012     return index;
1013 }
1014 
1015 size_t
1016 Disassembler::ParseInstructions
1017 (
1018     const ExecutionContext *exe_ctx,
1019     const AddressRange &range,
1020     Stream *error_strm_ptr
1021 )
1022 {
1023     if (exe_ctx)
1024     {
1025         Target *target = exe_ctx->GetTargetPtr();
1026         const addr_t byte_size = range.GetByteSize();
1027         if (target == NULL || byte_size == 0 || !range.GetBaseAddress().IsValid())
1028             return 0;
1029 
1030         DataBufferHeap *heap_buffer = new DataBufferHeap (byte_size, '\0');
1031         DataBufferSP data_sp(heap_buffer);
1032 
1033         Error error;
1034         const bool prefer_file_cache = true;
1035         const size_t bytes_read = target->ReadMemory (range.GetBaseAddress(),
1036                                                       prefer_file_cache,
1037                                                       heap_buffer->GetBytes(),
1038                                                       heap_buffer->GetByteSize(),
1039                                                       error);
1040 
1041         if (bytes_read > 0)
1042         {
1043             if (bytes_read != heap_buffer->GetByteSize())
1044                 heap_buffer->SetByteSize (bytes_read);
1045             DataExtractor data (data_sp,
1046                                 m_arch.GetByteOrder(),
1047                                 m_arch.GetAddressByteSize());
1048             return DecodeInstructions (range.GetBaseAddress(), data, 0, UINT32_MAX, false);
1049         }
1050         else if (error_strm_ptr)
1051         {
1052             const char *error_cstr = error.AsCString();
1053             if (error_cstr)
1054             {
1055                 error_strm_ptr->Printf("error: %s\n", error_cstr);
1056             }
1057         }
1058     }
1059     else if (error_strm_ptr)
1060     {
1061         error_strm_ptr->PutCString("error: invalid execution context\n");
1062     }
1063     return 0;
1064 }
1065 
1066 size_t
1067 Disassembler::ParseInstructions
1068 (
1069     const ExecutionContext *exe_ctx,
1070     const Address &start,
1071     uint32_t num_instructions
1072 )
1073 {
1074     m_instruction_list.Clear();
1075 
1076     if (exe_ctx == NULL || num_instructions == 0 || !start.IsValid())
1077         return 0;
1078 
1079     Target *target = exe_ctx->GetTargetPtr();
1080     // Calculate the max buffer size we will need in order to disassemble
1081     const addr_t byte_size = num_instructions * m_arch.GetMaximumOpcodeByteSize();
1082 
1083     if (target == NULL || byte_size == 0)
1084         return 0;
1085 
1086     DataBufferHeap *heap_buffer = new DataBufferHeap (byte_size, '\0');
1087     DataBufferSP data_sp (heap_buffer);
1088 
1089     Error error;
1090     bool prefer_file_cache = true;
1091     const size_t bytes_read = target->ReadMemory (start,
1092                                                   prefer_file_cache,
1093                                                   heap_buffer->GetBytes(),
1094                                                   byte_size,
1095                                                   error);
1096 
1097     if (bytes_read == 0)
1098         return 0;
1099     DataExtractor data (data_sp,
1100                         m_arch.GetByteOrder(),
1101                         m_arch.GetAddressByteSize());
1102 
1103     const bool append_instructions = true;
1104     DecodeInstructions (start,
1105                         data,
1106                         0,
1107                         num_instructions,
1108                         append_instructions);
1109 
1110     return m_instruction_list.GetSize();
1111 }
1112 
1113 //----------------------------------------------------------------------
1114 // Disassembler copy constructor
1115 //----------------------------------------------------------------------
1116 Disassembler::Disassembler(const ArchSpec& arch) :
1117     m_arch (arch),
1118     m_instruction_list(),
1119     m_base_addr(LLDB_INVALID_ADDRESS)
1120 {
1121 
1122 }
1123 
1124 //----------------------------------------------------------------------
1125 // Destructor
1126 //----------------------------------------------------------------------
1127 Disassembler::~Disassembler()
1128 {
1129 }
1130 
1131 InstructionList &
1132 Disassembler::GetInstructionList ()
1133 {
1134     return m_instruction_list;
1135 }
1136 
1137 const InstructionList &
1138 Disassembler::GetInstructionList () const
1139 {
1140     return m_instruction_list;
1141 }
1142 
1143 //----------------------------------------------------------------------
1144 // Class PseudoInstruction
1145 //----------------------------------------------------------------------
1146 PseudoInstruction::PseudoInstruction () :
1147     Instruction (Address(), eAddressClassUnknown),
1148     m_description ()
1149 {
1150 }
1151 
1152 PseudoInstruction::~PseudoInstruction ()
1153 {
1154 }
1155 
1156 bool
1157 PseudoInstruction::DoesBranch () const
1158 {
1159     // This is NOT a valid question for a pseudo instruction.
1160     return false;
1161 }
1162 
1163 size_t
1164 PseudoInstruction::Decode (const lldb_private::Disassembler &disassembler,
1165                            const lldb_private::DataExtractor &data,
1166                            uint32_t data_offset)
1167 {
1168     return m_opcode.GetByteSize();
1169 }
1170 
1171 
1172 void
1173 PseudoInstruction::SetOpcode (size_t opcode_size, void *opcode_data)
1174 {
1175     if (!opcode_data)
1176         return;
1177 
1178     switch (opcode_size)
1179     {
1180         case 8:
1181         {
1182             uint8_t value8 = *((uint8_t *) opcode_data);
1183             m_opcode.SetOpcode8 (value8);
1184             break;
1185          }
1186         case 16:
1187         {
1188             uint16_t value16 = *((uint16_t *) opcode_data);
1189             m_opcode.SetOpcode16 (value16);
1190             break;
1191          }
1192         case 32:
1193         {
1194             uint32_t value32 = *((uint32_t *) opcode_data);
1195             m_opcode.SetOpcode32 (value32);
1196             break;
1197          }
1198         case 64:
1199         {
1200             uint64_t value64 = *((uint64_t *) opcode_data);
1201             m_opcode.SetOpcode64 (value64);
1202             break;
1203          }
1204         default:
1205             break;
1206     }
1207 }
1208 
1209 void
1210 PseudoInstruction::SetDescription (const char *description)
1211 {
1212     if (description && strlen (description) > 0)
1213         m_description = description;
1214 }
1215