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 Status TargetList::CreateTarget(Debugger &debugger,
46                                 llvm::StringRef user_exe_path,
47                                 llvm::StringRef triple_str,
48                                 LoadDependentFiles load_dependent_files,
49                                 const OptionGroupPlatform *platform_options,
50                                 TargetSP &target_sp) {
51   auto result = TargetList::CreateTargetInternal(
52       debugger, user_exe_path, triple_str, load_dependent_files,
53       platform_options, target_sp);
54 
55   if (target_sp && result.Success())
56     AddTargetInternal(target_sp, /*do_select*/ true);
57   return result;
58 }
59 
60 Status TargetList::CreateTarget(Debugger &debugger,
61                                 llvm::StringRef user_exe_path,
62                                 const ArchSpec &specified_arch,
63                                 LoadDependentFiles load_dependent_files,
64                                 PlatformSP &platform_sp, TargetSP &target_sp) {
65   auto result = TargetList::CreateTargetInternal(
66       debugger, user_exe_path, specified_arch, load_dependent_files,
67       platform_sp, target_sp);
68 
69   if (target_sp && result.Success())
70     AddTargetInternal(target_sp, /*do_select*/ true);
71   return result;
72 }
73 
74 Status TargetList::CreateTargetInternal(
75     Debugger &debugger, llvm::StringRef user_exe_path,
76     llvm::StringRef triple_str, LoadDependentFiles load_dependent_files,
77     const OptionGroupPlatform *platform_options, TargetSP &target_sp) {
78   Status error;
79 
80   // Let's start by looking at the selected platform.
81   PlatformSP platform_sp = debugger.GetPlatformList().GetSelectedPlatform();
82 
83   // This variable corresponds to the architecture specified by the triple
84   // string. If that string was empty the currently selected platform will
85   // determine the architecture.
86   const ArchSpec arch(triple_str);
87   if (!triple_str.empty() && !arch.IsValid()) {
88     error.SetErrorStringWithFormat("invalid triple '%s'",
89                                    triple_str.str().c_str());
90     return error;
91   }
92 
93   ArchSpec platform_arch(arch);
94 
95   // Create a new platform if a platform was specified in the platform options
96   // and doesn't match the selected platform.
97   if (platform_options && platform_options->PlatformWasSpecified() &&
98       !platform_options->PlatformMatches(platform_sp)) {
99     const bool select_platform = true;
100     platform_sp = platform_options->CreatePlatformWithOptions(
101         debugger.GetCommandInterpreter(), arch, select_platform, error,
102         platform_arch);
103     if (!platform_sp)
104       return error;
105   }
106 
107   bool prefer_platform_arch = false;
108   auto update_platform_arch = [&](const ArchSpec &module_arch) {
109     // If the OS or vendor weren't specified, then adopt the module's
110     // architecture so that the platform matching can be more accurate.
111     if (!platform_arch.TripleOSWasSpecified() ||
112         !platform_arch.TripleVendorWasSpecified()) {
113       prefer_platform_arch = true;
114       platform_arch = module_arch;
115     }
116   };
117 
118   if (!user_exe_path.empty()) {
119     ModuleSpec module_spec(FileSpec(user_exe_path, FileSpec::Style::native));
120     FileSystem::Instance().Resolve(module_spec.GetFileSpec());
121     // Resolve the executable in case we are given a path to a application
122     // bundle like a .app bundle on MacOSX.
123     Host::ResolveExecutableInBundle(module_spec.GetFileSpec());
124 
125     lldb::offset_t file_offset = 0;
126     lldb::offset_t file_size = 0;
127     ModuleSpecList module_specs;
128     const size_t num_specs = ObjectFile::GetModuleSpecifications(
129         module_spec.GetFileSpec(), file_offset, file_size, module_specs);
130 
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               update_platform_arch(matching_module_spec.GetArchitecture());
143             } else {
144               StreamString platform_arch_strm;
145               StreamString module_arch_strm;
146 
147               platform_arch.DumpTriple(platform_arch_strm.AsRawOstream());
148               matching_module_spec.GetArchitecture().DumpTriple(
149                   module_arch_strm.AsRawOstream());
150               error.SetErrorStringWithFormat(
151                   "the specified architecture '%s' is not compatible with '%s' "
152                   "in '%s'",
153                   platform_arch_strm.GetData(), module_arch_strm.GetData(),
154                   module_spec.GetFileSpec().GetPath().c_str());
155               return error;
156             }
157           } else {
158             // Only one arch and none was specified.
159             prefer_platform_arch = true;
160             platform_arch = matching_module_spec.GetArchitecture();
161           }
162         }
163       } else if (arch.IsValid()) {
164         // Fat binary. A (valid) architecture was specified.
165         module_spec.GetArchitecture() = arch;
166         if (module_specs.FindMatchingModuleSpec(module_spec,
167                                                 matching_module_spec))
168             update_platform_arch(matching_module_spec.GetArchitecture());
169       } else {
170         // Fat binary. No architecture specified, check if there is
171         // only one platform for all of the architectures.
172         PlatformSP host_platform_sp = Platform::GetHostPlatform();
173         std::vector<PlatformSP> platforms;
174         for (size_t i = 0; i < num_specs; ++i) {
175           ModuleSpec module_spec;
176           if (module_specs.GetModuleSpecAtIndex(i, module_spec)) {
177             // First consider the platform specified by the user, if any, and
178             // the selected platform otherwise.
179             if (platform_sp) {
180               if (platform_sp->IsCompatibleArchitecture(
181                       module_spec.GetArchitecture(), false, nullptr)) {
182                 platforms.push_back(platform_sp);
183                 continue;
184               }
185             }
186 
187             // Now consider the host platform if it is different from the
188             // specified/selected platform.
189             if (host_platform_sp &&
190                 (!platform_sp ||
191                  host_platform_sp->GetName() != platform_sp->GetName())) {
192               if (host_platform_sp->IsCompatibleArchitecture(
193                       module_spec.GetArchitecture(), false, nullptr)) {
194                 platforms.push_back(host_platform_sp);
195                 continue;
196               }
197             }
198 
199             // Finally find a platform that matches the architecture in the
200             // executable file.
201             PlatformSP fallback_platform_sp(
202                 Platform::GetPlatformForArchitecture(
203                     module_spec.GetArchitecture(), nullptr));
204             if (fallback_platform_sp) {
205               platforms.push_back(fallback_platform_sp);
206             }
207           }
208         }
209 
210         Platform *platform_ptr = nullptr;
211         bool more_than_one_platforms = false;
212         for (const auto &the_platform_sp : platforms) {
213           if (platform_ptr) {
214             if (platform_ptr->GetName() != the_platform_sp->GetName()) {
215               more_than_one_platforms = true;
216               platform_ptr = nullptr;
217               break;
218             }
219           } else {
220             platform_ptr = the_platform_sp.get();
221           }
222         }
223 
224         if (platform_ptr) {
225           // All platforms for all modules in the executable match, so we can
226           // select this platform.
227           platform_sp = platforms.front();
228         } else if (!more_than_one_platforms) {
229           // No platforms claim to support this file.
230           error.SetErrorString("no matching platforms found for this file");
231           return error;
232         } else {
233           // More than one platform claims to support this file.
234           StreamString error_strm;
235           std::set<Platform *> platform_set;
236           error_strm.Printf(
237               "more than one platform supports this executable (");
238           for (const auto &the_platform_sp : platforms) {
239             if (platform_set.find(the_platform_sp.get()) ==
240                 platform_set.end()) {
241               if (!platform_set.empty())
242                 error_strm.PutCString(", ");
243               error_strm.PutCString(the_platform_sp->GetName().GetCString());
244               platform_set.insert(the_platform_sp.get());
245             }
246           }
247           error_strm.Printf("), specify an architecture to disambiguate");
248           error.SetErrorString(error_strm.GetString());
249           return error;
250         }
251       }
252     }
253   }
254 
255   // If we have a valid architecture, make sure the current platform is
256   // compatible with that architecture.
257   if (!prefer_platform_arch && arch.IsValid()) {
258     if (!platform_sp->IsCompatibleArchitecture(arch, false, nullptr)) {
259       platform_sp = Platform::GetPlatformForArchitecture(arch, &platform_arch);
260       if (platform_sp)
261         debugger.GetPlatformList().SetSelectedPlatform(platform_sp);
262     }
263   } else if (platform_arch.IsValid()) {
264     // If "arch" isn't valid, yet "platform_arch" is, it means we have an
265     // executable file with a single architecture which should be used.
266     ArchSpec fixed_platform_arch;
267     if (!platform_sp->IsCompatibleArchitecture(platform_arch, false, nullptr)) {
268       platform_sp = Platform::GetPlatformForArchitecture(platform_arch,
269                                                          &fixed_platform_arch);
270       if (platform_sp)
271         debugger.GetPlatformList().SetSelectedPlatform(platform_sp);
272     }
273   }
274 
275   if (!platform_arch.IsValid())
276     platform_arch = arch;
277 
278   return TargetList::CreateTargetInternal(debugger, user_exe_path,
279                                           platform_arch, load_dependent_files,
280                                           platform_sp, target_sp);
281 }
282 
283 Status TargetList::CreateTargetInternal(Debugger &debugger,
284                                         llvm::StringRef user_exe_path,
285                                         const ArchSpec &specified_arch,
286                                         LoadDependentFiles load_dependent_files,
287                                         lldb::PlatformSP &platform_sp,
288                                         lldb::TargetSP &target_sp) {
289   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
290   Timer scoped_timer(
291       func_cat, "TargetList::CreateTarget (file = '%s', arch = '%s')",
292       user_exe_path.str().c_str(), specified_arch.GetArchitectureName());
293   Status error;
294   const bool is_dummy_target = false;
295 
296   ArchSpec arch(specified_arch);
297 
298   if (arch.IsValid()) {
299     if (!platform_sp ||
300         !platform_sp->IsCompatibleArchitecture(arch, false, nullptr))
301       platform_sp = Platform::GetPlatformForArchitecture(specified_arch, &arch);
302   }
303 
304   if (!platform_sp)
305     platform_sp = debugger.GetPlatformList().GetSelectedPlatform();
306 
307   if (!arch.IsValid())
308     arch = specified_arch;
309 
310   FileSpec file(user_exe_path);
311   if (!FileSystem::Instance().Exists(file) && user_exe_path.startswith("~")) {
312     // we want to expand the tilde but we don't want to resolve any symbolic
313     // links so we can't use the FileSpec constructor's resolve flag
314     llvm::SmallString<64> unglobbed_path;
315     StandardTildeExpressionResolver Resolver;
316     Resolver.ResolveFullPath(user_exe_path, unglobbed_path);
317 
318     if (unglobbed_path.empty())
319       file = FileSpec(user_exe_path);
320     else
321       file = FileSpec(unglobbed_path.c_str());
322   }
323 
324   bool user_exe_path_is_bundle = false;
325   char resolved_bundle_exe_path[PATH_MAX];
326   resolved_bundle_exe_path[0] = '\0';
327   if (file) {
328     if (FileSystem::Instance().IsDirectory(file))
329       user_exe_path_is_bundle = true;
330 
331     if (file.IsRelative() && !user_exe_path.empty()) {
332       llvm::SmallString<64> cwd;
333       if (! llvm::sys::fs::current_path(cwd)) {
334         FileSpec cwd_file(cwd.c_str());
335         cwd_file.AppendPathComponent(file);
336         if (FileSystem::Instance().Exists(cwd_file))
337           file = cwd_file;
338       }
339     }
340 
341     ModuleSP exe_module_sp;
342     if (platform_sp) {
343       FileSpecList executable_search_paths(
344           Target::GetDefaultExecutableSearchPaths());
345       ModuleSpec module_spec(file, arch);
346       error = platform_sp->ResolveExecutable(module_spec, exe_module_sp,
347                                              executable_search_paths.GetSize()
348                                                  ? &executable_search_paths
349                                                  : nullptr);
350     }
351 
352     if (error.Success() && exe_module_sp) {
353       if (exe_module_sp->GetObjectFile() == nullptr) {
354         if (arch.IsValid()) {
355           error.SetErrorStringWithFormat(
356               "\"%s\" doesn't contain architecture %s", file.GetPath().c_str(),
357               arch.GetArchitectureName());
358         } else {
359           error.SetErrorStringWithFormat("unsupported file type \"%s\"",
360                                          file.GetPath().c_str());
361         }
362         return error;
363       }
364       target_sp.reset(new Target(debugger, arch, platform_sp, is_dummy_target));
365       target_sp->SetExecutableModule(exe_module_sp, load_dependent_files);
366       if (user_exe_path_is_bundle)
367         exe_module_sp->GetFileSpec().GetPath(resolved_bundle_exe_path,
368                                              sizeof(resolved_bundle_exe_path));
369       if (target_sp->GetPreloadSymbols())
370         exe_module_sp->PreloadSymbols();
371     }
372   } else {
373     // No file was specified, just create an empty target with any arch if a
374     // valid arch was specified
375     target_sp.reset(new Target(debugger, arch, platform_sp, is_dummy_target));
376   }
377 
378   if (!target_sp)
379     return error;
380 
381   // Set argv0 with what the user typed, unless the user specified a
382   // directory. If the user specified a directory, then it is probably a
383   // bundle that was resolved and we need to use the resolved bundle path
384   if (!user_exe_path.empty()) {
385     // Use exactly what the user typed as the first argument when we exec or
386     // posix_spawn
387     if (user_exe_path_is_bundle && resolved_bundle_exe_path[0]) {
388       target_sp->SetArg0(resolved_bundle_exe_path);
389     } else {
390       // Use resolved path
391       target_sp->SetArg0(file.GetPath().c_str());
392     }
393   }
394   if (file.GetDirectory()) {
395     FileSpec file_dir;
396     file_dir.GetDirectory() = file.GetDirectory();
397     target_sp->AppendExecutableSearchPaths(file_dir);
398   }
399 
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 void TargetList::AddTargetInternal(TargetSP target_sp, bool do_select) {
562   lldbassert(std::find(m_target_list.begin(), m_target_list.end(), target_sp) ==
563                  m_target_list.end() &&
564              "target already exists it the list");
565   m_target_list.push_back(std::move(target_sp));
566   if (do_select)
567     SetSelectedTargetInternal(m_target_list.size() - 1);
568 }
569 
570 void TargetList::SetSelectedTargetInternal(uint32_t index) {
571   lldbassert(!m_target_list.empty());
572   m_selected_target_idx = index < m_target_list.size() ? index : 0;
573 }
574 
575 void TargetList::SetSelectedTarget(uint32_t index) {
576   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
577   SetSelectedTargetInternal(index);
578 }
579 
580 void TargetList::SetSelectedTarget(const TargetSP &target_sp) {
581   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
582   auto it = std::find(m_target_list.begin(), m_target_list.end(), target_sp);
583   SetSelectedTargetInternal(std::distance(m_target_list.begin(), it));
584 }
585 
586 lldb::TargetSP TargetList::GetSelectedTarget() {
587   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
588   if (m_selected_target_idx >= m_target_list.size())
589     m_selected_target_idx = 0;
590   return GetTargetAtIndex(m_selected_target_idx);
591 }
592