1 //===-- TargetList.cpp ------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Target/TargetList.h"
10 #include "lldb/Core/Debugger.h"
11 #include "lldb/Core/Module.h"
12 #include "lldb/Core/ModuleSpec.h"
13 #include "lldb/Host/Host.h"
14 #include "lldb/Host/HostInfo.h"
15 #include "lldb/Interpreter/CommandInterpreter.h"
16 #include "lldb/Interpreter/OptionGroupPlatform.h"
17 #include "lldb/Symbol/ObjectFile.h"
18 #include "lldb/Target/Platform.h"
19 #include "lldb/Target/Process.h"
20 #include "lldb/Utility/Broadcaster.h"
21 #include "lldb/Utility/Event.h"
22 #include "lldb/Utility/State.h"
23 #include "lldb/Utility/TildeExpressionResolver.h"
24 #include "lldb/Utility/Timer.h"
25 
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/Support/FileSystem.h"
28 
29 using namespace lldb;
30 using namespace lldb_private;
31 
32 ConstString &TargetList::GetStaticBroadcasterClass() {
33   static ConstString class_name("lldb.targetList");
34   return class_name;
35 }
36 
37 //----------------------------------------------------------------------
38 // TargetList constructor
39 //----------------------------------------------------------------------
40 TargetList::TargetList(Debugger &debugger)
41     : Broadcaster(debugger.GetBroadcasterManager(),
42                   TargetList::GetStaticBroadcasterClass().AsCString()),
43       m_target_list(), m_target_list_mutex(), m_selected_target_idx(0) {
44   CheckInWithManager();
45 }
46 
47 //----------------------------------------------------------------------
48 // Destructor
49 //----------------------------------------------------------------------
50 TargetList::~TargetList() {
51   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
52   m_target_list.clear();
53 }
54 
55 Status TargetList::CreateTarget(Debugger &debugger,
56                                 llvm::StringRef user_exe_path,
57                                 llvm::StringRef triple_str,
58                                 LoadDependentFiles load_dependent_files,
59                                 const OptionGroupPlatform *platform_options,
60                                 TargetSP &target_sp) {
61   return CreateTargetInternal(debugger, user_exe_path, triple_str,
62                               load_dependent_files, platform_options, target_sp,
63                               false);
64 }
65 
66 Status TargetList::CreateTarget(Debugger &debugger,
67                                 llvm::StringRef user_exe_path,
68                                 const ArchSpec &specified_arch,
69                                 LoadDependentFiles load_dependent_files,
70                                 PlatformSP &platform_sp, TargetSP &target_sp) {
71   return CreateTargetInternal(debugger, user_exe_path, specified_arch,
72                               load_dependent_files, platform_sp, target_sp,
73                               false);
74 }
75 
76 Status TargetList::CreateTargetInternal(
77     Debugger &debugger, llvm::StringRef user_exe_path,
78     llvm::StringRef triple_str, LoadDependentFiles load_dependent_files,
79     const OptionGroupPlatform *platform_options, TargetSP &target_sp,
80     bool is_dummy_target) {
81   Status error;
82   PlatformSP platform_sp;
83 
84   // This is purposely left empty unless it is specified by triple_cstr. If not
85   // initialized via triple_cstr, then the currently selected platform will set
86   // the architecture correctly.
87   const ArchSpec arch(triple_str);
88   if (!triple_str.empty()) {
89     if (!arch.IsValid()) {
90       error.SetErrorStringWithFormat("invalid triple '%s'",
91                                      triple_str.str().c_str());
92       return error;
93     }
94   }
95 
96   ArchSpec platform_arch(arch);
97 
98   bool prefer_platform_arch = false;
99 
100   CommandInterpreter &interpreter = debugger.GetCommandInterpreter();
101 
102   // let's see if there is already an existing platform before we go creating
103   // another...
104   platform_sp = debugger.GetPlatformList().GetSelectedPlatform();
105 
106   if (platform_options && platform_options->PlatformWasSpecified()) {
107     // Create a new platform if it doesn't match the selected platform
108     if (!platform_options->PlatformMatches(platform_sp)) {
109       const bool select_platform = true;
110       platform_sp = platform_options->CreatePlatformWithOptions(
111           interpreter, arch, select_platform, error, platform_arch);
112       if (!platform_sp)
113         return error;
114     }
115   }
116 
117   if (!user_exe_path.empty()) {
118     ModuleSpecList module_specs;
119     ModuleSpec module_spec;
120     module_spec.GetFileSpec().SetFile(user_exe_path, FileSpec::Style::native);
121     FileSystem::Instance().Resolve(module_spec.GetFileSpec());
122 
123     // Resolve the executable in case we are given a path to a application
124     // bundle like a .app bundle on MacOSX
125     Host::ResolveExecutableInBundle(module_spec.GetFileSpec());
126 
127     lldb::offset_t file_offset = 0;
128     lldb::offset_t file_size = 0;
129     const size_t num_specs = ObjectFile::GetModuleSpecifications(
130         module_spec.GetFileSpec(), file_offset, file_size, module_specs);
131     if (num_specs > 0) {
132       ModuleSpec matching_module_spec;
133 
134       if (num_specs == 1) {
135         if (module_specs.GetModuleSpecAtIndex(0, matching_module_spec)) {
136           if (platform_arch.IsValid()) {
137             if (platform_arch.IsCompatibleMatch(
138                     matching_module_spec.GetArchitecture())) {
139               // If the OS or vendor weren't specified, then adopt the module's
140               // architecture so that the platform matching can be more
141               // accurate
142               if (!platform_arch.TripleOSWasSpecified() ||
143                   !platform_arch.TripleVendorWasSpecified()) {
144                 prefer_platform_arch = true;
145                 platform_arch = matching_module_spec.GetArchitecture();
146               }
147             } else {
148               StreamString platform_arch_strm;
149               StreamString module_arch_strm;
150 
151               platform_arch.DumpTriple(platform_arch_strm);
152               matching_module_spec.GetArchitecture().DumpTriple(
153                   module_arch_strm);
154               error.SetErrorStringWithFormat(
155                   "the specified architecture '%s' is not compatible with '%s' "
156                   "in '%s'",
157                   platform_arch_strm.GetData(), module_arch_strm.GetData(),
158                   module_spec.GetFileSpec().GetPath().c_str());
159               return error;
160             }
161           } else {
162             // Only one arch and none was specified
163             prefer_platform_arch = true;
164             platform_arch = matching_module_spec.GetArchitecture();
165           }
166         }
167       } else {
168         if (arch.IsValid()) {
169           module_spec.GetArchitecture() = arch;
170           if (module_specs.FindMatchingModuleSpec(module_spec,
171                                                   matching_module_spec)) {
172             prefer_platform_arch = true;
173             platform_arch = matching_module_spec.GetArchitecture();
174           }
175         } else {
176           // No architecture specified, check if there is only one platform for
177           // all of the architectures.
178 
179           typedef std::vector<PlatformSP> PlatformList;
180           PlatformList platforms;
181           PlatformSP host_platform_sp = Platform::GetHostPlatform();
182           for (size_t i = 0; i < num_specs; ++i) {
183             ModuleSpec module_spec;
184             if (module_specs.GetModuleSpecAtIndex(i, module_spec)) {
185               // See if there was a selected platform and check that first
186               // since the user may have specified it.
187               if (platform_sp) {
188                 if (platform_sp->IsCompatibleArchitecture(
189                         module_spec.GetArchitecture(), false, nullptr)) {
190                   platforms.push_back(platform_sp);
191                   continue;
192                 }
193               }
194 
195               // Next check the host platform it if wasn't already checked
196               // above
197               if (host_platform_sp &&
198                   (!platform_sp ||
199                    host_platform_sp->GetName() != platform_sp->GetName())) {
200                 if (host_platform_sp->IsCompatibleArchitecture(
201                         module_spec.GetArchitecture(), false, nullptr)) {
202                   platforms.push_back(host_platform_sp);
203                   continue;
204                 }
205               }
206 
207               // Just find a platform that matches the architecture in the
208               // executable file
209               PlatformSP fallback_platform_sp(
210                   Platform::GetPlatformForArchitecture(
211                       module_spec.GetArchitecture(), nullptr));
212               if (fallback_platform_sp) {
213                 platforms.push_back(fallback_platform_sp);
214               }
215             }
216           }
217 
218           Platform *platform_ptr = nullptr;
219           bool more_than_one_platforms = false;
220           for (const auto &the_platform_sp : platforms) {
221             if (platform_ptr) {
222               if (platform_ptr->GetName() != the_platform_sp->GetName()) {
223                 more_than_one_platforms = true;
224                 platform_ptr = nullptr;
225                 break;
226               }
227             } else {
228               platform_ptr = the_platform_sp.get();
229             }
230           }
231 
232           if (platform_ptr) {
233             // All platforms for all modules in the executable match, so we can
234             // select this platform
235             platform_sp = platforms.front();
236           } else if (!more_than_one_platforms) {
237             // No platforms claim to support this file
238             error.SetErrorString("No matching platforms found for this file, "
239                                  "specify one with the --platform option");
240             return error;
241           } else {
242             // More than one platform claims to support this file, so the
243             // --platform option must be specified
244             StreamString error_strm;
245             std::set<Platform *> platform_set;
246             error_strm.Printf(
247                 "more than one platform supports this executable (");
248             for (const auto &the_platform_sp : platforms) {
249               if (platform_set.find(the_platform_sp.get()) ==
250                   platform_set.end()) {
251                 if (!platform_set.empty())
252                   error_strm.PutCString(", ");
253                 error_strm.PutCString(the_platform_sp->GetName().GetCString());
254                 platform_set.insert(the_platform_sp.get());
255               }
256             }
257             error_strm.Printf(
258                 "), use the --platform option to specify a platform");
259             error.SetErrorString(error_strm.GetString());
260             return error;
261           }
262         }
263       }
264     }
265   }
266 
267   // If we have a valid architecture, make sure the current platform is
268   // compatible with that architecture
269   if (!prefer_platform_arch && arch.IsValid()) {
270     if (!platform_sp->IsCompatibleArchitecture(arch, false, &platform_arch)) {
271       platform_sp = Platform::GetPlatformForArchitecture(arch, &platform_arch);
272       if (!is_dummy_target && platform_sp)
273         debugger.GetPlatformList().SetSelectedPlatform(platform_sp);
274     }
275   } else if (platform_arch.IsValid()) {
276     // if "arch" isn't valid, yet "platform_arch" is, it means we have an
277     // executable file with a single architecture which should be used
278     ArchSpec fixed_platform_arch;
279     if (!platform_sp->IsCompatibleArchitecture(platform_arch, false,
280                                                &fixed_platform_arch)) {
281       platform_sp = Platform::GetPlatformForArchitecture(platform_arch,
282                                                          &fixed_platform_arch);
283       if (!is_dummy_target && platform_sp)
284         debugger.GetPlatformList().SetSelectedPlatform(platform_sp);
285     }
286   }
287 
288   if (!platform_arch.IsValid())
289     platform_arch = arch;
290 
291   error = TargetList::CreateTargetInternal(
292       debugger, user_exe_path, platform_arch, load_dependent_files, platform_sp,
293       target_sp, is_dummy_target);
294   return error;
295 }
296 
297 lldb::TargetSP TargetList::GetDummyTarget(lldb_private::Debugger &debugger) {
298   // FIXME: Maybe the dummy target should be per-Debugger
299   if (!m_dummy_target_sp || !m_dummy_target_sp->IsValid()) {
300     ArchSpec arch(Target::GetDefaultArchitecture());
301     if (!arch.IsValid())
302       arch = HostInfo::GetArchitecture();
303     Status err = CreateDummyTarget(
304         debugger, arch.GetTriple().getTriple().c_str(), m_dummy_target_sp);
305   }
306 
307   return m_dummy_target_sp;
308 }
309 
310 Status TargetList::CreateDummyTarget(Debugger &debugger,
311                                      llvm::StringRef specified_arch_name,
312                                      lldb::TargetSP &target_sp) {
313   PlatformSP host_platform_sp(Platform::GetHostPlatform());
314   return CreateTargetInternal(
315       debugger, (const char *)nullptr, specified_arch_name, eLoadDependentsNo,
316       (const OptionGroupPlatform *)nullptr, target_sp, true);
317 }
318 
319 Status TargetList::CreateTargetInternal(Debugger &debugger,
320                                         llvm::StringRef user_exe_path,
321                                         const ArchSpec &specified_arch,
322                                         LoadDependentFiles load_dependent_files,
323                                         lldb::PlatformSP &platform_sp,
324                                         lldb::TargetSP &target_sp,
325                                         bool is_dummy_target) {
326   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
327   Timer scoped_timer(
328       func_cat, "TargetList::CreateTarget (file = '%s', arch = '%s')",
329       user_exe_path.str().c_str(), specified_arch.GetArchitectureName());
330   Status error;
331 
332   ArchSpec arch(specified_arch);
333 
334   if (arch.IsValid()) {
335     if (!platform_sp ||
336         !platform_sp->IsCompatibleArchitecture(arch, false, nullptr))
337       platform_sp = Platform::GetPlatformForArchitecture(specified_arch, &arch);
338   }
339 
340   if (!platform_sp)
341     platform_sp = debugger.GetPlatformList().GetSelectedPlatform();
342 
343   if (!arch.IsValid())
344     arch = specified_arch;
345 
346   FileSpec file(user_exe_path);
347   if (!FileSystem::Instance().Exists(file) && user_exe_path.startswith("~")) {
348     // we want to expand the tilde but we don't want to resolve any symbolic
349     // links so we can't use the FileSpec constructor's resolve flag
350     llvm::SmallString<64> unglobbed_path;
351     StandardTildeExpressionResolver Resolver;
352     Resolver.ResolveFullPath(user_exe_path, unglobbed_path);
353 
354     if (unglobbed_path.empty())
355       file = FileSpec(user_exe_path);
356     else
357       file = FileSpec(unglobbed_path.c_str());
358   }
359 
360   bool user_exe_path_is_bundle = false;
361   char resolved_bundle_exe_path[PATH_MAX];
362   resolved_bundle_exe_path[0] = '\0';
363   if (file) {
364     if (FileSystem::Instance().IsDirectory(file))
365       user_exe_path_is_bundle = true;
366 
367     if (file.IsRelative() && !user_exe_path.empty()) {
368       llvm::SmallString<64> cwd;
369       if (! llvm::sys::fs::current_path(cwd)) {
370         FileSpec cwd_file(cwd.c_str());
371         cwd_file.AppendPathComponent(file);
372         if (FileSystem::Instance().Exists(cwd_file))
373           file = cwd_file;
374       }
375     }
376 
377     ModuleSP exe_module_sp;
378     if (platform_sp) {
379       FileSpecList executable_search_paths(
380           Target::GetDefaultExecutableSearchPaths());
381       ModuleSpec module_spec(file, arch);
382       error = platform_sp->ResolveExecutable(module_spec, exe_module_sp,
383                                              executable_search_paths.GetSize()
384                                                  ? &executable_search_paths
385                                                  : nullptr);
386     }
387 
388     if (error.Success() && exe_module_sp) {
389       if (exe_module_sp->GetObjectFile() == nullptr) {
390         if (arch.IsValid()) {
391           error.SetErrorStringWithFormat(
392               "\"%s\" doesn't contain architecture %s", file.GetPath().c_str(),
393               arch.GetArchitectureName());
394         } else {
395           error.SetErrorStringWithFormat("unsupported file type \"%s\"",
396                                          file.GetPath().c_str());
397         }
398         return error;
399       }
400       target_sp.reset(new Target(debugger, arch, platform_sp, is_dummy_target));
401       target_sp->SetExecutableModule(exe_module_sp, load_dependent_files);
402       if (user_exe_path_is_bundle)
403         exe_module_sp->GetFileSpec().GetPath(resolved_bundle_exe_path,
404                                              sizeof(resolved_bundle_exe_path));
405     }
406   } else {
407     // No file was specified, just create an empty target with any arch if a
408     // valid arch was specified
409     target_sp.reset(new Target(debugger, arch, platform_sp, is_dummy_target));
410   }
411 
412   if (target_sp) {
413     // Set argv0 with what the user typed, unless the user specified a
414     // directory. If the user specified a directory, then it is probably a
415     // bundle that was resolved and we need to use the resolved bundle path
416     if (!user_exe_path.empty()) {
417       // Use exactly what the user typed as the first argument when we exec or
418       // posix_spawn
419       if (user_exe_path_is_bundle && resolved_bundle_exe_path[0]) {
420         target_sp->SetArg0(resolved_bundle_exe_path);
421       } else {
422         // Use resolved path
423         target_sp->SetArg0(file.GetPath().c_str());
424       }
425     }
426     if (file.GetDirectory()) {
427       FileSpec file_dir;
428       file_dir.GetDirectory() = file.GetDirectory();
429       target_sp->GetExecutableSearchPaths().Append(file_dir);
430     }
431 
432     // Don't put the dummy target in the target list, it's held separately.
433     if (!is_dummy_target) {
434       std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
435       m_selected_target_idx = m_target_list.size();
436       m_target_list.push_back(target_sp);
437       // Now prime this from the dummy target:
438       target_sp->PrimeFromDummyTarget(debugger.GetDummyTarget());
439     } else {
440       m_dummy_target_sp = target_sp;
441     }
442   }
443 
444   return error;
445 }
446 
447 bool TargetList::DeleteTarget(TargetSP &target_sp) {
448   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
449   collection::iterator pos, end = m_target_list.end();
450 
451   for (pos = m_target_list.begin(); pos != end; ++pos) {
452     if (pos->get() == target_sp.get()) {
453       m_target_list.erase(pos);
454       return true;
455     }
456   }
457   return false;
458 }
459 
460 TargetSP TargetList::FindTargetWithExecutableAndArchitecture(
461     const FileSpec &exe_file_spec, const ArchSpec *exe_arch_ptr) const {
462   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
463   TargetSP target_sp;
464   bool full_match = (bool)exe_file_spec.GetDirectory();
465 
466   collection::const_iterator pos, end = m_target_list.end();
467   for (pos = m_target_list.begin(); pos != end; ++pos) {
468     Module *exe_module = (*pos)->GetExecutableModulePointer();
469 
470     if (exe_module) {
471       if (FileSpec::Equal(exe_file_spec, exe_module->GetFileSpec(),
472                           full_match)) {
473         if (exe_arch_ptr) {
474           if (!exe_arch_ptr->IsCompatibleMatch(exe_module->GetArchitecture()))
475             continue;
476         }
477         target_sp = *pos;
478         break;
479       }
480     }
481   }
482   return target_sp;
483 }
484 
485 TargetSP TargetList::FindTargetWithProcessID(lldb::pid_t pid) const {
486   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
487   TargetSP target_sp;
488   collection::const_iterator pos, end = m_target_list.end();
489   for (pos = m_target_list.begin(); pos != end; ++pos) {
490     Process *process = (*pos)->GetProcessSP().get();
491     if (process && process->GetID() == pid) {
492       target_sp = *pos;
493       break;
494     }
495   }
496   return target_sp;
497 }
498 
499 TargetSP TargetList::FindTargetWithProcess(Process *process) const {
500   TargetSP target_sp;
501   if (process) {
502     std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
503     collection::const_iterator pos, end = m_target_list.end();
504     for (pos = m_target_list.begin(); pos != end; ++pos) {
505       if (process == (*pos)->GetProcessSP().get()) {
506         target_sp = *pos;
507         break;
508       }
509     }
510   }
511   return target_sp;
512 }
513 
514 TargetSP TargetList::GetTargetSP(Target *target) const {
515   TargetSP target_sp;
516   if (target) {
517     std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
518     collection::const_iterator pos, end = m_target_list.end();
519     for (pos = m_target_list.begin(); pos != end; ++pos) {
520       if (target == (*pos).get()) {
521         target_sp = *pos;
522         break;
523       }
524     }
525   }
526   return target_sp;
527 }
528 
529 uint32_t TargetList::SendAsyncInterrupt(lldb::pid_t pid) {
530   uint32_t num_async_interrupts_sent = 0;
531 
532   if (pid != LLDB_INVALID_PROCESS_ID) {
533     TargetSP target_sp(FindTargetWithProcessID(pid));
534     if (target_sp) {
535       Process *process = target_sp->GetProcessSP().get();
536       if (process) {
537         process->SendAsyncInterrupt();
538         ++num_async_interrupts_sent;
539       }
540     }
541   } else {
542     // We don't have a valid pid to broadcast to, so broadcast to the target
543     // list's async broadcaster...
544     BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
545   }
546 
547   return num_async_interrupts_sent;
548 }
549 
550 uint32_t TargetList::SignalIfRunning(lldb::pid_t pid, int signo) {
551   uint32_t num_signals_sent = 0;
552   Process *process = nullptr;
553   if (pid == LLDB_INVALID_PROCESS_ID) {
554     // Signal all processes with signal
555     std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
556     collection::iterator pos, end = m_target_list.end();
557     for (pos = m_target_list.begin(); pos != end; ++pos) {
558       process = (*pos)->GetProcessSP().get();
559       if (process) {
560         if (process->IsAlive()) {
561           ++num_signals_sent;
562           process->Signal(signo);
563         }
564       }
565     }
566   } else {
567     // Signal a specific process with signal
568     TargetSP target_sp(FindTargetWithProcessID(pid));
569     if (target_sp) {
570       process = target_sp->GetProcessSP().get();
571       if (process) {
572         if (process->IsAlive()) {
573           ++num_signals_sent;
574           process->Signal(signo);
575         }
576       }
577     }
578   }
579   return num_signals_sent;
580 }
581 
582 int TargetList::GetNumTargets() const {
583   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
584   return m_target_list.size();
585 }
586 
587 lldb::TargetSP TargetList::GetTargetAtIndex(uint32_t idx) const {
588   TargetSP target_sp;
589   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
590   if (idx < m_target_list.size())
591     target_sp = m_target_list[idx];
592   return target_sp;
593 }
594 
595 uint32_t TargetList::GetIndexOfTarget(lldb::TargetSP target_sp) const {
596   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
597   size_t num_targets = m_target_list.size();
598   for (size_t idx = 0; idx < num_targets; idx++) {
599     if (target_sp == m_target_list[idx])
600       return idx;
601   }
602   return UINT32_MAX;
603 }
604 
605 uint32_t TargetList::SetSelectedTarget(Target *target) {
606   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
607   collection::const_iterator pos, begin = m_target_list.begin(),
608                                   end = m_target_list.end();
609   for (pos = begin; pos != end; ++pos) {
610     if (pos->get() == target) {
611       m_selected_target_idx = std::distance(begin, pos);
612       return m_selected_target_idx;
613     }
614   }
615   m_selected_target_idx = 0;
616   return m_selected_target_idx;
617 }
618 
619 lldb::TargetSP TargetList::GetSelectedTarget() {
620   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
621   if (m_selected_target_idx >= m_target_list.size())
622     m_selected_target_idx = 0;
623   return GetTargetAtIndex(m_selected_target_idx);
624 }
625