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