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