1 //===-- IRExecutionUnit.cpp -------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
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"
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/LanguageRuntime.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"
34 #include "lldb/../../source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
35 #include "lldb/../../source/Plugins/ObjectFile/JIT/ObjectFileJIT.h"
37 using namespace lldb_private;
39 IRExecutionUnit::IRExecutionUnit(std::unique_ptr<llvm::LLVMContext> &context_up,
40 std::unique_ptr<llvm::Module> &module_up,
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) {}
52 lldb::addr_t IRExecutionUnit::WriteNow(const uint8_t *bytes, size_t size,
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);
60 return LLDB_INVALID_ADDRESS;
62 WriteMemory(allocation_process_addr, bytes, size, error);
64 if (!error.Success()) {
66 Free(allocation_process_addr, err);
68 return LLDB_INVALID_ADDRESS;
72 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)) {
73 DataBufferHeap my_buffer(size, 0);
75 ReadMemory(my_buffer.GetBytes(), allocation_process_addr, size, err);
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);
86 return allocation_process_addr;
89 void IRExecutionUnit::FreeNow(lldb::addr_t allocation) {
90 if (allocation == LLDB_INVALID_ADDRESS)
95 Free(allocation, err);
98 Status IRExecutionUnit::DisassembleFunction(Stream &stream,
99 lldb::ProcessSP &process_wp) {
100 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
102 ExecutionContext exe_ctx(process_wp);
108 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
109 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
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;
118 if (func_local_addr == LLDB_INVALID_ADDRESS) {
119 ret.SetErrorToGenericError();
120 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly",
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);
130 std::pair<lldb::addr_t, lldb::addr_t> func_range;
132 func_range = GetRemoteRangeForLocal(func_local_addr);
134 if (func_range.first == 0 && func_range.second == 0) {
135 ret.SetErrorToGenericError();
136 ret.SetErrorStringWithFormat("Couldn't find code range for function %s",
142 log->Printf("Function's code range is [0x%" PRIx64 "+0x%" PRIx64 "]",
143 func_range.first, func_range.second);
145 Target *target = exe_ctx.GetTargetPtr();
147 ret.SetErrorToGenericError();
148 ret.SetErrorString("Couldn't find the target");
152 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second, 0));
154 Process *process = exe_ctx.GetProcessPtr();
156 process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(),
157 buffer_sp->GetByteSize(), err);
159 if (!err.Success()) {
160 ret.SetErrorToGenericError();
161 ret.SetErrorStringWithFormat("Couldn't read from process: %s",
162 err.AsCString("unknown error"));
166 ArchSpec arch(target->GetArchitecture());
168 const char *plugin_name = nullptr;
169 const char *flavor_string = nullptr;
170 lldb::DisassemblerSP disassembler_sp =
171 Disassembler::FindPlugin(arch, flavor_string, plugin_name);
173 if (!disassembler_sp) {
174 ret.SetErrorToGenericError();
175 ret.SetErrorStringWithFormat(
176 "Unable to find disassembler plug-in for %s architecture.",
177 arch.GetArchitectureName());
182 ret.SetErrorToGenericError();
183 ret.SetErrorString("Couldn't find the process");
187 DataExtractor extractor(buffer_sp, process->GetByteOrder(),
188 target->GetArchitecture().GetAddressByteSize());
191 log->Printf("Function data has contents:");
192 extractor.PutToLog(log, 0, extractor.GetByteSize(), func_remote_addr, 16,
193 DataExtractor::TypeUInt8);
196 disassembler_sp->DecodeInstructions(Address(func_remote_addr), extractor, 0,
197 UINT32_MAX, false, false);
199 InstructionList &instruction_list = disassembler_sp->GetInstructionList();
200 instruction_list.Dump(&stream, true, true, &exe_ctx);
204 static void ReportInlineAsmError(const llvm::SMDiagnostic &diagnostic,
205 void *Context, unsigned LocCookie) {
206 Status *err = static_cast<Status *>(Context);
208 if (err && err->Success()) {
209 err->SetErrorToGenericError();
210 err->SetErrorStringWithFormat("Inline assembly error: %s",
211 diagnostic.getMessage().str().c_str());
215 void IRExecutionUnit::ReportSymbolLookupError(ConstString name) {
216 m_failed_lookups.push_back(name);
219 void IRExecutionUnit::GetRunnableInfo(Status &error, lldb::addr_t &func_addr,
220 lldb::addr_t &func_end) {
221 lldb::ProcessSP process_sp(GetProcessWP().lock());
223 static std::recursive_mutex s_runnable_info_mutex;
225 func_addr = LLDB_INVALID_ADDRESS;
226 func_end = LLDB_INVALID_ADDRESS;
229 error.SetErrorToGenericError();
230 error.SetErrorString("Couldn't write the JIT compiled code into the "
231 "process because the process is invalid");
236 func_addr = m_function_load_addr;
237 func_end = m_function_end_load_addr;
242 std::lock_guard<std::recursive_mutex> guard(s_runnable_info_mutex);
246 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
248 std::string error_string;
252 llvm::raw_string_ostream oss(s);
254 m_module->print(oss, nullptr);
258 log->Printf("Module being sent to JIT: \n%s", s.c_str());
261 m_module_up->getContext().setInlineAsmDiagnosticHandler(ReportInlineAsmError,
264 llvm::EngineBuilder builder(std::move(m_module_up));
265 llvm::Triple triple(m_module->getTargetTriple());
267 builder.setEngineKind(llvm::EngineKind::JIT)
268 .setErrorStr(&error_string)
269 .setRelocationModel(triple.isOSBinFormatMachO()
271 : llvm::Reloc::Static)
272 .setMCJITMemoryManager(
273 std::unique_ptr<MemoryManager>(new MemoryManager(*this)))
274 .setOptLevel(llvm::CodeGenOpt::Less);
276 llvm::StringRef mArch;
277 llvm::StringRef mCPU;
278 llvm::SmallVector<std::string, 0> mAttrs;
280 for (std::string &feature : m_cpu_features)
281 mAttrs.push_back(feature);
283 llvm::TargetMachine *target_machine =
284 builder.selectTarget(triple, mArch, mCPU, mAttrs);
286 m_execution_engine_up.reset(builder.create(target_machine));
288 if (!m_execution_engine_up) {
289 error.SetErrorToGenericError();
290 error.SetErrorStringWithFormat("Couldn't JIT the function: %s",
291 error_string.c_str());
296 (m_execution_engine_up->getDataLayout().getGlobalPrefix() == '_');
298 class ObjectDumper : public llvm::ObjectCache {
300 void notifyObjectCompiled(const llvm::Module *module,
301 llvm::MemoryBufferRef object) override {
303 llvm::SmallVector<char, 256> result_path;
304 std::string object_name_model =
305 "jit-object-" + module->getModuleIdentifier() + "-%%%.o";
306 (void)llvm::sys::fs::createUniqueFile(object_name_model, fd, result_path);
307 llvm::raw_fd_ostream fds(fd, true);
308 fds.write(object.getBufferStart(), object.getBufferSize());
311 std::unique_ptr<llvm::MemoryBuffer>
312 getObject(const llvm::Module *module) override {
313 // Return nothing - we're just abusing the object-cache mechanism to dump
319 if (process_sp->GetTarget().GetEnableSaveObjects()) {
320 m_object_cache_up = llvm::make_unique<ObjectDumper>();
321 m_execution_engine_up->setObjectCache(m_object_cache_up.get());
324 // Make sure we see all sections, including ones that don't have
326 m_execution_engine_up->setProcessAllSections(true);
328 m_execution_engine_up->DisableLazyCompilation();
330 for (llvm::Function &function : *m_module) {
331 if (function.isDeclaration() || function.hasPrivateLinkage())
334 const bool external =
335 function.hasExternalLinkage() || function.hasLinkOnceODRLinkage();
337 void *fun_ptr = m_execution_engine_up->getPointerToFunction(&function);
339 if (!error.Success()) {
340 // We got an error through our callback!
345 error.SetErrorToGenericError();
346 error.SetErrorStringWithFormat(
347 "'%s' was in the JITted module but wasn't lowered",
348 function.getName().str().c_str());
351 m_jitted_functions.push_back(JittedFunction(
352 function.getName().str().c_str(), external, (lldb::addr_t)fun_ptr));
355 CommitAllocations(process_sp);
356 ReportAllocations(*m_execution_engine_up);
358 // We have to do this after calling ReportAllocations because for the MCJIT,
359 // getGlobalValueAddress will cause the JIT to perform all relocations. That
360 // can only be done once, and has to happen after we do the remapping from
361 // local -> remote. That means we don't know the local address of the
362 // Variables, but we don't need that for anything, so that's okay.
364 std::function<void(llvm::GlobalValue &)> RegisterOneValue = [this](
365 llvm::GlobalValue &val) {
366 if (val.hasExternalLinkage() && !val.isDeclaration()) {
367 uint64_t var_ptr_addr =
368 m_execution_engine_up->getGlobalValueAddress(val.getName().str());
370 lldb::addr_t remote_addr = GetRemoteAddressForLocal(var_ptr_addr);
372 // This is a really unfortunae API that sometimes returns local addresses
373 // and sometimes returns remote addresses, based on whether the variable
374 // was relocated during ReportAllocations or not.
376 if (remote_addr == LLDB_INVALID_ADDRESS) {
377 remote_addr = var_ptr_addr;
380 if (var_ptr_addr != 0)
381 m_jitted_global_variables.push_back(JittedGlobalVariable(
382 val.getName().str().c_str(), LLDB_INVALID_ADDRESS, remote_addr));
386 for (llvm::GlobalVariable &global_var : m_module->getGlobalList()) {
387 RegisterOneValue(global_var);
390 for (llvm::GlobalAlias &global_alias : m_module->getAliasList()) {
391 RegisterOneValue(global_alias);
394 WriteData(process_sp);
396 if (m_failed_lookups.size()) {
399 ss.PutCString("Couldn't lookup symbols:\n");
401 bool emitNewLine = false;
403 for (ConstString failed_lookup : m_failed_lookups) {
408 ss.PutCString(Mangled(failed_lookup)
409 .GetDemangledName(lldb::eLanguageTypeObjC_plus_plus)
413 m_failed_lookups.clear();
415 error.SetErrorString(ss.GetString());
420 m_function_load_addr = LLDB_INVALID_ADDRESS;
421 m_function_end_load_addr = LLDB_INVALID_ADDRESS;
423 for (JittedFunction &jitted_function : m_jitted_functions) {
424 jitted_function.m_remote_addr =
425 GetRemoteAddressForLocal(jitted_function.m_local_addr);
427 if (!m_name.IsEmpty() && jitted_function.m_name == m_name) {
428 AddrRange func_range =
429 GetRemoteRangeForLocal(jitted_function.m_local_addr);
430 m_function_end_load_addr = func_range.first + func_range.second;
431 m_function_load_addr = jitted_function.m_remote_addr;
436 log->Printf("Code can be run in the target.");
438 StreamString disassembly_stream;
440 Status err = DisassembleFunction(disassembly_stream, process_sp);
442 if (!err.Success()) {
443 log->Printf("Couldn't disassemble function : %s",
444 err.AsCString("unknown error"));
446 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
449 log->Printf("Sections: ");
450 for (AllocationRecord &record : m_records) {
451 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
454 DataBufferHeap my_buffer(record.m_size, 0);
456 ReadMemory(my_buffer.GetBytes(), record.m_process_address,
460 DataExtractor my_extractor(my_buffer.GetBytes(),
461 my_buffer.GetByteSize(),
462 lldb::eByteOrderBig, 8);
463 my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(),
464 record.m_process_address, 16,
465 DataExtractor::TypeUInt8);
470 DataExtractor my_extractor((const void *)record.m_host_address,
471 record.m_size, lldb::eByteOrderBig, 8);
472 my_extractor.PutToLog(log, 0, record.m_size, record.m_host_address, 16,
473 DataExtractor::TypeUInt8);
478 func_addr = m_function_load_addr;
479 func_end = m_function_end_load_addr;
484 IRExecutionUnit::~IRExecutionUnit() {
486 m_execution_engine_up.reset();
487 m_context_up.reset();
490 IRExecutionUnit::MemoryManager::MemoryManager(IRExecutionUnit &parent)
491 : m_default_mm_up(new llvm::SectionMemoryManager()), m_parent(parent) {}
493 IRExecutionUnit::MemoryManager::~MemoryManager() {}
495 lldb::SectionType IRExecutionUnit::GetSectionTypeFromSectionName(
496 const llvm::StringRef &name, IRExecutionUnit::AllocationKind alloc_kind) {
497 lldb::SectionType sect_type = lldb::eSectionTypeCode;
498 switch (alloc_kind) {
499 case AllocationKind::Stub:
500 sect_type = lldb::eSectionTypeCode;
502 case AllocationKind::Code:
503 sect_type = lldb::eSectionTypeCode;
505 case AllocationKind::Data:
506 sect_type = lldb::eSectionTypeData;
508 case AllocationKind::Global:
509 sect_type = lldb::eSectionTypeData;
511 case AllocationKind::Bytes:
512 sect_type = lldb::eSectionTypeOther;
517 if (name.equals("__text") || name.equals(".text"))
518 sect_type = lldb::eSectionTypeCode;
519 else if (name.equals("__data") || name.equals(".data"))
520 sect_type = lldb::eSectionTypeCode;
521 else if (name.startswith("__debug_") || name.startswith(".debug_")) {
522 const uint32_t name_idx = name[0] == '_' ? 8 : 7;
523 llvm::StringRef dwarf_name(name.substr(name_idx));
524 switch (dwarf_name[0]) {
526 if (dwarf_name.equals("abbrev"))
527 sect_type = lldb::eSectionTypeDWARFDebugAbbrev;
528 else if (dwarf_name.equals("aranges"))
529 sect_type = lldb::eSectionTypeDWARFDebugAranges;
530 else if (dwarf_name.equals("addr"))
531 sect_type = lldb::eSectionTypeDWARFDebugAddr;
535 if (dwarf_name.equals("frame"))
536 sect_type = lldb::eSectionTypeDWARFDebugFrame;
540 if (dwarf_name.equals("info"))
541 sect_type = lldb::eSectionTypeDWARFDebugInfo;
545 if (dwarf_name.equals("line"))
546 sect_type = lldb::eSectionTypeDWARFDebugLine;
547 else if (dwarf_name.equals("loc"))
548 sect_type = lldb::eSectionTypeDWARFDebugLoc;
549 else if (dwarf_name.equals("loclists"))
550 sect_type = lldb::eSectionTypeDWARFDebugLocLists;
554 if (dwarf_name.equals("macinfo"))
555 sect_type = lldb::eSectionTypeDWARFDebugMacInfo;
559 if (dwarf_name.equals("pubnames"))
560 sect_type = lldb::eSectionTypeDWARFDebugPubNames;
561 else if (dwarf_name.equals("pubtypes"))
562 sect_type = lldb::eSectionTypeDWARFDebugPubTypes;
566 if (dwarf_name.equals("str"))
567 sect_type = lldb::eSectionTypeDWARFDebugStr;
568 else if (dwarf_name.equals("str_offsets"))
569 sect_type = lldb::eSectionTypeDWARFDebugStrOffsets;
573 if (dwarf_name.equals("ranges"))
574 sect_type = lldb::eSectionTypeDWARFDebugRanges;
580 } else if (name.startswith("__apple_") || name.startswith(".apple_"))
581 sect_type = lldb::eSectionTypeInvalid;
582 else if (name.equals("__objc_imageinfo"))
583 sect_type = lldb::eSectionTypeOther;
588 uint8_t *IRExecutionUnit::MemoryManager::allocateCodeSection(
589 uintptr_t Size, unsigned Alignment, unsigned SectionID,
590 llvm::StringRef SectionName) {
591 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
593 uint8_t *return_value = m_default_mm_up->allocateCodeSection(
594 Size, Alignment, SectionID, SectionName);
596 m_parent.m_records.push_back(AllocationRecord(
597 (uintptr_t)return_value,
598 lldb::ePermissionsReadable | lldb::ePermissionsExecutable,
599 GetSectionTypeFromSectionName(SectionName, AllocationKind::Code), Size,
600 Alignment, SectionID, SectionName.str().c_str()));
603 log->Printf("IRExecutionUnit::allocateCodeSection(Size=0x%" PRIx64
604 ", Alignment=%u, SectionID=%u) = %p",
605 (uint64_t)Size, Alignment, SectionID, (void *)return_value);
608 if (m_parent.m_reported_allocations) {
610 lldb::ProcessSP process_sp =
611 m_parent.GetBestExecutionContextScope()->CalculateProcess();
613 m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back());
619 uint8_t *IRExecutionUnit::MemoryManager::allocateDataSection(
620 uintptr_t Size, unsigned Alignment, unsigned SectionID,
621 llvm::StringRef SectionName, bool IsReadOnly) {
622 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
624 uint8_t *return_value = m_default_mm_up->allocateDataSection(
625 Size, Alignment, SectionID, SectionName, IsReadOnly);
627 uint32_t permissions = lldb::ePermissionsReadable;
629 permissions |= lldb::ePermissionsWritable;
630 m_parent.m_records.push_back(AllocationRecord(
631 (uintptr_t)return_value, permissions,
632 GetSectionTypeFromSectionName(SectionName, AllocationKind::Data), Size,
633 Alignment, SectionID, SectionName.str().c_str()));
635 log->Printf("IRExecutionUnit::allocateDataSection(Size=0x%" PRIx64
636 ", Alignment=%u, SectionID=%u) = %p",
637 (uint64_t)Size, Alignment, SectionID, (void *)return_value);
640 if (m_parent.m_reported_allocations) {
642 lldb::ProcessSP process_sp =
643 m_parent.GetBestExecutionContextScope()->CalculateProcess();
645 m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back());
652 FindBestAlternateMangledName(ConstString demangled,
653 const lldb::LanguageType &lang_type,
654 const SymbolContext &sym_ctx) {
655 CPlusPlusLanguage::MethodName cpp_name(demangled);
656 std::string scope_qualified_name = cpp_name.GetScopeQualifiedName();
658 if (!scope_qualified_name.size())
659 return ConstString();
661 if (!sym_ctx.module_sp)
662 return ConstString();
664 SymbolVendor *sym_vendor = sym_ctx.module_sp->GetSymbolVendor();
666 return ConstString();
668 lldb_private::SymbolFile *sym_file = sym_vendor->GetSymbolFile();
670 return ConstString();
672 std::vector<ConstString> alternates;
673 sym_file->GetMangledNamesForFunction(scope_qualified_name, alternates);
675 std::vector<ConstString> param_and_qual_matches;
676 std::vector<ConstString> param_matches;
677 for (size_t i = 0; i < alternates.size(); i++) {
678 ConstString alternate_mangled_name = alternates[i];
679 Mangled mangled(alternate_mangled_name, true);
680 ConstString demangled = mangled.GetDemangledName(lang_type);
682 CPlusPlusLanguage::MethodName alternate_cpp_name(demangled);
683 if (!cpp_name.IsValid())
686 if (alternate_cpp_name.GetArguments() == cpp_name.GetArguments()) {
687 if (alternate_cpp_name.GetQualifiers() == cpp_name.GetQualifiers())
688 param_and_qual_matches.push_back(alternate_mangled_name);
690 param_matches.push_back(alternate_mangled_name);
694 if (param_and_qual_matches.size())
695 return param_and_qual_matches[0]; // It is assumed that there will be only
697 else if (param_matches.size())
698 return param_matches[0]; // Return one of them as a best match
700 return ConstString();
703 struct IRExecutionUnit::SearchSpec {
705 lldb::FunctionNameType mask;
707 SearchSpec(ConstString n,
708 lldb::FunctionNameType m = lldb::eFunctionNameTypeFull)
709 : name(n), mask(m) {}
712 void IRExecutionUnit::CollectCandidateCNames(
713 std::vector<IRExecutionUnit::SearchSpec> &C_specs,
715 if (m_strip_underscore && name.AsCString()[0] == '_')
716 C_specs.insert(C_specs.begin(), ConstString(&name.AsCString()[1]));
717 C_specs.push_back(SearchSpec(name));
720 void IRExecutionUnit::CollectCandidateCPlusPlusNames(
721 std::vector<IRExecutionUnit::SearchSpec> &CPP_specs,
722 const std::vector<SearchSpec> &C_specs, const SymbolContext &sc) {
723 for (const SearchSpec &C_spec : C_specs) {
724 ConstString name = C_spec.name;
726 if (CPlusPlusLanguage::IsCPPMangledName(name.GetCString())) {
727 Mangled mangled(name, true);
728 ConstString demangled =
729 mangled.GetDemangledName(lldb::eLanguageTypeC_plus_plus);
732 ConstString best_alternate_mangled_name = FindBestAlternateMangledName(
733 demangled, lldb::eLanguageTypeC_plus_plus, sc);
735 if (best_alternate_mangled_name) {
736 CPP_specs.push_back(best_alternate_mangled_name);
739 CPP_specs.push_back(SearchSpec(demangled, lldb::eFunctionNameTypeFull));
743 std::set<ConstString> alternates;
744 CPlusPlusLanguage::FindAlternateFunctionManglings(name, alternates);
745 CPP_specs.insert(CPP_specs.end(), alternates.begin(), alternates.end());
749 void IRExecutionUnit::CollectFallbackNames(
750 std::vector<SearchSpec> &fallback_specs,
751 const std::vector<SearchSpec> &C_specs) {
752 // As a last-ditch fallback, try the base name for C++ names. It's terrible,
753 // but the DWARF doesn't always encode "extern C" correctly.
755 for (const SearchSpec &C_spec : C_specs) {
756 ConstString name = C_spec.name;
758 if (CPlusPlusLanguage::IsCPPMangledName(name.GetCString())) {
759 Mangled mangled_name(name);
760 ConstString demangled_name =
761 mangled_name.GetDemangledName(lldb::eLanguageTypeC_plus_plus);
762 if (!demangled_name.IsEmpty()) {
763 const char *demangled_cstr = demangled_name.AsCString();
764 const char *lparen_loc = strchr(demangled_cstr, '(');
766 llvm::StringRef base_name(demangled_cstr,
767 lparen_loc - demangled_cstr);
768 fallback_specs.push_back(ConstString(base_name));
775 lldb::addr_t IRExecutionUnit::FindInSymbols(
776 const std::vector<IRExecutionUnit::SearchSpec> &specs,
777 const lldb_private::SymbolContext &sc,
778 bool &symbol_was_missing_weak) {
779 symbol_was_missing_weak = false;
780 Target *target = sc.target_sp.get();
783 // we shouldn't be doing any symbol lookup at all without a target
784 return LLDB_INVALID_ADDRESS;
787 for (const SearchSpec &spec : specs) {
788 SymbolContextList sc_list;
790 lldb::addr_t best_internal_load_address = LLDB_INVALID_ADDRESS;
792 std::function<bool(lldb::addr_t &, SymbolContextList &,
793 const lldb_private::SymbolContext &)>
794 get_external_load_address = [&best_internal_load_address, target,
795 &symbol_was_missing_weak](
796 lldb::addr_t &load_address, SymbolContextList &sc_list,
797 const lldb_private::SymbolContext &sc) -> lldb::addr_t {
798 load_address = LLDB_INVALID_ADDRESS;
800 if (sc_list.GetSize() == 0)
803 // missing_weak_symbol will be true only if we found only weak undefined
804 // references to this symbol.
805 symbol_was_missing_weak = true;
806 for (auto candidate_sc : sc_list.SymbolContexts()) {
807 // Only symbols can be weak undefined:
808 if (!candidate_sc.symbol)
809 symbol_was_missing_weak = false;
810 else if (candidate_sc.symbol->GetType() != lldb::eSymbolTypeUndefined
811 || !candidate_sc.symbol->IsWeak())
812 symbol_was_missing_weak = false;
814 const bool is_external =
815 (candidate_sc.function) ||
816 (candidate_sc.symbol && candidate_sc.symbol->IsExternal());
817 if (candidate_sc.symbol) {
818 load_address = candidate_sc.symbol->ResolveCallableAddress(*target);
820 if (load_address == LLDB_INVALID_ADDRESS) {
821 if (target->GetProcessSP())
823 candidate_sc.symbol->GetAddress().GetLoadAddress(target);
825 load_address = candidate_sc.symbol->GetAddress().GetFileAddress();
829 if (load_address == LLDB_INVALID_ADDRESS && candidate_sc.function) {
830 if (target->GetProcessSP())
831 load_address = candidate_sc.function->GetAddressRange()
833 .GetLoadAddress(target);
835 load_address = candidate_sc.function->GetAddressRange()
840 if (load_address != LLDB_INVALID_ADDRESS) {
843 } else if (best_internal_load_address == LLDB_INVALID_ADDRESS) {
844 best_internal_load_address = load_address;
845 load_address = LLDB_INVALID_ADDRESS;
850 // You test the address of a weak symbol against NULL to see if it is
851 // present. So we should return 0 for a missing weak symbol.
852 if (symbol_was_missing_weak) {
861 sc.module_sp->FindFunctions(spec.name, nullptr, spec.mask,
862 true, // include_symbols
863 false, // include_inlines
868 lldb::addr_t load_address = LLDB_INVALID_ADDRESS;
870 if (get_external_load_address(load_address, sc_list, sc)) {
876 if (sc_list.GetSize() == 0 && sc.target_sp) {
877 sc.target_sp->GetImages().FindFunctions(spec.name, spec.mask,
878 true, // include_symbols
879 false, // include_inlines
884 if (get_external_load_address(load_address, sc_list, sc)) {
890 if (sc_list.GetSize() == 0 && sc.target_sp) {
891 sc.target_sp->GetImages().FindSymbolsWithNameAndType(
892 spec.name, lldb::eSymbolTypeAny, sc_list);
895 if (get_external_load_address(load_address, sc_list, sc)) {
898 // if there are any searches we try after this, add an sc_list.Clear() in
899 // an "else" clause here
901 if (best_internal_load_address != LLDB_INVALID_ADDRESS) {
902 return best_internal_load_address;
906 return LLDB_INVALID_ADDRESS;
910 IRExecutionUnit::FindInRuntimes(const std::vector<SearchSpec> &specs,
911 const lldb_private::SymbolContext &sc) {
912 lldb::TargetSP target_sp = sc.target_sp;
915 return LLDB_INVALID_ADDRESS;
918 lldb::ProcessSP process_sp = sc.target_sp->GetProcessSP();
921 return LLDB_INVALID_ADDRESS;
924 for (const SearchSpec &spec : specs) {
925 for (LanguageRuntime *runtime : process_sp->GetLanguageRuntimes()) {
926 lldb::addr_t symbol_load_addr = runtime->LookupRuntimeSymbol(spec.name);
928 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
929 return symbol_load_addr;
933 return LLDB_INVALID_ADDRESS;
936 lldb::addr_t IRExecutionUnit::FindInUserDefinedSymbols(
937 const std::vector<SearchSpec> &specs,
938 const lldb_private::SymbolContext &sc) {
939 lldb::TargetSP target_sp = sc.target_sp;
941 for (const SearchSpec &spec : specs) {
942 lldb::addr_t symbol_load_addr = target_sp->GetPersistentSymbol(spec.name);
944 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
945 return symbol_load_addr;
948 return LLDB_INVALID_ADDRESS;
952 IRExecutionUnit::FindSymbol(lldb_private::ConstString name, bool &missing_weak) {
953 std::vector<SearchSpec> candidate_C_names;
954 std::vector<SearchSpec> candidate_CPlusPlus_names;
956 CollectCandidateCNames(candidate_C_names, name);
958 lldb::addr_t ret = FindInSymbols(candidate_C_names, m_sym_ctx, missing_weak);
959 if (ret != LLDB_INVALID_ADDRESS)
962 // If we find the symbol in runtimes or user defined symbols it can't be
963 // a missing weak symbol.
964 missing_weak = false;
965 ret = FindInRuntimes(candidate_C_names, m_sym_ctx);
966 if (ret != LLDB_INVALID_ADDRESS)
969 ret = FindInUserDefinedSymbols(candidate_C_names, m_sym_ctx);
970 if (ret != LLDB_INVALID_ADDRESS)
973 CollectCandidateCPlusPlusNames(candidate_CPlusPlus_names, candidate_C_names,
975 ret = FindInSymbols(candidate_CPlusPlus_names, m_sym_ctx, missing_weak);
976 if (ret != LLDB_INVALID_ADDRESS)
979 std::vector<SearchSpec> candidate_fallback_names;
981 CollectFallbackNames(candidate_fallback_names, candidate_C_names);
982 ret = FindInSymbols(candidate_fallback_names, m_sym_ctx, missing_weak);
987 void IRExecutionUnit::GetStaticInitializers(
988 std::vector<lldb::addr_t> &static_initializers) {
989 if (llvm::GlobalVariable *global_ctors =
990 m_module->getNamedGlobal("llvm.global_ctors")) {
991 if (llvm::ConstantArray *ctor_array = llvm::dyn_cast<llvm::ConstantArray>(
992 global_ctors->getInitializer())) {
993 for (llvm::Use &ctor_use : ctor_array->operands()) {
994 if (llvm::ConstantStruct *ctor_struct =
995 llvm::dyn_cast<llvm::ConstantStruct>(ctor_use)) {
996 lldbassert(ctor_struct->getNumOperands() ==
997 3); // this is standardized
998 if (llvm::Function *ctor_function =
999 llvm::dyn_cast<llvm::Function>(ctor_struct->getOperand(1))) {
1000 ConstString ctor_function_name_cs(ctor_function->getName().str());
1002 for (JittedFunction &jitted_function : m_jitted_functions) {
1003 if (ctor_function_name_cs == jitted_function.m_name) {
1004 if (jitted_function.m_remote_addr != LLDB_INVALID_ADDRESS) {
1005 static_initializers.push_back(jitted_function.m_remote_addr);
1018 IRExecutionUnit::MemoryManager::findSymbol(const std::string &Name) {
1019 bool missing_weak = false;
1020 uint64_t addr = GetSymbolAddressAndPresence(Name, missing_weak);
1021 // This is a weak symbol:
1023 return llvm::JITSymbol(addr,
1024 llvm::JITSymbolFlags::Exported | llvm::JITSymbolFlags::Weak);
1026 return llvm::JITSymbol(addr, llvm::JITSymbolFlags::Exported);
1030 IRExecutionUnit::MemoryManager::getSymbolAddress(const std::string &Name) {
1031 bool missing_weak = false;
1032 return GetSymbolAddressAndPresence(Name, missing_weak);
1036 IRExecutionUnit::MemoryManager::GetSymbolAddressAndPresence(
1037 const std::string &Name, bool &missing_weak) {
1038 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1040 ConstString name_cs(Name.c_str());
1042 lldb::addr_t ret = m_parent.FindSymbol(name_cs, missing_weak);
1044 if (ret == LLDB_INVALID_ADDRESS) {
1047 "IRExecutionUnit::getSymbolAddress(Name=\"%s\") = <not found>",
1050 m_parent.ReportSymbolLookupError(name_cs);
1054 log->Printf("IRExecutionUnit::getSymbolAddress(Name=\"%s\") = %" PRIx64,
1060 void *IRExecutionUnit::MemoryManager::getPointerToNamedFunction(
1061 const std::string &Name, bool AbortOnFailure) {
1062 return (void *)getSymbolAddress(Name);
1066 IRExecutionUnit::GetRemoteAddressForLocal(lldb::addr_t local_address) {
1067 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1069 for (AllocationRecord &record : m_records) {
1070 if (local_address >= record.m_host_address &&
1071 local_address < record.m_host_address + record.m_size) {
1072 if (record.m_process_address == LLDB_INVALID_ADDRESS)
1073 return LLDB_INVALID_ADDRESS;
1076 record.m_process_address + (local_address - record.m_host_address);
1080 "IRExecutionUnit::GetRemoteAddressForLocal() found 0x%" PRIx64
1081 " in [0x%" PRIx64 "..0x%" PRIx64 "], and returned 0x%" PRIx64
1082 " from [0x%" PRIx64 "..0x%" PRIx64 "].",
1083 local_address, (uint64_t)record.m_host_address,
1084 (uint64_t)record.m_host_address + (uint64_t)record.m_size, ret,
1085 record.m_process_address, record.m_process_address + record.m_size);
1092 return LLDB_INVALID_ADDRESS;
1095 IRExecutionUnit::AddrRange
1096 IRExecutionUnit::GetRemoteRangeForLocal(lldb::addr_t local_address) {
1097 for (AllocationRecord &record : m_records) {
1098 if (local_address >= record.m_host_address &&
1099 local_address < record.m_host_address + record.m_size) {
1100 if (record.m_process_address == LLDB_INVALID_ADDRESS)
1101 return AddrRange(0, 0);
1103 return AddrRange(record.m_process_address, record.m_size);
1107 return AddrRange(0, 0);
1110 bool IRExecutionUnit::CommitOneAllocation(lldb::ProcessSP &process_sp,
1112 AllocationRecord &record) {
1113 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
1117 switch (record.m_sect_type) {
1118 case lldb::eSectionTypeInvalid:
1119 case lldb::eSectionTypeDWARFDebugAbbrev:
1120 case lldb::eSectionTypeDWARFDebugAddr:
1121 case lldb::eSectionTypeDWARFDebugAranges:
1122 case lldb::eSectionTypeDWARFDebugCuIndex:
1123 case lldb::eSectionTypeDWARFDebugFrame:
1124 case lldb::eSectionTypeDWARFDebugInfo:
1125 case lldb::eSectionTypeDWARFDebugLine:
1126 case lldb::eSectionTypeDWARFDebugLoc:
1127 case lldb::eSectionTypeDWARFDebugLocLists:
1128 case lldb::eSectionTypeDWARFDebugMacInfo:
1129 case lldb::eSectionTypeDWARFDebugPubNames:
1130 case lldb::eSectionTypeDWARFDebugPubTypes:
1131 case lldb::eSectionTypeDWARFDebugRanges:
1132 case lldb::eSectionTypeDWARFDebugStr:
1133 case lldb::eSectionTypeDWARFDebugStrOffsets:
1134 case lldb::eSectionTypeDWARFAppleNames:
1135 case lldb::eSectionTypeDWARFAppleTypes:
1136 case lldb::eSectionTypeDWARFAppleNamespaces:
1137 case lldb::eSectionTypeDWARFAppleObjC:
1138 case lldb::eSectionTypeDWARFGNUDebugAltLink:
1142 const bool zero_memory = false;
1143 record.m_process_address =
1144 Malloc(record.m_size, record.m_alignment, record.m_permissions,
1145 eAllocationPolicyProcessOnly, zero_memory, error);
1149 return error.Success();
1152 bool IRExecutionUnit::CommitAllocations(lldb::ProcessSP &process_sp) {
1155 lldb_private::Status err;
1157 for (AllocationRecord &record : m_records) {
1158 ret = CommitOneAllocation(process_sp, err, record);
1166 for (AllocationRecord &record : m_records) {
1167 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
1168 Free(record.m_process_address, err);
1169 record.m_process_address = LLDB_INVALID_ADDRESS;
1177 void IRExecutionUnit::ReportAllocations(llvm::ExecutionEngine &engine) {
1178 m_reported_allocations = true;
1180 for (AllocationRecord &record : m_records) {
1181 if (record.m_process_address == LLDB_INVALID_ADDRESS)
1184 if (record.m_section_id == eSectionIDInvalid)
1187 engine.mapSectionAddress((void *)record.m_host_address,
1188 record.m_process_address);
1191 // Trigger re-application of relocations.
1192 engine.finalizeObject();
1195 bool IRExecutionUnit::WriteData(lldb::ProcessSP &process_sp) {
1196 bool wrote_something = false;
1197 for (AllocationRecord &record : m_records) {
1198 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
1199 lldb_private::Status err;
1200 WriteMemory(record.m_process_address, (uint8_t *)record.m_host_address,
1201 record.m_size, err);
1203 wrote_something = true;
1206 return wrote_something;
1209 void IRExecutionUnit::AllocationRecord::dump(Log *log) {
1213 log->Printf("[0x%llx+0x%llx]->0x%llx (alignment %d, section ID %d, name %s)",
1214 (unsigned long long)m_host_address, (unsigned long long)m_size,
1215 (unsigned long long)m_process_address, (unsigned)m_alignment,
1216 (unsigned)m_section_id, m_name.c_str());
1219 lldb::ByteOrder IRExecutionUnit::GetByteOrder() const {
1220 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1221 return exe_ctx.GetByteOrder();
1224 uint32_t IRExecutionUnit::GetAddressByteSize() const {
1225 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1226 return exe_ctx.GetAddressByteSize();
1229 void IRExecutionUnit::PopulateSymtab(lldb_private::ObjectFile *obj_file,
1230 lldb_private::Symtab &symtab) {
1231 // No symbols yet...
1234 void IRExecutionUnit::PopulateSectionList(
1235 lldb_private::ObjectFile *obj_file,
1236 lldb_private::SectionList §ion_list) {
1237 for (AllocationRecord &record : m_records) {
1238 if (record.m_size > 0) {
1239 lldb::SectionSP section_sp(new lldb_private::Section(
1240 obj_file->GetModule(), obj_file, record.m_section_id,
1241 ConstString(record.m_name), record.m_sect_type,
1242 record.m_process_address, record.m_size,
1243 record.m_host_address, // file_offset (which is the host address for
1245 record.m_size, // file_size
1247 record.m_permissions)); // flags
1248 section_list.AddSection(section_sp);
1253 ArchSpec IRExecutionUnit::GetArchitecture() {
1254 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1255 if(Target *target = exe_ctx.GetTargetPtr())
1256 return target->GetArchitecture();
1260 lldb::ModuleSP IRExecutionUnit::GetJITModule() {
1261 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1262 Target *target = exe_ctx.GetTargetPtr();
1266 auto Delegate = std::static_pointer_cast<lldb_private::ObjectFileJITDelegate>(
1267 shared_from_this());
1269 lldb::ModuleSP jit_module_sp =
1270 lldb_private::Module::CreateModuleFromObjectFile<ObjectFileJIT>(Delegate);
1274 bool changed = false;
1275 jit_module_sp->SetLoadAddress(*target, 0, true, changed);
1276 return jit_module_sp;