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