Index: head/contrib/llvm/tools/lldb/include/lldb/Target/Platform.h =================================================================== --- head/contrib/llvm/tools/lldb/include/lldb/Target/Platform.h (revision 322325) +++ head/contrib/llvm/tools/lldb/include/lldb/Target/Platform.h (revision 322326) @@ -1,1169 +1,1173 @@ //===-- Platform.h ----------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef liblldb_Platform_h_ #define liblldb_Platform_h_ // C Includes // C++ Includes #include #include #include #include #include #include // Other libraries and framework includes // Project includes #include "lldb/Core/ArchSpec.h" #include "lldb/Core/PluginInterface.h" #include "lldb/Core/UserSettingsController.h" #include "lldb/Interpreter/Options.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/FileSpec.h" #include "lldb/lldb-private-forward.h" #include "lldb/lldb-public.h" // TODO pull NativeDelegate class out of NativeProcessProtocol so we // can just forward ref the NativeDelegate rather than include it here. #include "lldb/Host/common/NativeProcessProtocol.h" namespace lldb_private { class ModuleCache; enum MmapFlags { eMmapFlagsPrivate = 1, eMmapFlagsAnon = 2 }; class PlatformProperties : public Properties { public: PlatformProperties(); static ConstString GetSettingName(); bool GetUseModuleCache() const; bool SetUseModuleCache(bool use_module_cache); FileSpec GetModuleCacheDirectory() const; bool SetModuleCacheDirectory(const FileSpec &dir_spec); }; typedef std::shared_ptr PlatformPropertiesSP; +typedef llvm::SmallVector MmapArgList; //---------------------------------------------------------------------- /// @class Platform Platform.h "lldb/Target/Platform.h" /// @brief A plug-in interface definition class for debug platform that /// includes many platform abilities such as: /// @li getting platform information such as supported architectures, /// supported binary file formats and more /// @li launching new processes /// @li attaching to existing processes /// @li download/upload files /// @li execute shell commands /// @li listing and getting info for existing processes /// @li attaching and possibly debugging the platform's kernel //---------------------------------------------------------------------- class Platform : public PluginInterface { public: //------------------------------------------------------------------ /// Default Constructor //------------------------------------------------------------------ Platform(bool is_host_platform); //------------------------------------------------------------------ /// Destructor. /// /// The destructor is virtual since this class is designed to be /// inherited from by the plug-in instance. //------------------------------------------------------------------ ~Platform() override; static void Initialize(); static void Terminate(); static const PlatformPropertiesSP &GetGlobalPlatformProperties(); //------------------------------------------------------------------ /// Get the native host platform plug-in. /// /// There should only be one of these for each host that LLDB runs /// upon that should be statically compiled in and registered using /// preprocessor macros or other similar build mechanisms in a /// PlatformSubclass::Initialize() function. /// /// This platform will be used as the default platform when launching /// or attaching to processes unless another platform is specified. //------------------------------------------------------------------ static lldb::PlatformSP GetHostPlatform(); static lldb::PlatformSP GetPlatformForArchitecture(const ArchSpec &arch, ArchSpec *platform_arch_ptr); static const char *GetHostPlatformName(); static void SetHostPlatform(const lldb::PlatformSP &platform_sp); // Find an existing platform plug-in by name static lldb::PlatformSP Find(const ConstString &name); static lldb::PlatformSP Create(const ConstString &name, Status &error); static lldb::PlatformSP Create(const ArchSpec &arch, ArchSpec *platform_arch_ptr, Status &error); static uint32_t GetNumConnectedRemotePlatforms(); static lldb::PlatformSP GetConnectedRemotePlatformAtIndex(uint32_t idx); //------------------------------------------------------------------ /// Find a platform plugin for a given process. /// /// Scans the installed Platform plug-ins and tries to find /// an instance that can be used for \a process /// /// @param[in] process /// The process for which to try and locate a platform /// plug-in instance. /// /// @param[in] plugin_name /// An optional name of a specific platform plug-in that /// should be used. If nullptr, pick the best plug-in. //------------------------------------------------------------------ // static lldb::PlatformSP // FindPlugin (Process *process, const ConstString &plugin_name); //------------------------------------------------------------------ /// Set the target's executable based off of the existing /// architecture information in \a target given a path to an /// executable \a exe_file. /// /// Each platform knows the architectures that it supports and can /// select the correct architecture slice within \a exe_file by /// inspecting the architecture in \a target. If the target had an /// architecture specified, then in can try and obey that request /// and optionally fail if the architecture doesn't match up. /// If no architecture is specified, the platform should select the /// default architecture from \a exe_file. Any application bundles /// or executable wrappers can also be inspected for the actual /// application binary within the bundle that should be used. /// /// @return /// Returns \b true if this Platform plug-in was able to find /// a suitable executable, \b false otherwise. //------------------------------------------------------------------ virtual Status ResolveExecutable(const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, const FileSpecList *module_search_paths_ptr); //------------------------------------------------------------------ /// Find a symbol file given a symbol file module specification. /// /// Each platform might have tricks to find symbol files for an /// executable given information in a symbol file ModuleSpec. Some /// platforms might also support symbol files that are bundles and /// know how to extract the right symbol file given a bundle. /// /// @param[in] target /// The target in which we are trying to resolve the symbol file. /// The target has a list of modules that we might be able to /// use in order to help find the right symbol file. If the /// "m_file" or "m_platform_file" entries in the \a sym_spec /// are filled in, then we might be able to locate a module in /// the target, extract its UUID and locate a symbol file. /// If just the "m_uuid" is specified, then we might be able /// to find the module in the target that matches that UUID /// and pair the symbol file along with it. If just "m_symbol_file" /// is specified, we can use a variety of tricks to locate the /// symbols in an SDK, PDK, or other development kit location. /// /// @param[in] sym_spec /// A module spec that describes some information about the /// symbol file we are trying to resolve. The ModuleSpec might /// contain the following: /// m_file - A full or partial path to an executable from the /// target (might be empty). /// m_platform_file - Another executable hint that contains /// the path to the file as known on the /// local/remote platform. /// m_symbol_file - A full or partial path to a symbol file /// or symbol bundle that should be used when /// trying to resolve the symbol file. /// m_arch - The architecture we are looking for when resolving /// the symbol file. /// m_uuid - The UUID of the executable and symbol file. This /// can often be used to match up an executable with /// a symbol file, or resolve an symbol file in a /// symbol file bundle. /// /// @param[out] sym_file /// The resolved symbol file spec if the returned error /// indicates success. /// /// @return /// Returns an error that describes success or failure. //------------------------------------------------------------------ virtual Status ResolveSymbolFile(Target &target, const ModuleSpec &sym_spec, FileSpec &sym_file); //------------------------------------------------------------------ /// Resolves the FileSpec to a (possibly) remote path. Remote /// platforms must override this to resolve to a path on the remote /// side. //------------------------------------------------------------------ virtual bool ResolveRemotePath(const FileSpec &platform_path, FileSpec &resolved_platform_path); //------------------------------------------------------------------ /// Get the OS version from a connected platform. /// /// Some platforms might not be connected to a remote platform, but /// can figure out the OS version for a process. This is common for /// simulator platforms that will run native programs on the current /// host, but the simulator might be simulating a different OS. The /// \a process parameter might be specified to help to determine /// the OS version. //------------------------------------------------------------------ virtual bool GetOSVersion(uint32_t &major, uint32_t &minor, uint32_t &update, Process *process = nullptr); bool SetOSVersion(uint32_t major, uint32_t minor, uint32_t update); bool GetOSBuildString(std::string &s); bool GetOSKernelDescription(std::string &s); // Returns the name of the platform ConstString GetName(); virtual const char *GetHostname(); virtual ConstString GetFullNameForDylib(ConstString basename); virtual const char *GetDescription() = 0; //------------------------------------------------------------------ /// Report the current status for this platform. /// /// The returned string usually involves returning the OS version /// (if available), and any SDK directory that might be being used /// for local file caching, and if connected a quick blurb about /// what this platform is connected to. //------------------------------------------------------------------ virtual void GetStatus(Stream &strm); //------------------------------------------------------------------ // Subclasses must be able to fetch the current OS version // // Remote classes must be connected for this to succeed. Local // subclasses don't need to override this function as it will just // call the HostInfo::GetOSVersion(). //------------------------------------------------------------------ virtual bool GetRemoteOSVersion() { return false; } virtual bool GetRemoteOSBuildString(std::string &s) { s.clear(); return false; } virtual bool GetRemoteOSKernelDescription(std::string &s) { s.clear(); return false; } // Remote Platform subclasses need to override this function virtual ArchSpec GetRemoteSystemArchitecture() { return ArchSpec(); // Return an invalid architecture } virtual FileSpec GetRemoteWorkingDirectory() { return m_working_dir; } virtual bool SetRemoteWorkingDirectory(const FileSpec &working_dir); virtual const char *GetUserName(uint32_t uid); virtual const char *GetGroupName(uint32_t gid); //------------------------------------------------------------------ /// Locate a file for a platform. /// /// The default implementation of this function will return the same /// file patch in \a local_file as was in \a platform_file. /// /// @param[in] platform_file /// The platform file path to locate and cache locally. /// /// @param[in] uuid_ptr /// If we know the exact UUID of the file we are looking for, it /// can be specified. If it is not specified, we might now know /// the exact file. The UUID is usually some sort of MD5 checksum /// for the file and is sometimes known by dynamic linkers/loaders. /// If the UUID is known, it is best to supply it to platform /// file queries to ensure we are finding the correct file, not /// just a file at the correct path. /// /// @param[out] local_file /// A locally cached version of the platform file. For platforms /// that describe the current host computer, this will just be /// the same file. For remote platforms, this file might come from /// and SDK directory, or might need to be sync'ed over to the /// current machine for efficient debugging access. /// /// @return /// An error object. //------------------------------------------------------------------ virtual Status GetFileWithUUID(const FileSpec &platform_file, const UUID *uuid_ptr, FileSpec &local_file); //---------------------------------------------------------------------- // Locate the scripting resource given a module specification. // // Locating the file should happen only on the local computer or using // the current computers global settings. //---------------------------------------------------------------------- virtual FileSpecList LocateExecutableScriptingResources(Target *target, Module &module, Stream *feedback_stream); virtual Status GetSharedModule(const ModuleSpec &module_spec, Process *process, lldb::ModuleSP &module_sp, const FileSpecList *module_search_paths_ptr, lldb::ModuleSP *old_module_sp_ptr, bool *did_create_ptr); virtual bool GetModuleSpec(const FileSpec &module_file_spec, const ArchSpec &arch, ModuleSpec &module_spec); virtual Status ConnectRemote(Args &args); virtual Status DisconnectRemote(); //------------------------------------------------------------------ /// Get the platform's supported architectures in the order in which /// they should be searched. /// /// @param[in] idx /// A zero based architecture index /// /// @param[out] arch /// A copy of the architecture at index if the return value is /// \b true. /// /// @return /// \b true if \a arch was filled in and is valid, \b false /// otherwise. //------------------------------------------------------------------ virtual bool GetSupportedArchitectureAtIndex(uint32_t idx, ArchSpec &arch) = 0; virtual size_t GetSoftwareBreakpointTrapOpcode(Target &target, BreakpointSite *bp_site); //------------------------------------------------------------------ /// Launch a new process on a platform, not necessarily for /// debugging, it could be just for running the process. //------------------------------------------------------------------ virtual Status LaunchProcess(ProcessLaunchInfo &launch_info); //------------------------------------------------------------------ /// Perform expansion of the command-line for this launch info /// This can potentially involve wildcard expansion // environment variable replacement, and whatever other // argument magic the platform defines as part of its typical // user experience //------------------------------------------------------------------ virtual Status ShellExpandArguments(ProcessLaunchInfo &launch_info); //------------------------------------------------------------------ /// Kill process on a platform. //------------------------------------------------------------------ virtual Status KillProcess(const lldb::pid_t pid); //------------------------------------------------------------------ /// Lets a platform answer if it is compatible with a given /// architecture and the target triple contained within. //------------------------------------------------------------------ virtual bool IsCompatibleArchitecture(const ArchSpec &arch, bool exact_arch_match, ArchSpec *compatible_arch_ptr); //------------------------------------------------------------------ /// Not all platforms will support debugging a process by spawning /// somehow halted for a debugger (specified using the /// "eLaunchFlagDebug" launch flag) and then attaching. If your /// platform doesn't support this, override this function and return /// false. //------------------------------------------------------------------ virtual bool CanDebugProcess() { return true; } //------------------------------------------------------------------ /// Subclasses do not need to implement this function as it uses /// the Platform::LaunchProcess() followed by Platform::Attach (). /// Remote platforms will want to subclass this function in order /// to be able to intercept STDIO and possibly launch a separate /// process that will debug the debuggee. //------------------------------------------------------------------ virtual lldb::ProcessSP DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger, Target *target, // Can be nullptr, if nullptr create a new // target, else use existing one Status &error); virtual lldb::ProcessSP ConnectProcess(llvm::StringRef connect_url, llvm::StringRef plugin_name, lldb_private::Debugger &debugger, lldb_private::Target *target, lldb_private::Status &error); //------------------------------------------------------------------ /// Attach to an existing process using a process ID. /// /// Each platform subclass needs to implement this function and /// attempt to attach to the process with the process ID of \a pid. /// The platform subclass should return an appropriate ProcessSP /// subclass that is attached to the process, or an empty shared /// pointer with an appropriate error. /// /// @param[in] pid /// The process ID that we should attempt to attach to. /// /// @return /// An appropriate ProcessSP containing a valid shared pointer /// to the default Process subclass for the platform that is /// attached to the process, or an empty shared pointer with an /// appropriate error fill into the \a error object. //------------------------------------------------------------------ virtual lldb::ProcessSP Attach(ProcessAttachInfo &attach_info, Debugger &debugger, Target *target, // Can be nullptr, if nullptr // create a new target, else // use existing one Status &error) = 0; //------------------------------------------------------------------ /// Attach to an existing process by process name. /// /// This function is not meant to be overridden by Process /// subclasses. It will first call /// Process::WillAttach (const char *) and if that returns \b /// true, Process::DoAttach (const char *) will be called to /// actually do the attach. If DoAttach returns \b true, then /// Process::DidAttach() will be called. /// /// @param[in] process_name /// A process name to match against the current process list. /// /// @return /// Returns \a pid if attaching was successful, or /// LLDB_INVALID_PROCESS_ID if attaching fails. //------------------------------------------------------------------ // virtual lldb::ProcessSP // Attach (const char *process_name, // bool wait_for_launch, // Status &error) = 0; //------------------------------------------------------------------ // The base class Platform will take care of the host platform. // Subclasses will need to fill in the remote case. //------------------------------------------------------------------ virtual uint32_t FindProcesses(const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &proc_infos); virtual bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &proc_info); //------------------------------------------------------------------ // Set a breakpoint on all functions that can end up creating a thread // for this platform. This is needed when running expressions and // also for process control. //------------------------------------------------------------------ virtual lldb::BreakpointSP SetThreadCreationBreakpoint(Target &target); //------------------------------------------------------------------ // Given a target, find the local SDK directory if one exists on the // current host. //------------------------------------------------------------------ virtual lldb_private::ConstString GetSDKDirectory(lldb_private::Target &target) { return lldb_private::ConstString(); } const std::string &GetRemoteURL() const { return m_remote_url; } bool IsHost() const { return m_is_host; // Is this the default host platform? } bool IsRemote() const { return !m_is_host; } virtual bool IsConnected() const { // Remote subclasses should override this function return IsHost(); } const ArchSpec &GetSystemArchitecture(); void SetSystemArchitecture(const ArchSpec &arch) { m_system_arch = arch; if (IsHost()) m_os_version_set_while_connected = m_system_arch.IsValid(); } // Used for column widths size_t GetMaxUserIDNameLength() const { return m_max_uid_name_len; } // Used for column widths size_t GetMaxGroupIDNameLength() const { return m_max_gid_name_len; } const ConstString &GetSDKRootDirectory() const { return m_sdk_sysroot; } void SetSDKRootDirectory(const ConstString &dir) { m_sdk_sysroot = dir; } const ConstString &GetSDKBuild() const { return m_sdk_build; } void SetSDKBuild(const ConstString &sdk_build) { m_sdk_build = sdk_build; } // Override this to return true if your platform supports Clang modules. // You may also need to override AddClangModuleCompilationOptions to pass the // right Clang flags for your platform. virtual bool SupportsModules() { return false; } // Appends the platform-specific options required to find the modules for the // current platform. virtual void AddClangModuleCompilationOptions(Target *target, std::vector &options); FileSpec GetWorkingDirectory(); bool SetWorkingDirectory(const FileSpec &working_dir); // There may be modules that we don't want to find by default for operations // like "setting breakpoint by name". // The platform will return "true" from this call if the passed in module // happens to be one of these. virtual bool ModuleIsExcludedForUnconstrainedSearches(Target &target, const lldb::ModuleSP &module_sp) { return false; } virtual Status MakeDirectory(const FileSpec &file_spec, uint32_t permissions); virtual Status GetFilePermissions(const FileSpec &file_spec, uint32_t &file_permissions); virtual Status SetFilePermissions(const FileSpec &file_spec, uint32_t file_permissions); virtual lldb::user_id_t OpenFile(const FileSpec &file_spec, uint32_t flags, uint32_t mode, Status &error) { return UINT64_MAX; } virtual bool CloseFile(lldb::user_id_t fd, Status &error) { return false; } virtual lldb::user_id_t GetFileSize(const FileSpec &file_spec) { return UINT64_MAX; } virtual uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, uint64_t dst_len, Status &error) { error.SetErrorStringWithFormat( "Platform::ReadFile() is not supported in the %s platform", GetName().GetCString()); return -1; } virtual uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src, uint64_t src_len, Status &error) { error.SetErrorStringWithFormat( "Platform::ReadFile() is not supported in the %s platform", GetName().GetCString()); return -1; } virtual Status GetFile(const FileSpec &source, const FileSpec &destination); virtual Status PutFile(const FileSpec &source, const FileSpec &destination, uint32_t uid = UINT32_MAX, uint32_t gid = UINT32_MAX); virtual Status CreateSymlink(const FileSpec &src, // The name of the link is in src const FileSpec &dst); // The symlink points to dst //---------------------------------------------------------------------- /// Install a file or directory to the remote system. /// /// Install is similar to Platform::PutFile(), but it differs in that if /// an application/framework/shared library is installed on a remote /// platform and the remote platform requires something to be done to /// register the application/framework/shared library, then this extra /// registration can be done. /// /// @param[in] src /// The source file/directory to install on the remote system. /// /// @param[in] dst /// The destination file/directory where \a src will be installed. /// If \a dst has no filename specified, then its filename will /// be set from \a src. It \a dst has no directory specified, it /// will use the platform working directory. If \a dst has a /// directory specified, but the directory path is relative, the /// platform working directory will be prepended to the relative /// directory. /// /// @return /// An error object that describes anything that went wrong. //---------------------------------------------------------------------- virtual Status Install(const FileSpec &src, const FileSpec &dst); virtual size_t GetEnvironment(StringList &environment); virtual bool GetFileExists(const lldb_private::FileSpec &file_spec); virtual Status Unlink(const FileSpec &file_spec); - virtual uint64_t ConvertMmapFlagsToPlatform(const ArchSpec &arch, - unsigned flags); + virtual MmapArgList GetMmapArgumentList(const ArchSpec &arch, + lldb::addr_t addr, + lldb::addr_t length, + unsigned prot, unsigned flags, + lldb::addr_t fd, lldb::addr_t offset); virtual bool GetSupportsRSync() { return m_supports_rsync; } virtual void SetSupportsRSync(bool flag) { m_supports_rsync = flag; } virtual const char *GetRSyncOpts() { return m_rsync_opts.c_str(); } virtual void SetRSyncOpts(const char *opts) { m_rsync_opts.assign(opts); } virtual const char *GetRSyncPrefix() { return m_rsync_prefix.c_str(); } virtual void SetRSyncPrefix(const char *prefix) { m_rsync_prefix.assign(prefix); } virtual bool GetSupportsSSH() { return m_supports_ssh; } virtual void SetSupportsSSH(bool flag) { m_supports_ssh = flag; } virtual const char *GetSSHOpts() { return m_ssh_opts.c_str(); } virtual void SetSSHOpts(const char *opts) { m_ssh_opts.assign(opts); } virtual bool GetIgnoresRemoteHostname() { return m_ignores_remote_hostname; } virtual void SetIgnoresRemoteHostname(bool flag) { m_ignores_remote_hostname = flag; } virtual lldb_private::OptionGroupOptions * GetConnectionOptions(CommandInterpreter &interpreter) { return nullptr; } virtual lldb_private::Status RunShellCommand( const char *command, // Shouldn't be nullptr const FileSpec &working_dir, // Pass empty FileSpec to use the current // working directory int *status_ptr, // Pass nullptr if you don't want the process exit status int *signo_ptr, // Pass nullptr if you don't want the signal that caused // the process to exit std::string *command_output, // Pass nullptr if you don't want the command output uint32_t timeout_sec); // Timeout in seconds to wait for shell program to // finish virtual void SetLocalCacheDirectory(const char *local); virtual const char *GetLocalCacheDirectory(); virtual std::string GetPlatformSpecificConnectionInformation() { return ""; } virtual bool CalculateMD5(const FileSpec &file_spec, uint64_t &low, uint64_t &high); virtual int32_t GetResumeCountForLaunchInfo(ProcessLaunchInfo &launch_info) { return 1; } virtual const lldb::UnixSignalsSP &GetRemoteUnixSignals(); const lldb::UnixSignalsSP &GetUnixSignals(); //------------------------------------------------------------------ /// Locate a queue name given a thread's qaddr /// /// On a system using libdispatch ("Grand Central Dispatch") style /// queues, a thread may be associated with a GCD queue or not, /// and a queue may be associated with multiple threads. /// The process/thread must provide a way to find the "dispatch_qaddr" /// for each thread, and from that dispatch_qaddr this Platform method /// will locate the queue name and provide that. /// /// @param[in] process /// A process is required for reading memory. /// /// @param[in] dispatch_qaddr /// The dispatch_qaddr for this thread. /// /// @return /// The name of the queue, if there is one. An empty string /// means that this thread is not associated with a dispatch /// queue. //------------------------------------------------------------------ virtual std::string GetQueueNameForThreadQAddress(Process *process, lldb::addr_t dispatch_qaddr) { return ""; } //------------------------------------------------------------------ /// Locate a queue ID given a thread's qaddr /// /// On a system using libdispatch ("Grand Central Dispatch") style /// queues, a thread may be associated with a GCD queue or not, /// and a queue may be associated with multiple threads. /// The process/thread must provide a way to find the "dispatch_qaddr" /// for each thread, and from that dispatch_qaddr this Platform method /// will locate the queue ID and provide that. /// /// @param[in] process /// A process is required for reading memory. /// /// @param[in] dispatch_qaddr /// The dispatch_qaddr for this thread. /// /// @return /// The queue_id for this thread, if this thread is associated /// with a dispatch queue. Else LLDB_INVALID_QUEUE_ID is returned. //------------------------------------------------------------------ virtual lldb::queue_id_t GetQueueIDForThreadQAddress(Process *process, lldb::addr_t dispatch_qaddr) { return LLDB_INVALID_QUEUE_ID; } //------------------------------------------------------------------ /// Provide a list of trap handler function names for this platform /// /// The unwinder needs to treat trap handlers specially -- the stack /// frame may not be aligned correctly for a trap handler (the kernel /// often won't perturb the stack pointer, or won't re-align it properly, /// in the process of calling the handler) and the frame above the handler /// needs to be treated by the unwinder's "frame 0" rules instead of its /// "middle of the stack frame" rules. /// /// In a user process debugging scenario, the list of trap handlers is /// typically just "_sigtramp". /// /// The Platform base class provides the m_trap_handlers ivar but it does /// not populate it. Subclasses should add the names of the asynchronous /// signal handler routines as needed. For most Unix platforms, add /// _sigtramp. /// /// @return /// A list of symbol names. The list may be empty. //------------------------------------------------------------------ virtual const std::vector &GetTrapHandlerSymbolNames(); //------------------------------------------------------------------ /// Find a support executable that may not live within in the /// standard locations related to LLDB. /// /// Executable might exist within the Platform SDK directories, or /// in standard tool directories within the current IDE that is /// running LLDB. /// /// @param[in] basename /// The basename of the executable to locate in the current /// platform. /// /// @return /// A FileSpec pointing to the executable on disk, or an invalid /// FileSpec if the executable cannot be found. //------------------------------------------------------------------ virtual FileSpec LocateExecutable(const char *basename) { return FileSpec(); } //------------------------------------------------------------------ /// Allow the platform to set preferred memory cache line size. If non-zero /// (and the user /// has not set cache line size explicitly), this value will be used as the /// cache line /// size for memory reads. //------------------------------------------------------------------ virtual uint32_t GetDefaultMemoryCacheLineSize() { return 0; } //------------------------------------------------------------------ /// Load a shared library into this process. /// /// Try and load a shared library into the current process. This /// call might fail in the dynamic loader plug-in says it isn't safe /// to try and load shared libraries at the moment. /// /// @param[in] process /// The process to load the image. /// /// @param[in] local_file /// The file spec that points to the shared library that you want /// to load if the library is located on the host. The library will /// be copied over to the location specified by remote_file or into /// the current working directory with the same filename if the /// remote_file isn't specified. /// /// @param[in] remote_file /// If local_file is specified then the location where the library /// should be copied over from the host. If local_file isn't /// specified, then the path for the shared library on the target /// what you want to load. /// /// @param[out] error /// An error object that gets filled in with any errors that /// might occur when trying to load the shared library. /// /// @return /// A token that represents the shared library that can be /// later used to unload the shared library. A value of /// LLDB_INVALID_IMAGE_TOKEN will be returned if the shared /// library can't be opened. //------------------------------------------------------------------ uint32_t LoadImage(lldb_private::Process *process, const lldb_private::FileSpec &local_file, const lldb_private::FileSpec &remote_file, lldb_private::Status &error); virtual uint32_t DoLoadImage(lldb_private::Process *process, const lldb_private::FileSpec &remote_file, lldb_private::Status &error); virtual Status UnloadImage(lldb_private::Process *process, uint32_t image_token); //------------------------------------------------------------------ /// Connect to all processes waiting for a debugger to attach /// /// If the platform have a list of processes waiting for a debugger /// to connect to them then connect to all of these pending processes. /// /// @param[in] debugger /// The debugger used for the connect. /// /// @param[out] error /// If an error occurred during the connect then this object will /// contain the error message. /// /// @return /// The number of processes we are successfully connected to. //------------------------------------------------------------------ virtual size_t ConnectToWaitingProcesses(lldb_private::Debugger &debugger, lldb_private::Status &error); protected: bool m_is_host; // Set to true when we are able to actually set the OS version while // being connected. For remote platforms, we might set the version ahead // of time before we actually connect and this version might change when // we actually connect to a remote platform. For the host platform this // will be set to the once we call HostInfo::GetOSVersion(). bool m_os_version_set_while_connected; bool m_system_arch_set_while_connected; ConstString m_sdk_sysroot; // the root location of where the SDK files are all located ConstString m_sdk_build; FileSpec m_working_dir; // The working directory which is used when installing // modules that have no install path set std::string m_remote_url; std::string m_name; uint32_t m_major_os_version; uint32_t m_minor_os_version; uint32_t m_update_os_version; ArchSpec m_system_arch; // The architecture of the kernel or the remote platform typedef std::map IDToNameMap; // Mutex for modifying Platform data structures that should only be used for // non-reentrant code std::mutex m_mutex; IDToNameMap m_uid_map; IDToNameMap m_gid_map; size_t m_max_uid_name_len; size_t m_max_gid_name_len; bool m_supports_rsync; std::string m_rsync_opts; std::string m_rsync_prefix; bool m_supports_ssh; std::string m_ssh_opts; bool m_ignores_remote_hostname; std::string m_local_cache_directory; std::vector m_trap_handlers; bool m_calculated_trap_handlers; const std::unique_ptr m_module_cache; //------------------------------------------------------------------ /// Ask the Platform subclass to fill in the list of trap handler names /// /// For most Unix user process environments, this will be a single /// function name, _sigtramp. More specialized environments may have /// additional handler names. The unwinder code needs to know when a /// trap handler is on the stack because the unwind rules for the frame /// that caused the trap are different. /// /// The base class Platform ivar m_trap_handlers should be updated by /// the Platform subclass when this method is called. If there are no /// predefined trap handlers, this method may be a no-op. //------------------------------------------------------------------ virtual void CalculateTrapHandlerSymbolNames() = 0; const char *GetCachedUserName(uint32_t uid) { std::lock_guard guard(m_mutex); // return the empty string if our string is NULL // so we can tell when things were in the negative // cached (didn't find a valid user name, don't keep // trying) const auto pos = m_uid_map.find(uid); return ((pos != m_uid_map.end()) ? pos->second.AsCString("") : nullptr); } const char *SetCachedUserName(uint32_t uid, const char *name, size_t name_len) { std::lock_guard guard(m_mutex); ConstString const_name(name); m_uid_map[uid] = const_name; if (m_max_uid_name_len < name_len) m_max_uid_name_len = name_len; // Const strings lives forever in our const string pool, so we can return // the const char * return const_name.GetCString(); } void SetUserNameNotFound(uint32_t uid) { std::lock_guard guard(m_mutex); m_uid_map[uid] = ConstString(); } void ClearCachedUserNames() { std::lock_guard guard(m_mutex); m_uid_map.clear(); } const char *GetCachedGroupName(uint32_t gid) { std::lock_guard guard(m_mutex); // return the empty string if our string is NULL // so we can tell when things were in the negative // cached (didn't find a valid group name, don't keep // trying) const auto pos = m_gid_map.find(gid); return ((pos != m_gid_map.end()) ? pos->second.AsCString("") : nullptr); } const char *SetCachedGroupName(uint32_t gid, const char *name, size_t name_len) { std::lock_guard guard(m_mutex); ConstString const_name(name); m_gid_map[gid] = const_name; if (m_max_gid_name_len < name_len) m_max_gid_name_len = name_len; // Const strings lives forever in our const string pool, so we can return // the const char * return const_name.GetCString(); } void SetGroupNameNotFound(uint32_t gid) { std::lock_guard guard(m_mutex); m_gid_map[gid] = ConstString(); } void ClearCachedGroupNames() { std::lock_guard guard(m_mutex); m_gid_map.clear(); } Status GetCachedExecutable(ModuleSpec &module_spec, lldb::ModuleSP &module_sp, const FileSpecList *module_search_paths_ptr, Platform &remote_platform); virtual Status DownloadModuleSlice(const FileSpec &src_file_spec, const uint64_t src_offset, const uint64_t src_size, const FileSpec &dst_file_spec); virtual Status DownloadSymbolFile(const lldb::ModuleSP &module_sp, const FileSpec &dst_file_spec); virtual const char *GetCacheHostname(); private: typedef std::function ModuleResolver; Status GetRemoteSharedModule(const ModuleSpec &module_spec, Process *process, lldb::ModuleSP &module_sp, const ModuleResolver &module_resolver, bool *did_create_ptr); bool GetCachedSharedModule(const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, bool *did_create_ptr); Status LoadCachedExecutable(const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, const FileSpecList *module_search_paths_ptr, Platform &remote_platform); FileSpec GetModuleCacheRoot(); DISALLOW_COPY_AND_ASSIGN(Platform); }; class PlatformList { public: PlatformList() : m_mutex(), m_platforms(), m_selected_platform_sp() {} ~PlatformList() = default; void Append(const lldb::PlatformSP &platform_sp, bool set_selected) { std::lock_guard guard(m_mutex); m_platforms.push_back(platform_sp); if (set_selected) m_selected_platform_sp = m_platforms.back(); } size_t GetSize() { std::lock_guard guard(m_mutex); return m_platforms.size(); } lldb::PlatformSP GetAtIndex(uint32_t idx) { lldb::PlatformSP platform_sp; { std::lock_guard guard(m_mutex); if (idx < m_platforms.size()) platform_sp = m_platforms[idx]; } return platform_sp; } //------------------------------------------------------------------ /// Select the active platform. /// /// In order to debug remotely, other platform's can be remotely /// connected to and set as the selected platform for any subsequent /// debugging. This allows connection to remote targets and allows /// the ability to discover process info, launch and attach to remote /// processes. //------------------------------------------------------------------ lldb::PlatformSP GetSelectedPlatform() { std::lock_guard guard(m_mutex); if (!m_selected_platform_sp && !m_platforms.empty()) m_selected_platform_sp = m_platforms.front(); return m_selected_platform_sp; } void SetSelectedPlatform(const lldb::PlatformSP &platform_sp) { if (platform_sp) { std::lock_guard guard(m_mutex); const size_t num_platforms = m_platforms.size(); for (size_t idx = 0; idx < num_platforms; ++idx) { if (m_platforms[idx].get() == platform_sp.get()) { m_selected_platform_sp = m_platforms[idx]; return; } } m_platforms.push_back(platform_sp); m_selected_platform_sp = m_platforms.back(); } } protected: typedef std::vector collection; mutable std::recursive_mutex m_mutex; collection m_platforms; lldb::PlatformSP m_selected_platform_sp; private: DISALLOW_COPY_AND_ASSIGN(PlatformList); }; class OptionGroupPlatformRSync : public lldb_private::OptionGroup { public: OptionGroupPlatformRSync() = default; ~OptionGroupPlatformRSync() override = default; lldb_private::Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, ExecutionContext *execution_context) override; void OptionParsingStarting(ExecutionContext *execution_context) override; llvm::ArrayRef GetDefinitions() override; // Options table: Required for subclasses of Options. static lldb_private::OptionDefinition g_option_table[]; // Instance variables to hold the values for command options. bool m_rsync; std::string m_rsync_opts; std::string m_rsync_prefix; bool m_ignores_remote_hostname; private: DISALLOW_COPY_AND_ASSIGN(OptionGroupPlatformRSync); }; class OptionGroupPlatformSSH : public lldb_private::OptionGroup { public: OptionGroupPlatformSSH() = default; ~OptionGroupPlatformSSH() override = default; lldb_private::Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, ExecutionContext *execution_context) override; void OptionParsingStarting(ExecutionContext *execution_context) override; llvm::ArrayRef GetDefinitions() override; // Options table: Required for subclasses of Options. static lldb_private::OptionDefinition g_option_table[]; // Instance variables to hold the values for command options. bool m_ssh; std::string m_ssh_opts; private: DISALLOW_COPY_AND_ASSIGN(OptionGroupPlatformSSH); }; class OptionGroupPlatformCaching : public lldb_private::OptionGroup { public: OptionGroupPlatformCaching() = default; ~OptionGroupPlatformCaching() override = default; lldb_private::Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, ExecutionContext *execution_context) override; void OptionParsingStarting(ExecutionContext *execution_context) override; llvm::ArrayRef GetDefinitions() override; // Options table: Required for subclasses of Options. static lldb_private::OptionDefinition g_option_table[]; // Instance variables to hold the values for command options. std::string m_cache_dir; private: DISALLOW_COPY_AND_ASSIGN(OptionGroupPlatformCaching); }; } // namespace lldb_private #endif // liblldb_Platform_h_ Index: head/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.cpp =================================================================== --- head/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.cpp (revision 322325) +++ head/contrib/llvm/tools/lldb/source/Plugins/ABI/SysV-i386/ABISysV_i386.cpp (revision 322326) @@ -1,859 +1,859 @@ //===----------------------- ABISysV_i386.cpp -------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. // See LICENSE.TXT for details. //===----------------------------------------------------------------------===// #include "ABISysV_i386.h" // C Includes // C++ Includes // Other libraries and framework includes #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/Triple.h" // Project includes #include "lldb/Core/Module.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/RegisterValue.h" #include "lldb/Core/Value.h" #include "lldb/Core/ValueObjectConstResult.h" #include "lldb/Core/ValueObjectMemory.h" #include "lldb/Core/ValueObjectRegister.h" #include "lldb/Symbol/UnwindPlan.h" #include "lldb/Target/Process.h" #include "lldb/Target/RegisterContext.h" #include "lldb/Target/StackFrame.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; // This source file uses the following document as a reference: //==================================================================== // System V Application Binary Interface // Intel386 Architecture Processor Supplement, Version 1.0 // Edited by // H.J. Lu, David L Kreitzer, Milind Girkar, Zia Ansari // // (Based on // System V Application Binary Interface, // AMD64 Architecture Processor Supplement, // Edited by // H.J. Lu, Michael Matz, Milind Girkar, Jan Hubicka, // Andreas Jaeger, Mark Mitchell) // // February 3, 2015 //==================================================================== // DWARF Register Number Mapping // See Table 2.14 of the reference document (specified on top of this file) // Comment: Table 2.14 is followed till 'mm' entries. // After that, all entries are ignored here. enum dwarf_regnums { dwarf_eax = 0, dwarf_ecx, dwarf_edx, dwarf_ebx, dwarf_esp, dwarf_ebp, dwarf_esi, dwarf_edi, dwarf_eip, dwarf_eflags, dwarf_st0 = 11, dwarf_st1, dwarf_st2, dwarf_st3, dwarf_st4, dwarf_st5, dwarf_st6, dwarf_st7, dwarf_xmm0 = 21, dwarf_xmm1, dwarf_xmm2, dwarf_xmm3, dwarf_xmm4, dwarf_xmm5, dwarf_xmm6, dwarf_xmm7, dwarf_ymm0 = dwarf_xmm0, dwarf_ymm1 = dwarf_xmm1, dwarf_ymm2 = dwarf_xmm2, dwarf_ymm3 = dwarf_xmm3, dwarf_ymm4 = dwarf_xmm4, dwarf_ymm5 = dwarf_xmm5, dwarf_ymm6 = dwarf_xmm6, dwarf_ymm7 = dwarf_xmm7, dwarf_mm0 = 29, dwarf_mm1, dwarf_mm2, dwarf_mm3, dwarf_mm4, dwarf_mm5, dwarf_mm6, dwarf_mm7, dwarf_bnd0 = 101, dwarf_bnd1, dwarf_bnd2, dwarf_bnd3 }; static RegisterInfo g_register_infos[] = { // clang-format off //NAME ALT SZ OFF ENCODING FORMAT EH_FRAME DWARF GENERIC PROCESS PLUGIN LLDB NATIVE VALUE INVAL DYN EXPR SZ //========== ======= == === ============= ==================== =================== =================== ========================= =================== =================== ======= ======= ======== == {"eax", nullptr, 4, 0, eEncodingUint, eFormatHex, {dwarf_eax, dwarf_eax, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"ebx", nullptr, 4, 0, eEncodingUint, eFormatHex, {dwarf_ebx, dwarf_ebx, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"ecx", nullptr, 4, 0, eEncodingUint, eFormatHex, {dwarf_ecx, dwarf_ecx, LLDB_REGNUM_GENERIC_ARG4, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"edx", nullptr, 4, 0, eEncodingUint, eFormatHex, {dwarf_edx, dwarf_edx, LLDB_REGNUM_GENERIC_ARG3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"esi", nullptr, 4, 0, eEncodingUint, eFormatHex, {dwarf_esi, dwarf_esi, LLDB_REGNUM_GENERIC_ARG2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"edi", nullptr, 4, 0, eEncodingUint, eFormatHex, {dwarf_edi, dwarf_edi, LLDB_REGNUM_GENERIC_ARG1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"ebp", "fp", 4, 0, eEncodingUint, eFormatHex, {dwarf_ebp, dwarf_ebp, LLDB_REGNUM_GENERIC_FP, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"esp", "sp", 4, 0, eEncodingUint, eFormatHex, {dwarf_esp, dwarf_esp, LLDB_REGNUM_GENERIC_SP, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"eip", "pc", 4, 0, eEncodingUint, eFormatHex, {dwarf_eip, dwarf_eip, LLDB_REGNUM_GENERIC_PC, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"eflags", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_REGNUM_GENERIC_FLAGS,LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"cs", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"ss", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"ds", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"es", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"fs", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"gs", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"st0", nullptr, 10, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_st0, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"st1", nullptr, 10, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_st1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"st2", nullptr, 10, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_st2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"st3", nullptr, 10, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_st3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"st4", nullptr, 10, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_st4, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"st5", nullptr, 10, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_st5, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"st6", nullptr, 10, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_st6, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"st7", nullptr, 10, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_st7, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"fctrl", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"fstat", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"ftag", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"fiseg", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"fioff", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"foseg", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"fooff", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"fop", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"xmm0", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_xmm0, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"xmm1", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_xmm1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"xmm2", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_xmm2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"xmm3", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_xmm3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"xmm4", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_xmm4, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"xmm5", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_xmm5, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"xmm6", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_xmm6, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"xmm7", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_xmm7, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"mxcsr", nullptr, 4, 0, eEncodingUint, eFormatHex, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"ymm0", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_ymm0, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"ymm1", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_ymm1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"ymm2", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_ymm2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"ymm3", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_ymm3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"ymm4", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_ymm4, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"ymm5", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_ymm5, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"ymm6", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_ymm6, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"ymm7", nullptr, 32, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, dwarf_ymm7, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"bnd0", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt64,{dwarf_bnd0, dwarf_bnd0, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"bnd1", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt64,{dwarf_bnd1, dwarf_bnd1, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"bnd2", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt64,{dwarf_bnd2, dwarf_bnd2, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"bnd3", nullptr, 16, 0, eEncodingVector, eFormatVectorOfUInt64,{dwarf_bnd3, dwarf_bnd3, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"bndcfgu", nullptr, 8, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0}, {"bndstatus",nullptr, 8, 0, eEncodingVector, eFormatVectorOfUInt8, {LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM, LLDB_INVALID_REGNUM}, nullptr, nullptr, nullptr, 0} // clang-format on }; static const uint32_t k_num_register_infos = llvm::array_lengthof(g_register_infos); static bool g_register_info_names_constified = false; const lldb_private::RegisterInfo * ABISysV_i386::GetRegisterInfoArray(uint32_t &count) { // Make the C-string names and alt_names for the register infos into const // C-string values by having the ConstString unique the names in the global // constant C-string pool. if (!g_register_info_names_constified) { g_register_info_names_constified = true; for (uint32_t i = 0; i < k_num_register_infos; ++i) { if (g_register_infos[i].name) g_register_infos[i].name = ConstString(g_register_infos[i].name).GetCString(); if (g_register_infos[i].alt_name) g_register_infos[i].alt_name = ConstString(g_register_infos[i].alt_name).GetCString(); } } count = k_num_register_infos; return g_register_infos; } //------------------------------------------------------------------ // Static Functions //------------------------------------------------------------------ ABISP ABISysV_i386::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) { static ABISP g_abi_sp; if ((arch.GetTriple().getArch() == llvm::Triple::x86) && - arch.GetTriple().isOSLinux()) { + (arch.GetTriple().isOSLinux() || arch.GetTriple().isOSFreeBSD())) { if (!g_abi_sp) g_abi_sp.reset(new ABISysV_i386(process_sp)); return g_abi_sp; } return ABISP(); } bool ABISysV_i386::PrepareTrivialCall(Thread &thread, addr_t sp, addr_t func_addr, addr_t return_addr, llvm::ArrayRef args) const { RegisterContext *reg_ctx = thread.GetRegisterContext().get(); if (!reg_ctx) return false; uint32_t pc_reg_num = reg_ctx->ConvertRegisterKindToRegisterNumber( eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); uint32_t sp_reg_num = reg_ctx->ConvertRegisterKindToRegisterNumber( eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP); // While using register info to write a register value to memory, the register // info // just needs to have the correct size of a 32 bit register, the actual // register it // pertains to is not important, just the size needs to be correct. // "eax" is used here for this purpose. const RegisterInfo *reg_info_32 = reg_ctx->GetRegisterInfoByName("eax"); if (!reg_info_32) return false; // TODO this should actually never happen Status error; RegisterValue reg_value; // Make room for the argument(s) on the stack sp -= 4 * args.size(); // SP Alignment sp &= ~(16ull - 1ull); // 16-byte alignment // Write arguments onto the stack addr_t arg_pos = sp; for (addr_t arg : args) { reg_value.SetUInt32(arg); error = reg_ctx->WriteRegisterValueToMemory( reg_info_32, arg_pos, reg_info_32->byte_size, reg_value); if (error.Fail()) return false; arg_pos += 4; } // The return address is pushed onto the stack sp -= 4; reg_value.SetUInt32(return_addr); error = reg_ctx->WriteRegisterValueToMemory( reg_info_32, sp, reg_info_32->byte_size, reg_value); if (error.Fail()) return false; // Setting %esp to the actual stack value. if (!reg_ctx->WriteRegisterFromUnsigned(sp_reg_num, sp)) return false; // Setting %eip to the address of the called function. if (!reg_ctx->WriteRegisterFromUnsigned(pc_reg_num, func_addr)) return false; return true; } static bool ReadIntegerArgument(Scalar &scalar, unsigned int bit_width, bool is_signed, Process *process, addr_t ¤t_stack_argument) { uint32_t byte_size = (bit_width + (8 - 1)) / 8; Status error; if (!process) return false; if (process->ReadScalarIntegerFromMemory(current_stack_argument, byte_size, is_signed, scalar, error)) { current_stack_argument += byte_size; return true; } return false; } bool ABISysV_i386::GetArgumentValues(Thread &thread, ValueList &values) const { unsigned int num_values = values.GetSize(); unsigned int value_index; RegisterContext *reg_ctx = thread.GetRegisterContext().get(); if (!reg_ctx) return false; // Get pointer to the first stack argument addr_t sp = reg_ctx->GetSP(0); if (!sp) return false; addr_t current_stack_argument = sp + 4; // jump over return address for (value_index = 0; value_index < num_values; ++value_index) { Value *value = values.GetValueAtIndex(value_index); if (!value) return false; // Currently: Support for extracting values with Clang QualTypes only. CompilerType compiler_type(value->GetCompilerType()); if (compiler_type) { bool is_signed; if (compiler_type.IsIntegerOrEnumerationType(is_signed)) { ReadIntegerArgument(value->GetScalar(), compiler_type.GetBitSize(&thread), is_signed, thread.GetProcess().get(), current_stack_argument); } else if (compiler_type.IsPointerType()) { ReadIntegerArgument(value->GetScalar(), compiler_type.GetBitSize(&thread), false, thread.GetProcess().get(), current_stack_argument); } } } return true; } Status ABISysV_i386::SetReturnValueObject(lldb::StackFrameSP &frame_sp, lldb::ValueObjectSP &new_value_sp) { Status error; if (!new_value_sp) { error.SetErrorString("Empty value object for return value."); return error; } CompilerType compiler_type = new_value_sp->GetCompilerType(); if (!compiler_type) { error.SetErrorString("Null clang type for return value."); return error; } const uint32_t type_flags = compiler_type.GetTypeInfo(); Thread *thread = frame_sp->GetThread().get(); RegisterContext *reg_ctx = thread->GetRegisterContext().get(); DataExtractor data; Status data_error; size_t num_bytes = new_value_sp->GetData(data, data_error); bool register_write_successful = true; if (data_error.Fail()) { error.SetErrorStringWithFormat( "Couldn't convert return value to raw data: %s", data_error.AsCString()); return error; } // Following "IF ELSE" block categorizes various 'Fundamental Data Types'. // The terminology 'Fundamental Data Types' used here is adopted from // Table 2.1 of the reference document (specified on top of this file) if (type_flags & eTypeIsPointer) // 'Pointer' { if (num_bytes != sizeof(uint32_t)) { error.SetErrorString("Pointer to be returned is not 4 bytes wide"); return error; } lldb::offset_t offset = 0; const RegisterInfo *eax_info = reg_ctx->GetRegisterInfoByName("eax", 0); uint32_t raw_value = data.GetMaxU32(&offset, num_bytes); register_write_successful = reg_ctx->WriteRegisterFromUnsigned(eax_info, raw_value); } else if ((type_flags & eTypeIsScalar) || (type_flags & eTypeIsEnumeration)) //'Integral' + 'Floating Point' { lldb::offset_t offset = 0; const RegisterInfo *eax_info = reg_ctx->GetRegisterInfoByName("eax", 0); if (type_flags & eTypeIsInteger) // 'Integral' except enum { switch (num_bytes) { default: break; case 16: // For clang::BuiltinType::UInt128 & Int128 // ToDo: Need to decide how to handle it break; case 8: { uint32_t raw_value_low = data.GetMaxU32(&offset, 4); const RegisterInfo *edx_info = reg_ctx->GetRegisterInfoByName("edx", 0); uint32_t raw_value_high = data.GetMaxU32(&offset, num_bytes - offset); register_write_successful = (reg_ctx->WriteRegisterFromUnsigned(eax_info, raw_value_low) && reg_ctx->WriteRegisterFromUnsigned(edx_info, raw_value_high)); break; } case 4: case 2: case 1: { uint32_t raw_value = data.GetMaxU32(&offset, num_bytes); register_write_successful = reg_ctx->WriteRegisterFromUnsigned(eax_info, raw_value); break; } } } else if (type_flags & eTypeIsEnumeration) // handles enum { uint32_t raw_value = data.GetMaxU32(&offset, num_bytes); register_write_successful = reg_ctx->WriteRegisterFromUnsigned(eax_info, raw_value); } else if (type_flags & eTypeIsFloat) // 'Floating Point' { RegisterValue st0_value, fstat_value, ftag_value; const RegisterInfo *st0_info = reg_ctx->GetRegisterInfoByName("st0", 0); const RegisterInfo *fstat_info = reg_ctx->GetRegisterInfoByName("fstat", 0); const RegisterInfo *ftag_info = reg_ctx->GetRegisterInfoByName("ftag", 0); /* According to Page 3-12 of document System V Application Binary Interface, Intel386 Architecture Processor Supplement, Fourth Edition To return Floating Point values, all st% registers except st0 should be empty after exiting from a function. This requires setting fstat and ftag registers to specific values. fstat: The TOP field of fstat should be set to a value [0,7]. ABI doesn't specify the specific value of TOP in case of function return. Hence, we set the TOP field to 7 by our choice. */ uint32_t value_fstat_u32 = 0x00003800; /* ftag: Implication of setting TOP to 7 and indicating all st% registers empty except st0 is to set 7th bit of 4th byte of FXSAVE area to 1 and all other bits of this byte to 0. This is in accordance with the document Intel 64 and IA-32 Architectures Software Developer's Manual, January 2015 */ uint32_t value_ftag_u32 = 0x00000080; if (num_bytes <= 12) // handles float, double, long double, __float80 { long double value_long_dbl = 0.0; if (num_bytes == 4) value_long_dbl = data.GetFloat(&offset); else if (num_bytes == 8) value_long_dbl = data.GetDouble(&offset); else if (num_bytes == 12) value_long_dbl = data.GetLongDouble(&offset); else { error.SetErrorString("Invalid number of bytes for this return type"); return error; } st0_value.SetLongDouble(value_long_dbl); fstat_value.SetUInt32(value_fstat_u32); ftag_value.SetUInt32(value_ftag_u32); register_write_successful = reg_ctx->WriteRegister(st0_info, st0_value) && reg_ctx->WriteRegister(fstat_info, fstat_value) && reg_ctx->WriteRegister(ftag_info, ftag_value); } else if (num_bytes == 16) // handles __float128 { error.SetErrorString("Implementation is missing for this clang type."); } } else { // Neither 'Integral' nor 'Floating Point'. If flow reaches here // then check type_flags. This type_flags is not a valid type. error.SetErrorString("Invalid clang type"); } } else { /* 'Complex Floating Point', 'Packed', 'Decimal Floating Point' and 'Aggregate' data types are yet to be implemented */ error.SetErrorString("Currently only Integral and Floating Point clang " "types are supported."); } if (!register_write_successful) error.SetErrorString("Register writing failed"); return error; } ValueObjectSP ABISysV_i386::GetReturnValueObjectSimple( Thread &thread, CompilerType &return_compiler_type) const { ValueObjectSP return_valobj_sp; Value value; if (!return_compiler_type) return return_valobj_sp; value.SetCompilerType(return_compiler_type); RegisterContext *reg_ctx = thread.GetRegisterContext().get(); if (!reg_ctx) return return_valobj_sp; const uint32_t type_flags = return_compiler_type.GetTypeInfo(); unsigned eax_id = reg_ctx->GetRegisterInfoByName("eax", 0)->kinds[eRegisterKindLLDB]; unsigned edx_id = reg_ctx->GetRegisterInfoByName("edx", 0)->kinds[eRegisterKindLLDB]; // Following "IF ELSE" block categorizes various 'Fundamental Data Types'. // The terminology 'Fundamental Data Types' used here is adopted from // Table 2.1 of the reference document (specified on top of this file) if (type_flags & eTypeIsPointer) // 'Pointer' { uint32_t ptr = thread.GetRegisterContext()->ReadRegisterAsUnsigned(eax_id, 0) & 0xffffffff; value.SetValueType(Value::eValueTypeScalar); value.GetScalar() = ptr; return_valobj_sp = ValueObjectConstResult::Create( thread.GetStackFrameAtIndex(0).get(), value, ConstString("")); } else if ((type_flags & eTypeIsScalar) || (type_flags & eTypeIsEnumeration)) //'Integral' + 'Floating Point' { value.SetValueType(Value::eValueTypeScalar); const size_t byte_size = return_compiler_type.GetByteSize(nullptr); bool success = false; if (type_flags & eTypeIsInteger) // 'Integral' except enum { const bool is_signed = ((type_flags & eTypeIsSigned) != 0); uint64_t raw_value = thread.GetRegisterContext()->ReadRegisterAsUnsigned(eax_id, 0) & 0xffffffff; raw_value |= (thread.GetRegisterContext()->ReadRegisterAsUnsigned(edx_id, 0) & 0xffffffff) << 32; switch (byte_size) { default: break; case 16: // For clang::BuiltinType::UInt128 & Int128 // ToDo: Need to decide how to handle it break; case 8: if (is_signed) value.GetScalar() = (int64_t)(raw_value); else value.GetScalar() = (uint64_t)(raw_value); success = true; break; case 4: if (is_signed) value.GetScalar() = (int32_t)(raw_value & UINT32_MAX); else value.GetScalar() = (uint32_t)(raw_value & UINT32_MAX); success = true; break; case 2: if (is_signed) value.GetScalar() = (int16_t)(raw_value & UINT16_MAX); else value.GetScalar() = (uint16_t)(raw_value & UINT16_MAX); success = true; break; case 1: if (is_signed) value.GetScalar() = (int8_t)(raw_value & UINT8_MAX); else value.GetScalar() = (uint8_t)(raw_value & UINT8_MAX); success = true; break; } if (success) return_valobj_sp = ValueObjectConstResult::Create( thread.GetStackFrameAtIndex(0).get(), value, ConstString("")); } else if (type_flags & eTypeIsEnumeration) // handles enum { uint32_t enm = thread.GetRegisterContext()->ReadRegisterAsUnsigned(eax_id, 0) & 0xffffffff; value.SetValueType(Value::eValueTypeScalar); value.GetScalar() = enm; return_valobj_sp = ValueObjectConstResult::Create( thread.GetStackFrameAtIndex(0).get(), value, ConstString("")); } else if (type_flags & eTypeIsFloat) // 'Floating Point' { if (byte_size <= 12) // handles float, double, long double, __float80 { const RegisterInfo *st0_info = reg_ctx->GetRegisterInfoByName("st0", 0); RegisterValue st0_value; if (reg_ctx->ReadRegister(st0_info, st0_value)) { DataExtractor data; if (st0_value.GetData(data)) { lldb::offset_t offset = 0; long double value_long_double = data.GetLongDouble(&offset); if (byte_size == 4) // float is 4 bytes { float value_float = (float)value_long_double; value.GetScalar() = value_float; success = true; } else if (byte_size == 8) // double is 8 bytes { // On Android Platform: long double is also 8 bytes // It will be handled here only. double value_double = (double)value_long_double; value.GetScalar() = value_double; success = true; } else if (byte_size == 12) // long double and __float80 are 12 bytes on i386 { value.GetScalar() = value_long_double; success = true; } } } if (success) return_valobj_sp = ValueObjectConstResult::Create( thread.GetStackFrameAtIndex(0).get(), value, ConstString("")); } else if (byte_size == 16) // handles __float128 { lldb::addr_t storage_addr = (uint32_t)( thread.GetRegisterContext()->ReadRegisterAsUnsigned(eax_id, 0) & 0xffffffff); return_valobj_sp = ValueObjectMemory::Create( &thread, "", Address(storage_addr, nullptr), return_compiler_type); } } else // Neither 'Integral' nor 'Floating Point' { // If flow reaches here then check type_flags // This type_flags is unhandled } } else if (type_flags & eTypeIsComplex) // 'Complex Floating Point' { // ToDo: Yet to be implemented } else if (type_flags & eTypeIsVector) // 'Packed' { const size_t byte_size = return_compiler_type.GetByteSize(nullptr); if (byte_size > 0) { const RegisterInfo *vec_reg = reg_ctx->GetRegisterInfoByName("xmm0", 0); if (vec_reg == nullptr) vec_reg = reg_ctx->GetRegisterInfoByName("mm0", 0); if (vec_reg) { if (byte_size <= vec_reg->byte_size) { ProcessSP process_sp(thread.GetProcess()); if (process_sp) { std::unique_ptr heap_data_ap( new DataBufferHeap(byte_size, 0)); const ByteOrder byte_order = process_sp->GetByteOrder(); RegisterValue reg_value; if (reg_ctx->ReadRegister(vec_reg, reg_value)) { Status error; if (reg_value.GetAsMemoryData(vec_reg, heap_data_ap->GetBytes(), heap_data_ap->GetByteSize(), byte_order, error)) { DataExtractor data(DataBufferSP(heap_data_ap.release()), byte_order, process_sp->GetTarget() .GetArchitecture() .GetAddressByteSize()); return_valobj_sp = ValueObjectConstResult::Create( &thread, return_compiler_type, ConstString(""), data); } } } } else if (byte_size <= vec_reg->byte_size * 2) { const RegisterInfo *vec_reg2 = reg_ctx->GetRegisterInfoByName("xmm1", 0); if (vec_reg2) { ProcessSP process_sp(thread.GetProcess()); if (process_sp) { std::unique_ptr heap_data_ap( new DataBufferHeap(byte_size, 0)); const ByteOrder byte_order = process_sp->GetByteOrder(); RegisterValue reg_value; RegisterValue reg_value2; if (reg_ctx->ReadRegister(vec_reg, reg_value) && reg_ctx->ReadRegister(vec_reg2, reg_value2)) { Status error; if (reg_value.GetAsMemoryData(vec_reg, heap_data_ap->GetBytes(), vec_reg->byte_size, byte_order, error) && reg_value2.GetAsMemoryData( vec_reg2, heap_data_ap->GetBytes() + vec_reg->byte_size, heap_data_ap->GetByteSize() - vec_reg->byte_size, byte_order, error)) { DataExtractor data(DataBufferSP(heap_data_ap.release()), byte_order, process_sp->GetTarget() .GetArchitecture() .GetAddressByteSize()); return_valobj_sp = ValueObjectConstResult::Create( &thread, return_compiler_type, ConstString(""), data); } } } } } } } } else // 'Decimal Floating Point' { // ToDo: Yet to be implemented } return return_valobj_sp; } ValueObjectSP ABISysV_i386::GetReturnValueObjectImpl( Thread &thread, CompilerType &return_compiler_type) const { ValueObjectSP return_valobj_sp; if (!return_compiler_type) return return_valobj_sp; ExecutionContext exe_ctx(thread.shared_from_this()); return_valobj_sp = GetReturnValueObjectSimple(thread, return_compiler_type); if (return_valobj_sp) return return_valobj_sp; RegisterContextSP reg_ctx_sp = thread.GetRegisterContext(); if (!reg_ctx_sp) return return_valobj_sp; if (return_compiler_type.IsAggregateType()) { unsigned eax_id = reg_ctx_sp->GetRegisterInfoByName("eax", 0)->kinds[eRegisterKindLLDB]; lldb::addr_t storage_addr = (uint32_t)( thread.GetRegisterContext()->ReadRegisterAsUnsigned(eax_id, 0) & 0xffffffff); return_valobj_sp = ValueObjectMemory::Create( &thread, "", Address(storage_addr, nullptr), return_compiler_type); } return return_valobj_sp; } // This defines CFA as esp+4 // The saved pc is at CFA-4 (i.e. esp+0) // The saved esp is CFA+0 bool ABISysV_i386::CreateFunctionEntryUnwindPlan(UnwindPlan &unwind_plan) { unwind_plan.Clear(); unwind_plan.SetRegisterKind(eRegisterKindDWARF); uint32_t sp_reg_num = dwarf_esp; uint32_t pc_reg_num = dwarf_eip; UnwindPlan::RowSP row(new UnwindPlan::Row); row->GetCFAValue().SetIsRegisterPlusOffset(sp_reg_num, 4); row->SetRegisterLocationToAtCFAPlusOffset(pc_reg_num, -4, false); row->SetRegisterLocationToIsCFAPlusOffset(sp_reg_num, 0, true); unwind_plan.AppendRow(row); unwind_plan.SetSourceName("i386 at-func-entry default"); unwind_plan.SetSourcedFromCompiler(eLazyBoolNo); return true; } // This defines CFA as ebp+8 // The saved pc is at CFA-4 (i.e. ebp+4) // The saved ebp is at CFA-8 (i.e. ebp+0) // The saved esp is CFA+0 bool ABISysV_i386::CreateDefaultUnwindPlan(UnwindPlan &unwind_plan) { unwind_plan.Clear(); unwind_plan.SetRegisterKind(eRegisterKindDWARF); uint32_t fp_reg_num = dwarf_ebp; uint32_t sp_reg_num = dwarf_esp; uint32_t pc_reg_num = dwarf_eip; UnwindPlan::RowSP row(new UnwindPlan::Row); const int32_t ptr_size = 4; row->GetCFAValue().SetIsRegisterPlusOffset(fp_reg_num, 2 * ptr_size); row->SetOffset(0); row->SetRegisterLocationToAtCFAPlusOffset(fp_reg_num, ptr_size * -2, true); row->SetRegisterLocationToAtCFAPlusOffset(pc_reg_num, ptr_size * -1, true); row->SetRegisterLocationToIsCFAPlusOffset(sp_reg_num, 0, true); unwind_plan.AppendRow(row); unwind_plan.SetSourceName("i386 default unwind plan"); unwind_plan.SetSourcedFromCompiler(eLazyBoolNo); unwind_plan.SetUnwindPlanValidAtAllInstructions(eLazyBoolNo); return true; } // According to "Register Usage" in reference document (specified on top // of this source file) ebx, ebp, esi, edi and esp registers are preserved // i.e. non-volatile i.e. callee-saved on i386 bool ABISysV_i386::RegisterIsCalleeSaved(const RegisterInfo *reg_info) { if (!reg_info) return false; // Saved registers are ebx, ebp, esi, edi, esp, eip const char *name = reg_info->name; if (name[0] == 'e') { switch (name[1]) { case 'b': if (name[2] == 'x' || name[2] == 'p') return name[3] == '\0'; break; case 'd': if (name[2] == 'i') return name[3] == '\0'; break; case 'i': if (name[2] == 'p') return name[3] == '\0'; break; case 's': if (name[2] == 'i' || name[2] == 'p') return name[3] == '\0'; break; } } if (name[0] == 's' && name[1] == 'p' && name[2] == '\0') // sp return true; if (name[0] == 'f' && name[1] == 'p' && name[2] == '\0') // fp return true; if (name[0] == 'p' && name[1] == 'c' && name[2] == '\0') // pc return true; return false; } void ABISysV_i386::Initialize() { PluginManager::RegisterPlugin( GetPluginNameStatic(), "System V ABI for i386 targets", CreateInstance); } void ABISysV_i386::Terminate() { PluginManager::UnregisterPlugin(CreateInstance); } //------------------------------------------------------------------ // PluginInterface protocol //------------------------------------------------------------------ lldb_private::ConstString ABISysV_i386::GetPluginNameStatic() { static ConstString g_name("sysv-i386"); return g_name; } lldb_private::ConstString ABISysV_i386::GetPluginName() { return GetPluginNameStatic(); } Index: head/contrib/llvm/tools/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.cpp =================================================================== --- head/contrib/llvm/tools/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.cpp (revision 322325) +++ head/contrib/llvm/tools/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.cpp (revision 322326) @@ -1,326 +1,332 @@ //===-- PlatformFreeBSD.cpp -------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "PlatformFreeBSD.h" #include "lldb/Host/Config.h" // C Includes #include #ifndef LLDB_DISABLE_POSIX #include #endif // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Breakpoint/BreakpointSite.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/State.h" #include "lldb/Host/HostInfo.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" // Define these constants from FreeBSD mman.h for use when targeting // remote FreeBSD systems even when host has different values. #define MAP_PRIVATE 0x0002 #define MAP_ANON 0x1000 using namespace lldb; using namespace lldb_private; using namespace lldb_private::platform_freebsd; static uint32_t g_initialize_count = 0; //------------------------------------------------------------------ PlatformSP PlatformFreeBSD::CreateInstance(bool force, const ArchSpec *arch) { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); LLDB_LOG(log, "force = {0}, arch=({1}, {2})", force, arch ? arch->GetArchitectureName() : "", arch ? arch->GetTriple().getTriple() : ""); bool create = force; if (create == false && arch && arch->IsValid()) { const llvm::Triple &triple = arch->GetTriple(); switch (triple.getOS()) { case llvm::Triple::FreeBSD: create = true; break; #if defined(__FreeBSD__) // Only accept "unknown" for the OS if the host is BSD and // it "unknown" wasn't specified (it was just returned because it // was NOT specified) case llvm::Triple::OSType::UnknownOS: create = !arch->TripleOSWasSpecified(); break; #endif default: break; } } LLDB_LOG(log, "create = {0}", create); if (create) { return PlatformSP(new PlatformFreeBSD(false)); } return PlatformSP(); } ConstString PlatformFreeBSD::GetPluginNameStatic(bool is_host) { if (is_host) { static ConstString g_host_name(Platform::GetHostPlatformName()); return g_host_name; } else { static ConstString g_remote_name("remote-freebsd"); return g_remote_name; } } const char *PlatformFreeBSD::GetPluginDescriptionStatic(bool is_host) { if (is_host) return "Local FreeBSD user platform plug-in."; else return "Remote FreeBSD user platform plug-in."; } ConstString PlatformFreeBSD::GetPluginName() { return GetPluginNameStatic(IsHost()); } void PlatformFreeBSD::Initialize() { Platform::Initialize(); if (g_initialize_count++ == 0) { #if defined(__FreeBSD__) PlatformSP default_platform_sp(new PlatformFreeBSD(true)); default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture()); Platform::SetHostPlatform(default_platform_sp); #endif PluginManager::RegisterPlugin( PlatformFreeBSD::GetPluginNameStatic(false), PlatformFreeBSD::GetPluginDescriptionStatic(false), PlatformFreeBSD::CreateInstance, nullptr); } } void PlatformFreeBSD::Terminate() { if (g_initialize_count > 0) { if (--g_initialize_count == 0) { PluginManager::UnregisterPlugin(PlatformFreeBSD::CreateInstance); } } PlatformPOSIX::Terminate(); } //------------------------------------------------------------------ /// Default Constructor //------------------------------------------------------------------ PlatformFreeBSD::PlatformFreeBSD(bool is_host) : PlatformPOSIX(is_host) // This is the local host platform {} PlatformFreeBSD::~PlatformFreeBSD() = default; bool PlatformFreeBSD::GetSupportedArchitectureAtIndex(uint32_t idx, ArchSpec &arch) { if (IsHost()) { ArchSpec hostArch = HostInfo::GetArchitecture(HostInfo::eArchKindDefault); if (hostArch.GetTriple().isOSFreeBSD()) { if (idx == 0) { arch = hostArch; return arch.IsValid(); } else if (idx == 1) { // If the default host architecture is 64-bit, look for a 32-bit variant if (hostArch.IsValid() && hostArch.GetTriple().isArch64Bit()) { arch = HostInfo::GetArchitecture(HostInfo::eArchKind32); return arch.IsValid(); } } } } else { if (m_remote_platform_sp) return m_remote_platform_sp->GetSupportedArchitectureAtIndex(idx, arch); llvm::Triple triple; // Set the OS to FreeBSD triple.setOS(llvm::Triple::FreeBSD); // Set the architecture switch (idx) { case 0: triple.setArchName("x86_64"); break; case 1: triple.setArchName("i386"); break; case 2: triple.setArchName("aarch64"); break; case 3: triple.setArchName("arm"); break; case 4: triple.setArchName("mips64"); break; case 5: triple.setArchName("mips"); break; case 6: triple.setArchName("ppc64"); break; case 7: triple.setArchName("ppc"); break; default: return false; } // Leave the vendor as "llvm::Triple:UnknownVendor" and don't specify the // vendor by // calling triple.SetVendorName("unknown") so that it is a "unspecified // unknown". // This means when someone calls triple.GetVendorName() it will return an // empty string // which indicates that the vendor can be set when two architectures are // merged // Now set the triple into "arch" and return true arch.SetTriple(triple); return true; } return false; } void PlatformFreeBSD::GetStatus(Stream &strm) { Platform::GetStatus(strm); #ifndef LLDB_DISABLE_POSIX // Display local kernel information only when we are running in host mode. // Otherwise, we would end up printing non-FreeBSD information (when running // on Mac OS for example). if (IsHost()) { struct utsname un; if (uname(&un)) return; strm.Printf(" Kernel: %s\n", un.sysname); strm.Printf(" Release: %s\n", un.release); strm.Printf(" Version: %s\n", un.version); } #endif } size_t PlatformFreeBSD::GetSoftwareBreakpointTrapOpcode(Target &target, BreakpointSite *bp_site) { switch (target.GetArchitecture().GetMachine()) { case llvm::Triple::arm: { lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0)); AddressClass addr_class = eAddressClassUnknown; if (bp_loc_sp) { addr_class = bp_loc_sp->GetAddress().GetAddressClass(); if (addr_class == eAddressClassUnknown && (bp_loc_sp->GetAddress().GetFileAddress() & 1)) addr_class = eAddressClassCodeAlternateISA; } if (addr_class == eAddressClassCodeAlternateISA) { // TODO: Enable when FreeBSD supports thumb breakpoints. // FreeBSD kernel as of 10.x, does not support thumb breakpoints return 0; } static const uint8_t g_arm_breakpoint_opcode[] = {0xFE, 0xDE, 0xFF, 0xE7}; size_t trap_opcode_size = sizeof(g_arm_breakpoint_opcode); assert(bp_site); if (bp_site->SetTrapOpcode(g_arm_breakpoint_opcode, trap_opcode_size)) return trap_opcode_size; } LLVM_FALLTHROUGH; default: return Platform::GetSoftwareBreakpointTrapOpcode(target, bp_site); } } Status PlatformFreeBSD::LaunchProcess(ProcessLaunchInfo &launch_info) { Status error; if (IsHost()) { error = Platform::LaunchProcess(launch_info); } else { if (m_remote_platform_sp) error = m_remote_platform_sp->LaunchProcess(launch_info); else error.SetErrorString("the platform is not currently connected"); } return error; } lldb::ProcessSP PlatformFreeBSD::Attach(ProcessAttachInfo &attach_info, Debugger &debugger, Target *target, Status &error) { lldb::ProcessSP process_sp; if (IsHost()) { if (target == NULL) { TargetSP new_target_sp; ArchSpec emptyArchSpec; error = debugger.GetTargetList().CreateTarget(debugger, "", emptyArchSpec, false, m_remote_platform_sp, new_target_sp); target = new_target_sp.get(); } else error.Clear(); if (target && error.Success()) { debugger.GetTargetList().SetSelectedTarget(target); // The freebsd always currently uses the GDB remote debugger plug-in // so even when debugging locally we are debugging remotely! // Just like the darwin plugin. process_sp = target->CreateProcess( attach_info.GetListenerForProcess(debugger), "gdb-remote", NULL); if (process_sp) error = process_sp->Attach(attach_info); } } else { if (m_remote_platform_sp) process_sp = m_remote_platform_sp->Attach(attach_info, debugger, target, error); else error.SetErrorString("the platform is not currently connected"); } return process_sp; } // FreeBSD processes cannot yet be launched by spawning and attaching. bool PlatformFreeBSD::CanDebugProcess() { return false; } void PlatformFreeBSD::CalculateTrapHandlerSymbolNames() { m_trap_handlers.push_back(ConstString("_sigtramp")); } -uint64_t PlatformFreeBSD::ConvertMmapFlagsToPlatform(const ArchSpec &arch, - unsigned flags) { +MmapArgList PlatformFreeBSD::GetMmapArgumentList(const ArchSpec &arch, + addr_t addr, addr_t length, + unsigned prot, unsigned flags, + addr_t fd, addr_t offset) { uint64_t flags_platform = 0; if (flags & eMmapFlagsPrivate) flags_platform |= MAP_PRIVATE; if (flags & eMmapFlagsAnon) flags_platform |= MAP_ANON; - return flags_platform; + + MmapArgList args({addr, length, prot, flags_platform, fd, offset}); + if (arch.GetTriple().getArch() == llvm::Triple::x86) + args.push_back(0); + return args; } Index: head/contrib/llvm/tools/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.h =================================================================== --- head/contrib/llvm/tools/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.h (revision 322325) +++ head/contrib/llvm/tools/lldb/source/Plugins/Platform/FreeBSD/PlatformFreeBSD.h (revision 322326) @@ -1,74 +1,76 @@ //===-- PlatformFreeBSD.h ---------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef liblldb_PlatformFreeBSD_h_ #define liblldb_PlatformFreeBSD_h_ #include "Plugins/Platform/POSIX/PlatformPOSIX.h" namespace lldb_private { namespace platform_freebsd { class PlatformFreeBSD : public PlatformPOSIX { public: PlatformFreeBSD(bool is_host); ~PlatformFreeBSD() override; static void Initialize(); static void Terminate(); //------------------------------------------------------------ // lldb_private::PluginInterface functions //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const ArchSpec *arch); static ConstString GetPluginNameStatic(bool is_host); static const char *GetPluginDescriptionStatic(bool is_host); ConstString GetPluginName() override; uint32_t GetPluginVersion() override { return 1; } //------------------------------------------------------------ // lldb_private::Platform functions //------------------------------------------------------------ const char *GetDescription() override { return GetPluginDescriptionStatic(IsHost()); } void GetStatus(Stream &strm) override; bool GetSupportedArchitectureAtIndex(uint32_t idx, ArchSpec &arch) override; bool CanDebugProcess() override; size_t GetSoftwareBreakpointTrapOpcode(Target &target, BreakpointSite *bp_site) override; Status LaunchProcess(ProcessLaunchInfo &launch_info) override; lldb::ProcessSP Attach(ProcessAttachInfo &attach_info, Debugger &debugger, Target *target, Status &error) override; void CalculateTrapHandlerSymbolNames() override; - uint64_t ConvertMmapFlagsToPlatform(const ArchSpec &arch, - unsigned flags) override; + MmapArgList GetMmapArgumentList(const ArchSpec &arch, lldb::addr_t addr, + lldb::addr_t length, unsigned prot, + unsigned flags, lldb::addr_t fd, + lldb::addr_t offset) override; private: DISALLOW_COPY_AND_ASSIGN(PlatformFreeBSD); }; } // namespace platform_freebsd } // namespace lldb_private #endif // liblldb_PlatformFreeBSD_h_ Index: head/contrib/llvm/tools/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.cpp =================================================================== --- head/contrib/llvm/tools/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.cpp (revision 322325) +++ head/contrib/llvm/tools/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.cpp (revision 322326) @@ -1,432 +1,436 @@ //===-- PlatformNetBSD.cpp -------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "PlatformNetBSD.h" #include "lldb/Host/Config.h" // C Includes #include #ifndef LLDB_DISABLE_POSIX #include #endif // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/Debugger.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/State.h" #include "lldb/Host/HostInfo.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" // Define these constants from NetBSD mman.h for use when targeting // remote netbsd systems even when host has different values. #define MAP_PRIVATE 0x0002 #define MAP_ANON 0x1000 using namespace lldb; using namespace lldb_private; using namespace lldb_private::platform_netbsd; static uint32_t g_initialize_count = 0; //------------------------------------------------------------------ PlatformSP PlatformNetBSD::CreateInstance(bool force, const ArchSpec *arch) { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); if (log) { const char *arch_name; if (arch && arch->GetArchitectureName()) arch_name = arch->GetArchitectureName(); else arch_name = ""; const char *triple_cstr = arch ? arch->GetTriple().getTriple().c_str() : ""; log->Printf("PlatformNetBSD::%s(force=%s, arch={%s,%s})", __FUNCTION__, force ? "true" : "false", arch_name, triple_cstr); } bool create = force; if (create == false && arch && arch->IsValid()) { const llvm::Triple &triple = arch->GetTriple(); switch (triple.getOS()) { case llvm::Triple::NetBSD: create = true; break; default: break; } } if (create) { if (log) log->Printf("PlatformNetBSD::%s() creating remote-netbsd platform", __FUNCTION__); return PlatformSP(new PlatformNetBSD(false)); } if (log) log->Printf( "PlatformNetBSD::%s() aborting creation of remote-netbsd platform", __FUNCTION__); return PlatformSP(); } ConstString PlatformNetBSD::GetPluginNameStatic(bool is_host) { if (is_host) { static ConstString g_host_name(Platform::GetHostPlatformName()); return g_host_name; } else { static ConstString g_remote_name("remote-netbsd"); return g_remote_name; } } const char *PlatformNetBSD::GetPluginDescriptionStatic(bool is_host) { if (is_host) return "Local NetBSD user platform plug-in."; else return "Remote NetBSD user platform plug-in."; } ConstString PlatformNetBSD::GetPluginName() { return GetPluginNameStatic(IsHost()); } void PlatformNetBSD::Initialize() { PlatformPOSIX::Initialize(); if (g_initialize_count++ == 0) { #if defined(__NetBSD__) PlatformSP default_platform_sp(new PlatformNetBSD(true)); default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture()); Platform::SetHostPlatform(default_platform_sp); #endif PluginManager::RegisterPlugin( PlatformNetBSD::GetPluginNameStatic(false), PlatformNetBSD::GetPluginDescriptionStatic(false), PlatformNetBSD::CreateInstance, nullptr); } } void PlatformNetBSD::Terminate() { if (g_initialize_count > 0) { if (--g_initialize_count == 0) { PluginManager::UnregisterPlugin(PlatformNetBSD::CreateInstance); } } PlatformPOSIX::Terminate(); } //------------------------------------------------------------------ /// Default Constructor //------------------------------------------------------------------ PlatformNetBSD::PlatformNetBSD(bool is_host) : PlatformPOSIX(is_host) // This is the local host platform {} PlatformNetBSD::~PlatformNetBSD() = default; bool PlatformNetBSD::GetSupportedArchitectureAtIndex(uint32_t idx, ArchSpec &arch) { if (IsHost()) { ArchSpec hostArch = HostInfo::GetArchitecture(HostInfo::eArchKindDefault); if (hostArch.GetTriple().isOSNetBSD()) { if (idx == 0) { arch = hostArch; return arch.IsValid(); } else if (idx == 1) { // If the default host architecture is 64-bit, look for a 32-bit variant if (hostArch.IsValid() && hostArch.GetTriple().isArch64Bit()) { arch = HostInfo::GetArchitecture(HostInfo::eArchKind32); return arch.IsValid(); } } } } else { if (m_remote_platform_sp) return m_remote_platform_sp->GetSupportedArchitectureAtIndex(idx, arch); llvm::Triple triple; // Set the OS to NetBSD triple.setOS(llvm::Triple::NetBSD); // Set the architecture switch (idx) { case 0: triple.setArchName("x86_64"); break; case 1: triple.setArchName("i386"); break; default: return false; } // Leave the vendor as "llvm::Triple:UnknownVendor" and don't specify the // vendor by // calling triple.SetVendorName("unknown") so that it is a "unspecified // unknown". // This means when someone calls triple.GetVendorName() it will return an // empty string // which indicates that the vendor can be set when two architectures are // merged // Now set the triple into "arch" and return true arch.SetTriple(triple); return true; } return false; } void PlatformNetBSD::GetStatus(Stream &strm) { Platform::GetStatus(strm); #ifndef LLDB_DISABLE_POSIX // Display local kernel information only when we are running in host mode. // Otherwise, we would end up printing non-NetBSD information (when running // on Mac OS for example). if (IsHost()) { struct utsname un; if (uname(&un)) return; strm.Printf(" Kernel: %s\n", un.sysname); strm.Printf(" Release: %s\n", un.release); strm.Printf(" Version: %s\n", un.version); } #endif } int32_t PlatformNetBSD::GetResumeCountForLaunchInfo(ProcessLaunchInfo &launch_info) { int32_t resume_count = 0; // Always resume past the initial stop when we use eLaunchFlagDebug if (launch_info.GetFlags().Test(eLaunchFlagDebug)) { // Resume past the stop for the final exec into the true inferior. ++resume_count; } // If we're not launching a shell, we're done. const FileSpec &shell = launch_info.GetShell(); if (!shell) return resume_count; std::string shell_string = shell.GetPath(); // We're in a shell, so for sure we have to resume past the shell exec. ++resume_count; // Figure out what shell we're planning on using. const char *shell_name = strrchr(shell_string.c_str(), '/'); if (shell_name == NULL) shell_name = shell_string.c_str(); else shell_name++; if (strcmp(shell_name, "csh") == 0 || strcmp(shell_name, "tcsh") == 0 || strcmp(shell_name, "zsh") == 0 || strcmp(shell_name, "sh") == 0) { // These shells seem to re-exec themselves. Add another resume. ++resume_count; } return resume_count; } bool PlatformNetBSD::CanDebugProcess() { if (IsHost()) { return true; } else { // If we're connected, we can debug. return IsConnected(); } } // For local debugging, NetBSD will override the debug logic to use llgs-launch // rather than // lldb-launch, llgs-attach. This differs from current lldb-launch, // debugserver-attach // approach on MacOSX. lldb::ProcessSP PlatformNetBSD::DebugProcess( ProcessLaunchInfo &launch_info, Debugger &debugger, Target *target, // Can be NULL, if NULL create a new // target, else use existing one Status &error) { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); if (log) log->Printf("PlatformNetBSD::%s entered (target %p)", __FUNCTION__, static_cast(target)); // If we're a remote host, use standard behavior from parent class. if (!IsHost()) return PlatformPOSIX::DebugProcess(launch_info, debugger, target, error); // // For local debugging, we'll insist on having ProcessGDBRemote create the // process. // ProcessSP process_sp; // Make sure we stop at the entry point launch_info.GetFlags().Set(eLaunchFlagDebug); // We always launch the process we are going to debug in a separate process // group, since then we can handle ^C interrupts ourselves w/o having to worry // about the target getting them as well. launch_info.SetLaunchInSeparateProcessGroup(true); // Ensure we have a target. if (target == nullptr) { if (log) log->Printf("PlatformNetBSD::%s creating new target", __FUNCTION__); TargetSP new_target_sp; error = debugger.GetTargetList().CreateTarget(debugger, "", "", false, nullptr, new_target_sp); if (error.Fail()) { if (log) log->Printf("PlatformNetBSD::%s failed to create new target: %s", __FUNCTION__, error.AsCString()); return process_sp; } target = new_target_sp.get(); if (!target) { error.SetErrorString("CreateTarget() returned nullptr"); if (log) log->Printf("PlatformNetBSD::%s failed: %s", __FUNCTION__, error.AsCString()); return process_sp; } } else { if (log) log->Printf("PlatformNetBSD::%s using provided target", __FUNCTION__); } // Mark target as currently selected target. debugger.GetTargetList().SetSelectedTarget(target); // Now create the gdb-remote process. if (log) log->Printf( "PlatformNetBSD::%s having target create process with gdb-remote plugin", __FUNCTION__); process_sp = target->CreateProcess( launch_info.GetListenerForProcess(debugger), "gdb-remote", nullptr); if (!process_sp) { error.SetErrorString("CreateProcess() failed for gdb-remote process"); if (log) log->Printf("PlatformNetBSD::%s failed: %s", __FUNCTION__, error.AsCString()); return process_sp; } else { if (log) log->Printf("PlatformNetBSD::%s successfully created process", __FUNCTION__); } // Adjust launch for a hijacker. ListenerSP listener_sp; if (!launch_info.GetHijackListener()) { if (log) log->Printf("PlatformNetBSD::%s setting up hijacker", __FUNCTION__); listener_sp = Listener::MakeListener("lldb.PlatformNetBSD.DebugProcess.hijack"); launch_info.SetHijackListener(listener_sp); process_sp->HijackProcessEvents(listener_sp); } // Log file actions. if (log) { log->Printf( "PlatformNetBSD::%s launching process with the following file actions:", __FUNCTION__); StreamString stream; size_t i = 0; const FileAction *file_action; while ((file_action = launch_info.GetFileActionAtIndex(i++)) != nullptr) { file_action->Dump(stream); log->PutCString(stream.GetData()); stream.Clear(); } } // Do the launch. error = process_sp->Launch(launch_info); if (error.Success()) { // Handle the hijacking of process events. if (listener_sp) { const StateType state = process_sp->WaitForProcessToStop( llvm::None, NULL, false, listener_sp); if (state == eStateStopped) { if (log) log->Printf("PlatformNetBSD::%s pid %" PRIu64 " state %s\n", __FUNCTION__, process_sp->GetID(), StateAsCString(state)); } else { if (log) log->Printf("PlatformNetBSD::%s pid %" PRIu64 " state is not stopped - %s\n", __FUNCTION__, process_sp->GetID(), StateAsCString(state)); } } // Hook up process PTY if we have one (which we should for local debugging // with llgs). int pty_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor(); if (pty_fd != lldb_utility::PseudoTerminal::invalid_fd) { process_sp->SetSTDIOFileDescriptor(pty_fd); if (log) log->Printf("PlatformNetBSD::%s pid %" PRIu64 " hooked up STDIO pty to process", __FUNCTION__, process_sp->GetID()); } else { if (log) log->Printf("PlatformNetBSD::%s pid %" PRIu64 " not using process STDIO pty", __FUNCTION__, process_sp->GetID()); } } else { if (log) log->Printf("PlatformNetBSD::%s process launch failed: %s", __FUNCTION__, error.AsCString()); // FIXME figure out appropriate cleanup here. Do we delete the target? Do // we delete the process? Does our caller do that? } return process_sp; } void PlatformNetBSD::CalculateTrapHandlerSymbolNames() { m_trap_handlers.push_back(ConstString("_sigtramp")); } -uint64_t PlatformNetBSD::ConvertMmapFlagsToPlatform(const ArchSpec &arch, - unsigned flags) { +MmapArgList PlatformNetBSD::GetMmapArgumentList(const ArchSpec &arch, + addr_t addr, addr_t length, + unsigned prot, unsigned flags, + addr_t fd, addr_t offset) { uint64_t flags_platform = 0; if (flags & eMmapFlagsPrivate) flags_platform |= MAP_PRIVATE; if (flags & eMmapFlagsAnon) flags_platform |= MAP_ANON; - return flags_platform; + + MmapArgList args({addr, length, prot, flags_platform, fd, offset}); + return args; } Index: head/contrib/llvm/tools/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.h =================================================================== --- head/contrib/llvm/tools/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.h (revision 322325) +++ head/contrib/llvm/tools/lldb/source/Plugins/Platform/NetBSD/PlatformNetBSD.h (revision 322326) @@ -1,72 +1,74 @@ //===-- PlatformNetBSD.h ----------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef liblldb_PlatformNetBSD_h_ #define liblldb_PlatformNetBSD_h_ #include "Plugins/Platform/POSIX/PlatformPOSIX.h" namespace lldb_private { namespace platform_netbsd { class PlatformNetBSD : public PlatformPOSIX { public: PlatformNetBSD(bool is_host); ~PlatformNetBSD() override; static void Initialize(); static void Terminate(); //------------------------------------------------------------ // lldb_private::PluginInterface functions //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const ArchSpec *arch); static ConstString GetPluginNameStatic(bool is_host); static const char *GetPluginDescriptionStatic(bool is_host); ConstString GetPluginName() override; uint32_t GetPluginVersion() override { return 1; } //------------------------------------------------------------ // lldb_private::Platform functions //------------------------------------------------------------ const char *GetDescription() override { return GetPluginDescriptionStatic(IsHost()); } void GetStatus(Stream &strm) override; bool GetSupportedArchitectureAtIndex(uint32_t idx, ArchSpec &arch) override; int32_t GetResumeCountForLaunchInfo(ProcessLaunchInfo &launch_info) override; bool CanDebugProcess() override; lldb::ProcessSP DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger, Target *target, Status &error) override; void CalculateTrapHandlerSymbolNames() override; - uint64_t ConvertMmapFlagsToPlatform(const ArchSpec &arch, - unsigned flags) override; + MmapArgList GetMmapArgumentList(const ArchSpec &arch, lldb::addr_t addr, + lldb::addr_t length, unsigned prot, + unsigned flags, lldb::addr_t fd, + lldb::addr_t offset) override; private: DISALLOW_COPY_AND_ASSIGN(PlatformNetBSD); }; } // namespace platform_netbsd } // namespace lldb_private #endif // liblldb_PlatformNetBSD_h_ Index: head/contrib/llvm/tools/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.cpp =================================================================== --- head/contrib/llvm/tools/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.cpp (revision 322325) +++ head/contrib/llvm/tools/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.cpp (revision 322326) @@ -1,223 +1,225 @@ //===-- PlatformOpenBSD.cpp -------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "PlatformOpenBSD.h" #include "lldb/Host/Config.h" // C Includes #include #ifndef LLDB_DISABLE_POSIX #include #endif // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/Debugger.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/State.h" #include "lldb/Host/HostInfo.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" // Define these constants from OpenBSD mman.h for use when targeting // remote openbsd systems even when host has different values. #define MAP_PRIVATE 0x0002 #define MAP_ANON 0x1000 using namespace lldb; using namespace lldb_private; using namespace lldb_private::platform_openbsd; static uint32_t g_initialize_count = 0; //------------------------------------------------------------------ PlatformSP PlatformOpenBSD::CreateInstance(bool force, const ArchSpec *arch) { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); LLDB_LOG(log, "force = {0}, arch=({1}, {2})", force, arch ? arch->GetArchitectureName() : "", arch ? arch->GetTriple().getTriple() : ""); bool create = force; if (create == false && arch && arch->IsValid()) { const llvm::Triple &triple = arch->GetTriple(); switch (triple.getOS()) { case llvm::Triple::OpenBSD: create = true; break; #if defined(__OpenBSD__) // Only accept "unknown" for the OS if the host is BSD and // it "unknown" wasn't specified (it was just returned because it // was NOT specified) case llvm::Triple::OSType::UnknownOS: create = !arch->TripleOSWasSpecified(); break; #endif default: break; } } LLDB_LOG(log, "create = {0}", create); if (create) { return PlatformSP(new PlatformOpenBSD(false)); } return PlatformSP(); } ConstString PlatformOpenBSD::GetPluginNameStatic(bool is_host) { if (is_host) { static ConstString g_host_name(Platform::GetHostPlatformName()); return g_host_name; } else { static ConstString g_remote_name("remote-openbsd"); return g_remote_name; } } const char *PlatformOpenBSD::GetPluginDescriptionStatic(bool is_host) { if (is_host) return "Local OpenBSD user platform plug-in."; else return "Remote OpenBSD user platform plug-in."; } ConstString PlatformOpenBSD::GetPluginName() { return GetPluginNameStatic(IsHost()); } void PlatformOpenBSD::Initialize() { Platform::Initialize(); if (g_initialize_count++ == 0) { #if defined(__OpenBSD__) PlatformSP default_platform_sp(new PlatformOpenBSD(true)); default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture()); Platform::SetHostPlatform(default_platform_sp); #endif PluginManager::RegisterPlugin( PlatformOpenBSD::GetPluginNameStatic(false), PlatformOpenBSD::GetPluginDescriptionStatic(false), PlatformOpenBSD::CreateInstance, nullptr); } } void PlatformOpenBSD::Terminate() { if (g_initialize_count > 0) { if (--g_initialize_count == 0) { PluginManager::UnregisterPlugin(PlatformOpenBSD::CreateInstance); } } PlatformPOSIX::Terminate(); } //------------------------------------------------------------------ /// Default Constructor //------------------------------------------------------------------ PlatformOpenBSD::PlatformOpenBSD(bool is_host) : PlatformPOSIX(is_host) // This is the local host platform {} PlatformOpenBSD::~PlatformOpenBSD() = default; bool PlatformOpenBSD::GetSupportedArchitectureAtIndex(uint32_t idx, ArchSpec &arch) { if (IsHost()) { ArchSpec hostArch = HostInfo::GetArchitecture(HostInfo::eArchKindDefault); if (hostArch.GetTriple().isOSOpenBSD()) { if (idx == 0) { arch = hostArch; return arch.IsValid(); } } } else { if (m_remote_platform_sp) return m_remote_platform_sp->GetSupportedArchitectureAtIndex(idx, arch); llvm::Triple triple; // Set the OS to OpenBSD triple.setOS(llvm::Triple::OpenBSD); // Set the architecture switch (idx) { case 0: triple.setArchName("x86_64"); break; case 1: triple.setArchName("i386"); break; case 2: triple.setArchName("aarch64"); break; case 3: triple.setArchName("arm"); break; default: return false; } // Leave the vendor as "llvm::Triple:UnknownVendor" and don't specify the // vendor by // calling triple.SetVendorName("unknown") so that it is a "unspecified // unknown". // This means when someone calls triple.GetVendorName() it will return an // empty string // which indicates that the vendor can be set when two architectures are // merged // Now set the triple into "arch" and return true arch.SetTriple(triple); return true; } return false; } void PlatformOpenBSD::GetStatus(Stream &strm) { Platform::GetStatus(strm); #ifndef LLDB_DISABLE_POSIX // Display local kernel information only when we are running in host mode. // Otherwise, we would end up printing non-OpenBSD information (when running // on Mac OS for example). if (IsHost()) { struct utsname un; if (uname(&un)) return; strm.Printf(" Kernel: %s\n", un.sysname); strm.Printf(" Release: %s\n", un.release); strm.Printf(" Version: %s\n", un.version); } #endif } // OpenBSD processes cannot yet be launched by spawning and attaching. bool PlatformOpenBSD::CanDebugProcess() { return false; } void PlatformOpenBSD::CalculateTrapHandlerSymbolNames() { m_trap_handlers.push_back(ConstString("_sigtramp")); } uint64_t PlatformOpenBSD::ConvertMmapFlagsToPlatform(const ArchSpec &arch, unsigned flags) { uint64_t flags_platform = 0; if (flags & eMmapFlagsPrivate) flags_platform |= MAP_PRIVATE; if (flags & eMmapFlagsAnon) flags_platform |= MAP_ANON; - return flags_platform; + + MmapArgList args({addr, length, prot, flags_platform, fd, offset}); + return args; } Index: head/contrib/llvm/tools/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.h =================================================================== --- head/contrib/llvm/tools/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.h (revision 322325) +++ head/contrib/llvm/tools/lldb/source/Plugins/Platform/OpenBSD/PlatformOpenBSD.h (revision 322326) @@ -1,66 +1,68 @@ //===-- PlatformOpenBSD.h ---------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef liblldb_PlatformOpenBSD_h_ #define liblldb_PlatformOpenBSD_h_ #include "Plugins/Platform/POSIX/PlatformPOSIX.h" namespace lldb_private { namespace platform_openbsd { class PlatformOpenBSD : public PlatformPOSIX { public: PlatformOpenBSD(bool is_host); ~PlatformOpenBSD() override; static void Initialize(); static void Terminate(); //------------------------------------------------------------ // lldb_private::PluginInterface functions //------------------------------------------------------------ static lldb::PlatformSP CreateInstance(bool force, const ArchSpec *arch); static ConstString GetPluginNameStatic(bool is_host); static const char *GetPluginDescriptionStatic(bool is_host); ConstString GetPluginName() override; uint32_t GetPluginVersion() override { return 1; } //------------------------------------------------------------ // lldb_private::Platform functions //------------------------------------------------------------ const char *GetDescription() override { return GetPluginDescriptionStatic(IsHost()); } void GetStatus(Stream &strm) override; bool GetSupportedArchitectureAtIndex(uint32_t idx, ArchSpec &arch) override; bool CanDebugProcess() override; void CalculateTrapHandlerSymbolNames() override; - uint64_t ConvertMmapFlagsToPlatform(const ArchSpec &arch, - unsigned flags) override; + MmapArgList GetMmapArgumentList(const ArchSpec &arch, lldb::addr_t addr, + lldb::addr_t length, unsigned prot, + unsigned flags, lldb::addr_t fd, + lldb::addr_t offset) override; private: DISALLOW_COPY_AND_ASSIGN(PlatformOpenBSD); }; } // namespace platform_openbsd } // namespace lldb_private #endif // liblldb_PlatformOpenBSD_h_ Index: head/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/InferiorCallPOSIX.cpp =================================================================== --- head/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/InferiorCallPOSIX.cpp (revision 322325) +++ head/contrib/llvm/tools/lldb/source/Plugins/Process/Utility/InferiorCallPOSIX.cpp (revision 322326) @@ -1,240 +1,238 @@ //===-- InferiorCallPOSIX.cpp -----------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "InferiorCallPOSIX.h" #include "lldb/Core/Address.h" #include "lldb/Core/StreamFile.h" #include "lldb/Core/ValueObject.h" #include "lldb/Expression/DiagnosticManager.h" #include "lldb/Host/Config.h" #include "lldb/Symbol/ClangASTContext.h" #include "lldb/Symbol/SymbolContext.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Platform.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Target/ThreadPlanCallFunction.h" #ifndef LLDB_DISABLE_POSIX #include #else // define them #define PROT_NONE 0 #define PROT_READ 1 #define PROT_WRITE 2 #define PROT_EXEC 4 #endif using namespace lldb; using namespace lldb_private; bool lldb_private::InferiorCallMmap(Process *process, addr_t &allocated_addr, addr_t addr, addr_t length, unsigned prot, unsigned flags, addr_t fd, addr_t offset) { Thread *thread = process->GetThreadList().GetExpressionExecutionThread().get(); if (thread == NULL) return false; const bool append = true; const bool include_symbols = true; const bool include_inlines = false; SymbolContextList sc_list; const uint32_t count = process->GetTarget().GetImages().FindFunctions( ConstString("mmap"), eFunctionNameTypeFull, include_symbols, include_inlines, append, sc_list); if (count > 0) { SymbolContext sc; if (sc_list.GetContextAtIndex(0, sc)) { const uint32_t range_scope = eSymbolContextFunction | eSymbolContextSymbol; const bool use_inline_block_range = false; EvaluateExpressionOptions options; options.SetStopOthers(true); options.SetUnwindOnError(true); options.SetIgnoreBreakpoints(true); options.SetTryAllThreads(true); options.SetDebug(false); options.SetTimeout(std::chrono::milliseconds(500)); options.SetTrapExceptions(false); - addr_t prot_arg, flags_arg = 0; + addr_t prot_arg; if (prot == eMmapProtNone) prot_arg = PROT_NONE; else { prot_arg = 0; if (prot & eMmapProtExec) prot_arg |= PROT_EXEC; if (prot & eMmapProtRead) prot_arg |= PROT_READ; if (prot & eMmapProtWrite) prot_arg |= PROT_WRITE; } - const ArchSpec arch = process->GetTarget().GetArchitecture(); - flags_arg = - process->GetTarget().GetPlatform()->ConvertMmapFlagsToPlatform(arch, - flags); - AddressRange mmap_range; if (sc.GetAddressRange(range_scope, 0, use_inline_block_range, mmap_range)) { ClangASTContext *clang_ast_context = process->GetTarget().GetScratchClangASTContext(); CompilerType clang_void_ptr_type = clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType(); - lldb::addr_t args[] = {addr, length, prot_arg, flags_arg, fd, offset}; + const ArchSpec arch = process->GetTarget().GetArchitecture(); + MmapArgList args = + process->GetTarget().GetPlatform()->GetMmapArgumentList( + arch, addr, length, prot_arg, flags, fd, offset); lldb::ThreadPlanSP call_plan_sp( new ThreadPlanCallFunction(*thread, mmap_range.GetBaseAddress(), clang_void_ptr_type, args, options)); if (call_plan_sp) { DiagnosticManager diagnostics; StackFrame *frame = thread->GetStackFrameAtIndex(0).get(); if (frame) { ExecutionContext exe_ctx; frame->CalculateExecutionContext(exe_ctx); ExpressionResults result = process->RunThreadPlan( exe_ctx, call_plan_sp, options, diagnostics); if (result == eExpressionCompleted) { allocated_addr = call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned( LLDB_INVALID_ADDRESS); if (process->GetAddressByteSize() == 4) { if (allocated_addr == UINT32_MAX) return false; } else if (process->GetAddressByteSize() == 8) { if (allocated_addr == UINT64_MAX) return false; } return true; } } } } } } return false; } bool lldb_private::InferiorCallMunmap(Process *process, addr_t addr, addr_t length) { Thread *thread = process->GetThreadList().GetExpressionExecutionThread().get(); if (thread == NULL) return false; const bool append = true; const bool include_symbols = true; const bool include_inlines = false; SymbolContextList sc_list; const uint32_t count = process->GetTarget().GetImages().FindFunctions( ConstString("munmap"), eFunctionNameTypeFull, include_symbols, include_inlines, append, sc_list); if (count > 0) { SymbolContext sc; if (sc_list.GetContextAtIndex(0, sc)) { const uint32_t range_scope = eSymbolContextFunction | eSymbolContextSymbol; const bool use_inline_block_range = false; EvaluateExpressionOptions options; options.SetStopOthers(true); options.SetUnwindOnError(true); options.SetIgnoreBreakpoints(true); options.SetTryAllThreads(true); options.SetDebug(false); options.SetTimeout(std::chrono::milliseconds(500)); options.SetTrapExceptions(false); AddressRange munmap_range; if (sc.GetAddressRange(range_scope, 0, use_inline_block_range, munmap_range)) { lldb::addr_t args[] = {addr, length}; lldb::ThreadPlanSP call_plan_sp( new ThreadPlanCallFunction(*thread, munmap_range.GetBaseAddress(), CompilerType(), args, options)); if (call_plan_sp) { DiagnosticManager diagnostics; StackFrame *frame = thread->GetStackFrameAtIndex(0).get(); if (frame) { ExecutionContext exe_ctx; frame->CalculateExecutionContext(exe_ctx); ExpressionResults result = process->RunThreadPlan( exe_ctx, call_plan_sp, options, diagnostics); if (result == eExpressionCompleted) { return true; } } } } } } return false; } // FIXME: This has nothing to do with Posix, it is just a convenience function // that calls a // function of the form "void * (*)(void)". We should find a better place to // put this. bool lldb_private::InferiorCall(Process *process, const Address *address, addr_t &returned_func, bool trap_exceptions) { Thread *thread = process->GetThreadList().GetExpressionExecutionThread().get(); if (thread == NULL || address == NULL) return false; EvaluateExpressionOptions options; options.SetStopOthers(true); options.SetUnwindOnError(true); options.SetIgnoreBreakpoints(true); options.SetTryAllThreads(true); options.SetDebug(false); options.SetTimeout(std::chrono::milliseconds(500)); options.SetTrapExceptions(trap_exceptions); ClangASTContext *clang_ast_context = process->GetTarget().GetScratchClangASTContext(); CompilerType clang_void_ptr_type = clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType(); lldb::ThreadPlanSP call_plan_sp( new ThreadPlanCallFunction(*thread, *address, clang_void_ptr_type, llvm::ArrayRef(), options)); if (call_plan_sp) { DiagnosticManager diagnostics; StackFrame *frame = thread->GetStackFrameAtIndex(0).get(); if (frame) { ExecutionContext exe_ctx; frame->CalculateExecutionContext(exe_ctx); ExpressionResults result = process->RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics); if (result == eExpressionCompleted) { returned_func = call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned( LLDB_INVALID_ADDRESS); if (process->GetAddressByteSize() == 4) { if (returned_func == UINT32_MAX) return false; } else if (process->GetAddressByteSize() == 8) { if (returned_func == UINT64_MAX) return false; } return true; } } } return false; } Index: head/contrib/llvm/tools/lldb/source/Target/Platform.cpp =================================================================== --- head/contrib/llvm/tools/lldb/source/Target/Platform.cpp (revision 322325) +++ head/contrib/llvm/tools/lldb/source/Target/Platform.cpp (revision 322326) @@ -1,1894 +1,1898 @@ //===-- Platform.cpp --------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes #include #include #include // Other libraries and framework includes #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" // Project includes #include "lldb/Breakpoint/BreakpointIDList.h" #include "lldb/Breakpoint/BreakpointLocation.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/StreamFile.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" #include "lldb/Host/OptionParser.h" #include "lldb/Interpreter/OptionValueProperties.h" #include "lldb/Interpreter/Property.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/ModuleCache.h" #include "lldb/Target/Platform.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Target/UnixSignals.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StructuredData.h" #include "llvm/Support/FileSystem.h" // Define these constants from POSIX mman.h rather than include the file // so that they will be correct even when compiled on Linux. #define MAP_PRIVATE 2 #define MAP_ANON 0x1000 using namespace lldb; using namespace lldb_private; static uint32_t g_initialize_count = 0; // Use a singleton function for g_local_platform_sp to avoid init // constructors since LLDB is often part of a shared library static PlatformSP &GetHostPlatformSP() { static PlatformSP g_platform_sp; return g_platform_sp; } const char *Platform::GetHostPlatformName() { return "host"; } namespace { PropertyDefinition g_properties[] = { {"use-module-cache", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "Use module cache."}, {"module-cache-directory", OptionValue::eTypeFileSpec, true, 0, nullptr, nullptr, "Root directory for cached modules."}, {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}}; enum { ePropertyUseModuleCache, ePropertyModuleCacheDirectory }; } // namespace ConstString PlatformProperties::GetSettingName() { static ConstString g_setting_name("platform"); return g_setting_name; } PlatformProperties::PlatformProperties() { m_collection_sp.reset(new OptionValueProperties(GetSettingName())); m_collection_sp->Initialize(g_properties); auto module_cache_dir = GetModuleCacheDirectory(); if (module_cache_dir) return; llvm::SmallString<64> user_home_dir; if (!llvm::sys::path::home_directory(user_home_dir)) return; module_cache_dir = FileSpec(user_home_dir.c_str(), false); module_cache_dir.AppendPathComponent(".lldb"); module_cache_dir.AppendPathComponent("module_cache"); SetModuleCacheDirectory(module_cache_dir); } bool PlatformProperties::GetUseModuleCache() const { const auto idx = ePropertyUseModuleCache; return m_collection_sp->GetPropertyAtIndexAsBoolean( nullptr, idx, g_properties[idx].default_uint_value != 0); } bool PlatformProperties::SetUseModuleCache(bool use_module_cache) { return m_collection_sp->SetPropertyAtIndexAsBoolean( nullptr, ePropertyUseModuleCache, use_module_cache); } FileSpec PlatformProperties::GetModuleCacheDirectory() const { return m_collection_sp->GetPropertyAtIndexAsFileSpec( nullptr, ePropertyModuleCacheDirectory); } bool PlatformProperties::SetModuleCacheDirectory(const FileSpec &dir_spec) { return m_collection_sp->SetPropertyAtIndexAsFileSpec( nullptr, ePropertyModuleCacheDirectory, dir_spec); } //------------------------------------------------------------------ /// Get the native host platform plug-in. /// /// There should only be one of these for each host that LLDB runs /// upon that should be statically compiled in and registered using /// preprocessor macros or other similar build mechanisms. /// /// This platform will be used as the default platform when launching /// or attaching to processes unless another platform is specified. //------------------------------------------------------------------ PlatformSP Platform::GetHostPlatform() { return GetHostPlatformSP(); } static std::vector &GetPlatformList() { static std::vector g_platform_list; return g_platform_list; } static std::recursive_mutex &GetPlatformListMutex() { static std::recursive_mutex g_mutex; return g_mutex; } void Platform::Initialize() { g_initialize_count++; } void Platform::Terminate() { if (g_initialize_count > 0) { if (--g_initialize_count == 0) { std::lock_guard guard(GetPlatformListMutex()); GetPlatformList().clear(); } } } const PlatformPropertiesSP &Platform::GetGlobalPlatformProperties() { static const auto g_settings_sp(std::make_shared()); return g_settings_sp; } void Platform::SetHostPlatform(const lldb::PlatformSP &platform_sp) { // The native platform should use its static void Platform::Initialize() // function to register itself as the native platform. GetHostPlatformSP() = platform_sp; if (platform_sp) { std::lock_guard guard(GetPlatformListMutex()); GetPlatformList().push_back(platform_sp); } } Status Platform::GetFileWithUUID(const FileSpec &platform_file, const UUID *uuid_ptr, FileSpec &local_file) { // Default to the local case local_file = platform_file; return Status(); } FileSpecList Platform::LocateExecutableScriptingResources(Target *target, Module &module, Stream *feedback_stream) { return FileSpecList(); } // PlatformSP // Platform::FindPlugin (Process *process, const ConstString &plugin_name) //{ // PlatformCreateInstance create_callback = nullptr; // if (plugin_name) // { // create_callback = // PluginManager::GetPlatformCreateCallbackForPluginName (plugin_name); // if (create_callback) // { // ArchSpec arch; // if (process) // { // arch = process->GetTarget().GetArchitecture(); // } // PlatformSP platform_sp(create_callback(process, &arch)); // if (platform_sp) // return platform_sp; // } // } // else // { // for (uint32_t idx = 0; (create_callback = // PluginManager::GetPlatformCreateCallbackAtIndex(idx)) != nullptr; // ++idx) // { // PlatformSP platform_sp(create_callback(process, nullptr)); // if (platform_sp) // return platform_sp; // } // } // return PlatformSP(); //} Status Platform::GetSharedModule(const ModuleSpec &module_spec, Process *process, ModuleSP &module_sp, const FileSpecList *module_search_paths_ptr, ModuleSP *old_module_sp_ptr, bool *did_create_ptr) { if (IsHost()) return ModuleList::GetSharedModule( module_spec, module_sp, module_search_paths_ptr, old_module_sp_ptr, did_create_ptr, false); return GetRemoteSharedModule(module_spec, process, module_sp, [&](const ModuleSpec &spec) { Status error = ModuleList::GetSharedModule( spec, module_sp, module_search_paths_ptr, old_module_sp_ptr, did_create_ptr, false); if (error.Success() && module_sp) module_sp->SetPlatformFileSpec( spec.GetFileSpec()); return error; }, did_create_ptr); } bool Platform::GetModuleSpec(const FileSpec &module_file_spec, const ArchSpec &arch, ModuleSpec &module_spec) { ModuleSpecList module_specs; if (ObjectFile::GetModuleSpecifications(module_file_spec, 0, 0, module_specs) == 0) return false; ModuleSpec matched_module_spec; return module_specs.FindMatchingModuleSpec(ModuleSpec(module_file_spec, arch), module_spec); } PlatformSP Platform::Find(const ConstString &name) { if (name) { static ConstString g_host_platform_name("host"); if (name == g_host_platform_name) return GetHostPlatform(); std::lock_guard guard(GetPlatformListMutex()); for (const auto &platform_sp : GetPlatformList()) { if (platform_sp->GetName() == name) return platform_sp; } } return PlatformSP(); } PlatformSP Platform::Create(const ConstString &name, Status &error) { PlatformCreateInstance create_callback = nullptr; lldb::PlatformSP platform_sp; if (name) { static ConstString g_host_platform_name("host"); if (name == g_host_platform_name) return GetHostPlatform(); create_callback = PluginManager::GetPlatformCreateCallbackForPluginName(name); if (create_callback) platform_sp = create_callback(true, nullptr); else error.SetErrorStringWithFormat( "unable to find a plug-in for the platform named \"%s\"", name.GetCString()); } else error.SetErrorString("invalid platform name"); if (platform_sp) { std::lock_guard guard(GetPlatformListMutex()); GetPlatformList().push_back(platform_sp); } return platform_sp; } PlatformSP Platform::Create(const ArchSpec &arch, ArchSpec *platform_arch_ptr, Status &error) { lldb::PlatformSP platform_sp; if (arch.IsValid()) { // Scope for locker { // First try exact arch matches across all platforms already created std::lock_guard guard(GetPlatformListMutex()); for (const auto &platform_sp : GetPlatformList()) { if (platform_sp->IsCompatibleArchitecture(arch, true, platform_arch_ptr)) return platform_sp; } // Next try compatible arch matches across all platforms already created for (const auto &platform_sp : GetPlatformList()) { if (platform_sp->IsCompatibleArchitecture(arch, false, platform_arch_ptr)) return platform_sp; } } PlatformCreateInstance create_callback; // First try exact arch matches across all platform plug-ins uint32_t idx; for (idx = 0; (create_callback = PluginManager::GetPlatformCreateCallbackAtIndex(idx)); ++idx) { if (create_callback) { platform_sp = create_callback(false, &arch); if (platform_sp && platform_sp->IsCompatibleArchitecture(arch, true, platform_arch_ptr)) { std::lock_guard guard(GetPlatformListMutex()); GetPlatformList().push_back(platform_sp); return platform_sp; } } } // Next try compatible arch matches across all platform plug-ins for (idx = 0; (create_callback = PluginManager::GetPlatformCreateCallbackAtIndex(idx)); ++idx) { if (create_callback) { platform_sp = create_callback(false, &arch); if (platform_sp && platform_sp->IsCompatibleArchitecture(arch, false, platform_arch_ptr)) { std::lock_guard guard(GetPlatformListMutex()); GetPlatformList().push_back(platform_sp); return platform_sp; } } } } else error.SetErrorString("invalid platform name"); if (platform_arch_ptr) platform_arch_ptr->Clear(); platform_sp.reset(); return platform_sp; } //------------------------------------------------------------------ /// Default Constructor //------------------------------------------------------------------ Platform::Platform(bool is_host) : m_is_host(is_host), m_os_version_set_while_connected(false), m_system_arch_set_while_connected(false), m_sdk_sysroot(), m_sdk_build(), m_working_dir(), m_remote_url(), m_name(), m_major_os_version(UINT32_MAX), m_minor_os_version(UINT32_MAX), m_update_os_version(UINT32_MAX), m_system_arch(), m_mutex(), m_uid_map(), m_gid_map(), m_max_uid_name_len(0), m_max_gid_name_len(0), m_supports_rsync(false), m_rsync_opts(), m_rsync_prefix(), m_supports_ssh(false), m_ssh_opts(), m_ignores_remote_hostname(false), m_trap_handlers(), m_calculated_trap_handlers(false), m_module_cache(llvm::make_unique()) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT)); if (log) log->Printf("%p Platform::Platform()", static_cast(this)); } //------------------------------------------------------------------ /// Destructor. /// /// The destructor is virtual since this class is designed to be /// inherited from by the plug-in instance. //------------------------------------------------------------------ Platform::~Platform() { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT)); if (log) log->Printf("%p Platform::~Platform()", static_cast(this)); } void Platform::GetStatus(Stream &strm) { uint32_t major = UINT32_MAX; uint32_t minor = UINT32_MAX; uint32_t update = UINT32_MAX; std::string s; strm.Printf(" Platform: %s\n", GetPluginName().GetCString()); ArchSpec arch(GetSystemArchitecture()); if (arch.IsValid()) { if (!arch.GetTriple().str().empty()) { strm.Printf(" Triple: "); arch.DumpTriple(strm); strm.EOL(); } } if (GetOSVersion(major, minor, update)) { strm.Printf("OS Version: %u", major); if (minor != UINT32_MAX) strm.Printf(".%u", minor); if (update != UINT32_MAX) strm.Printf(".%u", update); if (GetOSBuildString(s)) strm.Printf(" (%s)", s.c_str()); strm.EOL(); } if (GetOSKernelDescription(s)) strm.Printf(" Kernel: %s\n", s.c_str()); if (IsHost()) { strm.Printf(" Hostname: %s\n", GetHostname()); } else { const bool is_connected = IsConnected(); if (is_connected) strm.Printf(" Hostname: %s\n", GetHostname()); strm.Printf(" Connected: %s\n", is_connected ? "yes" : "no"); } if (GetWorkingDirectory()) { strm.Printf("WorkingDir: %s\n", GetWorkingDirectory().GetCString()); } if (!IsConnected()) return; std::string specific_info(GetPlatformSpecificConnectionInformation()); if (!specific_info.empty()) strm.Printf("Platform-specific connection: %s\n", specific_info.c_str()); } bool Platform::GetOSVersion(uint32_t &major, uint32_t &minor, uint32_t &update, Process *process) { std::lock_guard guard(m_mutex); bool success = m_major_os_version != UINT32_MAX; if (IsHost()) { if (!success) { // We have a local host platform success = HostInfo::GetOSVersion(m_major_os_version, m_minor_os_version, m_update_os_version); m_os_version_set_while_connected = success; } } else { // We have a remote platform. We can only fetch the remote // OS version if we are connected, and we don't want to do it // more than once. const bool is_connected = IsConnected(); bool fetch = false; if (success) { // We have valid OS version info, check to make sure it wasn't // manually set prior to connecting. If it was manually set prior // to connecting, then lets fetch the actual OS version info // if we are now connected. if (is_connected && !m_os_version_set_while_connected) fetch = true; } else { // We don't have valid OS version info, fetch it if we are connected fetch = is_connected; } if (fetch) { success = GetRemoteOSVersion(); m_os_version_set_while_connected = success; } } if (success) { major = m_major_os_version; minor = m_minor_os_version; update = m_update_os_version; } else if (process) { // Check with the process in case it can answer the question if // a process was provided return process->GetHostOSVersion(major, minor, update); } return success; } bool Platform::GetOSBuildString(std::string &s) { s.clear(); if (IsHost()) #if !defined(__linux__) return HostInfo::GetOSBuildString(s); #else return false; #endif else return GetRemoteOSBuildString(s); } bool Platform::GetOSKernelDescription(std::string &s) { if (IsHost()) #if !defined(__linux__) return HostInfo::GetOSKernelDescription(s); #else return false; #endif else return GetRemoteOSKernelDescription(s); } void Platform::AddClangModuleCompilationOptions( Target *target, std::vector &options) { std::vector default_compilation_options = { "-x", "c++", "-Xclang", "-nostdsysteminc", "-Xclang", "-nostdsysteminc"}; options.insert(options.end(), default_compilation_options.begin(), default_compilation_options.end()); } FileSpec Platform::GetWorkingDirectory() { if (IsHost()) { llvm::SmallString<64> cwd; if (llvm::sys::fs::current_path(cwd)) return FileSpec{}; else return FileSpec(cwd, true); } else { if (!m_working_dir) m_working_dir = GetRemoteWorkingDirectory(); return m_working_dir; } } struct RecurseCopyBaton { const FileSpec &dst; Platform *platform_ptr; Status error; }; static FileSpec::EnumerateDirectoryResult RecurseCopy_Callback(void *baton, llvm::sys::fs::file_type ft, const FileSpec &src) { RecurseCopyBaton *rc_baton = (RecurseCopyBaton *)baton; namespace fs = llvm::sys::fs; switch (ft) { case fs::file_type::fifo_file: case fs::file_type::socket_file: // we have no way to copy pipes and sockets - ignore them and continue return FileSpec::eEnumerateDirectoryResultNext; break; case fs::file_type::directory_file: { // make the new directory and get in there FileSpec dst_dir = rc_baton->dst; if (!dst_dir.GetFilename()) dst_dir.GetFilename() = src.GetLastPathComponent(); Status error = rc_baton->platform_ptr->MakeDirectory( dst_dir, lldb::eFilePermissionsDirectoryDefault); if (error.Fail()) { rc_baton->error.SetErrorStringWithFormat( "unable to setup directory %s on remote end", dst_dir.GetCString()); return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out } // now recurse std::string src_dir_path(src.GetPath()); // Make a filespec that only fills in the directory of a FileSpec so // when we enumerate we can quickly fill in the filename for dst copies FileSpec recurse_dst; recurse_dst.GetDirectory().SetCString(dst_dir.GetPath().c_str()); RecurseCopyBaton rc_baton2 = {recurse_dst, rc_baton->platform_ptr, Status()}; FileSpec::EnumerateDirectory(src_dir_path, true, true, true, RecurseCopy_Callback, &rc_baton2); if (rc_baton2.error.Fail()) { rc_baton->error.SetErrorString(rc_baton2.error.AsCString()); return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out } return FileSpec::eEnumerateDirectoryResultNext; } break; case fs::file_type::symlink_file: { // copy the file and keep going FileSpec dst_file = rc_baton->dst; if (!dst_file.GetFilename()) dst_file.GetFilename() = src.GetFilename(); FileSpec src_resolved; rc_baton->error = FileSystem::Readlink(src, src_resolved); if (rc_baton->error.Fail()) return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out rc_baton->error = rc_baton->platform_ptr->CreateSymlink(dst_file, src_resolved); if (rc_baton->error.Fail()) return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out return FileSpec::eEnumerateDirectoryResultNext; } break; case fs::file_type::regular_file: { // copy the file and keep going FileSpec dst_file = rc_baton->dst; if (!dst_file.GetFilename()) dst_file.GetFilename() = src.GetFilename(); Status err = rc_baton->platform_ptr->PutFile(src, dst_file); if (err.Fail()) { rc_baton->error.SetErrorString(err.AsCString()); return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out } return FileSpec::eEnumerateDirectoryResultNext; } break; default: rc_baton->error.SetErrorStringWithFormat( "invalid file detected during copy: %s", src.GetPath().c_str()); return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out break; } llvm_unreachable("Unhandled file_type!"); } Status Platform::Install(const FileSpec &src, const FileSpec &dst) { Status error; Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); if (log) log->Printf("Platform::Install (src='%s', dst='%s')", src.GetPath().c_str(), dst.GetPath().c_str()); FileSpec fixed_dst(dst); if (!fixed_dst.GetFilename()) fixed_dst.GetFilename() = src.GetFilename(); FileSpec working_dir = GetWorkingDirectory(); if (dst) { if (dst.GetDirectory()) { const char first_dst_dir_char = dst.GetDirectory().GetCString()[0]; if (first_dst_dir_char == '/' || first_dst_dir_char == '\\') { fixed_dst.GetDirectory() = dst.GetDirectory(); } // If the fixed destination file doesn't have a directory yet, // then we must have a relative path. We will resolve this relative // path against the platform's working directory if (!fixed_dst.GetDirectory()) { FileSpec relative_spec; std::string path; if (working_dir) { relative_spec = working_dir; relative_spec.AppendPathComponent(dst.GetPath()); fixed_dst.GetDirectory() = relative_spec.GetDirectory(); } else { error.SetErrorStringWithFormat( "platform working directory must be valid for relative path '%s'", dst.GetPath().c_str()); return error; } } } else { if (working_dir) { fixed_dst.GetDirectory().SetCString(working_dir.GetCString()); } else { error.SetErrorStringWithFormat( "platform working directory must be valid for relative path '%s'", dst.GetPath().c_str()); return error; } } } else { if (working_dir) { fixed_dst.GetDirectory().SetCString(working_dir.GetCString()); } else { error.SetErrorStringWithFormat("platform working directory must be valid " "when destination directory is empty"); return error; } } if (log) log->Printf("Platform::Install (src='%s', dst='%s') fixed_dst='%s'", src.GetPath().c_str(), dst.GetPath().c_str(), fixed_dst.GetPath().c_str()); if (GetSupportsRSync()) { error = PutFile(src, dst); } else { namespace fs = llvm::sys::fs; switch (fs::get_file_type(src.GetPath(), false)) { case fs::file_type::directory_file: { llvm::sys::fs::remove(fixed_dst.GetPath()); uint32_t permissions = src.GetPermissions(); if (permissions == 0) permissions = eFilePermissionsDirectoryDefault; error = MakeDirectory(fixed_dst, permissions); if (error.Success()) { // Make a filespec that only fills in the directory of a FileSpec so // when we enumerate we can quickly fill in the filename for dst copies FileSpec recurse_dst; recurse_dst.GetDirectory().SetCString(fixed_dst.GetCString()); std::string src_dir_path(src.GetPath()); RecurseCopyBaton baton = {recurse_dst, this, Status()}; FileSpec::EnumerateDirectory(src_dir_path, true, true, true, RecurseCopy_Callback, &baton); return baton.error; } } break; case fs::file_type::regular_file: llvm::sys::fs::remove(fixed_dst.GetPath()); error = PutFile(src, fixed_dst); break; case fs::file_type::symlink_file: { llvm::sys::fs::remove(fixed_dst.GetPath()); FileSpec src_resolved; error = FileSystem::Readlink(src, src_resolved); if (error.Success()) error = CreateSymlink(dst, src_resolved); } break; case fs::file_type::fifo_file: error.SetErrorString("platform install doesn't handle pipes"); break; case fs::file_type::socket_file: error.SetErrorString("platform install doesn't handle sockets"); break; default: error.SetErrorString( "platform install doesn't handle non file or directory items"); break; } } return error; } bool Platform::SetWorkingDirectory(const FileSpec &file_spec) { if (IsHost()) { Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); LLDB_LOG(log, "{0}", file_spec); if (std::error_code ec = llvm::sys::fs::set_current_path(file_spec.GetPath())) { LLDB_LOG(log, "error: {0}", ec.message()); return false; } return true; } else { m_working_dir.Clear(); return SetRemoteWorkingDirectory(file_spec); } } Status Platform::MakeDirectory(const FileSpec &file_spec, uint32_t permissions) { if (IsHost()) return llvm::sys::fs::create_directory(file_spec.GetPath(), permissions); else { Status error; error.SetErrorStringWithFormat("remote platform %s doesn't support %s", GetPluginName().GetCString(), LLVM_PRETTY_FUNCTION); return error; } } Status Platform::GetFilePermissions(const FileSpec &file_spec, uint32_t &file_permissions) { if (IsHost()) { auto Value = llvm::sys::fs::getPermissions(file_spec.GetPath()); if (Value) file_permissions = Value.get(); return Status(Value.getError()); } else { Status error; error.SetErrorStringWithFormat("remote platform %s doesn't support %s", GetPluginName().GetCString(), LLVM_PRETTY_FUNCTION); return error; } } Status Platform::SetFilePermissions(const FileSpec &file_spec, uint32_t file_permissions) { if (IsHost()) { auto Perms = static_cast(file_permissions); return llvm::sys::fs::setPermissions(file_spec.GetPath(), Perms); } else { Status error; error.SetErrorStringWithFormat("remote platform %s doesn't support %s", GetPluginName().GetCString(), LLVM_PRETTY_FUNCTION); return error; } } ConstString Platform::GetName() { return GetPluginName(); } const char *Platform::GetHostname() { if (IsHost()) return "127.0.0.1"; if (m_name.empty()) return nullptr; return m_name.c_str(); } ConstString Platform::GetFullNameForDylib(ConstString basename) { return basename; } bool Platform::SetRemoteWorkingDirectory(const FileSpec &working_dir) { Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); if (log) log->Printf("Platform::SetRemoteWorkingDirectory('%s')", working_dir.GetCString()); m_working_dir = working_dir; return true; } const char *Platform::GetUserName(uint32_t uid) { #if !defined(LLDB_DISABLE_POSIX) const char *user_name = GetCachedUserName(uid); if (user_name) return user_name; if (IsHost()) { std::string name; if (HostInfo::LookupUserName(uid, name)) return SetCachedUserName(uid, name.c_str(), name.size()); } #endif return nullptr; } const char *Platform::GetGroupName(uint32_t gid) { #if !defined(LLDB_DISABLE_POSIX) const char *group_name = GetCachedGroupName(gid); if (group_name) return group_name; if (IsHost()) { std::string name; if (HostInfo::LookupGroupName(gid, name)) return SetCachedGroupName(gid, name.c_str(), name.size()); } #endif return nullptr; } bool Platform::SetOSVersion(uint32_t major, uint32_t minor, uint32_t update) { if (IsHost()) { // We don't need anyone setting the OS version for the host platform, // we should be able to figure it out by calling // HostInfo::GetOSVersion(...). return false; } else { // We have a remote platform, allow setting the target OS version if // we aren't connected, since if we are connected, we should be able to // request the remote OS version from the connected platform. if (IsConnected()) return false; else { // We aren't connected and we might want to set the OS version // ahead of time before we connect so we can peruse files and // use a local SDK or PDK cache of support files to disassemble // or do other things. m_major_os_version = major; m_minor_os_version = minor; m_update_os_version = update; return true; } } return false; } Status Platform::ResolveExecutable(const ModuleSpec &module_spec, lldb::ModuleSP &exe_module_sp, const FileSpecList *module_search_paths_ptr) { Status error; if (module_spec.GetFileSpec().Exists()) { if (module_spec.GetArchitecture().IsValid()) { error = ModuleList::GetSharedModule(module_spec, exe_module_sp, module_search_paths_ptr, nullptr, nullptr); } else { // No valid architecture was specified, ask the platform for // the architectures that we should be using (in the correct order) // and see if we can find a match that way ModuleSpec arch_module_spec(module_spec); for (uint32_t idx = 0; GetSupportedArchitectureAtIndex( idx, arch_module_spec.GetArchitecture()); ++idx) { error = ModuleList::GetSharedModule(arch_module_spec, exe_module_sp, module_search_paths_ptr, nullptr, nullptr); // Did we find an executable using one of the if (error.Success() && exe_module_sp) break; } } } else { error.SetErrorStringWithFormat("'%s' does not exist", module_spec.GetFileSpec().GetPath().c_str()); } return error; } Status Platform::ResolveSymbolFile(Target &target, const ModuleSpec &sym_spec, FileSpec &sym_file) { Status error; if (sym_spec.GetSymbolFileSpec().Exists()) sym_file = sym_spec.GetSymbolFileSpec(); else error.SetErrorString("unable to resolve symbol file"); return error; } bool Platform::ResolveRemotePath(const FileSpec &platform_path, FileSpec &resolved_platform_path) { resolved_platform_path = platform_path; return resolved_platform_path.ResolvePath(); } const ArchSpec &Platform::GetSystemArchitecture() { if (IsHost()) { if (!m_system_arch.IsValid()) { // We have a local host platform m_system_arch = HostInfo::GetArchitecture(); m_system_arch_set_while_connected = m_system_arch.IsValid(); } } else { // We have a remote platform. We can only fetch the remote // system architecture if we are connected, and we don't want to do it // more than once. const bool is_connected = IsConnected(); bool fetch = false; if (m_system_arch.IsValid()) { // We have valid OS version info, check to make sure it wasn't // manually set prior to connecting. If it was manually set prior // to connecting, then lets fetch the actual OS version info // if we are now connected. if (is_connected && !m_system_arch_set_while_connected) fetch = true; } else { // We don't have valid OS version info, fetch it if we are connected fetch = is_connected; } if (fetch) { m_system_arch = GetRemoteSystemArchitecture(); m_system_arch_set_while_connected = m_system_arch.IsValid(); } } return m_system_arch; } Status Platform::ConnectRemote(Args &args) { Status error; if (IsHost()) error.SetErrorStringWithFormat("The currently selected platform (%s) is " "the host platform and is always connected.", GetPluginName().GetCString()); else error.SetErrorStringWithFormat( "Platform::ConnectRemote() is not supported by %s", GetPluginName().GetCString()); return error; } Status Platform::DisconnectRemote() { Status error; if (IsHost()) error.SetErrorStringWithFormat("The currently selected platform (%s) is " "the host platform and is always connected.", GetPluginName().GetCString()); else error.SetErrorStringWithFormat( "Platform::DisconnectRemote() is not supported by %s", GetPluginName().GetCString()); return error; } bool Platform::GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info) { // Take care of the host case so that each subclass can just // call this function to get the host functionality. if (IsHost()) return Host::GetProcessInfo(pid, process_info); return false; } uint32_t Platform::FindProcesses(const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos) { // Take care of the host case so that each subclass can just // call this function to get the host functionality. uint32_t match_count = 0; if (IsHost()) match_count = Host::FindProcesses(match_info, process_infos); return match_count; } Status Platform::LaunchProcess(ProcessLaunchInfo &launch_info) { Status error; Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); if (log) log->Printf("Platform::%s()", __FUNCTION__); // Take care of the host case so that each subclass can just // call this function to get the host functionality. if (IsHost()) { if (::getenv("LLDB_LAUNCH_FLAG_LAUNCH_IN_TTY")) launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY); if (launch_info.GetFlags().Test(eLaunchFlagLaunchInShell)) { const bool is_localhost = true; const bool will_debug = launch_info.GetFlags().Test(eLaunchFlagDebug); const bool first_arg_is_full_shell_command = false; uint32_t num_resumes = GetResumeCountForLaunchInfo(launch_info); if (log) { const FileSpec &shell = launch_info.GetShell(); const char *shell_str = (shell) ? shell.GetPath().c_str() : ""; log->Printf( "Platform::%s GetResumeCountForLaunchInfo() returned %" PRIu32 ", shell is '%s'", __FUNCTION__, num_resumes, shell_str); } if (!launch_info.ConvertArgumentsForLaunchingInShell( error, is_localhost, will_debug, first_arg_is_full_shell_command, num_resumes)) return error; } else if (launch_info.GetFlags().Test(eLaunchFlagShellExpandArguments)) { error = ShellExpandArguments(launch_info); if (error.Fail()) { error.SetErrorStringWithFormat("shell expansion failed (reason: %s). " "consider launching with 'process " "launch'.", error.AsCString("unknown")); return error; } } if (log) log->Printf("Platform::%s final launch_info resume count: %" PRIu32, __FUNCTION__, launch_info.GetResumeCount()); error = Host::LaunchProcess(launch_info); } else error.SetErrorString( "base lldb_private::Platform class can't launch remote processes"); return error; } Status Platform::ShellExpandArguments(ProcessLaunchInfo &launch_info) { if (IsHost()) return Host::ShellExpandArguments(launch_info); return Status("base lldb_private::Platform class can't expand arguments"); } Status Platform::KillProcess(const lldb::pid_t pid) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); if (log) log->Printf("Platform::%s, pid %" PRIu64, __FUNCTION__, pid); // Try to find a process plugin to handle this Kill request. If we can't, // fall back to // the default OS implementation. size_t num_debuggers = Debugger::GetNumDebuggers(); for (size_t didx = 0; didx < num_debuggers; ++didx) { DebuggerSP debugger = Debugger::GetDebuggerAtIndex(didx); lldb_private::TargetList &targets = debugger->GetTargetList(); for (int tidx = 0; tidx < targets.GetNumTargets(); ++tidx) { ProcessSP process = targets.GetTargetAtIndex(tidx)->GetProcessSP(); if (process->GetID() == pid) return process->Destroy(true); } } if (!IsHost()) { return Status( "base lldb_private::Platform class can't kill remote processes unless " "they are controlled by a process plugin"); } Host::Kill(pid, SIGTERM); return Status(); } lldb::ProcessSP Platform::DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger, Target *target, // Can be nullptr, if nullptr create a // new target, else use existing one Status &error) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); if (log) log->Printf("Platform::%s entered (target %p)", __FUNCTION__, static_cast(target)); ProcessSP process_sp; // Make sure we stop at the entry point launch_info.GetFlags().Set(eLaunchFlagDebug); // We always launch the process we are going to debug in a separate process // group, since then we can handle ^C interrupts ourselves w/o having to worry // about the target getting them as well. launch_info.SetLaunchInSeparateProcessGroup(true); // Allow any StructuredData process-bound plugins to adjust the launch info // if needed size_t i = 0; bool iteration_complete = false; // Note iteration can't simply go until a nullptr callback is returned, as // it is valid for a plugin to not supply a filter. auto get_filter_func = PluginManager::GetStructuredDataFilterCallbackAtIndex; for (auto filter_callback = get_filter_func(i, iteration_complete); !iteration_complete; filter_callback = get_filter_func(++i, iteration_complete)) { if (filter_callback) { // Give this ProcessLaunchInfo filter a chance to adjust the launch // info. error = (*filter_callback)(launch_info, target); if (!error.Success()) { if (log) log->Printf("Platform::%s() StructuredDataPlugin launch " "filter failed.", __FUNCTION__); return process_sp; } } } error = LaunchProcess(launch_info); if (error.Success()) { if (log) log->Printf("Platform::%s LaunchProcess() call succeeded (pid=%" PRIu64 ")", __FUNCTION__, launch_info.GetProcessID()); if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) { ProcessAttachInfo attach_info(launch_info); process_sp = Attach(attach_info, debugger, target, error); if (process_sp) { if (log) log->Printf("Platform::%s Attach() succeeded, Process plugin: %s", __FUNCTION__, process_sp->GetPluginName().AsCString()); launch_info.SetHijackListener(attach_info.GetHijackListener()); // Since we attached to the process, it will think it needs to detach // if the process object just goes away without an explicit call to // Process::Kill() or Process::Detach(), so let it know to kill the // process if this happens. process_sp->SetShouldDetach(false); // If we didn't have any file actions, the pseudo terminal might // have been used where the slave side was given as the file to // open for stdin/out/err after we have already opened the master // so we can read/write stdin/out/err. int pty_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor(); if (pty_fd != lldb_utility::PseudoTerminal::invalid_fd) { process_sp->SetSTDIOFileDescriptor(pty_fd); } } else { if (log) log->Printf("Platform::%s Attach() failed: %s", __FUNCTION__, error.AsCString()); } } else { if (log) log->Printf("Platform::%s LaunchProcess() returned launch_info with " "invalid process id", __FUNCTION__); } } else { if (log) log->Printf("Platform::%s LaunchProcess() failed: %s", __FUNCTION__, error.AsCString()); } return process_sp; } lldb::PlatformSP Platform::GetPlatformForArchitecture(const ArchSpec &arch, ArchSpec *platform_arch_ptr) { lldb::PlatformSP platform_sp; Status error; if (arch.IsValid()) platform_sp = Platform::Create(arch, platform_arch_ptr, error); return platform_sp; } //------------------------------------------------------------------ /// Lets a platform answer if it is compatible with a given /// architecture and the target triple contained within. //------------------------------------------------------------------ bool Platform::IsCompatibleArchitecture(const ArchSpec &arch, bool exact_arch_match, ArchSpec *compatible_arch_ptr) { // If the architecture is invalid, we must answer true... if (arch.IsValid()) { ArchSpec platform_arch; // Try for an exact architecture match first. if (exact_arch_match) { for (uint32_t arch_idx = 0; GetSupportedArchitectureAtIndex(arch_idx, platform_arch); ++arch_idx) { if (arch.IsExactMatch(platform_arch)) { if (compatible_arch_ptr) *compatible_arch_ptr = platform_arch; return true; } } } else { for (uint32_t arch_idx = 0; GetSupportedArchitectureAtIndex(arch_idx, platform_arch); ++arch_idx) { if (arch.IsCompatibleMatch(platform_arch)) { if (compatible_arch_ptr) *compatible_arch_ptr = platform_arch; return true; } } } } if (compatible_arch_ptr) compatible_arch_ptr->Clear(); return false; } Status Platform::PutFile(const FileSpec &source, const FileSpec &destination, uint32_t uid, uint32_t gid) { Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); if (log) log->Printf("[PutFile] Using block by block transfer....\n"); uint32_t source_open_options = File::eOpenOptionRead | File::eOpenOptionCloseOnExec; namespace fs = llvm::sys::fs; if (fs::is_symlink_file(source.GetPath())) source_open_options |= File::eOpenOptionDontFollowSymlinks; File source_file(source, source_open_options, lldb::eFilePermissionsUserRW); Status error; uint32_t permissions = source_file.GetPermissions(error); if (permissions == 0) permissions = lldb::eFilePermissionsFileDefault; if (!source_file.IsValid()) return Status("PutFile: unable to open source file"); lldb::user_id_t dest_file = OpenFile( destination, File::eOpenOptionCanCreate | File::eOpenOptionWrite | File::eOpenOptionTruncate | File::eOpenOptionCloseOnExec, permissions, error); if (log) log->Printf("dest_file = %" PRIu64 "\n", dest_file); if (error.Fail()) return error; if (dest_file == UINT64_MAX) return Status("unable to open target file"); lldb::DataBufferSP buffer_sp(new DataBufferHeap(1024, 0)); uint64_t offset = 0; for (;;) { size_t bytes_read = buffer_sp->GetByteSize(); error = source_file.Read(buffer_sp->GetBytes(), bytes_read); if (error.Fail() || bytes_read == 0) break; const uint64_t bytes_written = WriteFile(dest_file, offset, buffer_sp->GetBytes(), bytes_read, error); if (error.Fail()) break; offset += bytes_written; if (bytes_written != bytes_read) { // We didn't write the correct number of bytes, so adjust // the file position in the source file we are reading from... source_file.SeekFromStart(offset); } } CloseFile(dest_file, error); if (uid == UINT32_MAX && gid == UINT32_MAX) return error; // TODO: ChownFile? return error; } Status Platform::GetFile(const FileSpec &source, const FileSpec &destination) { Status error("unimplemented"); return error; } Status Platform::CreateSymlink(const FileSpec &src, // The name of the link is in src const FileSpec &dst) // The symlink points to dst { Status error("unimplemented"); return error; } bool Platform::GetFileExists(const lldb_private::FileSpec &file_spec) { return false; } Status Platform::Unlink(const FileSpec &path) { Status error("unimplemented"); return error; } -uint64_t Platform::ConvertMmapFlagsToPlatform(const ArchSpec &arch, - unsigned flags) { +MmapArgList Platform::GetMmapArgumentList(const ArchSpec &arch, addr_t addr, + addr_t length, unsigned prot, + unsigned flags, addr_t fd, + addr_t offset) { uint64_t flags_platform = 0; if (flags & eMmapFlagsPrivate) flags_platform |= MAP_PRIVATE; if (flags & eMmapFlagsAnon) flags_platform |= MAP_ANON; - return flags_platform; + + MmapArgList args({addr, length, prot, flags_platform, fd, offset}); + return args; } lldb_private::Status Platform::RunShellCommand( const char *command, // Shouldn't be nullptr const FileSpec & working_dir, // Pass empty FileSpec to use the current working directory int *status_ptr, // Pass nullptr if you don't want the process exit status int *signo_ptr, // Pass nullptr if you don't want the signal that caused the // process to exit std::string *command_output, // Pass nullptr if you don't want the command output uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish { if (IsHost()) return Host::RunShellCommand(command, working_dir, status_ptr, signo_ptr, command_output, timeout_sec); else return Status("unimplemented"); } bool Platform::CalculateMD5(const FileSpec &file_spec, uint64_t &low, uint64_t &high) { if (!IsHost()) return false; auto Result = llvm::sys::fs::md5_contents(file_spec.GetPath()); if (!Result) return false; std::tie(high, low) = Result->words(); return true; } void Platform::SetLocalCacheDirectory(const char *local) { m_local_cache_directory.assign(local); } const char *Platform::GetLocalCacheDirectory() { return m_local_cache_directory.c_str(); } static OptionDefinition g_rsync_option_table[] = { {LLDB_OPT_SET_ALL, false, "rsync", 'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Enable rsync."}, {LLDB_OPT_SET_ALL, false, "rsync-opts", 'R', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCommandName, "Platform-specific options required for rsync to work."}, {LLDB_OPT_SET_ALL, false, "rsync-prefix", 'P', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCommandName, "Platform-specific rsync prefix put before the remote path."}, {LLDB_OPT_SET_ALL, false, "ignore-remote-hostname", 'i', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Do not automatically fill in the remote hostname when composing the " "rsync command."}, }; static OptionDefinition g_ssh_option_table[] = { {LLDB_OPT_SET_ALL, false, "ssh", 's', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Enable SSH."}, {LLDB_OPT_SET_ALL, false, "ssh-opts", 'S', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCommandName, "Platform-specific options required for SSH to work."}, }; static OptionDefinition g_caching_option_table[] = { {LLDB_OPT_SET_ALL, false, "local-cache-dir", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePath, "Path in which to store local copies of files."}, }; llvm::ArrayRef OptionGroupPlatformRSync::GetDefinitions() { return llvm::makeArrayRef(g_rsync_option_table); } void OptionGroupPlatformRSync::OptionParsingStarting( ExecutionContext *execution_context) { m_rsync = false; m_rsync_opts.clear(); m_rsync_prefix.clear(); m_ignores_remote_hostname = false; } lldb_private::Status OptionGroupPlatformRSync::SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) { Status error; char short_option = (char)GetDefinitions()[option_idx].short_option; switch (short_option) { case 'r': m_rsync = true; break; case 'R': m_rsync_opts.assign(option_arg); break; case 'P': m_rsync_prefix.assign(option_arg); break; case 'i': m_ignores_remote_hostname = true; break; default: error.SetErrorStringWithFormat("unrecognized option '%c'", short_option); break; } return error; } lldb::BreakpointSP Platform::SetThreadCreationBreakpoint(lldb_private::Target &target) { return lldb::BreakpointSP(); } llvm::ArrayRef OptionGroupPlatformSSH::GetDefinitions() { return llvm::makeArrayRef(g_ssh_option_table); } void OptionGroupPlatformSSH::OptionParsingStarting( ExecutionContext *execution_context) { m_ssh = false; m_ssh_opts.clear(); } lldb_private::Status OptionGroupPlatformSSH::SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) { Status error; char short_option = (char)GetDefinitions()[option_idx].short_option; switch (short_option) { case 's': m_ssh = true; break; case 'S': m_ssh_opts.assign(option_arg); break; default: error.SetErrorStringWithFormat("unrecognized option '%c'", short_option); break; } return error; } llvm::ArrayRef OptionGroupPlatformCaching::GetDefinitions() { return llvm::makeArrayRef(g_caching_option_table); } void OptionGroupPlatformCaching::OptionParsingStarting( ExecutionContext *execution_context) { m_cache_dir.clear(); } lldb_private::Status OptionGroupPlatformCaching::SetOptionValue( uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) { Status error; char short_option = (char)GetDefinitions()[option_idx].short_option; switch (short_option) { case 'c': m_cache_dir.assign(option_arg); break; default: error.SetErrorStringWithFormat("unrecognized option '%c'", short_option); break; } return error; } size_t Platform::GetEnvironment(StringList &environment) { environment.Clear(); return false; } const std::vector &Platform::GetTrapHandlerSymbolNames() { if (!m_calculated_trap_handlers) { std::lock_guard guard(m_mutex); if (!m_calculated_trap_handlers) { CalculateTrapHandlerSymbolNames(); m_calculated_trap_handlers = true; } } return m_trap_handlers; } Status Platform::GetCachedExecutable( ModuleSpec &module_spec, lldb::ModuleSP &module_sp, const FileSpecList *module_search_paths_ptr, Platform &remote_platform) { const auto platform_spec = module_spec.GetFileSpec(); const auto error = LoadCachedExecutable( module_spec, module_sp, module_search_paths_ptr, remote_platform); if (error.Success()) { module_spec.GetFileSpec() = module_sp->GetFileSpec(); module_spec.GetPlatformFileSpec() = platform_spec; } return error; } Status Platform::LoadCachedExecutable( const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, const FileSpecList *module_search_paths_ptr, Platform &remote_platform) { return GetRemoteSharedModule(module_spec, nullptr, module_sp, [&](const ModuleSpec &spec) { return remote_platform.ResolveExecutable( spec, module_sp, module_search_paths_ptr); }, nullptr); } Status Platform::GetRemoteSharedModule(const ModuleSpec &module_spec, Process *process, lldb::ModuleSP &module_sp, const ModuleResolver &module_resolver, bool *did_create_ptr) { // Get module information from a target. ModuleSpec resolved_module_spec; bool got_module_spec = false; if (process) { // Try to get module information from the process if (process->GetModuleSpec(module_spec.GetFileSpec(), module_spec.GetArchitecture(), resolved_module_spec)) { if (module_spec.GetUUID().IsValid() == false || module_spec.GetUUID() == resolved_module_spec.GetUUID()) { got_module_spec = true; } } } if (module_spec.GetArchitecture().IsValid() == false) { Status error; // No valid architecture was specified, ask the platform for // the architectures that we should be using (in the correct order) // and see if we can find a match that way ModuleSpec arch_module_spec(module_spec); for (uint32_t idx = 0; GetSupportedArchitectureAtIndex( idx, arch_module_spec.GetArchitecture()); ++idx) { error = ModuleList::GetSharedModule(arch_module_spec, module_sp, nullptr, nullptr, nullptr); // Did we find an executable using one of the if (error.Success() && module_sp) break; } if (module_sp) got_module_spec = true; } if (!got_module_spec) { // Get module information from a target. if (!GetModuleSpec(module_spec.GetFileSpec(), module_spec.GetArchitecture(), resolved_module_spec)) { if (module_spec.GetUUID().IsValid() == false || module_spec.GetUUID() == resolved_module_spec.GetUUID()) { return module_resolver(module_spec); } } } // If we are looking for a specific UUID, make sure resolved_module_spec has // the same one before we search. if (module_spec.GetUUID().IsValid()) { resolved_module_spec.GetUUID() = module_spec.GetUUID(); } // Trying to find a module by UUID on local file system. const auto error = module_resolver(resolved_module_spec); if (error.Fail()) { if (GetCachedSharedModule(resolved_module_spec, module_sp, did_create_ptr)) return Status(); } return error; } bool Platform::GetCachedSharedModule(const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, bool *did_create_ptr) { if (IsHost() || !GetGlobalPlatformProperties()->GetUseModuleCache() || !GetGlobalPlatformProperties()->GetModuleCacheDirectory()) return false; Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); // Check local cache for a module. auto error = m_module_cache->GetAndPut( GetModuleCacheRoot(), GetCacheHostname(), module_spec, [this](const ModuleSpec &module_spec, const FileSpec &tmp_download_file_spec) { return DownloadModuleSlice( module_spec.GetFileSpec(), module_spec.GetObjectOffset(), module_spec.GetObjectSize(), tmp_download_file_spec); }, [this](const ModuleSP &module_sp, const FileSpec &tmp_download_file_spec) { return DownloadSymbolFile(module_sp, tmp_download_file_spec); }, module_sp, did_create_ptr); if (error.Success()) return true; if (log) log->Printf("Platform::%s - module %s not found in local cache: %s", __FUNCTION__, module_spec.GetUUID().GetAsString().c_str(), error.AsCString()); return false; } Status Platform::DownloadModuleSlice(const FileSpec &src_file_spec, const uint64_t src_offset, const uint64_t src_size, const FileSpec &dst_file_spec) { Status error; std::error_code EC; llvm::raw_fd_ostream dst(dst_file_spec.GetPath(), EC, llvm::sys::fs::F_None); if (EC) { error.SetErrorStringWithFormat("unable to open destination file: %s", dst_file_spec.GetPath().c_str()); return error; } auto src_fd = OpenFile(src_file_spec, File::eOpenOptionRead, lldb::eFilePermissionsFileDefault, error); if (error.Fail()) { error.SetErrorStringWithFormat("unable to open source file: %s", error.AsCString()); return error; } std::vector buffer(1024); auto offset = src_offset; uint64_t total_bytes_read = 0; while (total_bytes_read < src_size) { const auto to_read = std::min(static_cast(buffer.size()), src_size - total_bytes_read); const uint64_t n_read = ReadFile(src_fd, offset, &buffer[0], to_read, error); if (error.Fail()) break; if (n_read == 0) { error.SetErrorString("read 0 bytes"); break; } offset += n_read; total_bytes_read += n_read; dst.write(&buffer[0], n_read); } Status close_error; CloseFile(src_fd, close_error); // Ignoring close error. return error; } Status Platform::DownloadSymbolFile(const lldb::ModuleSP &module_sp, const FileSpec &dst_file_spec) { return Status( "Symbol file downloading not supported by the default platform."); } FileSpec Platform::GetModuleCacheRoot() { auto dir_spec = GetGlobalPlatformProperties()->GetModuleCacheDirectory(); dir_spec.AppendPathComponent(GetName().AsCString()); return dir_spec; } const char *Platform::GetCacheHostname() { return GetHostname(); } const UnixSignalsSP &Platform::GetRemoteUnixSignals() { static const auto s_default_unix_signals_sp = std::make_shared(); return s_default_unix_signals_sp; } const UnixSignalsSP &Platform::GetUnixSignals() { if (IsHost()) return Host::GetUnixSignals(); return GetRemoteUnixSignals(); } uint32_t Platform::LoadImage(lldb_private::Process *process, const lldb_private::FileSpec &local_file, const lldb_private::FileSpec &remote_file, lldb_private::Status &error) { if (local_file && remote_file) { // Both local and remote file was specified. Install the local file to the // given location. if (IsRemote() || local_file != remote_file) { error = Install(local_file, remote_file); if (error.Fail()) return LLDB_INVALID_IMAGE_TOKEN; } return DoLoadImage(process, remote_file, error); } if (local_file) { // Only local file was specified. Install it to the current working // directory. FileSpec target_file = GetWorkingDirectory(); target_file.AppendPathComponent(local_file.GetFilename().AsCString()); if (IsRemote() || local_file != target_file) { error = Install(local_file, target_file); if (error.Fail()) return LLDB_INVALID_IMAGE_TOKEN; } return DoLoadImage(process, target_file, error); } if (remote_file) { // Only remote file was specified so we don't have to do any copying return DoLoadImage(process, remote_file, error); } error.SetErrorString("Neither local nor remote file was specified"); return LLDB_INVALID_IMAGE_TOKEN; } uint32_t Platform::DoLoadImage(lldb_private::Process *process, const lldb_private::FileSpec &remote_file, lldb_private::Status &error) { error.SetErrorString("LoadImage is not supported on the current platform"); return LLDB_INVALID_IMAGE_TOKEN; } Status Platform::UnloadImage(lldb_private::Process *process, uint32_t image_token) { return Status("UnloadImage is not supported on the current platform"); } lldb::ProcessSP Platform::ConnectProcess(llvm::StringRef connect_url, llvm::StringRef plugin_name, lldb_private::Debugger &debugger, lldb_private::Target *target, lldb_private::Status &error) { error.Clear(); if (!target) { TargetSP new_target_sp; error = debugger.GetTargetList().CreateTarget(debugger, "", "", false, nullptr, new_target_sp); target = new_target_sp.get(); } if (!target || error.Fail()) return nullptr; debugger.GetTargetList().SetSelectedTarget(target); lldb::ProcessSP process_sp = target->CreateProcess(debugger.GetListener(), plugin_name, nullptr); if (!process_sp) return nullptr; error = process_sp->ConnectRemote(debugger.GetOutputFile().get(), connect_url); if (error.Fail()) return nullptr; return process_sp; } size_t Platform::ConnectToWaitingProcesses(lldb_private::Debugger &debugger, lldb_private::Status &error) { error.Clear(); return 0; } size_t Platform::GetSoftwareBreakpointTrapOpcode(Target &target, BreakpointSite *bp_site) { ArchSpec arch = target.GetArchitecture(); const uint8_t *trap_opcode = nullptr; size_t trap_opcode_size = 0; switch (arch.GetMachine()) { case llvm::Triple::aarch64: { static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4}; trap_opcode = g_aarch64_opcode; trap_opcode_size = sizeof(g_aarch64_opcode); } break; // TODO: support big-endian arm and thumb trap codes. case llvm::Triple::arm: { // The ARM reference recommends the use of 0xe7fddefe and 0xdefe // but the linux kernel does otherwise. static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7}; static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde}; lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0)); AddressClass addr_class = eAddressClassUnknown; if (bp_loc_sp) { addr_class = bp_loc_sp->GetAddress().GetAddressClass(); if (addr_class == eAddressClassUnknown && (bp_loc_sp->GetAddress().GetFileAddress() & 1)) addr_class = eAddressClassCodeAlternateISA; } if (addr_class == eAddressClassCodeAlternateISA) { trap_opcode = g_thumb_breakpoint_opcode; trap_opcode_size = sizeof(g_thumb_breakpoint_opcode); } else { trap_opcode = g_arm_breakpoint_opcode; trap_opcode_size = sizeof(g_arm_breakpoint_opcode); } } break; case llvm::Triple::mips: case llvm::Triple::mips64: { static const uint8_t g_hex_opcode[] = {0x00, 0x00, 0x00, 0x0d}; trap_opcode = g_hex_opcode; trap_opcode_size = sizeof(g_hex_opcode); } break; case llvm::Triple::mipsel: case llvm::Triple::mips64el: { static const uint8_t g_hex_opcode[] = {0x0d, 0x00, 0x00, 0x00}; trap_opcode = g_hex_opcode; trap_opcode_size = sizeof(g_hex_opcode); } break; case llvm::Triple::systemz: { static const uint8_t g_hex_opcode[] = {0x00, 0x01}; trap_opcode = g_hex_opcode; trap_opcode_size = sizeof(g_hex_opcode); } break; case llvm::Triple::hexagon: { static const uint8_t g_hex_opcode[] = {0x0c, 0xdb, 0x00, 0x54}; trap_opcode = g_hex_opcode; trap_opcode_size = sizeof(g_hex_opcode); } break; case llvm::Triple::ppc: case llvm::Triple::ppc64: { static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08}; trap_opcode = g_ppc_opcode; trap_opcode_size = sizeof(g_ppc_opcode); } break; case llvm::Triple::x86: case llvm::Triple::x86_64: { static const uint8_t g_i386_opcode[] = {0xCC}; trap_opcode = g_i386_opcode; trap_opcode_size = sizeof(g_i386_opcode); } break; default: llvm_unreachable( "Unhandled architecture in Platform::GetSoftwareBreakpointTrapOpcode"); } assert(bp_site); if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size)) return trap_opcode_size; return 0; }