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