xref: /freebsd-src/contrib/llvm-project/lldb/source/Target/TargetList.cpp (revision 2eb4d8dc723da3cf7d735a3226ae49da4c8c5dbc)
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   LLDB_SCOPED_TIMERF("TargetList::CreateTarget (file = '%s', arch = '%s')",
290                      user_exe_path.str().c_str(),
291                      specified_arch.GetArchitectureName());
292   Status error;
293   const bool is_dummy_target = false;
294 
295   ArchSpec arch(specified_arch);
296 
297   if (arch.IsValid()) {
298     if (!platform_sp ||
299         !platform_sp->IsCompatibleArchitecture(arch, false, nullptr))
300       platform_sp = Platform::GetPlatformForArchitecture(specified_arch, &arch);
301   }
302 
303   if (!platform_sp)
304     platform_sp = debugger.GetPlatformList().GetSelectedPlatform();
305 
306   if (!arch.IsValid())
307     arch = specified_arch;
308 
309   FileSpec file(user_exe_path);
310   if (!FileSystem::Instance().Exists(file) && user_exe_path.startswith("~")) {
311     // we want to expand the tilde but we don't want to resolve any symbolic
312     // links so we can't use the FileSpec constructor's resolve flag
313     llvm::SmallString<64> unglobbed_path;
314     StandardTildeExpressionResolver Resolver;
315     Resolver.ResolveFullPath(user_exe_path, unglobbed_path);
316 
317     if (unglobbed_path.empty())
318       file = FileSpec(user_exe_path);
319     else
320       file = FileSpec(unglobbed_path.c_str());
321   }
322 
323   bool user_exe_path_is_bundle = false;
324   char resolved_bundle_exe_path[PATH_MAX];
325   resolved_bundle_exe_path[0] = '\0';
326   if (file) {
327     if (FileSystem::Instance().IsDirectory(file))
328       user_exe_path_is_bundle = true;
329 
330     if (file.IsRelative() && !user_exe_path.empty()) {
331       llvm::SmallString<64> cwd;
332       if (! llvm::sys::fs::current_path(cwd)) {
333         FileSpec cwd_file(cwd.c_str());
334         cwd_file.AppendPathComponent(file);
335         if (FileSystem::Instance().Exists(cwd_file))
336           file = cwd_file;
337       }
338     }
339 
340     ModuleSP exe_module_sp;
341     if (platform_sp) {
342       FileSpecList executable_search_paths(
343           Target::GetDefaultExecutableSearchPaths());
344       ModuleSpec module_spec(file, arch);
345       error = platform_sp->ResolveExecutable(module_spec, exe_module_sp,
346                                              executable_search_paths.GetSize()
347                                                  ? &executable_search_paths
348                                                  : nullptr);
349     }
350 
351     if (error.Success() && exe_module_sp) {
352       if (exe_module_sp->GetObjectFile() == nullptr) {
353         if (arch.IsValid()) {
354           error.SetErrorStringWithFormat(
355               "\"%s\" doesn't contain architecture %s", file.GetPath().c_str(),
356               arch.GetArchitectureName());
357         } else {
358           error.SetErrorStringWithFormat("unsupported file type \"%s\"",
359                                          file.GetPath().c_str());
360         }
361         return error;
362       }
363       target_sp.reset(new Target(debugger, arch, platform_sp, is_dummy_target));
364       target_sp->SetExecutableModule(exe_module_sp, load_dependent_files);
365       if (user_exe_path_is_bundle)
366         exe_module_sp->GetFileSpec().GetPath(resolved_bundle_exe_path,
367                                              sizeof(resolved_bundle_exe_path));
368       if (target_sp->GetPreloadSymbols())
369         exe_module_sp->PreloadSymbols();
370     }
371   } else {
372     // No file was specified, just create an empty target with any arch if a
373     // valid arch was specified
374     target_sp.reset(new Target(debugger, arch, platform_sp, is_dummy_target));
375   }
376 
377   if (!target_sp)
378     return error;
379 
380   // Set argv0 with what the user typed, unless the user specified a
381   // directory. If the user specified a directory, then it is probably a
382   // bundle that was resolved and we need to use the resolved bundle path
383   if (!user_exe_path.empty()) {
384     // Use exactly what the user typed as the first argument when we exec or
385     // posix_spawn
386     if (user_exe_path_is_bundle && resolved_bundle_exe_path[0]) {
387       target_sp->SetArg0(resolved_bundle_exe_path);
388     } else {
389       // Use resolved path
390       target_sp->SetArg0(file.GetPath().c_str());
391     }
392   }
393   if (file.GetDirectory()) {
394     FileSpec file_dir;
395     file_dir.GetDirectory() = file.GetDirectory();
396     target_sp->AppendExecutableSearchPaths(file_dir);
397   }
398 
399   // Now prime this from the dummy target:
400   target_sp->PrimeFromDummyTarget(debugger.GetDummyTarget());
401 
402   return error;
403 }
404 
405 bool TargetList::DeleteTarget(TargetSP &target_sp) {
406   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
407   auto it = std::find(m_target_list.begin(), m_target_list.end(), target_sp);
408   if (it == m_target_list.end())
409     return false;
410 
411   m_target_list.erase(it);
412   return true;
413 }
414 
415 TargetSP TargetList::FindTargetWithExecutableAndArchitecture(
416     const FileSpec &exe_file_spec, const ArchSpec *exe_arch_ptr) const {
417   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
418   auto it = std::find_if(m_target_list.begin(), m_target_list.end(),
419       [&exe_file_spec, exe_arch_ptr](const TargetSP &item) {
420         Module *exe_module = item->GetExecutableModulePointer();
421         if (!exe_module ||
422             !FileSpec::Match(exe_file_spec, exe_module->GetFileSpec()))
423           return false;
424 
425         return !exe_arch_ptr ||
426                exe_arch_ptr->IsCompatibleMatch(exe_module->GetArchitecture());
427       });
428 
429   if (it != m_target_list.end())
430     return *it;
431 
432   return TargetSP();
433 }
434 
435 TargetSP TargetList::FindTargetWithProcessID(lldb::pid_t pid) const {
436   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
437   auto it = std::find_if(m_target_list.begin(), m_target_list.end(),
438       [pid](const TargetSP &item) {
439         auto *process_ptr = item->GetProcessSP().get();
440         return process_ptr && (process_ptr->GetID() == pid);
441       });
442 
443   if (it != m_target_list.end())
444     return *it;
445 
446   return TargetSP();
447 }
448 
449 TargetSP TargetList::FindTargetWithProcess(Process *process) const {
450   TargetSP target_sp;
451   if (!process)
452     return target_sp;
453 
454   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
455   auto it = std::find_if(m_target_list.begin(), m_target_list.end(),
456       [process](const TargetSP &item) {
457         return item->GetProcessSP().get() == process;
458       });
459 
460   if (it != m_target_list.end())
461     target_sp = *it;
462 
463   return target_sp;
464 }
465 
466 TargetSP TargetList::GetTargetSP(Target *target) const {
467   TargetSP target_sp;
468   if (!target)
469     return target_sp;
470 
471   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
472   auto it = std::find_if(m_target_list.begin(), m_target_list.end(),
473       [target](const TargetSP &item) { return item.get() == target; });
474   if (it != m_target_list.end())
475     target_sp = *it;
476 
477   return target_sp;
478 }
479 
480 uint32_t TargetList::SendAsyncInterrupt(lldb::pid_t pid) {
481   uint32_t num_async_interrupts_sent = 0;
482 
483   if (pid != LLDB_INVALID_PROCESS_ID) {
484     TargetSP target_sp(FindTargetWithProcessID(pid));
485     if (target_sp) {
486       Process *process = target_sp->GetProcessSP().get();
487       if (process) {
488         process->SendAsyncInterrupt();
489         ++num_async_interrupts_sent;
490       }
491     }
492   } else {
493     // We don't have a valid pid to broadcast to, so broadcast to the target
494     // list's async broadcaster...
495     BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
496   }
497 
498   return num_async_interrupts_sent;
499 }
500 
501 uint32_t TargetList::SignalIfRunning(lldb::pid_t pid, int signo) {
502   uint32_t num_signals_sent = 0;
503   Process *process = nullptr;
504   if (pid == LLDB_INVALID_PROCESS_ID) {
505     // Signal all processes with signal
506     std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
507     for (const auto &target_sp : m_target_list) {
508       process = target_sp->GetProcessSP().get();
509       if (process && process->IsAlive()) {
510         ++num_signals_sent;
511         process->Signal(signo);
512       }
513     }
514   } else {
515     // Signal a specific process with signal
516     TargetSP target_sp(FindTargetWithProcessID(pid));
517     if (target_sp) {
518       process = target_sp->GetProcessSP().get();
519       if (process && process->IsAlive()) {
520         ++num_signals_sent;
521         process->Signal(signo);
522       }
523     }
524   }
525   return num_signals_sent;
526 }
527 
528 int TargetList::GetNumTargets() const {
529   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
530   return m_target_list.size();
531 }
532 
533 lldb::TargetSP TargetList::GetTargetAtIndex(uint32_t idx) const {
534   TargetSP target_sp;
535   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
536   if (idx < m_target_list.size())
537     target_sp = m_target_list[idx];
538   return target_sp;
539 }
540 
541 uint32_t TargetList::GetIndexOfTarget(lldb::TargetSP target_sp) const {
542   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
543   auto it = std::find(m_target_list.begin(), m_target_list.end(), target_sp);
544   if (it != m_target_list.end())
545     return std::distance(m_target_list.begin(), it);
546   return UINT32_MAX;
547 }
548 
549 void TargetList::AddTargetInternal(TargetSP target_sp, bool do_select) {
550   lldbassert(std::find(m_target_list.begin(), m_target_list.end(), target_sp) ==
551                  m_target_list.end() &&
552              "target already exists it the list");
553   m_target_list.push_back(std::move(target_sp));
554   if (do_select)
555     SetSelectedTargetInternal(m_target_list.size() - 1);
556 }
557 
558 void TargetList::SetSelectedTargetInternal(uint32_t index) {
559   lldbassert(!m_target_list.empty());
560   m_selected_target_idx = index < m_target_list.size() ? index : 0;
561 }
562 
563 void TargetList::SetSelectedTarget(uint32_t index) {
564   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
565   SetSelectedTargetInternal(index);
566 }
567 
568 void TargetList::SetSelectedTarget(const TargetSP &target_sp) {
569   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
570   auto it = std::find(m_target_list.begin(), m_target_list.end(), target_sp);
571   SetSelectedTargetInternal(std::distance(m_target_list.begin(), it));
572 }
573 
574 lldb::TargetSP TargetList::GetSelectedTarget() {
575   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
576   if (m_selected_target_idx >= m_target_list.size())
577     m_selected_target_idx = 0;
578   return GetTargetAtIndex(m_selected_target_idx);
579 }
580