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 34 namespace lldb_private { 35 36 class ProcessInstanceInfo; 37 class ProcessInstanceInfoMatch; 38 typedef std::vector<ProcessInstanceInfo> ProcessInstanceInfoList; 39 40 class ModuleCache; 41 enum MmapFlags { eMmapFlagsPrivate = 1, eMmapFlagsAnon = 2 }; 42 43 class PlatformProperties : public Properties { 44 public: 45 PlatformProperties(); 46 47 static ConstString 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 55 private: 56 void SetDefaultModuleCacheDirectory(const FileSpec &dir_spec); 57 }; 58 59 typedef llvm::SmallVector<lldb::addr_t, 6> MmapArgList; 60 61 /// \class Platform Platform.h "lldb/Target/Platform.h" 62 /// A plug-in interface definition class for debug platform that 63 /// includes many platform abilities such as: 64 /// \li getting platform information such as supported architectures, 65 /// supported binary file formats and more 66 /// \li launching new processes 67 /// \li attaching to existing processes 68 /// \li download/upload files 69 /// \li execute shell commands 70 /// \li listing and getting info for existing processes 71 /// \li attaching and possibly debugging the platform's kernel 72 class Platform : public PluginInterface { 73 public: 74 /// Default Constructor 75 Platform(bool is_host_platform); 76 77 /// 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 GetName()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(). GetRemoteOSVersion()233 virtual bool GetRemoteOSVersion() { return false; } 234 GetRemoteOSBuildString()235 virtual std::optional<std::string> GetRemoteOSBuildString() { 236 return std::nullopt; 237 } 238 GetRemoteOSKernelDescription()239 virtual std::optional<std::string> GetRemoteOSKernelDescription() { 240 return std::nullopt; 241 } 242 243 // Remote Platform subclasses need to override this function GetRemoteSystemArchitecture()244 virtual ArchSpec GetRemoteSystemArchitecture() { 245 return ArchSpec(); // Return an invalid architecture 246 } 247 GetRemoteWorkingDirectory()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 virtual Status GetSharedModule( 292 const ModuleSpec &module_spec, Process *process, 293 lldb::ModuleSP &module_sp, const FileSpecList *module_search_paths_ptr, 294 llvm::SmallVectorImpl<lldb::ModuleSP> *old_modules, bool *did_create_ptr); 295 296 virtual bool GetModuleSpec(const FileSpec &module_file_spec, 297 const ArchSpec &arch, ModuleSpec &module_spec); 298 299 virtual Status ConnectRemote(Args &args); 300 301 virtual Status DisconnectRemote(); 302 303 /// Get the platform's supported architectures in the order in which they 304 /// should be searched. 305 /// 306 /// \param[in] process_host_arch 307 /// The process host architecture if it's known. An invalid ArchSpec 308 /// represents that the process host architecture is unknown. 309 virtual std::vector<ArchSpec> 310 GetSupportedArchitectures(const ArchSpec &process_host_arch) = 0; 311 312 virtual size_t GetSoftwareBreakpointTrapOpcode(Target &target, 313 BreakpointSite *bp_site); 314 315 /// Launch a new process on a platform, not necessarily for debugging, it 316 /// could be just for running the process. 317 virtual Status LaunchProcess(ProcessLaunchInfo &launch_info); 318 319 /// Perform expansion of the command-line for this launch info This can 320 /// potentially involve wildcard expansion 321 /// environment variable replacement, and whatever other 322 /// argument magic the platform defines as part of its typical 323 /// user experience 324 virtual Status ShellExpandArguments(ProcessLaunchInfo &launch_info); 325 326 /// Kill process on a platform. 327 virtual Status KillProcess(const lldb::pid_t pid); 328 329 /// Lets a platform answer if it is compatible with a given architecture and 330 /// the target triple contained within. 331 virtual bool IsCompatibleArchitecture(const ArchSpec &arch, 332 const ArchSpec &process_host_arch, 333 ArchSpec::MatchType match, 334 ArchSpec *compatible_arch_ptr); 335 336 /// Not all platforms will support debugging a process by spawning somehow 337 /// halted for a debugger (specified using the "eLaunchFlagDebug" launch 338 /// flag) and then attaching. If your platform doesn't support this, 339 /// override this function and return false. CanDebugProcess()340 virtual bool CanDebugProcess() { return true; } 341 342 /// Subclasses do not need to implement this function as it uses the 343 /// Platform::LaunchProcess() followed by Platform::Attach (). Remote 344 /// platforms will want to subclass this function in order to be able to 345 /// intercept STDIO and possibly launch a separate process that will debug 346 /// the debuggee. 347 virtual lldb::ProcessSP DebugProcess(ProcessLaunchInfo &launch_info, 348 Debugger &debugger, Target &target, 349 Status &error); 350 351 virtual lldb::ProcessSP ConnectProcess(llvm::StringRef connect_url, 352 llvm::StringRef plugin_name, 353 Debugger &debugger, Target *target, 354 Status &error); 355 356 virtual lldb::ProcessSP 357 ConnectProcessSynchronous(llvm::StringRef connect_url, 358 llvm::StringRef plugin_name, Debugger &debugger, 359 Stream &stream, Target *target, Status &error); 360 361 /// Attach to an existing process using a process ID. 362 /// 363 /// Each platform subclass needs to implement this function and attempt to 364 /// attach to the process with the process ID of \a pid. The platform 365 /// subclass should return an appropriate ProcessSP subclass that is 366 /// attached to the process, or an empty shared pointer with an appropriate 367 /// error. 368 /// 369 /// \return 370 /// An appropriate ProcessSP containing a valid shared pointer 371 /// to the default Process subclass for the platform that is 372 /// attached to the process, or an empty shared pointer with an 373 /// appropriate error fill into the \a error object. 374 virtual lldb::ProcessSP Attach(ProcessAttachInfo &attach_info, 375 Debugger &debugger, 376 Target *target, // Can be nullptr, if nullptr 377 // create a new target, else 378 // use existing one 379 Status &error) = 0; 380 381 /// Attach to an existing process by process name. 382 /// 383 /// This function is not meant to be overridden by Process subclasses. It 384 /// will first call Process::WillAttach (const char *) and if that returns 385 /// \b true, Process::DoAttach (const char *) will be called to actually do 386 /// the attach. If DoAttach returns \b true, then Process::DidAttach() will 387 /// be called. 388 /// 389 /// \param[in] process_name 390 /// A process name to match against the current process list. 391 /// 392 /// \return 393 /// Returns \a pid if attaching was successful, or 394 /// LLDB_INVALID_PROCESS_ID if attaching fails. 395 // virtual lldb::ProcessSP 396 // Attach (const char *process_name, 397 // bool wait_for_launch, 398 // Status &error) = 0; 399 400 // The base class Platform will take care of the host platform. Subclasses 401 // will need to fill in the remote case. 402 virtual uint32_t FindProcesses(const ProcessInstanceInfoMatch &match_info, 403 ProcessInstanceInfoList &proc_infos); 404 405 virtual bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &proc_info); 406 407 // Set a breakpoint on all functions that can end up creating a thread for 408 // this platform. This is needed when running expressions and also for 409 // process control. 410 virtual lldb::BreakpointSP SetThreadCreationBreakpoint(Target &target); 411 412 // Given a target, find the local SDK directory if one exists on the current 413 // host. 414 virtual lldb_private::ConstString GetSDKDirectory(lldb_private::Target & target)415 GetSDKDirectory(lldb_private::Target &target) { 416 return lldb_private::ConstString(); 417 } 418 GetRemoteURL()419 const std::string &GetRemoteURL() const { return m_remote_url; } 420 IsHost()421 bool IsHost() const { 422 return m_is_host; // Is this the default host platform? 423 } 424 IsRemote()425 bool IsRemote() const { return !m_is_host; } 426 IsConnected()427 virtual bool IsConnected() const { 428 // Remote subclasses should override this function 429 return IsHost(); 430 } 431 432 const ArchSpec &GetSystemArchitecture(); 433 SetSystemArchitecture(const ArchSpec & arch)434 void SetSystemArchitecture(const ArchSpec &arch) { 435 m_system_arch = arch; 436 if (IsHost()) 437 m_os_version_set_while_connected = m_system_arch.IsValid(); 438 } 439 440 /// If the triple contains not specify the vendor, os, and environment 441 /// parts, we "augment" these using information from the platform and return 442 /// the resulting ArchSpec object. 443 ArchSpec GetAugmentedArchSpec(llvm::StringRef triple); 444 445 // Used for column widths GetMaxUserIDNameLength()446 size_t GetMaxUserIDNameLength() const { return m_max_uid_name_len; } 447 448 // Used for column widths GetMaxGroupIDNameLength()449 size_t GetMaxGroupIDNameLength() const { return m_max_gid_name_len; } 450 GetSDKRootDirectory()451 ConstString GetSDKRootDirectory() const { return m_sdk_sysroot; } 452 SetSDKRootDirectory(ConstString dir)453 void SetSDKRootDirectory(ConstString dir) { m_sdk_sysroot = dir; } 454 GetSDKBuild()455 ConstString GetSDKBuild() const { return m_sdk_build; } 456 SetSDKBuild(ConstString sdk_build)457 void SetSDKBuild(ConstString sdk_build) { m_sdk_build = sdk_build; } 458 459 // Override this to return true if your platform supports Clang modules. You 460 // may also need to override AddClangModuleCompilationOptions to pass the 461 // right Clang flags for your platform. SupportsModules()462 virtual bool SupportsModules() { return false; } 463 464 // Appends the platform-specific options required to find the modules for the 465 // current platform. 466 virtual void 467 AddClangModuleCompilationOptions(Target *target, 468 std::vector<std::string> &options); 469 470 FileSpec GetWorkingDirectory(); 471 472 bool SetWorkingDirectory(const FileSpec &working_dir); 473 474 // There may be modules that we don't want to find by default for operations 475 // like "setting breakpoint by name". The platform will return "true" from 476 // this call if the passed in module happens to be one of these. 477 478 virtual bool ModuleIsExcludedForUnconstrainedSearches(Target & target,const lldb::ModuleSP & module_sp)479 ModuleIsExcludedForUnconstrainedSearches(Target &target, 480 const lldb::ModuleSP &module_sp) { 481 return false; 482 } 483 484 virtual Status MakeDirectory(const FileSpec &file_spec, uint32_t permissions); 485 486 virtual Status GetFilePermissions(const FileSpec &file_spec, 487 uint32_t &file_permissions); 488 489 virtual Status SetFilePermissions(const FileSpec &file_spec, 490 uint32_t file_permissions); 491 492 virtual lldb::user_id_t OpenFile(const FileSpec &file_spec, 493 File::OpenOptions flags, uint32_t mode, 494 Status &error); 495 496 virtual bool CloseFile(lldb::user_id_t fd, Status &error); 497 498 virtual lldb::user_id_t GetFileSize(const FileSpec &file_spec); 499 AutoCompleteDiskFileOrDirectory(CompletionRequest & request,bool only_dir)500 virtual void AutoCompleteDiskFileOrDirectory(CompletionRequest &request, 501 bool only_dir) {} 502 503 virtual uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, 504 uint64_t dst_len, Status &error); 505 506 virtual uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, 507 const void *src, uint64_t src_len, Status &error); 508 509 virtual Status GetFile(const FileSpec &source, const FileSpec &destination); 510 511 virtual Status PutFile(const FileSpec &source, const FileSpec &destination, 512 uint32_t uid = UINT32_MAX, uint32_t gid = UINT32_MAX); 513 514 virtual Status 515 CreateSymlink(const FileSpec &src, // The name of the link is in src 516 const FileSpec &dst); // The symlink points to dst 517 518 /// Install a file or directory to the remote system. 519 /// 520 /// Install is similar to Platform::PutFile(), but it differs in that if an 521 /// application/framework/shared library is installed on a remote platform 522 /// and the remote platform requires something to be done to register the 523 /// application/framework/shared library, then this extra registration can 524 /// be done. 525 /// 526 /// \param[in] src 527 /// The source file/directory to install on the remote system. 528 /// 529 /// \param[in] dst 530 /// The destination file/directory where \a src will be installed. 531 /// If \a dst has no filename specified, then its filename will 532 /// be set from \a src. It \a dst has no directory specified, it 533 /// will use the platform working directory. If \a dst has a 534 /// directory specified, but the directory path is relative, the 535 /// platform working directory will be prepended to the relative 536 /// directory. 537 /// 538 /// \return 539 /// An error object that describes anything that went wrong. 540 virtual Status Install(const FileSpec &src, const FileSpec &dst); 541 542 virtual Environment GetEnvironment(); 543 544 virtual bool GetFileExists(const lldb_private::FileSpec &file_spec); 545 546 virtual Status Unlink(const FileSpec &file_spec); 547 548 virtual MmapArgList GetMmapArgumentList(const ArchSpec &arch, 549 lldb::addr_t addr, 550 lldb::addr_t length, 551 unsigned prot, unsigned flags, 552 lldb::addr_t fd, lldb::addr_t offset); 553 GetSupportsRSync()554 virtual bool GetSupportsRSync() { return m_supports_rsync; } 555 SetSupportsRSync(bool flag)556 virtual void SetSupportsRSync(bool flag) { m_supports_rsync = flag; } 557 GetRSyncOpts()558 virtual const char *GetRSyncOpts() { return m_rsync_opts.c_str(); } 559 SetRSyncOpts(const char * opts)560 virtual void SetRSyncOpts(const char *opts) { m_rsync_opts.assign(opts); } 561 GetRSyncPrefix()562 virtual const char *GetRSyncPrefix() { return m_rsync_prefix.c_str(); } 563 SetRSyncPrefix(const char * prefix)564 virtual void SetRSyncPrefix(const char *prefix) { 565 m_rsync_prefix.assign(prefix); 566 } 567 GetSupportsSSH()568 virtual bool GetSupportsSSH() { return m_supports_ssh; } 569 SetSupportsSSH(bool flag)570 virtual void SetSupportsSSH(bool flag) { m_supports_ssh = flag; } 571 GetSSHOpts()572 virtual const char *GetSSHOpts() { return m_ssh_opts.c_str(); } 573 SetSSHOpts(const char * opts)574 virtual void SetSSHOpts(const char *opts) { m_ssh_opts.assign(opts); } 575 GetIgnoresRemoteHostname()576 virtual bool GetIgnoresRemoteHostname() { return m_ignores_remote_hostname; } 577 SetIgnoresRemoteHostname(bool flag)578 virtual void SetIgnoresRemoteHostname(bool flag) { 579 m_ignores_remote_hostname = flag; 580 } 581 582 virtual lldb_private::OptionGroupOptions * GetConnectionOptions(CommandInterpreter & interpreter)583 GetConnectionOptions(CommandInterpreter &interpreter) { 584 return nullptr; 585 } 586 587 virtual lldb_private::Status RunShellCommand( 588 llvm::StringRef command, 589 const FileSpec &working_dir, // Pass empty FileSpec to use the current 590 // working directory 591 int *status_ptr, // Pass nullptr if you don't want the process exit status 592 int *signo_ptr, // Pass nullptr if you don't want the signal that caused 593 // the process to exit 594 std::string 595 *command_output, // Pass nullptr if you don't want the command output 596 const Timeout<std::micro> &timeout); 597 598 virtual lldb_private::Status RunShellCommand( 599 llvm::StringRef shell, llvm::StringRef command, 600 const FileSpec &working_dir, // Pass empty FileSpec to use the current 601 // working directory 602 int *status_ptr, // Pass nullptr if you don't want the process exit status 603 int *signo_ptr, // Pass nullptr if you don't want the signal that caused 604 // the process to exit 605 std::string 606 *command_output, // Pass nullptr if you don't want the command output 607 const Timeout<std::micro> &timeout); 608 609 virtual void SetLocalCacheDirectory(const char *local); 610 611 virtual const char *GetLocalCacheDirectory(); 612 GetPlatformSpecificConnectionInformation()613 virtual std::string GetPlatformSpecificConnectionInformation() { return ""; } 614 615 virtual bool CalculateMD5(const FileSpec &file_spec, uint64_t &low, 616 uint64_t &high); 617 GetResumeCountForLaunchInfo(ProcessLaunchInfo & launch_info)618 virtual uint32_t GetResumeCountForLaunchInfo(ProcessLaunchInfo &launch_info) { 619 return 1; 620 } 621 622 virtual const lldb::UnixSignalsSP &GetRemoteUnixSignals(); 623 624 lldb::UnixSignalsSP GetUnixSignals(); 625 626 /// Locate a queue name given a thread's qaddr 627 /// 628 /// On a system using libdispatch ("Grand Central Dispatch") style queues, a 629 /// thread may be associated with a GCD queue or not, and a queue may be 630 /// associated with multiple threads. The process/thread must provide a way 631 /// to find the "dispatch_qaddr" for each thread, and from that 632 /// dispatch_qaddr this Platform method will locate the queue name and 633 /// provide that. 634 /// 635 /// \param[in] process 636 /// A process is required for reading memory. 637 /// 638 /// \param[in] dispatch_qaddr 639 /// The dispatch_qaddr for this thread. 640 /// 641 /// \return 642 /// The name of the queue, if there is one. An empty string 643 /// means that this thread is not associated with a dispatch 644 /// queue. 645 virtual std::string GetQueueNameForThreadQAddress(Process * process,lldb::addr_t dispatch_qaddr)646 GetQueueNameForThreadQAddress(Process *process, lldb::addr_t dispatch_qaddr) { 647 return ""; 648 } 649 650 /// Locate a queue ID given a thread's qaddr 651 /// 652 /// On a system using libdispatch ("Grand Central Dispatch") style queues, a 653 /// thread may be associated with a GCD queue or not, and a queue may be 654 /// associated with multiple threads. The process/thread must provide a way 655 /// to find the "dispatch_qaddr" for each thread, and from that 656 /// dispatch_qaddr this Platform method will locate the queue ID and provide 657 /// that. 658 /// 659 /// \param[in] process 660 /// A process is required for reading memory. 661 /// 662 /// \param[in] dispatch_qaddr 663 /// The dispatch_qaddr for this thread. 664 /// 665 /// \return 666 /// The queue_id for this thread, if this thread is associated 667 /// with a dispatch queue. Else LLDB_INVALID_QUEUE_ID is returned. 668 virtual lldb::queue_id_t GetQueueIDForThreadQAddress(Process * process,lldb::addr_t dispatch_qaddr)669 GetQueueIDForThreadQAddress(Process *process, lldb::addr_t dispatch_qaddr) { 670 return LLDB_INVALID_QUEUE_ID; 671 } 672 673 /// Provide a list of trap handler function names for this platform 674 /// 675 /// The unwinder needs to treat trap handlers specially -- the stack frame 676 /// may not be aligned correctly for a trap handler (the kernel often won't 677 /// perturb the stack pointer, or won't re-align it properly, in the process 678 /// of calling the handler) and the frame above the handler needs to be 679 /// treated by the unwinder's "frame 0" rules instead of its "middle of the 680 /// stack frame" rules. 681 /// 682 /// In a user process debugging scenario, the list of trap handlers is 683 /// typically just "_sigtramp". 684 /// 685 /// The Platform base class provides the m_trap_handlers ivar but it does 686 /// not populate it. Subclasses should add the names of the asynchronous 687 /// signal handler routines as needed. For most Unix platforms, add 688 /// _sigtramp. 689 /// 690 /// \return 691 /// A list of symbol names. The list may be empty. 692 virtual const std::vector<ConstString> &GetTrapHandlerSymbolNames(); 693 694 /// Try to get a specific unwind plan for a named trap handler. 695 /// The default is not to have specific unwind plans for trap handlers. 696 /// 697 /// \param[in] triple 698 /// Triple of the current target. 699 /// 700 /// \param[in] name 701 /// Name of the trap handler function. 702 /// 703 /// \return 704 /// A specific unwind plan for that trap handler, or an empty 705 /// shared pointer. The latter means there is no specific plan, 706 /// unwind as normal. 707 virtual lldb::UnwindPlanSP GetTrapHandlerUnwindPlan(const llvm::Triple & triple,ConstString name)708 GetTrapHandlerUnwindPlan(const llvm::Triple &triple, ConstString name) { 709 return {}; 710 } 711 712 /// Find a support executable that may not live within in the standard 713 /// locations related to LLDB. 714 /// 715 /// Executable might exist within the Platform SDK directories, or in 716 /// standard tool directories within the current IDE that is running LLDB. 717 /// 718 /// \param[in] basename 719 /// The basename of the executable to locate in the current 720 /// platform. 721 /// 722 /// \return 723 /// A FileSpec pointing to the executable on disk, or an invalid 724 /// FileSpec if the executable cannot be found. LocateExecutable(const char * basename)725 virtual FileSpec LocateExecutable(const char *basename) { return FileSpec(); } 726 727 /// Allow the platform to set preferred memory cache line size. If non-zero 728 /// (and the user has not set cache line size explicitly), this value will 729 /// be used as the cache line size for memory reads. GetDefaultMemoryCacheLineSize()730 virtual uint32_t GetDefaultMemoryCacheLineSize() { return 0; } 731 732 /// Load a shared library into this process. 733 /// 734 /// Try and load a shared library into the current process. This call might 735 /// fail in the dynamic loader plug-in says it isn't safe to try and load 736 /// shared libraries at the moment. 737 /// 738 /// \param[in] process 739 /// The process to load the image. 740 /// 741 /// \param[in] local_file 742 /// The file spec that points to the shared library that you want 743 /// to load if the library is located on the host. The library will 744 /// be copied over to the location specified by remote_file or into 745 /// the current working directory with the same filename if the 746 /// remote_file isn't specified. 747 /// 748 /// \param[in] remote_file 749 /// If local_file is specified then the location where the library 750 /// should be copied over from the host. If local_file isn't 751 /// specified, then the path for the shared library on the target 752 /// what you want to load. 753 /// 754 /// \param[out] error 755 /// An error object that gets filled in with any errors that 756 /// might occur when trying to load the shared library. 757 /// 758 /// \return 759 /// A token that represents the shared library that can be 760 /// later used to unload the shared library. A value of 761 /// LLDB_INVALID_IMAGE_TOKEN will be returned if the shared 762 /// library can't be opened. 763 uint32_t LoadImage(lldb_private::Process *process, 764 const lldb_private::FileSpec &local_file, 765 const lldb_private::FileSpec &remote_file, 766 lldb_private::Status &error); 767 768 /// Load a shared library specified by base name into this process, 769 /// looking by hand along a set of paths. 770 /// 771 /// \param[in] process 772 /// The process to load the image. 773 /// 774 /// \param[in] library_name 775 /// The name of the library to look for. If library_name is an 776 /// absolute path, the basename will be extracted and searched for 777 /// along the paths. This emulates the behavior of the loader when 778 /// given an install name and a set (e.g. DYLD_LIBRARY_PATH provided) of 779 /// alternate paths. 780 /// 781 /// \param[in] paths 782 /// The list of paths to use to search for the library. First 783 /// match wins. 784 /// 785 /// \param[out] error 786 /// An error object that gets filled in with any errors that 787 /// might occur when trying to load the shared library. 788 /// 789 /// \param[out] loaded_path 790 /// If non-null, the path to the dylib that was successfully loaded 791 /// is stored in this path. 792 /// 793 /// \return 794 /// A token that represents the shared library which can be 795 /// passed to UnloadImage. A value of 796 /// LLDB_INVALID_IMAGE_TOKEN will be returned if the shared 797 /// library can't be opened. 798 uint32_t LoadImageUsingPaths(lldb_private::Process *process, 799 const lldb_private::FileSpec &library_name, 800 const std::vector<std::string> &paths, 801 lldb_private::Status &error, 802 lldb_private::FileSpec *loaded_path); 803 804 virtual uint32_t DoLoadImage(lldb_private::Process *process, 805 const lldb_private::FileSpec &remote_file, 806 const std::vector<std::string> *paths, 807 lldb_private::Status &error, 808 lldb_private::FileSpec *loaded_path = nullptr); 809 810 virtual Status UnloadImage(lldb_private::Process *process, 811 uint32_t image_token); 812 813 /// Connect to all processes waiting for a debugger to attach 814 /// 815 /// If the platform have a list of processes waiting for a debugger to 816 /// connect to them then connect to all of these pending processes. 817 /// 818 /// \param[in] debugger 819 /// The debugger used for the connect. 820 /// 821 /// \param[out] error 822 /// If an error occurred during the connect then this object will 823 /// contain the error message. 824 /// 825 /// \return 826 /// The number of processes we are successfully connected to. 827 virtual size_t ConnectToWaitingProcesses(lldb_private::Debugger &debugger, 828 lldb_private::Status &error); 829 830 /// Gather all of crash informations into a structured data dictionary. 831 /// 832 /// If the platform have a crashed process with crash information entries, 833 /// gather all the entries into an structured data dictionary or return a 834 /// nullptr. This dictionary is generic and extensible, as it contains an 835 /// array for each different type of crash information. 836 /// 837 /// \param[in] process 838 /// The crashed process. 839 /// 840 /// \return 841 /// A structured data dictionary containing at each entry, the crash 842 /// information type as the entry key and the matching an array as the 843 /// entry value. \b nullptr if not implemented or if the process has no 844 /// crash information entry. \b error if an error occured. 845 virtual llvm::Expected<StructuredData::DictionarySP> FetchExtendedCrashInformation(lldb_private::Process & process)846 FetchExtendedCrashInformation(lldb_private::Process &process) { 847 return nullptr; 848 } 849 850 /// Detect a binary in memory that will determine which Platform and 851 /// DynamicLoader should be used in this target/process, and update 852 /// the Platform/DynamicLoader. 853 /// The binary will be loaded into the Target, or will be registered with 854 /// the DynamicLoader so that it will be loaded at a later stage. Returns 855 /// true to indicate that this is a platform binary and has been 856 /// loaded/registered, no further action should be taken by the caller. 857 /// 858 /// \param[in] process 859 /// Process read memory from, a Process must be provided. 860 /// 861 /// \param[in] addr 862 /// Address of a binary in memory. 863 /// 864 /// \param[in] notify 865 /// Whether ModulesDidLoad should be called, if a binary is loaded. 866 /// Caller may prefer to call ModulesDidLoad for multiple binaries 867 /// that were loaded at the same time. 868 /// 869 /// \return 870 /// Returns true if the binary was loaded in the target (or will be 871 /// via a DynamicLoader). Returns false if the binary was not 872 /// loaded/registered, and the caller must load it into the target. LoadPlatformBinaryAndSetup(Process * process,lldb::addr_t addr,bool notify)873 virtual bool LoadPlatformBinaryAndSetup(Process *process, lldb::addr_t addr, 874 bool notify) { 875 return false; 876 } 877 878 virtual CompilerType GetSiginfoType(const llvm::Triple &triple); 879 880 virtual Args GetExtraStartupCommands(); 881 882 protected: 883 /// Create a list of ArchSpecs with the given OS and a architectures. The 884 /// vendor field is left as an "unspecified unknown". 885 static std::vector<ArchSpec> 886 CreateArchList(llvm::ArrayRef<llvm::Triple::ArchType> archs, 887 llvm::Triple::OSType os); 888 889 /// Private implementation of connecting to a process. If the stream is set 890 /// we connect synchronously. 891 lldb::ProcessSP DoConnectProcess(llvm::StringRef connect_url, 892 llvm::StringRef plugin_name, 893 Debugger &debugger, Stream *stream, 894 Target *target, Status &error); 895 bool m_is_host; 896 // Set to true when we are able to actually set the OS version while being 897 // connected. For remote platforms, we might set the version ahead of time 898 // before we actually connect and this version might change when we actually 899 // connect to a remote platform. For the host platform this will be set to 900 // the once we call HostInfo::GetOSVersion(). 901 bool m_os_version_set_while_connected; 902 bool m_system_arch_set_while_connected; 903 ConstString 904 m_sdk_sysroot; // the root location of where the SDK files are all located 905 ConstString m_sdk_build; 906 FileSpec m_working_dir; // The working directory which is used when installing 907 // modules that have no install path set 908 std::string m_remote_url; 909 std::string m_hostname; 910 llvm::VersionTuple m_os_version; 911 ArchSpec 912 m_system_arch; // The architecture of the kernel or the remote platform 913 typedef std::map<uint32_t, ConstString> IDToNameMap; 914 // Mutex for modifying Platform data structures that should only be used for 915 // non-reentrant code 916 std::mutex m_mutex; 917 size_t m_max_uid_name_len; 918 size_t m_max_gid_name_len; 919 bool m_supports_rsync; 920 std::string m_rsync_opts; 921 std::string m_rsync_prefix; 922 bool m_supports_ssh; 923 std::string m_ssh_opts; 924 bool m_ignores_remote_hostname; 925 std::string m_local_cache_directory; 926 std::vector<ConstString> m_trap_handlers; 927 bool m_calculated_trap_handlers; 928 const std::unique_ptr<ModuleCache> m_module_cache; 929 930 /// Ask the Platform subclass to fill in the list of trap handler names 931 /// 932 /// For most Unix user process environments, this will be a single function 933 /// name, _sigtramp. More specialized environments may have additional 934 /// handler names. The unwinder code needs to know when a trap handler is 935 /// on the stack because the unwind rules for the frame that caused the trap 936 /// are different. 937 /// 938 /// The base class Platform ivar m_trap_handlers should be updated by the 939 /// Platform subclass when this method is called. If there are no 940 /// predefined trap handlers, this method may be a no-op. 941 virtual void CalculateTrapHandlerSymbolNames() = 0; 942 943 Status GetCachedExecutable(ModuleSpec &module_spec, lldb::ModuleSP &module_sp, 944 const FileSpecList *module_search_paths_ptr); 945 946 virtual Status DownloadModuleSlice(const FileSpec &src_file_spec, 947 const uint64_t src_offset, 948 const uint64_t src_size, 949 const FileSpec &dst_file_spec); 950 951 virtual Status DownloadSymbolFile(const lldb::ModuleSP &module_sp, 952 const FileSpec &dst_file_spec); 953 954 virtual const char *GetCacheHostname(); 955 956 virtual Status 957 ResolveRemoteExecutable(const ModuleSpec &module_spec, 958 lldb::ModuleSP &exe_module_sp, 959 const FileSpecList *module_search_paths_ptr); 960 961 private: 962 typedef std::function<Status(const ModuleSpec &)> ModuleResolver; 963 964 Status GetRemoteSharedModule(const ModuleSpec &module_spec, Process *process, 965 lldb::ModuleSP &module_sp, 966 const ModuleResolver &module_resolver, 967 bool *did_create_ptr); 968 969 bool GetCachedSharedModule(const ModuleSpec &module_spec, 970 lldb::ModuleSP &module_sp, bool *did_create_ptr); 971 972 FileSpec GetModuleCacheRoot(); 973 }; 974 975 class PlatformList { 976 public: 977 PlatformList() = default; 978 979 ~PlatformList() = default; 980 Append(const lldb::PlatformSP & platform_sp,bool set_selected)981 void Append(const lldb::PlatformSP &platform_sp, bool set_selected) { 982 std::lock_guard<std::recursive_mutex> guard(m_mutex); 983 m_platforms.push_back(platform_sp); 984 if (set_selected) 985 m_selected_platform_sp = m_platforms.back(); 986 } 987 GetSize()988 size_t GetSize() { 989 std::lock_guard<std::recursive_mutex> guard(m_mutex); 990 return m_platforms.size(); 991 } 992 GetAtIndex(uint32_t idx)993 lldb::PlatformSP GetAtIndex(uint32_t idx) { 994 lldb::PlatformSP platform_sp; 995 { 996 std::lock_guard<std::recursive_mutex> guard(m_mutex); 997 if (idx < m_platforms.size()) 998 platform_sp = m_platforms[idx]; 999 } 1000 return platform_sp; 1001 } 1002 1003 /// Select the active platform. 1004 /// 1005 /// In order to debug remotely, other platform's can be remotely connected 1006 /// to and set as the selected platform for any subsequent debugging. This 1007 /// allows connection to remote targets and allows the ability to discover 1008 /// process info, launch and attach to remote processes. GetSelectedPlatform()1009 lldb::PlatformSP GetSelectedPlatform() { 1010 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1011 if (!m_selected_platform_sp && !m_platforms.empty()) 1012 m_selected_platform_sp = m_platforms.front(); 1013 1014 return m_selected_platform_sp; 1015 } 1016 SetSelectedPlatform(const lldb::PlatformSP & platform_sp)1017 void SetSelectedPlatform(const lldb::PlatformSP &platform_sp) { 1018 if (platform_sp) { 1019 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1020 const size_t num_platforms = m_platforms.size(); 1021 for (size_t idx = 0; idx < num_platforms; ++idx) { 1022 if (m_platforms[idx].get() == platform_sp.get()) { 1023 m_selected_platform_sp = m_platforms[idx]; 1024 return; 1025 } 1026 } 1027 m_platforms.push_back(platform_sp); 1028 m_selected_platform_sp = m_platforms.back(); 1029 } 1030 } 1031 1032 lldb::PlatformSP GetOrCreate(llvm::StringRef name); 1033 lldb::PlatformSP GetOrCreate(const ArchSpec &arch, 1034 const ArchSpec &process_host_arch, 1035 ArchSpec *platform_arch_ptr, Status &error); 1036 lldb::PlatformSP GetOrCreate(const ArchSpec &arch, 1037 const ArchSpec &process_host_arch, 1038 ArchSpec *platform_arch_ptr); 1039 1040 /// Get the platform for the given list of architectures. 1041 /// 1042 /// The algorithm works a follows: 1043 /// 1044 /// 1. Returns the selected platform if it matches any of the architectures. 1045 /// 2. Returns the host platform if it matches any of the architectures. 1046 /// 3. Returns the platform that matches all the architectures. 1047 /// 1048 /// If none of the above apply, this function returns a default platform. The 1049 /// candidates output argument differentiates between either no platforms 1050 /// supporting the given architecture or multiple platforms supporting the 1051 /// given architecture. 1052 lldb::PlatformSP GetOrCreate(llvm::ArrayRef<ArchSpec> archs, 1053 const ArchSpec &process_host_arch, 1054 std::vector<lldb::PlatformSP> &candidates); 1055 1056 lldb::PlatformSP Create(llvm::StringRef name); 1057 1058 /// Detect a binary in memory that will determine which Platform and 1059 /// DynamicLoader should be used in this target/process, and update 1060 /// the Platform/DynamicLoader. 1061 /// The binary will be loaded into the Target, or will be registered with 1062 /// the DynamicLoader so that it will be loaded at a later stage. Returns 1063 /// true to indicate that this is a platform binary and has been 1064 /// loaded/registered, no further action should be taken by the caller. 1065 /// 1066 /// \param[in] process 1067 /// Process read memory from, a Process must be provided. 1068 /// 1069 /// \param[in] addr 1070 /// Address of a binary in memory. 1071 /// 1072 /// \param[in] notify 1073 /// Whether ModulesDidLoad should be called, if a binary is loaded. 1074 /// Caller may prefer to call ModulesDidLoad for multiple binaries 1075 /// that were loaded at the same time. 1076 /// 1077 /// \return 1078 /// Returns true if the binary was loaded in the target (or will be 1079 /// via a DynamicLoader). Returns false if the binary was not 1080 /// loaded/registered, and the caller must load it into the target. 1081 bool LoadPlatformBinaryAndSetup(Process *process, lldb::addr_t addr, 1082 bool notify); 1083 1084 protected: 1085 typedef std::vector<lldb::PlatformSP> collection; 1086 mutable std::recursive_mutex m_mutex; 1087 collection m_platforms; 1088 lldb::PlatformSP m_selected_platform_sp; 1089 1090 private: 1091 PlatformList(const PlatformList &) = delete; 1092 const PlatformList &operator=(const PlatformList &) = delete; 1093 }; 1094 1095 class OptionGroupPlatformRSync : public lldb_private::OptionGroup { 1096 public: 1097 OptionGroupPlatformRSync() = default; 1098 1099 ~OptionGroupPlatformRSync() override = default; 1100 1101 lldb_private::Status 1102 SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, 1103 ExecutionContext *execution_context) override; 1104 1105 void OptionParsingStarting(ExecutionContext *execution_context) override; 1106 1107 llvm::ArrayRef<OptionDefinition> GetDefinitions() override; 1108 1109 // Instance variables to hold the values for command options. 1110 1111 bool m_rsync; 1112 std::string m_rsync_opts; 1113 std::string m_rsync_prefix; 1114 bool m_ignores_remote_hostname; 1115 1116 private: 1117 OptionGroupPlatformRSync(const OptionGroupPlatformRSync &) = delete; 1118 const OptionGroupPlatformRSync & 1119 operator=(const OptionGroupPlatformRSync &) = delete; 1120 }; 1121 1122 class OptionGroupPlatformSSH : public lldb_private::OptionGroup { 1123 public: 1124 OptionGroupPlatformSSH() = default; 1125 1126 ~OptionGroupPlatformSSH() override = default; 1127 1128 lldb_private::Status 1129 SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, 1130 ExecutionContext *execution_context) override; 1131 1132 void OptionParsingStarting(ExecutionContext *execution_context) override; 1133 1134 llvm::ArrayRef<OptionDefinition> GetDefinitions() override; 1135 1136 // Instance variables to hold the values for command options. 1137 1138 bool m_ssh; 1139 std::string m_ssh_opts; 1140 1141 private: 1142 OptionGroupPlatformSSH(const OptionGroupPlatformSSH &) = delete; 1143 const OptionGroupPlatformSSH & 1144 operator=(const OptionGroupPlatformSSH &) = delete; 1145 }; 1146 1147 class OptionGroupPlatformCaching : public lldb_private::OptionGroup { 1148 public: 1149 OptionGroupPlatformCaching() = default; 1150 1151 ~OptionGroupPlatformCaching() override = default; 1152 1153 lldb_private::Status 1154 SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, 1155 ExecutionContext *execution_context) override; 1156 1157 void OptionParsingStarting(ExecutionContext *execution_context) override; 1158 1159 llvm::ArrayRef<OptionDefinition> GetDefinitions() override; 1160 1161 // Instance variables to hold the values for command options. 1162 1163 std::string m_cache_dir; 1164 1165 private: 1166 OptionGroupPlatformCaching(const OptionGroupPlatformCaching &) = delete; 1167 const OptionGroupPlatformCaching & 1168 operator=(const OptionGroupPlatformCaching &) = delete; 1169 }; 1170 1171 } // namespace lldb_private 1172 1173 #endif // LLDB_TARGET_PLATFORM_H 1174