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