]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/include/lldb/Target/Platform.h
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / include / lldb / Target / Platform.h
1 //===-- Platform.h ----------------------------------------------*- C++ -*-===//
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 #ifndef liblldb_Platform_h_
10 #define liblldb_Platform_h_
11
12 #include <functional>
13 #include <map>
14 #include <memory>
15 #include <mutex>
16 #include <string>
17 #include <vector>
18
19 #include "lldb/Core/PluginInterface.h"
20 #include "lldb/Core/UserSettingsController.h"
21 #include "lldb/Interpreter/Options.h"
22 #include "lldb/Utility/ArchSpec.h"
23 #include "lldb/Utility/ConstString.h"
24 #include "lldb/Utility/FileSpec.h"
25 #include "lldb/Utility/Timeout.h"
26 #include "lldb/Utility/UserIDResolver.h"
27 #include "lldb/lldb-private-forward.h"
28 #include "lldb/lldb-public.h"
29 #include "llvm/Support/VersionTuple.h"
30
31 namespace lldb_private {
32
33 class ProcessInstanceInfo;
34 class ProcessInstanceInfoList;
35 class ProcessInstanceInfoMatch;
36
37 class ModuleCache;
38 enum MmapFlags { eMmapFlagsPrivate = 1, eMmapFlagsAnon = 2 };
39
40 class PlatformProperties : public Properties {
41 public:
42   PlatformProperties();
43
44   static ConstString GetSettingName();
45
46   bool GetUseModuleCache() const;
47   bool SetUseModuleCache(bool use_module_cache);
48
49   FileSpec GetModuleCacheDirectory() const;
50   bool SetModuleCacheDirectory(const FileSpec &dir_spec);
51 };
52
53 typedef std::shared_ptr<PlatformProperties> PlatformPropertiesSP;
54 typedef llvm::SmallVector<lldb::addr_t, 6> MmapArgList;
55
56 /// \class Platform Platform.h "lldb/Target/Platform.h"
57 /// A plug-in interface definition class for debug platform that
58 /// includes many platform abilities such as:
59 ///     \li getting platform information such as supported architectures,
60 ///         supported binary file formats and more
61 ///     \li launching new processes
62 ///     \li attaching to existing processes
63 ///     \li download/upload files
64 ///     \li execute shell commands
65 ///     \li listing and getting info for existing processes
66 ///     \li attaching and possibly debugging the platform's kernel
67 class Platform : public PluginInterface {
68 public:
69   /// Default Constructor
70   Platform(bool is_host_platform);
71
72   /// Destructor.
73   ///
74   /// The destructor is virtual since this class is designed to be inherited
75   /// from by the plug-in instance.
76   ~Platform() override;
77
78   static void Initialize();
79
80   static void Terminate();
81
82   static const PlatformPropertiesSP &GetGlobalPlatformProperties();
83
84   /// Get the native host platform plug-in.
85   ///
86   /// There should only be one of these for each host that LLDB runs upon that
87   /// should be statically compiled in and registered using preprocessor
88   /// macros or other similar build mechanisms in a
89   /// PlatformSubclass::Initialize() function.
90   ///
91   /// This platform will be used as the default platform when launching or
92   /// attaching to processes unless another platform is specified.
93   static lldb::PlatformSP GetHostPlatform();
94
95   static lldb::PlatformSP
96   GetPlatformForArchitecture(const ArchSpec &arch, ArchSpec *platform_arch_ptr);
97
98   static const char *GetHostPlatformName();
99
100   static void SetHostPlatform(const lldb::PlatformSP &platform_sp);
101
102   // Find an existing platform plug-in by name
103   static lldb::PlatformSP Find(ConstString name);
104
105   static lldb::PlatformSP Create(ConstString name, Status &error);
106
107   static lldb::PlatformSP Create(const ArchSpec &arch,
108                                  ArchSpec *platform_arch_ptr, Status &error);
109
110   /// Augments the triple either with information from platform or the host
111   /// system (if platform is null).
112   static ArchSpec GetAugmentedArchSpec(Platform *platform,
113                                        llvm::StringRef triple);
114
115   /// Find a platform plugin for a given process.
116   ///
117   /// Scans the installed Platform plug-ins and tries to find an instance that
118   /// can be used for \a process
119   ///
120   /// \param[in] process
121   ///     The process for which to try and locate a platform
122   ///     plug-in instance.
123   ///
124   /// \param[in] plugin_name
125   ///     An optional name of a specific platform plug-in that
126   ///     should be used. If nullptr, pick the best plug-in.
127   //        static lldb::PlatformSP
128   //        FindPlugin (Process *process, ConstString plugin_name);
129
130   /// Set the target's executable based off of the existing architecture
131   /// information in \a target given a path to an executable \a exe_file.
132   ///
133   /// Each platform knows the architectures that it supports and can select
134   /// the correct architecture slice within \a exe_file by inspecting the
135   /// architecture in \a target. If the target had an architecture specified,
136   /// then in can try and obey that request and optionally fail if the
137   /// architecture doesn't match up. If no architecture is specified, the
138   /// platform should select the default architecture from \a exe_file. Any
139   /// application bundles or executable wrappers can also be inspected for the
140   /// actual application binary within the bundle that should be used.
141   ///
142   /// \return
143   ///     Returns \b true if this Platform plug-in was able to find
144   ///     a suitable executable, \b false otherwise.
145   virtual Status ResolveExecutable(const ModuleSpec &module_spec,
146                                    lldb::ModuleSP &module_sp,
147                                    const FileSpecList *module_search_paths_ptr);
148
149   /// Find a symbol file given a symbol file module specification.
150   ///
151   /// Each platform might have tricks to find symbol files for an executable
152   /// given information in a symbol file ModuleSpec. Some platforms might also
153   /// support symbol files that are bundles and know how to extract the right
154   /// symbol file given a bundle.
155   ///
156   /// \param[in] target
157   ///     The target in which we are trying to resolve the symbol file.
158   ///     The target has a list of modules that we might be able to
159   ///     use in order to help find the right symbol file. If the
160   ///     "m_file" or "m_platform_file" entries in the \a sym_spec
161   ///     are filled in, then we might be able to locate a module in
162   ///     the target, extract its UUID and locate a symbol file.
163   ///     If just the "m_uuid" is specified, then we might be able
164   ///     to find the module in the target that matches that UUID
165   ///     and pair the symbol file along with it. If just "m_symbol_file"
166   ///     is specified, we can use a variety of tricks to locate the
167   ///     symbols in an SDK, PDK, or other development kit location.
168   ///
169   /// \param[in] sym_spec
170   ///     A module spec that describes some information about the
171   ///     symbol file we are trying to resolve. The ModuleSpec might
172   ///     contain the following:
173   ///     m_file - A full or partial path to an executable from the
174   ///              target (might be empty).
175   ///     m_platform_file - Another executable hint that contains
176   ///                       the path to the file as known on the
177   ///                       local/remote platform.
178   ///     m_symbol_file - A full or partial path to a symbol file
179   ///                     or symbol bundle that should be used when
180   ///                     trying to resolve the symbol file.
181   ///     m_arch - The architecture we are looking for when resolving
182   ///              the symbol file.
183   ///     m_uuid - The UUID of the executable and symbol file. This
184   ///              can often be used to match up an executable with
185   ///              a symbol file, or resolve an symbol file in a
186   ///              symbol file bundle.
187   ///
188   /// \param[out] sym_file
189   ///     The resolved symbol file spec if the returned error
190   ///     indicates success.
191   ///
192   /// \return
193   ///     Returns an error that describes success or failure.
194   virtual Status ResolveSymbolFile(Target &target, const ModuleSpec &sym_spec,
195                                    FileSpec &sym_file);
196
197   /// Resolves the FileSpec to a (possibly) remote path. Remote platforms must
198   /// override this to resolve to a path on the remote side.
199   virtual bool ResolveRemotePath(const FileSpec &platform_path,
200                                  FileSpec &resolved_platform_path);
201
202   /// Get the OS version from a connected platform.
203   ///
204   /// Some platforms might not be connected to a remote platform, but can
205   /// figure out the OS version for a process. This is common for simulator
206   /// platforms that will run native programs on the current host, but the
207   /// simulator might be simulating a different OS. The \a process parameter
208   /// might be specified to help to determine the OS version.
209   virtual llvm::VersionTuple GetOSVersion(Process *process = nullptr);
210
211   bool SetOSVersion(llvm::VersionTuple os_version);
212
213   bool GetOSBuildString(std::string &s);
214
215   bool GetOSKernelDescription(std::string &s);
216
217   // Returns the name of the platform
218   ConstString GetName();
219
220   virtual const char *GetHostname();
221
222   virtual ConstString GetFullNameForDylib(ConstString basename);
223
224   virtual const char *GetDescription() = 0;
225
226   /// Report the current status for this platform.
227   ///
228   /// The returned string usually involves returning the OS version (if
229   /// available), and any SDK directory that might be being used for local
230   /// file caching, and if connected a quick blurb about what this platform is
231   /// connected to.
232   virtual void GetStatus(Stream &strm);
233
234   // Subclasses must be able to fetch the current OS version
235   //
236   // Remote classes must be connected for this to succeed. Local subclasses
237   // don't need to override this function as it will just call the
238   // HostInfo::GetOSVersion().
239   virtual bool GetRemoteOSVersion() { return false; }
240
241   virtual bool GetRemoteOSBuildString(std::string &s) {
242     s.clear();
243     return false;
244   }
245
246   virtual bool GetRemoteOSKernelDescription(std::string &s) {
247     s.clear();
248     return false;
249   }
250
251   // Remote Platform subclasses need to override this function
252   virtual ArchSpec GetRemoteSystemArchitecture() {
253     return ArchSpec(); // Return an invalid architecture
254   }
255
256   virtual FileSpec GetRemoteWorkingDirectory() { return m_working_dir; }
257
258   virtual bool SetRemoteWorkingDirectory(const FileSpec &working_dir);
259
260   /// Retrieve the system include directories on this platform for the
261   /// given language.
262   ///
263   /// \param[in] lang
264   ///     The language for which the include directories should be queried.
265   ///
266   /// \param[out] directories
267   ///     The include directories for this system.
268   virtual std::vector<std::string>
269   GetSystemIncludeDirectories(lldb::LanguageType lang) {
270     return {};
271   }
272
273   virtual UserIDResolver &GetUserIDResolver() = 0;
274
275   /// Locate a file for a platform.
276   ///
277   /// The default implementation of this function will return the same file
278   /// patch in \a local_file as was in \a platform_file.
279   ///
280   /// \param[in] platform_file
281   ///     The platform file path to locate and cache locally.
282   ///
283   /// \param[in] uuid_ptr
284   ///     If we know the exact UUID of the file we are looking for, it
285   ///     can be specified. If it is not specified, we might now know
286   ///     the exact file. The UUID is usually some sort of MD5 checksum
287   ///     for the file and is sometimes known by dynamic linkers/loaders.
288   ///     If the UUID is known, it is best to supply it to platform
289   ///     file queries to ensure we are finding the correct file, not
290   ///     just a file at the correct path.
291   ///
292   /// \param[out] local_file
293   ///     A locally cached version of the platform file. For platforms
294   ///     that describe the current host computer, this will just be
295   ///     the same file. For remote platforms, this file might come from
296   ///     and SDK directory, or might need to be sync'ed over to the
297   ///     current machine for efficient debugging access.
298   ///
299   /// \return
300   ///     An error object.
301   virtual Status GetFileWithUUID(const FileSpec &platform_file,
302                                  const UUID *uuid_ptr, FileSpec &local_file);
303
304   // Locate the scripting resource given a module specification.
305   //
306   // Locating the file should happen only on the local computer or using the
307   // current computers global settings.
308   virtual FileSpecList
309   LocateExecutableScriptingResources(Target *target, Module &module,
310                                      Stream *feedback_stream);
311
312   virtual Status GetSharedModule(const ModuleSpec &module_spec,
313                                  Process *process, lldb::ModuleSP &module_sp,
314                                  const FileSpecList *module_search_paths_ptr,
315                                  lldb::ModuleSP *old_module_sp_ptr,
316                                  bool *did_create_ptr);
317
318   virtual bool GetModuleSpec(const FileSpec &module_file_spec,
319                              const ArchSpec &arch, ModuleSpec &module_spec);
320
321   virtual Status ConnectRemote(Args &args);
322
323   virtual Status DisconnectRemote();
324
325   /// Get the platform's supported architectures in the order in which they
326   /// should be searched.
327   ///
328   /// \param[in] idx
329   ///     A zero based architecture index
330   ///
331   /// \param[out] arch
332   ///     A copy of the architecture at index if the return value is
333   ///     \b true.
334   ///
335   /// \return
336   ///     \b true if \a arch was filled in and is valid, \b false
337   ///     otherwise.
338   virtual bool GetSupportedArchitectureAtIndex(uint32_t idx,
339                                                ArchSpec &arch) = 0;
340
341   virtual size_t GetSoftwareBreakpointTrapOpcode(Target &target,
342                                                  BreakpointSite *bp_site);
343
344   /// Launch a new process on a platform, not necessarily for debugging, it
345   /// could be just for running the process.
346   virtual Status LaunchProcess(ProcessLaunchInfo &launch_info);
347
348   /// Perform expansion of the command-line for this launch info This can
349   /// potentially involve wildcard expansion
350   /// environment variable replacement, and whatever other
351   /// argument magic the platform defines as part of its typical
352   /// user experience
353   virtual Status ShellExpandArguments(ProcessLaunchInfo &launch_info);
354
355   /// Kill process on a platform.
356   virtual Status KillProcess(const lldb::pid_t pid);
357
358   /// Lets a platform answer if it is compatible with a given architecture and
359   /// the target triple contained within.
360   virtual bool IsCompatibleArchitecture(const ArchSpec &arch,
361                                         bool exact_arch_match,
362                                         ArchSpec *compatible_arch_ptr);
363
364   /// Not all platforms will support debugging a process by spawning somehow
365   /// halted for a debugger (specified using the "eLaunchFlagDebug" launch
366   /// flag) and then attaching. If your platform doesn't support this,
367   /// override this function and return false.
368   virtual bool CanDebugProcess() { return true; }
369
370   /// Subclasses do not need to implement this function as it uses the
371   /// Platform::LaunchProcess() followed by Platform::Attach (). Remote
372   /// platforms will want to subclass this function in order to be able to
373   /// intercept STDIO and possibly launch a separate process that will debug
374   /// the debuggee.
375   virtual lldb::ProcessSP
376   DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger,
377                Target *target, // Can be nullptr, if nullptr create a new
378                                // target, else use existing one
379                Status &error);
380
381   virtual lldb::ProcessSP ConnectProcess(llvm::StringRef connect_url,
382                                          llvm::StringRef plugin_name,
383                                          lldb_private::Debugger &debugger,
384                                          lldb_private::Target *target,
385                                          lldb_private::Status &error);
386
387   /// Attach to an existing process using a process ID.
388   ///
389   /// Each platform subclass needs to implement this function and attempt to
390   /// attach to the process with the process ID of \a pid. The platform
391   /// subclass should return an appropriate ProcessSP subclass that is
392   /// attached to the process, or an empty shared pointer with an appropriate
393   /// error.
394   ///
395   /// \param[in] pid
396   ///     The process ID that we should attempt to attach to.
397   ///
398   /// \return
399   ///     An appropriate ProcessSP containing a valid shared pointer
400   ///     to the default Process subclass for the platform that is
401   ///     attached to the process, or an empty shared pointer with an
402   ///     appropriate error fill into the \a error object.
403   virtual lldb::ProcessSP Attach(ProcessAttachInfo &attach_info,
404                                  Debugger &debugger,
405                                  Target *target, // Can be nullptr, if nullptr
406                                                  // create a new target, else
407                                                  // use existing one
408                                  Status &error) = 0;
409
410   /// Attach to an existing process by process name.
411   ///
412   /// This function is not meant to be overridden by Process subclasses. It
413   /// will first call Process::WillAttach (const char *) and if that returns
414   /// \b true, Process::DoAttach (const char *) will be called to actually do
415   /// the attach. If DoAttach returns \b true, then Process::DidAttach() will
416   /// be called.
417   ///
418   /// \param[in] process_name
419   ///     A process name to match against the current process list.
420   ///
421   /// \return
422   ///     Returns \a pid if attaching was successful, or
423   ///     LLDB_INVALID_PROCESS_ID if attaching fails.
424   //        virtual lldb::ProcessSP
425   //        Attach (const char *process_name,
426   //                bool wait_for_launch,
427   //                Status &error) = 0;
428
429   // The base class Platform will take care of the host platform. Subclasses
430   // will need to fill in the remote case.
431   virtual uint32_t FindProcesses(const ProcessInstanceInfoMatch &match_info,
432                                  ProcessInstanceInfoList &proc_infos);
433
434   virtual bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &proc_info);
435
436   // Set a breakpoint on all functions that can end up creating a thread for
437   // this platform. This is needed when running expressions and also for
438   // process control.
439   virtual lldb::BreakpointSP SetThreadCreationBreakpoint(Target &target);
440
441   // Given a target, find the local SDK directory if one exists on the current
442   // host.
443   virtual lldb_private::ConstString
444   GetSDKDirectory(lldb_private::Target &target) {
445     return lldb_private::ConstString();
446   }
447
448   const std::string &GetRemoteURL() const { return m_remote_url; }
449
450   bool IsHost() const {
451     return m_is_host; // Is this the default host platform?
452   }
453
454   bool IsRemote() const { return !m_is_host; }
455
456   virtual bool IsConnected() const {
457     // Remote subclasses should override this function
458     return IsHost();
459   }
460
461   const ArchSpec &GetSystemArchitecture();
462
463   void SetSystemArchitecture(const ArchSpec &arch) {
464     m_system_arch = arch;
465     if (IsHost())
466       m_os_version_set_while_connected = m_system_arch.IsValid();
467   }
468
469   /// If the triple contains not specify the vendor, os, and environment
470   /// parts, we "augment" these using information from the platform and return
471   /// the resulting ArchSpec object.
472   ArchSpec GetAugmentedArchSpec(llvm::StringRef triple);
473
474   // Used for column widths
475   size_t GetMaxUserIDNameLength() const { return m_max_uid_name_len; }
476
477   // Used for column widths
478   size_t GetMaxGroupIDNameLength() const { return m_max_gid_name_len; }
479
480   ConstString GetSDKRootDirectory() const { return m_sdk_sysroot; }
481
482   void SetSDKRootDirectory(ConstString dir) { m_sdk_sysroot = dir; }
483
484   ConstString GetSDKBuild() const { return m_sdk_build; }
485
486   void SetSDKBuild(ConstString sdk_build) { m_sdk_build = sdk_build; }
487
488   // Override this to return true if your platform supports Clang modules. You
489   // may also need to override AddClangModuleCompilationOptions to pass the
490   // right Clang flags for your platform.
491   virtual bool SupportsModules() { return false; }
492
493   // Appends the platform-specific options required to find the modules for the
494   // current platform.
495   virtual void
496   AddClangModuleCompilationOptions(Target *target,
497                                    std::vector<std::string> &options);
498
499   FileSpec GetWorkingDirectory();
500
501   bool SetWorkingDirectory(const FileSpec &working_dir);
502
503   // There may be modules that we don't want to find by default for operations
504   // like "setting breakpoint by name". The platform will return "true" from
505   // this call if the passed in module happens to be one of these.
506
507   virtual bool
508   ModuleIsExcludedForUnconstrainedSearches(Target &target,
509                                            const lldb::ModuleSP &module_sp) {
510     return false;
511   }
512
513   virtual Status MakeDirectory(const FileSpec &file_spec, uint32_t permissions);
514
515   virtual Status GetFilePermissions(const FileSpec &file_spec,
516                                     uint32_t &file_permissions);
517
518   virtual Status SetFilePermissions(const FileSpec &file_spec,
519                                     uint32_t file_permissions);
520
521   virtual lldb::user_id_t OpenFile(const FileSpec &file_spec, uint32_t flags,
522                                    uint32_t mode, Status &error) {
523     return UINT64_MAX;
524   }
525
526   virtual bool CloseFile(lldb::user_id_t fd, Status &error) { return false; }
527
528   virtual lldb::user_id_t GetFileSize(const FileSpec &file_spec) {
529     return UINT64_MAX;
530   }
531
532   virtual uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst,
533                             uint64_t dst_len, Status &error) {
534     error.SetErrorStringWithFormat(
535         "Platform::ReadFile() is not supported in the %s platform",
536         GetName().GetCString());
537     return -1;
538   }
539
540   virtual uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset,
541                              const void *src, uint64_t src_len, Status &error) {
542     error.SetErrorStringWithFormat(
543         "Platform::WriteFile() is not supported in the %s platform",
544         GetName().GetCString());
545     return -1;
546   }
547
548   virtual Status GetFile(const FileSpec &source, const FileSpec &destination);
549
550   virtual Status PutFile(const FileSpec &source, const FileSpec &destination,
551                          uint32_t uid = UINT32_MAX, uint32_t gid = UINT32_MAX);
552
553   virtual Status
554   CreateSymlink(const FileSpec &src,  // The name of the link is in src
555                 const FileSpec &dst); // The symlink points to dst
556
557   /// Install a file or directory to the remote system.
558   ///
559   /// Install is similar to Platform::PutFile(), but it differs in that if an
560   /// application/framework/shared library is installed on a remote platform
561   /// and the remote platform requires something to be done to register the
562   /// application/framework/shared library, then this extra registration can
563   /// be done.
564   ///
565   /// \param[in] src
566   ///     The source file/directory to install on the remote system.
567   ///
568   /// \param[in] dst
569   ///     The destination file/directory where \a src will be installed.
570   ///     If \a dst has no filename specified, then its filename will
571   ///     be set from \a src. It \a dst has no directory specified, it
572   ///     will use the platform working directory. If \a dst has a
573   ///     directory specified, but the directory path is relative, the
574   ///     platform working directory will be prepended to the relative
575   ///     directory.
576   ///
577   /// \return
578   ///     An error object that describes anything that went wrong.
579   virtual Status Install(const FileSpec &src, const FileSpec &dst);
580
581   virtual Environment GetEnvironment();
582
583   virtual bool GetFileExists(const lldb_private::FileSpec &file_spec);
584
585   virtual Status Unlink(const FileSpec &file_spec);
586
587   virtual MmapArgList GetMmapArgumentList(const ArchSpec &arch,
588                                           lldb::addr_t addr,
589                                           lldb::addr_t length,
590                                           unsigned prot, unsigned flags,
591                                           lldb::addr_t fd, lldb::addr_t offset);
592
593   virtual bool GetSupportsRSync() { return m_supports_rsync; }
594
595   virtual void SetSupportsRSync(bool flag) { m_supports_rsync = flag; }
596
597   virtual const char *GetRSyncOpts() { return m_rsync_opts.c_str(); }
598
599   virtual void SetRSyncOpts(const char *opts) { m_rsync_opts.assign(opts); }
600
601   virtual const char *GetRSyncPrefix() { return m_rsync_prefix.c_str(); }
602
603   virtual void SetRSyncPrefix(const char *prefix) {
604     m_rsync_prefix.assign(prefix);
605   }
606
607   virtual bool GetSupportsSSH() { return m_supports_ssh; }
608
609   virtual void SetSupportsSSH(bool flag) { m_supports_ssh = flag; }
610
611   virtual const char *GetSSHOpts() { return m_ssh_opts.c_str(); }
612
613   virtual void SetSSHOpts(const char *opts) { m_ssh_opts.assign(opts); }
614
615   virtual bool GetIgnoresRemoteHostname() { return m_ignores_remote_hostname; }
616
617   virtual void SetIgnoresRemoteHostname(bool flag) {
618     m_ignores_remote_hostname = flag;
619   }
620
621   virtual lldb_private::OptionGroupOptions *
622   GetConnectionOptions(CommandInterpreter &interpreter) {
623     return nullptr;
624   }
625
626   virtual lldb_private::Status RunShellCommand(
627       const char *command,         // Shouldn't be nullptr
628       const FileSpec &working_dir, // Pass empty FileSpec to use the current
629                                    // working directory
630       int *status_ptr, // Pass nullptr if you don't want the process exit status
631       int *signo_ptr,  // Pass nullptr if you don't want the signal that caused
632                        // the process to exit
633       std::string
634           *command_output, // Pass nullptr if you don't want the command output
635       const Timeout<std::micro> &timeout);
636
637   virtual void SetLocalCacheDirectory(const char *local);
638
639   virtual const char *GetLocalCacheDirectory();
640
641   virtual std::string GetPlatformSpecificConnectionInformation() { return ""; }
642
643   virtual bool CalculateMD5(const FileSpec &file_spec, uint64_t &low,
644                             uint64_t &high);
645
646   virtual int32_t GetResumeCountForLaunchInfo(ProcessLaunchInfo &launch_info) {
647     return 1;
648   }
649
650   virtual const lldb::UnixSignalsSP &GetRemoteUnixSignals();
651
652   lldb::UnixSignalsSP GetUnixSignals();
653
654   /// Locate a queue name given a thread's qaddr
655   ///
656   /// On a system using libdispatch ("Grand Central Dispatch") style queues, a
657   /// thread may be associated with a GCD queue or not, and a queue may be
658   /// associated with multiple threads. The process/thread must provide a way
659   /// to find the "dispatch_qaddr" for each thread, and from that
660   /// dispatch_qaddr this Platform method will locate the queue name and
661   /// provide that.
662   ///
663   /// \param[in] process
664   ///     A process is required for reading memory.
665   ///
666   /// \param[in] dispatch_qaddr
667   ///     The dispatch_qaddr for this thread.
668   ///
669   /// \return
670   ///     The name of the queue, if there is one.  An empty string
671   ///     means that this thread is not associated with a dispatch
672   ///     queue.
673   virtual std::string
674   GetQueueNameForThreadQAddress(Process *process, lldb::addr_t dispatch_qaddr) {
675     return "";
676   }
677
678   /// Locate a queue ID given a thread's qaddr
679   ///
680   /// On a system using libdispatch ("Grand Central Dispatch") style queues, a
681   /// thread may be associated with a GCD queue or not, and a queue may be
682   /// associated with multiple threads. The process/thread must provide a way
683   /// to find the "dispatch_qaddr" for each thread, and from that
684   /// dispatch_qaddr this Platform method will locate the queue ID and provide
685   /// that.
686   ///
687   /// \param[in] process
688   ///     A process is required for reading memory.
689   ///
690   /// \param[in] dispatch_qaddr
691   ///     The dispatch_qaddr for this thread.
692   ///
693   /// \return
694   ///     The queue_id for this thread, if this thread is associated
695   ///     with a dispatch queue.  Else LLDB_INVALID_QUEUE_ID is returned.
696   virtual lldb::queue_id_t
697   GetQueueIDForThreadQAddress(Process *process, lldb::addr_t dispatch_qaddr) {
698     return LLDB_INVALID_QUEUE_ID;
699   }
700
701   /// Provide a list of trap handler function names for this platform
702   ///
703   /// The unwinder needs to treat trap handlers specially -- the stack frame
704   /// may not be aligned correctly for a trap handler (the kernel often won't
705   /// perturb the stack pointer, or won't re-align it properly, in the process
706   /// of calling the handler) and the frame above the handler needs to be
707   /// treated by the unwinder's "frame 0" rules instead of its "middle of the
708   /// stack frame" rules.
709   ///
710   /// In a user process debugging scenario, the list of trap handlers is
711   /// typically just "_sigtramp".
712   ///
713   /// The Platform base class provides the m_trap_handlers ivar but it does
714   /// not populate it.  Subclasses should add the names of the asynchronous
715   /// signal handler routines as needed.  For most Unix platforms, add
716   /// _sigtramp.
717   ///
718   /// \return
719   ///     A list of symbol names.  The list may be empty.
720   virtual const std::vector<ConstString> &GetTrapHandlerSymbolNames();
721
722   /// Find a support executable that may not live within in the standard
723   /// locations related to LLDB.
724   ///
725   /// Executable might exist within the Platform SDK directories, or in
726   /// standard tool directories within the current IDE that is running LLDB.
727   ///
728   /// \param[in] basename
729   ///     The basename of the executable to locate in the current
730   ///     platform.
731   ///
732   /// \return
733   ///     A FileSpec pointing to the executable on disk, or an invalid
734   ///     FileSpec if the executable cannot be found.
735   virtual FileSpec LocateExecutable(const char *basename) { return FileSpec(); }
736
737   /// Allow the platform to set preferred memory cache line size. If non-zero
738   /// (and the user has not set cache line size explicitly), this value will
739   /// be used as the cache line size for memory reads.
740   virtual uint32_t GetDefaultMemoryCacheLineSize() { return 0; }
741
742   /// Load a shared library into this process.
743   ///
744   /// Try and load a shared library into the current process. This call might
745   /// fail in the dynamic loader plug-in says it isn't safe to try and load
746   /// shared libraries at the moment.
747   ///
748   /// \param[in] process
749   ///     The process to load the image.
750   ///
751   /// \param[in] local_file
752   ///     The file spec that points to the shared library that you want
753   ///     to load if the library is located on the host. The library will
754   ///     be copied over to the location specified by remote_file or into
755   ///     the current working directory with the same filename if the
756   ///     remote_file isn't specified.
757   ///
758   /// \param[in] remote_file
759   ///     If local_file is specified then the location where the library
760   ///     should be copied over from the host. If local_file isn't
761   ///     specified, then the path for the shared library on the target
762   ///     what you want to load.
763   ///
764   /// \param[out] error
765   ///     An error object that gets filled in with any errors that
766   ///     might occur when trying to load the shared library.
767   ///
768   /// \return
769   ///     A token that represents the shared library that can be
770   ///     later used to unload the shared library. A value of
771   ///     LLDB_INVALID_IMAGE_TOKEN will be returned if the shared
772   ///     library can't be opened.
773   uint32_t LoadImage(lldb_private::Process *process,
774                      const lldb_private::FileSpec &local_file,
775                      const lldb_private::FileSpec &remote_file,
776                      lldb_private::Status &error);
777
778   /// Load a shared library specified by base name into this process,
779   /// looking by hand along a set of paths.
780   ///
781   /// \param[in] process
782   ///     The process to load the image.
783   ///
784   /// \param[in] library_name
785   ///     The name of the library to look for.  If library_name is an
786   ///     absolute path, the basename will be extracted and searched for
787   ///     along the paths.  This emulates the behavior of the loader when
788   ///     given an install name and a set (e.g. DYLD_LIBRARY_PATH provided) of
789   ///     alternate paths.
790   ///
791   /// \param[in] path_list
792   ///     The list of paths to use to search for the library.  First
793   ///     match wins.
794   ///
795   /// \param[out] error
796   ///     An error object that gets filled in with any errors that
797   ///     might occur when trying to load the shared library.
798   ///
799   /// \param[out] loaded_path
800   ///      If non-null, the path to the dylib that was successfully loaded
801   ///      is stored in this path.
802   /// 
803   /// \return
804   ///     A token that represents the shared library which can be
805   ///     passed to UnloadImage. A value of
806   ///     LLDB_INVALID_IMAGE_TOKEN will be returned if the shared
807   ///     library can't be opened.
808   uint32_t LoadImageUsingPaths(lldb_private::Process *process,
809                                const lldb_private::FileSpec &library_name,
810                                const std::vector<std::string> &paths,
811                                lldb_private::Status &error,
812                                lldb_private::FileSpec *loaded_path);
813
814   virtual uint32_t DoLoadImage(lldb_private::Process *process,
815                                const lldb_private::FileSpec &remote_file,
816                                const std::vector<std::string> *paths,
817                                lldb_private::Status &error,
818                                lldb_private::FileSpec *loaded_path = nullptr);
819
820   virtual Status UnloadImage(lldb_private::Process *process,
821                              uint32_t image_token);
822
823   /// Connect to all processes waiting for a debugger to attach
824   ///
825   /// If the platform have a list of processes waiting for a debugger to
826   /// connect to them then connect to all of these pending processes.
827   ///
828   /// \param[in] debugger
829   ///     The debugger used for the connect.
830   ///
831   /// \param[out] error
832   ///     If an error occurred during the connect then this object will
833   ///     contain the error message.
834   ///
835   /// \return
836   ///     The number of processes we are successfully connected to.
837   virtual size_t ConnectToWaitingProcesses(lldb_private::Debugger &debugger,
838                                            lldb_private::Status &error);
839
840 protected:
841   bool m_is_host;
842   // Set to true when we are able to actually set the OS version while being
843   // connected. For remote platforms, we might set the version ahead of time
844   // before we actually connect and this version might change when we actually
845   // connect to a remote platform. For the host platform this will be set to
846   // the once we call HostInfo::GetOSVersion().
847   bool m_os_version_set_while_connected;
848   bool m_system_arch_set_while_connected;
849   ConstString
850       m_sdk_sysroot; // the root location of where the SDK files are all located
851   ConstString m_sdk_build;
852   FileSpec m_working_dir; // The working directory which is used when installing
853                           // modules that have no install path set
854   std::string m_remote_url;
855   std::string m_name;
856   llvm::VersionTuple m_os_version;
857   ArchSpec
858       m_system_arch; // The architecture of the kernel or the remote platform
859   typedef std::map<uint32_t, ConstString> IDToNameMap;
860   // Mutex for modifying Platform data structures that should only be used for
861   // non-reentrant code
862   std::mutex m_mutex;
863   size_t m_max_uid_name_len;
864   size_t m_max_gid_name_len;
865   bool m_supports_rsync;
866   std::string m_rsync_opts;
867   std::string m_rsync_prefix;
868   bool m_supports_ssh;
869   std::string m_ssh_opts;
870   bool m_ignores_remote_hostname;
871   std::string m_local_cache_directory;
872   std::vector<ConstString> m_trap_handlers;
873   bool m_calculated_trap_handlers;
874   const std::unique_ptr<ModuleCache> m_module_cache;
875
876   /// Ask the Platform subclass to fill in the list of trap handler names
877   ///
878   /// For most Unix user process environments, this will be a single function
879   /// name, _sigtramp.  More specialized environments may have additional
880   /// handler names.  The unwinder code needs to know when a trap handler is
881   /// on the stack because the unwind rules for the frame that caused the trap
882   /// are different.
883   ///
884   /// The base class Platform ivar m_trap_handlers should be updated by the
885   /// Platform subclass when this method is called.  If there are no
886   /// predefined trap handlers, this method may be a no-op.
887   virtual void CalculateTrapHandlerSymbolNames() = 0;
888
889   Status GetCachedExecutable(ModuleSpec &module_spec, lldb::ModuleSP &module_sp,
890                              const FileSpecList *module_search_paths_ptr,
891                              Platform &remote_platform);
892
893   virtual Status DownloadModuleSlice(const FileSpec &src_file_spec,
894                                      const uint64_t src_offset,
895                                      const uint64_t src_size,
896                                      const FileSpec &dst_file_spec);
897
898   virtual Status DownloadSymbolFile(const lldb::ModuleSP &module_sp,
899                                     const FileSpec &dst_file_spec);
900
901   virtual const char *GetCacheHostname();
902
903 private:
904   typedef std::function<Status(const ModuleSpec &)> ModuleResolver;
905
906   Status GetRemoteSharedModule(const ModuleSpec &module_spec, Process *process,
907                                lldb::ModuleSP &module_sp,
908                                const ModuleResolver &module_resolver,
909                                bool *did_create_ptr);
910
911   bool GetCachedSharedModule(const ModuleSpec &module_spec,
912                              lldb::ModuleSP &module_sp, bool *did_create_ptr);
913
914   Status LoadCachedExecutable(const ModuleSpec &module_spec,
915                               lldb::ModuleSP &module_sp,
916                               const FileSpecList *module_search_paths_ptr,
917                               Platform &remote_platform);
918
919   FileSpec GetModuleCacheRoot();
920
921   DISALLOW_COPY_AND_ASSIGN(Platform);
922 };
923
924 class PlatformList {
925 public:
926   PlatformList() : m_mutex(), m_platforms(), m_selected_platform_sp() {}
927
928   ~PlatformList() = default;
929
930   void Append(const lldb::PlatformSP &platform_sp, bool set_selected) {
931     std::lock_guard<std::recursive_mutex> guard(m_mutex);
932     m_platforms.push_back(platform_sp);
933     if (set_selected)
934       m_selected_platform_sp = m_platforms.back();
935   }
936
937   size_t GetSize() {
938     std::lock_guard<std::recursive_mutex> guard(m_mutex);
939     return m_platforms.size();
940   }
941
942   lldb::PlatformSP GetAtIndex(uint32_t idx) {
943     lldb::PlatformSP platform_sp;
944     {
945       std::lock_guard<std::recursive_mutex> guard(m_mutex);
946       if (idx < m_platforms.size())
947         platform_sp = m_platforms[idx];
948     }
949     return platform_sp;
950   }
951
952   /// Select the active platform.
953   ///
954   /// In order to debug remotely, other platform's can be remotely connected
955   /// to and set as the selected platform for any subsequent debugging. This
956   /// allows connection to remote targets and allows the ability to discover
957   /// process info, launch and attach to remote processes.
958   lldb::PlatformSP GetSelectedPlatform() {
959     std::lock_guard<std::recursive_mutex> guard(m_mutex);
960     if (!m_selected_platform_sp && !m_platforms.empty())
961       m_selected_platform_sp = m_platforms.front();
962
963     return m_selected_platform_sp;
964   }
965
966   void SetSelectedPlatform(const lldb::PlatformSP &platform_sp) {
967     if (platform_sp) {
968       std::lock_guard<std::recursive_mutex> guard(m_mutex);
969       const size_t num_platforms = m_platforms.size();
970       for (size_t idx = 0; idx < num_platforms; ++idx) {
971         if (m_platforms[idx].get() == platform_sp.get()) {
972           m_selected_platform_sp = m_platforms[idx];
973           return;
974         }
975       }
976       m_platforms.push_back(platform_sp);
977       m_selected_platform_sp = m_platforms.back();
978     }
979   }
980
981 protected:
982   typedef std::vector<lldb::PlatformSP> collection;
983   mutable std::recursive_mutex m_mutex;
984   collection m_platforms;
985   lldb::PlatformSP m_selected_platform_sp;
986
987 private:
988   DISALLOW_COPY_AND_ASSIGN(PlatformList);
989 };
990
991 class OptionGroupPlatformRSync : public lldb_private::OptionGroup {
992 public:
993   OptionGroupPlatformRSync() = default;
994
995   ~OptionGroupPlatformRSync() override = default;
996
997   lldb_private::Status
998   SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
999                  ExecutionContext *execution_context) override;
1000
1001   void OptionParsingStarting(ExecutionContext *execution_context) override;
1002
1003   llvm::ArrayRef<OptionDefinition> GetDefinitions() override;
1004
1005   // Instance variables to hold the values for command options.
1006
1007   bool m_rsync;
1008   std::string m_rsync_opts;
1009   std::string m_rsync_prefix;
1010   bool m_ignores_remote_hostname;
1011
1012 private:
1013   DISALLOW_COPY_AND_ASSIGN(OptionGroupPlatformRSync);
1014 };
1015
1016 class OptionGroupPlatformSSH : public lldb_private::OptionGroup {
1017 public:
1018   OptionGroupPlatformSSH() = default;
1019
1020   ~OptionGroupPlatformSSH() override = default;
1021
1022   lldb_private::Status
1023   SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
1024                  ExecutionContext *execution_context) override;
1025
1026   void OptionParsingStarting(ExecutionContext *execution_context) override;
1027
1028   llvm::ArrayRef<OptionDefinition> GetDefinitions() override;
1029
1030   // Instance variables to hold the values for command options.
1031
1032   bool m_ssh;
1033   std::string m_ssh_opts;
1034
1035 private:
1036   DISALLOW_COPY_AND_ASSIGN(OptionGroupPlatformSSH);
1037 };
1038
1039 class OptionGroupPlatformCaching : public lldb_private::OptionGroup {
1040 public:
1041   OptionGroupPlatformCaching() = default;
1042
1043   ~OptionGroupPlatformCaching() override = default;
1044
1045   lldb_private::Status
1046   SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
1047                  ExecutionContext *execution_context) override;
1048
1049   void OptionParsingStarting(ExecutionContext *execution_context) override;
1050
1051   llvm::ArrayRef<OptionDefinition> GetDefinitions() override;
1052
1053   // Instance variables to hold the values for command options.
1054
1055   std::string m_cache_dir;
1056
1057 private:
1058   DISALLOW_COPY_AND_ASSIGN(OptionGroupPlatformCaching);
1059 };
1060
1061 } // namespace lldb_private
1062
1063 #endif // liblldb_Platform_h_