1 //===-- TargetList.cpp ------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Target/TargetList.h"
11 #include "lldb/Core/Debugger.h"
12 #include "lldb/Core/Module.h"
13 #include "lldb/Core/ModuleSpec.h"
14 #include "lldb/Host/Host.h"
15 #include "lldb/Host/HostInfo.h"
16 #include "lldb/Interpreter/CommandInterpreter.h"
17 #include "lldb/Interpreter/OptionGroupPlatform.h"
18 #include "lldb/Symbol/ObjectFile.h"
19 #include "lldb/Target/Platform.h"
20 #include "lldb/Target/Process.h"
21 #include "lldb/Utility/Broadcaster.h"
22 #include "lldb/Utility/Event.h"
23 #include "lldb/Utility/State.h"
24 #include "lldb/Utility/TildeExpressionResolver.h"
25 #include "lldb/Utility/Timer.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/Support/FileSystem.h"
31 using namespace lldb_private;
33 ConstString &TargetList::GetStaticBroadcasterClass() {
34 static ConstString class_name("lldb.targetList");
38 //----------------------------------------------------------------------
39 // TargetList constructor
40 //----------------------------------------------------------------------
41 TargetList::TargetList(Debugger &debugger)
42 : Broadcaster(debugger.GetBroadcasterManager(),
43 TargetList::GetStaticBroadcasterClass().AsCString()),
44 m_target_list(), m_target_list_mutex(), m_selected_target_idx(0) {
48 //----------------------------------------------------------------------
50 //----------------------------------------------------------------------
51 TargetList::~TargetList() {
52 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
53 m_target_list.clear();
56 Status TargetList::CreateTarget(Debugger &debugger,
57 llvm::StringRef user_exe_path,
58 llvm::StringRef triple_str,
59 LoadDependentFiles load_dependent_files,
60 const OptionGroupPlatform *platform_options,
61 TargetSP &target_sp) {
62 return CreateTargetInternal(debugger, user_exe_path, triple_str,
63 load_dependent_files, platform_options, target_sp,
67 Status TargetList::CreateTarget(Debugger &debugger,
68 llvm::StringRef user_exe_path,
69 const ArchSpec &specified_arch,
70 LoadDependentFiles load_dependent_files,
71 PlatformSP &platform_sp, TargetSP &target_sp) {
72 return CreateTargetInternal(debugger, user_exe_path, specified_arch,
73 load_dependent_files, platform_sp, target_sp,
77 Status TargetList::CreateTargetInternal(
78 Debugger &debugger, llvm::StringRef user_exe_path,
79 llvm::StringRef triple_str, LoadDependentFiles load_dependent_files,
80 const OptionGroupPlatform *platform_options, TargetSP &target_sp,
81 bool is_dummy_target) {
83 PlatformSP platform_sp;
85 // This is purposely left empty unless it is specified by triple_cstr. If not
86 // initialized via triple_cstr, then the currently selected platform will set
87 // the architecture correctly.
88 const ArchSpec arch(triple_str);
89 if (!triple_str.empty()) {
90 if (!arch.IsValid()) {
91 error.SetErrorStringWithFormat("invalid triple '%s'",
92 triple_str.str().c_str());
97 ArchSpec platform_arch(arch);
99 bool prefer_platform_arch = false;
101 CommandInterpreter &interpreter = debugger.GetCommandInterpreter();
103 // let's see if there is already an existing platform before we go creating
105 platform_sp = debugger.GetPlatformList().GetSelectedPlatform();
107 if (platform_options && platform_options->PlatformWasSpecified()) {
108 // Create a new platform if it doesn't match the selected platform
109 if (!platform_options->PlatformMatches(platform_sp)) {
110 const bool select_platform = true;
111 platform_sp = platform_options->CreatePlatformWithOptions(
112 interpreter, arch, select_platform, error, platform_arch);
118 if (!user_exe_path.empty()) {
119 ModuleSpecList module_specs;
120 ModuleSpec module_spec;
121 module_spec.GetFileSpec().SetFile(user_exe_path, FileSpec::Style::native);
122 FileSystem::Instance().Resolve(module_spec.GetFileSpec());
124 // Resolve the executable in case we are given a path to a application
125 // bundle like a .app bundle on MacOSX
126 Host::ResolveExecutableInBundle(module_spec.GetFileSpec());
128 lldb::offset_t file_offset = 0;
129 lldb::offset_t file_size = 0;
130 const size_t num_specs = ObjectFile::GetModuleSpecifications(
131 module_spec.GetFileSpec(), file_offset, file_size, module_specs);
133 ModuleSpec matching_module_spec;
135 if (num_specs == 1) {
136 if (module_specs.GetModuleSpecAtIndex(0, matching_module_spec)) {
137 if (platform_arch.IsValid()) {
138 if (platform_arch.IsCompatibleMatch(
139 matching_module_spec.GetArchitecture())) {
140 // If the OS or vendor weren't specified, then adopt the module's
141 // architecture so that the platform matching can be more
143 if (!platform_arch.TripleOSWasSpecified() ||
144 !platform_arch.TripleVendorWasSpecified()) {
145 prefer_platform_arch = true;
146 platform_arch = matching_module_spec.GetArchitecture();
149 StreamString platform_arch_strm;
150 StreamString module_arch_strm;
152 platform_arch.DumpTriple(platform_arch_strm);
153 matching_module_spec.GetArchitecture().DumpTriple(
155 error.SetErrorStringWithFormat(
156 "the specified architecture '%s' is not compatible with '%s' "
158 platform_arch_strm.GetData(), module_arch_strm.GetData(),
159 module_spec.GetFileSpec().GetPath().c_str());
163 // Only one arch and none was specified
164 prefer_platform_arch = true;
165 platform_arch = matching_module_spec.GetArchitecture();
169 if (arch.IsValid()) {
170 module_spec.GetArchitecture() = arch;
171 if (module_specs.FindMatchingModuleSpec(module_spec,
172 matching_module_spec)) {
173 prefer_platform_arch = true;
174 platform_arch = matching_module_spec.GetArchitecture();
177 // No architecture specified, check if there is only one platform for
178 // all of the architectures.
180 typedef std::vector<PlatformSP> PlatformList;
181 PlatformList platforms;
182 PlatformSP host_platform_sp = Platform::GetHostPlatform();
183 for (size_t i = 0; i < num_specs; ++i) {
184 ModuleSpec module_spec;
185 if (module_specs.GetModuleSpecAtIndex(i, module_spec)) {
186 // See if there was a selected platform and check that first
187 // since the user may have specified it.
189 if (platform_sp->IsCompatibleArchitecture(
190 module_spec.GetArchitecture(), false, nullptr)) {
191 platforms.push_back(platform_sp);
196 // Next check the host platform it if wasn't already checked
198 if (host_platform_sp &&
200 host_platform_sp->GetName() != platform_sp->GetName())) {
201 if (host_platform_sp->IsCompatibleArchitecture(
202 module_spec.GetArchitecture(), false, nullptr)) {
203 platforms.push_back(host_platform_sp);
208 // Just find a platform that matches the architecture in the
210 PlatformSP fallback_platform_sp(
211 Platform::GetPlatformForArchitecture(
212 module_spec.GetArchitecture(), nullptr));
213 if (fallback_platform_sp) {
214 platforms.push_back(fallback_platform_sp);
219 Platform *platform_ptr = nullptr;
220 bool more_than_one_platforms = false;
221 for (const auto &the_platform_sp : platforms) {
223 if (platform_ptr->GetName() != the_platform_sp->GetName()) {
224 more_than_one_platforms = true;
225 platform_ptr = nullptr;
229 platform_ptr = the_platform_sp.get();
234 // All platforms for all modules in the executable match, so we can
235 // select this platform
236 platform_sp = platforms.front();
237 } else if (!more_than_one_platforms) {
238 // No platforms claim to support this file
239 error.SetErrorString("No matching platforms found for this file, "
240 "specify one with the --platform option");
243 // More than one platform claims to support this file, so the
244 // --platform option must be specified
245 StreamString error_strm;
246 std::set<Platform *> platform_set;
248 "more than one platform supports this executable (");
249 for (const auto &the_platform_sp : platforms) {
250 if (platform_set.find(the_platform_sp.get()) ==
251 platform_set.end()) {
252 if (!platform_set.empty())
253 error_strm.PutCString(", ");
254 error_strm.PutCString(the_platform_sp->GetName().GetCString());
255 platform_set.insert(the_platform_sp.get());
259 "), use the --platform option to specify a platform");
260 error.SetErrorString(error_strm.GetString());
268 // If we have a valid architecture, make sure the current platform is
269 // compatible with that architecture
270 if (!prefer_platform_arch && arch.IsValid()) {
271 if (!platform_sp->IsCompatibleArchitecture(arch, false, &platform_arch)) {
272 platform_sp = Platform::GetPlatformForArchitecture(arch, &platform_arch);
273 if (!is_dummy_target && platform_sp)
274 debugger.GetPlatformList().SetSelectedPlatform(platform_sp);
276 } else if (platform_arch.IsValid()) {
277 // if "arch" isn't valid, yet "platform_arch" is, it means we have an
278 // executable file with a single architecture which should be used
279 ArchSpec fixed_platform_arch;
280 if (!platform_sp->IsCompatibleArchitecture(platform_arch, false,
281 &fixed_platform_arch)) {
282 platform_sp = Platform::GetPlatformForArchitecture(platform_arch,
283 &fixed_platform_arch);
284 if (!is_dummy_target && platform_sp)
285 debugger.GetPlatformList().SetSelectedPlatform(platform_sp);
289 if (!platform_arch.IsValid())
290 platform_arch = arch;
292 error = TargetList::CreateTargetInternal(
293 debugger, user_exe_path, platform_arch, load_dependent_files, platform_sp,
294 target_sp, is_dummy_target);
298 lldb::TargetSP TargetList::GetDummyTarget(lldb_private::Debugger &debugger) {
299 // FIXME: Maybe the dummy target should be per-Debugger
300 if (!m_dummy_target_sp || !m_dummy_target_sp->IsValid()) {
301 ArchSpec arch(Target::GetDefaultArchitecture());
303 arch = HostInfo::GetArchitecture();
304 Status err = CreateDummyTarget(
305 debugger, arch.GetTriple().getTriple().c_str(), m_dummy_target_sp);
308 return m_dummy_target_sp;
311 Status TargetList::CreateDummyTarget(Debugger &debugger,
312 llvm::StringRef specified_arch_name,
313 lldb::TargetSP &target_sp) {
314 PlatformSP host_platform_sp(Platform::GetHostPlatform());
315 return CreateTargetInternal(
316 debugger, (const char *)nullptr, specified_arch_name, eLoadDependentsNo,
317 (const OptionGroupPlatform *)nullptr, target_sp, true);
320 Status TargetList::CreateTargetInternal(Debugger &debugger,
321 llvm::StringRef user_exe_path,
322 const ArchSpec &specified_arch,
323 LoadDependentFiles load_dependent_files,
324 lldb::PlatformSP &platform_sp,
325 lldb::TargetSP &target_sp,
326 bool is_dummy_target) {
327 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
329 func_cat, "TargetList::CreateTarget (file = '%s', arch = '%s')",
330 user_exe_path.str().c_str(), specified_arch.GetArchitectureName());
333 ArchSpec arch(specified_arch);
335 if (arch.IsValid()) {
337 !platform_sp->IsCompatibleArchitecture(arch, false, nullptr))
338 platform_sp = Platform::GetPlatformForArchitecture(specified_arch, &arch);
342 platform_sp = debugger.GetPlatformList().GetSelectedPlatform();
345 arch = specified_arch;
347 FileSpec file(user_exe_path);
348 if (!FileSystem::Instance().Exists(file) && user_exe_path.startswith("~")) {
349 // we want to expand the tilde but we don't want to resolve any symbolic
350 // links so we can't use the FileSpec constructor's resolve flag
351 llvm::SmallString<64> unglobbed_path;
352 StandardTildeExpressionResolver Resolver;
353 Resolver.ResolveFullPath(user_exe_path, unglobbed_path);
355 if (unglobbed_path.empty())
356 file = FileSpec(user_exe_path);
358 file = FileSpec(unglobbed_path.c_str());
361 bool user_exe_path_is_bundle = false;
362 char resolved_bundle_exe_path[PATH_MAX];
363 resolved_bundle_exe_path[0] = '\0';
365 if (FileSystem::Instance().IsDirectory(file))
366 user_exe_path_is_bundle = true;
368 if (file.IsRelative() && !user_exe_path.empty()) {
369 llvm::SmallString<64> cwd;
370 if (! llvm::sys::fs::current_path(cwd)) {
371 FileSpec cwd_file(cwd.c_str());
372 cwd_file.AppendPathComponent(file);
373 if (FileSystem::Instance().Exists(cwd_file))
378 ModuleSP exe_module_sp;
380 FileSpecList executable_search_paths(
381 Target::GetDefaultExecutableSearchPaths());
382 ModuleSpec module_spec(file, arch);
383 error = platform_sp->ResolveExecutable(module_spec, exe_module_sp,
384 executable_search_paths.GetSize()
385 ? &executable_search_paths
389 if (error.Success() && exe_module_sp) {
390 if (exe_module_sp->GetObjectFile() == nullptr) {
391 if (arch.IsValid()) {
392 error.SetErrorStringWithFormat(
393 "\"%s\" doesn't contain architecture %s", file.GetPath().c_str(),
394 arch.GetArchitectureName());
396 error.SetErrorStringWithFormat("unsupported file type \"%s\"",
397 file.GetPath().c_str());
401 target_sp.reset(new Target(debugger, arch, platform_sp, is_dummy_target));
402 target_sp->SetExecutableModule(exe_module_sp, load_dependent_files);
403 if (user_exe_path_is_bundle)
404 exe_module_sp->GetFileSpec().GetPath(resolved_bundle_exe_path,
405 sizeof(resolved_bundle_exe_path));
408 // No file was specified, just create an empty target with any arch if a
409 // valid arch was specified
410 target_sp.reset(new Target(debugger, arch, platform_sp, is_dummy_target));
414 // Set argv0 with what the user typed, unless the user specified a
415 // directory. If the user specified a directory, then it is probably a
416 // bundle that was resolved and we need to use the resolved bundle path
417 if (!user_exe_path.empty()) {
418 // Use exactly what the user typed as the first argument when we exec or
420 if (user_exe_path_is_bundle && resolved_bundle_exe_path[0]) {
421 target_sp->SetArg0(resolved_bundle_exe_path);
424 target_sp->SetArg0(file.GetPath().c_str());
427 if (file.GetDirectory()) {
429 file_dir.GetDirectory() = file.GetDirectory();
430 target_sp->GetExecutableSearchPaths().Append(file_dir);
433 // Don't put the dummy target in the target list, it's held separately.
434 if (!is_dummy_target) {
435 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
436 m_selected_target_idx = m_target_list.size();
437 m_target_list.push_back(target_sp);
438 // Now prime this from the dummy target:
439 target_sp->PrimeFromDummyTarget(debugger.GetDummyTarget());
441 m_dummy_target_sp = target_sp;
448 bool TargetList::DeleteTarget(TargetSP &target_sp) {
449 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
450 collection::iterator pos, end = m_target_list.end();
452 for (pos = m_target_list.begin(); pos != end; ++pos) {
453 if (pos->get() == target_sp.get()) {
454 m_target_list.erase(pos);
461 TargetSP TargetList::FindTargetWithExecutableAndArchitecture(
462 const FileSpec &exe_file_spec, const ArchSpec *exe_arch_ptr) const {
463 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
465 bool full_match = (bool)exe_file_spec.GetDirectory();
467 collection::const_iterator pos, end = m_target_list.end();
468 for (pos = m_target_list.begin(); pos != end; ++pos) {
469 Module *exe_module = (*pos)->GetExecutableModulePointer();
472 if (FileSpec::Equal(exe_file_spec, exe_module->GetFileSpec(),
475 if (!exe_arch_ptr->IsCompatibleMatch(exe_module->GetArchitecture()))
486 TargetSP TargetList::FindTargetWithProcessID(lldb::pid_t pid) const {
487 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
489 collection::const_iterator pos, end = m_target_list.end();
490 for (pos = m_target_list.begin(); pos != end; ++pos) {
491 Process *process = (*pos)->GetProcessSP().get();
492 if (process && process->GetID() == pid) {
500 TargetSP TargetList::FindTargetWithProcess(Process *process) const {
503 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
504 collection::const_iterator pos, end = m_target_list.end();
505 for (pos = m_target_list.begin(); pos != end; ++pos) {
506 if (process == (*pos)->GetProcessSP().get()) {
515 TargetSP TargetList::GetTargetSP(Target *target) const {
518 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
519 collection::const_iterator pos, end = m_target_list.end();
520 for (pos = m_target_list.begin(); pos != end; ++pos) {
521 if (target == (*pos).get()) {
530 uint32_t TargetList::SendAsyncInterrupt(lldb::pid_t pid) {
531 uint32_t num_async_interrupts_sent = 0;
533 if (pid != LLDB_INVALID_PROCESS_ID) {
534 TargetSP target_sp(FindTargetWithProcessID(pid));
536 Process *process = target_sp->GetProcessSP().get();
538 process->SendAsyncInterrupt();
539 ++num_async_interrupts_sent;
543 // We don't have a valid pid to broadcast to, so broadcast to the target
544 // list's async broadcaster...
545 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
548 return num_async_interrupts_sent;
551 uint32_t TargetList::SignalIfRunning(lldb::pid_t pid, int signo) {
552 uint32_t num_signals_sent = 0;
553 Process *process = nullptr;
554 if (pid == LLDB_INVALID_PROCESS_ID) {
555 // Signal all processes with signal
556 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
557 collection::iterator pos, end = m_target_list.end();
558 for (pos = m_target_list.begin(); pos != end; ++pos) {
559 process = (*pos)->GetProcessSP().get();
561 if (process->IsAlive()) {
563 process->Signal(signo);
568 // Signal a specific process with signal
569 TargetSP target_sp(FindTargetWithProcessID(pid));
571 process = target_sp->GetProcessSP().get();
573 if (process->IsAlive()) {
575 process->Signal(signo);
580 return num_signals_sent;
583 int TargetList::GetNumTargets() const {
584 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
585 return m_target_list.size();
588 lldb::TargetSP TargetList::GetTargetAtIndex(uint32_t idx) const {
590 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
591 if (idx < m_target_list.size())
592 target_sp = m_target_list[idx];
596 uint32_t TargetList::GetIndexOfTarget(lldb::TargetSP target_sp) const {
597 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
598 size_t num_targets = m_target_list.size();
599 for (size_t idx = 0; idx < num_targets; idx++) {
600 if (target_sp == m_target_list[idx])
606 uint32_t TargetList::SetSelectedTarget(Target *target) {
607 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
608 collection::const_iterator pos, begin = m_target_list.begin(),
609 end = m_target_list.end();
610 for (pos = begin; pos != end; ++pos) {
611 if (pos->get() == target) {
612 m_selected_target_idx = std::distance(begin, pos);
613 return m_selected_target_idx;
616 m_selected_target_idx = 0;
617 return m_selected_target_idx;
620 lldb::TargetSP TargetList::GetSelectedTarget() {
621 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
622 if (m_selected_target_idx >= m_target_list.size())
623 m_selected_target_idx = 0;
624 return GetTargetAtIndex(m_selected_target_idx);