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