1 //===-- IRExecutionUnit.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 "llvm/ExecutionEngine/ExecutionEngine.h"
11 #include "llvm/IR/LLVMContext.h"
12 #include "llvm/IR/Module.h"
13 #include "llvm/Support/SourceMgr.h"
14 #include "lldb/Core/DataBufferHeap.h"
15 #include "lldb/Core/DataExtractor.h"
16 #include "lldb/Core/Disassembler.h"
17 #include "lldb/Core/Log.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/Section.h"
20 #include "lldb/Expression/IRExecutionUnit.h"
21 #include "lldb/Target/ExecutionContext.h"
22 #include "lldb/Target/Target.h"
23 
24 using namespace lldb_private;
25 
26 IRExecutionUnit::IRExecutionUnit (std::unique_ptr<llvm::LLVMContext> &context_ap,
27                                   std::unique_ptr<llvm::Module> &module_ap,
28                                   ConstString &name,
29                                   const lldb::TargetSP &target_sp,
30                                   std::vector<std::string> &cpu_features) :
31     IRMemoryMap(target_sp),
32     m_context_ap(context_ap.release()),
33     m_module_ap(module_ap.release()),
34     m_module(m_module_ap.get()),
35     m_cpu_features(cpu_features),
36     m_name(name),
37     m_did_jit(false),
38     m_function_load_addr(LLDB_INVALID_ADDRESS),
39     m_function_end_load_addr(LLDB_INVALID_ADDRESS)
40 {
41 }
42 
43 lldb::addr_t
44 IRExecutionUnit::WriteNow (const uint8_t *bytes,
45                            size_t size,
46                            Error &error)
47 {
48     lldb::addr_t allocation_process_addr = Malloc (size,
49                                                    8,
50                                                    lldb::ePermissionsWritable | lldb::ePermissionsReadable,
51                                                    eAllocationPolicyMirror,
52                                                    error);
53 
54     if (!error.Success())
55         return LLDB_INVALID_ADDRESS;
56 
57     WriteMemory(allocation_process_addr, bytes, size, error);
58 
59     if (!error.Success())
60     {
61         Error err;
62         Free (allocation_process_addr, err);
63 
64         return LLDB_INVALID_ADDRESS;
65     }
66 
67     if (Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS))
68     {
69         DataBufferHeap my_buffer(size, 0);
70         Error err;
71         ReadMemory(my_buffer.GetBytes(), allocation_process_addr, size, err);
72 
73         if (err.Success())
74         {
75             DataExtractor my_extractor(my_buffer.GetBytes(), my_buffer.GetByteSize(), lldb::eByteOrderBig, 8);
76             my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(), allocation_process_addr, 16, DataExtractor::TypeUInt8);
77         }
78     }
79 
80     return allocation_process_addr;
81 }
82 
83 void
84 IRExecutionUnit::FreeNow (lldb::addr_t allocation)
85 {
86     if (allocation == LLDB_INVALID_ADDRESS)
87         return;
88 
89     Error err;
90 
91     Free(allocation, err);
92 }
93 
94 Error
95 IRExecutionUnit::DisassembleFunction (Stream &stream,
96                                       lldb::ProcessSP &process_wp)
97 {
98     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
99 
100     ExecutionContext exe_ctx(process_wp);
101 
102     Error ret;
103 
104     ret.Clear();
105 
106     lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
107     lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
108 
109     for (JittedFunction &function : m_jitted_functions)
110     {
111         if (strstr(function.m_name.c_str(), m_name.AsCString()))
112         {
113             func_local_addr = function.m_local_addr;
114             func_remote_addr = function.m_remote_addr;
115         }
116     }
117 
118     if (func_local_addr == LLDB_INVALID_ADDRESS)
119     {
120         ret.SetErrorToGenericError();
121         ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", m_name.AsCString());
122         return ret;
123     }
124 
125     if (log)
126         log->Printf("Found function, has local address 0x%" PRIx64 " and remote address 0x%" PRIx64, (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
127 
128     std::pair <lldb::addr_t, lldb::addr_t> func_range;
129 
130     func_range = GetRemoteRangeForLocal(func_local_addr);
131 
132     if (func_range.first == 0 && func_range.second == 0)
133     {
134         ret.SetErrorToGenericError();
135         ret.SetErrorStringWithFormat("Couldn't find code range for function %s", m_name.AsCString());
136         return ret;
137     }
138 
139     if (log)
140         log->Printf("Function's code range is [0x%" PRIx64 "+0x%" PRIx64 "]", func_range.first, func_range.second);
141 
142     Target *target = exe_ctx.GetTargetPtr();
143     if (!target)
144     {
145         ret.SetErrorToGenericError();
146         ret.SetErrorString("Couldn't find the target");
147         return ret;
148     }
149 
150     lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second, 0));
151 
152     Process *process = exe_ctx.GetProcessPtr();
153     Error err;
154     process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
155 
156     if (!err.Success())
157     {
158         ret.SetErrorToGenericError();
159         ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
160         return ret;
161     }
162 
163     ArchSpec arch(target->GetArchitecture());
164 
165     const char *plugin_name = NULL;
166     const char *flavor_string = NULL;
167     lldb::DisassemblerSP disassembler_sp = Disassembler::FindPlugin(arch, flavor_string, plugin_name);
168 
169     if (!disassembler_sp)
170     {
171         ret.SetErrorToGenericError();
172         ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
173         return ret;
174     }
175 
176     if (!process)
177     {
178         ret.SetErrorToGenericError();
179         ret.SetErrorString("Couldn't find the process");
180         return ret;
181     }
182 
183     DataExtractor extractor(buffer_sp,
184                             process->GetByteOrder(),
185                             target->GetArchitecture().GetAddressByteSize());
186 
187     if (log)
188     {
189         log->Printf("Function data has contents:");
190         extractor.PutToLog (log,
191                             0,
192                             extractor.GetByteSize(),
193                             func_remote_addr,
194                             16,
195                             DataExtractor::TypeUInt8);
196     }
197 
198     disassembler_sp->DecodeInstructions (Address (func_remote_addr), extractor, 0, UINT32_MAX, false, false);
199 
200     InstructionList &instruction_list = disassembler_sp->GetInstructionList();
201     const uint32_t max_opcode_byte_size = instruction_list.GetMaxOpcocdeByteSize();
202 
203     for (size_t instruction_index = 0, num_instructions = instruction_list.GetSize();
204          instruction_index < num_instructions;
205          ++instruction_index)
206     {
207         Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
208         instruction->Dump (&stream,
209                            max_opcode_byte_size,
210                            true,
211                            true,
212                            &exe_ctx);
213         stream.PutChar('\n');
214     }
215     // FIXME: The DisassemblerLLVMC has a reference cycle and won't go away if it has any active instructions.
216     // I'll fix that but for now, just clear the list and it will go away nicely.
217     disassembler_sp->GetInstructionList().Clear();
218     return ret;
219 }
220 
221 static void ReportInlineAsmError(const llvm::SMDiagnostic &diagnostic, void *Context, unsigned LocCookie)
222 {
223     Error *err = static_cast<Error*>(Context);
224 
225     if (err && err->Success())
226     {
227         err->SetErrorToGenericError();
228         err->SetErrorStringWithFormat("Inline assembly error: %s", diagnostic.getMessage().str().c_str());
229     }
230 }
231 
232 void
233 IRExecutionUnit::GetRunnableInfo(Error &error,
234                                  lldb::addr_t &func_addr,
235                                  lldb::addr_t &func_end)
236 {
237     lldb::ProcessSP process_sp(GetProcessWP().lock());
238 
239     static Mutex s_runnable_info_mutex(Mutex::Type::eMutexTypeRecursive);
240 
241     func_addr = LLDB_INVALID_ADDRESS;
242     func_end = LLDB_INVALID_ADDRESS;
243 
244     if (!process_sp)
245     {
246         error.SetErrorToGenericError();
247         error.SetErrorString("Couldn't write the JIT compiled code into the process because the process is invalid");
248         return;
249     }
250 
251     if (m_did_jit)
252     {
253         func_addr = m_function_load_addr;
254         func_end = m_function_end_load_addr;
255 
256         return;
257     };
258 
259     Mutex::Locker runnable_info_mutex_locker(s_runnable_info_mutex);
260 
261     m_did_jit = true;
262 
263     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
264 
265     std::string error_string;
266 
267     if (log)
268     {
269         std::string s;
270         llvm::raw_string_ostream oss(s);
271 
272         m_module->print(oss, NULL);
273 
274         oss.flush();
275 
276         log->Printf ("Module being sent to JIT: \n%s", s.c_str());
277     }
278 
279     llvm::Triple triple(m_module->getTargetTriple());
280     llvm::Function *function = m_module->getFunction (m_name.AsCString());
281     llvm::Reloc::Model relocModel;
282     llvm::CodeModel::Model codeModel;
283 
284     if (triple.isOSBinFormatELF())
285     {
286         relocModel = llvm::Reloc::Static;
287         // This will be small for 32-bit and large for 64-bit.
288         codeModel = llvm::CodeModel::JITDefault;
289     }
290     else
291     {
292         relocModel = llvm::Reloc::PIC_;
293         codeModel = llvm::CodeModel::Small;
294     }
295 
296     m_module_ap->getContext().setInlineAsmDiagnosticHandler(ReportInlineAsmError, &error);
297 
298     llvm::EngineBuilder builder(std::move(m_module_ap));
299 
300     builder.setEngineKind(llvm::EngineKind::JIT)
301     .setErrorStr(&error_string)
302     .setRelocationModel(relocModel)
303     .setJITMemoryManager(new MemoryManager(*this))
304     .setOptLevel(llvm::CodeGenOpt::Less)
305     .setAllocateGVsWithCode(true)
306     .setCodeModel(codeModel)
307     .setUseMCJIT(true);
308 
309     llvm::StringRef mArch;
310     llvm::StringRef mCPU;
311     llvm::SmallVector<std::string, 0> mAttrs;
312 
313     for (std::string &feature : m_cpu_features)
314         mAttrs.push_back(feature);
315 
316     llvm::TargetMachine *target_machine = builder.selectTarget(triple,
317                                                                mArch,
318                                                                mCPU,
319                                                                mAttrs);
320 
321     m_execution_engine_ap.reset(builder.create(target_machine));
322 
323     if (!m_execution_engine_ap.get())
324     {
325         error.SetErrorToGenericError();
326         error.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
327         return;
328     }
329 
330     // Make sure we see all sections, including ones that don't have relocations...
331     m_execution_engine_ap->setProcessAllSections(true);
332 
333     m_execution_engine_ap->DisableLazyCompilation();
334 
335     // We don't actually need the function pointer here, this just forces it to get resolved.
336 
337     void *fun_ptr = m_execution_engine_ap->getPointerToFunction(function);
338 
339     if (!error.Success())
340     {
341         // We got an error through our callback!
342         return;
343     }
344 
345     if (!function)
346     {
347         error.SetErrorToGenericError();
348         error.SetErrorStringWithFormat("Couldn't find '%s' in the JITted module", m_name.AsCString());
349         return;
350     }
351 
352     if (!fun_ptr)
353     {
354         error.SetErrorToGenericError();
355         error.SetErrorStringWithFormat("'%s' was in the JITted module but wasn't lowered", m_name.AsCString());
356         return;
357     }
358 
359     m_jitted_functions.push_back (JittedFunction(m_name.AsCString(), (lldb::addr_t)fun_ptr));
360 
361     CommitAllocations(process_sp);
362     ReportAllocations(*m_execution_engine_ap);
363     WriteData(process_sp);
364 
365     for (JittedFunction &jitted_function : m_jitted_functions)
366     {
367         jitted_function.m_remote_addr = GetRemoteAddressForLocal (jitted_function.m_local_addr);
368 
369         if (!jitted_function.m_name.compare(m_name.AsCString()))
370         {
371             AddrRange func_range = GetRemoteRangeForLocal(jitted_function.m_local_addr);
372             m_function_end_load_addr = func_range.first + func_range.second;
373             m_function_load_addr = jitted_function.m_remote_addr;
374         }
375     }
376 
377     if (log)
378     {
379         log->Printf("Code can be run in the target.");
380 
381         StreamString disassembly_stream;
382 
383         Error err = DisassembleFunction(disassembly_stream, process_sp);
384 
385         if (!err.Success())
386         {
387             log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
388         }
389         else
390         {
391             log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
392         }
393 
394         log->Printf("Sections: ");
395         for (AllocationRecord &record : m_records)
396         {
397             if (record.m_process_address != LLDB_INVALID_ADDRESS)
398             {
399                 record.dump(log);
400 
401                 DataBufferHeap my_buffer(record.m_size, 0);
402                 Error err;
403                 ReadMemory(my_buffer.GetBytes(), record.m_process_address, record.m_size, err);
404 
405                 if (err.Success())
406                 {
407                     DataExtractor my_extractor(my_buffer.GetBytes(), my_buffer.GetByteSize(), lldb::eByteOrderBig, 8);
408                     my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(), record.m_process_address, 16, DataExtractor::TypeUInt8);
409                 }
410             }
411         }
412     }
413 
414     func_addr = m_function_load_addr;
415     func_end = m_function_end_load_addr;
416 
417     return;
418 }
419 
420 IRExecutionUnit::~IRExecutionUnit ()
421 {
422     m_module_ap.reset();
423     m_execution_engine_ap.reset();
424     m_context_ap.reset();
425 }
426 
427 IRExecutionUnit::MemoryManager::MemoryManager (IRExecutionUnit &parent) :
428     m_default_mm_ap (llvm::JITMemoryManager::CreateDefaultMemManager()),
429     m_parent (parent)
430 {
431 }
432 
433 IRExecutionUnit::MemoryManager::~MemoryManager ()
434 {
435 }
436 void
437 IRExecutionUnit::MemoryManager::setMemoryWritable ()
438 {
439     m_default_mm_ap->setMemoryWritable();
440 }
441 
442 void
443 IRExecutionUnit::MemoryManager::setMemoryExecutable ()
444 {
445     m_default_mm_ap->setMemoryExecutable();
446 }
447 
448 
449 uint8_t *
450 IRExecutionUnit::MemoryManager::startFunctionBody(const llvm::Function *F,
451                                                   uintptr_t &ActualSize)
452 {
453     return m_default_mm_ap->startFunctionBody(F, ActualSize);
454 }
455 
456 uint8_t *
457 IRExecutionUnit::MemoryManager::allocateStub(const llvm::GlobalValue* F,
458                                              unsigned StubSize,
459                                              unsigned Alignment)
460 {
461     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
462 
463     uint8_t *return_value = m_default_mm_ap->allocateStub(F, StubSize, Alignment);
464 
465     m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
466                                                   lldb::ePermissionsReadable | lldb::ePermissionsWritable,
467                                                   GetSectionTypeFromSectionName (llvm::StringRef(), AllocationKind::Stub),
468                                                   StubSize,
469                                                   Alignment,
470                                                   eSectionIDInvalid,
471                                                   NULL));
472 
473     if (log)
474     {
475         log->Printf("IRExecutionUnit::allocateStub (F=%p, StubSize=%u, Alignment=%u) = %p",
476                     static_cast<const void*>(F), StubSize, Alignment,
477                     static_cast<void*>(return_value));
478     }
479 
480     return return_value;
481 }
482 
483 void
484 IRExecutionUnit::MemoryManager::endFunctionBody(const llvm::Function *F,
485                                                 uint8_t *FunctionStart,
486                                                 uint8_t *FunctionEnd)
487 {
488     m_default_mm_ap->endFunctionBody(F, FunctionStart, FunctionEnd);
489 }
490 
491 lldb::SectionType
492 IRExecutionUnit::GetSectionTypeFromSectionName (const llvm::StringRef &name, IRExecutionUnit::AllocationKind alloc_kind)
493 {
494     lldb::SectionType sect_type = lldb::eSectionTypeCode;
495     switch (alloc_kind)
496     {
497         case AllocationKind::Stub:  sect_type = lldb::eSectionTypeCode; break;
498         case AllocationKind::Code:  sect_type = lldb::eSectionTypeCode; break;
499         case AllocationKind::Data:  sect_type = lldb::eSectionTypeData; break;
500         case AllocationKind::Global:sect_type = lldb::eSectionTypeData; break;
501         case AllocationKind::Bytes: sect_type = lldb::eSectionTypeOther; break;
502     }
503 
504     if (!name.empty())
505     {
506         if (name.equals("__text") || name.equals(".text"))
507             sect_type = lldb::eSectionTypeCode;
508         else if (name.equals("__data") || name.equals(".data"))
509             sect_type = lldb::eSectionTypeCode;
510         else if (name.startswith("__debug_") || name.startswith(".debug_"))
511         {
512             const uint32_t name_idx = name[0] == '_' ? 8 : 7;
513             llvm::StringRef dwarf_name(name.substr(name_idx));
514             switch (dwarf_name[0])
515             {
516                 case 'a':
517                     if (dwarf_name.equals("abbrev"))
518                         sect_type = lldb::eSectionTypeDWARFDebugAbbrev;
519                     else if (dwarf_name.equals("aranges"))
520                         sect_type = lldb::eSectionTypeDWARFDebugAranges;
521                     break;
522 
523                 case 'f':
524                     if (dwarf_name.equals("frame"))
525                         sect_type = lldb::eSectionTypeDWARFDebugFrame;
526                     break;
527 
528                 case 'i':
529                     if (dwarf_name.equals("info"))
530                         sect_type = lldb::eSectionTypeDWARFDebugInfo;
531                     break;
532 
533                 case 'l':
534                     if (dwarf_name.equals("line"))
535                         sect_type = lldb::eSectionTypeDWARFDebugLine;
536                     else if (dwarf_name.equals("loc"))
537                         sect_type = lldb::eSectionTypeDWARFDebugLoc;
538                     break;
539 
540                 case 'm':
541                     if (dwarf_name.equals("macinfo"))
542                         sect_type = lldb::eSectionTypeDWARFDebugMacInfo;
543                     break;
544 
545                 case 'p':
546                     if (dwarf_name.equals("pubnames"))
547                         sect_type = lldb::eSectionTypeDWARFDebugPubNames;
548                     else if (dwarf_name.equals("pubtypes"))
549                         sect_type = lldb::eSectionTypeDWARFDebugPubTypes;
550                     break;
551 
552                 case 's':
553                     if (dwarf_name.equals("str"))
554                         sect_type = lldb::eSectionTypeDWARFDebugStr;
555                     break;
556 
557                 case 'r':
558                     if (dwarf_name.equals("ranges"))
559                         sect_type = lldb::eSectionTypeDWARFDebugRanges;
560                     break;
561 
562                 default:
563                     break;
564             }
565         }
566         else if (name.startswith("__apple_") || name.startswith(".apple_"))
567         {
568 #if 0
569             const uint32_t name_idx = name[0] == '_' ? 8 : 7;
570             llvm::StringRef apple_name(name.substr(name_idx));
571             switch (apple_name[0])
572             {
573                 case 'n':
574                     if (apple_name.equals("names"))
575                         sect_type = lldb::eSectionTypeDWARFAppleNames;
576                     else if (apple_name.equals("namespac") || apple_name.equals("namespaces"))
577                         sect_type = lldb::eSectionTypeDWARFAppleNamespaces;
578                     break;
579                 case 't':
580                     if (apple_name.equals("types"))
581                         sect_type = lldb::eSectionTypeDWARFAppleTypes;
582                     break;
583                 case 'o':
584                     if (apple_name.equals("objc"))
585                         sect_type = lldb::eSectionTypeDWARFAppleObjC;
586                     break;
587                 default:
588                     break;
589             }
590 #else
591             sect_type = lldb::eSectionTypeInvalid;
592 #endif
593         }
594         else if (name.equals("__objc_imageinfo"))
595             sect_type = lldb::eSectionTypeOther;
596     }
597     return sect_type;
598 }
599 
600 uint8_t *
601 IRExecutionUnit::MemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
602 {
603     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
604 
605     uint8_t *return_value = m_default_mm_ap->allocateSpace(Size, Alignment);
606 
607     m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
608                                                   lldb::ePermissionsReadable | lldb::ePermissionsWritable,
609                                                   GetSectionTypeFromSectionName (llvm::StringRef(), AllocationKind::Bytes),
610                                                   Size,
611                                                   Alignment,
612                                                   eSectionIDInvalid,
613                                                   NULL));
614 
615     if (log)
616     {
617         log->Printf("IRExecutionUnit::allocateSpace(Size=%" PRIu64 ", Alignment=%u) = %p",
618                                (uint64_t)Size, Alignment, return_value);
619     }
620 
621     return return_value;
622 }
623 
624 uint8_t *
625 IRExecutionUnit::MemoryManager::allocateCodeSection(uintptr_t Size,
626                                                     unsigned Alignment,
627                                                     unsigned SectionID,
628                                                     llvm::StringRef SectionName)
629 {
630     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
631 
632     uint8_t *return_value = m_default_mm_ap->allocateCodeSection(Size, Alignment, SectionID, SectionName);
633 
634     m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
635                                                   lldb::ePermissionsReadable | lldb::ePermissionsExecutable,
636                                                   GetSectionTypeFromSectionName (SectionName, AllocationKind::Code),
637                                                   Size,
638                                                   Alignment,
639                                                   SectionID,
640                                                   SectionName.str().c_str()));
641 
642     if (log)
643     {
644         log->Printf("IRExecutionUnit::allocateCodeSection(Size=0x%" PRIx64 ", Alignment=%u, SectionID=%u) = %p",
645                     (uint64_t)Size, Alignment, SectionID, return_value);
646     }
647 
648     return return_value;
649 }
650 
651 uint8_t *
652 IRExecutionUnit::MemoryManager::allocateDataSection(uintptr_t Size,
653                                                     unsigned Alignment,
654                                                     unsigned SectionID,
655                                                     llvm::StringRef SectionName,
656                                                     bool IsReadOnly)
657 {
658     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
659 
660     uint8_t *return_value = m_default_mm_ap->allocateDataSection(Size, Alignment, SectionID, SectionName, IsReadOnly);
661 
662     m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
663                                                   lldb::ePermissionsReadable | (IsReadOnly ? 0 : lldb::ePermissionsWritable),
664                                                   GetSectionTypeFromSectionName (SectionName, AllocationKind::Data),
665                                                   Size,
666                                                   Alignment,
667                                                   SectionID,
668                                                   SectionName.str().c_str()));
669     if (log)
670     {
671         log->Printf("IRExecutionUnit::allocateDataSection(Size=0x%" PRIx64 ", Alignment=%u, SectionID=%u) = %p",
672                     (uint64_t)Size, Alignment, SectionID, return_value);
673     }
674 
675     return return_value;
676 }
677 
678 uint8_t *
679 IRExecutionUnit::MemoryManager::allocateGlobal(uintptr_t Size,
680                                                unsigned Alignment)
681 {
682     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
683 
684     uint8_t *return_value = m_default_mm_ap->allocateGlobal(Size, Alignment);
685 
686     m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
687                                                   lldb::ePermissionsReadable | lldb::ePermissionsWritable,
688                                                   GetSectionTypeFromSectionName (llvm::StringRef(), AllocationKind::Global),
689                                                   Size,
690                                                   Alignment,
691                                                   eSectionIDInvalid,
692                                                   NULL));
693 
694     if (log)
695     {
696         log->Printf("IRExecutionUnit::allocateGlobal(Size=0x%" PRIx64 ", Alignment=%u) = %p",
697                     (uint64_t)Size, Alignment, return_value);
698     }
699 
700     return return_value;
701 }
702 
703 void
704 IRExecutionUnit::MemoryManager::deallocateFunctionBody(void *Body)
705 {
706     m_default_mm_ap->deallocateFunctionBody(Body);
707 }
708 
709 lldb::addr_t
710 IRExecutionUnit::GetRemoteAddressForLocal (lldb::addr_t local_address)
711 {
712     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
713 
714     for (AllocationRecord &record : m_records)
715     {
716         if (local_address >= record.m_host_address &&
717             local_address < record.m_host_address + record.m_size)
718         {
719             if (record.m_process_address == LLDB_INVALID_ADDRESS)
720                 return LLDB_INVALID_ADDRESS;
721 
722             lldb::addr_t ret = record.m_process_address + (local_address - record.m_host_address);
723 
724             if (log)
725             {
726                 log->Printf("IRExecutionUnit::GetRemoteAddressForLocal() found 0x%" PRIx64 " in [0x%" PRIx64 "..0x%" PRIx64 "], and returned 0x%" PRIx64 " from [0x%" PRIx64 "..0x%" PRIx64 "].",
727                             local_address,
728                             (uint64_t)record.m_host_address,
729                             (uint64_t)record.m_host_address + (uint64_t)record.m_size,
730                             ret,
731                             record.m_process_address,
732                             record.m_process_address + record.m_size);
733             }
734 
735             return ret;
736         }
737     }
738 
739     return LLDB_INVALID_ADDRESS;
740 }
741 
742 IRExecutionUnit::AddrRange
743 IRExecutionUnit::GetRemoteRangeForLocal (lldb::addr_t local_address)
744 {
745     for (AllocationRecord &record : m_records)
746     {
747         if (local_address >= record.m_host_address &&
748             local_address < record.m_host_address + record.m_size)
749         {
750             if (record.m_process_address == LLDB_INVALID_ADDRESS)
751                 return AddrRange(0, 0);
752 
753             return AddrRange(record.m_process_address, record.m_size);
754         }
755     }
756 
757     return AddrRange (0, 0);
758 }
759 
760 bool
761 IRExecutionUnit::CommitAllocations (lldb::ProcessSP &process_sp)
762 {
763     bool ret = true;
764 
765     lldb_private::Error err;
766 
767     for (AllocationRecord &record : m_records)
768     {
769         if (record.m_process_address != LLDB_INVALID_ADDRESS)
770             continue;
771 
772         switch (record.m_sect_type)
773         {
774         case lldb::eSectionTypeInvalid:
775         case lldb::eSectionTypeDWARFDebugAbbrev:
776         case lldb::eSectionTypeDWARFDebugAranges:
777         case lldb::eSectionTypeDWARFDebugFrame:
778         case lldb::eSectionTypeDWARFDebugInfo:
779         case lldb::eSectionTypeDWARFDebugLine:
780         case lldb::eSectionTypeDWARFDebugLoc:
781         case lldb::eSectionTypeDWARFDebugMacInfo:
782         case lldb::eSectionTypeDWARFDebugPubNames:
783         case lldb::eSectionTypeDWARFDebugPubTypes:
784         case lldb::eSectionTypeDWARFDebugRanges:
785         case lldb::eSectionTypeDWARFDebugStr:
786         case lldb::eSectionTypeDWARFAppleNames:
787         case lldb::eSectionTypeDWARFAppleTypes:
788         case lldb::eSectionTypeDWARFAppleNamespaces:
789         case lldb::eSectionTypeDWARFAppleObjC:
790             err.Clear();
791             break;
792         default:
793             record.m_process_address = Malloc (record.m_size,
794                                                record.m_alignment,
795                                                record.m_permissions,
796                                                eAllocationPolicyProcessOnly,
797                                                err);
798             break;
799         }
800 
801         if (!err.Success())
802         {
803             ret = false;
804             break;
805         }
806     }
807 
808     if (!ret)
809     {
810         for (AllocationRecord &record : m_records)
811         {
812             if (record.m_process_address != LLDB_INVALID_ADDRESS)
813             {
814                 Free(record.m_process_address, err);
815                 record.m_process_address = LLDB_INVALID_ADDRESS;
816             }
817         }
818     }
819 
820     return ret;
821 }
822 
823 void
824 IRExecutionUnit::ReportAllocations (llvm::ExecutionEngine &engine)
825 {
826     for (AllocationRecord &record : m_records)
827     {
828         if (record.m_process_address == LLDB_INVALID_ADDRESS)
829             continue;
830 
831         if (record.m_section_id == eSectionIDInvalid)
832             continue;
833 
834         engine.mapSectionAddress((void*)record.m_host_address, record.m_process_address);
835     }
836 
837     // Trigger re-application of relocations.
838     engine.finalizeObject();
839 }
840 
841 bool
842 IRExecutionUnit::WriteData (lldb::ProcessSP &process_sp)
843 {
844     bool wrote_something = false;
845     for (AllocationRecord &record : m_records)
846     {
847         if (record.m_process_address != LLDB_INVALID_ADDRESS)
848         {
849             lldb_private::Error err;
850             WriteMemory (record.m_process_address, (uint8_t*)record.m_host_address, record.m_size, err);
851             if (err.Success())
852                 wrote_something = true;
853         }
854     }
855     return wrote_something;
856 }
857 
858 void
859 IRExecutionUnit::AllocationRecord::dump (Log *log)
860 {
861     if (!log)
862         return;
863 
864     log->Printf("[0x%llx+0x%llx]->0x%llx (alignment %d, section ID %d)",
865                 (unsigned long long)m_host_address,
866                 (unsigned long long)m_size,
867                 (unsigned long long)m_process_address,
868                 (unsigned)m_alignment,
869                 (unsigned)m_section_id);
870 }
871 
872 
873 lldb::ByteOrder
874 IRExecutionUnit::GetByteOrder () const
875 {
876     ExecutionContext exe_ctx (GetBestExecutionContextScope());
877     return exe_ctx.GetByteOrder();
878 }
879 
880 uint32_t
881 IRExecutionUnit::GetAddressByteSize () const
882 {
883     ExecutionContext exe_ctx (GetBestExecutionContextScope());
884     return exe_ctx.GetAddressByteSize();
885 }
886 
887 void
888 IRExecutionUnit::PopulateSymtab (lldb_private::ObjectFile *obj_file,
889                                  lldb_private::Symtab &symtab)
890 {
891     // No symbols yet...
892 }
893 
894 
895 void
896 IRExecutionUnit::PopulateSectionList (lldb_private::ObjectFile *obj_file,
897                                       lldb_private::SectionList &section_list)
898 {
899     for (AllocationRecord &record : m_records)
900     {
901         if (record.m_size > 0)
902         {
903             lldb::SectionSP section_sp (new lldb_private::Section (obj_file->GetModule(),
904                                                                    obj_file,
905                                                                    record.m_section_id,
906                                                                    ConstString(record.m_name),
907                                                                    record.m_sect_type,
908                                                                    record.m_process_address,
909                                                                    record.m_size,
910                                                                    record.m_host_address,   // file_offset (which is the host address for the data)
911                                                                    record.m_size,           // file_size
912                                                                    0,
913                                                                    record.m_permissions));  // flags
914             section_list.AddSection (section_sp);
915         }
916     }
917 }
918 
919 bool
920 IRExecutionUnit::GetArchitecture (lldb_private::ArchSpec &arch)
921 {
922     ExecutionContext exe_ctx (GetBestExecutionContextScope());
923     Target *target = exe_ctx.GetTargetPtr();
924     if (target)
925         arch = target->GetArchitecture();
926     else
927         arch.Clear();
928     return arch.IsValid();
929 }
930 
931 lldb::ModuleSP
932 IRExecutionUnit::GetJITModule ()
933 {
934     ExecutionContext exe_ctx (GetBestExecutionContextScope());
935     Target *target = exe_ctx.GetTargetPtr();
936     if (target)
937     {
938         lldb::ModuleSP jit_module_sp = lldb_private::Module::CreateJITModule (std::static_pointer_cast<lldb_private::ObjectFileJITDelegate>(shared_from_this()));
939         if (jit_module_sp)
940         {
941             bool changed = false;
942             jit_module_sp->SetLoadAddress(*target, 0, true, changed);
943         }
944         return jit_module_sp;
945     }
946     return lldb::ModuleSP();
947 }
948