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