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