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