1 //===-- Process.h -----------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef liblldb_Process_h_
11 #define liblldb_Process_h_
13 #include "lldb/Host/Config.h"
24 #include <unordered_set>
27 // Other libraries and framework includes
29 #include "lldb/Breakpoint/BreakpointSiteList.h"
30 #include "lldb/Core/ArchSpec.h"
31 #include "lldb/Core/Broadcaster.h"
32 #include "lldb/Core/Communication.h"
33 #include "lldb/Core/Event.h"
34 #include "lldb/Core/Listener.h"
35 #include "lldb/Core/LoadedModuleInfoList.h"
36 #include "lldb/Core/PluginInterface.h"
37 #include "lldb/Core/StructuredData.h"
38 #include "lldb/Core/ThreadSafeValue.h"
39 #include "lldb/Core/TraceOptions.h"
40 #include "lldb/Core/UserSettingsController.h"
41 #include "lldb/Host/HostThread.h"
42 #include "lldb/Host/ProcessRunLock.h"
43 #include "lldb/Interpreter/Options.h"
44 #include "lldb/Target/ExecutionContextScope.h"
45 #include "lldb/Target/InstrumentationRuntime.h"
46 #include "lldb/Target/Memory.h"
47 #include "lldb/Target/ProcessInfo.h"
48 #include "lldb/Target/ProcessLaunchInfo.h"
49 #include "lldb/Target/QueueList.h"
50 #include "lldb/Target/ThreadList.h"
51 #include "lldb/Utility/Error.h"
52 #include "lldb/Utility/NameMatches.h"
53 #include "lldb/lldb-private.h"
55 #include "llvm/ADT/ArrayRef.h"
57 namespace lldb_private {
59 template <typename B, typename S> struct Range;
61 //----------------------------------------------------------------------
63 //----------------------------------------------------------------------
64 class ProcessProperties : public Properties {
66 // Pass nullptr for "process" if the ProcessProperties are to be the global
68 ProcessProperties(lldb_private::Process *process);
70 ~ProcessProperties() override;
72 bool GetDisableMemoryCache() const;
74 uint64_t GetMemoryCacheLineSize() const;
76 Args GetExtraStartupCommands() const;
78 void SetExtraStartupCommands(const Args &args);
80 FileSpec GetPythonOSPluginPath() const;
82 void SetPythonOSPluginPath(const FileSpec &file);
84 bool GetIgnoreBreakpointsInExpressions() const;
86 void SetIgnoreBreakpointsInExpressions(bool ignore);
88 bool GetUnwindOnErrorInExpressions() const;
90 void SetUnwindOnErrorInExpressions(bool ignore);
92 bool GetStopOnSharedLibraryEvents() const;
94 void SetStopOnSharedLibraryEvents(bool stop);
96 bool GetDetachKeepsStopped() const;
98 void SetDetachKeepsStopped(bool keep_stopped);
100 bool GetWarningsOptimization() const;
103 static void OptionValueChangedCallback(void *baton,
104 OptionValue *option_value);
106 Process *m_process; // Can be nullptr for global ProcessProperties
109 typedef std::shared_ptr<ProcessProperties> ProcessPropertiesSP;
111 //----------------------------------------------------------------------
112 // ProcessInstanceInfo
114 // Describes an existing process and any discoverable information that
115 // pertains to that process.
116 //----------------------------------------------------------------------
117 class ProcessInstanceInfo : public ProcessInfo {
119 ProcessInstanceInfo()
120 : ProcessInfo(), m_euid(UINT32_MAX), m_egid(UINT32_MAX),
121 m_parent_pid(LLDB_INVALID_PROCESS_ID) {}
123 ProcessInstanceInfo(const char *name, const ArchSpec &arch, lldb::pid_t pid)
124 : ProcessInfo(name, arch, pid), m_euid(UINT32_MAX), m_egid(UINT32_MAX),
125 m_parent_pid(LLDB_INVALID_PROCESS_ID) {}
128 ProcessInfo::Clear();
131 m_parent_pid = LLDB_INVALID_PROCESS_ID;
134 uint32_t GetEffectiveUserID() const { return m_euid; }
136 uint32_t GetEffectiveGroupID() const { return m_egid; }
138 bool EffectiveUserIDIsValid() const { return m_euid != UINT32_MAX; }
140 bool EffectiveGroupIDIsValid() const { return m_egid != UINT32_MAX; }
142 void SetEffectiveUserID(uint32_t uid) { m_euid = uid; }
144 void SetEffectiveGroupID(uint32_t gid) { m_egid = gid; }
146 lldb::pid_t GetParentProcessID() const { return m_parent_pid; }
148 void SetParentProcessID(lldb::pid_t pid) { m_parent_pid = pid; }
150 bool ParentProcessIDIsValid() const {
151 return m_parent_pid != LLDB_INVALID_PROCESS_ID;
154 void Dump(Stream &s, Platform *platform) const;
156 static void DumpTableHeader(Stream &s, Platform *platform, bool show_args,
159 void DumpAsTableRow(Stream &s, Platform *platform, bool show_args,
165 lldb::pid_t m_parent_pid;
168 //----------------------------------------------------------------------
171 // Describes any information that is required to attach to a process.
172 //----------------------------------------------------------------------
174 class ProcessAttachInfo : public ProcessInstanceInfo {
177 : ProcessInstanceInfo(), m_listener_sp(), m_hijack_listener_sp(),
178 m_plugin_name(), m_resume_count(0), m_wait_for_launch(false),
179 m_ignore_existing(true), m_continue_once_attached(false),
180 m_detach_on_error(true), m_async(false) {}
182 ProcessAttachInfo(const ProcessLaunchInfo &launch_info)
183 : ProcessInstanceInfo(), m_listener_sp(), m_hijack_listener_sp(),
184 m_plugin_name(), m_resume_count(0), m_wait_for_launch(false),
185 m_ignore_existing(true), m_continue_once_attached(false),
186 m_detach_on_error(true), m_async(false) {
187 ProcessInfo::operator=(launch_info);
188 SetProcessPluginName(launch_info.GetProcessPluginName());
189 SetResumeCount(launch_info.GetResumeCount());
190 SetListener(launch_info.GetListener());
191 SetHijackListener(launch_info.GetHijackListener());
192 m_detach_on_error = launch_info.GetDetachOnError();
195 bool GetWaitForLaunch() const { return m_wait_for_launch; }
197 void SetWaitForLaunch(bool b) { m_wait_for_launch = b; }
199 bool GetAsync() const { return m_async; }
201 void SetAsync(bool b) { m_async = b; }
203 bool GetIgnoreExisting() const { return m_ignore_existing; }
205 void SetIgnoreExisting(bool b) { m_ignore_existing = b; }
207 bool GetContinueOnceAttached() const { return m_continue_once_attached; }
209 void SetContinueOnceAttached(bool b) { m_continue_once_attached = b; }
211 uint32_t GetResumeCount() const { return m_resume_count; }
213 void SetResumeCount(uint32_t c) { m_resume_count = c; }
215 const char *GetProcessPluginName() const {
216 return (m_plugin_name.empty() ? nullptr : m_plugin_name.c_str());
219 void SetProcessPluginName(llvm::StringRef plugin) { m_plugin_name = plugin; }
222 ProcessInstanceInfo::Clear();
223 m_plugin_name.clear();
225 m_wait_for_launch = false;
226 m_ignore_existing = true;
227 m_continue_once_attached = false;
230 bool ProcessInfoSpecified() const {
231 if (GetExecutableFile())
233 if (GetProcessID() != LLDB_INVALID_PROCESS_ID)
235 if (GetParentProcessID() != LLDB_INVALID_PROCESS_ID)
240 lldb::ListenerSP GetHijackListener() const { return m_hijack_listener_sp; }
242 void SetHijackListener(const lldb::ListenerSP &listener_sp) {
243 m_hijack_listener_sp = listener_sp;
246 bool GetDetachOnError() const { return m_detach_on_error; }
248 void SetDetachOnError(bool enable) { m_detach_on_error = enable; }
250 // Get and set the actual listener that will be used for the process events
251 lldb::ListenerSP GetListener() const { return m_listener_sp; }
253 void SetListener(const lldb::ListenerSP &listener_sp) {
254 m_listener_sp = listener_sp;
257 lldb::ListenerSP GetListenerForProcess(Debugger &debugger);
260 lldb::ListenerSP m_listener_sp;
261 lldb::ListenerSP m_hijack_listener_sp;
262 std::string m_plugin_name;
263 uint32_t m_resume_count; // How many times do we resume after launching
264 bool m_wait_for_launch;
265 bool m_ignore_existing;
266 bool m_continue_once_attached; // Supports the use-case scenario of
267 // immediately continuing the process once
269 bool m_detach_on_error; // If we are debugging remotely, instruct the stub to
270 // detach rather than killing the target on error.
271 bool m_async; // Use an async attach where we start the attach and return
272 // immediately (used by GUI programs with --waitfor so they can
273 // call SBProcess::Stop() to cancel attach)
276 class ProcessLaunchCommandOptions : public Options {
278 ProcessLaunchCommandOptions() : Options() {
279 // Keep default values of all options in one place: OptionParsingStarting ()
280 OptionParsingStarting(nullptr);
283 ~ProcessLaunchCommandOptions() override = default;
285 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
286 ExecutionContext *execution_context) override;
288 void OptionParsingStarting(ExecutionContext *execution_context) override {
290 disable_aslr = eLazyBoolCalculate;
293 llvm::ArrayRef<OptionDefinition> GetDefinitions() override;
295 // Instance variables to hold the values for command options.
297 ProcessLaunchInfo launch_info;
298 lldb_private::LazyBool disable_aslr;
301 //----------------------------------------------------------------------
302 // ProcessInstanceInfoMatch
304 // A class to help matching one ProcessInstanceInfo to another.
305 //----------------------------------------------------------------------
307 class ProcessInstanceInfoMatch {
309 ProcessInstanceInfoMatch()
310 : m_match_info(), m_name_match_type(NameMatch::Ignore),
311 m_match_all_users(false) {}
313 ProcessInstanceInfoMatch(const char *process_name,
314 NameMatch process_name_match_type)
315 : m_match_info(), m_name_match_type(process_name_match_type),
316 m_match_all_users(false) {
317 m_match_info.GetExecutableFile().SetFile(process_name, false);
320 ProcessInstanceInfo &GetProcessInfo() { return m_match_info; }
322 const ProcessInstanceInfo &GetProcessInfo() const { return m_match_info; }
324 bool GetMatchAllUsers() const { return m_match_all_users; }
326 void SetMatchAllUsers(bool b) { m_match_all_users = b; }
328 NameMatch GetNameMatchType() const { return m_name_match_type; }
330 void SetNameMatchType(NameMatch name_match_type) {
331 m_name_match_type = name_match_type;
334 bool NameMatches(const char *process_name) const;
336 bool Matches(const ProcessInstanceInfo &proc_info) const;
338 bool MatchAllProcesses() const;
342 ProcessInstanceInfo m_match_info;
343 NameMatch m_name_match_type;
344 bool m_match_all_users;
347 class ProcessInstanceInfoList {
349 ProcessInstanceInfoList() = default;
351 void Clear() { m_infos.clear(); }
353 size_t GetSize() { return m_infos.size(); }
355 void Append(const ProcessInstanceInfo &info) { m_infos.push_back(info); }
357 const char *GetProcessNameAtIndex(size_t idx) {
358 return ((idx < m_infos.size()) ? m_infos[idx].GetName() : nullptr);
361 size_t GetProcessNameLengthAtIndex(size_t idx) {
362 return ((idx < m_infos.size()) ? m_infos[idx].GetNameLength() : 0);
365 lldb::pid_t GetProcessIDAtIndex(size_t idx) {
366 return ((idx < m_infos.size()) ? m_infos[idx].GetProcessID() : 0);
369 bool GetInfoAtIndex(size_t idx, ProcessInstanceInfo &info) {
370 if (idx < m_infos.size()) {
377 // You must ensure "idx" is valid before calling this function
378 const ProcessInstanceInfo &GetProcessInfoAtIndex(size_t idx) const {
379 assert(idx < m_infos.size());
384 typedef std::vector<ProcessInstanceInfo> collection;
388 // This class tracks the Modification state of the process. Things that can
390 // the program are running the program (which will up the StopID) and writing
392 // will up the MemoryID.)
393 // FIXME: Should we also include modification of register states?
396 friend bool operator==(const ProcessModID &lhs, const ProcessModID &rhs);
400 : m_stop_id(0), m_last_natural_stop_id(0), m_resume_id(0), m_memory_id(0),
401 m_last_user_expression_resume(0), m_running_user_expression(false) {}
403 ProcessModID(const ProcessModID &rhs)
404 : m_stop_id(rhs.m_stop_id), m_memory_id(rhs.m_memory_id) {}
406 const ProcessModID &operator=(const ProcessModID &rhs) {
408 m_stop_id = rhs.m_stop_id;
409 m_memory_id = rhs.m_memory_id;
414 ~ProcessModID() = default;
418 if (!IsLastResumeForUserExpression())
419 m_last_natural_stop_id++;
422 void BumpMemoryID() { m_memory_id++; }
424 void BumpResumeID() {
426 if (m_running_user_expression > 0)
427 m_last_user_expression_resume = m_resume_id;
430 uint32_t GetStopID() const { return m_stop_id; }
431 uint32_t GetLastNaturalStopID() const { return m_last_natural_stop_id; }
432 uint32_t GetMemoryID() const { return m_memory_id; }
433 uint32_t GetResumeID() const { return m_resume_id; }
434 uint32_t GetLastUserExpressionResumeID() const {
435 return m_last_user_expression_resume;
438 bool MemoryIDEqual(const ProcessModID &compare) const {
439 return m_memory_id == compare.m_memory_id;
442 bool StopIDEqual(const ProcessModID &compare) const {
443 return m_stop_id == compare.m_stop_id;
446 void SetInvalid() { m_stop_id = UINT32_MAX; }
448 bool IsValid() const { return m_stop_id != UINT32_MAX; }
450 bool IsLastResumeForUserExpression() const {
451 // If we haven't yet resumed the target, then it can't be for a user
453 if (m_resume_id == 0)
456 return m_resume_id == m_last_user_expression_resume;
459 void SetRunningUserExpression(bool on) {
461 m_running_user_expression++;
463 m_running_user_expression--;
466 void SetStopEventForLastNaturalStopID(lldb::EventSP event_sp) {
467 m_last_natural_stop_event = event_sp;
470 lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const {
471 if (stop_id == m_last_natural_stop_id)
472 return m_last_natural_stop_event;
473 return lldb::EventSP();
478 uint32_t m_last_natural_stop_id;
479 uint32_t m_resume_id;
480 uint32_t m_memory_id;
481 uint32_t m_last_user_expression_resume;
482 uint32_t m_running_user_expression;
483 lldb::EventSP m_last_natural_stop_event;
486 inline bool operator==(const ProcessModID &lhs, const ProcessModID &rhs) {
487 if (lhs.StopIDEqual(rhs) && lhs.MemoryIDEqual(rhs))
493 inline bool operator!=(const ProcessModID &lhs, const ProcessModID &rhs) {
494 return (!lhs.StopIDEqual(rhs) || !lhs.MemoryIDEqual(rhs));
497 //----------------------------------------------------------------------
498 /// @class Process Process.h "lldb/Target/Process.h"
499 /// @brief A plug-in interface definition class for debugging a process.
500 //----------------------------------------------------------------------
501 class Process : public std::enable_shared_from_this<Process>,
502 public ProcessProperties,
505 public ExecutionContextScope,
506 public PluginInterface {
507 friend class FunctionCaller; // For WaitForStateChangeEventsPrivate
508 friend class Debugger; // For PopProcessIOHandler and ProcessIOHandlerIsActive
509 friend class DynamicLoader; // For LoadOperatingSystemPlugin
510 friend class ProcessEventData;
511 friend class StopInfo;
513 friend class ThreadList;
516 //------------------------------------------------------------------
517 /// Broadcaster event bits definitions.
518 //------------------------------------------------------------------
520 eBroadcastBitStateChanged = (1 << 0),
521 eBroadcastBitInterrupt = (1 << 1),
522 eBroadcastBitSTDOUT = (1 << 2),
523 eBroadcastBitSTDERR = (1 << 3),
524 eBroadcastBitProfileData = (1 << 4),
525 eBroadcastBitStructuredData = (1 << 5),
529 eBroadcastInternalStateControlStop = (1 << 0),
530 eBroadcastInternalStateControlPause = (1 << 1),
531 eBroadcastInternalStateControlResume = (1 << 2)
534 //------------------------------------------------------------------
535 /// Process warning types.
536 //------------------------------------------------------------------
537 enum Warnings { eWarningsOptimization = 1 };
539 typedef Range<lldb::addr_t, lldb::addr_t> LoadRange;
540 // We use a read/write lock to allow on or more clients to
541 // access the process state while the process is stopped (reader).
542 // We lock the write lock to control access to the process
543 // while it is running (readers, or clients that want the process
544 // stopped can block waiting for the process to stop, or just
545 // try to lock it to see if they can immediately access the stopped
546 // process. If the try read lock fails, then the process is running.
547 typedef ProcessRunLock::ProcessRunLocker StopLocker;
549 // These two functions fill out the Broadcaster interface:
551 static ConstString &GetStaticBroadcasterClass();
553 ConstString &GetBroadcasterClass() const override {
554 return GetStaticBroadcasterClass();
557 //------------------------------------------------------------------
558 /// A notification structure that can be used by clients to listen
559 /// for changes in a process's lifetime.
561 /// @see RegisterNotificationCallbacks (const Notifications&)
562 /// @see UnregisterNotificationCallbacks (const Notifications&)
563 //------------------------------------------------------------------
567 void (*initialize)(void *baton, Process *process);
568 void (*process_state_changed)(void *baton, Process *process,
569 lldb::StateType state);
572 class ProcessEventData : public EventData {
573 friend class Process;
577 ProcessEventData(const lldb::ProcessSP &process, lldb::StateType state);
579 ~ProcessEventData() override;
581 static const ConstString &GetFlavorString();
583 const ConstString &GetFlavor() const override;
585 lldb::ProcessSP GetProcessSP() const { return m_process_wp.lock(); }
587 lldb::StateType GetState() const { return m_state; }
588 bool GetRestarted() const { return m_restarted; }
590 size_t GetNumRestartedReasons() { return m_restarted_reasons.size(); }
592 const char *GetRestartedReasonAtIndex(size_t idx) {
593 return ((idx < m_restarted_reasons.size())
594 ? m_restarted_reasons[idx].c_str()
598 bool GetInterrupted() const { return m_interrupted; }
600 void Dump(Stream *s) const override;
602 void DoOnRemoval(Event *event_ptr) override;
604 static const Process::ProcessEventData *
605 GetEventDataFromEvent(const Event *event_ptr);
607 static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr);
609 static lldb::StateType GetStateFromEvent(const Event *event_ptr);
611 static bool GetRestartedFromEvent(const Event *event_ptr);
613 static size_t GetNumRestartedReasons(const Event *event_ptr);
615 static const char *GetRestartedReasonAtIndex(const Event *event_ptr,
618 static void AddRestartedReason(Event *event_ptr, const char *reason);
620 static void SetRestartedInEvent(Event *event_ptr, bool new_value);
622 static bool GetInterruptedFromEvent(const Event *event_ptr);
624 static void SetInterruptedInEvent(Event *event_ptr, bool new_value);
626 static bool SetUpdateStateOnRemoval(Event *event_ptr);
629 void SetUpdateStateOnRemoval() { m_update_state++; }
631 void SetRestarted(bool new_value) { m_restarted = new_value; }
633 void SetInterrupted(bool new_value) { m_interrupted = new_value; }
635 void AddRestartedReason(const char *reason) {
636 m_restarted_reasons.push_back(reason);
639 lldb::ProcessWP m_process_wp;
640 lldb::StateType m_state;
641 std::vector<std::string> m_restarted_reasons;
642 bool m_restarted; // For "eStateStopped" events, this is true if the target
643 // was automatically restarted.
647 DISALLOW_COPY_AND_ASSIGN(ProcessEventData);
651 //------------------------------------------------------------------
652 /// Construct with a shared pointer to a target, and the Process listener.
653 /// Uses the Host UnixSignalsSP by default.
654 //------------------------------------------------------------------
655 Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp);
657 //------------------------------------------------------------------
658 /// Construct with a shared pointer to a target, the Process listener,
659 /// and the appropriate UnixSignalsSP for the process.
660 //------------------------------------------------------------------
661 Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp,
662 const lldb::UnixSignalsSP &unix_signals_sp);
664 //------------------------------------------------------------------
667 /// The destructor is virtual since this class is designed to be
668 /// inherited from by the plug-in instance.
669 //------------------------------------------------------------------
672 static void SettingsInitialize();
674 static void SettingsTerminate();
676 static const ProcessPropertiesSP &GetGlobalProperties();
678 //------------------------------------------------------------------
679 /// Find a Process plug-in that can debug \a module using the
680 /// currently selected architecture.
682 /// Scans all loaded plug-in interfaces that implement versions of
683 /// the Process plug-in interface and returns the first instance
684 /// that can debug the file.
686 /// @param[in] module_sp
687 /// The module shared pointer that this process will debug.
689 /// @param[in] plugin_name
690 /// If nullptr, select the best plug-in for the binary. If non-nullptr
691 /// then look for a plugin whose PluginInfo's name matches
694 /// @see Process::CanDebug ()
695 //------------------------------------------------------------------
696 static lldb::ProcessSP FindPlugin(lldb::TargetSP target_sp,
697 llvm::StringRef plugin_name,
698 lldb::ListenerSP listener_sp,
699 const FileSpec *crash_file_path);
701 //------------------------------------------------------------------
702 /// Static function that can be used with the \b host function
703 /// Host::StartMonitoringChildProcess ().
705 /// This function can be used by lldb_private::Process subclasses
706 /// when they want to watch for a local process and have its exit
707 /// status automatically set when the host child process exits.
708 /// Subclasses should call Host::StartMonitoringChildProcess ()
710 /// callback = Process::SetHostProcessExitStatus
711 /// pid = Process::GetID()
712 /// monitor_signals = false
713 //------------------------------------------------------------------
715 SetProcessExitStatus(lldb::pid_t pid, // The process ID we want to monitor
717 int signo, // Zero for no signal
718 int status); // Exit value of process if signal is zero
720 lldb::ByteOrder GetByteOrder() const;
722 uint32_t GetAddressByteSize() const;
724 uint32_t GetUniqueID() const { return m_process_unique_id; }
726 //------------------------------------------------------------------
727 /// Check if a plug-in instance can debug the file in \a module.
729 /// Each plug-in is given a chance to say whether it can debug
730 /// the file in \a module. If the Process plug-in instance can
731 /// debug a file on the current system, it should return \b true.
734 /// Returns \b true if this Process plug-in instance can
735 /// debug the executable, \b false otherwise.
736 //------------------------------------------------------------------
737 virtual bool CanDebug(lldb::TargetSP target,
738 bool plugin_specified_by_name) = 0;
740 //------------------------------------------------------------------
741 /// This object is about to be destroyed, do any necessary cleanup.
743 /// Subclasses that override this method should always call this
744 /// superclass method.
745 //------------------------------------------------------------------
746 virtual void Finalize();
748 //------------------------------------------------------------------
749 /// Return whether this object is valid (i.e. has not been finalized.)
752 /// Returns \b true if this Process has not been finalized
753 /// and \b false otherwise.
754 //------------------------------------------------------------------
755 bool IsValid() const { return !m_finalize_called; }
757 //------------------------------------------------------------------
758 /// Return a multi-word command object that can be used to expose
759 /// plug-in specific commands.
761 /// This object will be used to resolve plug-in commands and can be
762 /// triggered by a call to:
764 /// (lldb) process commmand <args>
767 /// A CommandObject which can be one of the concrete subclasses
768 /// of CommandObject like CommandObjectRaw, CommandObjectParsed,
769 /// or CommandObjectMultiword.
770 //------------------------------------------------------------------
771 virtual CommandObject *GetPluginCommandObject() { return nullptr; }
773 //------------------------------------------------------------------
774 /// Launch a new process.
776 /// Launch a new process by spawning a new process using the
777 /// target object's executable module's file as the file to launch.
779 /// This function is not meant to be overridden by Process
780 /// subclasses. It will first call Process::WillLaunch (Module *)
781 /// and if that returns \b true, Process::DoLaunch (Module*,
782 /// char const *[],char const *[],const char *,const char *,
783 /// const char *) will be called to actually do the launching. If
784 /// DoLaunch returns \b true, then Process::DidLaunch() will be
787 /// @param[in] launch_info
788 /// Details regarding the environment, STDIN/STDOUT/STDERR
789 /// redirection, working path, etc. related to the requested launch.
792 /// An error object. Call GetID() to get the process ID if
793 /// the error object is success.
794 //------------------------------------------------------------------
795 virtual Error Launch(ProcessLaunchInfo &launch_info);
797 virtual Error LoadCore();
799 virtual Error DoLoadCore() {
801 error.SetErrorStringWithFormat(
802 "error: %s does not support loading core files.",
803 GetPluginName().GetCString());
807 //------------------------------------------------------------------
808 /// Get the dynamic loader plug-in for this process.
810 /// The default action is to let the DynamicLoader plug-ins check
811 /// the main executable and the DynamicLoader will select itself
812 /// automatically. Subclasses can override this if inspecting the
813 /// executable is not desired, or if Process subclasses can only
814 /// use a specific DynamicLoader plug-in.
815 //------------------------------------------------------------------
816 virtual DynamicLoader *GetDynamicLoader();
818 //------------------------------------------------------------------
819 // Returns AUXV structure found in many ELF-based environments.
821 // The default action is to return an empty data buffer.
824 // A data buffer containing the contents of the AUXV data.
825 //------------------------------------------------------------------
826 virtual const lldb::DataBufferSP GetAuxvData();
828 //------------------------------------------------------------------
829 /// Sometimes processes know how to retrieve and load shared libraries.
830 /// This is normally done by DynamicLoader plug-ins, but sometimes the
831 /// connection to the process allows retrieving this information. The
832 /// dynamic loader plug-ins can use this function if they can't
833 /// determine the current shared library load state.
836 /// The number of shared libraries that were loaded
837 //------------------------------------------------------------------
838 virtual size_t LoadModules() { return 0; }
840 virtual size_t LoadModules(LoadedModuleInfoList &) { return 0; }
843 virtual JITLoaderList &GetJITLoaders();
846 //------------------------------------------------------------------
847 /// Get the system runtime plug-in for this process.
850 /// Returns a pointer to the SystemRuntime plugin for this Process
851 /// if one is available. Else returns nullptr.
852 //------------------------------------------------------------------
853 virtual SystemRuntime *GetSystemRuntime();
855 //------------------------------------------------------------------
856 /// Attach to an existing process using the process attach info.
858 /// This function is not meant to be overridden by Process
859 /// subclasses. It will first call WillAttach (lldb::pid_t)
860 /// or WillAttach (const char *), and if that returns \b
861 /// true, DoAttach (lldb::pid_t) or DoAttach (const char *) will
862 /// be called to actually do the attach. If DoAttach returns \b
863 /// true, then Process::DidAttach() will be called.
866 /// The process ID that we should attempt to attach to.
869 /// Returns \a pid if attaching was successful, or
870 /// LLDB_INVALID_PROCESS_ID if attaching fails.
871 //------------------------------------------------------------------
872 virtual Error Attach(ProcessAttachInfo &attach_info);
874 //------------------------------------------------------------------
875 /// Attach to a remote system via a URL
878 /// A stream where output intended for the user
879 /// (if the driver has a way to display that) generated during
880 /// the connection. This may be nullptr if no output is needed.A
882 /// @param[in] remote_url
883 /// The URL format that we are connecting to.
886 /// Returns an error object.
887 //------------------------------------------------------------------
888 virtual Error ConnectRemote(Stream *strm, llvm::StringRef remote_url);
890 bool GetShouldDetach() const { return m_should_detach; }
892 void SetShouldDetach(bool b) { m_should_detach = b; }
894 //------------------------------------------------------------------
895 /// Get the image information address for the current process.
897 /// Some runtimes have system functions that can help dynamic
898 /// loaders locate the dynamic loader information needed to observe
899 /// shared libraries being loaded or unloaded. This function is
900 /// in the Process interface (as opposed to the DynamicLoader
901 /// interface) to ensure that remote debugging can take advantage of
902 /// this functionality.
905 /// The address of the dynamic loader information, or
906 /// LLDB_INVALID_ADDRESS if this is not supported by this
908 //------------------------------------------------------------------
909 virtual lldb::addr_t GetImageInfoAddress();
911 //------------------------------------------------------------------
912 /// Called when the process is about to broadcast a public stop.
914 /// There are public and private stops. Private stops are when the
915 /// process is doing things like stepping and the client doesn't
916 /// need to know about starts and stop that implement a thread plan.
917 /// Single stepping over a source line in code might end up being
918 /// implemented by one or more process starts and stops. Public stops
919 /// are when clients will be notified that the process is stopped.
920 /// These events typically trigger UI updates (thread stack frames to
921 /// be displayed, variables to be displayed, and more). This function
922 /// can be overriden and allows process subclasses to do something
923 /// before the eBroadcastBitStateChanged event is sent to public
925 //------------------------------------------------------------------
926 virtual void WillPublicStop() {}
928 //------------------------------------------------------------------
929 /// Register for process and thread notifications.
931 /// Clients can register notification callbacks by filling out a
932 /// Process::Notifications structure and calling this function.
934 /// @param[in] callbacks
935 /// A structure that contains the notification baton and
936 /// callback functions.
938 /// @see Process::Notifications
939 //------------------------------------------------------------------
941 void RegisterNotificationCallbacks(const Process::Notifications &callbacks);
944 //------------------------------------------------------------------
945 /// Unregister for process and thread notifications.
947 /// Clients can unregister notification callbacks by passing a copy of
948 /// the original baton and callbacks in \a callbacks.
950 /// @param[in] callbacks
951 /// A structure that contains the notification baton and
952 /// callback functions.
955 /// Returns \b true if the notification callbacks were
956 /// successfully removed from the process, \b false otherwise.
958 /// @see Process::Notifications
959 //------------------------------------------------------------------
961 bool UnregisterNotificationCallbacks(const Process::Notifications &callbacks);
964 //==================================================================
965 // Built in Process Control functions
966 //==================================================================
967 //------------------------------------------------------------------
968 /// Resumes all of a process's threads as configured using the
969 /// Thread run control functions.
971 /// Threads for a process should be updated with one of the run
972 /// control actions (resume, step, or suspend) that they should take
973 /// when the process is resumed. If no run control action is given
974 /// to a thread it will be resumed by default.
976 /// This function is not meant to be overridden by Process
977 /// subclasses. This function will take care of disabling any
978 /// breakpoints that threads may be stopped at, single stepping, and
979 /// re-enabling breakpoints, and enabling the basic flow control
980 /// that the plug-in instances need not worry about.
982 /// N.B. This function also sets the Write side of the Run Lock,
983 /// which is unset when the corresponding stop event is pulled off
984 /// the Public Event Queue. If you need to resume the process without
985 /// setting the Run Lock, use PrivateResume (though you should only do
986 /// that from inside the Process class.
989 /// Returns an error object.
991 /// @see Thread:Resume()
992 /// @see Thread:Step()
993 /// @see Thread:Suspend()
994 //------------------------------------------------------------------
997 Error ResumeSynchronous(Stream *stream);
999 //------------------------------------------------------------------
1000 /// Halts a running process.
1002 /// This function is not meant to be overridden by Process
1004 /// If the process is successfully halted, a eStateStopped
1005 /// process event with GetInterrupted will be broadcast. If false, we will
1006 /// halt the process with no events generated by the halt.
1008 /// @param[in] clear_thread_plans
1009 /// If true, when the process stops, clear all thread plans.
1011 /// @param[in] use_run_lock
1012 /// Whether to release the run lock after the stop.
1015 /// Returns an error object. If the error is empty, the process is
1017 /// otherwise the halt has failed.
1018 //------------------------------------------------------------------
1019 Error Halt(bool clear_thread_plans = false, bool use_run_lock = true);
1021 //------------------------------------------------------------------
1022 /// Detaches from a running or stopped process.
1024 /// This function is not meant to be overridden by Process
1027 /// @param[in] keep_stopped
1028 /// If true, don't resume the process on detach.
1031 /// Returns an error object.
1032 //------------------------------------------------------------------
1033 Error Detach(bool keep_stopped);
1035 //------------------------------------------------------------------
1036 /// Kills the process and shuts down all threads that were spawned
1037 /// to track and monitor the process.
1039 /// This function is not meant to be overridden by Process
1042 /// @param[in] force_kill
1043 /// Whether lldb should force a kill (instead of a detach) from
1044 /// the inferior process. Normally if lldb launched a binary and
1045 /// Destory is called, lldb kills it. If lldb attached to a
1046 /// running process and Destory is called, lldb detaches. If
1047 /// this behavior needs to be over-ridden, this is the bool that
1051 /// Returns an error object.
1052 //------------------------------------------------------------------
1053 Error Destroy(bool force_kill);
1055 //------------------------------------------------------------------
1056 /// Sends a process a UNIX signal \a signal.
1058 /// This function is not meant to be overridden by Process
1062 /// Returns an error object.
1063 //------------------------------------------------------------------
1064 Error Signal(int signal);
1066 void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp);
1068 const lldb::UnixSignalsSP &GetUnixSignals();
1070 //==================================================================
1071 // Plug-in Process Control Overrides
1072 //==================================================================
1074 //------------------------------------------------------------------
1075 /// Called before attaching to a process.
1077 /// Allow Process plug-ins to execute some code before attaching a
1081 /// Returns an error object.
1082 //------------------------------------------------------------------
1083 virtual Error WillAttachToProcessWithID(lldb::pid_t pid) { return Error(); }
1085 //------------------------------------------------------------------
1086 /// Called before attaching to a process.
1088 /// Allow Process plug-ins to execute some code before attaching a
1092 /// Returns an error object.
1093 //------------------------------------------------------------------
1094 virtual Error WillAttachToProcessWithName(const char *process_name,
1095 bool wait_for_launch) {
1099 //------------------------------------------------------------------
1100 /// Attach to a remote system via a URL
1103 /// A stream where output intended for the user
1104 /// (if the driver has a way to display that) generated during
1105 /// the connection. This may be nullptr if no output is needed.A
1107 /// @param[in] remote_url
1108 /// The URL format that we are connecting to.
1111 /// Returns an error object.
1112 //------------------------------------------------------------------
1113 virtual Error DoConnectRemote(Stream *strm, llvm::StringRef remote_url) {
1115 error.SetErrorString("remote connections are not supported");
1119 //------------------------------------------------------------------
1120 /// Attach to an existing process using a process ID.
1123 /// The process ID that we should attempt to attach to.
1125 /// @param[in] attach_info
1126 /// Information on how to do the attach. For example, GetUserID()
1127 /// will return the uid to attach as.
1130 /// Returns a successful Error attaching was successful, or
1131 /// an appropriate (possibly platform-specific) error code if
1132 /// attaching fails.
1133 /// hanming : need flag
1134 //------------------------------------------------------------------
1135 virtual Error DoAttachToProcessWithID(lldb::pid_t pid,
1136 const ProcessAttachInfo &attach_info) {
1138 error.SetErrorStringWithFormat(
1139 "error: %s does not support attaching to a process by pid",
1140 GetPluginName().GetCString());
1144 //------------------------------------------------------------------
1145 /// Attach to an existing process using a partial process name.
1147 /// @param[in] process_name
1148 /// The name of the process to attach to.
1150 /// @param[in] attach_info
1151 /// Information on how to do the attach. For example, GetUserID()
1152 /// will return the uid to attach as.
1155 /// Returns a successful Error attaching was successful, or
1156 /// an appropriate (possibly platform-specific) error code if
1157 /// attaching fails.
1158 //------------------------------------------------------------------
1160 DoAttachToProcessWithName(const char *process_name,
1161 const ProcessAttachInfo &attach_info) {
1163 error.SetErrorString("attach by name is not supported");
1167 //------------------------------------------------------------------
1168 /// Called after attaching a process.
1170 /// @param[in] process_arch
1171 /// If you can figure out the process architecture after attach, fill it
1174 /// Allow Process plug-ins to execute some code after attaching to
1176 //------------------------------------------------------------------
1177 virtual void DidAttach(ArchSpec &process_arch) { process_arch.Clear(); }
1179 //------------------------------------------------------------------
1180 /// Called after a process re-execs itself.
1182 /// Allow Process plug-ins to execute some code after a process has
1183 /// exec'ed itself. Subclasses typically should override DoDidExec()
1184 /// as the lldb_private::Process class needs to remove its dynamic
1185 /// loader, runtime, ABI and other plug-ins, as well as unload all
1186 /// shared libraries.
1187 //------------------------------------------------------------------
1188 virtual void DidExec();
1190 //------------------------------------------------------------------
1191 /// Subclasses of Process should implement this function if they
1192 /// need to do anything after a process exec's itself.
1193 //------------------------------------------------------------------
1194 virtual void DoDidExec() {}
1196 //------------------------------------------------------------------
1197 /// Called before launching to a process.
1199 /// Allow Process plug-ins to execute some code before launching a
1203 /// Returns an error object.
1204 //------------------------------------------------------------------
1205 virtual Error WillLaunch(Module *module) { return Error(); }
1207 //------------------------------------------------------------------
1208 /// Launch a new process.
1210 /// Launch a new process by spawning a new process using
1211 /// \a exe_module's file as the file to launch. Launch details are
1212 /// provided in \a launch_info.
1214 /// @param[in] exe_module
1215 /// The module from which to extract the file specification and
1218 /// @param[in] launch_info
1219 /// Details (e.g. arguments, stdio redirection, etc.) for the
1220 /// requested launch.
1223 /// An Error instance indicating success or failure of the
1225 //------------------------------------------------------------------
1226 virtual Error DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) {
1228 error.SetErrorStringWithFormat(
1229 "error: %s does not support launching processes",
1230 GetPluginName().GetCString());
1234 //------------------------------------------------------------------
1235 /// Called after launching a process.
1237 /// Allow Process plug-ins to execute some code after launching
1239 //------------------------------------------------------------------
1240 virtual void DidLaunch() {}
1242 //------------------------------------------------------------------
1243 /// Called before resuming to a process.
1245 /// Allow Process plug-ins to execute some code before resuming a
1249 /// Returns an error object.
1250 //------------------------------------------------------------------
1251 virtual Error WillResume() { return Error(); }
1253 //------------------------------------------------------------------
1254 /// Resumes all of a process's threads as configured using the
1255 /// Thread run control functions.
1257 /// Threads for a process should be updated with one of the run
1258 /// control actions (resume, step, or suspend) that they should take
1259 /// when the process is resumed. If no run control action is given
1260 /// to a thread it will be resumed by default.
1263 /// Returns \b true if the process successfully resumes using
1264 /// the thread run control actions, \b false otherwise.
1266 /// @see Thread:Resume()
1267 /// @see Thread:Step()
1268 /// @see Thread:Suspend()
1269 //------------------------------------------------------------------
1270 virtual Error DoResume() {
1272 error.SetErrorStringWithFormat(
1273 "error: %s does not support resuming processes",
1274 GetPluginName().GetCString());
1278 //------------------------------------------------------------------
1279 /// Called after resuming a process.
1281 /// Allow Process plug-ins to execute some code after resuming
1283 //------------------------------------------------------------------
1284 virtual void DidResume() {}
1286 //------------------------------------------------------------------
1287 /// Called before halting to a process.
1289 /// Allow Process plug-ins to execute some code before halting a
1293 /// Returns an error object.
1294 //------------------------------------------------------------------
1295 virtual Error WillHalt() { return Error(); }
1297 //------------------------------------------------------------------
1298 /// Halts a running process.
1300 /// DoHalt must produce one and only one stop StateChanged event if it
1302 /// stops the process. If the stop happens through some natural event (for
1303 /// instance a SIGSTOP), then forwarding that event will do. Otherwise, you
1305 /// generate the event manually. This function is called from the context of
1307 /// private state thread.
1309 /// @param[out] caused_stop
1310 /// If true, then this Halt caused the stop, otherwise, the
1311 /// process was already stopped.
1314 /// Returns \b true if the process successfully halts, \b false
1316 //------------------------------------------------------------------
1317 virtual Error DoHalt(bool &caused_stop) {
1319 error.SetErrorStringWithFormat(
1320 "error: %s does not support halting processes",
1321 GetPluginName().GetCString());
1325 //------------------------------------------------------------------
1326 /// Called after halting a process.
1328 /// Allow Process plug-ins to execute some code after halting
1330 //------------------------------------------------------------------
1331 virtual void DidHalt() {}
1333 //------------------------------------------------------------------
1334 /// Called before detaching from a process.
1336 /// Allow Process plug-ins to execute some code before detaching
1340 /// Returns an error object.
1341 //------------------------------------------------------------------
1342 virtual Error WillDetach() { return Error(); }
1344 //------------------------------------------------------------------
1345 /// Detaches from a running or stopped process.
1348 /// Returns \b true if the process successfully detaches, \b
1349 /// false otherwise.
1350 //------------------------------------------------------------------
1351 virtual Error DoDetach(bool keep_stopped) {
1353 error.SetErrorStringWithFormat(
1354 "error: %s does not support detaching from processes",
1355 GetPluginName().GetCString());
1359 //------------------------------------------------------------------
1360 /// Called after detaching from a process.
1362 /// Allow Process plug-ins to execute some code after detaching
1364 //------------------------------------------------------------------
1365 virtual void DidDetach() {}
1367 virtual bool DetachRequiresHalt() { return false; }
1369 //------------------------------------------------------------------
1370 /// Called before sending a signal to a process.
1372 /// Allow Process plug-ins to execute some code before sending a
1373 /// signal to a process.
1376 /// Returns no error if it is safe to proceed with a call to
1377 /// Process::DoSignal(int), otherwise an error describing what
1378 /// prevents the signal from being sent.
1379 //------------------------------------------------------------------
1380 virtual Error WillSignal() { return Error(); }
1382 //------------------------------------------------------------------
1383 /// Sends a process a UNIX signal \a signal.
1386 /// Returns an error object.
1387 //------------------------------------------------------------------
1388 virtual Error DoSignal(int signal) {
1390 error.SetErrorStringWithFormat(
1391 "error: %s does not support sending signals to processes",
1392 GetPluginName().GetCString());
1396 virtual Error WillDestroy() { return Error(); }
1398 virtual Error DoDestroy() = 0;
1400 virtual void DidDestroy() {}
1402 virtual bool DestroyRequiresHalt() { return true; }
1404 //------------------------------------------------------------------
1405 /// Called after sending a signal to a process.
1407 /// Allow Process plug-ins to execute some code after sending a
1408 /// signal to a process.
1409 //------------------------------------------------------------------
1410 virtual void DidSignal() {}
1412 //------------------------------------------------------------------
1413 /// Currently called as part of ShouldStop.
1414 /// FIXME: Should really happen when the target stops before the
1415 /// event is taken from the queue...
1417 /// This callback is called as the event
1418 /// is about to be queued up to allow Process plug-ins to execute
1419 /// some code prior to clients being notified that a process was
1420 /// stopped. Common operations include updating the thread list,
1421 /// invalidating any thread state (registers, stack, etc) prior to
1422 /// letting the notification go out.
1424 //------------------------------------------------------------------
1425 virtual void RefreshStateAfterStop() = 0;
1427 //------------------------------------------------------------------
1428 /// Sometimes the connection to a process can detect the host OS
1429 /// version that the process is running on. The current platform
1430 /// should be checked first in case the platform is connected, but
1431 /// clients can fall back onto this function if the platform fails
1432 /// to identify the host OS version. The platform should be checked
1433 /// first in case you are running a simulator platform that might
1434 /// itself be running natively, but have different heuristics for
1435 /// figuring out which OS is is emulating.
1437 /// @param[out] major
1438 /// The major OS version, or UINT32_MAX if it can't be determined
1440 /// @param[out] minor
1441 /// The minor OS version, or UINT32_MAX if it can't be determined
1443 /// @param[out] update
1444 /// The update OS version, or UINT32_MAX if it can't be determined
1447 /// Returns \b true if the host OS version info was filled in
1448 /// and \b false otherwise.
1449 //------------------------------------------------------------------
1450 virtual bool GetHostOSVersion(uint32_t &major, uint32_t &minor,
1454 update = UINT32_MAX;
1458 //------------------------------------------------------------------
1459 /// Get the target object pointer for this module.
1462 /// A Target object pointer to the target that owns this
1464 //------------------------------------------------------------------
1465 Target &GetTarget() { return *m_target_sp.lock(); }
1467 //------------------------------------------------------------------
1468 /// Get the const target object pointer for this module.
1471 /// A const Target object pointer to the target that owns this
1473 //------------------------------------------------------------------
1474 const Target &GetTarget() const { return *m_target_sp.lock(); }
1476 //------------------------------------------------------------------
1477 /// Flush all data in the process.
1479 /// Flush the memory caches, all threads, and any other cached data
1482 /// This function can be called after a world changing event like
1483 /// adding a new symbol file, or after the process makes a large
1484 /// context switch (from boot ROM to booted into an OS).
1485 //------------------------------------------------------------------
1488 //------------------------------------------------------------------
1489 /// Get accessor for the current process state.
1492 /// The current state of the process.
1494 /// @see lldb::StateType
1495 //------------------------------------------------------------------
1496 lldb::StateType GetState();
1498 lldb::ExpressionResults
1499 RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp,
1500 const EvaluateExpressionOptions &options,
1501 DiagnosticManager &diagnostic_manager);
1503 static const char *ExecutionResultAsCString(lldb::ExpressionResults result);
1505 void GetStatus(Stream &ostrm);
1507 size_t GetThreadStatus(Stream &ostrm, bool only_threads_with_stop_reason,
1508 uint32_t start_frame, uint32_t num_frames,
1509 uint32_t num_frames_with_source,
1512 void SendAsyncInterrupt();
1514 //------------------------------------------------------------------
1515 // Notify this process class that modules got loaded.
1517 // If subclasses override this method, they must call this version
1518 // before doing anything in the subclass version of the function.
1519 //------------------------------------------------------------------
1520 virtual void ModulesDidLoad(ModuleList &module_list);
1522 //------------------------------------------------------------------
1523 /// Retrieve the list of shared libraries that are loaded for this process
1524 /// This method is used on pre-macOS 10.12, pre-iOS 10, pre-tvOS 10,
1525 /// pre-watchOS 3 systems. The following two methods are for newer versions
1528 /// For certain platforms, the time it takes for the DynamicLoader plugin to
1529 /// read all of the shared libraries out of memory over a slow communication
1530 /// channel may be too long. In that instance, the gdb-remote stub may be
1531 /// able to retrieve the necessary information about the solibs out of memory
1532 /// and return a concise summary sufficient for the DynamicLoader plugin.
1534 /// @param [in] image_list_address
1535 /// The address where the table of shared libraries is stored in memory,
1536 /// if that is appropriate for this platform. Else this may be
1537 /// passed as LLDB_INVALID_ADDRESS.
1539 /// @param [in] image_count
1540 /// The number of shared libraries that are present in this process, if
1541 /// that is appropriate for this platofrm Else this may be passed as
1542 /// LLDB_INVALID_ADDRESS.
1545 /// A StructureDataSP object which, if non-empty, will contain the
1546 /// information the DynamicLoader needs to get the initial scan of
1547 /// solibs resolved.
1548 //------------------------------------------------------------------
1549 virtual lldb_private::StructuredData::ObjectSP
1550 GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address,
1551 lldb::addr_t image_count) {
1552 return StructuredData::ObjectSP();
1555 // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1557 // the full list of loaded shared libraries without needing any input.
1558 virtual lldb_private::StructuredData::ObjectSP
1559 GetLoadedDynamicLibrariesInfos() {
1560 return StructuredData::ObjectSP();
1563 // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1565 // information about binaries given their load addresses.
1566 virtual lldb_private::StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos(
1567 const std::vector<lldb::addr_t> &load_addresses) {
1568 return StructuredData::ObjectSP();
1571 //------------------------------------------------------------------
1572 // Get information about the library shared cache, if that exists
1574 // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1576 // information about the library shared cache (a set of standard libraries
1578 // loaded at the same location for all processes on a system) in use.
1579 //------------------------------------------------------------------
1580 virtual lldb_private::StructuredData::ObjectSP GetSharedCacheInfo() {
1581 return StructuredData::ObjectSP();
1584 //------------------------------------------------------------------
1585 /// Print a user-visible warning about a module being built with optimization
1587 /// Prints a async warning message to the user one time per Module
1588 /// where a function is found that was compiled with optimization, per
1592 /// A SymbolContext with eSymbolContextFunction and eSymbolContextModule
1594 //------------------------------------------------------------------
1595 void PrintWarningOptimization(const SymbolContext &sc);
1597 virtual bool GetProcessInfo(ProcessInstanceInfo &info);
1600 //------------------------------------------------------------------
1601 /// Get the exit status for a process.
1604 /// The process's return code, or -1 if the current process
1605 /// state is not eStateExited.
1606 //------------------------------------------------------------------
1607 int GetExitStatus();
1609 //------------------------------------------------------------------
1610 /// Get a textual description of what the process exited.
1613 /// The textual description of why the process exited, or nullptr
1614 /// if there is no description available.
1615 //------------------------------------------------------------------
1616 const char *GetExitDescription();
1618 virtual void DidExit() {}
1620 //------------------------------------------------------------------
1621 /// Get the Modification ID of the process.
1624 /// The modification ID of the process.
1625 //------------------------------------------------------------------
1626 ProcessModID GetModID() const { return m_mod_id; }
1628 const ProcessModID &GetModIDRef() const { return m_mod_id; }
1630 uint32_t GetStopID() const { return m_mod_id.GetStopID(); }
1632 uint32_t GetResumeID() const { return m_mod_id.GetResumeID(); }
1634 uint32_t GetLastUserExpressionResumeID() const {
1635 return m_mod_id.GetLastUserExpressionResumeID();
1638 uint32_t GetLastNaturalStopID() const {
1639 return m_mod_id.GetLastNaturalStopID();
1642 lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const {
1643 return m_mod_id.GetStopEventForStopID(stop_id);
1646 //------------------------------------------------------------------
1647 /// Set accessor for the process exit status (return code).
1649 /// Sometimes a child exits and the exit can be detected by global
1650 /// functions (signal handler for SIGCHLD for example). This
1651 /// accessor allows the exit status to be set from an external
1654 /// Setting this will cause a eStateExited event to be posted to
1655 /// the process event queue.
1657 /// @param[in] exit_status
1658 /// The value for the process's return code.
1660 /// @see lldb::StateType
1661 //------------------------------------------------------------------
1662 virtual bool SetExitStatus(int exit_status, const char *cstr);
1664 //------------------------------------------------------------------
1665 /// Check if a process is still alive.
1668 /// Returns \b true if the process is still valid, \b false
1670 //------------------------------------------------------------------
1671 virtual bool IsAlive();
1673 //------------------------------------------------------------------
1674 /// Before lldb detaches from a process, it warns the user that they are about
1675 /// to lose their debug session.
1676 /// In some cases, this warning doesn't need to be emitted -- for instance,
1677 /// with core file debugging where
1678 /// the user can reconstruct the "state" by simply re-running the debugger on
1682 // true if the user should be warned about detaching from this process.
1683 //------------------------------------------------------------------
1684 virtual bool WarnBeforeDetach() const { return true; }
1686 //------------------------------------------------------------------
1687 /// Actually do the reading of memory from a process.
1689 /// Subclasses must override this function and can return fewer
1690 /// bytes than requested when memory requests are too large. This
1691 /// class will break up the memory requests and keep advancing the
1692 /// arguments along as needed.
1694 /// @param[in] vm_addr
1695 /// A virtual load address that indicates where to start reading
1699 /// The number of bytes to read.
1702 /// A byte buffer that is at least \a size bytes long that
1703 /// will receive the memory bytes.
1706 /// The number of bytes that were actually read into \a buf.
1707 //------------------------------------------------------------------
1708 virtual size_t DoReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1711 //------------------------------------------------------------------
1712 /// Read of memory from a process.
1714 /// This function will read memory from the current process's
1715 /// address space and remove any traps that may have been inserted
1716 /// into the memory.
1718 /// This function is not meant to be overridden by Process
1719 /// subclasses, the subclasses should implement
1720 /// Process::DoReadMemory (lldb::addr_t, size_t, void *).
1722 /// @param[in] vm_addr
1723 /// A virtual load address that indicates where to start reading
1727 /// A byte buffer that is at least \a size bytes long that
1728 /// will receive the memory bytes.
1731 /// The number of bytes to read.
1734 /// The number of bytes that were actually read into \a buf. If
1735 /// the returned number is greater than zero, yet less than \a
1736 /// size, then this function will get called again with \a
1737 /// vm_addr, \a buf, and \a size updated appropriately. Zero is
1738 /// returned to indicate an error.
1739 //------------------------------------------------------------------
1740 virtual size_t ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1743 //------------------------------------------------------------------
1744 /// Read a NULL terminated string from memory
1746 /// This function will read a cache page at a time until a NULL
1747 /// string terminator is found. It will stop reading if an aligned
1748 /// sequence of NULL termination \a type_width bytes is not found
1749 /// before reading \a cstr_max_len bytes. The results are always
1750 /// guaranteed to be NULL terminated, and that no more than
1751 /// (max_bytes - type_width) bytes will be read.
1753 /// @param[in] vm_addr
1754 /// The virtual load address to start the memory read.
1757 /// A character buffer containing at least max_bytes.
1759 /// @param[in] max_bytes
1760 /// The maximum number of bytes to read.
1762 /// @param[in] error
1763 /// The error status of the read operation.
1765 /// @param[in] type_width
1766 /// The size of the null terminator (1 to 4 bytes per
1767 /// character). Defaults to 1.
1770 /// The error status or the number of bytes prior to the null terminator.
1771 //------------------------------------------------------------------
1772 size_t ReadStringFromMemory(lldb::addr_t vm_addr, char *str, size_t max_bytes,
1773 Error &error, size_t type_width = 1);
1775 //------------------------------------------------------------------
1776 /// Read a NULL terminated C string from memory
1778 /// This function will read a cache page at a time until the NULL
1779 /// C string terminator is found. It will stop reading if the NULL
1780 /// termination byte isn't found before reading \a cstr_max_len
1781 /// bytes, and the results are always guaranteed to be NULL
1782 /// terminated (at most cstr_max_len - 1 bytes will be read).
1783 //------------------------------------------------------------------
1784 size_t ReadCStringFromMemory(lldb::addr_t vm_addr, char *cstr,
1785 size_t cstr_max_len, Error &error);
1787 size_t ReadCStringFromMemory(lldb::addr_t vm_addr, std::string &out_str,
1790 size_t ReadMemoryFromInferior(lldb::addr_t vm_addr, void *buf, size_t size,
1793 //------------------------------------------------------------------
1794 /// Reads an unsigned integer of the specified byte size from
1797 /// @param[in] load_addr
1798 /// A load address of the integer to read.
1800 /// @param[in] byte_size
1801 /// The size in byte of the integer to read.
1803 /// @param[in] fail_value
1804 /// The value to return if we fail to read an integer.
1806 /// @param[out] error
1807 /// An error that indicates the success or failure of this
1808 /// operation. If error indicates success (error.Success()),
1809 /// then the value returned can be trusted, otherwise zero
1810 /// will be returned.
1813 /// The unsigned integer that was read from the process memory
1814 /// space. If the integer was smaller than a uint64_t, any
1815 /// unused upper bytes will be zero filled. If the process
1816 /// byte order differs from the host byte order, the integer
1817 /// value will be appropriately byte swapped into host byte
1819 //------------------------------------------------------------------
1820 uint64_t ReadUnsignedIntegerFromMemory(lldb::addr_t load_addr,
1821 size_t byte_size, uint64_t fail_value,
1824 int64_t ReadSignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size,
1825 int64_t fail_value, Error &error);
1827 lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Error &error);
1829 bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
1832 //------------------------------------------------------------------
1833 /// Actually do the writing of memory to a process.
1835 /// @param[in] vm_addr
1836 /// A virtual load address that indicates where to start writing
1840 /// A byte buffer that is at least \a size bytes long that
1841 /// contains the data to write.
1844 /// The number of bytes to write.
1846 /// @param[out] error
1847 /// An error value in case the memory write fails.
1850 /// The number of bytes that were actually written.
1851 //------------------------------------------------------------------
1852 virtual size_t DoWriteMemory(lldb::addr_t vm_addr, const void *buf,
1853 size_t size, Error &error) {
1854 error.SetErrorStringWithFormat(
1855 "error: %s does not support writing to processes",
1856 GetPluginName().GetCString());
1860 //------------------------------------------------------------------
1861 /// Write all or part of a scalar value to memory.
1863 /// The value contained in \a scalar will be swapped to match the
1864 /// byte order of the process that is being debugged. If \a size is
1865 /// less than the size of scalar, the least significant \a size bytes
1866 /// from scalar will be written. If \a size is larger than the byte
1867 /// size of scalar, then the extra space will be padded with zeros
1868 /// and the scalar value will be placed in the least significant
1869 /// bytes in memory.
1871 /// @param[in] vm_addr
1872 /// A virtual load address that indicates where to start writing
1875 /// @param[in] scalar
1876 /// The scalar to write to the debugged process.
1879 /// This value can be smaller or larger than the scalar value
1880 /// itself. If \a size is smaller than the size of \a scalar,
1881 /// the least significant bytes in \a scalar will be used. If
1882 /// \a size is larger than the byte size of \a scalar, then
1883 /// the extra space will be padded with zeros. If \a size is
1884 /// set to UINT32_MAX, then the size of \a scalar will be used.
1886 /// @param[out] error
1887 /// An error value in case the memory write fails.
1890 /// The number of bytes that were actually written.
1891 //------------------------------------------------------------------
1892 size_t WriteScalarToMemory(lldb::addr_t vm_addr, const Scalar &scalar,
1893 size_t size, Error &error);
1895 size_t ReadScalarIntegerFromMemory(lldb::addr_t addr, uint32_t byte_size,
1896 bool is_signed, Scalar &scalar,
1899 //------------------------------------------------------------------
1900 /// Write memory to a process.
1902 /// This function will write memory to the current process's
1903 /// address space and maintain any traps that might be present due
1904 /// to software breakpoints.
1906 /// This function is not meant to be overridden by Process
1907 /// subclasses, the subclasses should implement
1908 /// Process::DoWriteMemory (lldb::addr_t, size_t, void *).
1910 /// @param[in] vm_addr
1911 /// A virtual load address that indicates where to start writing
1915 /// A byte buffer that is at least \a size bytes long that
1916 /// contains the data to write.
1919 /// The number of bytes to write.
1922 /// The number of bytes that were actually written.
1923 //------------------------------------------------------------------
1924 // TODO: change this to take an ArrayRef<uint8_t>
1925 size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1928 //------------------------------------------------------------------
1929 /// Actually allocate memory in the process.
1931 /// This function will allocate memory in the process's address
1932 /// space. This can't rely on the generic function calling mechanism,
1933 /// since that requires this function.
1936 /// The size of the allocation requested.
1939 /// The address of the allocated buffer in the process, or
1940 /// LLDB_INVALID_ADDRESS if the allocation failed.
1941 //------------------------------------------------------------------
1943 virtual lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions,
1945 error.SetErrorStringWithFormat(
1946 "error: %s does not support allocating in the debug process",
1947 GetPluginName().GetCString());
1948 return LLDB_INVALID_ADDRESS;
1951 //------------------------------------------------------------------
1952 /// The public interface to allocating memory in the process.
1954 /// This function will allocate memory in the process's address
1955 /// space. This can't rely on the generic function calling mechanism,
1956 /// since that requires this function.
1959 /// The size of the allocation requested.
1961 /// @param[in] permissions
1962 /// Or together any of the lldb::Permissions bits. The permissions on
1963 /// a given memory allocation can't be changed after allocation. Note
1964 /// that a block that isn't set writable can still be written on from
1966 /// just not by the process itself.
1968 /// @param[in,out] error
1969 /// An error object to fill in if things go wrong.
1971 /// The address of the allocated buffer in the process, or
1972 /// LLDB_INVALID_ADDRESS if the allocation failed.
1973 //------------------------------------------------------------------
1974 lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Error &error);
1976 //------------------------------------------------------------------
1977 /// The public interface to allocating memory in the process, this also
1978 /// clears the allocated memory.
1980 /// This function will allocate memory in the process's address
1981 /// space. This can't rely on the generic function calling mechanism,
1982 /// since that requires this function.
1985 /// The size of the allocation requested.
1987 /// @param[in] permissions
1988 /// Or together any of the lldb::Permissions bits. The permissions on
1989 /// a given memory allocation can't be changed after allocation. Note
1990 /// that a block that isn't set writable can still be written on from
1992 /// just not by the process itself.
1994 /// @param[in/out] error
1995 /// An error object to fill in if things go wrong.
1997 /// The address of the allocated buffer in the process, or
1998 /// LLDB_INVALID_ADDRESS if the allocation failed.
1999 //------------------------------------------------------------------
2001 lldb::addr_t CallocateMemory(size_t size, uint32_t permissions, Error &error);
2003 //------------------------------------------------------------------
2004 /// Resolve dynamically loaded indirect functions.
2006 /// @param[in] address
2007 /// The load address of the indirect function to resolve.
2009 /// @param[out] error
2010 /// An error value in case the resolve fails.
2013 /// The address of the resolved function.
2014 /// LLDB_INVALID_ADDRESS if the resolution failed.
2015 //------------------------------------------------------------------
2016 virtual lldb::addr_t ResolveIndirectFunction(const Address *address,
2019 //------------------------------------------------------------------
2020 /// Locate the memory region that contains load_addr.
2022 /// If load_addr is within the address space the process has mapped
2023 /// range_info will be filled in with the start and end of that range
2024 /// as well as the permissions for that range and range_info.GetMapped
2025 /// will return true.
2027 /// If load_addr is outside any mapped region then range_info will
2028 /// have its start address set to load_addr and the end of the
2029 /// range will indicate the start of the next mapped range or be
2030 /// set to LLDB_INVALID_ADDRESS if there are no valid mapped ranges
2031 /// between load_addr and the end of the process address space.
2033 /// GetMemoryRegionInfo will only return an error if it is
2034 /// unimplemented for the current process.
2036 /// @param[in] load_addr
2037 /// The load address to query the range_info for.
2039 /// @param[out] range_info
2040 /// An range_info value containing the details of the range.
2044 //------------------------------------------------------------------
2045 virtual Error GetMemoryRegionInfo(lldb::addr_t load_addr,
2046 MemoryRegionInfo &range_info) {
2048 error.SetErrorString("Process::GetMemoryRegionInfo() not supported");
2052 //------------------------------------------------------------------
2053 /// Obtain all the mapped memory regions within this process.
2055 /// @param[out] region_list
2056 /// A vector to contain MemoryRegionInfo objects for all mapped
2061 //------------------------------------------------------------------
2063 GetMemoryRegions(std::vector<lldb::MemoryRegionInfoSP> ®ion_list);
2065 virtual Error GetWatchpointSupportInfo(uint32_t &num) {
2068 error.SetErrorString("Process::GetWatchpointSupportInfo() not supported");
2072 virtual Error GetWatchpointSupportInfo(uint32_t &num, bool &after) {
2076 error.SetErrorString("Process::GetWatchpointSupportInfo() not supported");
2080 lldb::ModuleSP ReadModuleFromMemory(const FileSpec &file_spec,
2081 lldb::addr_t header_addr,
2082 size_t size_to_read = 512);
2084 //------------------------------------------------------------------
2085 /// Attempt to get the attributes for a region of memory in the process.
2087 /// It may be possible for the remote debug server to inspect attributes
2088 /// for a region of memory in the process, such as whether there is a
2089 /// valid page of memory at a given address or whether that page is
2090 /// readable/writable/executable by the process.
2092 /// @param[in] load_addr
2093 /// The address of interest in the process.
2095 /// @param[out] permissions
2096 /// If this call returns successfully, this bitmask will have
2097 /// its Permissions bits set to indicate whether the region is
2098 /// readable/writable/executable. If this call fails, the
2099 /// bitmask values are undefined.
2102 /// Returns true if it was able to determine the attributes of the
2103 /// memory region. False if not.
2104 //------------------------------------------------------------------
2105 virtual bool GetLoadAddressPermissions(lldb::addr_t load_addr,
2106 uint32_t &permissions);
2108 //------------------------------------------------------------------
2109 /// Determines whether executing JIT-compiled code in this process
2113 /// True if execution of JIT code is possible; false otherwise.
2114 //------------------------------------------------------------------
2117 //------------------------------------------------------------------
2118 /// Sets whether executing JIT-compiled code in this process
2121 /// @param[in] can_jit
2122 /// True if execution of JIT code is possible; false otherwise.
2123 //------------------------------------------------------------------
2124 void SetCanJIT(bool can_jit);
2126 //------------------------------------------------------------------
2127 /// Determines whether executing function calls using the interpreter
2128 /// is possible for this process.
2131 /// True if possible; false otherwise.
2132 //------------------------------------------------------------------
2133 bool CanInterpretFunctionCalls() { return m_can_interpret_function_calls; }
2135 //------------------------------------------------------------------
2136 /// Sets whether executing function calls using the interpreter
2137 /// is possible for this process.
2139 /// @param[in] can_interpret_function_calls
2140 /// True if possible; false otherwise.
2141 //------------------------------------------------------------------
2142 void SetCanInterpretFunctionCalls(bool can_interpret_function_calls) {
2143 m_can_interpret_function_calls = can_interpret_function_calls;
2146 //------------------------------------------------------------------
2147 /// Sets whether executing code in this process is possible.
2148 /// This could be either through JIT or interpreting.
2150 /// @param[in] can_run_code
2151 /// True if execution of code is possible; false otherwise.
2152 //------------------------------------------------------------------
2153 void SetCanRunCode(bool can_run_code);
2155 //------------------------------------------------------------------
2156 /// Actually deallocate memory in the process.
2158 /// This function will deallocate memory in the process's address
2159 /// space that was allocated with AllocateMemory.
2162 /// A return value from AllocateMemory, pointing to the memory you
2163 /// want to deallocate.
2166 /// \btrue if the memory was deallocated, \bfalse otherwise.
2167 //------------------------------------------------------------------
2168 virtual Error DoDeallocateMemory(lldb::addr_t ptr) {
2170 error.SetErrorStringWithFormat(
2171 "error: %s does not support deallocating in the debug process",
2172 GetPluginName().GetCString());
2176 //------------------------------------------------------------------
2177 /// The public interface to deallocating memory in the process.
2179 /// This function will deallocate memory in the process's address
2180 /// space that was allocated with AllocateMemory.
2183 /// A return value from AllocateMemory, pointing to the memory you
2184 /// want to deallocate.
2187 /// \btrue if the memory was deallocated, \bfalse otherwise.
2188 //------------------------------------------------------------------
2189 Error DeallocateMemory(lldb::addr_t ptr);
2191 //------------------------------------------------------------------
2192 /// Get any available STDOUT.
2194 /// Calling this method is a valid operation only if all of the
2195 /// following conditions are true:
2196 /// 1) The process was launched, and not attached to.
2197 /// 2) The process was not launched with eLaunchFlagDisableSTDIO.
2198 /// 3) The process was launched without supplying a valid file path
2201 /// Note that the implementation will probably need to start a read
2202 /// thread in the background to make sure that the pipe is drained
2203 /// and the STDOUT buffered appropriately, to prevent the process
2204 /// from deadlocking trying to write to a full buffer.
2206 /// Events will be queued indicating that there is STDOUT available
2207 /// that can be retrieved using this function.
2210 /// A buffer that will receive any STDOUT bytes that are
2211 /// currently available.
2213 /// @param[in] buf_size
2214 /// The size in bytes for the buffer \a buf.
2217 /// The number of bytes written into \a buf. If this value is
2218 /// equal to \a buf_size, another call to this function should
2219 /// be made to retrieve more STDOUT data.
2220 //------------------------------------------------------------------
2221 virtual size_t GetSTDOUT(char *buf, size_t buf_size, Error &error);
2223 //------------------------------------------------------------------
2224 /// Get any available STDERR.
2226 /// Calling this method is a valid operation only if all of the
2227 /// following conditions are true:
2228 /// 1) The process was launched, and not attached to.
2229 /// 2) The process was not launched with eLaunchFlagDisableSTDIO.
2230 /// 3) The process was launched without supplying a valid file path
2233 /// Note that the implementation will probably need to start a read
2234 /// thread in the background to make sure that the pipe is drained
2235 /// and the STDERR buffered appropriately, to prevent the process
2236 /// from deadlocking trying to write to a full buffer.
2238 /// Events will be queued indicating that there is STDERR available
2239 /// that can be retrieved using this function.
2242 /// A buffer that will receive any STDERR bytes that are
2243 /// currently available.
2245 /// @param[out] buf_size
2246 /// The size in bytes for the buffer \a buf.
2249 /// The number of bytes written into \a buf. If this value is
2250 /// equal to \a buf_size, another call to this function should
2251 /// be made to retrieve more STDERR data.
2252 //------------------------------------------------------------------
2253 virtual size_t GetSTDERR(char *buf, size_t buf_size, Error &error);
2255 //------------------------------------------------------------------
2256 /// Puts data into this process's STDIN.
2258 /// Calling this method is a valid operation only if all of the
2259 /// following conditions are true:
2260 /// 1) The process was launched, and not attached to.
2261 /// 2) The process was not launched with eLaunchFlagDisableSTDIO.
2262 /// 3) The process was launched without supplying a valid file path
2266 /// A buffer that contains the data to write to the process's STDIN.
2268 /// @param[in] buf_size
2269 /// The size in bytes for the buffer \a buf.
2272 /// The number of bytes written into \a buf. If this value is
2273 /// less than \a buf_size, another call to this function should
2274 /// be made to write the rest of the data.
2275 //------------------------------------------------------------------
2276 virtual size_t PutSTDIN(const char *buf, size_t buf_size, Error &error) {
2277 error.SetErrorString("stdin unsupported");
2281 //------------------------------------------------------------------
2282 /// Get any available profile data.
2285 /// A buffer that will receive any profile data bytes that are
2286 /// currently available.
2288 /// @param[out] buf_size
2289 /// The size in bytes for the buffer \a buf.
2292 /// The number of bytes written into \a buf. If this value is
2293 /// equal to \a buf_size, another call to this function should
2294 /// be made to retrieve more profile data.
2295 //------------------------------------------------------------------
2296 virtual size_t GetAsyncProfileData(char *buf, size_t buf_size, Error &error);
2298 //----------------------------------------------------------------------
2299 // Process Breakpoints
2300 //----------------------------------------------------------------------
2301 size_t GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site);
2303 virtual Error EnableBreakpointSite(BreakpointSite *bp_site) {
2305 error.SetErrorStringWithFormat(
2306 "error: %s does not support enabling breakpoints",
2307 GetPluginName().GetCString());
2311 virtual Error DisableBreakpointSite(BreakpointSite *bp_site) {
2313 error.SetErrorStringWithFormat(
2314 "error: %s does not support disabling breakpoints",
2315 GetPluginName().GetCString());
2319 // This is implemented completely using the lldb::Process API. Subclasses
2320 // don't need to implement this function unless the standard flow of
2321 // read existing opcode, write breakpoint opcode, verify breakpoint opcode
2322 // doesn't work for a specific process plug-in.
2323 virtual Error EnableSoftwareBreakpoint(BreakpointSite *bp_site);
2325 // This is implemented completely using the lldb::Process API. Subclasses
2326 // don't need to implement this function unless the standard flow of
2327 // restoring original opcode in memory and verifying the restored opcode
2328 // doesn't work for a specific process plug-in.
2329 virtual Error DisableSoftwareBreakpoint(BreakpointSite *bp_site);
2331 BreakpointSiteList &GetBreakpointSiteList();
2333 const BreakpointSiteList &GetBreakpointSiteList() const;
2335 void DisableAllBreakpointSites();
2337 Error ClearBreakpointSiteByID(lldb::user_id_t break_id);
2339 lldb::break_id_t CreateBreakpointSite(const lldb::BreakpointLocationSP &owner,
2342 Error DisableBreakpointSiteByID(lldb::user_id_t break_id);
2344 Error EnableBreakpointSiteByID(lldb::user_id_t break_id);
2346 // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove
2347 // themselves from the owner's list of this breakpoint sites.
2348 void RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
2349 lldb::user_id_t owner_loc_id,
2350 lldb::BreakpointSiteSP &bp_site_sp);
2352 //----------------------------------------------------------------------
2353 // Process Watchpoints (optional)
2354 //----------------------------------------------------------------------
2355 virtual Error EnableWatchpoint(Watchpoint *wp, bool notify = true);
2357 virtual Error DisableWatchpoint(Watchpoint *wp, bool notify = true);
2359 //------------------------------------------------------------------
2361 //------------------------------------------------------------------
2362 virtual bool UpdateThreadList(ThreadList &old_thread_list,
2363 ThreadList &new_thread_list) = 0;
2365 void UpdateThreadListIfNeeded();
2367 ThreadList &GetThreadList() { return m_thread_list; }
2369 // When ExtendedBacktraces are requested, the HistoryThreads that are
2370 // created need an owner -- they're saved here in the Process. The
2371 // threads in this list are not iterated over - driver programs need to
2372 // request the extended backtrace calls starting from a root concrete
2373 // thread one by one.
2374 ThreadList &GetExtendedThreadList() { return m_extended_thread_list; }
2376 ThreadList::ThreadIterable Threads() { return m_thread_list.Threads(); }
2378 uint32_t GetNextThreadIndexID(uint64_t thread_id);
2380 lldb::ThreadSP CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context);
2382 // Returns true if an index id has been assigned to a thread.
2383 bool HasAssignedIndexIDToThread(uint64_t sb_thread_id);
2385 // Given a thread_id, it will assign a more reasonable index id for display to
2387 // If the thread_id has previously been assigned, the same index id will be
2389 uint32_t AssignIndexIDToThread(uint64_t thread_id);
2391 //------------------------------------------------------------------
2393 //------------------------------------------------------------------
2395 void UpdateQueueListIfNeeded();
2397 QueueList &GetQueueList() {
2398 UpdateQueueListIfNeeded();
2399 return m_queue_list;
2402 QueueList::QueueIterable Queues() {
2403 UpdateQueueListIfNeeded();
2404 return m_queue_list.Queues();
2407 //------------------------------------------------------------------
2409 //------------------------------------------------------------------
2410 lldb::StateType GetNextEvent(lldb::EventSP &event_sp);
2412 // Returns the process state when it is stopped. If specified, event_sp_ptr
2413 // is set to the event which triggered the stop. If wait_always = false,
2414 // and the process is already stopped, this function returns immediately.
2415 // If the process is hijacked and use_run_lock is true (the default), then
2417 // function releases the run lock after the stop. Setting use_run_lock to
2419 // will avoid this behavior.
2421 WaitForProcessToStop(const Timeout<std::micro> &timeout,
2422 lldb::EventSP *event_sp_ptr = nullptr,
2423 bool wait_always = true,
2424 lldb::ListenerSP hijack_listener = lldb::ListenerSP(),
2425 Stream *stream = nullptr, bool use_run_lock = true);
2427 uint32_t GetIOHandlerID() const { return m_iohandler_sync.GetValue(); }
2429 //--------------------------------------------------------------------------------------
2430 /// Waits for the process state to be running within a given msec timeout.
2432 /// The main purpose of this is to implement an interlock waiting for
2433 /// HandlePrivateEvent
2434 /// to push an IOHandler.
2436 /// @param[in] timeout_msec
2437 /// The maximum time length to wait for the process to transition to the
2438 /// eStateRunning state, specified in milliseconds.
2439 //--------------------------------------------------------------------------------------
2440 void SyncIOHandler(uint32_t iohandler_id, uint64_t timeout_msec);
2442 lldb::StateType GetStateChangedEvents(
2443 lldb::EventSP &event_sp, const Timeout<std::micro> &timeout,
2445 hijack_listener); // Pass an empty ListenerSP to use builtin listener
2447 //--------------------------------------------------------------------------------------
2448 /// Centralize the code that handles and prints descriptions for process state
2451 /// @param[in] event_sp
2452 /// The process state changed event
2454 /// @param[in] stream
2455 /// The output stream to get the state change description
2457 /// @param[in,out] pop_process_io_handler
2458 /// If this value comes in set to \b true, then pop the Process IOHandler
2460 /// Else this variable will be set to \b true or \b false to indicate if
2462 /// needs to have its process IOHandler popped.
2465 /// \b true if the event describes a process state changed event, \b false
2467 //--------------------------------------------------------------------------------------
2468 static bool HandleProcessStateChangedEvent(const lldb::EventSP &event_sp,
2470 bool &pop_process_io_handler);
2472 Event *PeekAtStateChangedEvents();
2474 class ProcessEventHijacker {
2476 ProcessEventHijacker(Process &process, lldb::ListenerSP listener_sp)
2477 : m_process(process) {
2478 m_process.HijackProcessEvents(listener_sp);
2481 ~ProcessEventHijacker() { m_process.RestoreProcessEvents(); }
2487 friend class ProcessEventHijacker;
2488 friend class ProcessProperties;
2489 //------------------------------------------------------------------
2490 /// If you need to ensure that you and only you will hear about some public
2491 /// event, then make a new listener, set to listen to process events, and
2492 /// then call this with that listener. Then you will have to wait on that
2493 /// listener explicitly for events (rather than using the GetNextEvent &
2495 /// calls above. Be sure to call RestoreProcessEvents when you are done.
2497 /// @param[in] listener
2498 /// This is the new listener to whom all process events will be delivered.
2501 /// Returns \b true if the new listener could be installed,
2502 /// \b false otherwise.
2503 //------------------------------------------------------------------
2504 bool HijackProcessEvents(lldb::ListenerSP listener_sp);
2506 //------------------------------------------------------------------
2507 /// Restores the process event broadcasting to its normal state.
2509 //------------------------------------------------------------------
2510 void RestoreProcessEvents();
2512 const lldb::ABISP &GetABI();
2514 OperatingSystem *GetOperatingSystem() { return m_os_ap.get(); }
2516 ArchSpec::StopInfoOverrideCallbackType GetStopInfoOverrideCallback() const {
2517 return m_stop_info_override_callback;
2520 virtual LanguageRuntime *GetLanguageRuntime(lldb::LanguageType language,
2521 bool retry_if_null = true);
2523 virtual CPPLanguageRuntime *GetCPPLanguageRuntime(bool retry_if_null = true);
2525 virtual ObjCLanguageRuntime *
2526 GetObjCLanguageRuntime(bool retry_if_null = true);
2528 bool IsPossibleDynamicValue(ValueObject &in_value);
2530 bool IsRunning() const;
2532 DynamicCheckerFunctions *GetDynamicCheckers() {
2533 return m_dynamic_checkers_ap.get();
2536 void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers);
2538 //------------------------------------------------------------------
2539 /// Call this to set the lldb in the mode where it breaks on new thread
2540 /// creations, and then auto-restarts. This is useful when you are trying
2541 /// to run only one thread, but either that thread or the kernel is creating
2542 /// new threads in the process. If you stop when the thread is created, you
2543 /// can immediately suspend it, and keep executing only the one thread you
2547 /// Returns \b true if we were able to start up the notification
2548 /// \b false otherwise.
2549 //------------------------------------------------------------------
2550 virtual bool StartNoticingNewThreads() { return true; }
2552 //------------------------------------------------------------------
2553 /// Call this to turn off the stop & notice new threads mode.
2556 /// Returns \b true if we were able to start up the notification
2557 /// \b false otherwise.
2558 //------------------------------------------------------------------
2559 virtual bool StopNoticingNewThreads() { return true; }
2561 void SetRunningUserExpression(bool on);
2563 //------------------------------------------------------------------
2564 // lldb::ExecutionContextScope pure virtual functions
2565 //------------------------------------------------------------------
2566 lldb::TargetSP CalculateTarget() override;
2568 lldb::ProcessSP CalculateProcess() override { return shared_from_this(); }
2570 lldb::ThreadSP CalculateThread() override { return lldb::ThreadSP(); }
2572 lldb::StackFrameSP CalculateStackFrame() override {
2573 return lldb::StackFrameSP();
2576 void CalculateExecutionContext(ExecutionContext &exe_ctx) override;
2578 void SetSTDIOFileDescriptor(int file_descriptor);
2580 //------------------------------------------------------------------
2581 // Add a permanent region of memory that should never be read or
2582 // written to. This can be used to ensure that memory reads or writes
2583 // to certain areas of memory never end up being sent to the
2584 // DoReadMemory or DoWriteMemory functions which can improve
2586 //------------------------------------------------------------------
2587 void AddInvalidMemoryRegion(const LoadRange ®ion);
2589 //------------------------------------------------------------------
2590 // Remove a permanent region of memory that should never be read or
2591 // written to that was previously added with AddInvalidMemoryRegion.
2592 //------------------------------------------------------------------
2593 bool RemoveInvalidMemoryRange(const LoadRange ®ion);
2595 //------------------------------------------------------------------
2596 // If the setup code of a thread plan needs to do work that might involve
2597 // calling a function in the target, it should not do that work directly
2598 // in one of the thread plan functions (DidPush/WillResume) because
2599 // such work needs to be handled carefully. Instead, put that work in
2600 // a PreResumeAction callback, and register it with the process. It will
2601 // get done before the actual "DoResume" gets called.
2602 //------------------------------------------------------------------
2604 typedef bool(PreResumeActionCallback)(void *);
2606 void AddPreResumeAction(PreResumeActionCallback callback, void *baton);
2608 bool RunPreResumeActions();
2610 void ClearPreResumeActions();
2612 void ClearPreResumeAction(PreResumeActionCallback callback, void *baton);
2614 ProcessRunLock &GetRunLock();
2616 virtual Error SendEventData(const char *data) {
2617 Error return_error("Sending an event is not supported for this process.");
2618 return return_error;
2621 lldb::ThreadCollectionSP GetHistoryThreads(lldb::addr_t addr);
2623 lldb::InstrumentationRuntimeSP
2624 GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type);
2626 //------------------------------------------------------------------
2627 /// Try to fetch the module specification for a module with the
2628 /// given file name and architecture. Process sub-classes have to
2629 /// override this method if they support platforms where the
2630 /// Platform object can't get the module spec for all module.
2632 /// @param[in] module_file_spec
2633 /// The file name of the module to get specification for.
2636 /// The architecture of the module to get specification for.
2638 /// @param[out] module_spec
2639 /// The fetched module specification if the return value is
2640 /// \b true, unchanged otherwise.
2643 /// Returns \b true if the module spec fetched successfully,
2644 /// \b false otherwise.
2645 //------------------------------------------------------------------
2646 virtual bool GetModuleSpec(const FileSpec &module_file_spec,
2647 const ArchSpec &arch, ModuleSpec &module_spec);
2649 virtual void PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs,
2650 const llvm::Triple &triple) {}
2652 //------------------------------------------------------------------
2653 /// Try to find the load address of a file.
2654 /// The load address is defined as the address of the first memory
2655 /// region what contains data mapped from the specified file.
2658 /// The name of the file whose load address we are looking for
2660 /// @param[out] is_loaded
2661 /// \b True if the file is loaded into the memory and false
2664 /// @param[out] load_addr
2665 /// The load address of the file if it is loaded into the
2666 /// processes address space, LLDB_INVALID_ADDRESS otherwise.
2667 //------------------------------------------------------------------
2668 virtual Error GetFileLoadAddress(const FileSpec &file, bool &is_loaded,
2669 lldb::addr_t &load_addr) {
2670 return Error("Not supported");
2673 size_t AddImageToken(lldb::addr_t image_ptr);
2675 lldb::addr_t GetImagePtrFromToken(size_t token) const;
2677 void ResetImageToken(size_t token);
2679 //------------------------------------------------------------------
2680 /// Find the next branch instruction to set a breakpoint on
2682 /// When instruction stepping through a source line, instead of
2683 /// stepping through each instruction, we can put a breakpoint on
2684 /// the next branch instruction (within the range of instructions
2685 /// we are stepping through) and continue the process to there,
2686 /// yielding significant performance benefits over instruction
2689 /// @param[in] default_stop_addr
2690 /// The address of the instruction where lldb would put a
2691 /// breakpoint normally.
2693 /// @param[in] range_bounds
2694 /// The range which the breakpoint must be contained within.
2695 /// Typically a source line.
2698 /// The address of the next branch instruction, or the end of
2699 /// the range provided in range_bounds. If there are any
2700 /// problems with the disassembly or getting the instructions,
2701 /// the original default_stop_addr will be returned.
2702 //------------------------------------------------------------------
2703 Address AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
2704 AddressRange range_bounds);
2706 //------------------------------------------------------------------
2707 /// Configure asynchronous structured data feature.
2709 /// Each Process type that supports using an asynchronous StructuredData
2710 /// feature should implement this to enable/disable/configure the feature.
2711 /// The default implementation here will always return an error indiciating
2712 /// the feature is unsupported.
2714 /// StructuredDataPlugin implementations will call this to configure
2715 /// a feature that has been reported as being supported.
2717 /// @param[in] type_name
2718 /// The StructuredData type name as previously discovered by
2719 /// the Process-derived instance.
2721 /// @param[in] config
2722 /// Configuration data for the feature being enabled. This config
2723 /// data, which may be null, will be passed along to the feature
2724 /// to process. The feature will dictate whether this is a dictionary,
2725 /// an array or some other object. If the feature needs to be
2726 /// set up properly before it can be enabled, then the config should
2727 /// also take an enable/disable flag.
2730 /// Returns the result of attempting to configure the feature.
2731 //------------------------------------------------------------------
2733 ConfigureStructuredData(const ConstString &type_name,
2734 const StructuredData::ObjectSP &config_sp);
2736 //------------------------------------------------------------------
2737 /// Broadcasts the given structured data object from the given
2740 /// StructuredDataPlugin instances can use this to optionally
2741 /// broadcast any of their data if they want to make it available
2742 /// for clients. The data will come in on the structured data
2743 /// event bit (eBroadcastBitStructuredData).
2745 /// @param[in] object_sp
2746 /// The structured data object to broadcast.
2748 /// @param[in] plugin_sp
2749 /// The plugin that will be reported in the event's plugin
2751 //------------------------------------------------------------------
2752 void BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
2753 const lldb::StructuredDataPluginSP &plugin_sp);
2755 //------------------------------------------------------------------
2756 /// Returns the StructuredDataPlugin associated with a given type
2757 /// name, if there is one.
2759 /// There will only be a plugin for a given StructuredDataType if the
2760 /// debugged process monitor claims that the feature is supported.
2761 /// This is one way to tell whether a feature is available.
2764 /// The plugin if one is available for the specified feature;
2765 /// otherwise, returns an empty shared pointer.
2766 //------------------------------------------------------------------
2767 lldb::StructuredDataPluginSP
2768 GetStructuredDataPlugin(const ConstString &type_name) const;
2770 //------------------------------------------------------------------
2771 /// Starts tracing with the configuration provided in options. To
2772 /// enable tracing on the complete process the thread_id in the
2773 /// options should be set to LLDB_INVALID_THREAD_ID. The API returns
2774 /// a user_id which is needed by other API's that manipulate the
2776 /// The handling of erroneous or unsupported configuration is left
2777 /// to the trace technology implementations in the server, as they
2778 /// could be returned as an error, or rounded to a valid
2779 /// configuration to start tracing. In the later case the
2780 /// GetTraceConfig should supply the actual used trace
2782 //------------------------------------------------------------------
2783 virtual lldb::user_id_t StartTrace(lldb::TraceOptionsSP &options,
2785 error.SetErrorString("Not implemented");
2786 return LLDB_INVALID_UID;
2789 //------------------------------------------------------------------
2790 /// Stops the tracing instance leading to deletion of the trace
2791 /// data. The tracing instance is identified by the user_id which
2792 /// is obtained when tracing was started from the StartTrace.
2793 /// In case tracing of the complete process needs to be stopped
2794 /// the thread_id should be set to LLDB_INVALID_THREAD_ID.
2795 /// In the other case that tracing on an individual thread needs
2796 /// to be stopped a thread_id can be supplied.
2797 //------------------------------------------------------------------
2798 virtual void StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id,
2800 error.SetErrorString("Not implemented");
2803 //------------------------------------------------------------------
2804 /// Provides the trace data as raw bytes. A buffer needs to be
2805 /// supplied to copy the trace data. The exact behavior of this API
2806 /// may vary across trace technology, as some may support partial
2807 /// reading of the trace data from a specified offset while some
2808 /// may not. The thread_id should be used to select a particular
2809 /// thread for trace extraction.
2810 //------------------------------------------------------------------
2811 virtual size_t GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
2812 Error &error, void *buf, size_t size,
2813 size_t offset = 0) {
2814 error.SetErrorString("Not implemented");
2818 //------------------------------------------------------------------
2819 /// Similar API as above except for obtaining meta data
2820 //------------------------------------------------------------------
2821 virtual size_t GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
2822 Error &error, void *buf, size_t size,
2823 size_t offset = 0) {
2824 error.SetErrorString("Not implemented");
2828 //------------------------------------------------------------------
2829 /// API to obtain the trace configuration used by a trace instance.
2830 /// Configurations that may be specific to some trace technology
2831 /// should be stored in the custom parameters. The options are
2832 /// transported to the server, which shall interpret accordingly.
2833 /// The thread_id can be specified in the options to obtain the
2834 /// configuration used by a specific thread. The thread_id specified
2835 /// should also match the uid otherwise an error will be returned.
2836 //------------------------------------------------------------------
2837 virtual void GetTraceConfig(lldb::user_id_t uid, Error &error,
2838 lldb::TraceOptionsSP &options) {
2839 error.SetErrorString("Not implemented");
2844 void SetState(lldb::EventSP &event_sp);
2846 lldb::StateType GetPrivateState();
2848 //------------------------------------------------------------------
2849 /// The "private" side of resuming a process. This doesn't alter the
2850 /// state of m_run_lock, but just causes the process to resume.
2853 /// An Error object describing the success or failure of the resume.
2854 //------------------------------------------------------------------
2855 Error PrivateResume();
2857 //------------------------------------------------------------------
2858 // Called internally
2859 //------------------------------------------------------------------
2860 void CompleteAttach();
2862 //------------------------------------------------------------------
2863 /// Print a user-visible warning one time per Process
2865 /// A facility for printing a warning to the user once per repeat_key.
2867 /// warning_type is from the Process::Warnings enums.
2868 /// repeat_key is a pointer value that will be used to ensure that the
2869 /// warning message is not printed multiple times. For instance, with a
2870 /// warning about a function being optimized, you can pass the CompileUnit
2871 /// pointer to have the warning issued for only the first function in a
2872 /// CU, or the Function pointer to have it issued once for every function,
2873 /// or a Module pointer to have it issued once per Module.
2875 /// Classes outside Process should call a specific PrintWarning method
2876 /// so that the warning strings are all centralized in Process, instead of
2877 /// calling PrintWarning() directly.
2879 /// @param [in] warning_type
2880 /// One of the types defined in Process::Warnings.
2882 /// @param [in] repeat_key
2883 /// A pointer value used to ensure that the warning is only printed once.
2884 /// May be nullptr, indicating that the warning is printed unconditionally
2888 /// printf style format string
2889 //------------------------------------------------------------------
2890 void PrintWarning(uint64_t warning_type, const void *repeat_key,
2891 const char *fmt, ...) __attribute__((format(printf, 4, 5)));
2893 //------------------------------------------------------------------
2894 // NextEventAction provides a way to register an action on the next
2895 // event that is delivered to this process. There is currently only
2896 // one next event action allowed in the process at one time. If a
2897 // new "NextEventAction" is added while one is already present, the
2898 // old action will be discarded (with HandleBeingUnshipped called
2899 // after it is discarded.)
2901 // If you want to resume the process as a result of a resume action,
2902 // call RequestResume, don't call Resume directly.
2903 //------------------------------------------------------------------
2904 class NextEventAction {
2906 typedef enum EventActionResult {
2907 eEventActionSuccess,
2910 } EventActionResult;
2912 NextEventAction(Process *process) : m_process(process) {}
2914 virtual ~NextEventAction() = default;
2916 virtual EventActionResult PerformAction(lldb::EventSP &event_sp) = 0;
2917 virtual void HandleBeingUnshipped() {}
2918 virtual EventActionResult HandleBeingInterrupted() = 0;
2919 virtual const char *GetExitString() = 0;
2920 void RequestResume() { m_process->m_resume_requested = true; }
2926 void SetNextEventAction(Process::NextEventAction *next_event_action) {
2927 if (m_next_event_action_ap.get())
2928 m_next_event_action_ap->HandleBeingUnshipped();
2930 m_next_event_action_ap.reset(next_event_action);
2933 // This is the completer for Attaching:
2934 class AttachCompletionHandler : public NextEventAction {
2936 AttachCompletionHandler(Process *process, uint32_t exec_count);
2938 ~AttachCompletionHandler() override = default;
2940 EventActionResult PerformAction(lldb::EventSP &event_sp) override;
2941 EventActionResult HandleBeingInterrupted() override;
2942 const char *GetExitString() override;
2945 uint32_t m_exec_count;
2946 std::string m_exit_string;
2949 bool PrivateStateThreadIsValid() const {
2950 lldb::StateType state = m_private_state.GetValue();
2951 return state != lldb::eStateInvalid && state != lldb::eStateDetached &&
2952 state != lldb::eStateExited && m_private_state_thread.IsJoinable();
2955 void ForceNextEventDelivery() { m_force_next_event_delivery = true; }
2957 //------------------------------------------------------------------
2958 /// Loads any plugins associated with asynchronous structured data
2959 /// and maps the relevant supported type name to the plugin.
2961 /// Processes can receive asynchronous structured data from the
2962 /// process monitor. This method will load and map any structured
2963 /// data plugins that support the given set of supported type names.
2964 /// Later, if any of these features are enabled, the process monitor
2965 /// is free to generate asynchronous structured data. The data must
2966 /// come in as a single \b StructuredData::Dictionary. That dictionary
2967 /// must have a string field named 'type', with a value that equals
2968 /// the relevant type name string (one of the values in
2969 /// \b supported_type_names).
2971 /// @param[in] supported_type_names
2972 /// An array of zero or more type names. Each must be unique.
2973 /// For each entry in the list, a StructuredDataPlugin will be
2974 /// searched for that supports the structured data type name.
2975 //------------------------------------------------------------------
2976 void MapSupportedStructuredDataPlugins(
2977 const StructuredData::Array &supported_type_names);
2979 //------------------------------------------------------------------
2980 /// Route the incoming structured data dictionary to the right plugin.
2982 /// The incoming structured data must be a dictionary, and it must
2983 /// have a key named 'type' that stores a string value. The string
2984 /// value must be the name of the structured data feature that
2985 /// knows how to handle it.
2987 /// @param[in] object_sp
2988 /// When non-null and pointing to a dictionary, the 'type'
2989 /// key's string value is used to look up the plugin that
2990 /// was registered for that structured data type. It then
2991 /// calls the following method on the StructuredDataPlugin
2995 /// HandleArrivalOfStructuredData(Process &process,
2996 /// const ConstString &type_name,
2997 /// const StructuredData::ObjectSP
3001 /// True if the structured data was routed to a plugin; otherwise,
3003 //------------------------------------------------------------------
3004 bool RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp);
3006 //------------------------------------------------------------------
3008 //------------------------------------------------------------------
3009 typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP>
3010 LanguageRuntimeCollection;
3011 typedef std::unordered_set<const void *> WarningsPointerSet;
3012 typedef std::map<uint64_t, WarningsPointerSet> WarningsCollection;
3014 struct PreResumeCallbackAndBaton {
3015 bool (*callback)(void *);
3017 PreResumeCallbackAndBaton(PreResumeActionCallback in_callback,
3019 : callback(in_callback), baton(in_baton) {}
3020 bool operator== (const PreResumeCallbackAndBaton &rhs) {
3021 return callback == rhs.callback && baton == rhs.baton;
3025 using StructuredDataPluginMap =
3026 std::map<ConstString, lldb::StructuredDataPluginSP>;
3028 //------------------------------------------------------------------
3030 //------------------------------------------------------------------
3031 std::weak_ptr<Target> m_target_sp; ///< The target that owns this process.
3032 ThreadSafeValue<lldb::StateType> m_public_state;
3033 ThreadSafeValue<lldb::StateType>
3034 m_private_state; // The actual state of our process
3035 Broadcaster m_private_state_broadcaster; // This broadcaster feeds state
3036 // changed events into the private
3037 // state thread's listener.
3038 Broadcaster m_private_state_control_broadcaster; // This is the control
3039 // broadcaster, used to
3040 // pause, resume & stop the
3041 // private state thread.
3042 lldb::ListenerSP m_private_state_listener_sp; // This is the listener for the
3043 // private state thread.
3044 HostThread m_private_state_thread; ///< Thread ID for the thread that watches
3045 ///internal state events
3046 ProcessModID m_mod_id; ///< Tracks the state of the process over stops and
3047 ///other alterations.
3048 uint32_t m_process_unique_id; ///< Each lldb_private::Process class that is
3049 ///created gets a unique integer ID that
3050 ///increments with each new instance
3051 uint32_t m_thread_index_id; ///< Each thread is created with a 1 based index
3052 ///that won't get re-used.
3053 std::map<uint64_t, uint32_t> m_thread_id_to_index_id_map;
3054 int m_exit_status; ///< The exit status of the process, or -1 if not set.
3055 std::string m_exit_string; ///< A textual description of why a process exited.
3056 std::mutex m_exit_status_mutex; ///< Mutex so m_exit_status m_exit_string can
3057 ///be safely accessed from multiple threads
3058 std::recursive_mutex m_thread_mutex;
3059 ThreadList m_thread_list_real; ///< The threads for this process as are known
3060 ///to the protocol we are debugging with
3061 ThreadList m_thread_list; ///< The threads for this process as the user will
3062 ///see them. This is usually the same as
3063 ///< m_thread_list_real, but might be different if there is an OS plug-in
3064 ///creating memory threads
3065 ThreadList m_extended_thread_list; ///< Owner for extended threads that may be
3066 ///generated, cleared on natural stops
3067 uint32_t m_extended_thread_stop_id; ///< The natural stop id when
3068 ///extended_thread_list was last updated
3070 m_queue_list; ///< The list of libdispatch queues at a given stop point
3071 uint32_t m_queue_list_stop_id; ///< The natural stop id when queue list was
3073 std::vector<Notifications> m_notifications; ///< The list of notifications
3074 ///that this process can deliver.
3075 std::vector<lldb::addr_t> m_image_tokens;
3076 lldb::ListenerSP m_listener_sp; ///< Shared pointer to the listener used for
3077 ///public events. Can not be empty.
3078 BreakpointSiteList m_breakpoint_site_list; ///< This is the list of breakpoint
3079 ///locations we intend to insert in
3081 lldb::DynamicLoaderUP m_dyld_ap;
3082 lldb::JITLoaderListUP m_jit_loaders_ap;
3083 lldb::DynamicCheckerFunctionsUP m_dynamic_checkers_ap; ///< The functions used
3084 ///by the expression
3085 ///parser to validate
3088 lldb::OperatingSystemUP m_os_ap;
3089 lldb::SystemRuntimeUP m_system_runtime_ap;
3091 m_unix_signals_sp; /// This is the current signal set for this process.
3092 lldb::ABISP m_abi_sp;
3093 lldb::IOHandlerSP m_process_input_reader;
3094 Communication m_stdio_communication;
3095 std::recursive_mutex m_stdio_communication_mutex;
3096 bool m_stdin_forward; /// Remember if stdin must be forwarded to remote debug
3098 std::string m_stdout_data;
3099 std::string m_stderr_data;
3100 std::recursive_mutex m_profile_data_comm_mutex;
3101 std::vector<std::string> m_profile_data;
3102 Predicate<uint32_t> m_iohandler_sync;
3103 MemoryCache m_memory_cache;
3104 AllocatedMemoryCache m_allocated_memory_cache;
3105 bool m_should_detach; /// Should we detach if the process object goes away
3106 /// with an explicit call to Kill or Detach?
3107 LanguageRuntimeCollection m_language_runtimes;
3108 InstrumentationRuntimeCollection m_instrumentation_runtimes;
3109 std::unique_ptr<NextEventAction> m_next_event_action_ap;
3110 std::vector<PreResumeCallbackAndBaton> m_pre_resume_actions;
3111 ProcessRunLock m_public_run_lock;
3112 ProcessRunLock m_private_run_lock;
3113 ArchSpec::StopInfoOverrideCallbackType m_stop_info_override_callback;
3114 bool m_currently_handling_do_on_removals;
3115 bool m_resume_requested; // If m_currently_handling_event or
3116 // m_currently_handling_do_on_removals are true,
3117 // Resume will only request a resume, using this flag
3119 bool m_finalizing; // This is set at the beginning of Process::Finalize() to
3120 // stop functions from looking up or creating things during
3122 bool m_finalize_called; // This is set at the end of Process::Finalize()
3123 bool m_clear_thread_plans_on_stop;
3124 bool m_force_next_event_delivery;
3125 lldb::StateType m_last_broadcast_state; /// This helps with the Public event
3127 /// ShouldBroadcastEvent.
3128 std::map<lldb::addr_t, lldb::addr_t> m_resolved_indirect_addresses;
3129 bool m_destroy_in_process;
3130 bool m_can_interpret_function_calls; // Some targets, e.g the OSX kernel,
3131 // don't support the ability to modify
3133 WarningsCollection m_warnings_issued; // A set of object pointers which have
3134 // already had warnings printed
3135 std::mutex m_run_thread_plan_lock;
3136 StructuredDataPluginMap m_structured_data_plugin_map;
3138 enum { eCanJITDontKnow = 0, eCanJITYes, eCanJITNo } m_can_jit;
3140 size_t RemoveBreakpointOpcodesFromBuffer(lldb::addr_t addr, size_t size,
3141 uint8_t *buf) const;
3143 void SynchronouslyNotifyStateChanged(lldb::StateType state);
3145 void SetPublicState(lldb::StateType new_state, bool restarted);
3147 void SetPrivateState(lldb::StateType state);
3149 bool StartPrivateStateThread(bool is_secondary_thread = false);
3151 void StopPrivateStateThread();
3153 void PausePrivateStateThread();
3155 void ResumePrivateStateThread();
3158 struct PrivateStateThreadArgs {
3159 PrivateStateThreadArgs(Process *p, bool s)
3160 : process(p), is_secondary_thread(s){};
3162 bool is_secondary_thread;
3165 // arg is a pointer to a new'ed PrivateStateThreadArgs structure.
3166 // PrivateStateThread will free it for you.
3167 static lldb::thread_result_t PrivateStateThread(void *arg);
3169 // The starts up the private state thread that will watch for events from the
3171 // Pass true for is_secondary_thread in the case where you have to temporarily
3173 // secondary state thread to handle events from a hand-called function on the
3175 // private state thread.
3177 lldb::thread_result_t RunPrivateStateThread(bool is_secondary_thread);
3180 void HandlePrivateEvent(lldb::EventSP &event_sp);
3182 Error HaltPrivate();
3184 lldb::StateType WaitForProcessStopPrivate(lldb::EventSP &event_sp,
3185 const Timeout<std::micro> &timeout);
3187 // This waits for both the state change broadcaster, and the control
3189 // If control_only, it only waits for the control broadcaster.
3191 bool GetEventsPrivate(lldb::EventSP &event_sp,
3192 const Timeout<std::micro> &timeout, bool control_only);
3195 GetStateChangedEventsPrivate(lldb::EventSP &event_sp,
3196 const Timeout<std::micro> &timeout);
3198 size_t WriteMemoryPrivate(lldb::addr_t addr, const void *buf, size_t size,
3201 void AppendSTDOUT(const char *s, size_t len);
3203 void AppendSTDERR(const char *s, size_t len);
3205 void BroadcastAsyncProfileData(const std::string &one_profile_data);
3207 static void STDIOReadThreadBytesReceived(void *baton, const void *src,
3210 bool PushProcessIOHandler();
3212 bool PopProcessIOHandler();
3214 bool ProcessIOHandlerIsActive();
3216 bool ProcessIOHandlerExists() const {
3217 return static_cast<bool>(m_process_input_reader);
3220 Error StopForDestroyOrDetach(lldb::EventSP &exit_event_sp);
3222 virtual Error UpdateAutomaticSignalFiltering();
3224 bool StateChangedIsExternallyHijacked();
3226 void LoadOperatingSystemPlugin(bool flush);
3229 //------------------------------------------------------------------
3230 /// This is the part of the event handling that for a process event.
3231 /// It decides what to do with the event and returns true if the
3232 /// event needs to be propagated to the user, and false otherwise.
3233 /// If the event is not propagated, this call will most likely set
3234 /// the target to executing again.
3235 /// There is only one place where this call should be called,
3236 /// HandlePrivateEvent.
3237 /// Don't call it from anywhere else...
3239 /// @param[in] event_ptr
3240 /// This is the event we are handling.
3243 /// Returns \b true if the event should be reported to the
3244 /// user, \b false otherwise.
3245 //------------------------------------------------------------------
3246 bool ShouldBroadcastEvent(Event *event_ptr);
3248 void ControlPrivateStateThread(uint32_t signal);
3250 DISALLOW_COPY_AND_ASSIGN(Process);
3253 } // namespace lldb_private
3255 #endif // liblldb_Process_h_