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