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