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