]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Target/TargetList.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Target / TargetList.cpp
1 //===-- TargetList.cpp ------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "lldb/Target/TargetList.h"
11 #include "lldb/Core/Debugger.h"
12 #include "lldb/Core/Module.h"
13 #include "lldb/Core/ModuleSpec.h"
14 #include "lldb/Host/Host.h"
15 #include "lldb/Host/HostInfo.h"
16 #include "lldb/Interpreter/CommandInterpreter.h"
17 #include "lldb/Interpreter/OptionGroupPlatform.h"
18 #include "lldb/Symbol/ObjectFile.h"
19 #include "lldb/Target/Platform.h"
20 #include "lldb/Target/Process.h"
21 #include "lldb/Utility/Broadcaster.h"
22 #include "lldb/Utility/Event.h"
23 #include "lldb/Utility/State.h"
24 #include "lldb/Utility/TildeExpressionResolver.h"
25 #include "lldb/Utility/Timer.h"
26
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/Support/FileSystem.h"
29
30 using namespace lldb;
31 using namespace lldb_private;
32
33 ConstString &TargetList::GetStaticBroadcasterClass() {
34   static ConstString class_name("lldb.targetList");
35   return class_name;
36 }
37
38 //----------------------------------------------------------------------
39 // TargetList constructor
40 //----------------------------------------------------------------------
41 TargetList::TargetList(Debugger &debugger)
42     : Broadcaster(debugger.GetBroadcasterManager(),
43                   TargetList::GetStaticBroadcasterClass().AsCString()),
44       m_target_list(), m_target_list_mutex(), m_selected_target_idx(0) {
45   CheckInWithManager();
46 }
47
48 //----------------------------------------------------------------------
49 // Destructor
50 //----------------------------------------------------------------------
51 TargetList::~TargetList() {
52   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
53   m_target_list.clear();
54 }
55
56 Status TargetList::CreateTarget(Debugger &debugger,
57                                 llvm::StringRef user_exe_path,
58                                 llvm::StringRef triple_str,
59                                 LoadDependentFiles load_dependent_files,
60                                 const OptionGroupPlatform *platform_options,
61                                 TargetSP &target_sp) {
62   return CreateTargetInternal(debugger, user_exe_path, triple_str,
63                               load_dependent_files, platform_options, target_sp,
64                               false);
65 }
66
67 Status TargetList::CreateTarget(Debugger &debugger,
68                                 llvm::StringRef user_exe_path,
69                                 const ArchSpec &specified_arch,
70                                 LoadDependentFiles load_dependent_files,
71                                 PlatformSP &platform_sp, TargetSP &target_sp) {
72   return CreateTargetInternal(debugger, user_exe_path, specified_arch,
73                               load_dependent_files, platform_sp, target_sp,
74                               false);
75 }
76
77 Status TargetList::CreateTargetInternal(
78     Debugger &debugger, llvm::StringRef user_exe_path,
79     llvm::StringRef triple_str, LoadDependentFiles load_dependent_files,
80     const OptionGroupPlatform *platform_options, TargetSP &target_sp,
81     bool is_dummy_target) {
82   Status error;
83   PlatformSP platform_sp;
84
85   // This is purposely left empty unless it is specified by triple_cstr. If not
86   // initialized via triple_cstr, then the currently selected platform will set
87   // the architecture correctly.
88   const ArchSpec arch(triple_str);
89   if (!triple_str.empty()) {
90     if (!arch.IsValid()) {
91       error.SetErrorStringWithFormat("invalid triple '%s'",
92                                      triple_str.str().c_str());
93       return error;
94     }
95   }
96
97   ArchSpec platform_arch(arch);
98
99   bool prefer_platform_arch = false;
100
101   CommandInterpreter &interpreter = debugger.GetCommandInterpreter();
102
103   // let's see if there is already an existing platform before we go creating
104   // another...
105   platform_sp = debugger.GetPlatformList().GetSelectedPlatform();
106
107   if (platform_options && platform_options->PlatformWasSpecified()) {
108     // Create a new platform if it doesn't match the selected platform
109     if (!platform_options->PlatformMatches(platform_sp)) {
110       const bool select_platform = true;
111       platform_sp = platform_options->CreatePlatformWithOptions(
112           interpreter, arch, select_platform, error, platform_arch);
113       if (!platform_sp)
114         return error;
115     }
116   }
117
118   if (!user_exe_path.empty()) {
119     ModuleSpecList module_specs;
120     ModuleSpec module_spec;
121     module_spec.GetFileSpec().SetFile(user_exe_path, FileSpec::Style::native);
122     FileSystem::Instance().Resolve(module_spec.GetFileSpec());
123
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     const size_t num_specs = ObjectFile::GetModuleSpecifications(
131         module_spec.GetFileSpec(), file_offset, file_size, module_specs);
132     if (num_specs > 0) {
133       ModuleSpec matching_module_spec;
134
135       if (num_specs == 1) {
136         if (module_specs.GetModuleSpecAtIndex(0, matching_module_spec)) {
137           if (platform_arch.IsValid()) {
138             if (platform_arch.IsCompatibleMatch(
139                     matching_module_spec.GetArchitecture())) {
140               // If the OS or vendor weren't specified, then adopt the module's
141               // architecture so that the platform matching can be more
142               // accurate
143               if (!platform_arch.TripleOSWasSpecified() ||
144                   !platform_arch.TripleVendorWasSpecified()) {
145                 prefer_platform_arch = true;
146                 platform_arch = matching_module_spec.GetArchitecture();
147               }
148             } else {
149               StreamString platform_arch_strm;
150               StreamString module_arch_strm;
151
152               platform_arch.DumpTriple(platform_arch_strm);
153               matching_module_spec.GetArchitecture().DumpTriple(
154                   module_arch_strm);
155               error.SetErrorStringWithFormat(
156                   "the specified architecture '%s' is not compatible with '%s' "
157                   "in '%s'",
158                   platform_arch_strm.GetData(), module_arch_strm.GetData(),
159                   module_spec.GetFileSpec().GetPath().c_str());
160               return error;
161             }
162           } else {
163             // Only one arch and none was specified
164             prefer_platform_arch = true;
165             platform_arch = matching_module_spec.GetArchitecture();
166           }
167         }
168       } else {
169         if (arch.IsValid()) {
170           module_spec.GetArchitecture() = arch;
171           if (module_specs.FindMatchingModuleSpec(module_spec,
172                                                   matching_module_spec)) {
173             prefer_platform_arch = true;
174             platform_arch = matching_module_spec.GetArchitecture();
175           }
176         } else {
177           // No architecture specified, check if there is only one platform for
178           // all of the architectures.
179
180           typedef std::vector<PlatformSP> PlatformList;
181           PlatformList platforms;
182           PlatformSP host_platform_sp = Platform::GetHostPlatform();
183           for (size_t i = 0; i < num_specs; ++i) {
184             ModuleSpec module_spec;
185             if (module_specs.GetModuleSpecAtIndex(i, module_spec)) {
186               // See if there was a selected platform and check that first
187               // since the user may have specified it.
188               if (platform_sp) {
189                 if (platform_sp->IsCompatibleArchitecture(
190                         module_spec.GetArchitecture(), false, nullptr)) {
191                   platforms.push_back(platform_sp);
192                   continue;
193                 }
194               }
195
196               // Next check the host platform it if wasn't already checked
197               // above
198               if (host_platform_sp &&
199                   (!platform_sp ||
200                    host_platform_sp->GetName() != platform_sp->GetName())) {
201                 if (host_platform_sp->IsCompatibleArchitecture(
202                         module_spec.GetArchitecture(), false, nullptr)) {
203                   platforms.push_back(host_platform_sp);
204                   continue;
205                 }
206               }
207
208               // Just find a platform that matches the architecture in the
209               // executable file
210               PlatformSP fallback_platform_sp(
211                   Platform::GetPlatformForArchitecture(
212                       module_spec.GetArchitecture(), nullptr));
213               if (fallback_platform_sp) {
214                 platforms.push_back(fallback_platform_sp);
215               }
216             }
217           }
218
219           Platform *platform_ptr = nullptr;
220           bool more_than_one_platforms = false;
221           for (const auto &the_platform_sp : platforms) {
222             if (platform_ptr) {
223               if (platform_ptr->GetName() != the_platform_sp->GetName()) {
224                 more_than_one_platforms = true;
225                 platform_ptr = nullptr;
226                 break;
227               }
228             } else {
229               platform_ptr = the_platform_sp.get();
230             }
231           }
232
233           if (platform_ptr) {
234             // All platforms for all modules in the executable match, so we can
235             // select this platform
236             platform_sp = platforms.front();
237           } else if (!more_than_one_platforms) {
238             // No platforms claim to support this file
239             error.SetErrorString("No matching platforms found for this file, "
240                                  "specify one with the --platform option");
241             return error;
242           } else {
243             // More than one platform claims to support this file, so the
244             // --platform option must be specified
245             StreamString error_strm;
246             std::set<Platform *> platform_set;
247             error_strm.Printf(
248                 "more than one platform supports this executable (");
249             for (const auto &the_platform_sp : platforms) {
250               if (platform_set.find(the_platform_sp.get()) ==
251                   platform_set.end()) {
252                 if (!platform_set.empty())
253                   error_strm.PutCString(", ");
254                 error_strm.PutCString(the_platform_sp->GetName().GetCString());
255                 platform_set.insert(the_platform_sp.get());
256               }
257             }
258             error_strm.Printf(
259                 "), use the --platform option to specify a platform");
260             error.SetErrorString(error_strm.GetString());
261             return error;
262           }
263         }
264       }
265     }
266   }
267
268   // If we have a valid architecture, make sure the current platform is
269   // compatible with that architecture
270   if (!prefer_platform_arch && arch.IsValid()) {
271     if (!platform_sp->IsCompatibleArchitecture(arch, false, &platform_arch)) {
272       platform_sp = Platform::GetPlatformForArchitecture(arch, &platform_arch);
273       if (!is_dummy_target && platform_sp)
274         debugger.GetPlatformList().SetSelectedPlatform(platform_sp);
275     }
276   } else if (platform_arch.IsValid()) {
277     // if "arch" isn't valid, yet "platform_arch" is, it means we have an
278     // executable file with a single architecture which should be used
279     ArchSpec fixed_platform_arch;
280     if (!platform_sp->IsCompatibleArchitecture(platform_arch, false,
281                                                &fixed_platform_arch)) {
282       platform_sp = Platform::GetPlatformForArchitecture(platform_arch,
283                                                          &fixed_platform_arch);
284       if (!is_dummy_target && platform_sp)
285         debugger.GetPlatformList().SetSelectedPlatform(platform_sp);
286     }
287   }
288
289   if (!platform_arch.IsValid())
290     platform_arch = arch;
291
292   error = TargetList::CreateTargetInternal(
293       debugger, user_exe_path, platform_arch, load_dependent_files, platform_sp,
294       target_sp, is_dummy_target);
295   return error;
296 }
297
298 lldb::TargetSP TargetList::GetDummyTarget(lldb_private::Debugger &debugger) {
299   // FIXME: Maybe the dummy target should be per-Debugger
300   if (!m_dummy_target_sp || !m_dummy_target_sp->IsValid()) {
301     ArchSpec arch(Target::GetDefaultArchitecture());
302     if (!arch.IsValid())
303       arch = HostInfo::GetArchitecture();
304     Status err = CreateDummyTarget(
305         debugger, arch.GetTriple().getTriple().c_str(), m_dummy_target_sp);
306   }
307
308   return m_dummy_target_sp;
309 }
310
311 Status TargetList::CreateDummyTarget(Debugger &debugger,
312                                      llvm::StringRef specified_arch_name,
313                                      lldb::TargetSP &target_sp) {
314   PlatformSP host_platform_sp(Platform::GetHostPlatform());
315   return CreateTargetInternal(
316       debugger, (const char *)nullptr, specified_arch_name, eLoadDependentsNo,
317       (const OptionGroupPlatform *)nullptr, target_sp, true);
318 }
319
320 Status TargetList::CreateTargetInternal(Debugger &debugger,
321                                         llvm::StringRef user_exe_path,
322                                         const ArchSpec &specified_arch,
323                                         LoadDependentFiles load_dependent_files,
324                                         lldb::PlatformSP &platform_sp,
325                                         lldb::TargetSP &target_sp,
326                                         bool is_dummy_target) {
327   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
328   Timer scoped_timer(
329       func_cat, "TargetList::CreateTarget (file = '%s', arch = '%s')",
330       user_exe_path.str().c_str(), specified_arch.GetArchitectureName());
331   Status error;
332
333   ArchSpec arch(specified_arch);
334
335   if (arch.IsValid()) {
336     if (!platform_sp ||
337         !platform_sp->IsCompatibleArchitecture(arch, false, nullptr))
338       platform_sp = Platform::GetPlatformForArchitecture(specified_arch, &arch);
339   }
340
341   if (!platform_sp)
342     platform_sp = debugger.GetPlatformList().GetSelectedPlatform();
343
344   if (!arch.IsValid())
345     arch = specified_arch;
346
347   FileSpec file(user_exe_path);
348   if (!FileSystem::Instance().Exists(file) && user_exe_path.startswith("~")) {
349     // we want to expand the tilde but we don't want to resolve any symbolic
350     // links so we can't use the FileSpec constructor's resolve flag
351     llvm::SmallString<64> unglobbed_path;
352     StandardTildeExpressionResolver Resolver;
353     Resolver.ResolveFullPath(user_exe_path, unglobbed_path);
354
355     if (unglobbed_path.empty())
356       file = FileSpec(user_exe_path);
357     else
358       file = FileSpec(unglobbed_path.c_str());
359   }
360
361   bool user_exe_path_is_bundle = false;
362   char resolved_bundle_exe_path[PATH_MAX];
363   resolved_bundle_exe_path[0] = '\0';
364   if (file) {
365     if (FileSystem::Instance().IsDirectory(file))
366       user_exe_path_is_bundle = true;
367
368     if (file.IsRelative() && !user_exe_path.empty()) {
369       llvm::SmallString<64> cwd;
370       if (! llvm::sys::fs::current_path(cwd)) {
371         FileSpec cwd_file(cwd.c_str());
372         cwd_file.AppendPathComponent(file);
373         if (FileSystem::Instance().Exists(cwd_file))
374           file = cwd_file;
375       }
376     }
377
378     ModuleSP exe_module_sp;
379     if (platform_sp) {
380       FileSpecList executable_search_paths(
381           Target::GetDefaultExecutableSearchPaths());
382       ModuleSpec module_spec(file, arch);
383       error = platform_sp->ResolveExecutable(module_spec, exe_module_sp,
384                                              executable_search_paths.GetSize()
385                                                  ? &executable_search_paths
386                                                  : nullptr);
387     }
388
389     if (error.Success() && exe_module_sp) {
390       if (exe_module_sp->GetObjectFile() == nullptr) {
391         if (arch.IsValid()) {
392           error.SetErrorStringWithFormat(
393               "\"%s\" doesn't contain architecture %s", file.GetPath().c_str(),
394               arch.GetArchitectureName());
395         } else {
396           error.SetErrorStringWithFormat("unsupported file type \"%s\"",
397                                          file.GetPath().c_str());
398         }
399         return error;
400       }
401       target_sp.reset(new Target(debugger, arch, platform_sp, is_dummy_target));
402       target_sp->SetExecutableModule(exe_module_sp, load_dependent_files);
403       if (user_exe_path_is_bundle)
404         exe_module_sp->GetFileSpec().GetPath(resolved_bundle_exe_path,
405                                              sizeof(resolved_bundle_exe_path));
406     }
407   } else {
408     // No file was specified, just create an empty target with any arch if a
409     // valid arch was specified
410     target_sp.reset(new Target(debugger, arch, platform_sp, is_dummy_target));
411   }
412
413   if (target_sp) {
414     // Set argv0 with what the user typed, unless the user specified a
415     // directory. If the user specified a directory, then it is probably a
416     // bundle that was resolved and we need to use the resolved bundle path
417     if (!user_exe_path.empty()) {
418       // Use exactly what the user typed as the first argument when we exec or
419       // posix_spawn
420       if (user_exe_path_is_bundle && resolved_bundle_exe_path[0]) {
421         target_sp->SetArg0(resolved_bundle_exe_path);
422       } else {
423         // Use resolved path
424         target_sp->SetArg0(file.GetPath().c_str());
425       }
426     }
427     if (file.GetDirectory()) {
428       FileSpec file_dir;
429       file_dir.GetDirectory() = file.GetDirectory();
430       target_sp->GetExecutableSearchPaths().Append(file_dir);
431     }
432
433     // Don't put the dummy target in the target list, it's held separately.
434     if (!is_dummy_target) {
435       std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
436       m_selected_target_idx = m_target_list.size();
437       m_target_list.push_back(target_sp);
438       // Now prime this from the dummy target:
439       target_sp->PrimeFromDummyTarget(debugger.GetDummyTarget());
440     } else {
441       m_dummy_target_sp = target_sp;
442     }
443   }
444
445   return error;
446 }
447
448 bool TargetList::DeleteTarget(TargetSP &target_sp) {
449   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
450   collection::iterator pos, end = m_target_list.end();
451
452   for (pos = m_target_list.begin(); pos != end; ++pos) {
453     if (pos->get() == target_sp.get()) {
454       m_target_list.erase(pos);
455       return true;
456     }
457   }
458   return false;
459 }
460
461 TargetSP TargetList::FindTargetWithExecutableAndArchitecture(
462     const FileSpec &exe_file_spec, const ArchSpec *exe_arch_ptr) const {
463   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
464   TargetSP target_sp;
465   bool full_match = (bool)exe_file_spec.GetDirectory();
466
467   collection::const_iterator pos, end = m_target_list.end();
468   for (pos = m_target_list.begin(); pos != end; ++pos) {
469     Module *exe_module = (*pos)->GetExecutableModulePointer();
470
471     if (exe_module) {
472       if (FileSpec::Equal(exe_file_spec, exe_module->GetFileSpec(),
473                           full_match)) {
474         if (exe_arch_ptr) {
475           if (!exe_arch_ptr->IsCompatibleMatch(exe_module->GetArchitecture()))
476             continue;
477         }
478         target_sp = *pos;
479         break;
480       }
481     }
482   }
483   return target_sp;
484 }
485
486 TargetSP TargetList::FindTargetWithProcessID(lldb::pid_t pid) const {
487   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
488   TargetSP target_sp;
489   collection::const_iterator pos, end = m_target_list.end();
490   for (pos = m_target_list.begin(); pos != end; ++pos) {
491     Process *process = (*pos)->GetProcessSP().get();
492     if (process && process->GetID() == pid) {
493       target_sp = *pos;
494       break;
495     }
496   }
497   return target_sp;
498 }
499
500 TargetSP TargetList::FindTargetWithProcess(Process *process) const {
501   TargetSP target_sp;
502   if (process) {
503     std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
504     collection::const_iterator pos, end = m_target_list.end();
505     for (pos = m_target_list.begin(); pos != end; ++pos) {
506       if (process == (*pos)->GetProcessSP().get()) {
507         target_sp = *pos;
508         break;
509       }
510     }
511   }
512   return target_sp;
513 }
514
515 TargetSP TargetList::GetTargetSP(Target *target) const {
516   TargetSP target_sp;
517   if (target) {
518     std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
519     collection::const_iterator pos, end = m_target_list.end();
520     for (pos = m_target_list.begin(); pos != end; ++pos) {
521       if (target == (*pos).get()) {
522         target_sp = *pos;
523         break;
524       }
525     }
526   }
527   return target_sp;
528 }
529
530 uint32_t TargetList::SendAsyncInterrupt(lldb::pid_t pid) {
531   uint32_t num_async_interrupts_sent = 0;
532
533   if (pid != LLDB_INVALID_PROCESS_ID) {
534     TargetSP target_sp(FindTargetWithProcessID(pid));
535     if (target_sp) {
536       Process *process = target_sp->GetProcessSP().get();
537       if (process) {
538         process->SendAsyncInterrupt();
539         ++num_async_interrupts_sent;
540       }
541     }
542   } else {
543     // We don't have a valid pid to broadcast to, so broadcast to the target
544     // list's async broadcaster...
545     BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
546   }
547
548   return num_async_interrupts_sent;
549 }
550
551 uint32_t TargetList::SignalIfRunning(lldb::pid_t pid, int signo) {
552   uint32_t num_signals_sent = 0;
553   Process *process = nullptr;
554   if (pid == LLDB_INVALID_PROCESS_ID) {
555     // Signal all processes with signal
556     std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
557     collection::iterator pos, end = m_target_list.end();
558     for (pos = m_target_list.begin(); pos != end; ++pos) {
559       process = (*pos)->GetProcessSP().get();
560       if (process) {
561         if (process->IsAlive()) {
562           ++num_signals_sent;
563           process->Signal(signo);
564         }
565       }
566     }
567   } else {
568     // Signal a specific process with signal
569     TargetSP target_sp(FindTargetWithProcessID(pid));
570     if (target_sp) {
571       process = target_sp->GetProcessSP().get();
572       if (process) {
573         if (process->IsAlive()) {
574           ++num_signals_sent;
575           process->Signal(signo);
576         }
577       }
578     }
579   }
580   return num_signals_sent;
581 }
582
583 int TargetList::GetNumTargets() const {
584   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
585   return m_target_list.size();
586 }
587
588 lldb::TargetSP TargetList::GetTargetAtIndex(uint32_t idx) const {
589   TargetSP target_sp;
590   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
591   if (idx < m_target_list.size())
592     target_sp = m_target_list[idx];
593   return target_sp;
594 }
595
596 uint32_t TargetList::GetIndexOfTarget(lldb::TargetSP target_sp) const {
597   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
598   size_t num_targets = m_target_list.size();
599   for (size_t idx = 0; idx < num_targets; idx++) {
600     if (target_sp == m_target_list[idx])
601       return idx;
602   }
603   return UINT32_MAX;
604 }
605
606 uint32_t TargetList::SetSelectedTarget(Target *target) {
607   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
608   collection::const_iterator pos, begin = m_target_list.begin(),
609                                   end = m_target_list.end();
610   for (pos = begin; pos != end; ++pos) {
611     if (pos->get() == target) {
612       m_selected_target_idx = std::distance(begin, pos);
613       return m_selected_target_idx;
614     }
615   }
616   m_selected_target_idx = 0;
617   return m_selected_target_idx;
618 }
619
620 lldb::TargetSP TargetList::GetSelectedTarget() {
621   std::lock_guard<std::recursive_mutex> guard(m_target_list_mutex);
622   if (m_selected_target_idx >= m_target_list.size())
623     m_selected_target_idx = 0;
624   return GetTargetAtIndex(m_selected_target_idx);
625 }