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 //===----------------------------------------------------------------------===//
11 #include "lldb/Target/TargetList.h"
12 #include "lldb/Core/Broadcaster.h"
13 #include "lldb/Core/Debugger.h"
14 #include "lldb/Core/Event.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/ModuleSpec.h"
17 #include "lldb/Core/State.h"
18 #include "lldb/Host/Host.h"
19 #include "lldb/Host/HostInfo.h"
20 #include "lldb/Interpreter/CommandInterpreter.h"
21 #include "lldb/Interpreter/OptionGroupPlatform.h"
22 #include "lldb/Symbol/ObjectFile.h"
23 #include "lldb/Target/Platform.h"
24 #include "lldb/Target/Process.h"
25 #include "lldb/Utility/TildeExpressionResolver.h"
26 #include "lldb/Utility/Timer.h"
28 // Other libraries and framework includes
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/Support/FileSystem.h"
33 using namespace lldb_private;
35 ConstString &TargetList::GetStaticBroadcasterClass() {
36 static ConstString class_name("lldb.targetList");
40 //----------------------------------------------------------------------
41 // TargetList constructor
42 //----------------------------------------------------------------------
43 TargetList::TargetList(Debugger &debugger)
44 : Broadcaster(debugger.GetBroadcasterManager(),
45 TargetList::GetStaticBroadcasterClass().AsCString()),
46 m_target_list(), m_target_list_mutex(), m_selected_target_idx(0) {
50 //----------------------------------------------------------------------
52 //----------------------------------------------------------------------
53 TargetList::~TargetList() {
54 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
55 m_target_list.clear();
58 Status TargetList::CreateTarget(Debugger &debugger,
59 llvm::StringRef user_exe_path,
60 llvm::StringRef triple_str,
61 bool get_dependent_files,
62 const OptionGroupPlatform *platform_options,
63 TargetSP &target_sp) {
64 return CreateTargetInternal(debugger, user_exe_path, triple_str,
65 get_dependent_files, platform_options, target_sp,
69 Status TargetList::CreateTarget(Debugger &debugger,
70 llvm::StringRef user_exe_path,
71 const ArchSpec &specified_arch,
72 bool get_dependent_files,
73 PlatformSP &platform_sp, TargetSP &target_sp) {
74 return CreateTargetInternal(debugger, user_exe_path, specified_arch,
75 get_dependent_files, platform_sp, target_sp,
79 Status TargetList::CreateTargetInternal(
80 Debugger &debugger, llvm::StringRef user_exe_path,
81 llvm::StringRef triple_str, bool get_dependent_files,
82 const OptionGroupPlatform *platform_options, TargetSP &target_sp,
83 bool is_dummy_target) {
85 PlatformSP platform_sp;
87 // This is purposely left empty unless it is specified by triple_cstr.
88 // If not initialized via triple_cstr, then the currently selected platform
89 // will set the architecture correctly.
90 const ArchSpec arch(triple_str);
91 if (!triple_str.empty()) {
92 if (!arch.IsValid()) {
93 error.SetErrorStringWithFormat("invalid triple '%s'",
94 triple_str.str().c_str());
99 ArchSpec platform_arch(arch);
101 bool prefer_platform_arch = false;
103 CommandInterpreter &interpreter = debugger.GetCommandInterpreter();
105 // let's see if there is already an existing plaform before we go creating
107 platform_sp = debugger.GetPlatformList().GetSelectedPlatform();
109 if (platform_options && platform_options->PlatformWasSpecified()) {
110 // Create a new platform if it doesn't match the selected platform
111 if (!platform_options->PlatformMatches(platform_sp)) {
112 const bool select_platform = true;
113 platform_sp = platform_options->CreatePlatformWithOptions(
114 interpreter, arch, select_platform, error, platform_arch);
120 if (!user_exe_path.empty()) {
121 ModuleSpecList module_specs;
122 ModuleSpec module_spec;
123 module_spec.GetFileSpec().SetFile(user_exe_path, true);
125 // Resolve the executable in case we are given a path to a application
127 // like a .app bundle on MacOSX
128 Host::ResolveExecutableInBundle(module_spec.GetFileSpec());
130 lldb::offset_t file_offset = 0;
131 lldb::offset_t file_size = 0;
132 const size_t num_specs = ObjectFile::GetModuleSpecifications(
133 module_spec.GetFileSpec(), file_offset, file_size, module_specs);
135 ModuleSpec matching_module_spec;
137 if (num_specs == 1) {
138 if (module_specs.GetModuleSpecAtIndex(0, matching_module_spec)) {
139 if (platform_arch.IsValid()) {
140 if (platform_arch.IsCompatibleMatch(
141 matching_module_spec.GetArchitecture())) {
142 // If the OS or vendor weren't specified, then adopt the module's
143 // architecture so that the platform matching can be more accurate
144 if (!platform_arch.TripleOSWasSpecified() ||
145 !platform_arch.TripleVendorWasSpecified()) {
146 prefer_platform_arch = true;
147 platform_arch = matching_module_spec.GetArchitecture();
150 StreamString platform_arch_strm;
151 StreamString module_arch_strm;
153 platform_arch.DumpTriple(platform_arch_strm);
154 matching_module_spec.GetArchitecture().DumpTriple(
156 error.SetErrorStringWithFormat(
157 "the specified architecture '%s' is not compatible with '%s' "
159 platform_arch_strm.GetData(), module_arch_strm.GetData(),
160 module_spec.GetFileSpec().GetPath().c_str());
164 // Only one arch and none was specified
165 prefer_platform_arch = true;
166 platform_arch = matching_module_spec.GetArchitecture();
170 if (arch.IsValid()) {
171 module_spec.GetArchitecture() = arch;
172 if (module_specs.FindMatchingModuleSpec(module_spec,
173 matching_module_spec)) {
174 prefer_platform_arch = true;
175 platform_arch = matching_module_spec.GetArchitecture();
178 // No architecture specified, check if there is only one platform for
179 // all of the architectures.
181 typedef std::vector<PlatformSP> PlatformList;
182 PlatformList platforms;
183 PlatformSP host_platform_sp = Platform::GetHostPlatform();
184 for (size_t i = 0; i < num_specs; ++i) {
185 ModuleSpec module_spec;
186 if (module_specs.GetModuleSpecAtIndex(i, module_spec)) {
187 // See if there was a selected platform and check that first
188 // since the user may have specified it.
190 if (platform_sp->IsCompatibleArchitecture(
191 module_spec.GetArchitecture(), false, nullptr)) {
192 platforms.push_back(platform_sp);
197 // Next check the host platform it if wasn't already checked above
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 exectuable match, so we can
235 // select this platform
236 platform_sp = platforms.front();
237 } else if (more_than_one_platforms == false) {
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
279 // a single architecture which should be used
280 ArchSpec fixed_platform_arch;
281 if (!platform_sp->IsCompatibleArchitecture(platform_arch, false,
282 &fixed_platform_arch)) {
283 platform_sp = Platform::GetPlatformForArchitecture(platform_arch,
284 &fixed_platform_arch);
285 if (!is_dummy_target && platform_sp)
286 debugger.GetPlatformList().SetSelectedPlatform(platform_sp);
290 if (!platform_arch.IsValid())
291 platform_arch = arch;
293 error = TargetList::CreateTargetInternal(
294 debugger, user_exe_path, platform_arch, get_dependent_files, platform_sp,
295 target_sp, is_dummy_target);
299 lldb::TargetSP TargetList::GetDummyTarget(lldb_private::Debugger &debugger) {
300 // FIXME: Maybe the dummy target should be per-Debugger
301 if (!m_dummy_target_sp || !m_dummy_target_sp->IsValid()) {
302 ArchSpec arch(Target::GetDefaultArchitecture());
304 arch = HostInfo::GetArchitecture();
305 Status err = CreateDummyTarget(
306 debugger, arch.GetTriple().getTriple().c_str(), m_dummy_target_sp);
309 return m_dummy_target_sp;
312 Status TargetList::CreateDummyTarget(Debugger &debugger,
313 llvm::StringRef specified_arch_name,
314 lldb::TargetSP &target_sp) {
315 PlatformSP host_platform_sp(Platform::GetHostPlatform());
316 return CreateTargetInternal(
317 debugger, (const char *)nullptr, specified_arch_name, false,
318 (const OptionGroupPlatform *)nullptr, target_sp, true);
321 Status TargetList::CreateTargetInternal(Debugger &debugger,
322 llvm::StringRef user_exe_path,
323 const ArchSpec &specified_arch,
324 bool get_dependent_files,
325 lldb::PlatformSP &platform_sp,
326 lldb::TargetSP &target_sp,
327 bool is_dummy_target) {
328 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
330 func_cat, "TargetList::CreateTarget (file = '%s', arch = '%s')",
331 user_exe_path.str().c_str(), specified_arch.GetArchitectureName());
334 ArchSpec arch(specified_arch);
336 if (arch.IsValid()) {
338 !platform_sp->IsCompatibleArchitecture(arch, false, nullptr))
339 platform_sp = Platform::GetPlatformForArchitecture(specified_arch, &arch);
343 platform_sp = debugger.GetPlatformList().GetSelectedPlatform();
346 arch = specified_arch;
348 FileSpec file(user_exe_path, false);
349 if (!file.Exists() && user_exe_path.startswith("~")) {
350 // we want to expand the tilde but we don't want to resolve any symbolic
351 // links so we can't use the FileSpec constructor's resolve flag
352 llvm::SmallString<64> unglobbed_path;
353 StandardTildeExpressionResolver Resolver;
354 Resolver.ResolveFullPath(user_exe_path, unglobbed_path);
356 if (unglobbed_path.empty())
357 file = FileSpec(user_exe_path, false);
359 file = FileSpec(unglobbed_path.c_str(), false);
362 bool user_exe_path_is_bundle = false;
363 char resolved_bundle_exe_path[PATH_MAX];
364 resolved_bundle_exe_path[0] = '\0';
366 if (llvm::sys::fs::is_directory(file.GetPath()))
367 user_exe_path_is_bundle = true;
369 if (file.IsRelative() && !user_exe_path.empty()) {
370 // Ignore paths that start with "./" and "../"
371 if (!user_exe_path.startswith("./") && !user_exe_path.startswith("../")) {
372 llvm::SmallString<64> cwd;
373 if (! llvm::sys::fs::current_path(cwd)) {
375 cwd += user_exe_path;
376 FileSpec cwd_file(cwd, false);
377 if (cwd_file.Exists())
383 ModuleSP exe_module_sp;
385 FileSpecList executable_search_paths(
386 Target::GetDefaultExecutableSearchPaths());
387 ModuleSpec module_spec(file, arch);
388 error = platform_sp->ResolveExecutable(module_spec, exe_module_sp,
389 executable_search_paths.GetSize()
390 ? &executable_search_paths
394 if (error.Success() && exe_module_sp) {
395 if (exe_module_sp->GetObjectFile() == nullptr) {
396 if (arch.IsValid()) {
397 error.SetErrorStringWithFormat(
398 "\"%s\" doesn't contain architecture %s", file.GetPath().c_str(),
399 arch.GetArchitectureName());
401 error.SetErrorStringWithFormat("unsupported file type \"%s\"",
402 file.GetPath().c_str());
406 target_sp.reset(new Target(debugger, arch, platform_sp, is_dummy_target));
407 target_sp->SetExecutableModule(exe_module_sp, get_dependent_files);
408 if (user_exe_path_is_bundle)
409 exe_module_sp->GetFileSpec().GetPath(resolved_bundle_exe_path,
410 sizeof(resolved_bundle_exe_path));
413 // No file was specified, just create an empty target with any arch
414 // if a valid arch was specified
415 target_sp.reset(new Target(debugger, arch, platform_sp, is_dummy_target));
419 // Set argv0 with what the user typed, unless the user specified a
420 // directory. If the user specified a directory, then it is probably a
421 // bundle that was resolved and we need to use the resolved bundle path
422 if (!user_exe_path.empty()) {
423 // Use exactly what the user typed as the first argument when we exec or
425 if (user_exe_path_is_bundle && resolved_bundle_exe_path[0]) {
426 target_sp->SetArg0(resolved_bundle_exe_path);
429 target_sp->SetArg0(file.GetPath().c_str());
432 if (file.GetDirectory()) {
434 file_dir.GetDirectory() = file.GetDirectory();
435 target_sp->GetExecutableSearchPaths().Append(file_dir);
438 // Don't put the dummy target in the target list, it's held separately.
439 if (!is_dummy_target) {
440 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
441 m_selected_target_idx = m_target_list.size();
442 m_target_list.push_back(target_sp);
443 // Now prime this from the dummy target:
444 target_sp->PrimeFromDummyTarget(debugger.GetDummyTarget());
446 m_dummy_target_sp = target_sp;
453 bool TargetList::DeleteTarget(TargetSP &target_sp) {
454 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
455 collection::iterator pos, end = m_target_list.end();
457 for (pos = m_target_list.begin(); pos != end; ++pos) {
458 if (pos->get() == target_sp.get()) {
459 m_target_list.erase(pos);
466 TargetSP TargetList::FindTargetWithExecutableAndArchitecture(
467 const FileSpec &exe_file_spec, const ArchSpec *exe_arch_ptr) const {
468 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
470 bool full_match = (bool)exe_file_spec.GetDirectory();
472 collection::const_iterator pos, end = m_target_list.end();
473 for (pos = m_target_list.begin(); pos != end; ++pos) {
474 Module *exe_module = (*pos)->GetExecutableModulePointer();
477 if (FileSpec::Equal(exe_file_spec, exe_module->GetFileSpec(),
480 if (!exe_arch_ptr->IsCompatibleMatch(exe_module->GetArchitecture()))
491 TargetSP TargetList::FindTargetWithProcessID(lldb::pid_t pid) const {
492 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
494 collection::const_iterator pos, end = m_target_list.end();
495 for (pos = m_target_list.begin(); pos != end; ++pos) {
496 Process *process = (*pos)->GetProcessSP().get();
497 if (process && process->GetID() == pid) {
505 TargetSP TargetList::FindTargetWithProcess(Process *process) const {
508 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
509 collection::const_iterator pos, end = m_target_list.end();
510 for (pos = m_target_list.begin(); pos != end; ++pos) {
511 if (process == (*pos)->GetProcessSP().get()) {
520 TargetSP TargetList::GetTargetSP(Target *target) const {
523 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
524 collection::const_iterator pos, end = m_target_list.end();
525 for (pos = m_target_list.begin(); pos != end; ++pos) {
526 if (target == (*pos).get()) {
535 uint32_t TargetList::SendAsyncInterrupt(lldb::pid_t pid) {
536 uint32_t num_async_interrupts_sent = 0;
538 if (pid != LLDB_INVALID_PROCESS_ID) {
539 TargetSP target_sp(FindTargetWithProcessID(pid));
541 Process *process = target_sp->GetProcessSP().get();
543 process->SendAsyncInterrupt();
544 ++num_async_interrupts_sent;
548 // We don't have a valid pid to broadcast to, so broadcast to the target
549 // list's async broadcaster...
550 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
553 return num_async_interrupts_sent;
556 uint32_t TargetList::SignalIfRunning(lldb::pid_t pid, int signo) {
557 uint32_t num_signals_sent = 0;
558 Process *process = nullptr;
559 if (pid == LLDB_INVALID_PROCESS_ID) {
560 // Signal all processes with signal
561 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
562 collection::iterator pos, end = m_target_list.end();
563 for (pos = m_target_list.begin(); pos != end; ++pos) {
564 process = (*pos)->GetProcessSP().get();
566 if (process->IsAlive()) {
568 process->Signal(signo);
573 // Signal a specific process with signal
574 TargetSP target_sp(FindTargetWithProcessID(pid));
576 process = target_sp->GetProcessSP().get();
578 if (process->IsAlive()) {
580 process->Signal(signo);
585 return num_signals_sent;
588 int TargetList::GetNumTargets() const {
589 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
590 return m_target_list.size();
593 lldb::TargetSP TargetList::GetTargetAtIndex(uint32_t idx) const {
595 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
596 if (idx < m_target_list.size())
597 target_sp = m_target_list[idx];
601 uint32_t TargetList::GetIndexOfTarget(lldb::TargetSP target_sp) const {
602 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
603 size_t num_targets = m_target_list.size();
604 for (size_t idx = 0; idx < num_targets; idx++) {
605 if (target_sp == m_target_list[idx])
611 uint32_t TargetList::SetSelectedTarget(Target *target) {
612 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
613 collection::const_iterator pos, begin = m_target_list.begin(),
614 end = m_target_list.end();
615 for (pos = begin; pos != end; ++pos) {
616 if (pos->get() == target) {
617 m_selected_target_idx = std::distance(begin, pos);
618 return m_selected_target_idx;
621 m_selected_target_idx = 0;
622 return m_selected_target_idx;
625 lldb::TargetSP TargetList::GetSelectedTarget() {
626 std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
627 if (m_selected_target_idx >= m_target_list.size())
628 m_selected_target_idx = 0;
629 return GetTargetAtIndex(m_selected_target_idx);