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