Path: blob/main/contrib/llvm-project/lldb/source/Expression/IRExecutionUnit.cpp
39587 views
//===-- IRExecutionUnit.cpp -----------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "llvm/ExecutionEngine/ExecutionEngine.h"9#include "llvm/ExecutionEngine/ObjectCache.h"10#include "llvm/IR/Constants.h"11#include "llvm/IR/DiagnosticHandler.h"12#include "llvm/IR/DiagnosticInfo.h"13#include "llvm/IR/LLVMContext.h"14#include "llvm/IR/Module.h"15#include "llvm/Support/SourceMgr.h"16#include "llvm/Support/raw_ostream.h"1718#include "lldb/Core/Debugger.h"19#include "lldb/Core/Disassembler.h"20#include "lldb/Core/Module.h"21#include "lldb/Core/Section.h"22#include "lldb/Expression/IRExecutionUnit.h"23#include "lldb/Expression/ObjectFileJIT.h"24#include "lldb/Host/HostInfo.h"25#include "lldb/Symbol/CompileUnit.h"26#include "lldb/Symbol/SymbolContext.h"27#include "lldb/Symbol/SymbolFile.h"28#include "lldb/Symbol/SymbolVendor.h"29#include "lldb/Target/ExecutionContext.h"30#include "lldb/Target/Language.h"31#include "lldb/Target/LanguageRuntime.h"32#include "lldb/Target/Target.h"33#include "lldb/Utility/DataBufferHeap.h"34#include "lldb/Utility/DataExtractor.h"35#include "lldb/Utility/LLDBAssert.h"36#include "lldb/Utility/LLDBLog.h"37#include "lldb/Utility/Log.h"3839#include <optional>4041using namespace lldb_private;4243IRExecutionUnit::IRExecutionUnit(std::unique_ptr<llvm::LLVMContext> &context_up,44std::unique_ptr<llvm::Module> &module_up,45ConstString &name,46const lldb::TargetSP &target_sp,47const SymbolContext &sym_ctx,48std::vector<std::string> &cpu_features)49: IRMemoryMap(target_sp), m_context_up(context_up.release()),50m_module_up(module_up.release()), m_module(m_module_up.get()),51m_cpu_features(cpu_features), m_name(name), m_sym_ctx(sym_ctx),52m_did_jit(false), m_function_load_addr(LLDB_INVALID_ADDRESS),53m_function_end_load_addr(LLDB_INVALID_ADDRESS),54m_reported_allocations(false) {}5556lldb::addr_t IRExecutionUnit::WriteNow(const uint8_t *bytes, size_t size,57Status &error) {58const bool zero_memory = false;59lldb::addr_t allocation_process_addr =60Malloc(size, 8, lldb::ePermissionsWritable | lldb::ePermissionsReadable,61eAllocationPolicyMirror, zero_memory, error);6263if (!error.Success())64return LLDB_INVALID_ADDRESS;6566WriteMemory(allocation_process_addr, bytes, size, error);6768if (!error.Success()) {69Status err;70Free(allocation_process_addr, err);7172return LLDB_INVALID_ADDRESS;73}7475if (Log *log = GetLog(LLDBLog::Expressions)) {76DataBufferHeap my_buffer(size, 0);77Status err;78ReadMemory(my_buffer.GetBytes(), allocation_process_addr, size, err);7980if (err.Success()) {81DataExtractor my_extractor(my_buffer.GetBytes(), my_buffer.GetByteSize(),82lldb::eByteOrderBig, 8);83my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(),84allocation_process_addr, 16,85DataExtractor::TypeUInt8);86}87}8889return allocation_process_addr;90}9192void IRExecutionUnit::FreeNow(lldb::addr_t allocation) {93if (allocation == LLDB_INVALID_ADDRESS)94return;9596Status err;9798Free(allocation, err);99}100101Status IRExecutionUnit::DisassembleFunction(Stream &stream,102lldb::ProcessSP &process_wp) {103Log *log = GetLog(LLDBLog::Expressions);104105ExecutionContext exe_ctx(process_wp);106107Status ret;108109ret.Clear();110111lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;112lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;113114for (JittedFunction &function : m_jitted_functions) {115if (function.m_name == m_name) {116func_local_addr = function.m_local_addr;117func_remote_addr = function.m_remote_addr;118}119}120121if (func_local_addr == LLDB_INVALID_ADDRESS) {122ret.SetErrorToGenericError();123ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly",124m_name.AsCString());125return ret;126}127128LLDB_LOGF(log,129"Found function, has local address 0x%" PRIx64130" and remote address 0x%" PRIx64,131(uint64_t)func_local_addr, (uint64_t)func_remote_addr);132133std::pair<lldb::addr_t, lldb::addr_t> func_range;134135func_range = GetRemoteRangeForLocal(func_local_addr);136137if (func_range.first == 0 && func_range.second == 0) {138ret.SetErrorToGenericError();139ret.SetErrorStringWithFormat("Couldn't find code range for function %s",140m_name.AsCString());141return ret;142}143144LLDB_LOGF(log, "Function's code range is [0x%" PRIx64 "+0x%" PRIx64 "]",145func_range.first, func_range.second);146147Target *target = exe_ctx.GetTargetPtr();148if (!target) {149ret.SetErrorToGenericError();150ret.SetErrorString("Couldn't find the target");151return ret;152}153154lldb::WritableDataBufferSP buffer_sp(155new DataBufferHeap(func_range.second, 0));156157Process *process = exe_ctx.GetProcessPtr();158Status err;159process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(),160buffer_sp->GetByteSize(), err);161162if (!err.Success()) {163ret.SetErrorToGenericError();164ret.SetErrorStringWithFormat("Couldn't read from process: %s",165err.AsCString("unknown error"));166return ret;167}168169ArchSpec arch(target->GetArchitecture());170171const char *plugin_name = nullptr;172const char *flavor_string = nullptr;173lldb::DisassemblerSP disassembler_sp =174Disassembler::FindPlugin(arch, flavor_string, plugin_name);175176if (!disassembler_sp) {177ret.SetErrorToGenericError();178ret.SetErrorStringWithFormat(179"Unable to find disassembler plug-in for %s architecture.",180arch.GetArchitectureName());181return ret;182}183184if (!process) {185ret.SetErrorToGenericError();186ret.SetErrorString("Couldn't find the process");187return ret;188}189190DataExtractor extractor(buffer_sp, process->GetByteOrder(),191target->GetArchitecture().GetAddressByteSize());192193if (log) {194LLDB_LOGF(log, "Function data has contents:");195extractor.PutToLog(log, 0, extractor.GetByteSize(), func_remote_addr, 16,196DataExtractor::TypeUInt8);197}198199disassembler_sp->DecodeInstructions(Address(func_remote_addr), extractor, 0,200UINT32_MAX, false, false);201202InstructionList &instruction_list = disassembler_sp->GetInstructionList();203instruction_list.Dump(&stream, true, true, /*show_control_flow_kind=*/false,204&exe_ctx);205206return ret;207}208209namespace {210struct IRExecDiagnosticHandler : public llvm::DiagnosticHandler {211Status *err;212IRExecDiagnosticHandler(Status *err) : err(err) {}213bool handleDiagnostics(const llvm::DiagnosticInfo &DI) override {214if (DI.getSeverity() == llvm::DS_Error) {215const auto &DISM = llvm::cast<llvm::DiagnosticInfoSrcMgr>(DI);216if (err && err->Success()) {217err->SetErrorToGenericError();218err->SetErrorStringWithFormat(219"IRExecution error: %s",220DISM.getSMDiag().getMessage().str().c_str());221}222}223224return true;225}226};227} // namespace228229void IRExecutionUnit::ReportSymbolLookupError(ConstString name) {230m_failed_lookups.push_back(name);231}232233void IRExecutionUnit::GetRunnableInfo(Status &error, lldb::addr_t &func_addr,234lldb::addr_t &func_end) {235lldb::ProcessSP process_sp(GetProcessWP().lock());236237static std::recursive_mutex s_runnable_info_mutex;238239func_addr = LLDB_INVALID_ADDRESS;240func_end = LLDB_INVALID_ADDRESS;241242if (!process_sp) {243error.SetErrorToGenericError();244error.SetErrorString("Couldn't write the JIT compiled code into the "245"process because the process is invalid");246return;247}248249if (m_did_jit) {250func_addr = m_function_load_addr;251func_end = m_function_end_load_addr;252253return;254};255256std::lock_guard<std::recursive_mutex> guard(s_runnable_info_mutex);257258m_did_jit = true;259260Log *log = GetLog(LLDBLog::Expressions);261262std::string error_string;263264if (log) {265std::string s;266llvm::raw_string_ostream oss(s);267268m_module->print(oss, nullptr);269270oss.flush();271272LLDB_LOGF(log, "Module being sent to JIT: \n%s", s.c_str());273}274275m_module_up->getContext().setDiagnosticHandler(276std::make_unique<IRExecDiagnosticHandler>(&error));277278llvm::EngineBuilder builder(std::move(m_module_up));279llvm::Triple triple(m_module->getTargetTriple());280281builder.setEngineKind(llvm::EngineKind::JIT)282.setErrorStr(&error_string)283.setRelocationModel(triple.isOSBinFormatMachO() ? llvm::Reloc::PIC_284: llvm::Reloc::Static)285.setMCJITMemoryManager(std::make_unique<MemoryManager>(*this))286.setOptLevel(llvm::CodeGenOptLevel::Less);287288llvm::StringRef mArch;289llvm::StringRef mCPU;290llvm::SmallVector<std::string, 0> mAttrs;291292for (std::string &feature : m_cpu_features)293mAttrs.push_back(feature);294295llvm::TargetMachine *target_machine =296builder.selectTarget(triple, mArch, mCPU, mAttrs);297298m_execution_engine_up.reset(builder.create(target_machine));299300if (!m_execution_engine_up) {301error.SetErrorToGenericError();302error.SetErrorStringWithFormat("Couldn't JIT the function: %s",303error_string.c_str());304return;305}306307m_strip_underscore =308(m_execution_engine_up->getDataLayout().getGlobalPrefix() == '_');309310class ObjectDumper : public llvm::ObjectCache {311public:312ObjectDumper(FileSpec output_dir) : m_out_dir(output_dir) {}313void notifyObjectCompiled(const llvm::Module *module,314llvm::MemoryBufferRef object) override {315int fd = 0;316llvm::SmallVector<char, 256> result_path;317std::string object_name_model =318"jit-object-" + module->getModuleIdentifier() + "-%%%.o";319FileSpec model_spec320= m_out_dir.CopyByAppendingPathComponent(object_name_model);321std::string model_path = model_spec.GetPath();322323std::error_code result324= llvm::sys::fs::createUniqueFile(model_path, fd, result_path);325if (!result) {326llvm::raw_fd_ostream fds(fd, true);327fds.write(object.getBufferStart(), object.getBufferSize());328}329}330std::unique_ptr<llvm::MemoryBuffer>331getObject(const llvm::Module *module) override {332// Return nothing - we're just abusing the object-cache mechanism to dump333// objects.334return nullptr;335}336private:337FileSpec m_out_dir;338};339340FileSpec save_objects_dir = process_sp->GetTarget().GetSaveJITObjectsDir();341if (save_objects_dir) {342m_object_cache_up = std::make_unique<ObjectDumper>(save_objects_dir);343m_execution_engine_up->setObjectCache(m_object_cache_up.get());344}345346// Make sure we see all sections, including ones that don't have347// relocations...348m_execution_engine_up->setProcessAllSections(true);349350m_execution_engine_up->DisableLazyCompilation();351352for (llvm::Function &function : *m_module) {353if (function.isDeclaration() || function.hasPrivateLinkage())354continue;355356const bool external = !function.hasLocalLinkage();357358void *fun_ptr = m_execution_engine_up->getPointerToFunction(&function);359360if (!error.Success()) {361// We got an error through our callback!362return;363}364365if (!fun_ptr) {366error.SetErrorToGenericError();367error.SetErrorStringWithFormat(368"'%s' was in the JITted module but wasn't lowered",369function.getName().str().c_str());370return;371}372m_jitted_functions.push_back(JittedFunction(373function.getName().str().c_str(), external, reinterpret_cast<uintptr_t>(fun_ptr)));374}375376CommitAllocations(process_sp);377ReportAllocations(*m_execution_engine_up);378379// We have to do this after calling ReportAllocations because for the MCJIT,380// getGlobalValueAddress will cause the JIT to perform all relocations. That381// can only be done once, and has to happen after we do the remapping from382// local -> remote. That means we don't know the local address of the383// Variables, but we don't need that for anything, so that's okay.384385std::function<void(llvm::GlobalValue &)> RegisterOneValue = [this](386llvm::GlobalValue &val) {387if (val.hasExternalLinkage() && !val.isDeclaration()) {388uint64_t var_ptr_addr =389m_execution_engine_up->getGlobalValueAddress(val.getName().str());390391lldb::addr_t remote_addr = GetRemoteAddressForLocal(var_ptr_addr);392393// This is a really unfortunae API that sometimes returns local addresses394// and sometimes returns remote addresses, based on whether the variable395// was relocated during ReportAllocations or not.396397if (remote_addr == LLDB_INVALID_ADDRESS) {398remote_addr = var_ptr_addr;399}400401if (var_ptr_addr != 0)402m_jitted_global_variables.push_back(JittedGlobalVariable(403val.getName().str().c_str(), LLDB_INVALID_ADDRESS, remote_addr));404}405};406407for (llvm::GlobalVariable &global_var : m_module->globals()) {408RegisterOneValue(global_var);409}410411for (llvm::GlobalAlias &global_alias : m_module->aliases()) {412RegisterOneValue(global_alias);413}414415WriteData(process_sp);416417if (m_failed_lookups.size()) {418StreamString ss;419420ss.PutCString("Couldn't look up symbols:\n");421422bool emitNewLine = false;423424for (ConstString failed_lookup : m_failed_lookups) {425if (emitNewLine)426ss.PutCString("\n");427emitNewLine = true;428ss.PutCString(" ");429ss.PutCString(Mangled(failed_lookup).GetDemangledName().GetStringRef());430}431432m_failed_lookups.clear();433ss.PutCString(434"\nHint: The expression tried to call a function that is not present "435"in the target, perhaps because it was optimized out by the compiler.");436error.SetErrorString(ss.GetString());437438return;439}440441m_function_load_addr = LLDB_INVALID_ADDRESS;442m_function_end_load_addr = LLDB_INVALID_ADDRESS;443444for (JittedFunction &jitted_function : m_jitted_functions) {445jitted_function.m_remote_addr =446GetRemoteAddressForLocal(jitted_function.m_local_addr);447448if (!m_name.IsEmpty() && jitted_function.m_name == m_name) {449AddrRange func_range =450GetRemoteRangeForLocal(jitted_function.m_local_addr);451m_function_end_load_addr = func_range.first + func_range.second;452m_function_load_addr = jitted_function.m_remote_addr;453}454}455456if (log) {457LLDB_LOGF(log, "Code can be run in the target.");458459StreamString disassembly_stream;460461Status err = DisassembleFunction(disassembly_stream, process_sp);462463if (!err.Success()) {464LLDB_LOGF(log, "Couldn't disassemble function : %s",465err.AsCString("unknown error"));466} else {467LLDB_LOGF(log, "Function disassembly:\n%s", disassembly_stream.GetData());468}469470LLDB_LOGF(log, "Sections: ");471for (AllocationRecord &record : m_records) {472if (record.m_process_address != LLDB_INVALID_ADDRESS) {473record.dump(log);474475DataBufferHeap my_buffer(record.m_size, 0);476Status err;477ReadMemory(my_buffer.GetBytes(), record.m_process_address,478record.m_size, err);479480if (err.Success()) {481DataExtractor my_extractor(my_buffer.GetBytes(),482my_buffer.GetByteSize(),483lldb::eByteOrderBig, 8);484my_extractor.PutToLog(log, 0, my_buffer.GetByteSize(),485record.m_process_address, 16,486DataExtractor::TypeUInt8);487}488} else {489record.dump(log);490491DataExtractor my_extractor((const void *)record.m_host_address,492record.m_size, lldb::eByteOrderBig, 8);493my_extractor.PutToLog(log, 0, record.m_size, record.m_host_address, 16,494DataExtractor::TypeUInt8);495}496}497}498499func_addr = m_function_load_addr;500func_end = m_function_end_load_addr;501}502503IRExecutionUnit::~IRExecutionUnit() {504m_module_up.reset();505m_execution_engine_up.reset();506m_context_up.reset();507}508509IRExecutionUnit::MemoryManager::MemoryManager(IRExecutionUnit &parent)510: m_default_mm_up(new llvm::SectionMemoryManager()), m_parent(parent) {}511512IRExecutionUnit::MemoryManager::~MemoryManager() = default;513514lldb::SectionType IRExecutionUnit::GetSectionTypeFromSectionName(515const llvm::StringRef &name, IRExecutionUnit::AllocationKind alloc_kind) {516lldb::SectionType sect_type = lldb::eSectionTypeCode;517switch (alloc_kind) {518case AllocationKind::Stub:519sect_type = lldb::eSectionTypeCode;520break;521case AllocationKind::Code:522sect_type = lldb::eSectionTypeCode;523break;524case AllocationKind::Data:525sect_type = lldb::eSectionTypeData;526break;527case AllocationKind::Global:528sect_type = lldb::eSectionTypeData;529break;530case AllocationKind::Bytes:531sect_type = lldb::eSectionTypeOther;532break;533}534535if (!name.empty()) {536if (name == "__text" || name == ".text")537sect_type = lldb::eSectionTypeCode;538else if (name == "__data" || name == ".data")539sect_type = lldb::eSectionTypeCode;540else if (name.starts_with("__debug_") || name.starts_with(".debug_")) {541const uint32_t name_idx = name[0] == '_' ? 8 : 7;542llvm::StringRef dwarf_name(name.substr(name_idx));543switch (dwarf_name[0]) {544case 'a':545if (dwarf_name == "abbrev")546sect_type = lldb::eSectionTypeDWARFDebugAbbrev;547else if (dwarf_name == "aranges")548sect_type = lldb::eSectionTypeDWARFDebugAranges;549else if (dwarf_name == "addr")550sect_type = lldb::eSectionTypeDWARFDebugAddr;551break;552553case 'f':554if (dwarf_name == "frame")555sect_type = lldb::eSectionTypeDWARFDebugFrame;556break;557558case 'i':559if (dwarf_name == "info")560sect_type = lldb::eSectionTypeDWARFDebugInfo;561break;562563case 'l':564if (dwarf_name == "line")565sect_type = lldb::eSectionTypeDWARFDebugLine;566else if (dwarf_name == "loc")567sect_type = lldb::eSectionTypeDWARFDebugLoc;568else if (dwarf_name == "loclists")569sect_type = lldb::eSectionTypeDWARFDebugLocLists;570break;571572case 'm':573if (dwarf_name == "macinfo")574sect_type = lldb::eSectionTypeDWARFDebugMacInfo;575break;576577case 'p':578if (dwarf_name == "pubnames")579sect_type = lldb::eSectionTypeDWARFDebugPubNames;580else if (dwarf_name == "pubtypes")581sect_type = lldb::eSectionTypeDWARFDebugPubTypes;582break;583584case 's':585if (dwarf_name == "str")586sect_type = lldb::eSectionTypeDWARFDebugStr;587else if (dwarf_name == "str_offsets")588sect_type = lldb::eSectionTypeDWARFDebugStrOffsets;589break;590591case 'r':592if (dwarf_name == "ranges")593sect_type = lldb::eSectionTypeDWARFDebugRanges;594break;595596default:597break;598}599} else if (name.starts_with("__apple_") || name.starts_with(".apple_"))600sect_type = lldb::eSectionTypeInvalid;601else if (name == "__objc_imageinfo")602sect_type = lldb::eSectionTypeOther;603}604return sect_type;605}606607uint8_t *IRExecutionUnit::MemoryManager::allocateCodeSection(608uintptr_t Size, unsigned Alignment, unsigned SectionID,609llvm::StringRef SectionName) {610Log *log = GetLog(LLDBLog::Expressions);611612uint8_t *return_value = m_default_mm_up->allocateCodeSection(613Size, Alignment, SectionID, SectionName);614615m_parent.m_records.push_back(AllocationRecord(616(uintptr_t)return_value,617lldb::ePermissionsReadable | lldb::ePermissionsExecutable,618GetSectionTypeFromSectionName(SectionName, AllocationKind::Code), Size,619Alignment, SectionID, SectionName.str().c_str()));620621LLDB_LOGF(log,622"IRExecutionUnit::allocateCodeSection(Size=0x%" PRIx64623", Alignment=%u, SectionID=%u) = %p",624(uint64_t)Size, Alignment, SectionID, (void *)return_value);625626if (m_parent.m_reported_allocations) {627Status err;628lldb::ProcessSP process_sp =629m_parent.GetBestExecutionContextScope()->CalculateProcess();630631m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back());632}633634return return_value;635}636637uint8_t *IRExecutionUnit::MemoryManager::allocateDataSection(638uintptr_t Size, unsigned Alignment, unsigned SectionID,639llvm::StringRef SectionName, bool IsReadOnly) {640Log *log = GetLog(LLDBLog::Expressions);641642uint8_t *return_value = m_default_mm_up->allocateDataSection(643Size, Alignment, SectionID, SectionName, IsReadOnly);644645uint32_t permissions = lldb::ePermissionsReadable;646if (!IsReadOnly)647permissions |= lldb::ePermissionsWritable;648m_parent.m_records.push_back(AllocationRecord(649(uintptr_t)return_value, permissions,650GetSectionTypeFromSectionName(SectionName, AllocationKind::Data), Size,651Alignment, SectionID, SectionName.str().c_str()));652LLDB_LOGF(log,653"IRExecutionUnit::allocateDataSection(Size=0x%" PRIx64654", Alignment=%u, SectionID=%u) = %p",655(uint64_t)Size, Alignment, SectionID, (void *)return_value);656657if (m_parent.m_reported_allocations) {658Status err;659lldb::ProcessSP process_sp =660m_parent.GetBestExecutionContextScope()->CalculateProcess();661662m_parent.CommitOneAllocation(process_sp, err, m_parent.m_records.back());663}664665return return_value;666}667668void IRExecutionUnit::CollectCandidateCNames(std::vector<ConstString> &C_names,669ConstString name) {670if (m_strip_underscore && name.AsCString()[0] == '_')671C_names.insert(C_names.begin(), ConstString(&name.AsCString()[1]));672C_names.push_back(name);673}674675void IRExecutionUnit::CollectCandidateCPlusPlusNames(676std::vector<ConstString> &CPP_names,677const std::vector<ConstString> &C_names, const SymbolContext &sc) {678if (auto *cpp_lang = Language::FindPlugin(lldb::eLanguageTypeC_plus_plus)) {679for (const ConstString &name : C_names) {680Mangled mangled(name);681if (cpp_lang->SymbolNameFitsToLanguage(mangled)) {682if (ConstString best_alternate =683cpp_lang->FindBestAlternateFunctionMangledName(mangled, sc)) {684CPP_names.push_back(best_alternate);685}686}687688std::vector<ConstString> alternates =689cpp_lang->GenerateAlternateFunctionManglings(name);690CPP_names.insert(CPP_names.end(), alternates.begin(), alternates.end());691692// As a last-ditch fallback, try the base name for C++ names. It's693// terrible, but the DWARF doesn't always encode "extern C" correctly.694ConstString basename =695cpp_lang->GetDemangledFunctionNameWithoutArguments(mangled);696CPP_names.push_back(basename);697}698}699}700701class LoadAddressResolver {702public:703LoadAddressResolver(Target *target, bool &symbol_was_missing_weak)704: m_target(target), m_symbol_was_missing_weak(symbol_was_missing_weak) {}705706std::optional<lldb::addr_t> Resolve(SymbolContextList &sc_list) {707if (sc_list.IsEmpty())708return std::nullopt;709710lldb::addr_t load_address = LLDB_INVALID_ADDRESS;711712// Missing_weak_symbol will be true only if we found only weak undefined713// references to this symbol.714m_symbol_was_missing_weak = true;715716for (auto candidate_sc : sc_list.SymbolContexts()) {717// Only symbols can be weak undefined.718if (!candidate_sc.symbol ||719candidate_sc.symbol->GetType() != lldb::eSymbolTypeUndefined ||720!candidate_sc.symbol->IsWeak())721m_symbol_was_missing_weak = false;722723// First try the symbol.724if (candidate_sc.symbol) {725load_address = candidate_sc.symbol->ResolveCallableAddress(*m_target);726if (load_address == LLDB_INVALID_ADDRESS) {727Address addr = candidate_sc.symbol->GetAddress();728load_address = m_target->GetProcessSP()729? addr.GetLoadAddress(m_target)730: addr.GetFileAddress();731}732}733734// If that didn't work, try the function.735if (load_address == LLDB_INVALID_ADDRESS && candidate_sc.function) {736Address addr =737candidate_sc.function->GetAddressRange().GetBaseAddress();738load_address = m_target->GetProcessSP() ? addr.GetLoadAddress(m_target)739: addr.GetFileAddress();740}741742// We found a load address.743if (load_address != LLDB_INVALID_ADDRESS) {744// If the load address is external, we're done.745const bool is_external =746(candidate_sc.function) ||747(candidate_sc.symbol && candidate_sc.symbol->IsExternal());748if (is_external)749return load_address;750751// Otherwise, remember the best internal load address.752if (m_best_internal_load_address == LLDB_INVALID_ADDRESS)753m_best_internal_load_address = load_address;754}755}756757// You test the address of a weak symbol against NULL to see if it is758// present. So we should return 0 for a missing weak symbol.759if (m_symbol_was_missing_weak)760return 0;761762return std::nullopt;763}764765lldb::addr_t GetBestInternalLoadAddress() const {766return m_best_internal_load_address;767}768769private:770Target *m_target;771bool &m_symbol_was_missing_weak;772lldb::addr_t m_best_internal_load_address = LLDB_INVALID_ADDRESS;773};774775lldb::addr_t776IRExecutionUnit::FindInSymbols(const std::vector<ConstString> &names,777const lldb_private::SymbolContext &sc,778bool &symbol_was_missing_weak) {779symbol_was_missing_weak = false;780781Target *target = sc.target_sp.get();782if (!target) {783// We shouldn't be doing any symbol lookup at all without a target.784return LLDB_INVALID_ADDRESS;785}786787LoadAddressResolver resolver(target, symbol_was_missing_weak);788789ModuleFunctionSearchOptions function_options;790function_options.include_symbols = true;791function_options.include_inlines = false;792793for (const ConstString &name : names) {794if (sc.module_sp) {795SymbolContextList sc_list;796sc.module_sp->FindFunctions(name, CompilerDeclContext(),797lldb::eFunctionNameTypeFull, function_options,798sc_list);799if (auto load_addr = resolver.Resolve(sc_list))800return *load_addr;801}802803if (sc.target_sp) {804SymbolContextList sc_list;805sc.target_sp->GetImages().FindFunctions(name, lldb::eFunctionNameTypeFull,806function_options, sc_list);807if (auto load_addr = resolver.Resolve(sc_list))808return *load_addr;809}810811if (sc.target_sp) {812SymbolContextList sc_list;813sc.target_sp->GetImages().FindSymbolsWithNameAndType(814name, lldb::eSymbolTypeAny, sc_list);815if (auto load_addr = resolver.Resolve(sc_list))816return *load_addr;817}818819lldb::addr_t best_internal_load_address =820resolver.GetBestInternalLoadAddress();821if (best_internal_load_address != LLDB_INVALID_ADDRESS)822return best_internal_load_address;823}824825return LLDB_INVALID_ADDRESS;826}827828lldb::addr_t829IRExecutionUnit::FindInRuntimes(const std::vector<ConstString> &names,830const lldb_private::SymbolContext &sc) {831lldb::TargetSP target_sp = sc.target_sp;832833if (!target_sp) {834return LLDB_INVALID_ADDRESS;835}836837lldb::ProcessSP process_sp = sc.target_sp->GetProcessSP();838839if (!process_sp) {840return LLDB_INVALID_ADDRESS;841}842843for (const ConstString &name : names) {844for (LanguageRuntime *runtime : process_sp->GetLanguageRuntimes()) {845lldb::addr_t symbol_load_addr = runtime->LookupRuntimeSymbol(name);846847if (symbol_load_addr != LLDB_INVALID_ADDRESS)848return symbol_load_addr;849}850}851852return LLDB_INVALID_ADDRESS;853}854855lldb::addr_t IRExecutionUnit::FindInUserDefinedSymbols(856const std::vector<ConstString> &names,857const lldb_private::SymbolContext &sc) {858lldb::TargetSP target_sp = sc.target_sp;859860for (const ConstString &name : names) {861lldb::addr_t symbol_load_addr = target_sp->GetPersistentSymbol(name);862863if (symbol_load_addr != LLDB_INVALID_ADDRESS)864return symbol_load_addr;865}866867return LLDB_INVALID_ADDRESS;868}869870lldb::addr_t IRExecutionUnit::FindSymbol(lldb_private::ConstString name,871bool &missing_weak) {872std::vector<ConstString> candidate_C_names;873std::vector<ConstString> candidate_CPlusPlus_names;874875CollectCandidateCNames(candidate_C_names, name);876877lldb::addr_t ret = FindInSymbols(candidate_C_names, m_sym_ctx, missing_weak);878if (ret != LLDB_INVALID_ADDRESS)879return ret;880881// If we find the symbol in runtimes or user defined symbols it can't be882// a missing weak symbol.883missing_weak = false;884ret = FindInRuntimes(candidate_C_names, m_sym_ctx);885if (ret != LLDB_INVALID_ADDRESS)886return ret;887888ret = FindInUserDefinedSymbols(candidate_C_names, m_sym_ctx);889if (ret != LLDB_INVALID_ADDRESS)890return ret;891892CollectCandidateCPlusPlusNames(candidate_CPlusPlus_names, candidate_C_names,893m_sym_ctx);894ret = FindInSymbols(candidate_CPlusPlus_names, m_sym_ctx, missing_weak);895return ret;896}897898void IRExecutionUnit::GetStaticInitializers(899std::vector<lldb::addr_t> &static_initializers) {900Log *log = GetLog(LLDBLog::Expressions);901902llvm::GlobalVariable *global_ctors =903m_module->getNamedGlobal("llvm.global_ctors");904if (!global_ctors) {905LLDB_LOG(log, "Couldn't find llvm.global_ctors.");906return;907}908auto *ctor_array =909llvm::dyn_cast<llvm::ConstantArray>(global_ctors->getInitializer());910if (!ctor_array) {911LLDB_LOG(log, "llvm.global_ctors not a ConstantArray.");912return;913}914915for (llvm::Use &ctor_use : ctor_array->operands()) {916auto *ctor_struct = llvm::dyn_cast<llvm::ConstantStruct>(ctor_use);917if (!ctor_struct)918continue;919// this is standardized920lldbassert(ctor_struct->getNumOperands() == 3);921auto *ctor_function =922llvm::dyn_cast<llvm::Function>(ctor_struct->getOperand(1));923if (!ctor_function) {924LLDB_LOG(log, "global_ctor doesn't contain an llvm::Function");925continue;926}927928ConstString ctor_function_name(ctor_function->getName().str());929LLDB_LOG(log, "Looking for callable jitted function with name {0}.",930ctor_function_name);931932for (JittedFunction &jitted_function : m_jitted_functions) {933if (ctor_function_name != jitted_function.m_name)934continue;935if (jitted_function.m_remote_addr == LLDB_INVALID_ADDRESS) {936LLDB_LOG(log, "Found jitted function with invalid address.");937continue;938}939static_initializers.push_back(jitted_function.m_remote_addr);940LLDB_LOG(log, "Calling function at address {0:x}.",941jitted_function.m_remote_addr);942break;943}944}945}946947llvm::JITSymbol948IRExecutionUnit::MemoryManager::findSymbol(const std::string &Name) {949bool missing_weak = false;950uint64_t addr = GetSymbolAddressAndPresence(Name, missing_weak);951// This is a weak symbol:952if (missing_weak)953return llvm::JITSymbol(addr,954llvm::JITSymbolFlags::Exported | llvm::JITSymbolFlags::Weak);955else956return llvm::JITSymbol(addr, llvm::JITSymbolFlags::Exported);957}958959uint64_t960IRExecutionUnit::MemoryManager::getSymbolAddress(const std::string &Name) {961bool missing_weak = false;962return GetSymbolAddressAndPresence(Name, missing_weak);963}964965uint64_t966IRExecutionUnit::MemoryManager::GetSymbolAddressAndPresence(967const std::string &Name, bool &missing_weak) {968Log *log = GetLog(LLDBLog::Expressions);969970ConstString name_cs(Name.c_str());971972lldb::addr_t ret = m_parent.FindSymbol(name_cs, missing_weak);973974if (ret == LLDB_INVALID_ADDRESS) {975LLDB_LOGF(log,976"IRExecutionUnit::getSymbolAddress(Name=\"%s\") = <not found>",977Name.c_str());978979m_parent.ReportSymbolLookupError(name_cs);980return 0;981} else {982LLDB_LOGF(log, "IRExecutionUnit::getSymbolAddress(Name=\"%s\") = %" PRIx64,983Name.c_str(), ret);984return ret;985}986}987988void *IRExecutionUnit::MemoryManager::getPointerToNamedFunction(989const std::string &Name, bool AbortOnFailure) {990return (void *)getSymbolAddress(Name);991}992993lldb::addr_t994IRExecutionUnit::GetRemoteAddressForLocal(lldb::addr_t local_address) {995Log *log = GetLog(LLDBLog::Expressions);996997for (AllocationRecord &record : m_records) {998if (local_address >= record.m_host_address &&999local_address < record.m_host_address + record.m_size) {1000if (record.m_process_address == LLDB_INVALID_ADDRESS)1001return LLDB_INVALID_ADDRESS;10021003lldb::addr_t ret =1004record.m_process_address + (local_address - record.m_host_address);10051006LLDB_LOGF(log,1007"IRExecutionUnit::GetRemoteAddressForLocal() found 0x%" PRIx641008" in [0x%" PRIx64 "..0x%" PRIx64 "], and returned 0x%" PRIx641009" from [0x%" PRIx64 "..0x%" PRIx64 "].",1010local_address, (uint64_t)record.m_host_address,1011(uint64_t)record.m_host_address + (uint64_t)record.m_size, ret,1012record.m_process_address,1013record.m_process_address + record.m_size);10141015return ret;1016}1017}10181019return LLDB_INVALID_ADDRESS;1020}10211022IRExecutionUnit::AddrRange1023IRExecutionUnit::GetRemoteRangeForLocal(lldb::addr_t local_address) {1024for (AllocationRecord &record : m_records) {1025if (local_address >= record.m_host_address &&1026local_address < record.m_host_address + record.m_size) {1027if (record.m_process_address == LLDB_INVALID_ADDRESS)1028return AddrRange(0, 0);10291030return AddrRange(record.m_process_address, record.m_size);1031}1032}10331034return AddrRange(0, 0);1035}10361037bool IRExecutionUnit::CommitOneAllocation(lldb::ProcessSP &process_sp,1038Status &error,1039AllocationRecord &record) {1040if (record.m_process_address != LLDB_INVALID_ADDRESS) {1041return true;1042}10431044switch (record.m_sect_type) {1045case lldb::eSectionTypeInvalid:1046case lldb::eSectionTypeDWARFDebugAbbrev:1047case lldb::eSectionTypeDWARFDebugAddr:1048case lldb::eSectionTypeDWARFDebugAranges:1049case lldb::eSectionTypeDWARFDebugCuIndex:1050case lldb::eSectionTypeDWARFDebugFrame:1051case lldb::eSectionTypeDWARFDebugInfo:1052case lldb::eSectionTypeDWARFDebugLine:1053case lldb::eSectionTypeDWARFDebugLoc:1054case lldb::eSectionTypeDWARFDebugLocLists:1055case lldb::eSectionTypeDWARFDebugMacInfo:1056case lldb::eSectionTypeDWARFDebugPubNames:1057case lldb::eSectionTypeDWARFDebugPubTypes:1058case lldb::eSectionTypeDWARFDebugRanges:1059case lldb::eSectionTypeDWARFDebugStr:1060case lldb::eSectionTypeDWARFDebugStrOffsets:1061case lldb::eSectionTypeDWARFAppleNames:1062case lldb::eSectionTypeDWARFAppleTypes:1063case lldb::eSectionTypeDWARFAppleNamespaces:1064case lldb::eSectionTypeDWARFAppleObjC:1065case lldb::eSectionTypeDWARFGNUDebugAltLink:1066error.Clear();1067break;1068default:1069const bool zero_memory = false;1070record.m_process_address =1071Malloc(record.m_size, record.m_alignment, record.m_permissions,1072eAllocationPolicyProcessOnly, zero_memory, error);1073break;1074}10751076return error.Success();1077}10781079bool IRExecutionUnit::CommitAllocations(lldb::ProcessSP &process_sp) {1080bool ret = true;10811082lldb_private::Status err;10831084for (AllocationRecord &record : m_records) {1085ret = CommitOneAllocation(process_sp, err, record);10861087if (!ret) {1088break;1089}1090}10911092if (!ret) {1093for (AllocationRecord &record : m_records) {1094if (record.m_process_address != LLDB_INVALID_ADDRESS) {1095Free(record.m_process_address, err);1096record.m_process_address = LLDB_INVALID_ADDRESS;1097}1098}1099}11001101return ret;1102}11031104void IRExecutionUnit::ReportAllocations(llvm::ExecutionEngine &engine) {1105m_reported_allocations = true;11061107for (AllocationRecord &record : m_records) {1108if (record.m_process_address == LLDB_INVALID_ADDRESS)1109continue;11101111if (record.m_section_id == eSectionIDInvalid)1112continue;11131114engine.mapSectionAddress((void *)record.m_host_address,1115record.m_process_address);1116}11171118// Trigger re-application of relocations.1119engine.finalizeObject();1120}11211122bool IRExecutionUnit::WriteData(lldb::ProcessSP &process_sp) {1123bool wrote_something = false;1124for (AllocationRecord &record : m_records) {1125if (record.m_process_address != LLDB_INVALID_ADDRESS) {1126lldb_private::Status err;1127WriteMemory(record.m_process_address, (uint8_t *)record.m_host_address,1128record.m_size, err);1129if (err.Success())1130wrote_something = true;1131}1132}1133return wrote_something;1134}11351136void IRExecutionUnit::AllocationRecord::dump(Log *log) {1137if (!log)1138return;11391140LLDB_LOGF(log,1141"[0x%llx+0x%llx]->0x%llx (alignment %d, section ID %d, name %s)",1142(unsigned long long)m_host_address, (unsigned long long)m_size,1143(unsigned long long)m_process_address, (unsigned)m_alignment,1144(unsigned)m_section_id, m_name.c_str());1145}11461147lldb::ByteOrder IRExecutionUnit::GetByteOrder() const {1148ExecutionContext exe_ctx(GetBestExecutionContextScope());1149return exe_ctx.GetByteOrder();1150}11511152uint32_t IRExecutionUnit::GetAddressByteSize() const {1153ExecutionContext exe_ctx(GetBestExecutionContextScope());1154return exe_ctx.GetAddressByteSize();1155}11561157void IRExecutionUnit::PopulateSymtab(lldb_private::ObjectFile *obj_file,1158lldb_private::Symtab &symtab) {1159// No symbols yet...1160}11611162void IRExecutionUnit::PopulateSectionList(1163lldb_private::ObjectFile *obj_file,1164lldb_private::SectionList §ion_list) {1165for (AllocationRecord &record : m_records) {1166if (record.m_size > 0) {1167lldb::SectionSP section_sp(new lldb_private::Section(1168obj_file->GetModule(), obj_file, record.m_section_id,1169ConstString(record.m_name), record.m_sect_type,1170record.m_process_address, record.m_size,1171record.m_host_address, // file_offset (which is the host address for1172// the data)1173record.m_size, // file_size11740,1175record.m_permissions)); // flags1176section_list.AddSection(section_sp);1177}1178}1179}11801181ArchSpec IRExecutionUnit::GetArchitecture() {1182ExecutionContext exe_ctx(GetBestExecutionContextScope());1183if(Target *target = exe_ctx.GetTargetPtr())1184return target->GetArchitecture();1185return ArchSpec();1186}11871188lldb::ModuleSP IRExecutionUnit::GetJITModule() {1189ExecutionContext exe_ctx(GetBestExecutionContextScope());1190Target *target = exe_ctx.GetTargetPtr();1191if (!target)1192return nullptr;11931194auto Delegate = std::static_pointer_cast<lldb_private::ObjectFileJITDelegate>(1195shared_from_this());11961197lldb::ModuleSP jit_module_sp =1198lldb_private::Module::CreateModuleFromObjectFile<ObjectFileJIT>(Delegate);1199if (!jit_module_sp)1200return nullptr;12011202bool changed = false;1203jit_module_sp->SetLoadAddress(*target, 0, true, changed);1204return jit_module_sp;1205}120612071208