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