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 "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",
141 LLDB_LOGF(log, "Function's code range is [0x%" PRIx64 "+0x%" PRIx64 "]",
142 func_range.first, func_range.second);
144 Target *target = exe_ctx.GetTargetPtr();
146 ret.SetErrorToGenericError();
147 ret.SetErrorString("Couldn't find the target");
151 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second, 0));
153 Process *process = exe_ctx.GetProcessPtr();
155 process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(),
156 buffer_sp->GetByteSize(), err);
158 if (!err.Success()) {
159 ret.SetErrorToGenericError();
160 ret.SetErrorStringWithFormat("Couldn't read from process: %s",
161 err.AsCString("unknown error"));
165 ArchSpec arch(target->GetArchitecture());
167 const char *plugin_name = nullptr;
168 const char *flavor_string = nullptr;
169 lldb::DisassemblerSP disassembler_sp =
170 Disassembler::FindPlugin(arch, flavor_string, plugin_name);
172 if (!disassembler_sp) {
173 ret.SetErrorToGenericError();
174 ret.SetErrorStringWithFormat(
175 "Unable to find disassembler plug-in for %s architecture.",
176 arch.GetArchitectureName());
181 ret.SetErrorToGenericError();
182 ret.SetErrorString("Couldn't find the process");
186 DataExtractor extractor(buffer_sp, process->GetByteOrder(),
187 target->GetArchitecture().GetAddressByteSize());
190 LLDB_LOGF(log, "Function data has contents:");
191 extractor.PutToLog(log, 0, extractor.GetByteSize(), func_remote_addr, 16,
192 DataExtractor::TypeUInt8);
195 disassembler_sp->DecodeInstructions(Address(func_remote_addr), extractor, 0,
196 UINT32_MAX, false, false);
198 InstructionList &instruction_list = disassembler_sp->GetInstructionList();
199 instruction_list.Dump(&stream, true, true, &exe_ctx);
203 static void ReportInlineAsmError(const llvm::SMDiagnostic &diagnostic,
204 void *Context, unsigned LocCookie) {
205 Status *err = static_cast<Status *>(Context);
207 if (err && err->Success()) {
208 err->SetErrorToGenericError();
209 err->SetErrorStringWithFormat("Inline assembly error: %s",
210 diagnostic.getMessage().str().c_str());
214 void IRExecutionUnit::ReportSymbolLookupError(ConstString name) {
215 m_failed_lookups.push_back(name);
218 void IRExecutionUnit::GetRunnableInfo(Status &error, lldb::addr_t &func_addr,
219 lldb::addr_t &func_end) {
220 lldb::ProcessSP process_sp(GetProcessWP().lock());
222 static std::recursive_mutex s_runnable_info_mutex;
224 func_addr = LLDB_INVALID_ADDRESS;
225 func_end = LLDB_INVALID_ADDRESS;
228 error.SetErrorToGenericError();
229 error.SetErrorString("Couldn't write the JIT compiled code into the "
230 "process because the process is invalid");
235 func_addr = m_function_load_addr;
236 func_end = m_function_end_load_addr;
241 std::lock_guard<std::recursive_mutex> guard(s_runnable_info_mutex);
245 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
247 std::string error_string;
251 llvm::raw_string_ostream oss(s);
253 m_module->print(oss, nullptr);
257 LLDB_LOGF(log, "Module being sent to JIT: \n%s", s.c_str());
260 m_module_up->getContext().setInlineAsmDiagnosticHandler(ReportInlineAsmError,
263 llvm::EngineBuilder builder(std::move(m_module_up));
264 llvm::Triple triple(m_module->getTargetTriple());
266 builder.setEngineKind(llvm::EngineKind::JIT)
267 .setErrorStr(&error_string)
268 .setRelocationModel(triple.isOSBinFormatMachO()
270 : llvm::Reloc::Static)
271 .setMCJITMemoryManager(
272 std::unique_ptr<MemoryManager>(new MemoryManager(*this)))
273 .setOptLevel(llvm::CodeGenOpt::Less);
275 llvm::StringRef mArch;
276 llvm::StringRef mCPU;
277 llvm::SmallVector<std::string, 0> mAttrs;
279 for (std::string &feature : m_cpu_features)
280 mAttrs.push_back(feature);
282 llvm::TargetMachine *target_machine =
283 builder.selectTarget(triple, mArch, mCPU, mAttrs);
285 m_execution_engine_up.reset(builder.create(target_machine));
287 if (!m_execution_engine_up) {
288 error.SetErrorToGenericError();
289 error.SetErrorStringWithFormat("Couldn't JIT the function: %s",
290 error_string.c_str());
295 (m_execution_engine_up->getDataLayout().getGlobalPrefix() == '_');
297 class ObjectDumper : public llvm::ObjectCache {
299 void notifyObjectCompiled(const llvm::Module *module,
300 llvm::MemoryBufferRef object) override {
302 llvm::SmallVector<char, 256> result_path;
303 std::string object_name_model =
304 "jit-object-" + module->getModuleIdentifier() + "-%%%.o";
305 (void)llvm::sys::fs::createUniqueFile(object_name_model, fd, result_path);
306 llvm::raw_fd_ostream fds(fd, true);
307 fds.write(object.getBufferStart(), object.getBufferSize());
310 std::unique_ptr<llvm::MemoryBuffer>
311 getObject(const llvm::Module *module) override {
312 // Return nothing - we're just abusing the object-cache mechanism to dump
318 if (process_sp->GetTarget().GetEnableSaveObjects()) {
319 m_object_cache_up = std::make_unique<ObjectDumper>();
320 m_execution_engine_up->setObjectCache(m_object_cache_up.get());
323 // Make sure we see all sections, including ones that don't have
325 m_execution_engine_up->setProcessAllSections(true);
327 m_execution_engine_up->DisableLazyCompilation();
329 for (llvm::Function &function : *m_module) {
330 if (function.isDeclaration() || function.hasPrivateLinkage())
333 const bool external =
334 function.hasExternalLinkage() || function.hasLinkOnceODRLinkage();
336 void *fun_ptr = m_execution_engine_up->getPointerToFunction(&function);
338 if (!error.Success()) {
339 // We got an error through our callback!
344 error.SetErrorToGenericError();
345 error.SetErrorStringWithFormat(
346 "'%s' was in the JITted module but wasn't lowered",
347 function.getName().str().c_str());
350 m_jitted_functions.push_back(JittedFunction(
351 function.getName().str().c_str(), external, reinterpret_cast<uintptr_t>(fun_ptr)));
354 CommitAllocations(process_sp);
355 ReportAllocations(*m_execution_engine_up);
357 // We have to do this after calling ReportAllocations because for the MCJIT,
358 // getGlobalValueAddress will cause the JIT to perform all relocations. That
359 // can only be done once, and has to happen after we do the remapping from
360 // local -> remote. That means we don't know the local address of the
361 // Variables, but we don't need that for anything, so that's okay.
363 std::function<void(llvm::GlobalValue &)> RegisterOneValue = [this](
364 llvm::GlobalValue &val) {
365 if (val.hasExternalLinkage() && !val.isDeclaration()) {
366 uint64_t var_ptr_addr =
367 m_execution_engine_up->getGlobalValueAddress(val.getName().str());
369 lldb::addr_t remote_addr = GetRemoteAddressForLocal(var_ptr_addr);
371 // This is a really unfortunae API that sometimes returns local addresses
372 // and sometimes returns remote addresses, based on whether the variable
373 // was relocated during ReportAllocations or not.
375 if (remote_addr == LLDB_INVALID_ADDRESS) {
376 remote_addr = var_ptr_addr;
379 if (var_ptr_addr != 0)
380 m_jitted_global_variables.push_back(JittedGlobalVariable(
381 val.getName().str().c_str(), LLDB_INVALID_ADDRESS, remote_addr));
385 for (llvm::GlobalVariable &global_var : m_module->getGlobalList()) {
386 RegisterOneValue(global_var);
389 for (llvm::GlobalAlias &global_alias : m_module->getAliasList()) {
390 RegisterOneValue(global_alias);
393 WriteData(process_sp);
395 if (m_failed_lookups.size()) {
398 ss.PutCString("Couldn't lookup symbols:\n");
400 bool emitNewLine = false;
402 for (ConstString failed_lookup : m_failed_lookups) {
407 ss.PutCString(Mangled(failed_lookup)
408 .GetDemangledName(lldb::eLanguageTypeObjC_plus_plus)
412 m_failed_lookups.clear();
414 error.SetErrorString(ss.GetString());
419 m_function_load_addr = LLDB_INVALID_ADDRESS;
420 m_function_end_load_addr = LLDB_INVALID_ADDRESS;
422 for (JittedFunction &jitted_function : m_jitted_functions) {
423 jitted_function.m_remote_addr =
424 GetRemoteAddressForLocal(jitted_function.m_local_addr);
426 if (!m_name.IsEmpty() && jitted_function.m_name == m_name) {
427 AddrRange func_range =
428 GetRemoteRangeForLocal(jitted_function.m_local_addr);
429 m_function_end_load_addr = func_range.first + func_range.second;
430 m_function_load_addr = jitted_function.m_remote_addr;
435 LLDB_LOGF(log, "Code can be run in the target.");
437 StreamString disassembly_stream;
439 Status err = DisassembleFunction(disassembly_stream, process_sp);
441 if (!err.Success()) {
442 LLDB_LOGF(log, "Couldn't disassemble function : %s",
443 err.AsCString("unknown error"));
445 LLDB_LOGF(log, "Function disassembly:\n%s", disassembly_stream.GetData());
448 LLDB_LOGF(log, "Sections: ");
449 for (AllocationRecord &record : m_records) {
450 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
453 DataBufferHeap my_buffer(record.m_size, 0);
455 ReadMemory(my_buffer.GetBytes(), record.m_process_address,
459 DataExtractor my_extractor(my_buffer.GetBytes(),
460 my_buffer.GetByteSize(),
461 lldb::eByteOrderBig, 8);
462 my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(),
463 record.m_process_address, 16,
464 DataExtractor::TypeUInt8);
469 DataExtractor my_extractor((const void *)record.m_host_address,
470 record.m_size, lldb::eByteOrderBig, 8);
471 my_extractor.PutToLog(log, 0, record.m_size, record.m_host_address, 16,
472 DataExtractor::TypeUInt8);
477 func_addr = m_function_load_addr;
478 func_end = m_function_end_load_addr;
483 IRExecutionUnit::~IRExecutionUnit() {
485 m_execution_engine_up.reset();
486 m_context_up.reset();
489 IRExecutionUnit::MemoryManager::MemoryManager(IRExecutionUnit &parent)
490 : m_default_mm_up(new llvm::SectionMemoryManager()), m_parent(parent) {}
492 IRExecutionUnit::MemoryManager::~MemoryManager() {}
494 lldb::SectionType IRExecutionUnit::GetSectionTypeFromSectionName(
495 const llvm::StringRef &name, IRExecutionUnit::AllocationKind alloc_kind) {
496 lldb::SectionType sect_type = lldb::eSectionTypeCode;
497 switch (alloc_kind) {
498 case AllocationKind::Stub:
499 sect_type = lldb::eSectionTypeCode;
501 case AllocationKind::Code:
502 sect_type = lldb::eSectionTypeCode;
504 case AllocationKind::Data:
505 sect_type = lldb::eSectionTypeData;
507 case AllocationKind::Global:
508 sect_type = lldb::eSectionTypeData;
510 case AllocationKind::Bytes:
511 sect_type = lldb::eSectionTypeOther;
516 if (name.equals("__text") || name.equals(".text"))
517 sect_type = lldb::eSectionTypeCode;
518 else if (name.equals("__data") || name.equals(".data"))
519 sect_type = lldb::eSectionTypeCode;
520 else if (name.startswith("__debug_") || name.startswith(".debug_")) {
521 const uint32_t name_idx = name[0] == '_' ? 8 : 7;
522 llvm::StringRef dwarf_name(name.substr(name_idx));
523 switch (dwarf_name[0]) {
525 if (dwarf_name.equals("abbrev"))
526 sect_type = lldb::eSectionTypeDWARFDebugAbbrev;
527 else if (dwarf_name.equals("aranges"))
528 sect_type = lldb::eSectionTypeDWARFDebugAranges;
529 else if (dwarf_name.equals("addr"))
530 sect_type = lldb::eSectionTypeDWARFDebugAddr;
534 if (dwarf_name.equals("frame"))
535 sect_type = lldb::eSectionTypeDWARFDebugFrame;
539 if (dwarf_name.equals("info"))
540 sect_type = lldb::eSectionTypeDWARFDebugInfo;
544 if (dwarf_name.equals("line"))
545 sect_type = lldb::eSectionTypeDWARFDebugLine;
546 else if (dwarf_name.equals("loc"))
547 sect_type = lldb::eSectionTypeDWARFDebugLoc;
548 else if (dwarf_name.equals("loclists"))
549 sect_type = lldb::eSectionTypeDWARFDebugLocLists;
553 if (dwarf_name.equals("macinfo"))
554 sect_type = lldb::eSectionTypeDWARFDebugMacInfo;
558 if (dwarf_name.equals("pubnames"))
559 sect_type = lldb::eSectionTypeDWARFDebugPubNames;
560 else if (dwarf_name.equals("pubtypes"))
561 sect_type = lldb::eSectionTypeDWARFDebugPubTypes;
565 if (dwarf_name.equals("str"))
566 sect_type = lldb::eSectionTypeDWARFDebugStr;
567 else if (dwarf_name.equals("str_offsets"))
568 sect_type = lldb::eSectionTypeDWARFDebugStrOffsets;
572 if (dwarf_name.equals("ranges"))
573 sect_type = lldb::eSectionTypeDWARFDebugRanges;
579 } else if (name.startswith("__apple_") || name.startswith(".apple_"))
580 sect_type = lldb::eSectionTypeInvalid;
581 else if (name.equals("__objc_imageinfo"))
582 sect_type = lldb::eSectionTypeOther;
587 uint8_t *IRExecutionUnit::MemoryManager::allocateCodeSection(
588 uintptr_t Size, unsigned Alignment, unsigned SectionID,
589 llvm::StringRef SectionName) {
590 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
592 uint8_t *return_value = m_default_mm_up->allocateCodeSection(
593 Size, Alignment, SectionID, SectionName);
595 m_parent.m_records.push_back(AllocationRecord(
596 (uintptr_t)return_value,
597 lldb::ePermissionsReadable | lldb::ePermissionsExecutable,
598 GetSectionTypeFromSectionName(SectionName, AllocationKind::Code), Size,
599 Alignment, SectionID, SectionName.str().c_str()));
602 "IRExecutionUnit::allocateCodeSection(Size=0x%" PRIx64
603 ", Alignment=%u, SectionID=%u) = %p",
604 (uint64_t)Size, Alignment, SectionID, (void *)return_value);
606 if (m_parent.m_reported_allocations) {
608 lldb::ProcessSP process_sp =
609 m_parent.GetBestExecutionContextScope()->CalculateProcess();
611 m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back());
617 uint8_t *IRExecutionUnit::MemoryManager::allocateDataSection(
618 uintptr_t Size, unsigned Alignment, unsigned SectionID,
619 llvm::StringRef SectionName, bool IsReadOnly) {
620 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
622 uint8_t *return_value = m_default_mm_up->allocateDataSection(
623 Size, Alignment, SectionID, SectionName, IsReadOnly);
625 uint32_t permissions = lldb::ePermissionsReadable;
627 permissions |= lldb::ePermissionsWritable;
628 m_parent.m_records.push_back(AllocationRecord(
629 (uintptr_t)return_value, permissions,
630 GetSectionTypeFromSectionName(SectionName, AllocationKind::Data), Size,
631 Alignment, SectionID, SectionName.str().c_str()));
633 "IRExecutionUnit::allocateDataSection(Size=0x%" PRIx64
634 ", Alignment=%u, SectionID=%u) = %p",
635 (uint64_t)Size, Alignment, SectionID, (void *)return_value);
637 if (m_parent.m_reported_allocations) {
639 lldb::ProcessSP process_sp =
640 m_parent.GetBestExecutionContextScope()->CalculateProcess();
642 m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back());
649 FindBestAlternateMangledName(ConstString demangled,
650 const lldb::LanguageType &lang_type,
651 const SymbolContext &sym_ctx) {
652 CPlusPlusLanguage::MethodName cpp_name(demangled);
653 std::string scope_qualified_name = cpp_name.GetScopeQualifiedName();
655 if (!scope_qualified_name.size())
656 return ConstString();
658 if (!sym_ctx.module_sp)
659 return ConstString();
661 lldb_private::SymbolFile *sym_file = sym_ctx.module_sp->GetSymbolFile();
663 return ConstString();
665 std::vector<ConstString> alternates;
666 sym_file->GetMangledNamesForFunction(scope_qualified_name, alternates);
668 std::vector<ConstString> param_and_qual_matches;
669 std::vector<ConstString> param_matches;
670 for (size_t i = 0; i < alternates.size(); i++) {
671 ConstString alternate_mangled_name = alternates[i];
672 Mangled mangled(alternate_mangled_name);
673 ConstString demangled = mangled.GetDemangledName(lang_type);
675 CPlusPlusLanguage::MethodName alternate_cpp_name(demangled);
676 if (!cpp_name.IsValid())
679 if (alternate_cpp_name.GetArguments() == cpp_name.GetArguments()) {
680 if (alternate_cpp_name.GetQualifiers() == cpp_name.GetQualifiers())
681 param_and_qual_matches.push_back(alternate_mangled_name);
683 param_matches.push_back(alternate_mangled_name);
687 if (param_and_qual_matches.size())
688 return param_and_qual_matches[0]; // It is assumed that there will be only
690 else if (param_matches.size())
691 return param_matches[0]; // Return one of them as a best match
693 return ConstString();
696 struct IRExecutionUnit::SearchSpec {
698 lldb::FunctionNameType mask;
700 SearchSpec(ConstString n,
701 lldb::FunctionNameType m = lldb::eFunctionNameTypeFull)
702 : name(n), mask(m) {}
705 void IRExecutionUnit::CollectCandidateCNames(
706 std::vector<IRExecutionUnit::SearchSpec> &C_specs,
708 if (m_strip_underscore && name.AsCString()[0] == '_')
709 C_specs.insert(C_specs.begin(), ConstString(&name.AsCString()[1]));
710 C_specs.push_back(SearchSpec(name));
713 void IRExecutionUnit::CollectCandidateCPlusPlusNames(
714 std::vector<IRExecutionUnit::SearchSpec> &CPP_specs,
715 const std::vector<SearchSpec> &C_specs, const SymbolContext &sc) {
716 for (const SearchSpec &C_spec : C_specs) {
717 ConstString name = C_spec.name;
719 if (CPlusPlusLanguage::IsCPPMangledName(name.GetCString())) {
720 Mangled mangled(name);
721 ConstString demangled =
722 mangled.GetDemangledName(lldb::eLanguageTypeC_plus_plus);
725 ConstString best_alternate_mangled_name = FindBestAlternateMangledName(
726 demangled, lldb::eLanguageTypeC_plus_plus, sc);
728 if (best_alternate_mangled_name) {
729 CPP_specs.push_back(best_alternate_mangled_name);
734 std::set<ConstString> alternates;
735 CPlusPlusLanguage::FindAlternateFunctionManglings(name, alternates);
736 CPP_specs.insert(CPP_specs.end(), alternates.begin(), alternates.end());
740 void IRExecutionUnit::CollectFallbackNames(
741 std::vector<SearchSpec> &fallback_specs,
742 const std::vector<SearchSpec> &C_specs) {
743 // As a last-ditch fallback, try the base name for C++ names. It's terrible,
744 // but the DWARF doesn't always encode "extern C" correctly.
746 for (const SearchSpec &C_spec : C_specs) {
747 ConstString name = C_spec.name;
749 if (CPlusPlusLanguage::IsCPPMangledName(name.GetCString())) {
750 Mangled mangled_name(name);
751 ConstString demangled_name =
752 mangled_name.GetDemangledName(lldb::eLanguageTypeC_plus_plus);
753 if (!demangled_name.IsEmpty()) {
754 const char *demangled_cstr = demangled_name.AsCString();
755 const char *lparen_loc = strchr(demangled_cstr, '(');
757 llvm::StringRef base_name(demangled_cstr,
758 lparen_loc - demangled_cstr);
759 fallback_specs.push_back(ConstString(base_name));
766 lldb::addr_t IRExecutionUnit::FindInSymbols(
767 const std::vector<IRExecutionUnit::SearchSpec> &specs,
768 const lldb_private::SymbolContext &sc,
769 bool &symbol_was_missing_weak) {
770 symbol_was_missing_weak = false;
771 Target *target = sc.target_sp.get();
774 // we shouldn't be doing any symbol lookup at all without a target
775 return LLDB_INVALID_ADDRESS;
778 for (const SearchSpec &spec : specs) {
779 SymbolContextList sc_list;
781 lldb::addr_t best_internal_load_address = LLDB_INVALID_ADDRESS;
783 std::function<bool(lldb::addr_t &, SymbolContextList &,
784 const lldb_private::SymbolContext &)>
785 get_external_load_address = [&best_internal_load_address, target,
786 &symbol_was_missing_weak](
787 lldb::addr_t &load_address, SymbolContextList &sc_list,
788 const lldb_private::SymbolContext &sc) -> lldb::addr_t {
789 load_address = LLDB_INVALID_ADDRESS;
791 if (sc_list.GetSize() == 0)
794 // missing_weak_symbol will be true only if we found only weak undefined
795 // references to this symbol.
796 symbol_was_missing_weak = true;
797 for (auto candidate_sc : sc_list.SymbolContexts()) {
798 // Only symbols can be weak undefined:
799 if (!candidate_sc.symbol)
800 symbol_was_missing_weak = false;
801 else if (candidate_sc.symbol->GetType() != lldb::eSymbolTypeUndefined
802 || !candidate_sc.symbol->IsWeak())
803 symbol_was_missing_weak = false;
805 const bool is_external =
806 (candidate_sc.function) ||
807 (candidate_sc.symbol && candidate_sc.symbol->IsExternal());
808 if (candidate_sc.symbol) {
809 load_address = candidate_sc.symbol->ResolveCallableAddress(*target);
811 if (load_address == LLDB_INVALID_ADDRESS) {
812 if (target->GetProcessSP())
814 candidate_sc.symbol->GetAddress().GetLoadAddress(target);
816 load_address = candidate_sc.symbol->GetAddress().GetFileAddress();
820 if (load_address == LLDB_INVALID_ADDRESS && candidate_sc.function) {
821 if (target->GetProcessSP())
822 load_address = candidate_sc.function->GetAddressRange()
824 .GetLoadAddress(target);
826 load_address = candidate_sc.function->GetAddressRange()
831 if (load_address != LLDB_INVALID_ADDRESS) {
834 } else if (best_internal_load_address == LLDB_INVALID_ADDRESS) {
835 best_internal_load_address = load_address;
836 load_address = LLDB_INVALID_ADDRESS;
841 // You test the address of a weak symbol against NULL to see if it is
842 // present. So we should return 0 for a missing weak symbol.
843 if (symbol_was_missing_weak) {
852 sc.module_sp->FindFunctions(spec.name, nullptr, spec.mask,
853 true, // include_symbols
854 false, // include_inlines
858 lldb::addr_t load_address = LLDB_INVALID_ADDRESS;
860 if (get_external_load_address(load_address, sc_list, sc)) {
866 if (sc_list.GetSize() == 0 && sc.target_sp) {
867 sc.target_sp->GetImages().FindFunctions(spec.name, spec.mask,
868 true, // include_symbols
869 false, // include_inlines
873 if (get_external_load_address(load_address, sc_list, sc)) {
879 if (sc_list.GetSize() == 0 && sc.target_sp) {
880 sc.target_sp->GetImages().FindSymbolsWithNameAndType(
881 spec.name, lldb::eSymbolTypeAny, sc_list);
884 if (get_external_load_address(load_address, sc_list, sc)) {
887 // if there are any searches we try after this, add an sc_list.Clear() in
888 // an "else" clause here
890 if (best_internal_load_address != LLDB_INVALID_ADDRESS) {
891 return best_internal_load_address;
895 return LLDB_INVALID_ADDRESS;
899 IRExecutionUnit::FindInRuntimes(const std::vector<SearchSpec> &specs,
900 const lldb_private::SymbolContext &sc) {
901 lldb::TargetSP target_sp = sc.target_sp;
904 return LLDB_INVALID_ADDRESS;
907 lldb::ProcessSP process_sp = sc.target_sp->GetProcessSP();
910 return LLDB_INVALID_ADDRESS;
913 for (const SearchSpec &spec : specs) {
914 for (LanguageRuntime *runtime : process_sp->GetLanguageRuntimes()) {
915 lldb::addr_t symbol_load_addr = runtime->LookupRuntimeSymbol(spec.name);
917 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
918 return symbol_load_addr;
922 return LLDB_INVALID_ADDRESS;
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;
930 for (const SearchSpec &spec : specs) {
931 lldb::addr_t symbol_load_addr = target_sp->GetPersistentSymbol(spec.name);
933 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
934 return symbol_load_addr;
937 return LLDB_INVALID_ADDRESS;
941 IRExecutionUnit::FindSymbol(lldb_private::ConstString name, bool &missing_weak) {
942 std::vector<SearchSpec> candidate_C_names;
943 std::vector<SearchSpec> candidate_CPlusPlus_names;
945 CollectCandidateCNames(candidate_C_names, name);
947 lldb::addr_t ret = FindInSymbols(candidate_C_names, m_sym_ctx, missing_weak);
948 if (ret != LLDB_INVALID_ADDRESS)
951 // If we find the symbol in runtimes or user defined symbols it can't be
952 // a missing weak symbol.
953 missing_weak = false;
954 ret = FindInRuntimes(candidate_C_names, m_sym_ctx);
955 if (ret != LLDB_INVALID_ADDRESS)
958 ret = FindInUserDefinedSymbols(candidate_C_names, m_sym_ctx);
959 if (ret != LLDB_INVALID_ADDRESS)
962 CollectCandidateCPlusPlusNames(candidate_CPlusPlus_names, candidate_C_names,
964 ret = FindInSymbols(candidate_CPlusPlus_names, m_sym_ctx, missing_weak);
965 if (ret != LLDB_INVALID_ADDRESS)
968 std::vector<SearchSpec> candidate_fallback_names;
970 CollectFallbackNames(candidate_fallback_names, candidate_C_names);
971 ret = FindInSymbols(candidate_fallback_names, m_sym_ctx, missing_weak);
976 void IRExecutionUnit::GetStaticInitializers(
977 std::vector<lldb::addr_t> &static_initializers) {
978 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
980 llvm::GlobalVariable *global_ctors =
981 m_module->getNamedGlobal("llvm.global_ctors");
983 LLDB_LOG(log, "Couldn't find llvm.global_ctors.");
987 llvm::dyn_cast<llvm::ConstantArray>(global_ctors->getInitializer());
989 LLDB_LOG(log, "llvm.global_ctors not a ConstantArray.");
993 for (llvm::Use &ctor_use : ctor_array->operands()) {
994 auto *ctor_struct = llvm::dyn_cast<llvm::ConstantStruct>(ctor_use);
997 // this is standardized
998 lldbassert(ctor_struct->getNumOperands() == 3);
999 auto *ctor_function =
1000 llvm::dyn_cast<llvm::Function>(ctor_struct->getOperand(1));
1001 if (!ctor_function) {
1002 LLDB_LOG(log, "global_ctor doesn't contain an llvm::Function");
1006 ConstString ctor_function_name(ctor_function->getName().str());
1007 LLDB_LOG(log, "Looking for callable jitted function with name {0}.",
1008 ctor_function_name);
1010 for (JittedFunction &jitted_function : m_jitted_functions) {
1011 if (ctor_function_name != jitted_function.m_name)
1013 if (jitted_function.m_remote_addr == LLDB_INVALID_ADDRESS) {
1014 LLDB_LOG(log, "Found jitted function with invalid address.");
1017 static_initializers.push_back(jitted_function.m_remote_addr);
1018 LLDB_LOG(log, "Calling function at address {0:x}.",
1019 jitted_function.m_remote_addr);
1026 IRExecutionUnit::MemoryManager::findSymbol(const std::string &Name) {
1027 bool missing_weak = false;
1028 uint64_t addr = GetSymbolAddressAndPresence(Name, missing_weak);
1029 // This is a weak symbol:
1031 return llvm::JITSymbol(addr,
1032 llvm::JITSymbolFlags::Exported | llvm::JITSymbolFlags::Weak);
1034 return llvm::JITSymbol(addr, llvm::JITSymbolFlags::Exported);
1038 IRExecutionUnit::MemoryManager::getSymbolAddress(const std::string &Name) {
1039 bool missing_weak = false;
1040 return GetSymbolAddressAndPresence(Name, missing_weak);
1044 IRExecutionUnit::MemoryManager::GetSymbolAddressAndPresence(
1045 const std::string &Name, bool &missing_weak) {
1046 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1048 ConstString name_cs(Name.c_str());
1050 lldb::addr_t ret = m_parent.FindSymbol(name_cs, missing_weak);
1052 if (ret == LLDB_INVALID_ADDRESS) {
1054 "IRExecutionUnit::getSymbolAddress(Name=\"%s\") = <not found>",
1057 m_parent.ReportSymbolLookupError(name_cs);
1060 LLDB_LOGF(log, "IRExecutionUnit::getSymbolAddress(Name=\"%s\") = %" PRIx64,
1066 void *IRExecutionUnit::MemoryManager::getPointerToNamedFunction(
1067 const std::string &Name, bool AbortOnFailure) {
1068 return (void *)getSymbolAddress(Name);
1072 IRExecutionUnit::GetRemoteAddressForLocal(lldb::addr_t local_address) {
1073 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1075 for (AllocationRecord &record : m_records) {
1076 if (local_address >= record.m_host_address &&
1077 local_address < record.m_host_address + record.m_size) {
1078 if (record.m_process_address == LLDB_INVALID_ADDRESS)
1079 return LLDB_INVALID_ADDRESS;
1082 record.m_process_address + (local_address - record.m_host_address);
1085 "IRExecutionUnit::GetRemoteAddressForLocal() found 0x%" PRIx64
1086 " in [0x%" PRIx64 "..0x%" PRIx64 "], and returned 0x%" PRIx64
1087 " from [0x%" PRIx64 "..0x%" PRIx64 "].",
1088 local_address, (uint64_t)record.m_host_address,
1089 (uint64_t)record.m_host_address + (uint64_t)record.m_size, ret,
1090 record.m_process_address,
1091 record.m_process_address + record.m_size);
1097 return LLDB_INVALID_ADDRESS;
1100 IRExecutionUnit::AddrRange
1101 IRExecutionUnit::GetRemoteRangeForLocal(lldb::addr_t local_address) {
1102 for (AllocationRecord &record : m_records) {
1103 if (local_address >= record.m_host_address &&
1104 local_address < record.m_host_address + record.m_size) {
1105 if (record.m_process_address == LLDB_INVALID_ADDRESS)
1106 return AddrRange(0, 0);
1108 return AddrRange(record.m_process_address, record.m_size);
1112 return AddrRange(0, 0);
1115 bool IRExecutionUnit::CommitOneAllocation(lldb::ProcessSP &process_sp,
1117 AllocationRecord &record) {
1118 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
1122 switch (record.m_sect_type) {
1123 case lldb::eSectionTypeInvalid:
1124 case lldb::eSectionTypeDWARFDebugAbbrev:
1125 case lldb::eSectionTypeDWARFDebugAddr:
1126 case lldb::eSectionTypeDWARFDebugAranges:
1127 case lldb::eSectionTypeDWARFDebugCuIndex:
1128 case lldb::eSectionTypeDWARFDebugFrame:
1129 case lldb::eSectionTypeDWARFDebugInfo:
1130 case lldb::eSectionTypeDWARFDebugLine:
1131 case lldb::eSectionTypeDWARFDebugLoc:
1132 case lldb::eSectionTypeDWARFDebugLocLists:
1133 case lldb::eSectionTypeDWARFDebugMacInfo:
1134 case lldb::eSectionTypeDWARFDebugPubNames:
1135 case lldb::eSectionTypeDWARFDebugPubTypes:
1136 case lldb::eSectionTypeDWARFDebugRanges:
1137 case lldb::eSectionTypeDWARFDebugStr:
1138 case lldb::eSectionTypeDWARFDebugStrOffsets:
1139 case lldb::eSectionTypeDWARFAppleNames:
1140 case lldb::eSectionTypeDWARFAppleTypes:
1141 case lldb::eSectionTypeDWARFAppleNamespaces:
1142 case lldb::eSectionTypeDWARFAppleObjC:
1143 case lldb::eSectionTypeDWARFGNUDebugAltLink:
1147 const bool zero_memory = false;
1148 record.m_process_address =
1149 Malloc(record.m_size, record.m_alignment, record.m_permissions,
1150 eAllocationPolicyProcessOnly, zero_memory, error);
1154 return error.Success();
1157 bool IRExecutionUnit::CommitAllocations(lldb::ProcessSP &process_sp) {
1160 lldb_private::Status err;
1162 for (AllocationRecord &record : m_records) {
1163 ret = CommitOneAllocation(process_sp, err, record);
1171 for (AllocationRecord &record : m_records) {
1172 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
1173 Free(record.m_process_address, err);
1174 record.m_process_address = LLDB_INVALID_ADDRESS;
1182 void IRExecutionUnit::ReportAllocations(llvm::ExecutionEngine &engine) {
1183 m_reported_allocations = true;
1185 for (AllocationRecord &record : m_records) {
1186 if (record.m_process_address == LLDB_INVALID_ADDRESS)
1189 if (record.m_section_id == eSectionIDInvalid)
1192 engine.mapSectionAddress((void *)record.m_host_address,
1193 record.m_process_address);
1196 // Trigger re-application of relocations.
1197 engine.finalizeObject();
1200 bool IRExecutionUnit::WriteData(lldb::ProcessSP &process_sp) {
1201 bool wrote_something = false;
1202 for (AllocationRecord &record : m_records) {
1203 if (record.m_process_address != LLDB_INVALID_ADDRESS) {
1204 lldb_private::Status err;
1205 WriteMemory(record.m_process_address, (uint8_t *)record.m_host_address,
1206 record.m_size, err);
1208 wrote_something = true;
1211 return wrote_something;
1214 void IRExecutionUnit::AllocationRecord::dump(Log *log) {
1219 "[0x%llx+0x%llx]->0x%llx (alignment %d, section ID %d, name %s)",
1220 (unsigned long long)m_host_address, (unsigned long long)m_size,
1221 (unsigned long long)m_process_address, (unsigned)m_alignment,
1222 (unsigned)m_section_id, m_name.c_str());
1225 lldb::ByteOrder IRExecutionUnit::GetByteOrder() const {
1226 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1227 return exe_ctx.GetByteOrder();
1230 uint32_t IRExecutionUnit::GetAddressByteSize() const {
1231 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1232 return exe_ctx.GetAddressByteSize();
1235 void IRExecutionUnit::PopulateSymtab(lldb_private::ObjectFile *obj_file,
1236 lldb_private::Symtab &symtab) {
1237 // No symbols yet...
1240 void IRExecutionUnit::PopulateSectionList(
1241 lldb_private::ObjectFile *obj_file,
1242 lldb_private::SectionList §ion_list) {
1243 for (AllocationRecord &record : m_records) {
1244 if (record.m_size > 0) {
1245 lldb::SectionSP section_sp(new lldb_private::Section(
1246 obj_file->GetModule(), obj_file, record.m_section_id,
1247 ConstString(record.m_name), record.m_sect_type,
1248 record.m_process_address, record.m_size,
1249 record.m_host_address, // file_offset (which is the host address for
1251 record.m_size, // file_size
1253 record.m_permissions)); // flags
1254 section_list.AddSection(section_sp);
1259 ArchSpec IRExecutionUnit::GetArchitecture() {
1260 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1261 if(Target *target = exe_ctx.GetTargetPtr())
1262 return target->GetArchitecture();
1266 lldb::ModuleSP IRExecutionUnit::GetJITModule() {
1267 ExecutionContext exe_ctx(GetBestExecutionContextScope());
1268 Target *target = exe_ctx.GetTargetPtr();
1272 auto Delegate = std::static_pointer_cast<lldb_private::ObjectFileJITDelegate>(
1273 shared_from_this());
1275 lldb::ModuleSP jit_module_sp =
1276 lldb_private::Module::CreateModuleFromObjectFile<ObjectFileJIT>(Delegate);
1280 bool changed = false;
1281 jit_module_sp->SetLoadAddress(*target, 0, true, changed);
1282 return jit_module_sp;