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/Constants.h"
12 #include "llvm/IR/LLVMContext.h"
13 #include "llvm/IR/Module.h"
14 #include "llvm/Support/SourceMgr.h"
15 #include "llvm/Support/raw_ostream.h"
16 
17 #include "lldb/Core/DataBufferHeap.h"
18 #include "lldb/Core/DataExtractor.h"
19 #include "lldb/Core/Debugger.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/Symbol/CompileUnit.h"
25 #include "lldb/Symbol/SymbolContext.h"
26 #include "lldb/Symbol/SymbolVendor.h"
27 #include "lldb/Symbol/SymbolFile.h"
28 #include "lldb/Expression/IRExecutionUnit.h"
29 #include "lldb/Target/ExecutionContext.h"
30 #include "lldb/Target/Target.h"
31 #include "lldb/Target/ObjCLanguageRuntime.h"
32 #include "lldb/Utility/LLDBAssert.h"
33 
34 #include "lldb/../../source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
35 
36 using namespace lldb_private;
37 
38 IRExecutionUnit::IRExecutionUnit (std::unique_ptr<llvm::LLVMContext> &context_ap,
39                                   std::unique_ptr<llvm::Module> &module_ap,
40                                   ConstString &name,
41                                   const lldb::TargetSP &target_sp,
42                                   const SymbolContext &sym_ctx,
43                                   std::vector<std::string> &cpu_features) :
44     IRMemoryMap(target_sp),
45     m_context_ap(context_ap.release()),
46     m_module_ap(module_ap.release()),
47     m_module(m_module_ap.get()),
48     m_cpu_features(cpu_features),
49     m_name(name),
50     m_sym_ctx(sym_ctx),
51     m_did_jit(false),
52     m_function_load_addr(LLDB_INVALID_ADDRESS),
53     m_function_end_load_addr(LLDB_INVALID_ADDRESS),
54     m_reported_allocations(false)
55 {
56 }
57 
58 lldb::addr_t
59 IRExecutionUnit::WriteNow (const uint8_t *bytes,
60                            size_t size,
61                            Error &error)
62 {
63     const bool zero_memory = false;
64     lldb::addr_t allocation_process_addr = Malloc (size,
65                                                    8,
66                                                    lldb::ePermissionsWritable | lldb::ePermissionsReadable,
67                                                    eAllocationPolicyMirror,
68                                                    zero_memory,
69                                                    error);
70 
71     if (!error.Success())
72         return LLDB_INVALID_ADDRESS;
73 
74     WriteMemory(allocation_process_addr, bytes, size, error);
75 
76     if (!error.Success())
77     {
78         Error err;
79         Free (allocation_process_addr, err);
80 
81         return LLDB_INVALID_ADDRESS;
82     }
83 
84     if (Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS))
85     {
86         DataBufferHeap my_buffer(size, 0);
87         Error err;
88         ReadMemory(my_buffer.GetBytes(), allocation_process_addr, size, err);
89 
90         if (err.Success())
91         {
92             DataExtractor my_extractor(my_buffer.GetBytes(), my_buffer.GetByteSize(), lldb::eByteOrderBig, 8);
93             my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(), allocation_process_addr, 16, DataExtractor::TypeUInt8);
94         }
95     }
96 
97     return allocation_process_addr;
98 }
99 
100 void
101 IRExecutionUnit::FreeNow (lldb::addr_t allocation)
102 {
103     if (allocation == LLDB_INVALID_ADDRESS)
104         return;
105 
106     Error err;
107 
108     Free(allocation, err);
109 }
110 
111 Error
112 IRExecutionUnit::DisassembleFunction (Stream &stream,
113                                       lldb::ProcessSP &process_wp)
114 {
115     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
116 
117     ExecutionContext exe_ctx(process_wp);
118 
119     Error ret;
120 
121     ret.Clear();
122 
123     lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
124     lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
125 
126     for (JittedFunction &function : m_jitted_functions)
127     {
128         if (function.m_name == m_name)
129         {
130             func_local_addr = function.m_local_addr;
131             func_remote_addr = function.m_remote_addr;
132         }
133     }
134 
135     if (func_local_addr == LLDB_INVALID_ADDRESS)
136     {
137         ret.SetErrorToGenericError();
138         ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", m_name.AsCString());
139         return ret;
140     }
141 
142     if (log)
143         log->Printf("Found function, has local address 0x%" PRIx64 " and remote address 0x%" PRIx64, (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
144 
145     std::pair <lldb::addr_t, lldb::addr_t> func_range;
146 
147     func_range = GetRemoteRangeForLocal(func_local_addr);
148 
149     if (func_range.first == 0 && func_range.second == 0)
150     {
151         ret.SetErrorToGenericError();
152         ret.SetErrorStringWithFormat("Couldn't find code range for function %s", m_name.AsCString());
153         return ret;
154     }
155 
156     if (log)
157         log->Printf("Function's code range is [0x%" PRIx64 "+0x%" PRIx64 "]", func_range.first, func_range.second);
158 
159     Target *target = exe_ctx.GetTargetPtr();
160     if (!target)
161     {
162         ret.SetErrorToGenericError();
163         ret.SetErrorString("Couldn't find the target");
164         return ret;
165     }
166 
167     lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second, 0));
168 
169     Process *process = exe_ctx.GetProcessPtr();
170     Error err;
171     process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
172 
173     if (!err.Success())
174     {
175         ret.SetErrorToGenericError();
176         ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
177         return ret;
178     }
179 
180     ArchSpec arch(target->GetArchitecture());
181 
182     const char *plugin_name = NULL;
183     const char *flavor_string = NULL;
184     lldb::DisassemblerSP disassembler_sp = Disassembler::FindPlugin(arch, flavor_string, plugin_name);
185 
186     if (!disassembler_sp)
187     {
188         ret.SetErrorToGenericError();
189         ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
190         return ret;
191     }
192 
193     if (!process)
194     {
195         ret.SetErrorToGenericError();
196         ret.SetErrorString("Couldn't find the process");
197         return ret;
198     }
199 
200     DataExtractor extractor(buffer_sp,
201                             process->GetByteOrder(),
202                             target->GetArchitecture().GetAddressByteSize());
203 
204     if (log)
205     {
206         log->Printf("Function data has contents:");
207         extractor.PutToLog (log,
208                             0,
209                             extractor.GetByteSize(),
210                             func_remote_addr,
211                             16,
212                             DataExtractor::TypeUInt8);
213     }
214 
215     disassembler_sp->DecodeInstructions (Address (func_remote_addr), extractor, 0, UINT32_MAX, false, false);
216 
217     InstructionList &instruction_list = disassembler_sp->GetInstructionList();
218     instruction_list.Dump(&stream, true, true, &exe_ctx);
219 
220     // FIXME: The DisassemblerLLVMC has a reference cycle and won't go away if it has any active instructions.
221     // I'll fix that but for now, just clear the list and it will go away nicely.
222     disassembler_sp->GetInstructionList().Clear();
223     return ret;
224 }
225 
226 static void ReportInlineAsmError(const llvm::SMDiagnostic &diagnostic, void *Context, unsigned LocCookie)
227 {
228     Error *err = static_cast<Error*>(Context);
229 
230     if (err && err->Success())
231     {
232         err->SetErrorToGenericError();
233         err->SetErrorStringWithFormat("Inline assembly error: %s", diagnostic.getMessage().str().c_str());
234     }
235 }
236 
237 void
238 IRExecutionUnit::ReportSymbolLookupError(const ConstString &name)
239 {
240     m_failed_lookups.push_back(name);
241 }
242 
243 void
244 IRExecutionUnit::GetRunnableInfo(Error &error,
245                                  lldb::addr_t &func_addr,
246                                  lldb::addr_t &func_end)
247 {
248     lldb::ProcessSP process_sp(GetProcessWP().lock());
249 
250     static std::recursive_mutex s_runnable_info_mutex;
251 
252     func_addr = LLDB_INVALID_ADDRESS;
253     func_end = LLDB_INVALID_ADDRESS;
254 
255     if (!process_sp)
256     {
257         error.SetErrorToGenericError();
258         error.SetErrorString("Couldn't write the JIT compiled code into the process because the process is invalid");
259         return;
260     }
261 
262     if (m_did_jit)
263     {
264         func_addr = m_function_load_addr;
265         func_end = m_function_end_load_addr;
266 
267         return;
268     };
269 
270     std::lock_guard<std::recursive_mutex> guard(s_runnable_info_mutex);
271 
272     m_did_jit = true;
273 
274     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
275 
276     std::string error_string;
277 
278     if (log)
279     {
280         std::string s;
281         llvm::raw_string_ostream oss(s);
282 
283         m_module->print(oss, NULL);
284 
285         oss.flush();
286 
287         log->Printf ("Module being sent to JIT: \n%s", s.c_str());
288     }
289 
290     llvm::Triple triple(m_module->getTargetTriple());
291     llvm::Reloc::Model relocModel;
292     llvm::CodeModel::Model codeModel;
293 
294     if (triple.isOSBinFormatELF())
295     {
296         relocModel = llvm::Reloc::Static;
297     }
298     else
299     {
300         relocModel = llvm::Reloc::PIC_;
301     }
302 
303     // This will be small for 32-bit and large for 64-bit.
304     codeModel = llvm::CodeModel::JITDefault;
305 
306     m_module_ap->getContext().setInlineAsmDiagnosticHandler(ReportInlineAsmError, &error);
307 
308     llvm::EngineBuilder builder(std::move(m_module_ap));
309 
310     builder.setEngineKind(llvm::EngineKind::JIT)
311     .setErrorStr(&error_string)
312     .setRelocationModel(relocModel)
313     .setMCJITMemoryManager(std::unique_ptr<MemoryManager>(new MemoryManager(*this)))
314     .setCodeModel(codeModel)
315     .setOptLevel(llvm::CodeGenOpt::Less);
316 
317     llvm::StringRef mArch;
318     llvm::StringRef mCPU;
319     llvm::SmallVector<std::string, 0> mAttrs;
320 
321     for (std::string &feature : m_cpu_features)
322         mAttrs.push_back(feature);
323 
324     llvm::TargetMachine *target_machine = builder.selectTarget(triple,
325                                                                mArch,
326                                                                mCPU,
327                                                                mAttrs);
328 
329     m_execution_engine_ap.reset(builder.create(target_machine));
330 
331     m_strip_underscore = (m_execution_engine_ap->getDataLayout().getGlobalPrefix() == '_');
332 
333     if (!m_execution_engine_ap.get())
334     {
335         error.SetErrorToGenericError();
336         error.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
337         return;
338     }
339 
340     // Make sure we see all sections, including ones that don't have relocations...
341     m_execution_engine_ap->setProcessAllSections(true);
342 
343     m_execution_engine_ap->DisableLazyCompilation();
344 
345     for (llvm::Function &function : *m_module)
346     {
347         if (function.isDeclaration() || function.hasPrivateLinkage())
348             continue;
349 
350         const bool external = function.hasExternalLinkage() || function.hasLinkOnceODRLinkage();
351 
352         void *fun_ptr = m_execution_engine_ap->getPointerToFunction(&function);
353 
354         if (!error.Success())
355         {
356             // We got an error through our callback!
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", function.getName().str().c_str());
364             return;
365         }
366         m_jitted_functions.push_back (JittedFunction(function.getName().str().c_str(), external, (lldb::addr_t)fun_ptr));
367     }
368 
369     CommitAllocations(process_sp);
370     ReportAllocations(*m_execution_engine_ap);
371 
372     // We have to do this after calling ReportAllocations because for the MCJIT, getGlobalValueAddress
373     // will cause the JIT to perform all relocations.  That can only be done once, and has to happen
374     // after we do the remapping from local -> remote.
375     // That means we don't know the local address of the Variables, but we don't need that for anything,
376     // so that's okay.
377 
378     std::function<void (llvm::GlobalValue &)> RegisterOneValue = [this] (llvm::GlobalValue &val) {
379         if (val.hasExternalLinkage() && !val.isDeclaration())
380         {
381             uint64_t var_ptr_addr = m_execution_engine_ap->getGlobalValueAddress(val.getName().str());
382 
383             lldb::addr_t remote_addr = GetRemoteAddressForLocal(var_ptr_addr);
384 
385             // This is a really unfortunae API that sometimes returns local addresses and sometimes returns remote addresses, based on whether
386             // the variable was relocated during ReportAllocations or not.
387 
388             if (remote_addr == LLDB_INVALID_ADDRESS)
389             {
390                 remote_addr = var_ptr_addr;
391             }
392 
393             if (var_ptr_addr != 0)
394                 m_jitted_global_variables.push_back (JittedGlobalVariable (val.getName().str().c_str(), LLDB_INVALID_ADDRESS, remote_addr));
395         }
396     };
397 
398     for (llvm::GlobalVariable &global_var : m_module->getGlobalList())
399     {
400         RegisterOneValue(global_var);
401     }
402 
403     for (llvm::GlobalAlias &global_alias : m_module->getAliasList())
404     {
405         RegisterOneValue(global_alias);
406     }
407 
408     WriteData(process_sp);
409 
410     if (m_failed_lookups.size())
411     {
412         StreamString ss;
413 
414         ss.PutCString("Couldn't lookup symbols:\n");
415 
416         bool emitNewLine = false;
417 
418         for (const ConstString &failed_lookup : m_failed_lookups)
419         {
420             if (emitNewLine)
421                 ss.PutCString("\n");
422             emitNewLine = true;
423             ss.PutCString("  ");
424             ss.PutCString(Mangled(failed_lookup).GetDemangledName(lldb::eLanguageTypeObjC_plus_plus).AsCString());
425         }
426 
427         m_failed_lookups.clear();
428 
429         error.SetErrorString(ss.GetData());
430 
431         return;
432     }
433 
434     m_function_load_addr = LLDB_INVALID_ADDRESS;
435     m_function_end_load_addr = LLDB_INVALID_ADDRESS;
436 
437     for (JittedFunction &jitted_function : m_jitted_functions)
438     {
439         jitted_function.m_remote_addr = GetRemoteAddressForLocal (jitted_function.m_local_addr);
440 
441         if (!m_name.IsEmpty() && jitted_function.m_name == m_name)
442         {
443             AddrRange func_range = GetRemoteRangeForLocal(jitted_function.m_local_addr);
444             m_function_end_load_addr = func_range.first + func_range.second;
445             m_function_load_addr = jitted_function.m_remote_addr;
446         }
447     }
448 
449     if (log)
450     {
451         log->Printf("Code can be run in the target.");
452 
453         StreamString disassembly_stream;
454 
455         Error err = DisassembleFunction(disassembly_stream, process_sp);
456 
457         if (!err.Success())
458         {
459             log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
460         }
461         else
462         {
463             log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
464         }
465 
466         log->Printf("Sections: ");
467         for (AllocationRecord &record : m_records)
468         {
469             if (record.m_process_address != LLDB_INVALID_ADDRESS)
470             {
471                 record.dump(log);
472 
473                 DataBufferHeap my_buffer(record.m_size, 0);
474                 Error err;
475                 ReadMemory(my_buffer.GetBytes(), record.m_process_address, record.m_size, err);
476 
477                 if (err.Success())
478                 {
479                     DataExtractor my_extractor(my_buffer.GetBytes(), my_buffer.GetByteSize(), lldb::eByteOrderBig, 8);
480                     my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(), record.m_process_address, 16, DataExtractor::TypeUInt8);
481                 }
482             }
483             else
484             {
485                 record.dump(log);
486 
487                 DataExtractor my_extractor ((const void*)record.m_host_address, record.m_size, lldb::eByteOrderBig, 8);
488                 my_extractor.PutToLog(log, 0, record.m_size, record.m_host_address, 16, DataExtractor::TypeUInt8);
489             }
490         }
491     }
492 
493     func_addr = m_function_load_addr;
494     func_end = m_function_end_load_addr;
495 
496     return;
497 }
498 
499 IRExecutionUnit::~IRExecutionUnit ()
500 {
501     m_module_ap.reset();
502     m_execution_engine_ap.reset();
503     m_context_ap.reset();
504 }
505 
506 IRExecutionUnit::MemoryManager::MemoryManager (IRExecutionUnit &parent) :
507     m_default_mm_ap (new llvm::SectionMemoryManager()),
508     m_parent (parent)
509 {
510 }
511 
512 IRExecutionUnit::MemoryManager::~MemoryManager ()
513 {
514 }
515 
516 lldb::SectionType
517 IRExecutionUnit::GetSectionTypeFromSectionName (const llvm::StringRef &name, IRExecutionUnit::AllocationKind alloc_kind)
518 {
519     lldb::SectionType sect_type = lldb::eSectionTypeCode;
520     switch (alloc_kind)
521     {
522         case AllocationKind::Stub:  sect_type = lldb::eSectionTypeCode; break;
523         case AllocationKind::Code:  sect_type = lldb::eSectionTypeCode; break;
524         case AllocationKind::Data:  sect_type = lldb::eSectionTypeData; break;
525         case AllocationKind::Global:sect_type = lldb::eSectionTypeData; break;
526         case AllocationKind::Bytes: sect_type = lldb::eSectionTypeOther; break;
527     }
528 
529     if (!name.empty())
530     {
531         if (name.equals("__text") || name.equals(".text"))
532             sect_type = lldb::eSectionTypeCode;
533         else if (name.equals("__data") || name.equals(".data"))
534             sect_type = lldb::eSectionTypeCode;
535         else if (name.startswith("__debug_") || name.startswith(".debug_"))
536         {
537             const uint32_t name_idx = name[0] == '_' ? 8 : 7;
538             llvm::StringRef dwarf_name(name.substr(name_idx));
539             switch (dwarf_name[0])
540             {
541                 case 'a':
542                     if (dwarf_name.equals("abbrev"))
543                         sect_type = lldb::eSectionTypeDWARFDebugAbbrev;
544                     else if (dwarf_name.equals("aranges"))
545                         sect_type = lldb::eSectionTypeDWARFDebugAranges;
546                     else if (dwarf_name.equals("addr"))
547                         sect_type = lldb::eSectionTypeDWARFDebugAddr;
548                     break;
549 
550                 case 'f':
551                     if (dwarf_name.equals("frame"))
552                         sect_type = lldb::eSectionTypeDWARFDebugFrame;
553                     break;
554 
555                 case 'i':
556                     if (dwarf_name.equals("info"))
557                         sect_type = lldb::eSectionTypeDWARFDebugInfo;
558                     break;
559 
560                 case 'l':
561                     if (dwarf_name.equals("line"))
562                         sect_type = lldb::eSectionTypeDWARFDebugLine;
563                     else if (dwarf_name.equals("loc"))
564                         sect_type = lldb::eSectionTypeDWARFDebugLoc;
565                     break;
566 
567                 case 'm':
568                     if (dwarf_name.equals("macinfo"))
569                         sect_type = lldb::eSectionTypeDWARFDebugMacInfo;
570                     break;
571 
572                 case 'p':
573                     if (dwarf_name.equals("pubnames"))
574                         sect_type = lldb::eSectionTypeDWARFDebugPubNames;
575                     else if (dwarf_name.equals("pubtypes"))
576                         sect_type = lldb::eSectionTypeDWARFDebugPubTypes;
577                     break;
578 
579                 case 's':
580                     if (dwarf_name.equals("str"))
581                         sect_type = lldb::eSectionTypeDWARFDebugStr;
582                     else if (dwarf_name.equals("str_offsets"))
583                         sect_type = lldb::eSectionTypeDWARFDebugStrOffsets;
584                     break;
585 
586                 case 'r':
587                     if (dwarf_name.equals("ranges"))
588                         sect_type = lldb::eSectionTypeDWARFDebugRanges;
589                     break;
590 
591                 default:
592                     break;
593             }
594         }
595         else if (name.startswith("__apple_") || name.startswith(".apple_"))
596         {
597 #if 0
598             const uint32_t name_idx = name[0] == '_' ? 8 : 7;
599             llvm::StringRef apple_name(name.substr(name_idx));
600             switch (apple_name[0])
601             {
602                 case 'n':
603                     if (apple_name.equals("names"))
604                         sect_type = lldb::eSectionTypeDWARFAppleNames;
605                     else if (apple_name.equals("namespac") || apple_name.equals("namespaces"))
606                         sect_type = lldb::eSectionTypeDWARFAppleNamespaces;
607                     break;
608                 case 't':
609                     if (apple_name.equals("types"))
610                         sect_type = lldb::eSectionTypeDWARFAppleTypes;
611                     break;
612                 case 'o':
613                     if (apple_name.equals("objc"))
614                         sect_type = lldb::eSectionTypeDWARFAppleObjC;
615                     break;
616                 default:
617                     break;
618             }
619 #else
620             sect_type = lldb::eSectionTypeInvalid;
621 #endif
622         }
623         else if (name.equals("__objc_imageinfo"))
624             sect_type = lldb::eSectionTypeOther;
625     }
626     return sect_type;
627 }
628 
629 uint8_t *
630 IRExecutionUnit::MemoryManager::allocateCodeSection(uintptr_t Size,
631                                                     unsigned Alignment,
632                                                     unsigned SectionID,
633                                                     llvm::StringRef SectionName)
634 {
635     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
636 
637     uint8_t *return_value = m_default_mm_ap->allocateCodeSection(Size, Alignment, SectionID, SectionName);
638 
639     m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
640                                                   lldb::ePermissionsReadable | lldb::ePermissionsExecutable,
641                                                   GetSectionTypeFromSectionName (SectionName, AllocationKind::Code),
642                                                   Size,
643                                                   Alignment,
644                                                   SectionID,
645                                                   SectionName.str().c_str()));
646 
647     if (log)
648     {
649         log->Printf("IRExecutionUnit::allocateCodeSection(Size=0x%" PRIx64 ", Alignment=%u, SectionID=%u) = %p",
650                     (uint64_t)Size, Alignment, SectionID, (void *)return_value);
651     }
652 
653     if (m_parent.m_reported_allocations)
654     {
655         Error err;
656         lldb::ProcessSP process_sp = m_parent.GetBestExecutionContextScope()->CalculateProcess();
657 
658         m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back());
659     }
660 
661     return return_value;
662 }
663 
664 uint8_t *
665 IRExecutionUnit::MemoryManager::allocateDataSection(uintptr_t Size,
666                                                     unsigned Alignment,
667                                                     unsigned SectionID,
668                                                     llvm::StringRef SectionName,
669                                                     bool IsReadOnly)
670 {
671     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
672 
673     uint8_t *return_value = m_default_mm_ap->allocateDataSection(Size, Alignment, SectionID, SectionName, IsReadOnly);
674 
675     uint32_t permissions = lldb::ePermissionsReadable;
676     if (!IsReadOnly)
677         permissions |= lldb::ePermissionsWritable;
678     m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
679                                                   permissions,
680                                                   GetSectionTypeFromSectionName (SectionName, AllocationKind::Data),
681                                                   Size,
682                                                   Alignment,
683                                                   SectionID,
684                                                   SectionName.str().c_str()));
685     if (log)
686     {
687         log->Printf("IRExecutionUnit::allocateDataSection(Size=0x%" PRIx64 ", Alignment=%u, SectionID=%u) = %p",
688                     (uint64_t)Size, Alignment, SectionID, (void *)return_value);
689     }
690 
691     if (m_parent.m_reported_allocations)
692     {
693         Error err;
694         lldb::ProcessSP process_sp = m_parent.GetBestExecutionContextScope()->CalculateProcess();
695 
696         m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back());
697     }
698 
699     return return_value;
700 }
701 
702 static ConstString
703 FindBestAlternateMangledName(const ConstString &demangled,
704                              const lldb::LanguageType &lang_type,
705                              const SymbolContext &sym_ctx)
706 {
707     CPlusPlusLanguage::MethodName cpp_name(demangled);
708     std::string scope_qualified_name = cpp_name.GetScopeQualifiedName();
709 
710     if (!scope_qualified_name.size())
711         return ConstString();
712 
713     if (!sym_ctx.module_sp)
714         return ConstString();
715 
716     SymbolVendor *sym_vendor = sym_ctx.module_sp->GetSymbolVendor();
717     if (!sym_vendor)
718         return ConstString();
719 
720     lldb_private::SymbolFile *sym_file = sym_vendor->GetSymbolFile();
721     if (!sym_file)
722         return ConstString();
723 
724     std::vector<ConstString> alternates;
725     sym_file->GetMangledNamesForFunction(scope_qualified_name, alternates);
726 
727     std::vector<ConstString> param_and_qual_matches;
728     std::vector<ConstString> param_matches;
729     for (size_t i = 0; i < alternates.size(); i++)
730     {
731         ConstString alternate_mangled_name = alternates[i];
732         Mangled mangled(alternate_mangled_name, true);
733         ConstString demangled = mangled.GetDemangledName(lang_type);
734 
735         CPlusPlusLanguage::MethodName alternate_cpp_name(demangled);
736         if (!cpp_name.IsValid())
737             continue;
738 
739         if (alternate_cpp_name.GetArguments() == cpp_name.GetArguments())
740         {
741             if (alternate_cpp_name.GetQualifiers() == cpp_name.GetQualifiers())
742                 param_and_qual_matches.push_back(alternate_mangled_name);
743             else
744                 param_matches.push_back(alternate_mangled_name);
745         }
746     }
747 
748     if (param_and_qual_matches.size())
749         return param_and_qual_matches[0]; // It is assumed that there will be only one!
750     else if (param_matches.size())
751         return param_matches[0]; // Return one of them as a best match
752     else
753         return ConstString();
754 }
755 
756 struct IRExecutionUnit::SearchSpec
757 {
758     ConstString name;
759     uint32_t    mask;
760 
761     SearchSpec(ConstString n, uint32_t m = lldb::eFunctionNameTypeFull) :
762         name(n),
763         mask(m)
764     {
765     }
766 };
767 
768 void
769 IRExecutionUnit::CollectCandidateCNames(std::vector<IRExecutionUnit::SearchSpec> &C_specs, const ConstString &name)
770 {
771     if (m_strip_underscore && name.AsCString()[0] == '_')
772         C_specs.insert(C_specs.begin(), ConstString(&name.AsCString()[1]));
773     C_specs.push_back(SearchSpec(name));
774 }
775 
776 void
777 IRExecutionUnit::CollectCandidateCPlusPlusNames(std::vector<IRExecutionUnit::SearchSpec> &CPP_specs, const std::vector<SearchSpec> &C_specs, const SymbolContext &sc)
778 {
779     for (const SearchSpec &C_spec : C_specs)
780     {
781         const ConstString &name = C_spec.name;
782 
783         if (CPlusPlusLanguage::IsCPPMangledName(name.GetCString()))
784         {
785             Mangled mangled(name, true);
786             ConstString demangled = mangled.GetDemangledName(lldb::eLanguageTypeC_plus_plus);
787 
788             if (demangled)
789             {
790                 ConstString best_alternate_mangled_name = FindBestAlternateMangledName(demangled, lldb::eLanguageTypeC_plus_plus, sc);
791 
792                 if (best_alternate_mangled_name)
793                 {
794                     CPP_specs.push_back(best_alternate_mangled_name);
795                 }
796 
797                 CPP_specs.push_back(SearchSpec(demangled, lldb::eFunctionNameTypeFull));
798             }
799         }
800 
801         // Maybe we're looking for a const symbol but the debug info told us it was const...
802         if (!strncmp(name.GetCString(), "_ZN", 3) &&
803             strncmp(name.GetCString(), "_ZNK", 4))
804         {
805             std::string fixed_scratch("_ZNK");
806             fixed_scratch.append(name.GetCString() + 3);
807             CPP_specs.push_back(ConstString(fixed_scratch.c_str()));
808         }
809 
810         // Maybe we're looking for a static symbol but we thought it was global...
811         if (!strncmp(name.GetCString(), "_Z", 2) &&
812             strncmp(name.GetCString(), "_ZL", 3))
813         {
814             std::string fixed_scratch("_ZL");
815             fixed_scratch.append(name.GetCString() + 2);
816             CPP_specs.push_back(ConstString(fixed_scratch.c_str()));
817         }
818 
819     }
820 }
821 
822 void
823 IRExecutionUnit::CollectFallbackNames(std::vector<SearchSpec> &fallback_specs,
824                                       const std::vector<SearchSpec> &C_specs)
825 {
826     // As a last-ditch fallback, try the base name for C++ names.  It's terrible,
827     // but the DWARF doesn't always encode "extern C" correctly.
828 
829     for (const SearchSpec &C_spec : C_specs)
830     {
831         const ConstString &name = C_spec.name;
832 
833         if (CPlusPlusLanguage::IsCPPMangledName(name.GetCString()))
834         {
835             Mangled mangled_name(name);
836             ConstString demangled_name = mangled_name.GetDemangledName(lldb::eLanguageTypeC_plus_plus);
837             if (!demangled_name.IsEmpty())
838             {
839                 const char *demangled_cstr = demangled_name.AsCString();
840                 const char *lparen_loc = strchr(demangled_cstr, '(');
841                 if (lparen_loc)
842                 {
843                     llvm::StringRef base_name(demangled_cstr, lparen_loc-demangled_cstr);
844                     fallback_specs.push_back(ConstString(base_name));
845                 }
846             }
847         }
848     }
849 }
850 
851 
852 lldb::addr_t
853 IRExecutionUnit::FindInSymbols(const std::vector<IRExecutionUnit::SearchSpec> &specs, const lldb_private::SymbolContext &sc)
854 {
855     Target *target = sc.target_sp.get();
856 
857     if (!target)
858     {
859         // we shouldn't be doing any symbol lookup at all without a target
860         return LLDB_INVALID_ADDRESS;
861     }
862 
863     for (const SearchSpec &spec : specs)
864     {
865         SymbolContextList sc_list;
866 
867         lldb::addr_t best_internal_load_address = LLDB_INVALID_ADDRESS;
868 
869         std::function<bool (lldb::addr_t &, SymbolContextList &, const lldb_private::SymbolContext &)> get_external_load_address =
870             [&best_internal_load_address, target](lldb::addr_t &load_address,
871                                                   SymbolContextList &sc_list,
872                                                   const lldb_private::SymbolContext &sc) -> lldb::addr_t
873         {
874             load_address = LLDB_INVALID_ADDRESS;
875 
876             for (size_t si = 0, se = sc_list.GetSize(); si < se; ++si)
877             {
878                 SymbolContext candidate_sc;
879 
880                 sc_list.GetContextAtIndex(si, candidate_sc);
881 
882                 const bool is_external = (candidate_sc.function) ||
883                                          (candidate_sc.symbol && candidate_sc.symbol->IsExternal());
884                 if (candidate_sc.symbol)
885                 {
886                     load_address = candidate_sc.symbol->ResolveCallableAddress(*target);
887 
888                     if (load_address == LLDB_INVALID_ADDRESS)
889                     {
890                         if (target->GetProcessSP())
891                             load_address = candidate_sc.symbol->GetAddress().GetLoadAddress(target);
892                         else
893                             load_address = candidate_sc.symbol->GetAddress().GetFileAddress();
894                     }
895                 }
896 
897                 if (load_address == LLDB_INVALID_ADDRESS && candidate_sc.function)
898                 {
899                         if (target->GetProcessSP())
900                             load_address = candidate_sc.function->GetAddressRange().GetBaseAddress().GetLoadAddress(target);
901                         else
902                             load_address = candidate_sc.function->GetAddressRange().GetBaseAddress().GetFileAddress();
903                 }
904 
905                 if (load_address != LLDB_INVALID_ADDRESS)
906                 {
907                     if (is_external)
908                     {
909                         return true;
910                     }
911                     else if (best_internal_load_address == LLDB_INVALID_ADDRESS)
912                     {
913                         best_internal_load_address = load_address;
914                         load_address = LLDB_INVALID_ADDRESS;
915                     }
916                 }
917             }
918 
919             return false;
920         };
921 
922         if (sc.module_sp)
923         {
924             sc.module_sp->FindFunctions(spec.name,
925                                         NULL,
926                                         spec.mask,
927                                         true,  // include_symbols
928                                         false, // include_inlines
929                                         true,  // append
930                                         sc_list);
931         }
932 
933         lldb::addr_t load_address = LLDB_INVALID_ADDRESS;
934 
935         if (get_external_load_address(load_address, sc_list, sc))
936         {
937             return load_address;
938         }
939         else
940         {
941             sc_list.Clear();
942         }
943 
944         if (sc_list.GetSize() == 0 && sc.target_sp)
945         {
946             sc.target_sp->GetImages().FindFunctions(spec.name,
947                                                     spec.mask,
948                                                     true,  // include_symbols
949                                                     false, // include_inlines
950                                                     true,  // append
951                                                     sc_list);
952         }
953 
954         if (get_external_load_address(load_address, sc_list, sc))
955         {
956             return load_address;
957         }
958         else
959         {
960             sc_list.Clear();
961         }
962 
963         if (sc_list.GetSize() == 0 && sc.target_sp)
964         {
965             sc.target_sp->GetImages().FindSymbolsWithNameAndType(spec.name, lldb::eSymbolTypeAny, sc_list);
966         }
967 
968         if (get_external_load_address(load_address, sc_list, sc))
969         {
970             return load_address;
971         }
972         // if there are any searches we try after this, add an sc_list.Clear() in an "else" clause here
973 
974         if (best_internal_load_address != LLDB_INVALID_ADDRESS)
975         {
976             return best_internal_load_address;
977         }
978     }
979 
980     return LLDB_INVALID_ADDRESS;
981 }
982 
983 lldb::addr_t
984 IRExecutionUnit::FindInRuntimes(const std::vector<SearchSpec> &specs, const lldb_private::SymbolContext &sc)
985 {
986     lldb::TargetSP target_sp = sc.target_sp;
987 
988     if (!target_sp)
989     {
990         return LLDB_INVALID_ADDRESS;
991     }
992 
993     lldb::ProcessSP process_sp = sc.target_sp->GetProcessSP();
994 
995     if (!process_sp)
996     {
997         return LLDB_INVALID_ADDRESS;
998     }
999 
1000     ObjCLanguageRuntime *runtime = process_sp->GetObjCLanguageRuntime();
1001 
1002     if (runtime)
1003     {
1004         for (const SearchSpec &spec : specs)
1005         {
1006             lldb::addr_t symbol_load_addr = runtime->LookupRuntimeSymbol(spec.name);
1007 
1008             if (symbol_load_addr != LLDB_INVALID_ADDRESS)
1009                 return symbol_load_addr;
1010         }
1011     }
1012 
1013     return LLDB_INVALID_ADDRESS;
1014 }
1015 
1016 lldb::addr_t
1017 IRExecutionUnit::FindInUserDefinedSymbols(const std::vector<SearchSpec> &specs, const lldb_private::SymbolContext &sc)
1018 {
1019     lldb::TargetSP target_sp = sc.target_sp;
1020 
1021     for (const SearchSpec &spec : specs)
1022     {
1023         lldb::addr_t symbol_load_addr = target_sp->GetPersistentSymbol(spec.name);
1024 
1025         if (symbol_load_addr != LLDB_INVALID_ADDRESS)
1026             return symbol_load_addr;
1027     }
1028 
1029     return LLDB_INVALID_ADDRESS;
1030 }
1031 
1032 lldb::addr_t
1033 IRExecutionUnit::FindSymbol(const lldb_private::ConstString &name)
1034 {
1035     std::vector<SearchSpec> candidate_C_names;
1036     std::vector<SearchSpec> candidate_CPlusPlus_names;
1037 
1038     CollectCandidateCNames(candidate_C_names, name);
1039 
1040     lldb::addr_t ret = FindInSymbols(candidate_C_names, m_sym_ctx);
1041     if (ret == LLDB_INVALID_ADDRESS)
1042         ret = FindInRuntimes(candidate_C_names, m_sym_ctx);
1043 
1044     if (ret == LLDB_INVALID_ADDRESS)
1045         ret = FindInUserDefinedSymbols(candidate_C_names, m_sym_ctx);
1046 
1047     if (ret == LLDB_INVALID_ADDRESS)
1048     {
1049         CollectCandidateCPlusPlusNames(candidate_CPlusPlus_names, candidate_C_names, m_sym_ctx);
1050         ret = FindInSymbols(candidate_CPlusPlus_names, m_sym_ctx);
1051     }
1052 
1053     if (ret == LLDB_INVALID_ADDRESS)
1054     {
1055         std::vector<SearchSpec> candidate_fallback_names;
1056 
1057         CollectFallbackNames(candidate_fallback_names, candidate_C_names);
1058         ret = FindInSymbols(candidate_fallback_names, m_sym_ctx);
1059     }
1060 
1061     return ret;
1062 }
1063 
1064 void
1065 IRExecutionUnit::GetStaticInitializers(std::vector <lldb::addr_t> &static_initializers)
1066 {
1067     if (llvm::GlobalVariable *global_ctors = m_module->getNamedGlobal("llvm.global_ctors"))
1068     {
1069         if (llvm::ConstantArray *ctor_array = llvm::dyn_cast<llvm::ConstantArray>(global_ctors->getInitializer()))
1070         {
1071             for (llvm::Use &ctor_use : ctor_array->operands())
1072             {
1073                 if (llvm::ConstantStruct *ctor_struct = llvm::dyn_cast<llvm::ConstantStruct>(ctor_use))
1074                 {
1075                     lldbassert(ctor_struct->getNumOperands() == 3); // this is standardized
1076                     if (llvm::Function *ctor_function = llvm::dyn_cast<llvm::Function>(ctor_struct->getOperand(1)))
1077                     {
1078                         ctor_function->dump();
1079 
1080                         ConstString ctor_function_name_cs(ctor_function->getName().str());
1081 
1082                         for (JittedFunction &jitted_function : m_jitted_functions)
1083                         {
1084                             if (ctor_function_name_cs == jitted_function.m_name)
1085                             {
1086                                 if (jitted_function.m_remote_addr != LLDB_INVALID_ADDRESS)
1087                                 {
1088                                     static_initializers.push_back(jitted_function.m_remote_addr);
1089                                 }
1090                                 break;
1091                             }
1092                         }
1093                     }
1094                 }
1095             }
1096         }
1097     }
1098 }
1099 
1100 uint64_t
1101 IRExecutionUnit::MemoryManager::getSymbolAddress(const std::string &Name)
1102 {
1103     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1104 
1105     ConstString name_cs(Name.c_str());
1106 
1107     lldb::addr_t ret = m_parent.FindSymbol(name_cs);
1108 
1109     if (ret == LLDB_INVALID_ADDRESS)
1110     {
1111         if (log)
1112             log->Printf("IRExecutionUnit::getSymbolAddress(Name=\"%s\") = <not found>",
1113                         Name.c_str());
1114 
1115         m_parent.ReportSymbolLookupError(name_cs);
1116         return 0xbad0bad0;
1117     }
1118     else
1119     {
1120         if (log)
1121             log->Printf("IRExecutionUnit::getSymbolAddress(Name=\"%s\") = %" PRIx64,
1122                         Name.c_str(),
1123                         ret);
1124         return ret;
1125     }
1126 }
1127 
1128 void *
1129 IRExecutionUnit::MemoryManager::getPointerToNamedFunction(const std::string &Name,
1130                                                           bool AbortOnFailure) {
1131     assert (sizeof(void *) == 8);
1132 
1133     return (void*)getSymbolAddress(Name);
1134 }
1135 
1136 lldb::addr_t
1137 IRExecutionUnit::GetRemoteAddressForLocal (lldb::addr_t local_address)
1138 {
1139     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1140 
1141     for (AllocationRecord &record : m_records)
1142     {
1143         if (local_address >= record.m_host_address &&
1144             local_address < record.m_host_address + record.m_size)
1145         {
1146             if (record.m_process_address == LLDB_INVALID_ADDRESS)
1147                 return LLDB_INVALID_ADDRESS;
1148 
1149             lldb::addr_t ret = record.m_process_address + (local_address - record.m_host_address);
1150 
1151             if (log)
1152             {
1153                 log->Printf("IRExecutionUnit::GetRemoteAddressForLocal() found 0x%" PRIx64 " in [0x%" PRIx64 "..0x%" PRIx64 "], and returned 0x%" PRIx64 " from [0x%" PRIx64 "..0x%" PRIx64 "].",
1154                             local_address,
1155                             (uint64_t)record.m_host_address,
1156                             (uint64_t)record.m_host_address + (uint64_t)record.m_size,
1157                             ret,
1158                             record.m_process_address,
1159                             record.m_process_address + record.m_size);
1160             }
1161 
1162             return ret;
1163         }
1164     }
1165 
1166     return LLDB_INVALID_ADDRESS;
1167 }
1168 
1169 IRExecutionUnit::AddrRange
1170 IRExecutionUnit::GetRemoteRangeForLocal (lldb::addr_t local_address)
1171 {
1172     for (AllocationRecord &record : m_records)
1173     {
1174         if (local_address >= record.m_host_address &&
1175             local_address < record.m_host_address + record.m_size)
1176         {
1177             if (record.m_process_address == LLDB_INVALID_ADDRESS)
1178                 return AddrRange(0, 0);
1179 
1180             return AddrRange(record.m_process_address, record.m_size);
1181         }
1182     }
1183 
1184     return AddrRange (0, 0);
1185 }
1186 
1187 bool
1188 IRExecutionUnit::CommitOneAllocation (lldb::ProcessSP &process_sp,
1189                                       Error &error,
1190                                       AllocationRecord &record)
1191 {
1192     if (record.m_process_address != LLDB_INVALID_ADDRESS)
1193     {
1194         return true;
1195     }
1196 
1197     switch (record.m_sect_type)
1198     {
1199         case lldb::eSectionTypeInvalid:
1200         case lldb::eSectionTypeDWARFDebugAbbrev:
1201         case lldb::eSectionTypeDWARFDebugAddr:
1202         case lldb::eSectionTypeDWARFDebugAranges:
1203         case lldb::eSectionTypeDWARFDebugFrame:
1204         case lldb::eSectionTypeDWARFDebugInfo:
1205         case lldb::eSectionTypeDWARFDebugLine:
1206         case lldb::eSectionTypeDWARFDebugLoc:
1207         case lldb::eSectionTypeDWARFDebugMacInfo:
1208         case lldb::eSectionTypeDWARFDebugPubNames:
1209         case lldb::eSectionTypeDWARFDebugPubTypes:
1210         case lldb::eSectionTypeDWARFDebugRanges:
1211         case lldb::eSectionTypeDWARFDebugStr:
1212         case lldb::eSectionTypeDWARFDebugStrOffsets:
1213         case lldb::eSectionTypeDWARFAppleNames:
1214         case lldb::eSectionTypeDWARFAppleTypes:
1215         case lldb::eSectionTypeDWARFAppleNamespaces:
1216         case lldb::eSectionTypeDWARFAppleObjC:
1217             error.Clear();
1218             break;
1219         default:
1220             const bool zero_memory = false;
1221             record.m_process_address = Malloc (record.m_size,
1222                                                record.m_alignment,
1223                                                record.m_permissions,
1224                                                eAllocationPolicyProcessOnly,
1225                                                zero_memory,
1226                                                error);
1227             break;
1228     }
1229 
1230     return error.Success();
1231 }
1232 
1233 bool
1234 IRExecutionUnit::CommitAllocations (lldb::ProcessSP &process_sp)
1235 {
1236     bool ret = true;
1237 
1238     lldb_private::Error err;
1239 
1240     for (AllocationRecord &record : m_records)
1241     {
1242         ret = CommitOneAllocation(process_sp, err, record);
1243 
1244         if (!ret)
1245         {
1246             break;
1247         }
1248     }
1249 
1250     if (!ret)
1251     {
1252         for (AllocationRecord &record : m_records)
1253         {
1254             if (record.m_process_address != LLDB_INVALID_ADDRESS)
1255             {
1256                 Free(record.m_process_address, err);
1257                 record.m_process_address = LLDB_INVALID_ADDRESS;
1258             }
1259         }
1260     }
1261 
1262     return ret;
1263 }
1264 
1265 void
1266 IRExecutionUnit::ReportAllocations (llvm::ExecutionEngine &engine)
1267 {
1268     m_reported_allocations = true;
1269 
1270     for (AllocationRecord &record : m_records)
1271     {
1272         if (record.m_process_address == LLDB_INVALID_ADDRESS)
1273             continue;
1274 
1275         if (record.m_section_id == eSectionIDInvalid)
1276             continue;
1277 
1278         engine.mapSectionAddress((void*)record.m_host_address, record.m_process_address);
1279     }
1280 
1281     // Trigger re-application of relocations.
1282     engine.finalizeObject();
1283 }
1284 
1285 bool
1286 IRExecutionUnit::WriteData (lldb::ProcessSP &process_sp)
1287 {
1288     bool wrote_something = false;
1289     for (AllocationRecord &record : m_records)
1290     {
1291         if (record.m_process_address != LLDB_INVALID_ADDRESS)
1292         {
1293             lldb_private::Error err;
1294             WriteMemory (record.m_process_address, (uint8_t*)record.m_host_address, record.m_size, err);
1295             if (err.Success())
1296                 wrote_something = true;
1297         }
1298     }
1299     return wrote_something;
1300 }
1301 
1302 void
1303 IRExecutionUnit::AllocationRecord::dump (Log *log)
1304 {
1305     if (!log)
1306         return;
1307 
1308     log->Printf("[0x%llx+0x%llx]->0x%llx (alignment %d, section ID %d, name %s)",
1309                 (unsigned long long)m_host_address,
1310                 (unsigned long long)m_size,
1311                 (unsigned long long)m_process_address,
1312                 (unsigned)m_alignment,
1313                 (unsigned)m_section_id,
1314                 m_name.c_str());
1315 }
1316 
1317 
1318 lldb::ByteOrder
1319 IRExecutionUnit::GetByteOrder () const
1320 {
1321     ExecutionContext exe_ctx (GetBestExecutionContextScope());
1322     return exe_ctx.GetByteOrder();
1323 }
1324 
1325 uint32_t
1326 IRExecutionUnit::GetAddressByteSize () const
1327 {
1328     ExecutionContext exe_ctx (GetBestExecutionContextScope());
1329     return exe_ctx.GetAddressByteSize();
1330 }
1331 
1332 void
1333 IRExecutionUnit::PopulateSymtab (lldb_private::ObjectFile *obj_file,
1334                                  lldb_private::Symtab &symtab)
1335 {
1336     // No symbols yet...
1337 }
1338 
1339 
1340 void
1341 IRExecutionUnit::PopulateSectionList (lldb_private::ObjectFile *obj_file,
1342                                       lldb_private::SectionList &section_list)
1343 {
1344     for (AllocationRecord &record : m_records)
1345     {
1346         if (record.m_size > 0)
1347         {
1348             lldb::SectionSP section_sp (new lldb_private::Section (obj_file->GetModule(),
1349                                                                    obj_file,
1350                                                                    record.m_section_id,
1351                                                                    ConstString(record.m_name),
1352                                                                    record.m_sect_type,
1353                                                                    record.m_process_address,
1354                                                                    record.m_size,
1355                                                                    record.m_host_address,   // file_offset (which is the host address for the data)
1356                                                                    record.m_size,           // file_size
1357                                                                    0,
1358                                                                    record.m_permissions));  // flags
1359             section_list.AddSection (section_sp);
1360         }
1361     }
1362 }
1363 
1364 bool
1365 IRExecutionUnit::GetArchitecture (lldb_private::ArchSpec &arch)
1366 {
1367     ExecutionContext exe_ctx (GetBestExecutionContextScope());
1368     Target *target = exe_ctx.GetTargetPtr();
1369     if (target)
1370         arch = target->GetArchitecture();
1371     else
1372         arch.Clear();
1373     return arch.IsValid();
1374 }
1375 
1376 lldb::ModuleSP
1377 IRExecutionUnit::GetJITModule ()
1378 {
1379     ExecutionContext exe_ctx (GetBestExecutionContextScope());
1380     Target *target = exe_ctx.GetTargetPtr();
1381     if (target)
1382     {
1383         lldb::ModuleSP jit_module_sp = lldb_private::Module::CreateJITModule (std::static_pointer_cast<lldb_private::ObjectFileJITDelegate>(shared_from_this()));
1384         if (jit_module_sp)
1385         {
1386             bool changed = false;
1387             jit_module_sp->SetLoadAddress(*target, 0, true, changed);
1388         }
1389         return jit_module_sp;
1390     }
1391     return lldb::ModuleSP();
1392 }
1393