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(m_module_ap.get());
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     else
330     {
331         m_module_ap.release(); // ownership was transferred
332     }
333 
334     // Make sure we see all sections, including ones that don't have relocations...
335     m_execution_engine_ap->setProcessAllSections(true);
336 
337     m_execution_engine_ap->DisableLazyCompilation();
338 
339     // We don't actually need the function pointer here, this just forces it to get resolved.
340 
341     void *fun_ptr = m_execution_engine_ap->getPointerToFunction(function);
342 
343     if (!error.Success())
344     {
345         // We got an error through our callback!
346         return;
347     }
348 
349     if (!function)
350     {
351         error.SetErrorToGenericError();
352         error.SetErrorStringWithFormat("Couldn't find '%s' in the JITted module", m_name.AsCString());
353         return;
354     }
355 
356     if (!fun_ptr)
357     {
358         error.SetErrorToGenericError();
359         error.SetErrorStringWithFormat("'%s' was in the JITted module but wasn't lowered", m_name.AsCString());
360         return;
361     }
362 
363     m_jitted_functions.push_back (JittedFunction(m_name.AsCString(), (lldb::addr_t)fun_ptr));
364 
365     CommitAllocations(process_sp);
366     ReportAllocations(*m_execution_engine_ap);
367     WriteData(process_sp);
368 
369     for (JittedFunction &jitted_function : m_jitted_functions)
370     {
371         jitted_function.m_remote_addr = GetRemoteAddressForLocal (jitted_function.m_local_addr);
372 
373         if (!jitted_function.m_name.compare(m_name.AsCString()))
374         {
375             AddrRange func_range = GetRemoteRangeForLocal(jitted_function.m_local_addr);
376             m_function_end_load_addr = func_range.first + func_range.second;
377             m_function_load_addr = jitted_function.m_remote_addr;
378         }
379     }
380 
381     if (log)
382     {
383         log->Printf("Code can be run in the target.");
384 
385         StreamString disassembly_stream;
386 
387         Error err = DisassembleFunction(disassembly_stream, process_sp);
388 
389         if (!err.Success())
390         {
391             log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
392         }
393         else
394         {
395             log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
396         }
397 
398         log->Printf("Sections: ");
399         for (AllocationRecord &record : m_records)
400         {
401             if (record.m_process_address != LLDB_INVALID_ADDRESS)
402             {
403                 record.dump(log);
404 
405                 DataBufferHeap my_buffer(record.m_size, 0);
406                 Error err;
407                 ReadMemory(my_buffer.GetBytes(), record.m_process_address, record.m_size, err);
408 
409                 if (err.Success())
410                 {
411                     DataExtractor my_extractor(my_buffer.GetBytes(), my_buffer.GetByteSize(), lldb::eByteOrderBig, 8);
412                     my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(), record.m_process_address, 16, DataExtractor::TypeUInt8);
413                 }
414             }
415         }
416     }
417 
418     func_addr = m_function_load_addr;
419     func_end = m_function_end_load_addr;
420 
421     return;
422 }
423 
424 IRExecutionUnit::~IRExecutionUnit ()
425 {
426     m_module_ap.reset();
427     m_execution_engine_ap.reset();
428     m_context_ap.reset();
429 }
430 
431 IRExecutionUnit::MemoryManager::MemoryManager (IRExecutionUnit &parent) :
432     m_default_mm_ap (llvm::JITMemoryManager::CreateDefaultMemManager()),
433     m_parent (parent)
434 {
435 }
436 
437 IRExecutionUnit::MemoryManager::~MemoryManager ()
438 {
439 }
440 void
441 IRExecutionUnit::MemoryManager::setMemoryWritable ()
442 {
443     m_default_mm_ap->setMemoryWritable();
444 }
445 
446 void
447 IRExecutionUnit::MemoryManager::setMemoryExecutable ()
448 {
449     m_default_mm_ap->setMemoryExecutable();
450 }
451 
452 
453 uint8_t *
454 IRExecutionUnit::MemoryManager::startFunctionBody(const llvm::Function *F,
455                                                   uintptr_t &ActualSize)
456 {
457     return m_default_mm_ap->startFunctionBody(F, ActualSize);
458 }
459 
460 uint8_t *
461 IRExecutionUnit::MemoryManager::allocateStub(const llvm::GlobalValue* F,
462                                              unsigned StubSize,
463                                              unsigned Alignment)
464 {
465     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
466 
467     uint8_t *return_value = m_default_mm_ap->allocateStub(F, StubSize, Alignment);
468 
469     m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
470                                                   lldb::ePermissionsReadable | lldb::ePermissionsWritable,
471                                                   GetSectionTypeFromSectionName (llvm::StringRef(), AllocationKind::Stub),
472                                                   StubSize,
473                                                   Alignment,
474                                                   eSectionIDInvalid,
475                                                   NULL));
476 
477     if (log)
478     {
479         log->Printf("IRExecutionUnit::allocateStub (F=%p, StubSize=%u, Alignment=%u) = %p",
480                     static_cast<const void*>(F), StubSize, Alignment,
481                     static_cast<void*>(return_value));
482     }
483 
484     return return_value;
485 }
486 
487 void
488 IRExecutionUnit::MemoryManager::endFunctionBody(const llvm::Function *F,
489                                                 uint8_t *FunctionStart,
490                                                 uint8_t *FunctionEnd)
491 {
492     m_default_mm_ap->endFunctionBody(F, FunctionStart, FunctionEnd);
493 }
494 
495 lldb::SectionType
496 IRExecutionUnit::GetSectionTypeFromSectionName (const llvm::StringRef &name, IRExecutionUnit::AllocationKind alloc_kind)
497 {
498     lldb::SectionType sect_type = lldb::eSectionTypeCode;
499     switch (alloc_kind)
500     {
501         case AllocationKind::Stub:  sect_type = lldb::eSectionTypeCode; break;
502         case AllocationKind::Code:  sect_type = lldb::eSectionTypeCode; break;
503         case AllocationKind::Data:  sect_type = lldb::eSectionTypeData; break;
504         case AllocationKind::Global:sect_type = lldb::eSectionTypeData; break;
505         case AllocationKind::Bytes: sect_type = lldb::eSectionTypeOther; break;
506     }
507 
508     if (!name.empty())
509     {
510         if (name.equals("__text") || name.equals(".text"))
511             sect_type = lldb::eSectionTypeCode;
512         else if (name.equals("__data") || name.equals(".data"))
513             sect_type = lldb::eSectionTypeCode;
514         else if (name.startswith("__debug_") || name.startswith(".debug_"))
515         {
516             const uint32_t name_idx = name[0] == '_' ? 8 : 7;
517             llvm::StringRef dwarf_name(name.substr(name_idx));
518             switch (dwarf_name[0])
519             {
520                 case 'a':
521                     if (dwarf_name.equals("abbrev"))
522                         sect_type = lldb::eSectionTypeDWARFDebugAbbrev;
523                     else if (dwarf_name.equals("aranges"))
524                         sect_type = lldb::eSectionTypeDWARFDebugAranges;
525                     break;
526 
527                 case 'f':
528                     if (dwarf_name.equals("frame"))
529                         sect_type = lldb::eSectionTypeDWARFDebugFrame;
530                     break;
531 
532                 case 'i':
533                     if (dwarf_name.equals("info"))
534                         sect_type = lldb::eSectionTypeDWARFDebugInfo;
535                     break;
536 
537                 case 'l':
538                     if (dwarf_name.equals("line"))
539                         sect_type = lldb::eSectionTypeDWARFDebugLine;
540                     else if (dwarf_name.equals("loc"))
541                         sect_type = lldb::eSectionTypeDWARFDebugLoc;
542                     break;
543 
544                 case 'm':
545                     if (dwarf_name.equals("macinfo"))
546                         sect_type = lldb::eSectionTypeDWARFDebugMacInfo;
547                     break;
548 
549                 case 'p':
550                     if (dwarf_name.equals("pubnames"))
551                         sect_type = lldb::eSectionTypeDWARFDebugPubNames;
552                     else if (dwarf_name.equals("pubtypes"))
553                         sect_type = lldb::eSectionTypeDWARFDebugPubTypes;
554                     break;
555 
556                 case 's':
557                     if (dwarf_name.equals("str"))
558                         sect_type = lldb::eSectionTypeDWARFDebugStr;
559                     break;
560 
561                 case 'r':
562                     if (dwarf_name.equals("ranges"))
563                         sect_type = lldb::eSectionTypeDWARFDebugRanges;
564                     break;
565 
566                 default:
567                     break;
568             }
569         }
570         else if (name.startswith("__apple_") || name.startswith(".apple_"))
571         {
572 #if 0
573             const uint32_t name_idx = name[0] == '_' ? 8 : 7;
574             llvm::StringRef apple_name(name.substr(name_idx));
575             switch (apple_name[0])
576             {
577                 case 'n':
578                     if (apple_name.equals("names"))
579                         sect_type = lldb::eSectionTypeDWARFAppleNames;
580                     else if (apple_name.equals("namespac") || apple_name.equals("namespaces"))
581                         sect_type = lldb::eSectionTypeDWARFAppleNamespaces;
582                     break;
583                 case 't':
584                     if (apple_name.equals("types"))
585                         sect_type = lldb::eSectionTypeDWARFAppleTypes;
586                     break;
587                 case 'o':
588                     if (apple_name.equals("objc"))
589                         sect_type = lldb::eSectionTypeDWARFAppleObjC;
590                     break;
591                 default:
592                     break;
593             }
594 #else
595             sect_type = lldb::eSectionTypeInvalid;
596 #endif
597         }
598         else if (name.equals("__objc_imageinfo"))
599             sect_type = lldb::eSectionTypeOther;
600     }
601     return sect_type;
602 }
603 
604 uint8_t *
605 IRExecutionUnit::MemoryManager::allocateSpace(intptr_t Size, unsigned Alignment)
606 {
607     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
608 
609     uint8_t *return_value = m_default_mm_ap->allocateSpace(Size, Alignment);
610 
611     m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
612                                                   lldb::ePermissionsReadable | lldb::ePermissionsWritable,
613                                                   GetSectionTypeFromSectionName (llvm::StringRef(), AllocationKind::Bytes),
614                                                   Size,
615                                                   Alignment,
616                                                   eSectionIDInvalid,
617                                                   NULL));
618 
619     if (log)
620     {
621         log->Printf("IRExecutionUnit::allocateSpace(Size=%" PRIu64 ", Alignment=%u) = %p",
622                                (uint64_t)Size, Alignment, return_value);
623     }
624 
625     return return_value;
626 }
627 
628 uint8_t *
629 IRExecutionUnit::MemoryManager::allocateCodeSection(uintptr_t Size,
630                                                     unsigned Alignment,
631                                                     unsigned SectionID,
632                                                     llvm::StringRef SectionName)
633 {
634     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
635 
636     uint8_t *return_value = m_default_mm_ap->allocateCodeSection(Size, Alignment, SectionID, SectionName);
637 
638     m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
639                                                   lldb::ePermissionsReadable | lldb::ePermissionsExecutable,
640                                                   GetSectionTypeFromSectionName (SectionName, AllocationKind::Code),
641                                                   Size,
642                                                   Alignment,
643                                                   SectionID,
644                                                   SectionName.str().c_str()));
645 
646     if (log)
647     {
648         log->Printf("IRExecutionUnit::allocateCodeSection(Size=0x%" PRIx64 ", Alignment=%u, SectionID=%u) = %p",
649                     (uint64_t)Size, Alignment, SectionID, return_value);
650     }
651 
652     return return_value;
653 }
654 
655 uint8_t *
656 IRExecutionUnit::MemoryManager::allocateDataSection(uintptr_t Size,
657                                                     unsigned Alignment,
658                                                     unsigned SectionID,
659                                                     llvm::StringRef SectionName,
660                                                     bool IsReadOnly)
661 {
662     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
663 
664     uint8_t *return_value = m_default_mm_ap->allocateDataSection(Size, Alignment, SectionID, SectionName, IsReadOnly);
665 
666     m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
667                                                   lldb::ePermissionsReadable | (IsReadOnly ? 0 : lldb::ePermissionsWritable),
668                                                   GetSectionTypeFromSectionName (SectionName, AllocationKind::Data),
669                                                   Size,
670                                                   Alignment,
671                                                   SectionID,
672                                                   SectionName.str().c_str()));
673     if (log)
674     {
675         log->Printf("IRExecutionUnit::allocateDataSection(Size=0x%" PRIx64 ", Alignment=%u, SectionID=%u) = %p",
676                     (uint64_t)Size, Alignment, SectionID, return_value);
677     }
678 
679     return return_value;
680 }
681 
682 uint8_t *
683 IRExecutionUnit::MemoryManager::allocateGlobal(uintptr_t Size,
684                                                unsigned Alignment)
685 {
686     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
687 
688     uint8_t *return_value = m_default_mm_ap->allocateGlobal(Size, Alignment);
689 
690     m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
691                                                   lldb::ePermissionsReadable | lldb::ePermissionsWritable,
692                                                   GetSectionTypeFromSectionName (llvm::StringRef(), AllocationKind::Global),
693                                                   Size,
694                                                   Alignment,
695                                                   eSectionIDInvalid,
696                                                   NULL));
697 
698     if (log)
699     {
700         log->Printf("IRExecutionUnit::allocateGlobal(Size=0x%" PRIx64 ", Alignment=%u) = %p",
701                     (uint64_t)Size, Alignment, return_value);
702     }
703 
704     return return_value;
705 }
706 
707 void
708 IRExecutionUnit::MemoryManager::deallocateFunctionBody(void *Body)
709 {
710     m_default_mm_ap->deallocateFunctionBody(Body);
711 }
712 
713 lldb::addr_t
714 IRExecutionUnit::GetRemoteAddressForLocal (lldb::addr_t local_address)
715 {
716     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
717 
718     for (AllocationRecord &record : m_records)
719     {
720         if (local_address >= record.m_host_address &&
721             local_address < record.m_host_address + record.m_size)
722         {
723             if (record.m_process_address == LLDB_INVALID_ADDRESS)
724                 return LLDB_INVALID_ADDRESS;
725 
726             lldb::addr_t ret = record.m_process_address + (local_address - record.m_host_address);
727 
728             if (log)
729             {
730                 log->Printf("IRExecutionUnit::GetRemoteAddressForLocal() found 0x%" PRIx64 " in [0x%" PRIx64 "..0x%" PRIx64 "], and returned 0x%" PRIx64 " from [0x%" PRIx64 "..0x%" PRIx64 "].",
731                             local_address,
732                             (uint64_t)record.m_host_address,
733                             (uint64_t)record.m_host_address + (uint64_t)record.m_size,
734                             ret,
735                             record.m_process_address,
736                             record.m_process_address + record.m_size);
737             }
738 
739             return ret;
740         }
741     }
742 
743     return LLDB_INVALID_ADDRESS;
744 }
745 
746 IRExecutionUnit::AddrRange
747 IRExecutionUnit::GetRemoteRangeForLocal (lldb::addr_t local_address)
748 {
749     for (AllocationRecord &record : m_records)
750     {
751         if (local_address >= record.m_host_address &&
752             local_address < record.m_host_address + record.m_size)
753         {
754             if (record.m_process_address == LLDB_INVALID_ADDRESS)
755                 return AddrRange(0, 0);
756 
757             return AddrRange(record.m_process_address, record.m_size);
758         }
759     }
760 
761     return AddrRange (0, 0);
762 }
763 
764 bool
765 IRExecutionUnit::CommitAllocations (lldb::ProcessSP &process_sp)
766 {
767     bool ret = true;
768 
769     lldb_private::Error err;
770 
771     for (AllocationRecord &record : m_records)
772     {
773         if (record.m_process_address != LLDB_INVALID_ADDRESS)
774             continue;
775 
776         switch (record.m_sect_type)
777         {
778         case lldb::eSectionTypeInvalid:
779         case lldb::eSectionTypeDWARFDebugAbbrev:
780         case lldb::eSectionTypeDWARFDebugAranges:
781         case lldb::eSectionTypeDWARFDebugFrame:
782         case lldb::eSectionTypeDWARFDebugInfo:
783         case lldb::eSectionTypeDWARFDebugLine:
784         case lldb::eSectionTypeDWARFDebugLoc:
785         case lldb::eSectionTypeDWARFDebugMacInfo:
786         case lldb::eSectionTypeDWARFDebugPubNames:
787         case lldb::eSectionTypeDWARFDebugPubTypes:
788         case lldb::eSectionTypeDWARFDebugRanges:
789         case lldb::eSectionTypeDWARFDebugStr:
790         case lldb::eSectionTypeDWARFAppleNames:
791         case lldb::eSectionTypeDWARFAppleTypes:
792         case lldb::eSectionTypeDWARFAppleNamespaces:
793         case lldb::eSectionTypeDWARFAppleObjC:
794             err.Clear();
795             break;
796         default:
797             record.m_process_address = Malloc (record.m_size,
798                                                record.m_alignment,
799                                                record.m_permissions,
800                                                eAllocationPolicyProcessOnly,
801                                                err);
802             break;
803         }
804 
805         if (!err.Success())
806         {
807             ret = false;
808             break;
809         }
810     }
811 
812     if (!ret)
813     {
814         for (AllocationRecord &record : m_records)
815         {
816             if (record.m_process_address != LLDB_INVALID_ADDRESS)
817             {
818                 Free(record.m_process_address, err);
819                 record.m_process_address = LLDB_INVALID_ADDRESS;
820             }
821         }
822     }
823 
824     return ret;
825 }
826 
827 void
828 IRExecutionUnit::ReportAllocations (llvm::ExecutionEngine &engine)
829 {
830     for (AllocationRecord &record : m_records)
831     {
832         if (record.m_process_address == LLDB_INVALID_ADDRESS)
833             continue;
834 
835         if (record.m_section_id == eSectionIDInvalid)
836             continue;
837 
838         engine.mapSectionAddress((void*)record.m_host_address, record.m_process_address);
839     }
840 
841     // Trigger re-application of relocations.
842     engine.finalizeObject();
843 }
844 
845 bool
846 IRExecutionUnit::WriteData (lldb::ProcessSP &process_sp)
847 {
848     bool wrote_something = false;
849     for (AllocationRecord &record : m_records)
850     {
851         if (record.m_process_address != LLDB_INVALID_ADDRESS)
852         {
853             lldb_private::Error err;
854             WriteMemory (record.m_process_address, (uint8_t*)record.m_host_address, record.m_size, err);
855             if (err.Success())
856                 wrote_something = true;
857         }
858     }
859     return wrote_something;
860 }
861 
862 void
863 IRExecutionUnit::AllocationRecord::dump (Log *log)
864 {
865     if (!log)
866         return;
867 
868     log->Printf("[0x%llx+0x%llx]->0x%llx (alignment %d, section ID %d)",
869                 (unsigned long long)m_host_address,
870                 (unsigned long long)m_size,
871                 (unsigned long long)m_process_address,
872                 (unsigned)m_alignment,
873                 (unsigned)m_section_id);
874 }
875 
876 
877 lldb::ByteOrder
878 IRExecutionUnit::GetByteOrder () const
879 {
880     ExecutionContext exe_ctx (GetBestExecutionContextScope());
881     return exe_ctx.GetByteOrder();
882 }
883 
884 uint32_t
885 IRExecutionUnit::GetAddressByteSize () const
886 {
887     ExecutionContext exe_ctx (GetBestExecutionContextScope());
888     return exe_ctx.GetAddressByteSize();
889 }
890 
891 void
892 IRExecutionUnit::PopulateSymtab (lldb_private::ObjectFile *obj_file,
893                                  lldb_private::Symtab &symtab)
894 {
895     // No symbols yet...
896 }
897 
898 
899 void
900 IRExecutionUnit::PopulateSectionList (lldb_private::ObjectFile *obj_file,
901                                       lldb_private::SectionList &section_list)
902 {
903     for (AllocationRecord &record : m_records)
904     {
905         if (record.m_size > 0)
906         {
907             lldb::SectionSP section_sp (new lldb_private::Section (obj_file->GetModule(),
908                                                                    obj_file,
909                                                                    record.m_section_id,
910                                                                    ConstString(record.m_name),
911                                                                    record.m_sect_type,
912                                                                    record.m_process_address,
913                                                                    record.m_size,
914                                                                    record.m_host_address,   // file_offset (which is the host address for the data)
915                                                                    record.m_size,           // file_size
916                                                                    0,
917                                                                    record.m_permissions));  // flags
918             section_list.AddSection (section_sp);
919         }
920     }
921 }
922 
923 bool
924 IRExecutionUnit::GetArchitecture (lldb_private::ArchSpec &arch)
925 {
926     ExecutionContext exe_ctx (GetBestExecutionContextScope());
927     Target *target = exe_ctx.GetTargetPtr();
928     if (target)
929         arch = target->GetArchitecture();
930     else
931         arch.Clear();
932     return arch.IsValid();
933 }
934 
935 lldb::ModuleSP
936 IRExecutionUnit::GetJITModule ()
937 {
938     ExecutionContext exe_ctx (GetBestExecutionContextScope());
939     Target *target = exe_ctx.GetTargetPtr();
940     if (target)
941     {
942         lldb::ModuleSP jit_module_sp = lldb_private::Module::CreateJITModule (std::static_pointer_cast<lldb_private::ObjectFileJITDelegate>(shared_from_this()));
943         if (jit_module_sp)
944         {
945             bool changed = false;
946             jit_module_sp->SetLoadAddress(*target, 0, true, changed);
947         }
948         return jit_module_sp;
949     }
950     return lldb::ModuleSP();
951 }
952