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