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