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