Path: blob/main/contrib/llvm-project/lldb/source/Target/TargetList.cpp
39587 views
//===-- TargetList.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 "lldb/Target/TargetList.h"9#include "lldb/Core/Debugger.h"10#include "lldb/Core/Module.h"11#include "lldb/Core/ModuleSpec.h"12#include "lldb/Host/Host.h"13#include "lldb/Host/HostInfo.h"14#include "lldb/Interpreter/CommandInterpreter.h"15#include "lldb/Interpreter/OptionGroupPlatform.h"16#include "lldb/Symbol/ObjectFile.h"17#include "lldb/Target/Platform.h"18#include "lldb/Target/Process.h"19#include "lldb/Utility/Broadcaster.h"20#include "lldb/Utility/Event.h"21#include "lldb/Utility/State.h"22#include "lldb/Utility/TildeExpressionResolver.h"23#include "lldb/Utility/Timer.h"2425#include "llvm/ADT/SmallString.h"26#include "llvm/Support/FileSystem.h"2728using namespace lldb;29using namespace lldb_private;3031llvm::StringRef TargetList::GetStaticBroadcasterClass() {32static constexpr llvm::StringLiteral class_name("lldb.targetList");33return class_name;34}3536// TargetList constructor37TargetList::TargetList(Debugger &debugger)38: Broadcaster(debugger.GetBroadcasterManager(),39TargetList::GetStaticBroadcasterClass().str()),40m_target_list(), m_target_list_mutex(), m_selected_target_idx(0) {41CheckInWithManager();42}4344Status TargetList::CreateTarget(Debugger &debugger,45llvm::StringRef user_exe_path,46llvm::StringRef triple_str,47LoadDependentFiles load_dependent_files,48const OptionGroupPlatform *platform_options,49TargetSP &target_sp) {50std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);51auto result = TargetList::CreateTargetInternal(52debugger, user_exe_path, triple_str, load_dependent_files,53platform_options, target_sp);5455if (target_sp && result.Success())56AddTargetInternal(target_sp, /*do_select*/ true);57return result;58}5960Status TargetList::CreateTarget(Debugger &debugger,61llvm::StringRef user_exe_path,62const ArchSpec &specified_arch,63LoadDependentFiles load_dependent_files,64PlatformSP &platform_sp, TargetSP &target_sp) {65std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);66auto result = TargetList::CreateTargetInternal(67debugger, user_exe_path, specified_arch, load_dependent_files,68platform_sp, target_sp);6970if (target_sp && result.Success())71AddTargetInternal(target_sp, /*do_select*/ true);72return result;73}7475Status TargetList::CreateTargetInternal(76Debugger &debugger, llvm::StringRef user_exe_path,77llvm::StringRef triple_str, LoadDependentFiles load_dependent_files,78const OptionGroupPlatform *platform_options, TargetSP &target_sp) {79Status error;8081PlatformList &platform_list = debugger.GetPlatformList();82// Let's start by looking at the selected platform.83PlatformSP platform_sp = platform_list.GetSelectedPlatform();8485// This variable corresponds to the architecture specified by the triple86// string. If that string was empty the currently selected platform will87// determine the architecture.88const ArchSpec arch(triple_str);89if (!triple_str.empty() && !arch.IsValid()) {90error.SetErrorStringWithFormat("invalid triple '%s'",91triple_str.str().c_str());92return error;93}9495ArchSpec platform_arch(arch);9697// Create a new platform if a platform was specified in the platform options98// and doesn't match the selected platform.99if (platform_options && platform_options->PlatformWasSpecified() &&100!platform_options->PlatformMatches(platform_sp)) {101const bool select_platform = true;102platform_sp = platform_options->CreatePlatformWithOptions(103debugger.GetCommandInterpreter(), arch, select_platform, error,104platform_arch);105if (!platform_sp)106return error;107}108109bool prefer_platform_arch = false;110auto update_platform_arch = [&](const ArchSpec &module_arch) {111// If the OS or vendor weren't specified, then adopt the module's112// architecture so that the platform matching can be more accurate.113if (!platform_arch.TripleOSWasSpecified() ||114!platform_arch.TripleVendorWasSpecified()) {115prefer_platform_arch = true;116platform_arch = module_arch;117}118};119120if (!user_exe_path.empty()) {121ModuleSpec module_spec(FileSpec(user_exe_path, FileSpec::Style::native));122FileSystem::Instance().Resolve(module_spec.GetFileSpec());123124// Try to resolve the exe based on PATH and/or platform-specific suffixes,125// but only if using the host platform.126if (platform_sp->IsHost() &&127!FileSystem::Instance().Exists(module_spec.GetFileSpec()))128FileSystem::Instance().ResolveExecutableLocation(129module_spec.GetFileSpec());130131// Resolve the executable in case we are given a path to a application132// bundle like a .app bundle on MacOSX.133Host::ResolveExecutableInBundle(module_spec.GetFileSpec());134135lldb::offset_t file_offset = 0;136lldb::offset_t file_size = 0;137ModuleSpecList module_specs;138const size_t num_specs = ObjectFile::GetModuleSpecifications(139module_spec.GetFileSpec(), file_offset, file_size, module_specs);140141if (num_specs > 0) {142ModuleSpec matching_module_spec;143144if (num_specs == 1) {145if (module_specs.GetModuleSpecAtIndex(0, matching_module_spec)) {146if (platform_arch.IsValid()) {147if (platform_arch.IsCompatibleMatch(148matching_module_spec.GetArchitecture())) {149// If the OS or vendor weren't specified, then adopt the module's150// architecture so that the platform matching can be more151// accurate.152update_platform_arch(matching_module_spec.GetArchitecture());153} else {154StreamString platform_arch_strm;155StreamString module_arch_strm;156157platform_arch.DumpTriple(platform_arch_strm.AsRawOstream());158matching_module_spec.GetArchitecture().DumpTriple(159module_arch_strm.AsRawOstream());160error.SetErrorStringWithFormat(161"the specified architecture '%s' is not compatible with '%s' "162"in '%s'",163platform_arch_strm.GetData(), module_arch_strm.GetData(),164module_spec.GetFileSpec().GetPath().c_str());165return error;166}167} else {168// Only one arch and none was specified.169prefer_platform_arch = true;170platform_arch = matching_module_spec.GetArchitecture();171}172}173} else if (arch.IsValid()) {174// Fat binary. A (valid) architecture was specified.175module_spec.GetArchitecture() = arch;176if (module_specs.FindMatchingModuleSpec(module_spec,177matching_module_spec))178update_platform_arch(matching_module_spec.GetArchitecture());179} else {180// Fat binary. No architecture specified, check if there is181// only one platform for all of the architectures.182std::vector<PlatformSP> candidates;183std::vector<ArchSpec> archs;184for (const ModuleSpec &spec : module_specs.ModuleSpecs())185archs.push_back(spec.GetArchitecture());186if (PlatformSP platform_for_archs_sp =187platform_list.GetOrCreate(archs, {}, candidates)) {188platform_sp = platform_for_archs_sp;189} else if (candidates.empty()) {190error.SetErrorString("no matching platforms found for this file");191return error;192} else {193// More than one platform claims to support this file.194StreamString error_strm;195std::set<llvm::StringRef> platform_set;196error_strm.Printf(197"more than one platform supports this executable (");198for (const auto &candidate : candidates) {199llvm::StringRef platform_name = candidate->GetName();200if (platform_set.count(platform_name))201continue;202if (!platform_set.empty())203error_strm.PutCString(", ");204error_strm.PutCString(platform_name);205platform_set.insert(platform_name);206}207error_strm.Printf("), specify an architecture to disambiguate");208error.SetErrorString(error_strm.GetString());209return error;210}211}212}213}214215// If we have a valid architecture, make sure the current platform is216// compatible with that architecture.217if (!prefer_platform_arch && arch.IsValid()) {218if (!platform_sp->IsCompatibleArchitecture(219arch, {}, ArchSpec::CompatibleMatch, nullptr)) {220platform_sp = platform_list.GetOrCreate(arch, {}, &platform_arch);221if (platform_sp)222platform_list.SetSelectedPlatform(platform_sp);223}224} else if (platform_arch.IsValid()) {225// If "arch" isn't valid, yet "platform_arch" is, it means we have an226// executable file with a single architecture which should be used.227ArchSpec fixed_platform_arch;228if (!platform_sp->IsCompatibleArchitecture(229platform_arch, {}, ArchSpec::CompatibleMatch, nullptr)) {230platform_sp =231platform_list.GetOrCreate(platform_arch, {}, &fixed_platform_arch);232if (platform_sp)233platform_list.SetSelectedPlatform(platform_sp);234}235}236237if (!platform_arch.IsValid())238platform_arch = arch;239240return TargetList::CreateTargetInternal(debugger, user_exe_path,241platform_arch, load_dependent_files,242platform_sp, target_sp);243}244245Status TargetList::CreateTargetInternal(Debugger &debugger,246llvm::StringRef user_exe_path,247const ArchSpec &specified_arch,248LoadDependentFiles load_dependent_files,249lldb::PlatformSP &platform_sp,250lldb::TargetSP &target_sp) {251LLDB_SCOPED_TIMERF("TargetList::CreateTarget (file = '%s', arch = '%s')",252user_exe_path.str().c_str(),253specified_arch.GetArchitectureName());254Status error;255const bool is_dummy_target = false;256257ArchSpec arch(specified_arch);258259if (arch.IsValid()) {260if (!platform_sp || !platform_sp->IsCompatibleArchitecture(261arch, {}, ArchSpec::CompatibleMatch, nullptr))262platform_sp =263debugger.GetPlatformList().GetOrCreate(specified_arch, {}, &arch);264}265266if (!platform_sp)267platform_sp = debugger.GetPlatformList().GetSelectedPlatform();268269if (!arch.IsValid())270arch = specified_arch;271272FileSpec file(user_exe_path);273if (!FileSystem::Instance().Exists(file) && user_exe_path.starts_with("~")) {274// we want to expand the tilde but we don't want to resolve any symbolic275// links so we can't use the FileSpec constructor's resolve flag276llvm::SmallString<64> unglobbed_path;277StandardTildeExpressionResolver Resolver;278Resolver.ResolveFullPath(user_exe_path, unglobbed_path);279280if (unglobbed_path.empty())281file = FileSpec(user_exe_path);282else283file = FileSpec(unglobbed_path.c_str());284}285286bool user_exe_path_is_bundle = false;287char resolved_bundle_exe_path[PATH_MAX];288resolved_bundle_exe_path[0] = '\0';289if (file) {290if (FileSystem::Instance().IsDirectory(file))291user_exe_path_is_bundle = true;292293if (file.IsRelative() && !user_exe_path.empty()) {294llvm::SmallString<64> cwd;295if (! llvm::sys::fs::current_path(cwd)) {296FileSpec cwd_file(cwd.c_str());297cwd_file.AppendPathComponent(file);298if (FileSystem::Instance().Exists(cwd_file))299file = cwd_file;300}301}302303ModuleSP exe_module_sp;304if (platform_sp) {305FileSpecList executable_search_paths(306Target::GetDefaultExecutableSearchPaths());307ModuleSpec module_spec(file, arch);308error = platform_sp->ResolveExecutable(module_spec, exe_module_sp,309executable_search_paths.GetSize()310? &executable_search_paths311: nullptr);312}313314if (error.Success() && exe_module_sp) {315if (exe_module_sp->GetObjectFile() == nullptr) {316if (arch.IsValid()) {317error.SetErrorStringWithFormat(318"\"%s\" doesn't contain architecture %s", file.GetPath().c_str(),319arch.GetArchitectureName());320} else {321error.SetErrorStringWithFormat("unsupported file type \"%s\"",322file.GetPath().c_str());323}324return error;325}326target_sp.reset(new Target(debugger, arch, platform_sp, is_dummy_target));327debugger.GetTargetList().RegisterInProcessTarget(target_sp);328target_sp->SetExecutableModule(exe_module_sp, load_dependent_files);329if (user_exe_path_is_bundle)330exe_module_sp->GetFileSpec().GetPath(resolved_bundle_exe_path,331sizeof(resolved_bundle_exe_path));332if (target_sp->GetPreloadSymbols())333exe_module_sp->PreloadSymbols();334}335} else {336// No file was specified, just create an empty target with any arch if a337// valid arch was specified338target_sp.reset(new Target(debugger, arch, platform_sp, is_dummy_target));339debugger.GetTargetList().RegisterInProcessTarget(target_sp);340}341342if (!target_sp)343return error;344345// Set argv0 with what the user typed, unless the user specified a346// directory. If the user specified a directory, then it is probably a347// bundle that was resolved and we need to use the resolved bundle path348if (!user_exe_path.empty()) {349// Use exactly what the user typed as the first argument when we exec or350// posix_spawn351if (user_exe_path_is_bundle && resolved_bundle_exe_path[0]) {352target_sp->SetArg0(resolved_bundle_exe_path);353} else {354// Use resolved path355target_sp->SetArg0(file.GetPath().c_str());356}357}358if (file.GetDirectory()) {359FileSpec file_dir;360file_dir.SetDirectory(file.GetDirectory());361target_sp->AppendExecutableSearchPaths(file_dir);362}363364// Now prime this from the dummy target:365target_sp->PrimeFromDummyTarget(debugger.GetDummyTarget());366367return error;368}369370bool TargetList::DeleteTarget(TargetSP &target_sp) {371std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);372auto it = llvm::find(m_target_list, target_sp);373if (it == m_target_list.end())374return false;375376m_target_list.erase(it);377return true;378}379380TargetSP TargetList::FindTargetWithExecutableAndArchitecture(381const FileSpec &exe_file_spec, const ArchSpec *exe_arch_ptr) const {382std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);383auto it = std::find_if(m_target_list.begin(), m_target_list.end(),384[&exe_file_spec, exe_arch_ptr](const TargetSP &item) {385Module *exe_module = item->GetExecutableModulePointer();386if (!exe_module ||387!FileSpec::Match(exe_file_spec, exe_module->GetFileSpec()))388return false;389390return !exe_arch_ptr ||391exe_arch_ptr->IsCompatibleMatch(exe_module->GetArchitecture());392});393394if (it != m_target_list.end())395return *it;396397return TargetSP();398}399400TargetSP TargetList::FindTargetWithProcessID(lldb::pid_t pid) const {401std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);402auto it = std::find_if(m_target_list.begin(), m_target_list.end(),403[pid](const TargetSP &item) {404auto *process_ptr = item->GetProcessSP().get();405return process_ptr && (process_ptr->GetID() == pid);406});407408if (it != m_target_list.end())409return *it;410411return TargetSP();412}413414TargetSP TargetList::FindTargetWithProcess(Process *process) const {415TargetSP target_sp;416if (!process)417return target_sp;418419std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);420auto it = std::find_if(m_target_list.begin(), m_target_list.end(),421[process](const TargetSP &item) {422return item->GetProcessSP().get() == process;423});424425if (it != m_target_list.end())426target_sp = *it;427428return target_sp;429}430431TargetSP TargetList::GetTargetSP(Target *target) const {432TargetSP target_sp;433if (!target)434return target_sp;435436std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);437auto it = std::find_if(m_target_list.begin(), m_target_list.end(),438[target](const TargetSP &item) { return item.get() == target; });439if (it != m_target_list.end())440target_sp = *it;441442return target_sp;443}444445uint32_t TargetList::SendAsyncInterrupt(lldb::pid_t pid) {446uint32_t num_async_interrupts_sent = 0;447448if (pid != LLDB_INVALID_PROCESS_ID) {449TargetSP target_sp(FindTargetWithProcessID(pid));450if (target_sp) {451Process *process = target_sp->GetProcessSP().get();452if (process) {453process->SendAsyncInterrupt();454++num_async_interrupts_sent;455}456}457} else {458// We don't have a valid pid to broadcast to, so broadcast to the target459// list's async broadcaster...460BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);461}462463return num_async_interrupts_sent;464}465466uint32_t TargetList::SignalIfRunning(lldb::pid_t pid, int signo) {467uint32_t num_signals_sent = 0;468Process *process = nullptr;469if (pid == LLDB_INVALID_PROCESS_ID) {470// Signal all processes with signal471std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);472for (const auto &target_sp : m_target_list) {473process = target_sp->GetProcessSP().get();474if (process && process->IsAlive()) {475++num_signals_sent;476process->Signal(signo);477}478}479} else {480// Signal a specific process with signal481TargetSP target_sp(FindTargetWithProcessID(pid));482if (target_sp) {483process = target_sp->GetProcessSP().get();484if (process && process->IsAlive()) {485++num_signals_sent;486process->Signal(signo);487}488}489}490return num_signals_sent;491}492493size_t TargetList::GetNumTargets() const {494std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);495return m_target_list.size();496}497498lldb::TargetSP TargetList::GetTargetAtIndex(uint32_t idx) const {499TargetSP target_sp;500std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);501if (idx < m_target_list.size())502target_sp = m_target_list[idx];503return target_sp;504}505506uint32_t TargetList::GetIndexOfTarget(lldb::TargetSP target_sp) const {507std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);508auto it = llvm::find(m_target_list, target_sp);509if (it != m_target_list.end())510return std::distance(m_target_list.begin(), it);511return UINT32_MAX;512}513514void TargetList::AddTargetInternal(TargetSP target_sp, bool do_select) {515lldbassert(!llvm::is_contained(m_target_list, target_sp) &&516"target already exists it the list");517UnregisterInProcessTarget(target_sp);518m_target_list.push_back(std::move(target_sp));519if (do_select)520SetSelectedTargetInternal(m_target_list.size() - 1);521}522523void TargetList::SetSelectedTargetInternal(uint32_t index) {524lldbassert(!m_target_list.empty());525m_selected_target_idx = index < m_target_list.size() ? index : 0;526}527528void TargetList::SetSelectedTarget(uint32_t index) {529std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);530SetSelectedTargetInternal(index);531}532533void TargetList::SetSelectedTarget(const TargetSP &target_sp) {534// Don't allow an invalid target shared pointer or a target that has been535// destroyed to become the selected target.536if (target_sp && target_sp->IsValid()) {537std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);538auto it = llvm::find(m_target_list, target_sp);539SetSelectedTargetInternal(std::distance(m_target_list.begin(), it));540}541}542543lldb::TargetSP TargetList::GetSelectedTarget() {544std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);545if (m_selected_target_idx >= m_target_list.size())546m_selected_target_idx = 0;547return GetTargetAtIndex(m_selected_target_idx);548}549550bool TargetList::AnyTargetContainsModule(Module &module) {551std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);552for (const auto &target_sp : m_target_list) {553if (target_sp->GetImages().FindModule(&module))554return true;555}556for (const auto &target_sp: m_in_process_target_list) {557if (target_sp->GetImages().FindModule(&module))558return true;559}560return false;561}562563void TargetList::RegisterInProcessTarget(TargetSP target_sp) {564std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);565[[maybe_unused]] bool was_added;566std::tie(std::ignore, was_added) =567m_in_process_target_list.insert(target_sp);568assert(was_added && "Target pointer was left in the in-process map");569}570571void TargetList::UnregisterInProcessTarget(TargetSP target_sp) {572std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);573[[maybe_unused]] bool was_present =574m_in_process_target_list.erase(target_sp);575assert(was_present && "Target pointer being removed was not registered");576}577578bool TargetList::IsTargetInProcess(TargetSP target_sp) {579std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);580return m_in_process_target_list.count(target_sp) == 1;581}582583584