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