1 //===-- EmulateInstruction.h ------------------------------------*- 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/Core/EmulateInstruction.h"
11 
12 #include "lldb/Core/Address.h"
13 #include "lldb/Core/DataBufferHeap.h"
14 #include "lldb/Core/DataExtractor.h"
15 #include "lldb/Core/Error.h"
16 #include "lldb/Core/PluginManager.h"
17 #include "lldb/Core/StreamString.h"
18 #include "lldb/Host/Endian.h"
19 #include "lldb/Symbol/UnwindPlan.h"
20 #include "lldb/Target/Process.h"
21 #include "lldb/Target/RegisterContext.h"
22 #include "lldb/Target/Target.h"
23 #include "lldb/Target/Thread.h"
24 
25 using namespace lldb;
26 using namespace lldb_private;
27 
28 EmulateInstruction*
29 EmulateInstruction::FindPlugin (const ArchSpec &arch, InstructionType supported_inst_type, const char *plugin_name)
30 {
31     EmulateInstructionCreateInstance create_callback = NULL;
32     if (plugin_name)
33     {
34         create_callback  = PluginManager::GetEmulateInstructionCreateCallbackForPluginName (plugin_name);
35         if (create_callback)
36         {
37            	EmulateInstruction *emulate_insn_ptr = create_callback(arch, supported_inst_type);
38             if (emulate_insn_ptr)
39                 return emulate_insn_ptr;
40         }
41     }
42     else
43     {
44         for (uint32_t idx = 0; (create_callback = PluginManager::GetEmulateInstructionCreateCallbackAtIndex(idx)) != NULL; ++idx)
45         {
46             EmulateInstruction *emulate_insn_ptr = create_callback(arch, supported_inst_type);
47             if (emulate_insn_ptr)
48                 return emulate_insn_ptr;
49         }
50     }
51     return NULL;
52 }
53 
54 EmulateInstruction::EmulateInstruction (const ArchSpec &arch) :
55     m_arch (arch),
56     m_baton (NULL),
57     m_read_mem_callback (&ReadMemoryDefault),
58     m_write_mem_callback (&WriteMemoryDefault),
59     m_read_reg_callback (&ReadRegisterDefault),
60     m_write_reg_callback (&WriteRegisterDefault),
61     m_addr (LLDB_INVALID_ADDRESS)
62 {
63     ::memset (&m_opcode, 0, sizeof (m_opcode));
64 }
65 
66 
67 uint64_t
68 EmulateInstruction::ReadRegisterUnsigned (uint32_t reg_kind, uint32_t reg_num, uint64_t fail_value, bool *success_ptr)
69 {
70     RegisterInfo reg_info;
71     if (GetRegisterInfo(reg_kind, reg_num, reg_info))
72         return ReadRegisterUnsigned (reg_info, fail_value, success_ptr);
73     if (success_ptr)
74         *success_ptr = false;
75     return fail_value;
76 }
77 
78 uint64_t
79 EmulateInstruction::ReadRegisterUnsigned (const RegisterInfo &reg_info, uint64_t fail_value, bool *success_ptr)
80 {
81     uint64_t uval64 = 0;
82     bool success = m_read_reg_callback (this, m_baton, reg_info, uval64);
83     if (success_ptr)
84         *success_ptr = success;
85     if (!success)
86         uval64 = fail_value;
87     return uval64;
88 }
89 
90 bool
91 EmulateInstruction::WriteRegisterUnsigned (const Context &context, uint32_t reg_kind, uint32_t reg_num, uint64_t reg_value)
92 {
93     RegisterInfo reg_info;
94     if (GetRegisterInfo(reg_kind, reg_num, reg_info))
95         return WriteRegisterUnsigned (context, reg_info, reg_value);
96     return false;
97 }
98 
99 bool
100 EmulateInstruction::WriteRegisterUnsigned (const Context &context, const RegisterInfo &reg_info, uint64_t reg_value)
101 {
102     return m_write_reg_callback (this, m_baton, context, reg_info, reg_value);
103 }
104 
105 uint64_t
106 EmulateInstruction::ReadMemoryUnsigned (const Context &context, lldb::addr_t addr, size_t byte_size, uint64_t fail_value, bool *success_ptr)
107 {
108     uint64_t uval64 = 0;
109     bool success = false;
110     if (byte_size <= 8)
111     {
112         uint8_t buf[sizeof(uint64_t)];
113         size_t bytes_read = m_read_mem_callback (this, m_baton, context, addr, buf, byte_size);
114         if (bytes_read == byte_size)
115         {
116             uint32_t offset = 0;
117             DataExtractor data (buf, byte_size, GetByteOrder(), GetAddressByteSize());
118             uval64 = data.GetMaxU64 (&offset, byte_size);
119             success = true;
120         }
121     }
122 
123     if (success_ptr)
124         *success_ptr = success;
125 
126     if (!success)
127         uval64 = fail_value;
128     return uval64;
129 }
130 
131 
132 bool
133 EmulateInstruction::WriteMemoryUnsigned (const Context &context,
134                                          lldb::addr_t addr,
135                                          uint64_t uval,
136                                          size_t uval_byte_size)
137 {
138     StreamString strm(Stream::eBinary, GetAddressByteSize(), GetByteOrder());
139     strm.PutMaxHex64 (uval, uval_byte_size);
140 
141     size_t bytes_written = m_write_mem_callback (this, m_baton, context, addr, strm.GetData(), uval_byte_size);
142     if (bytes_written == uval_byte_size)
143         return true;
144     return false;
145 }
146 
147 
148 void
149 EmulateInstruction::SetBaton (void *baton)
150 {
151     m_baton = baton;
152 }
153 
154 void
155 EmulateInstruction::SetCallbacks (ReadMemory read_mem_callback,
156                                   WriteMemory write_mem_callback,
157                                   ReadRegister read_reg_callback,
158                                   WriteRegister write_reg_callback)
159 {
160     m_read_mem_callback = read_mem_callback;
161     m_write_mem_callback = write_mem_callback;
162     m_read_reg_callback = read_reg_callback;
163     m_write_reg_callback = write_reg_callback;
164 }
165 
166 void
167 EmulateInstruction::SetReadMemCallback (ReadMemory read_mem_callback)
168 {
169     m_read_mem_callback = read_mem_callback;
170 }
171 
172 
173 void
174 EmulateInstruction::SetWriteMemCallback (WriteMemory write_mem_callback)
175 {
176     m_write_mem_callback = write_mem_callback;
177 }
178 
179 
180 void
181 EmulateInstruction::SetReadRegCallback (ReadRegister read_reg_callback)
182 {
183     m_read_reg_callback = read_reg_callback;
184 }
185 
186 
187 void
188 EmulateInstruction::SetWriteRegCallback (WriteRegister write_reg_callback)
189 {
190     m_write_reg_callback = write_reg_callback;
191 }
192 
193 
194 
195 //
196 //  Read & Write Memory and Registers callback functions.
197 //
198 
199 size_t
200 EmulateInstruction::ReadMemoryFrame (EmulateInstruction *instruction,
201                                      void *baton,
202                                      const Context &context,
203                                      lldb::addr_t addr,
204                                      void *dst,
205                                      size_t length)
206 {
207     if (!baton)
208         return 0;
209 
210 
211     StackFrame *frame = (StackFrame *) baton;
212 
213     DataBufferSP data_sp (new DataBufferHeap (length, '\0'));
214     Error error;
215 
216     size_t bytes_read = frame->GetThread().GetProcess().ReadMemory (addr, data_sp->GetBytes(), data_sp->GetByteSize(),
217                                                                     error);
218 
219     if (bytes_read > 0)
220         ((DataBufferHeap *) data_sp.get())->CopyData (dst, length);
221 
222     return bytes_read;
223 }
224 
225 size_t
226 EmulateInstruction::WriteMemoryFrame (EmulateInstruction *instruction,
227                                       void *baton,
228                                       const Context &context,
229                                       lldb::addr_t addr,
230                                       const void *dst,
231                                       size_t length)
232 {
233     if (!baton)
234         return 0;
235 
236     StackFrame *frame = (StackFrame *) baton;
237 
238     lldb::DataBufferSP data_sp (new DataBufferHeap (dst, length));
239     if (data_sp)
240     {
241         length = data_sp->GetByteSize();
242         if (length > 0)
243         {
244             Error error;
245             size_t bytes_written = frame->GetThread().GetProcess().WriteMemory (addr, data_sp->GetBytes(), length,
246                                                                                 error);
247 
248             return bytes_written;
249         }
250     }
251 
252     return 0;
253 }
254 
255 bool
256 EmulateInstruction::ReadRegisterFrame  (EmulateInstruction *instruction,
257                                         void *baton,
258                                         const RegisterInfo &reg_info,
259                                         uint64_t &reg_value)
260 {
261     if (!baton)
262         return false;
263 
264     StackFrame *frame = (StackFrame *) baton;
265     RegisterContext *reg_ctx = frame->GetRegisterContext().get();
266     Scalar value;
267 
268     const uint32_t internal_reg_num = GetInternalRegisterNumber (reg_ctx, reg_info);
269 
270     if (internal_reg_num != LLDB_INVALID_REGNUM)
271     {
272         if (reg_ctx->ReadRegisterValue (internal_reg_num, value))
273         {
274             reg_value = value.GetRawBits64 (0);
275             return true;
276         }
277     }
278     return false;
279 }
280 
281 bool
282 EmulateInstruction::WriteRegisterFrame (EmulateInstruction *instruction,
283                                         void *baton,
284                                         const Context &context,
285                                         const RegisterInfo &reg_info,
286                                         uint64_t reg_value)
287 {
288     if (!baton)
289         return false;
290 
291     StackFrame *frame = (StackFrame *) baton;
292     RegisterContext *reg_ctx = frame->GetRegisterContext().get();
293     Scalar value (reg_value);
294     const uint32_t internal_reg_num = GetInternalRegisterNumber (reg_ctx, reg_info);
295     if (internal_reg_num != LLDB_INVALID_REGNUM)
296         return reg_ctx->WriteRegisterValue (internal_reg_num, value);
297     return false;
298 }
299 
300 size_t
301 EmulateInstruction::ReadMemoryDefault (EmulateInstruction *instruction,
302                                        void *baton,
303                                        const Context &context,
304                                        lldb::addr_t addr,
305                                        void *dst,
306                                        size_t length)
307 {
308     fprintf (stdout, "    Read from Memory (address = 0x%llx, length = %zu, context = ", addr, length);
309     context.Dump (stdout, instruction);
310     *((uint64_t *) dst) = 0xdeadbeef;
311     return length;
312 }
313 
314 size_t
315 EmulateInstruction::WriteMemoryDefault (EmulateInstruction *instruction,
316                                         void *baton,
317                                         const Context &context,
318                                         lldb::addr_t addr,
319                                         const void *dst,
320                                         size_t length)
321 {
322     fprintf (stdout, "    Write to Memory (address = 0x%llx, length = %zu, context = ", addr, length);
323     context.Dump (stdout, instruction);
324     return length;
325 }
326 
327 bool
328 EmulateInstruction::ReadRegisterDefault  (EmulateInstruction *instruction,
329                                           void *baton,
330                                           const RegisterInfo &reg_info,
331                                           uint64_t &reg_value)
332 {
333     fprintf (stdout, "  Read Register (%s)\n", reg_info.name);
334     uint32_t reg_kind, reg_num;
335     if (GetBestRegisterKindAndNumber (reg_info, reg_kind, reg_num))
336         reg_value = (uint64_t)reg_kind << 24 | reg_num;
337     else
338         reg_value = 0;
339 
340     return true;
341 }
342 
343 bool
344 EmulateInstruction::WriteRegisterDefault (EmulateInstruction *instruction,
345                                           void *baton,
346                                           const Context &context,
347                                           const RegisterInfo &reg_info,
348                                           uint64_t reg_value)
349 {
350     fprintf (stdout, "    Write to Register (name = %s, value = 0x%llx, context = ", reg_info.name, reg_value);
351     context.Dump (stdout, instruction);
352     return true;
353 }
354 
355 void
356 EmulateInstruction::Context::Dump (FILE *fh,
357                                    EmulateInstruction *instruction) const
358 {
359     switch (type)
360     {
361         case eContextReadOpcode:
362             fprintf (fh, "reading opcode");
363             break;
364 
365         case eContextImmediate:
366             fprintf (fh, "immediate");
367             break;
368 
369         case eContextPushRegisterOnStack:
370             fprintf (fh, "push register");
371             break;
372 
373         case eContextPopRegisterOffStack:
374             fprintf (fh, "pop register");
375             break;
376 
377         case eContextAdjustStackPointer:
378             fprintf (fh, "adjust sp");
379             break;
380 
381         case eContextAdjustBaseRegister:
382             fprintf (fh, "adjusting (writing value back to) a base register");
383             break;
384 
385         case eContextRegisterPlusOffset:
386             fprintf (fh, "register + offset");
387             break;
388 
389         case eContextRegisterStore:
390             fprintf (fh, "store register");
391             break;
392 
393         case eContextRegisterLoad:
394             fprintf (fh, "load register");
395             break;
396 
397         case eContextRelativeBranchImmediate:
398             fprintf (fh, "relative branch immediate");
399             break;
400 
401         case eContextAbsoluteBranchRegister:
402             fprintf (fh, "absolute branch register");
403             break;
404 
405         case eContextSupervisorCall:
406             fprintf (fh, "supervisor call");
407             break;
408 
409         case eContextTableBranchReadMemory:
410             fprintf (fh, "table branch read memory");
411             break;
412 
413         case eContextWriteRegisterRandomBits:
414             fprintf (fh, "write random bits to a register");
415             break;
416 
417         case eContextWriteMemoryRandomBits:
418             fprintf (fh, "write random bits to a memory address");
419             break;
420 
421         case eContextArithmetic:
422             fprintf (fh, "arithmetic");
423             break;
424 
425         case eContextReturnFromException:
426             fprintf (fh, "return from exception");
427             break;
428 
429         default:
430             fprintf (fh, "unrecognized context.");
431             break;
432     }
433 
434     switch (info_type)
435     {
436     case eInfoTypeRegisterPlusOffset:
437         {
438             fprintf (fh,
439                      " (reg_plus_offset = %s%+lld)\n",
440                      info.RegisterPlusOffset.reg.name,
441                      info.RegisterPlusOffset.signed_offset);
442         }
443         break;
444 
445     case eInfoTypeRegisterPlusIndirectOffset:
446         {
447             fprintf (fh, " (reg_plus_reg = %s + %s)\n",
448                      info.RegisterPlusIndirectOffset.base_reg.name,
449                      info.RegisterPlusIndirectOffset.offset_reg.name);
450         }
451         break;
452 
453     case eInfoTypeRegisterToRegisterPlusOffset:
454         {
455             fprintf (fh, " (base_and_imm_offset = %s%+lld, data_reg = %s)\n",
456                      info.RegisterToRegisterPlusOffset.base_reg.name,
457                      info.RegisterToRegisterPlusOffset.offset,
458                      info.RegisterToRegisterPlusOffset.data_reg.name);
459         }
460         break;
461 
462     case eInfoTypeRegisterToRegisterPlusIndirectOffset:
463         {
464             fprintf (fh, " (base_and_reg_offset = %s + %s, data_reg = %s)\n",
465                      info.RegisterToRegisterPlusIndirectOffset.base_reg.name,
466                      info.RegisterToRegisterPlusIndirectOffset.offset_reg.name,
467                      info.RegisterToRegisterPlusIndirectOffset.data_reg.name);
468         }
469         break;
470 
471     case eInfoTypeRegisterRegisterOperands:
472         {
473             fprintf (fh, " (register to register binary op: %s and %s)\n",
474                      info.RegisterRegisterOperands.operand1.name,
475                      info.RegisterRegisterOperands.operand2.name);
476         }
477         break;
478 
479     case eInfoTypeOffset:
480         fprintf (fh, " (signed_offset = %+lld)\n", info.signed_offset);
481         break;
482 
483     case eInfoTypeRegister:
484         fprintf (fh, " (reg = %s)\n", info.reg.name);
485         break;
486 
487     case eInfoTypeImmediate:
488         fprintf (fh,
489                  " (unsigned_immediate = %llu (0x%16.16llx))\n",
490                  info.unsigned_immediate,
491                  info.unsigned_immediate);
492         break;
493 
494     case eInfoTypeImmediateSigned:
495         fprintf (fh,
496                  " (signed_immediate = %+lld (0x%16.16llx))\n",
497                  info.signed_immediate,
498                  info.signed_immediate);
499         break;
500 
501     case eInfoTypeAddress:
502         fprintf (fh, " (address = 0x%llx)\n", info.address);
503         break;
504 
505     case eInfoTypeISAAndImmediate:
506         fprintf (fh,
507                  " (isa = %u, unsigned_immediate = %u (0x%8.8x))\n",
508                  info.ISAAndImmediate.isa,
509                  info.ISAAndImmediate.unsigned_data32,
510                  info.ISAAndImmediate.unsigned_data32);
511         break;
512 
513     case eInfoTypeISAAndImmediateSigned:
514         fprintf (fh,
515                  " (isa = %u, signed_immediate = %i (0x%8.8x))\n",
516                  info.ISAAndImmediateSigned.isa,
517                  info.ISAAndImmediateSigned.signed_data32,
518                  info.ISAAndImmediateSigned.signed_data32);
519         break;
520 
521     case eInfoTypeISA:
522         fprintf (fh, " (isa = %u)\n", info.isa);
523         break;
524 
525     case eInfoTypeNoArgs:
526         fprintf (fh, " \n");
527         break;
528 
529     default:
530         fprintf (fh, " (unknown <info_type>)\n");
531         break;
532     }
533 }
534 
535 bool
536 EmulateInstruction::SetInstruction (const Opcode &opcode, const Address &inst_addr, Target *target)
537 {
538     m_opcode = opcode;
539     m_addr = LLDB_INVALID_ADDRESS;
540     if (inst_addr.IsValid())
541     {
542         if (target)
543             m_addr = inst_addr.GetLoadAddress (target);
544         if (m_addr == LLDB_INVALID_ADDRESS)
545             m_addr = inst_addr.GetFileAddress ();
546     }
547     return true;
548 }
549 
550 bool
551 EmulateInstruction::GetBestRegisterKindAndNumber (const RegisterInfo &reg_info,
552                                                   uint32_t &reg_kind,
553                                                   uint32_t &reg_num)
554 {
555     // Generic and DWARF should be the two most popular register kinds when
556     // emulating instructions since they are the most platform agnostic...
557     reg_num = reg_info.kinds[eRegisterKindGeneric];
558     if (reg_num != LLDB_INVALID_REGNUM)
559     {
560         reg_kind = eRegisterKindGeneric;
561         return true;
562     }
563 
564     reg_num = reg_info.kinds[eRegisterKindDWARF];
565     if (reg_num != LLDB_INVALID_REGNUM)
566     {
567         reg_kind = eRegisterKindDWARF;
568         return true;
569     }
570 
571     reg_num = reg_info.kinds[eRegisterKindLLDB];
572     if (reg_num != LLDB_INVALID_REGNUM)
573     {
574         reg_kind = eRegisterKindLLDB;
575         return true;
576     }
577 
578     reg_num = reg_info.kinds[eRegisterKindGCC];
579     if (reg_num != LLDB_INVALID_REGNUM)
580     {
581         reg_kind = eRegisterKindGCC;
582         return true;
583     }
584 
585     reg_num = reg_info.kinds[eRegisterKindGDB];
586     if (reg_num != LLDB_INVALID_REGNUM)
587     {
588         reg_kind = eRegisterKindGDB;
589         return true;
590     }
591     return false;
592 }
593 
594 uint32_t
595 EmulateInstruction::GetInternalRegisterNumber (RegisterContext *reg_ctx, const RegisterInfo &reg_info)
596 {
597     uint32_t reg_kind, reg_num;
598     if (reg_ctx && GetBestRegisterKindAndNumber (reg_info, reg_kind, reg_num))
599         return reg_ctx->ConvertRegisterKindToRegisterNumber (reg_kind, reg_num);
600     return LLDB_INVALID_REGNUM;
601 }
602 
603 
604 bool
605 EmulateInstruction::CreateFunctionEntryUnwind (UnwindPlan &unwind_plan)
606 {
607     unwind_plan.Clear();
608     return false;
609 }
610 
611 
612