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