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