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   auto it = std::find(m_target_list.begin(), m_target_list.end(), target_sp);
409   if (it == m_target_list.end())
410     return false;
411 
412   m_target_list.erase(it);
413   return true;
414 }
415 
416 TargetSP TargetList::FindTargetWithExecutableAndArchitecture(
417     const FileSpec &exe_file_spec, const ArchSpec *exe_arch_ptr) const {
418   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
419   auto it = std::find_if(m_target_list.begin(), m_target_list.end(),
420       [&exe_file_spec, exe_arch_ptr](const TargetSP &item) {
421         Module *exe_module = item->GetExecutableModulePointer();
422         if (!exe_module ||
423             !FileSpec::Match(exe_file_spec, exe_module->GetFileSpec()))
424           return false;
425 
426         return !exe_arch_ptr ||
427                exe_arch_ptr->IsCompatibleMatch(exe_module->GetArchitecture());
428       });
429 
430   if (it != m_target_list.end())
431     return *it;
432 
433   return TargetSP();
434 }
435 
436 TargetSP TargetList::FindTargetWithProcessID(lldb::pid_t pid) const {
437   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
438   auto it = std::find_if(m_target_list.begin(), m_target_list.end(),
439       [pid](const TargetSP &item) {
440         auto *process_ptr = item->GetProcessSP().get();
441         return process_ptr && (process_ptr->GetID() == pid);
442       });
443 
444   if (it != m_target_list.end())
445     return *it;
446 
447   return TargetSP();
448 }
449 
450 TargetSP TargetList::FindTargetWithProcess(Process *process) const {
451   TargetSP target_sp;
452   if (!process)
453     return target_sp;
454 
455   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
456   auto it = std::find_if(m_target_list.begin(), m_target_list.end(),
457       [process](const TargetSP &item) {
458         return item->GetProcessSP().get() == process;
459       });
460 
461   if (it != m_target_list.end())
462     target_sp = *it;
463 
464   return target_sp;
465 }
466 
467 TargetSP TargetList::GetTargetSP(Target *target) const {
468   TargetSP target_sp;
469   if (!target)
470     return target_sp;
471 
472   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
473   auto it = std::find_if(m_target_list.begin(), m_target_list.end(),
474       [target](const TargetSP &item) { return item.get() == target; });
475   if (it != m_target_list.end())
476     target_sp = *it;
477 
478   return target_sp;
479 }
480 
481 uint32_t TargetList::SendAsyncInterrupt(lldb::pid_t pid) {
482   uint32_t num_async_interrupts_sent = 0;
483 
484   if (pid != LLDB_INVALID_PROCESS_ID) {
485     TargetSP target_sp(FindTargetWithProcessID(pid));
486     if (target_sp) {
487       Process *process = target_sp->GetProcessSP().get();
488       if (process) {
489         process->SendAsyncInterrupt();
490         ++num_async_interrupts_sent;
491       }
492     }
493   } else {
494     // We don't have a valid pid to broadcast to, so broadcast to the target
495     // list's async broadcaster...
496     BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
497   }
498 
499   return num_async_interrupts_sent;
500 }
501 
502 uint32_t TargetList::SignalIfRunning(lldb::pid_t pid, int signo) {
503   uint32_t num_signals_sent = 0;
504   Process *process = nullptr;
505   if (pid == LLDB_INVALID_PROCESS_ID) {
506     // Signal all processes with signal
507     std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
508     for (const auto &target_sp : m_target_list) {
509       process = target_sp->GetProcessSP().get();
510       if (process && process->IsAlive()) {
511         ++num_signals_sent;
512         process->Signal(signo);
513       }
514     }
515   } else {
516     // Signal a specific process with signal
517     TargetSP target_sp(FindTargetWithProcessID(pid));
518     if (target_sp) {
519       process = target_sp->GetProcessSP().get();
520       if (process && process->IsAlive()) {
521         ++num_signals_sent;
522         process->Signal(signo);
523       }
524     }
525   }
526   return num_signals_sent;
527 }
528 
529 int TargetList::GetNumTargets() const {
530   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
531   return m_target_list.size();
532 }
533 
534 lldb::TargetSP TargetList::GetTargetAtIndex(uint32_t idx) const {
535   TargetSP target_sp;
536   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
537   if (idx < m_target_list.size())
538     target_sp = m_target_list[idx];
539   return target_sp;
540 }
541 
542 uint32_t TargetList::GetIndexOfTarget(lldb::TargetSP target_sp) const {
543   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
544   auto it = std::find(m_target_list.begin(), m_target_list.end(), target_sp);
545   if (it != m_target_list.end())
546     return std::distance(m_target_list.begin(), it);
547   return UINT32_MAX;
548 }
549 
550 void TargetList::AddTargetInternal(TargetSP target_sp, bool do_select) {
551   lldbassert(std::find(m_target_list.begin(), m_target_list.end(), target_sp) ==
552                  m_target_list.end() &&
553              "target already exists it the list");
554   m_target_list.push_back(std::move(target_sp));
555   if (do_select)
556     SetSelectedTargetInternal(m_target_list.size() - 1);
557 }
558 
559 void TargetList::SetSelectedTargetInternal(uint32_t index) {
560   lldbassert(!m_target_list.empty());
561   m_selected_target_idx = index < m_target_list.size() ? index : 0;
562 }
563 
564 void TargetList::SetSelectedTarget(uint32_t index) {
565   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
566   SetSelectedTargetInternal(index);
567 }
568 
569 void TargetList::SetSelectedTarget(const TargetSP &target_sp) {
570   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
571   auto it = std::find(m_target_list.begin(), m_target_list.end(), target_sp);
572   SetSelectedTargetInternal(std::distance(m_target_list.begin(), it));
573 }
574 
575 lldb::TargetSP TargetList::GetSelectedTarget() {
576   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
577   if (m_selected_target_idx >= m_target_list.size())
578     m_selected_target_idx = 0;
579   return GetTargetAtIndex(m_selected_target_idx);
580 }
581