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/LLVMContext.h"
12 #include "llvm/IR/Module.h"
13 #include "llvm/Support/SourceMgr.h"
14 #include "lldb/Core/DataBufferHeap.h"
15 #include "lldb/Core/DataExtractor.h"
16 #include "lldb/Core/Debugger.h"
17 #include "lldb/Core/Disassembler.h"
18 #include "lldb/Core/Log.h"
19 #include "lldb/Core/Module.h"
20 #include "lldb/Core/Section.h"
21 #include "lldb/Expression/IRExecutionUnit.h"
22 #include "lldb/Target/ExecutionContext.h"
23 #include "lldb/Target/Target.h"
24 
25 using namespace lldb_private;
26 
27 IRExecutionUnit::IRExecutionUnit (std::unique_ptr<llvm::LLVMContext> &context_ap,
28                                   std::unique_ptr<llvm::Module> &module_ap,
29                                   ConstString &name,
30                                   const lldb::TargetSP &target_sp,
31                                   std::vector<std::string> &cpu_features) :
32     IRMemoryMap(target_sp),
33     m_context_ap(context_ap.release()),
34     m_module_ap(module_ap.release()),
35     m_module(m_module_ap.get()),
36     m_cpu_features(cpu_features),
37     m_name(name),
38     m_did_jit(false),
39     m_function_load_addr(LLDB_INVALID_ADDRESS),
40     m_function_end_load_addr(LLDB_INVALID_ADDRESS)
41 {
42 }
43 
44 lldb::addr_t
45 IRExecutionUnit::WriteNow (const uint8_t *bytes,
46                            size_t size,
47                            Error &error)
48 {
49     lldb::addr_t allocation_process_addr = Malloc (size,
50                                                    8,
51                                                    lldb::ePermissionsWritable | lldb::ePermissionsReadable,
52                                                    eAllocationPolicyMirror,
53                                                    error);
54 
55     if (!error.Success())
56         return LLDB_INVALID_ADDRESS;
57 
58     WriteMemory(allocation_process_addr, bytes, size, error);
59 
60     if (!error.Success())
61     {
62         Error err;
63         Free (allocation_process_addr, err);
64 
65         return LLDB_INVALID_ADDRESS;
66     }
67 
68     if (Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS))
69     {
70         DataBufferHeap my_buffer(size, 0);
71         Error err;
72         ReadMemory(my_buffer.GetBytes(), allocation_process_addr, size, err);
73 
74         if (err.Success())
75         {
76             DataExtractor my_extractor(my_buffer.GetBytes(), my_buffer.GetByteSize(), lldb::eByteOrderBig, 8);
77             my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(), allocation_process_addr, 16, DataExtractor::TypeUInt8);
78         }
79     }
80 
81     return allocation_process_addr;
82 }
83 
84 void
85 IRExecutionUnit::FreeNow (lldb::addr_t allocation)
86 {
87     if (allocation == LLDB_INVALID_ADDRESS)
88         return;
89 
90     Error err;
91 
92     Free(allocation, err);
93 }
94 
95 Error
96 IRExecutionUnit::DisassembleFunction (Stream &stream,
97                                       lldb::ProcessSP &process_wp)
98 {
99     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
100 
101     ExecutionContext exe_ctx(process_wp);
102 
103     Error ret;
104 
105     ret.Clear();
106 
107     lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
108     lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
109 
110     for (JittedFunction &function : m_jitted_functions)
111     {
112         if (strstr(function.m_name.c_str(), m_name.AsCString()))
113         {
114             func_local_addr = function.m_local_addr;
115             func_remote_addr = function.m_remote_addr;
116         }
117     }
118 
119     if (func_local_addr == LLDB_INVALID_ADDRESS)
120     {
121         ret.SetErrorToGenericError();
122         ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", m_name.AsCString());
123         return ret;
124     }
125 
126     if (log)
127         log->Printf("Found function, has local address 0x%" PRIx64 " and remote address 0x%" PRIx64, (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
128 
129     std::pair <lldb::addr_t, lldb::addr_t> func_range;
130 
131     func_range = GetRemoteRangeForLocal(func_local_addr);
132 
133     if (func_range.first == 0 && func_range.second == 0)
134     {
135         ret.SetErrorToGenericError();
136         ret.SetErrorStringWithFormat("Couldn't find code range for function %s", m_name.AsCString());
137         return ret;
138     }
139 
140     if (log)
141         log->Printf("Function's code range is [0x%" PRIx64 "+0x%" PRIx64 "]", func_range.first, func_range.second);
142 
143     Target *target = exe_ctx.GetTargetPtr();
144     if (!target)
145     {
146         ret.SetErrorToGenericError();
147         ret.SetErrorString("Couldn't find the target");
148         return ret;
149     }
150 
151     lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second, 0));
152 
153     Process *process = exe_ctx.GetProcessPtr();
154     Error err;
155     process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
156 
157     if (!err.Success())
158     {
159         ret.SetErrorToGenericError();
160         ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
161         return ret;
162     }
163 
164     ArchSpec arch(target->GetArchitecture());
165 
166     const char *plugin_name = NULL;
167     const char *flavor_string = NULL;
168     lldb::DisassemblerSP disassembler_sp = Disassembler::FindPlugin(arch, flavor_string, plugin_name);
169 
170     if (!disassembler_sp)
171     {
172         ret.SetErrorToGenericError();
173         ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
174         return ret;
175     }
176 
177     if (!process)
178     {
179         ret.SetErrorToGenericError();
180         ret.SetErrorString("Couldn't find the process");
181         return ret;
182     }
183 
184     DataExtractor extractor(buffer_sp,
185                             process->GetByteOrder(),
186                             target->GetArchitecture().GetAddressByteSize());
187 
188     if (log)
189     {
190         log->Printf("Function data has contents:");
191         extractor.PutToLog (log,
192                             0,
193                             extractor.GetByteSize(),
194                             func_remote_addr,
195                             16,
196                             DataExtractor::TypeUInt8);
197     }
198 
199     disassembler_sp->DecodeInstructions (Address (func_remote_addr), extractor, 0, UINT32_MAX, false, false);
200 
201     InstructionList &instruction_list = disassembler_sp->GetInstructionList();
202     instruction_list.Dump(&stream, true, true, &exe_ctx);
203 
204     // FIXME: The DisassemblerLLVMC has a reference cycle and won't go away if it has any active instructions.
205     // I'll fix that but for now, just clear the list and it will go away nicely.
206     disassembler_sp->GetInstructionList().Clear();
207     return ret;
208 }
209 
210 static void ReportInlineAsmError(const llvm::SMDiagnostic &diagnostic, void *Context, unsigned LocCookie)
211 {
212     Error *err = static_cast<Error*>(Context);
213 
214     if (err && err->Success())
215     {
216         err->SetErrorToGenericError();
217         err->SetErrorStringWithFormat("Inline assembly error: %s", diagnostic.getMessage().str().c_str());
218     }
219 }
220 
221 void
222 IRExecutionUnit::ReportSymbolLookupError(const ConstString &name)
223 {
224     m_failed_lookups.push_back(name);
225 }
226 
227 void
228 IRExecutionUnit::GetRunnableInfo(Error &error,
229                                  lldb::addr_t &func_addr,
230                                  lldb::addr_t &func_end)
231 {
232     lldb::ProcessSP process_sp(GetProcessWP().lock());
233 
234     static Mutex s_runnable_info_mutex(Mutex::Type::eMutexTypeRecursive);
235 
236     func_addr = LLDB_INVALID_ADDRESS;
237     func_end = LLDB_INVALID_ADDRESS;
238 
239     if (!process_sp)
240     {
241         error.SetErrorToGenericError();
242         error.SetErrorString("Couldn't write the JIT compiled code into the process because the process is invalid");
243         return;
244     }
245 
246     if (m_did_jit)
247     {
248         func_addr = m_function_load_addr;
249         func_end = m_function_end_load_addr;
250 
251         return;
252     };
253 
254     Mutex::Locker runnable_info_mutex_locker(s_runnable_info_mutex);
255 
256     m_did_jit = true;
257 
258     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
259 
260     std::string error_string;
261 
262     if (log)
263     {
264         std::string s;
265         llvm::raw_string_ostream oss(s);
266 
267         m_module->print(oss, NULL);
268 
269         oss.flush();
270 
271         log->Printf ("Module being sent to JIT: \n%s", s.c_str());
272     }
273 
274     llvm::Triple triple(m_module->getTargetTriple());
275     llvm::Function *function = m_module->getFunction (m_name.AsCString());
276     llvm::Reloc::Model relocModel;
277     llvm::CodeModel::Model codeModel;
278 
279     if (triple.isOSBinFormatELF())
280     {
281         relocModel = llvm::Reloc::Static;
282         // This will be small for 32-bit and large for 64-bit.
283         codeModel = llvm::CodeModel::JITDefault;
284     }
285     else
286     {
287         relocModel = llvm::Reloc::PIC_;
288         codeModel = llvm::CodeModel::Small;
289     }
290 
291     m_module_ap->getContext().setInlineAsmDiagnosticHandler(ReportInlineAsmError, &error);
292 
293     llvm::EngineBuilder builder(std::move(m_module_ap));
294 
295     builder.setEngineKind(llvm::EngineKind::JIT)
296     .setErrorStr(&error_string)
297     .setRelocationModel(relocModel)
298     .setMCJITMemoryManager(std::unique_ptr<MemoryManager>(new MemoryManager(*this)))
299     .setCodeModel(codeModel)
300     .setOptLevel(llvm::CodeGenOpt::Less);
301 
302     llvm::StringRef mArch;
303     llvm::StringRef mCPU;
304     llvm::SmallVector<std::string, 0> mAttrs;
305 
306     for (std::string &feature : m_cpu_features)
307         mAttrs.push_back(feature);
308 
309     llvm::TargetMachine *target_machine = builder.selectTarget(triple,
310                                                                mArch,
311                                                                mCPU,
312                                                                mAttrs);
313 
314     m_execution_engine_ap.reset(builder.create(target_machine));
315 
316     if (!m_execution_engine_ap.get())
317     {
318         error.SetErrorToGenericError();
319         error.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
320         return;
321     }
322 
323     // Make sure we see all sections, including ones that don't have relocations...
324     m_execution_engine_ap->setProcessAllSections(true);
325 
326     m_execution_engine_ap->DisableLazyCompilation();
327 
328     // We don't actually need the function pointer here, this just forces it to get resolved.
329 
330     void *fun_ptr = m_execution_engine_ap->getPointerToFunction(function);
331 
332     if (!error.Success())
333     {
334         // We got an error through our callback!
335         return;
336     }
337 
338     if (!function)
339     {
340         error.SetErrorToGenericError();
341         error.SetErrorStringWithFormat("Couldn't find '%s' in the JITted module", m_name.AsCString());
342         return;
343     }
344 
345     if (!fun_ptr)
346     {
347         error.SetErrorToGenericError();
348         error.SetErrorStringWithFormat("'%s' was in the JITted module but wasn't lowered", m_name.AsCString());
349         return;
350     }
351 
352     m_jitted_functions.push_back (JittedFunction(m_name.AsCString(), (lldb::addr_t)fun_ptr));
353 
354     CommitAllocations(process_sp);
355     ReportAllocations(*m_execution_engine_ap);
356     WriteData(process_sp);
357 
358     if (m_failed_lookups.size())
359     {
360         StreamString ss;
361 
362         ss.PutCString("Couldn't lookup symbols:\n");
363 
364         bool emitNewLine = false;
365 
366         for (const ConstString &failed_lookup : m_failed_lookups)
367         {
368             if (emitNewLine)
369                 ss.PutCString("\n");
370             emitNewLine = true;
371             ss.PutCString("  ");
372             ss.PutCString(Mangled(failed_lookup).GetDemangledName().AsCString());
373         }
374 
375         m_failed_lookups.clear();
376 
377         error.SetErrorString(ss.GetData());
378 
379         return;
380     }
381 
382     m_function_load_addr = LLDB_INVALID_ADDRESS;
383     m_function_end_load_addr = LLDB_INVALID_ADDRESS;
384 
385     for (JittedFunction &jitted_function : m_jitted_functions)
386     {
387         jitted_function.m_remote_addr = GetRemoteAddressForLocal (jitted_function.m_local_addr);
388 
389         if (!jitted_function.m_name.compare(m_name.AsCString()))
390         {
391             AddrRange func_range = GetRemoteRangeForLocal(jitted_function.m_local_addr);
392             m_function_end_load_addr = func_range.first + func_range.second;
393             m_function_load_addr = jitted_function.m_remote_addr;
394         }
395     }
396 
397     if (log)
398     {
399         log->Printf("Code can be run in the target.");
400 
401         StreamString disassembly_stream;
402 
403         Error err = DisassembleFunction(disassembly_stream, process_sp);
404 
405         if (!err.Success())
406         {
407             log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
408         }
409         else
410         {
411             log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
412         }
413 
414         log->Printf("Sections: ");
415         for (AllocationRecord &record : m_records)
416         {
417             if (record.m_process_address != LLDB_INVALID_ADDRESS)
418             {
419                 record.dump(log);
420 
421                 DataBufferHeap my_buffer(record.m_size, 0);
422                 Error err;
423                 ReadMemory(my_buffer.GetBytes(), record.m_process_address, record.m_size, err);
424 
425                 if (err.Success())
426                 {
427                     DataExtractor my_extractor(my_buffer.GetBytes(), my_buffer.GetByteSize(), lldb::eByteOrderBig, 8);
428                     my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(), record.m_process_address, 16, DataExtractor::TypeUInt8);
429                 }
430             }
431         }
432     }
433 
434     func_addr = m_function_load_addr;
435     func_end = m_function_end_load_addr;
436 
437     return;
438 }
439 
440 IRExecutionUnit::~IRExecutionUnit ()
441 {
442     m_module_ap.reset();
443     m_execution_engine_ap.reset();
444     m_context_ap.reset();
445 }
446 
447 IRExecutionUnit::MemoryManager::MemoryManager (IRExecutionUnit &parent) :
448     m_default_mm_ap (new llvm::SectionMemoryManager()),
449     m_parent (parent)
450 {
451 }
452 
453 IRExecutionUnit::MemoryManager::~MemoryManager ()
454 {
455 }
456 
457 lldb::SectionType
458 IRExecutionUnit::GetSectionTypeFromSectionName (const llvm::StringRef &name, IRExecutionUnit::AllocationKind alloc_kind)
459 {
460     lldb::SectionType sect_type = lldb::eSectionTypeCode;
461     switch (alloc_kind)
462     {
463         case AllocationKind::Stub:  sect_type = lldb::eSectionTypeCode; break;
464         case AllocationKind::Code:  sect_type = lldb::eSectionTypeCode; break;
465         case AllocationKind::Data:  sect_type = lldb::eSectionTypeData; break;
466         case AllocationKind::Global:sect_type = lldb::eSectionTypeData; break;
467         case AllocationKind::Bytes: sect_type = lldb::eSectionTypeOther; break;
468     }
469 
470     if (!name.empty())
471     {
472         if (name.equals("__text") || name.equals(".text"))
473             sect_type = lldb::eSectionTypeCode;
474         else if (name.equals("__data") || name.equals(".data"))
475             sect_type = lldb::eSectionTypeCode;
476         else if (name.startswith("__debug_") || name.startswith(".debug_"))
477         {
478             const uint32_t name_idx = name[0] == '_' ? 8 : 7;
479             llvm::StringRef dwarf_name(name.substr(name_idx));
480             switch (dwarf_name[0])
481             {
482                 case 'a':
483                     if (dwarf_name.equals("abbrev"))
484                         sect_type = lldb::eSectionTypeDWARFDebugAbbrev;
485                     else if (dwarf_name.equals("aranges"))
486                         sect_type = lldb::eSectionTypeDWARFDebugAranges;
487                     break;
488 
489                 case 'f':
490                     if (dwarf_name.equals("frame"))
491                         sect_type = lldb::eSectionTypeDWARFDebugFrame;
492                     break;
493 
494                 case 'i':
495                     if (dwarf_name.equals("info"))
496                         sect_type = lldb::eSectionTypeDWARFDebugInfo;
497                     break;
498 
499                 case 'l':
500                     if (dwarf_name.equals("line"))
501                         sect_type = lldb::eSectionTypeDWARFDebugLine;
502                     else if (dwarf_name.equals("loc"))
503                         sect_type = lldb::eSectionTypeDWARFDebugLoc;
504                     break;
505 
506                 case 'm':
507                     if (dwarf_name.equals("macinfo"))
508                         sect_type = lldb::eSectionTypeDWARFDebugMacInfo;
509                     break;
510 
511                 case 'p':
512                     if (dwarf_name.equals("pubnames"))
513                         sect_type = lldb::eSectionTypeDWARFDebugPubNames;
514                     else if (dwarf_name.equals("pubtypes"))
515                         sect_type = lldb::eSectionTypeDWARFDebugPubTypes;
516                     break;
517 
518                 case 's':
519                     if (dwarf_name.equals("str"))
520                         sect_type = lldb::eSectionTypeDWARFDebugStr;
521                     break;
522 
523                 case 'r':
524                     if (dwarf_name.equals("ranges"))
525                         sect_type = lldb::eSectionTypeDWARFDebugRanges;
526                     break;
527 
528                 default:
529                     break;
530             }
531         }
532         else if (name.startswith("__apple_") || name.startswith(".apple_"))
533         {
534 #if 0
535             const uint32_t name_idx = name[0] == '_' ? 8 : 7;
536             llvm::StringRef apple_name(name.substr(name_idx));
537             switch (apple_name[0])
538             {
539                 case 'n':
540                     if (apple_name.equals("names"))
541                         sect_type = lldb::eSectionTypeDWARFAppleNames;
542                     else if (apple_name.equals("namespac") || apple_name.equals("namespaces"))
543                         sect_type = lldb::eSectionTypeDWARFAppleNamespaces;
544                     break;
545                 case 't':
546                     if (apple_name.equals("types"))
547                         sect_type = lldb::eSectionTypeDWARFAppleTypes;
548                     break;
549                 case 'o':
550                     if (apple_name.equals("objc"))
551                         sect_type = lldb::eSectionTypeDWARFAppleObjC;
552                     break;
553                 default:
554                     break;
555             }
556 #else
557             sect_type = lldb::eSectionTypeInvalid;
558 #endif
559         }
560         else if (name.equals("__objc_imageinfo"))
561             sect_type = lldb::eSectionTypeOther;
562     }
563     return sect_type;
564 }
565 
566 uint8_t *
567 IRExecutionUnit::MemoryManager::allocateCodeSection(uintptr_t Size,
568                                                     unsigned Alignment,
569                                                     unsigned SectionID,
570                                                     llvm::StringRef SectionName)
571 {
572     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
573 
574     uint8_t *return_value = m_default_mm_ap->allocateCodeSection(Size, Alignment, SectionID, SectionName);
575 
576     m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
577                                                   lldb::ePermissionsReadable | lldb::ePermissionsExecutable,
578                                                   GetSectionTypeFromSectionName (SectionName, AllocationKind::Code),
579                                                   Size,
580                                                   Alignment,
581                                                   SectionID,
582                                                   SectionName.str().c_str()));
583 
584     if (log)
585     {
586         log->Printf("IRExecutionUnit::allocateCodeSection(Size=0x%" PRIx64 ", Alignment=%u, SectionID=%u) = %p",
587                     (uint64_t)Size, Alignment, SectionID, return_value);
588     }
589 
590     return return_value;
591 }
592 
593 uint8_t *
594 IRExecutionUnit::MemoryManager::allocateDataSection(uintptr_t Size,
595                                                     unsigned Alignment,
596                                                     unsigned SectionID,
597                                                     llvm::StringRef SectionName,
598                                                     bool IsReadOnly)
599 {
600     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
601 
602     uint8_t *return_value = m_default_mm_ap->allocateDataSection(Size, Alignment, SectionID, SectionName, IsReadOnly);
603 
604     m_parent.m_records.push_back(AllocationRecord((uintptr_t)return_value,
605                                                   lldb::ePermissionsReadable | (IsReadOnly ? 0 : lldb::ePermissionsWritable),
606                                                   GetSectionTypeFromSectionName (SectionName, AllocationKind::Data),
607                                                   Size,
608                                                   Alignment,
609                                                   SectionID,
610                                                   SectionName.str().c_str()));
611     if (log)
612     {
613         log->Printf("IRExecutionUnit::allocateDataSection(Size=0x%" PRIx64 ", Alignment=%u, SectionID=%u) = %p",
614                     (uint64_t)Size, Alignment, SectionID, return_value);
615     }
616 
617     return return_value;
618 }
619 
620 uint64_t
621 IRExecutionUnit::MemoryManager::getSymbolAddress(const std::string &Name)
622 {
623     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
624 
625     SymbolContextList sc_list;
626 
627     ExecutionContextScope *exe_scope = m_parent.GetBestExecutionContextScope();
628 
629     lldb::TargetSP target_sp = exe_scope->CalculateTarget();
630 
631     const char *name = Name.c_str();
632 
633     ConstString bare_name_cs(name);
634     ConstString name_cs;
635 
636     if (name[0] == '_')
637         name_cs = ConstString(name + 1);
638 
639     if (!target_sp)
640     {
641         if (log)
642             log->Printf("IRExecutionUnit::getSymbolAddress(Name=\"%s\") = <no target>",
643                         Name.c_str());
644 
645         m_parent.ReportSymbolLookupError(name_cs);
646 
647         return 0xbad0bad0;
648     }
649 
650     uint32_t num_matches = 0;
651     lldb::ProcessSP process_sp = exe_scope->CalculateProcess();
652 
653     if (!name_cs.IsEmpty())
654     {
655         target_sp->GetImages().FindSymbolsWithNameAndType(name_cs, lldb::eSymbolTypeAny, sc_list);
656         num_matches = sc_list.GetSize();
657     }
658 
659     if (!num_matches)
660     {
661         target_sp->GetImages().FindSymbolsWithNameAndType(bare_name_cs, lldb::eSymbolTypeAny, sc_list);
662         num_matches = sc_list.GetSize();
663     }
664 
665     lldb::addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
666 
667     for (uint32_t i=0; i<num_matches && (symbol_load_addr == 0 || symbol_load_addr == LLDB_INVALID_ADDRESS); i++)
668     {
669         SymbolContext sym_ctx;
670         sc_list.GetContextAtIndex(i, sym_ctx);
671 
672         if (sym_ctx.symbol->GetType() == lldb::eSymbolTypeUndefined)
673             continue;
674 
675         const Address *sym_address = &sym_ctx.symbol->GetAddress();
676 
677         if (!sym_address || !sym_address->IsValid())
678             continue;
679 
680         symbol_load_addr = sym_ctx.symbol->ResolveCallableAddress(*target_sp);
681 
682         if (symbol_load_addr == LLDB_INVALID_ADDRESS)
683         {
684             symbol_load_addr = sym_ctx.symbol->GetAddress().GetLoadAddress(target_sp.get());
685         }
686     }
687 
688     if (symbol_load_addr == LLDB_INVALID_ADDRESS && process_sp && name_cs)
689     {
690         // Try the Objective-C language runtime.
691 
692         ObjCLanguageRuntime *runtime = process_sp->GetObjCLanguageRuntime();
693 
694         if (runtime)
695             symbol_load_addr = runtime->LookupRuntimeSymbol(name_cs);
696     }
697 
698     if (symbol_load_addr == LLDB_INVALID_ADDRESS)
699     {
700         if (log)
701             log->Printf("IRExecutionUnit::getSymbolAddress(Name=\"%s\") = <not found>",
702                         name);
703 
704         m_parent.ReportSymbolLookupError(bare_name_cs);
705 
706         return 0xbad0bad0;
707     }
708 
709     if (log)
710         log->Printf("IRExecutionUnit::getSymbolAddress(Name=\"%s\") = %" PRIx64,
711                     name,
712                     symbol_load_addr);
713 
714     if (symbol_load_addr == 0)
715         return 0xbad00add;
716 
717     return symbol_load_addr;
718 }
719 
720 void *
721 IRExecutionUnit::MemoryManager::getPointerToNamedFunction(const std::string &Name,
722                                                           bool AbortOnFailure) {
723     assert (sizeof(void *) == 8);
724 
725     return (void*)getSymbolAddress(Name);
726 }
727 
728 lldb::addr_t
729 IRExecutionUnit::GetRemoteAddressForLocal (lldb::addr_t local_address)
730 {
731     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
732 
733     for (AllocationRecord &record : m_records)
734     {
735         if (local_address >= record.m_host_address &&
736             local_address < record.m_host_address + record.m_size)
737         {
738             if (record.m_process_address == LLDB_INVALID_ADDRESS)
739                 return LLDB_INVALID_ADDRESS;
740 
741             lldb::addr_t ret = record.m_process_address + (local_address - record.m_host_address);
742 
743             if (log)
744             {
745                 log->Printf("IRExecutionUnit::GetRemoteAddressForLocal() found 0x%" PRIx64 " in [0x%" PRIx64 "..0x%" PRIx64 "], and returned 0x%" PRIx64 " from [0x%" PRIx64 "..0x%" PRIx64 "].",
746                             local_address,
747                             (uint64_t)record.m_host_address,
748                             (uint64_t)record.m_host_address + (uint64_t)record.m_size,
749                             ret,
750                             record.m_process_address,
751                             record.m_process_address + record.m_size);
752             }
753 
754             return ret;
755         }
756     }
757 
758     return LLDB_INVALID_ADDRESS;
759 }
760 
761 IRExecutionUnit::AddrRange
762 IRExecutionUnit::GetRemoteRangeForLocal (lldb::addr_t local_address)
763 {
764     for (AllocationRecord &record : m_records)
765     {
766         if (local_address >= record.m_host_address &&
767             local_address < record.m_host_address + record.m_size)
768         {
769             if (record.m_process_address == LLDB_INVALID_ADDRESS)
770                 return AddrRange(0, 0);
771 
772             return AddrRange(record.m_process_address, record.m_size);
773         }
774     }
775 
776     return AddrRange (0, 0);
777 }
778 
779 bool
780 IRExecutionUnit::CommitAllocations (lldb::ProcessSP &process_sp)
781 {
782     bool ret = true;
783 
784     lldb_private::Error err;
785 
786     for (AllocationRecord &record : m_records)
787     {
788         if (record.m_process_address != LLDB_INVALID_ADDRESS)
789             continue;
790 
791         switch (record.m_sect_type)
792         {
793         case lldb::eSectionTypeInvalid:
794         case lldb::eSectionTypeDWARFDebugAbbrev:
795         case lldb::eSectionTypeDWARFDebugAranges:
796         case lldb::eSectionTypeDWARFDebugFrame:
797         case lldb::eSectionTypeDWARFDebugInfo:
798         case lldb::eSectionTypeDWARFDebugLine:
799         case lldb::eSectionTypeDWARFDebugLoc:
800         case lldb::eSectionTypeDWARFDebugMacInfo:
801         case lldb::eSectionTypeDWARFDebugPubNames:
802         case lldb::eSectionTypeDWARFDebugPubTypes:
803         case lldb::eSectionTypeDWARFDebugRanges:
804         case lldb::eSectionTypeDWARFDebugStr:
805         case lldb::eSectionTypeDWARFAppleNames:
806         case lldb::eSectionTypeDWARFAppleTypes:
807         case lldb::eSectionTypeDWARFAppleNamespaces:
808         case lldb::eSectionTypeDWARFAppleObjC:
809             err.Clear();
810             break;
811         default:
812             record.m_process_address = Malloc (record.m_size,
813                                                record.m_alignment,
814                                                record.m_permissions,
815                                                eAllocationPolicyProcessOnly,
816                                                err);
817             break;
818         }
819 
820         if (!err.Success())
821         {
822             ret = false;
823             break;
824         }
825     }
826 
827     if (!ret)
828     {
829         for (AllocationRecord &record : m_records)
830         {
831             if (record.m_process_address != LLDB_INVALID_ADDRESS)
832             {
833                 Free(record.m_process_address, err);
834                 record.m_process_address = LLDB_INVALID_ADDRESS;
835             }
836         }
837     }
838 
839     return ret;
840 }
841 
842 void
843 IRExecutionUnit::ReportAllocations (llvm::ExecutionEngine &engine)
844 {
845     for (AllocationRecord &record : m_records)
846     {
847         if (record.m_process_address == LLDB_INVALID_ADDRESS)
848             continue;
849 
850         if (record.m_section_id == eSectionIDInvalid)
851             continue;
852 
853         engine.mapSectionAddress((void*)record.m_host_address, record.m_process_address);
854     }
855 
856     // Trigger re-application of relocations.
857     engine.finalizeObject();
858 }
859 
860 bool
861 IRExecutionUnit::WriteData (lldb::ProcessSP &process_sp)
862 {
863     bool wrote_something = false;
864     for (AllocationRecord &record : m_records)
865     {
866         if (record.m_process_address != LLDB_INVALID_ADDRESS)
867         {
868             lldb_private::Error err;
869             WriteMemory (record.m_process_address, (uint8_t*)record.m_host_address, record.m_size, err);
870             if (err.Success())
871                 wrote_something = true;
872         }
873     }
874     return wrote_something;
875 }
876 
877 void
878 IRExecutionUnit::AllocationRecord::dump (Log *log)
879 {
880     if (!log)
881         return;
882 
883     log->Printf("[0x%llx+0x%llx]->0x%llx (alignment %d, section ID %d)",
884                 (unsigned long long)m_host_address,
885                 (unsigned long long)m_size,
886                 (unsigned long long)m_process_address,
887                 (unsigned)m_alignment,
888                 (unsigned)m_section_id);
889 }
890 
891 
892 lldb::ByteOrder
893 IRExecutionUnit::GetByteOrder () const
894 {
895     ExecutionContext exe_ctx (GetBestExecutionContextScope());
896     return exe_ctx.GetByteOrder();
897 }
898 
899 uint32_t
900 IRExecutionUnit::GetAddressByteSize () const
901 {
902     ExecutionContext exe_ctx (GetBestExecutionContextScope());
903     return exe_ctx.GetAddressByteSize();
904 }
905 
906 void
907 IRExecutionUnit::PopulateSymtab (lldb_private::ObjectFile *obj_file,
908                                  lldb_private::Symtab &symtab)
909 {
910     // No symbols yet...
911 }
912 
913 
914 void
915 IRExecutionUnit::PopulateSectionList (lldb_private::ObjectFile *obj_file,
916                                       lldb_private::SectionList &section_list)
917 {
918     for (AllocationRecord &record : m_records)
919     {
920         if (record.m_size > 0)
921         {
922             lldb::SectionSP section_sp (new lldb_private::Section (obj_file->GetModule(),
923                                                                    obj_file,
924                                                                    record.m_section_id,
925                                                                    ConstString(record.m_name),
926                                                                    record.m_sect_type,
927                                                                    record.m_process_address,
928                                                                    record.m_size,
929                                                                    record.m_host_address,   // file_offset (which is the host address for the data)
930                                                                    record.m_size,           // file_size
931                                                                    0,
932                                                                    record.m_permissions));  // flags
933             section_list.AddSection (section_sp);
934         }
935     }
936 }
937 
938 bool
939 IRExecutionUnit::GetArchitecture (lldb_private::ArchSpec &arch)
940 {
941     ExecutionContext exe_ctx (GetBestExecutionContextScope());
942     Target *target = exe_ctx.GetTargetPtr();
943     if (target)
944         arch = target->GetArchitecture();
945     else
946         arch.Clear();
947     return arch.IsValid();
948 }
949 
950 lldb::ModuleSP
951 IRExecutionUnit::GetJITModule ()
952 {
953     ExecutionContext exe_ctx (GetBestExecutionContextScope());
954     Target *target = exe_ctx.GetTargetPtr();
955     if (target)
956     {
957         lldb::ModuleSP jit_module_sp = lldb_private::Module::CreateJITModule (std::static_pointer_cast<lldb_private::ObjectFileJITDelegate>(shared_from_this()));
958         if (jit_module_sp)
959         {
960             bool changed = false;
961             jit_module_sp->SetLoadAddress(*target, 0, true, changed);
962         }
963         return jit_module_sp;
964     }
965     return lldb::ModuleSP();
966 }
967