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