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/Error.h"
34 #include "lldb/Core/Event.h"
35 #include "lldb/Core/Listener.h"
36 #include "lldb/Core/LoadedModuleInfoList.h"
37 #include "lldb/Core/PluginInterface.h"
38 #include "lldb/Core/StructuredData.h"
39 #include "lldb/Core/ThreadSafeValue.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/lldb-private.h"
53 #include "llvm/ADT/ArrayRef.h"
55 namespace lldb_private {
57 template <typename B, typename S> struct Range;
59 //----------------------------------------------------------------------
61 //----------------------------------------------------------------------
62 class ProcessProperties : public Properties {
64 // Pass nullptr for "process" if the ProcessProperties are to be the global
66 ProcessProperties(lldb_private::Process *process);
68 ~ProcessProperties() override;
70 bool GetDisableMemoryCache() const;
72 uint64_t GetMemoryCacheLineSize() const;
74 Args GetExtraStartupCommands() const;
76 void SetExtraStartupCommands(const Args &args);
78 FileSpec GetPythonOSPluginPath() const;
80 void SetPythonOSPluginPath(const FileSpec &file);
82 bool GetIgnoreBreakpointsInExpressions() const;
84 void SetIgnoreBreakpointsInExpressions(bool ignore);
86 bool GetUnwindOnErrorInExpressions() const;
88 void SetUnwindOnErrorInExpressions(bool ignore);
90 bool GetStopOnSharedLibraryEvents() const;
92 void SetStopOnSharedLibraryEvents(bool stop);
94 bool GetDetachKeepsStopped() const;
96 void SetDetachKeepsStopped(bool keep_stopped);
98 bool GetWarningsOptimization() const;
101 static void OptionValueChangedCallback(void *baton,
102 OptionValue *option_value);
104 Process *m_process; // Can be nullptr for global ProcessProperties
107 typedef std::shared_ptr<ProcessProperties> ProcessPropertiesSP;
109 //----------------------------------------------------------------------
110 // ProcessInstanceInfo
112 // Describes an existing process and any discoverable information that
113 // pertains to that process.
114 //----------------------------------------------------------------------
115 class ProcessInstanceInfo : public ProcessInfo {
117 ProcessInstanceInfo()
118 : ProcessInfo(), m_euid(UINT32_MAX), m_egid(UINT32_MAX),
119 m_parent_pid(LLDB_INVALID_PROCESS_ID) {}
121 ProcessInstanceInfo(const char *name, const ArchSpec &arch, lldb::pid_t pid)
122 : ProcessInfo(name, arch, pid), m_euid(UINT32_MAX), m_egid(UINT32_MAX),
123 m_parent_pid(LLDB_INVALID_PROCESS_ID) {}
126 ProcessInfo::Clear();
129 m_parent_pid = LLDB_INVALID_PROCESS_ID;
132 uint32_t GetEffectiveUserID() const { return m_euid; }
134 uint32_t GetEffectiveGroupID() const { return m_egid; }
136 bool EffectiveUserIDIsValid() const { return m_euid != UINT32_MAX; }
138 bool EffectiveGroupIDIsValid() const { return m_egid != UINT32_MAX; }
140 void SetEffectiveUserID(uint32_t uid) { m_euid = uid; }
142 void SetEffectiveGroupID(uint32_t gid) { m_egid = gid; }
144 lldb::pid_t GetParentProcessID() const { return m_parent_pid; }
146 void SetParentProcessID(lldb::pid_t pid) { m_parent_pid = pid; }
148 bool ParentProcessIDIsValid() const {
149 return m_parent_pid != LLDB_INVALID_PROCESS_ID;
152 void Dump(Stream &s, Platform *platform) const;
154 static void DumpTableHeader(Stream &s, Platform *platform, bool show_args,
157 void DumpAsTableRow(Stream &s, Platform *platform, bool show_args,
163 lldb::pid_t m_parent_pid;
166 //----------------------------------------------------------------------
169 // Describes any information that is required to attach to a process.
170 //----------------------------------------------------------------------
172 class ProcessAttachInfo : public ProcessInstanceInfo {
175 : ProcessInstanceInfo(), m_listener_sp(), m_hijack_listener_sp(),
176 m_plugin_name(), m_resume_count(0), m_wait_for_launch(false),
177 m_ignore_existing(true), m_continue_once_attached(false),
178 m_detach_on_error(true), m_async(false) {}
180 ProcessAttachInfo(const ProcessLaunchInfo &launch_info)
181 : ProcessInstanceInfo(), m_listener_sp(), m_hijack_listener_sp(),
182 m_plugin_name(), m_resume_count(0), m_wait_for_launch(false),
183 m_ignore_existing(true), m_continue_once_attached(false),
184 m_detach_on_error(true), m_async(false) {
185 ProcessInfo::operator=(launch_info);
186 SetProcessPluginName(launch_info.GetProcessPluginName());
187 SetResumeCount(launch_info.GetResumeCount());
188 SetListener(launch_info.GetListener());
189 SetHijackListener(launch_info.GetHijackListener());
190 m_detach_on_error = launch_info.GetDetachOnError();
193 bool GetWaitForLaunch() const { return m_wait_for_launch; }
195 void SetWaitForLaunch(bool b) { m_wait_for_launch = b; }
197 bool GetAsync() const { return m_async; }
199 void SetAsync(bool b) { m_async = b; }
201 bool GetIgnoreExisting() const { return m_ignore_existing; }
203 void SetIgnoreExisting(bool b) { m_ignore_existing = b; }
205 bool GetContinueOnceAttached() const { return m_continue_once_attached; }
207 void SetContinueOnceAttached(bool b) { m_continue_once_attached = b; }
209 uint32_t GetResumeCount() const { return m_resume_count; }
211 void SetResumeCount(uint32_t c) { m_resume_count = c; }
213 const char *GetProcessPluginName() const {
214 return (m_plugin_name.empty() ? nullptr : m_plugin_name.c_str());
217 void SetProcessPluginName(llvm::StringRef plugin) { m_plugin_name = plugin; }
220 ProcessInstanceInfo::Clear();
221 m_plugin_name.clear();
223 m_wait_for_launch = false;
224 m_ignore_existing = true;
225 m_continue_once_attached = false;
228 bool ProcessInfoSpecified() const {
229 if (GetExecutableFile())
231 if (GetProcessID() != LLDB_INVALID_PROCESS_ID)
233 if (GetParentProcessID() != LLDB_INVALID_PROCESS_ID)
238 lldb::ListenerSP GetHijackListener() const { return m_hijack_listener_sp; }
240 void SetHijackListener(const lldb::ListenerSP &listener_sp) {
241 m_hijack_listener_sp = listener_sp;
244 bool GetDetachOnError() const { return m_detach_on_error; }
246 void SetDetachOnError(bool enable) { m_detach_on_error = enable; }
248 // Get and set the actual listener that will be used for the process events
249 lldb::ListenerSP GetListener() const { return m_listener_sp; }
251 void SetListener(const lldb::ListenerSP &listener_sp) {
252 m_listener_sp = listener_sp;
255 lldb::ListenerSP GetListenerForProcess(Debugger &debugger);
258 lldb::ListenerSP m_listener_sp;
259 lldb::ListenerSP m_hijack_listener_sp;
260 std::string m_plugin_name;
261 uint32_t m_resume_count; // How many times do we resume after launching
262 bool m_wait_for_launch;
263 bool m_ignore_existing;
264 bool m_continue_once_attached; // Supports the use-case scenario of
265 // immediately continuing the process once
267 bool m_detach_on_error; // If we are debugging remotely, instruct the stub to
268 // detach rather than killing the target on error.
269 bool m_async; // Use an async attach where we start the attach and return
270 // immediately (used by GUI programs with --waitfor so they can
271 // call SBProcess::Stop() to cancel attach)
274 class ProcessLaunchCommandOptions : public Options {
276 ProcessLaunchCommandOptions() : Options() {
277 // Keep default values of all options in one place: OptionParsingStarting ()
278 OptionParsingStarting(nullptr);
281 ~ProcessLaunchCommandOptions() override = default;
283 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
284 ExecutionContext *execution_context) override;
286 void OptionParsingStarting(ExecutionContext *execution_context) override {
288 disable_aslr = eLazyBoolCalculate;
291 llvm::ArrayRef<OptionDefinition> GetDefinitions() override;
293 // Instance variables to hold the values for command options.
295 ProcessLaunchInfo launch_info;
296 lldb_private::LazyBool disable_aslr;
299 //----------------------------------------------------------------------
300 // ProcessInstanceInfoMatch
302 // A class to help matching one ProcessInstanceInfo to another.
303 //----------------------------------------------------------------------
305 class ProcessInstanceInfoMatch {
307 ProcessInstanceInfoMatch()
308 : m_match_info(), m_name_match_type(eNameMatchIgnore),
309 m_match_all_users(false) {}
311 ProcessInstanceInfoMatch(const char *process_name,
312 NameMatchType process_name_match_type)
313 : m_match_info(), m_name_match_type(process_name_match_type),
314 m_match_all_users(false) {
315 m_match_info.GetExecutableFile().SetFile(process_name, false);
318 ProcessInstanceInfo &GetProcessInfo() { return m_match_info; }
320 const ProcessInstanceInfo &GetProcessInfo() const { return m_match_info; }
322 bool GetMatchAllUsers() const { return m_match_all_users; }
324 void SetMatchAllUsers(bool b) { m_match_all_users = b; }
326 NameMatchType GetNameMatchType() const { return m_name_match_type; }
328 void SetNameMatchType(NameMatchType name_match_type) {
329 m_name_match_type = name_match_type;
332 bool NameMatches(const char *process_name) const;
334 bool Matches(const ProcessInstanceInfo &proc_info) const;
336 bool MatchAllProcesses() const;
340 ProcessInstanceInfo m_match_info;
341 NameMatchType m_name_match_type;
342 bool m_match_all_users;
345 class ProcessInstanceInfoList {
347 ProcessInstanceInfoList() = default;
349 void Clear() { m_infos.clear(); }
351 size_t GetSize() { return m_infos.size(); }
353 void Append(const ProcessInstanceInfo &info) { m_infos.push_back(info); }
355 const char *GetProcessNameAtIndex(size_t idx) {
356 return ((idx < m_infos.size()) ? m_infos[idx].GetName() : nullptr);
359 size_t GetProcessNameLengthAtIndex(size_t idx) {
360 return ((idx < m_infos.size()) ? m_infos[idx].GetNameLength() : 0);
363 lldb::pid_t GetProcessIDAtIndex(size_t idx) {
364 return ((idx < m_infos.size()) ? m_infos[idx].GetProcessID() : 0);
367 bool GetInfoAtIndex(size_t idx, ProcessInstanceInfo &info) {
368 if (idx < m_infos.size()) {
375 // You must ensure "idx" is valid before calling this function
376 const ProcessInstanceInfo &GetProcessInfoAtIndex(size_t idx) const {
377 assert(idx < m_infos.size());
382 typedef std::vector<ProcessInstanceInfo> collection;
386 // This class tracks the Modification state of the process. Things that can
388 // the program are running the program (which will up the StopID) and writing
390 // will up the MemoryID.)
391 // FIXME: Should we also include modification of register states?
394 friend bool operator==(const ProcessModID &lhs, const ProcessModID &rhs);
398 : m_stop_id(0), m_last_natural_stop_id(0), m_resume_id(0), m_memory_id(0),
399 m_last_user_expression_resume(0), m_running_user_expression(false) {}
401 ProcessModID(const ProcessModID &rhs)
402 : m_stop_id(rhs.m_stop_id), m_memory_id(rhs.m_memory_id) {}
404 const ProcessModID &operator=(const ProcessModID &rhs) {
406 m_stop_id = rhs.m_stop_id;
407 m_memory_id = rhs.m_memory_id;
412 ~ProcessModID() = default;
416 if (!IsLastResumeForUserExpression())
417 m_last_natural_stop_id++;
420 void BumpMemoryID() { m_memory_id++; }
422 void BumpResumeID() {
424 if (m_running_user_expression > 0)
425 m_last_user_expression_resume = m_resume_id;
428 uint32_t GetStopID() const { return m_stop_id; }
429 uint32_t GetLastNaturalStopID() const { return m_last_natural_stop_id; }
430 uint32_t GetMemoryID() const { return m_memory_id; }
431 uint32_t GetResumeID() const { return m_resume_id; }
432 uint32_t GetLastUserExpressionResumeID() const {
433 return m_last_user_expression_resume;
436 bool MemoryIDEqual(const ProcessModID &compare) const {
437 return m_memory_id == compare.m_memory_id;
440 bool StopIDEqual(const ProcessModID &compare) const {
441 return m_stop_id == compare.m_stop_id;
444 void SetInvalid() { m_stop_id = UINT32_MAX; }
446 bool IsValid() const { return m_stop_id != UINT32_MAX; }
448 bool IsLastResumeForUserExpression() const {
449 // If we haven't yet resumed the target, then it can't be for a user
451 if (m_resume_id == 0)
454 return m_resume_id == m_last_user_expression_resume;
457 void SetRunningUserExpression(bool on) {
459 m_running_user_expression++;
461 m_running_user_expression--;
464 void SetStopEventForLastNaturalStopID(lldb::EventSP event_sp) {
465 m_last_natural_stop_event = event_sp;
468 lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const {
469 if (stop_id == m_last_natural_stop_id)
470 return m_last_natural_stop_event;
471 return lldb::EventSP();
476 uint32_t m_last_natural_stop_id;
477 uint32_t m_resume_id;
478 uint32_t m_memory_id;
479 uint32_t m_last_user_expression_resume;
480 uint32_t m_running_user_expression;
481 lldb::EventSP m_last_natural_stop_event;
484 inline bool operator==(const ProcessModID &lhs, const ProcessModID &rhs) {
485 if (lhs.StopIDEqual(rhs) && lhs.MemoryIDEqual(rhs))
491 inline bool operator!=(const ProcessModID &lhs, const ProcessModID &rhs) {
492 return (!lhs.StopIDEqual(rhs) || !lhs.MemoryIDEqual(rhs));
495 //----------------------------------------------------------------------
496 /// @class Process Process.h "lldb/Target/Process.h"
497 /// @brief A plug-in interface definition class for debugging a process.
498 //----------------------------------------------------------------------
499 class Process : public std::enable_shared_from_this<Process>,
500 public ProcessProperties,
503 public ExecutionContextScope,
504 public PluginInterface {
505 friend class FunctionCaller; // For WaitForStateChangeEventsPrivate
506 friend class Debugger; // For PopProcessIOHandler and ProcessIOHandlerIsActive
507 friend class ProcessEventData;
508 friend class StopInfo;
510 friend class ThreadList;
513 //------------------------------------------------------------------
514 /// Broadcaster event bits definitions.
515 //------------------------------------------------------------------
517 eBroadcastBitStateChanged = (1 << 0),
518 eBroadcastBitInterrupt = (1 << 1),
519 eBroadcastBitSTDOUT = (1 << 2),
520 eBroadcastBitSTDERR = (1 << 3),
521 eBroadcastBitProfileData = (1 << 4),
522 eBroadcastBitStructuredData = (1 << 5),
526 eBroadcastInternalStateControlStop = (1 << 0),
527 eBroadcastInternalStateControlPause = (1 << 1),
528 eBroadcastInternalStateControlResume = (1 << 2)
531 //------------------------------------------------------------------
532 /// Process warning types.
533 //------------------------------------------------------------------
534 enum Warnings { eWarningsOptimization = 1 };
536 typedef Range<lldb::addr_t, lldb::addr_t> LoadRange;
537 // We use a read/write lock to allow on or more clients to
538 // access the process state while the process is stopped (reader).
539 // We lock the write lock to control access to the process
540 // while it is running (readers, or clients that want the process
541 // stopped can block waiting for the process to stop, or just
542 // try to lock it to see if they can immediately access the stopped
543 // process. If the try read lock fails, then the process is running.
544 typedef ProcessRunLock::ProcessRunLocker StopLocker;
546 // These two functions fill out the Broadcaster interface:
548 static ConstString &GetStaticBroadcasterClass();
550 ConstString &GetBroadcasterClass() const override {
551 return GetStaticBroadcasterClass();
554 //------------------------------------------------------------------
555 /// A notification structure that can be used by clients to listen
556 /// for changes in a process's lifetime.
558 /// @see RegisterNotificationCallbacks (const Notifications&)
559 /// @see UnregisterNotificationCallbacks (const Notifications&)
560 //------------------------------------------------------------------
564 void (*initialize)(void *baton, Process *process);
565 void (*process_state_changed)(void *baton, Process *process,
566 lldb::StateType state);
569 class ProcessEventData : public EventData {
570 friend class Process;
574 ProcessEventData(const lldb::ProcessSP &process, lldb::StateType state);
576 ~ProcessEventData() override;
578 static const ConstString &GetFlavorString();
580 const ConstString &GetFlavor() const override;
582 lldb::ProcessSP GetProcessSP() const { return m_process_wp.lock(); }
584 lldb::StateType GetState() const { return m_state; }
585 bool GetRestarted() const { return m_restarted; }
587 size_t GetNumRestartedReasons() { return m_restarted_reasons.size(); }
589 const char *GetRestartedReasonAtIndex(size_t idx) {
590 return ((idx < m_restarted_reasons.size())
591 ? m_restarted_reasons[idx].c_str()
595 bool GetInterrupted() const { return m_interrupted; }
597 void Dump(Stream *s) const override;
599 void DoOnRemoval(Event *event_ptr) override;
601 static const Process::ProcessEventData *
602 GetEventDataFromEvent(const Event *event_ptr);
604 static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr);
606 static lldb::StateType GetStateFromEvent(const Event *event_ptr);
608 static bool GetRestartedFromEvent(const Event *event_ptr);
610 static size_t GetNumRestartedReasons(const Event *event_ptr);
612 static const char *GetRestartedReasonAtIndex(const Event *event_ptr,
615 static void AddRestartedReason(Event *event_ptr, const char *reason);
617 static void SetRestartedInEvent(Event *event_ptr, bool new_value);
619 static bool GetInterruptedFromEvent(const Event *event_ptr);
621 static void SetInterruptedInEvent(Event *event_ptr, bool new_value);
623 static bool SetUpdateStateOnRemoval(Event *event_ptr);
626 void SetUpdateStateOnRemoval() { m_update_state++; }
628 void SetRestarted(bool new_value) { m_restarted = new_value; }
630 void SetInterrupted(bool new_value) { m_interrupted = new_value; }
632 void AddRestartedReason(const char *reason) {
633 m_restarted_reasons.push_back(reason);
636 lldb::ProcessWP m_process_wp;
637 lldb::StateType m_state;
638 std::vector<std::string> m_restarted_reasons;
639 bool m_restarted; // For "eStateStopped" events, this is true if the target
640 // was automatically restarted.
644 DISALLOW_COPY_AND_ASSIGN(ProcessEventData);
648 //------------------------------------------------------------------
649 /// Construct with a shared pointer to a target, and the Process listener.
650 /// Uses the Host UnixSignalsSP by default.
651 //------------------------------------------------------------------
652 Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp);
654 //------------------------------------------------------------------
655 /// Construct with a shared pointer to a target, the Process listener,
656 /// and the appropriate UnixSignalsSP for the process.
657 //------------------------------------------------------------------
658 Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp,
659 const lldb::UnixSignalsSP &unix_signals_sp);
661 //------------------------------------------------------------------
664 /// The destructor is virtual since this class is designed to be
665 /// inherited from by the plug-in instance.
666 //------------------------------------------------------------------
669 static void SettingsInitialize();
671 static void SettingsTerminate();
673 static const ProcessPropertiesSP &GetGlobalProperties();
675 //------------------------------------------------------------------
676 /// Find a Process plug-in that can debug \a module using the
677 /// currently selected architecture.
679 /// Scans all loaded plug-in interfaces that implement versions of
680 /// the Process plug-in interface and returns the first instance
681 /// that can debug the file.
683 /// @param[in] module_sp
684 /// The module shared pointer that this process will debug.
686 /// @param[in] plugin_name
687 /// If nullptr, select the best plug-in for the binary. If non-nullptr
688 /// then look for a plugin whose PluginInfo's name matches
691 /// @see Process::CanDebug ()
692 //------------------------------------------------------------------
693 static lldb::ProcessSP FindPlugin(lldb::TargetSP target_sp,
694 llvm::StringRef plugin_name,
695 lldb::ListenerSP listener_sp,
696 const FileSpec *crash_file_path);
698 //------------------------------------------------------------------
699 /// Static function that can be used with the \b host function
700 /// Host::StartMonitoringChildProcess ().
702 /// This function can be used by lldb_private::Process subclasses
703 /// when they want to watch for a local process and have its exit
704 /// status automatically set when the host child process exits.
705 /// Subclasses should call Host::StartMonitoringChildProcess ()
707 /// callback = Process::SetHostProcessExitStatus
708 /// pid = Process::GetID()
709 /// monitor_signals = false
710 //------------------------------------------------------------------
712 SetProcessExitStatus(lldb::pid_t pid, // The process ID we want to monitor
714 int signo, // Zero for no signal
715 int status); // Exit value of process if signal is zero
717 lldb::ByteOrder GetByteOrder() const;
719 uint32_t GetAddressByteSize() const;
721 uint32_t GetUniqueID() const { return m_process_unique_id; }
723 //------------------------------------------------------------------
724 /// Check if a plug-in instance can debug the file in \a module.
726 /// Each plug-in is given a chance to say whether it can debug
727 /// the file in \a module. If the Process plug-in instance can
728 /// debug a file on the current system, it should return \b true.
731 /// Returns \b true if this Process plug-in instance can
732 /// debug the executable, \b false otherwise.
733 //------------------------------------------------------------------
734 virtual bool CanDebug(lldb::TargetSP target,
735 bool plugin_specified_by_name) = 0;
737 //------------------------------------------------------------------
738 /// This object is about to be destroyed, do any necessary cleanup.
740 /// Subclasses that override this method should always call this
741 /// superclass method.
742 //------------------------------------------------------------------
743 virtual void Finalize();
745 //------------------------------------------------------------------
746 /// Return whether this object is valid (i.e. has not been finalized.)
749 /// Returns \b true if this Process has not been finalized
750 /// and \b false otherwise.
751 //------------------------------------------------------------------
752 bool IsValid() const { return !m_finalize_called; }
754 //------------------------------------------------------------------
755 /// Return a multi-word command object that can be used to expose
756 /// plug-in specific commands.
758 /// This object will be used to resolve plug-in commands and can be
759 /// triggered by a call to:
761 /// (lldb) process commmand <args>
764 /// A CommandObject which can be one of the concrete subclasses
765 /// of CommandObject like CommandObjectRaw, CommandObjectParsed,
766 /// or CommandObjectMultiword.
767 //------------------------------------------------------------------
768 virtual CommandObject *GetPluginCommandObject() { return nullptr; }
770 //------------------------------------------------------------------
771 /// Launch a new process.
773 /// Launch a new process by spawning a new process using the
774 /// target object's executable module's file as the file to launch.
776 /// This function is not meant to be overridden by Process
777 /// subclasses. It will first call Process::WillLaunch (Module *)
778 /// and if that returns \b true, Process::DoLaunch (Module*,
779 /// char const *[],char const *[],const char *,const char *,
780 /// const char *) will be called to actually do the launching. If
781 /// DoLaunch returns \b true, then Process::DidLaunch() will be
784 /// @param[in] launch_info
785 /// Details regarding the environment, STDIN/STDOUT/STDERR
786 /// redirection, working path, etc. related to the requested launch.
789 /// An error object. Call GetID() to get the process ID if
790 /// the error object is success.
791 //------------------------------------------------------------------
792 virtual Error Launch(ProcessLaunchInfo &launch_info);
794 virtual Error LoadCore();
796 virtual Error DoLoadCore() {
798 error.SetErrorStringWithFormat(
799 "error: %s does not support loading core files.",
800 GetPluginName().GetCString());
804 //------------------------------------------------------------------
805 /// Get the dynamic loader plug-in for this process.
807 /// The default action is to let the DynamicLoader plug-ins check
808 /// the main executable and the DynamicLoader will select itself
809 /// automatically. Subclasses can override this if inspecting the
810 /// executable is not desired, or if Process subclasses can only
811 /// use a specific DynamicLoader plug-in.
812 //------------------------------------------------------------------
813 virtual DynamicLoader *GetDynamicLoader();
815 //------------------------------------------------------------------
816 // Returns AUXV structure found in many ELF-based environments.
818 // The default action is to return an empty data buffer.
821 // A data buffer containing the contents of the AUXV data.
822 //------------------------------------------------------------------
823 virtual const lldb::DataBufferSP GetAuxvData();
825 //------------------------------------------------------------------
826 /// Sometimes processes know how to retrieve and load shared libraries.
827 /// This is normally done by DynamicLoader plug-ins, but sometimes the
828 /// connection to the process allows retrieving this information. The
829 /// dynamic loader plug-ins can use this function if they can't
830 /// determine the current shared library load state.
833 /// The number of shared libraries that were loaded
834 //------------------------------------------------------------------
835 virtual size_t LoadModules() { return 0; }
837 virtual size_t LoadModules(LoadedModuleInfoList &) { return 0; }
840 virtual JITLoaderList &GetJITLoaders();
843 //------------------------------------------------------------------
844 /// Get the system runtime plug-in for this process.
847 /// Returns a pointer to the SystemRuntime plugin for this Process
848 /// if one is available. Else returns nullptr.
849 //------------------------------------------------------------------
850 virtual SystemRuntime *GetSystemRuntime();
852 //------------------------------------------------------------------
853 /// Attach to an existing process using the process attach info.
855 /// This function is not meant to be overridden by Process
856 /// subclasses. It will first call WillAttach (lldb::pid_t)
857 /// or WillAttach (const char *), and if that returns \b
858 /// true, DoAttach (lldb::pid_t) or DoAttach (const char *) will
859 /// be called to actually do the attach. If DoAttach returns \b
860 /// true, then Process::DidAttach() will be called.
863 /// The process ID that we should attempt to attach to.
866 /// Returns \a pid if attaching was successful, or
867 /// LLDB_INVALID_PROCESS_ID if attaching fails.
868 //------------------------------------------------------------------
869 virtual Error Attach(ProcessAttachInfo &attach_info);
871 //------------------------------------------------------------------
872 /// Attach to a remote system via a URL
875 /// A stream where output intended for the user
876 /// (if the driver has a way to display that) generated during
877 /// the connection. This may be nullptr if no output is needed.A
879 /// @param[in] remote_url
880 /// The URL format that we are connecting to.
883 /// Returns an error object.
884 //------------------------------------------------------------------
885 virtual Error ConnectRemote(Stream *strm, llvm::StringRef remote_url);
887 bool GetShouldDetach() const { return m_should_detach; }
889 void SetShouldDetach(bool b) { m_should_detach = b; }
891 //------------------------------------------------------------------
892 /// Get the image information address for the current process.
894 /// Some runtimes have system functions that can help dynamic
895 /// loaders locate the dynamic loader information needed to observe
896 /// shared libraries being loaded or unloaded. This function is
897 /// in the Process interface (as opposed to the DynamicLoader
898 /// interface) to ensure that remote debugging can take advantage of
899 /// this functionality.
902 /// The address of the dynamic loader information, or
903 /// LLDB_INVALID_ADDRESS if this is not supported by this
905 //------------------------------------------------------------------
906 virtual lldb::addr_t GetImageInfoAddress();
908 //------------------------------------------------------------------
909 /// Called when the process is about to broadcast a public stop.
911 /// There are public and private stops. Private stops are when the
912 /// process is doing things like stepping and the client doesn't
913 /// need to know about starts and stop that implement a thread plan.
914 /// Single stepping over a source line in code might end up being
915 /// implemented by one or more process starts and stops. Public stops
916 /// are when clients will be notified that the process is stopped.
917 /// These events typically trigger UI updates (thread stack frames to
918 /// be displayed, variables to be displayed, and more). This function
919 /// can be overriden and allows process subclasses to do something
920 /// before the eBroadcastBitStateChanged event is sent to public
922 //------------------------------------------------------------------
923 virtual void WillPublicStop() {}
925 //------------------------------------------------------------------
926 /// Register for process and thread notifications.
928 /// Clients can register notification callbacks by filling out a
929 /// Process::Notifications structure and calling this function.
931 /// @param[in] callbacks
932 /// A structure that contains the notification baton and
933 /// callback functions.
935 /// @see Process::Notifications
936 //------------------------------------------------------------------
938 void RegisterNotificationCallbacks(const Process::Notifications &callbacks);
941 //------------------------------------------------------------------
942 /// Unregister for process and thread notifications.
944 /// Clients can unregister notification callbacks by passing a copy of
945 /// the original baton and callbacks in \a callbacks.
947 /// @param[in] callbacks
948 /// A structure that contains the notification baton and
949 /// callback functions.
952 /// Returns \b true if the notification callbacks were
953 /// successfully removed from the process, \b false otherwise.
955 /// @see Process::Notifications
956 //------------------------------------------------------------------
958 bool UnregisterNotificationCallbacks(const Process::Notifications &callbacks);
961 //==================================================================
962 // Built in Process Control functions
963 //==================================================================
964 //------------------------------------------------------------------
965 /// Resumes all of a process's threads as configured using the
966 /// Thread run control functions.
968 /// Threads for a process should be updated with one of the run
969 /// control actions (resume, step, or suspend) that they should take
970 /// when the process is resumed. If no run control action is given
971 /// to a thread it will be resumed by default.
973 /// This function is not meant to be overridden by Process
974 /// subclasses. This function will take care of disabling any
975 /// breakpoints that threads may be stopped at, single stepping, and
976 /// re-enabling breakpoints, and enabling the basic flow control
977 /// that the plug-in instances need not worry about.
979 /// N.B. This function also sets the Write side of the Run Lock,
980 /// which is unset when the corresponding stop event is pulled off
981 /// the Public Event Queue. If you need to resume the process without
982 /// setting the Run Lock, use PrivateResume (though you should only do
983 /// that from inside the Process class.
986 /// Returns an error object.
988 /// @see Thread:Resume()
989 /// @see Thread:Step()
990 /// @see Thread:Suspend()
991 //------------------------------------------------------------------
994 Error ResumeSynchronous(Stream *stream);
996 //------------------------------------------------------------------
997 /// Halts a running process.
999 /// This function is not meant to be overridden by Process
1001 /// If the process is successfully halted, a eStateStopped
1002 /// process event with GetInterrupted will be broadcast. If false, we will
1003 /// halt the process with no events generated by the halt.
1005 /// @param[in] clear_thread_plans
1006 /// If true, when the process stops, clear all thread plans.
1008 /// @param[in] use_run_lock
1009 /// Whether to release the run lock after the stop.
1012 /// Returns an error object. If the error is empty, the process is
1014 /// otherwise the halt has failed.
1015 //------------------------------------------------------------------
1016 Error Halt(bool clear_thread_plans = false, bool use_run_lock = true);
1018 //------------------------------------------------------------------
1019 /// Detaches from a running or stopped process.
1021 /// This function is not meant to be overridden by Process
1024 /// @param[in] keep_stopped
1025 /// If true, don't resume the process on detach.
1028 /// Returns an error object.
1029 //------------------------------------------------------------------
1030 Error Detach(bool keep_stopped);
1032 //------------------------------------------------------------------
1033 /// Kills the process and shuts down all threads that were spawned
1034 /// to track and monitor the process.
1036 /// This function is not meant to be overridden by Process
1039 /// @param[in] force_kill
1040 /// Whether lldb should force a kill (instead of a detach) from
1041 /// the inferior process. Normally if lldb launched a binary and
1042 /// Destory is called, lldb kills it. If lldb attached to a
1043 /// running process and Destory is called, lldb detaches. If
1044 /// this behavior needs to be over-ridden, this is the bool that
1048 /// Returns an error object.
1049 //------------------------------------------------------------------
1050 Error Destroy(bool force_kill);
1052 //------------------------------------------------------------------
1053 /// Sends a process a UNIX signal \a signal.
1055 /// This function is not meant to be overridden by Process
1059 /// Returns an error object.
1060 //------------------------------------------------------------------
1061 Error Signal(int signal);
1063 void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp);
1065 const lldb::UnixSignalsSP &GetUnixSignals();
1067 //==================================================================
1068 // Plug-in Process Control Overrides
1069 //==================================================================
1071 //------------------------------------------------------------------
1072 /// Called before attaching to a process.
1074 /// Allow Process plug-ins to execute some code before attaching a
1078 /// Returns an error object.
1079 //------------------------------------------------------------------
1080 virtual Error WillAttachToProcessWithID(lldb::pid_t pid) { return Error(); }
1082 //------------------------------------------------------------------
1083 /// Called before attaching to a process.
1085 /// Allow Process plug-ins to execute some code before attaching a
1089 /// Returns an error object.
1090 //------------------------------------------------------------------
1091 virtual Error WillAttachToProcessWithName(const char *process_name,
1092 bool wait_for_launch) {
1096 //------------------------------------------------------------------
1097 /// Attach to a remote system via a URL
1100 /// A stream where output intended for the user
1101 /// (if the driver has a way to display that) generated during
1102 /// the connection. This may be nullptr if no output is needed.A
1104 /// @param[in] remote_url
1105 /// The URL format that we are connecting to.
1108 /// Returns an error object.
1109 //------------------------------------------------------------------
1110 virtual Error DoConnectRemote(Stream *strm, llvm::StringRef remote_url) {
1112 error.SetErrorString("remote connections are not supported");
1116 //------------------------------------------------------------------
1117 /// Attach to an existing process using a process ID.
1120 /// The process ID that we should attempt to attach to.
1122 /// @param[in] attach_info
1123 /// Information on how to do the attach. For example, GetUserID()
1124 /// will return the uid to attach as.
1127 /// Returns a successful Error attaching was successful, or
1128 /// an appropriate (possibly platform-specific) error code if
1129 /// attaching fails.
1130 /// hanming : need flag
1131 //------------------------------------------------------------------
1132 virtual Error DoAttachToProcessWithID(lldb::pid_t pid,
1133 const ProcessAttachInfo &attach_info) {
1135 error.SetErrorStringWithFormat(
1136 "error: %s does not support attaching to a process by pid",
1137 GetPluginName().GetCString());
1141 //------------------------------------------------------------------
1142 /// Attach to an existing process using a partial process name.
1144 /// @param[in] process_name
1145 /// The name of the process to attach to.
1147 /// @param[in] attach_info
1148 /// Information on how to do the attach. For example, GetUserID()
1149 /// will return the uid to attach as.
1152 /// Returns a successful Error attaching was successful, or
1153 /// an appropriate (possibly platform-specific) error code if
1154 /// attaching fails.
1155 //------------------------------------------------------------------
1157 DoAttachToProcessWithName(const char *process_name,
1158 const ProcessAttachInfo &attach_info) {
1160 error.SetErrorString("attach by name is not supported");
1164 //------------------------------------------------------------------
1165 /// Called after attaching a process.
1167 /// @param[in] process_arch
1168 /// If you can figure out the process architecture after attach, fill it
1171 /// Allow Process plug-ins to execute some code after attaching to
1173 //------------------------------------------------------------------
1174 virtual void DidAttach(ArchSpec &process_arch) { process_arch.Clear(); }
1176 //------------------------------------------------------------------
1177 /// Called after a process re-execs itself.
1179 /// Allow Process plug-ins to execute some code after a process has
1180 /// exec'ed itself. Subclasses typically should override DoDidExec()
1181 /// as the lldb_private::Process class needs to remove its dynamic
1182 /// loader, runtime, ABI and other plug-ins, as well as unload all
1183 /// shared libraries.
1184 //------------------------------------------------------------------
1185 virtual void DidExec();
1187 //------------------------------------------------------------------
1188 /// Subclasses of Process should implement this function if they
1189 /// need to do anything after a process exec's itself.
1190 //------------------------------------------------------------------
1191 virtual void DoDidExec() {}
1193 //------------------------------------------------------------------
1194 /// Called before launching to a process.
1196 /// Allow Process plug-ins to execute some code before launching a
1200 /// Returns an error object.
1201 //------------------------------------------------------------------
1202 virtual Error WillLaunch(Module *module) { return Error(); }
1204 //------------------------------------------------------------------
1205 /// Launch a new process.
1207 /// Launch a new process by spawning a new process using
1208 /// \a exe_module's file as the file to launch. Launch details are
1209 /// provided in \a launch_info.
1211 /// @param[in] exe_module
1212 /// The module from which to extract the file specification and
1215 /// @param[in] launch_info
1216 /// Details (e.g. arguments, stdio redirection, etc.) for the
1217 /// requested launch.
1220 /// An Error instance indicating success or failure of the
1222 //------------------------------------------------------------------
1223 virtual Error DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) {
1225 error.SetErrorStringWithFormat(
1226 "error: %s does not support launching processes",
1227 GetPluginName().GetCString());
1231 //------------------------------------------------------------------
1232 /// Called after launching a process.
1234 /// Allow Process plug-ins to execute some code after launching
1236 //------------------------------------------------------------------
1237 virtual void DidLaunch() {}
1239 //------------------------------------------------------------------
1240 /// Called before resuming to a process.
1242 /// Allow Process plug-ins to execute some code before resuming a
1246 /// Returns an error object.
1247 //------------------------------------------------------------------
1248 virtual Error WillResume() { return Error(); }
1250 //------------------------------------------------------------------
1251 /// Resumes all of a process's threads as configured using the
1252 /// Thread run control functions.
1254 /// Threads for a process should be updated with one of the run
1255 /// control actions (resume, step, or suspend) that they should take
1256 /// when the process is resumed. If no run control action is given
1257 /// to a thread it will be resumed by default.
1260 /// Returns \b true if the process successfully resumes using
1261 /// the thread run control actions, \b false otherwise.
1263 /// @see Thread:Resume()
1264 /// @see Thread:Step()
1265 /// @see Thread:Suspend()
1266 //------------------------------------------------------------------
1267 virtual Error DoResume() {
1269 error.SetErrorStringWithFormat(
1270 "error: %s does not support resuming processes",
1271 GetPluginName().GetCString());
1275 //------------------------------------------------------------------
1276 /// Called after resuming a process.
1278 /// Allow Process plug-ins to execute some code after resuming
1280 //------------------------------------------------------------------
1281 virtual void DidResume() {}
1283 //------------------------------------------------------------------
1284 /// Called before halting to a process.
1286 /// Allow Process plug-ins to execute some code before halting a
1290 /// Returns an error object.
1291 //------------------------------------------------------------------
1292 virtual Error WillHalt() { return Error(); }
1294 //------------------------------------------------------------------
1295 /// Halts a running process.
1297 /// DoHalt must produce one and only one stop StateChanged event if it
1299 /// stops the process. If the stop happens through some natural event (for
1300 /// instance a SIGSTOP), then forwarding that event will do. Otherwise, you
1302 /// generate the event manually. This function is called from the context of
1304 /// private state thread.
1306 /// @param[out] caused_stop
1307 /// If true, then this Halt caused the stop, otherwise, the
1308 /// process was already stopped.
1311 /// Returns \b true if the process successfully halts, \b false
1313 //------------------------------------------------------------------
1314 virtual Error DoHalt(bool &caused_stop) {
1316 error.SetErrorStringWithFormat(
1317 "error: %s does not support halting processes",
1318 GetPluginName().GetCString());
1322 //------------------------------------------------------------------
1323 /// Called after halting a process.
1325 /// Allow Process plug-ins to execute some code after halting
1327 //------------------------------------------------------------------
1328 virtual void DidHalt() {}
1330 //------------------------------------------------------------------
1331 /// Called before detaching from a process.
1333 /// Allow Process plug-ins to execute some code before detaching
1337 /// Returns an error object.
1338 //------------------------------------------------------------------
1339 virtual Error WillDetach() { return Error(); }
1341 //------------------------------------------------------------------
1342 /// Detaches from a running or stopped process.
1345 /// Returns \b true if the process successfully detaches, \b
1346 /// false otherwise.
1347 //------------------------------------------------------------------
1348 virtual Error DoDetach(bool keep_stopped) {
1350 error.SetErrorStringWithFormat(
1351 "error: %s does not support detaching from processes",
1352 GetPluginName().GetCString());
1356 //------------------------------------------------------------------
1357 /// Called after detaching from a process.
1359 /// Allow Process plug-ins to execute some code after detaching
1361 //------------------------------------------------------------------
1362 virtual void DidDetach() {}
1364 virtual bool DetachRequiresHalt() { return false; }
1366 //------------------------------------------------------------------
1367 /// Called before sending a signal to a process.
1369 /// Allow Process plug-ins to execute some code before sending a
1370 /// signal to a process.
1373 /// Returns no error if it is safe to proceed with a call to
1374 /// Process::DoSignal(int), otherwise an error describing what
1375 /// prevents the signal from being sent.
1376 //------------------------------------------------------------------
1377 virtual Error WillSignal() { return Error(); }
1379 //------------------------------------------------------------------
1380 /// Sends a process a UNIX signal \a signal.
1383 /// Returns an error object.
1384 //------------------------------------------------------------------
1385 virtual Error DoSignal(int signal) {
1387 error.SetErrorStringWithFormat(
1388 "error: %s does not support sending signals to processes",
1389 GetPluginName().GetCString());
1393 virtual Error WillDestroy() { return Error(); }
1395 virtual Error DoDestroy() = 0;
1397 virtual void DidDestroy() {}
1399 virtual bool DestroyRequiresHalt() { return true; }
1401 //------------------------------------------------------------------
1402 /// Called after sending a signal to a process.
1404 /// Allow Process plug-ins to execute some code after sending a
1405 /// signal to a process.
1406 //------------------------------------------------------------------
1407 virtual void DidSignal() {}
1409 //------------------------------------------------------------------
1410 /// Currently called as part of ShouldStop.
1411 /// FIXME: Should really happen when the target stops before the
1412 /// event is taken from the queue...
1414 /// This callback is called as the event
1415 /// is about to be queued up to allow Process plug-ins to execute
1416 /// some code prior to clients being notified that a process was
1417 /// stopped. Common operations include updating the thread list,
1418 /// invalidating any thread state (registers, stack, etc) prior to
1419 /// letting the notification go out.
1421 //------------------------------------------------------------------
1422 virtual void RefreshStateAfterStop() = 0;
1424 //------------------------------------------------------------------
1425 /// Sometimes the connection to a process can detect the host OS
1426 /// version that the process is running on. The current platform
1427 /// should be checked first in case the platform is connected, but
1428 /// clients can fall back onto this function if the platform fails
1429 /// to identify the host OS version. The platform should be checked
1430 /// first in case you are running a simulator platform that might
1431 /// itself be running natively, but have different heuristics for
1432 /// figuring out which OS is is emulating.
1434 /// @param[out] major
1435 /// The major OS version, or UINT32_MAX if it can't be determined
1437 /// @param[out] minor
1438 /// The minor OS version, or UINT32_MAX if it can't be determined
1440 /// @param[out] update
1441 /// The update OS version, or UINT32_MAX if it can't be determined
1444 /// Returns \b true if the host OS version info was filled in
1445 /// and \b false otherwise.
1446 //------------------------------------------------------------------
1447 virtual bool GetHostOSVersion(uint32_t &major, uint32_t &minor,
1451 update = UINT32_MAX;
1455 //------------------------------------------------------------------
1456 /// Get the target object pointer for this module.
1459 /// A Target object pointer to the target that owns this
1461 //------------------------------------------------------------------
1462 Target &GetTarget() { return *m_target_sp.lock(); }
1464 //------------------------------------------------------------------
1465 /// Get the const target object pointer for this module.
1468 /// A const Target object pointer to the target that owns this
1470 //------------------------------------------------------------------
1471 const Target &GetTarget() const { return *m_target_sp.lock(); }
1473 //------------------------------------------------------------------
1474 /// Flush all data in the process.
1476 /// Flush the memory caches, all threads, and any other cached data
1479 /// This function can be called after a world changing event like
1480 /// adding a new symbol file, or after the process makes a large
1481 /// context switch (from boot ROM to booted into an OS).
1482 //------------------------------------------------------------------
1485 //------------------------------------------------------------------
1486 /// Get accessor for the current process state.
1489 /// The current state of the process.
1491 /// @see lldb::StateType
1492 //------------------------------------------------------------------
1493 lldb::StateType GetState();
1495 lldb::ExpressionResults
1496 RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp,
1497 const EvaluateExpressionOptions &options,
1498 DiagnosticManager &diagnostic_manager);
1500 static const char *ExecutionResultAsCString(lldb::ExpressionResults result);
1502 void GetStatus(Stream &ostrm);
1504 size_t GetThreadStatus(Stream &ostrm, bool only_threads_with_stop_reason,
1505 uint32_t start_frame, uint32_t num_frames,
1506 uint32_t num_frames_with_source,
1509 void SendAsyncInterrupt();
1511 //------------------------------------------------------------------
1512 // Notify this process class that modules got loaded.
1514 // If subclasses override this method, they must call this version
1515 // before doing anything in the subclass version of the function.
1516 //------------------------------------------------------------------
1517 virtual void ModulesDidLoad(ModuleList &module_list);
1519 //------------------------------------------------------------------
1520 /// Retrieve the list of shared libraries that are loaded for this process
1521 /// This method is used on pre-macOS 10.12, pre-iOS 10, pre-tvOS 10,
1522 /// pre-watchOS 3 systems. The following two methods are for newer versions
1525 /// For certain platforms, the time it takes for the DynamicLoader plugin to
1526 /// read all of the shared libraries out of memory over a slow communication
1527 /// channel may be too long. In that instance, the gdb-remote stub may be
1528 /// able to retrieve the necessary information about the solibs out of memory
1529 /// and return a concise summary sufficient for the DynamicLoader plugin.
1531 /// @param [in] image_list_address
1532 /// The address where the table of shared libraries is stored in memory,
1533 /// if that is appropriate for this platform. Else this may be
1534 /// passed as LLDB_INVALID_ADDRESS.
1536 /// @param [in] image_count
1537 /// The number of shared libraries that are present in this process, if
1538 /// that is appropriate for this platofrm Else this may be passed as
1539 /// LLDB_INVALID_ADDRESS.
1542 /// A StructureDataSP object which, if non-empty, will contain the
1543 /// information the DynamicLoader needs to get the initial scan of
1544 /// solibs resolved.
1545 //------------------------------------------------------------------
1546 virtual lldb_private::StructuredData::ObjectSP
1547 GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address,
1548 lldb::addr_t image_count) {
1549 return StructuredData::ObjectSP();
1552 // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1554 // the full list of loaded shared libraries without needing any input.
1555 virtual lldb_private::StructuredData::ObjectSP
1556 GetLoadedDynamicLibrariesInfos() {
1557 return StructuredData::ObjectSP();
1560 // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1562 // information about binaries given their load addresses.
1563 virtual lldb_private::StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos(
1564 const std::vector<lldb::addr_t> &load_addresses) {
1565 return StructuredData::ObjectSP();
1568 //------------------------------------------------------------------
1569 // Get information about the library shared cache, if that exists
1571 // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1573 // information about the library shared cache (a set of standard libraries
1575 // loaded at the same location for all processes on a system) in use.
1576 //------------------------------------------------------------------
1577 virtual lldb_private::StructuredData::ObjectSP GetSharedCacheInfo() {
1578 return StructuredData::ObjectSP();
1581 //------------------------------------------------------------------
1582 /// Print a user-visible warning about a module being built with optimization
1584 /// Prints a async warning message to the user one time per Module
1585 /// where a function is found that was compiled with optimization, per
1589 /// A SymbolContext with eSymbolContextFunction and eSymbolContextModule
1591 //------------------------------------------------------------------
1592 void PrintWarningOptimization(const SymbolContext &sc);
1594 virtual bool GetProcessInfo(ProcessInstanceInfo &info);
1597 //------------------------------------------------------------------
1598 /// Get the exit status for a process.
1601 /// The process's return code, or -1 if the current process
1602 /// state is not eStateExited.
1603 //------------------------------------------------------------------
1604 int GetExitStatus();
1606 //------------------------------------------------------------------
1607 /// Get a textual description of what the process exited.
1610 /// The textual description of why the process exited, or nullptr
1611 /// if there is no description available.
1612 //------------------------------------------------------------------
1613 const char *GetExitDescription();
1615 virtual void DidExit() {}
1617 //------------------------------------------------------------------
1618 /// Get the Modification ID of the process.
1621 /// The modification ID of the process.
1622 //------------------------------------------------------------------
1623 ProcessModID GetModID() const { return m_mod_id; }
1625 const ProcessModID &GetModIDRef() const { return m_mod_id; }
1627 uint32_t GetStopID() const { return m_mod_id.GetStopID(); }
1629 uint32_t GetResumeID() const { return m_mod_id.GetResumeID(); }
1631 uint32_t GetLastUserExpressionResumeID() const {
1632 return m_mod_id.GetLastUserExpressionResumeID();
1635 uint32_t GetLastNaturalStopID() const {
1636 return m_mod_id.GetLastNaturalStopID();
1639 lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const {
1640 return m_mod_id.GetStopEventForStopID(stop_id);
1643 //------------------------------------------------------------------
1644 /// Set accessor for the process exit status (return code).
1646 /// Sometimes a child exits and the exit can be detected by global
1647 /// functions (signal handler for SIGCHLD for example). This
1648 /// accessor allows the exit status to be set from an external
1651 /// Setting this will cause a eStateExited event to be posted to
1652 /// the process event queue.
1654 /// @param[in] exit_status
1655 /// The value for the process's return code.
1657 /// @see lldb::StateType
1658 //------------------------------------------------------------------
1659 virtual bool SetExitStatus(int exit_status, const char *cstr);
1661 //------------------------------------------------------------------
1662 /// Check if a process is still alive.
1665 /// Returns \b true if the process is still valid, \b false
1667 //------------------------------------------------------------------
1668 virtual bool IsAlive();
1670 //------------------------------------------------------------------
1671 /// Before lldb detaches from a process, it warns the user that they are about
1672 /// to lose their debug session.
1673 /// In some cases, this warning doesn't need to be emitted -- for instance,
1674 /// with core file debugging where
1675 /// the user can reconstruct the "state" by simply re-running the debugger on
1679 // true if the user should be warned about detaching from this process.
1680 //------------------------------------------------------------------
1681 virtual bool WarnBeforeDetach() const { return true; }
1683 //------------------------------------------------------------------
1684 /// Actually do the reading of memory from a process.
1686 /// Subclasses must override this function and can return fewer
1687 /// bytes than requested when memory requests are too large. This
1688 /// class will break up the memory requests and keep advancing the
1689 /// arguments along as needed.
1691 /// @param[in] vm_addr
1692 /// A virtual load address that indicates where to start reading
1696 /// The number of bytes to read.
1699 /// A byte buffer that is at least \a size bytes long that
1700 /// will receive the memory bytes.
1703 /// The number of bytes that were actually read into \a buf.
1704 //------------------------------------------------------------------
1705 virtual size_t DoReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1708 //------------------------------------------------------------------
1709 /// Read of memory from a process.
1711 /// This function will read memory from the current process's
1712 /// address space and remove any traps that may have been inserted
1713 /// into the memory.
1715 /// This function is not meant to be overridden by Process
1716 /// subclasses, the subclasses should implement
1717 /// Process::DoReadMemory (lldb::addr_t, size_t, void *).
1719 /// @param[in] vm_addr
1720 /// A virtual load address that indicates where to start reading
1724 /// A byte buffer that is at least \a size bytes long that
1725 /// will receive the memory bytes.
1728 /// The number of bytes to read.
1731 /// The number of bytes that were actually read into \a buf. If
1732 /// the returned number is greater than zero, yet less than \a
1733 /// size, then this function will get called again with \a
1734 /// vm_addr, \a buf, and \a size updated appropriately. Zero is
1735 /// returned to indicate an error.
1736 //------------------------------------------------------------------
1737 virtual size_t ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1740 //------------------------------------------------------------------
1741 /// Read a NULL terminated string from memory
1743 /// This function will read a cache page at a time until a NULL
1744 /// string terminator is found. It will stop reading if an aligned
1745 /// sequence of NULL termination \a type_width bytes is not found
1746 /// before reading \a cstr_max_len bytes. The results are always
1747 /// guaranteed to be NULL terminated, and that no more than
1748 /// (max_bytes - type_width) bytes will be read.
1750 /// @param[in] vm_addr
1751 /// The virtual load address to start the memory read.
1754 /// A character buffer containing at least max_bytes.
1756 /// @param[in] max_bytes
1757 /// The maximum number of bytes to read.
1759 /// @param[in] error
1760 /// The error status of the read operation.
1762 /// @param[in] type_width
1763 /// The size of the null terminator (1 to 4 bytes per
1764 /// character). Defaults to 1.
1767 /// The error status or the number of bytes prior to the null terminator.
1768 //------------------------------------------------------------------
1769 size_t ReadStringFromMemory(lldb::addr_t vm_addr, char *str, size_t max_bytes,
1770 Error &error, size_t type_width = 1);
1772 //------------------------------------------------------------------
1773 /// Read a NULL terminated C string from memory
1775 /// This function will read a cache page at a time until the NULL
1776 /// C string terminator is found. It will stop reading if the NULL
1777 /// termination byte isn't found before reading \a cstr_max_len
1778 /// bytes, and the results are always guaranteed to be NULL
1779 /// terminated (at most cstr_max_len - 1 bytes will be read).
1780 //------------------------------------------------------------------
1781 size_t ReadCStringFromMemory(lldb::addr_t vm_addr, char *cstr,
1782 size_t cstr_max_len, Error &error);
1784 size_t ReadCStringFromMemory(lldb::addr_t vm_addr, std::string &out_str,
1787 size_t ReadMemoryFromInferior(lldb::addr_t vm_addr, void *buf, size_t size,
1790 //------------------------------------------------------------------
1791 /// Reads an unsigned integer of the specified byte size from
1794 /// @param[in] load_addr
1795 /// A load address of the integer to read.
1797 /// @param[in] byte_size
1798 /// The size in byte of the integer to read.
1800 /// @param[in] fail_value
1801 /// The value to return if we fail to read an integer.
1803 /// @param[out] error
1804 /// An error that indicates the success or failure of this
1805 /// operation. If error indicates success (error.Success()),
1806 /// then the value returned can be trusted, otherwise zero
1807 /// will be returned.
1810 /// The unsigned integer that was read from the process memory
1811 /// space. If the integer was smaller than a uint64_t, any
1812 /// unused upper bytes will be zero filled. If the process
1813 /// byte order differs from the host byte order, the integer
1814 /// value will be appropriately byte swapped into host byte
1816 //------------------------------------------------------------------
1817 uint64_t ReadUnsignedIntegerFromMemory(lldb::addr_t load_addr,
1818 size_t byte_size, uint64_t fail_value,
1821 int64_t ReadSignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size,
1822 int64_t fail_value, Error &error);
1824 lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Error &error);
1826 bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
1829 //------------------------------------------------------------------
1830 /// Actually do the writing of memory to a process.
1832 /// @param[in] vm_addr
1833 /// A virtual load address that indicates where to start writing
1837 /// A byte buffer that is at least \a size bytes long that
1838 /// contains the data to write.
1841 /// The number of bytes to write.
1843 /// @param[out] error
1844 /// An error value in case the memory write fails.
1847 /// The number of bytes that were actually written.
1848 //------------------------------------------------------------------
1849 virtual size_t DoWriteMemory(lldb::addr_t vm_addr, const void *buf,
1850 size_t size, Error &error) {
1851 error.SetErrorStringWithFormat(
1852 "error: %s does not support writing to processes",
1853 GetPluginName().GetCString());
1857 //------------------------------------------------------------------
1858 /// Write all or part of a scalar value to memory.
1860 /// The value contained in \a scalar will be swapped to match the
1861 /// byte order of the process that is being debugged. If \a size is
1862 /// less than the size of scalar, the least significant \a size bytes
1863 /// from scalar will be written. If \a size is larger than the byte
1864 /// size of scalar, then the extra space will be padded with zeros
1865 /// and the scalar value will be placed in the least significant
1866 /// bytes in memory.
1868 /// @param[in] vm_addr
1869 /// A virtual load address that indicates where to start writing
1872 /// @param[in] scalar
1873 /// The scalar to write to the debugged process.
1876 /// This value can be smaller or larger than the scalar value
1877 /// itself. If \a size is smaller than the size of \a scalar,
1878 /// the least significant bytes in \a scalar will be used. If
1879 /// \a size is larger than the byte size of \a scalar, then
1880 /// the extra space will be padded with zeros. If \a size is
1881 /// set to UINT32_MAX, then the size of \a scalar will be used.
1883 /// @param[out] error
1884 /// An error value in case the memory write fails.
1887 /// The number of bytes that were actually written.
1888 //------------------------------------------------------------------
1889 size_t WriteScalarToMemory(lldb::addr_t vm_addr, const Scalar &scalar,
1890 size_t size, Error &error);
1892 size_t ReadScalarIntegerFromMemory(lldb::addr_t addr, uint32_t byte_size,
1893 bool is_signed, Scalar &scalar,
1896 //------------------------------------------------------------------
1897 /// Write memory to a process.
1899 /// This function will write memory to the current process's
1900 /// address space and maintain any traps that might be present due
1901 /// to software breakpoints.
1903 /// This function is not meant to be overridden by Process
1904 /// subclasses, the subclasses should implement
1905 /// Process::DoWriteMemory (lldb::addr_t, size_t, void *).
1907 /// @param[in] vm_addr
1908 /// A virtual load address that indicates where to start writing
1912 /// A byte buffer that is at least \a size bytes long that
1913 /// contains the data to write.
1916 /// The number of bytes to write.
1919 /// The number of bytes that were actually written.
1920 //------------------------------------------------------------------
1921 // TODO: change this to take an ArrayRef<uint8_t>
1922 size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1925 //------------------------------------------------------------------
1926 /// Actually allocate memory in the process.
1928 /// This function will allocate memory in the process's address
1929 /// space. This can't rely on the generic function calling mechanism,
1930 /// since that requires this function.
1933 /// The size of the allocation requested.
1936 /// The address of the allocated buffer in the process, or
1937 /// LLDB_INVALID_ADDRESS if the allocation failed.
1938 //------------------------------------------------------------------
1940 virtual lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions,
1942 error.SetErrorStringWithFormat(
1943 "error: %s does not support allocating in the debug process",
1944 GetPluginName().GetCString());
1945 return LLDB_INVALID_ADDRESS;
1948 //------------------------------------------------------------------
1949 /// The public interface to allocating memory in the process.
1951 /// This function will allocate memory in the process's address
1952 /// space. This can't rely on the generic function calling mechanism,
1953 /// since that requires this function.
1956 /// The size of the allocation requested.
1958 /// @param[in] permissions
1959 /// Or together any of the lldb::Permissions bits. The permissions on
1960 /// a given memory allocation can't be changed after allocation. Note
1961 /// that a block that isn't set writable can still be written on from
1963 /// just not by the process itself.
1965 /// @param[in,out] error
1966 /// An error object to fill in if things go wrong.
1968 /// The address of the allocated buffer in the process, or
1969 /// LLDB_INVALID_ADDRESS if the allocation failed.
1970 //------------------------------------------------------------------
1971 lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Error &error);
1973 //------------------------------------------------------------------
1974 /// The public interface to allocating memory in the process, this also
1975 /// clears the allocated memory.
1977 /// This function will allocate memory in the process's address
1978 /// space. This can't rely on the generic function calling mechanism,
1979 /// since that requires this function.
1982 /// The size of the allocation requested.
1984 /// @param[in] permissions
1985 /// Or together any of the lldb::Permissions bits. The permissions on
1986 /// a given memory allocation can't be changed after allocation. Note
1987 /// that a block that isn't set writable can still be written on from
1989 /// just not by the process itself.
1991 /// @param[in/out] error
1992 /// An error object to fill in if things go wrong.
1994 /// The address of the allocated buffer in the process, or
1995 /// LLDB_INVALID_ADDRESS if the allocation failed.
1996 //------------------------------------------------------------------
1998 lldb::addr_t CallocateMemory(size_t size, uint32_t permissions, Error &error);
2000 //------------------------------------------------------------------
2001 /// Resolve dynamically loaded indirect functions.
2003 /// @param[in] address
2004 /// The load address of the indirect function to resolve.
2006 /// @param[out] error
2007 /// An error value in case the resolve fails.
2010 /// The address of the resolved function.
2011 /// LLDB_INVALID_ADDRESS if the resolution failed.
2012 //------------------------------------------------------------------
2013 virtual lldb::addr_t ResolveIndirectFunction(const Address *address,
2016 //------------------------------------------------------------------
2017 /// Locate the memory region that contains load_addr.
2019 /// If load_addr is within the address space the process has mapped
2020 /// range_info will be filled in with the start and end of that range
2021 /// as well as the permissions for that range and range_info.GetMapped
2022 /// will return true.
2024 /// If load_addr is outside any mapped region then range_info will
2025 /// have its start address set to load_addr and the end of the
2026 /// range will indicate the start of the next mapped range or be
2027 /// set to LLDB_INVALID_ADDRESS if there are no valid mapped ranges
2028 /// between load_addr and the end of the process address space.
2030 /// GetMemoryRegionInfo will only return an error if it is
2031 /// unimplemented for the current process.
2033 /// @param[in] load_addr
2034 /// The load address to query the range_info for.
2036 /// @param[out] range_info
2037 /// An range_info value containing the details of the range.
2041 //------------------------------------------------------------------
2042 virtual Error GetMemoryRegionInfo(lldb::addr_t load_addr,
2043 MemoryRegionInfo &range_info) {
2045 error.SetErrorString("Process::GetMemoryRegionInfo() not supported");
2049 //------------------------------------------------------------------
2050 /// Obtain all the mapped memory regions within this process.
2052 /// @param[out] region_list
2053 /// A vector to contain MemoryRegionInfo objects for all mapped
2058 //------------------------------------------------------------------
2060 GetMemoryRegions(std::vector<lldb::MemoryRegionInfoSP> ®ion_list);
2062 virtual Error GetWatchpointSupportInfo(uint32_t &num) {
2065 error.SetErrorString("Process::GetWatchpointSupportInfo() not supported");
2069 virtual Error GetWatchpointSupportInfo(uint32_t &num, bool &after) {
2073 error.SetErrorString("Process::GetWatchpointSupportInfo() not supported");
2077 lldb::ModuleSP ReadModuleFromMemory(const FileSpec &file_spec,
2078 lldb::addr_t header_addr,
2079 size_t size_to_read = 512);
2081 //------------------------------------------------------------------
2082 /// Attempt to get the attributes for a region of memory in the process.
2084 /// It may be possible for the remote debug server to inspect attributes
2085 /// for a region of memory in the process, such as whether there is a
2086 /// valid page of memory at a given address or whether that page is
2087 /// readable/writable/executable by the process.
2089 /// @param[in] load_addr
2090 /// The address of interest in the process.
2092 /// @param[out] permissions
2093 /// If this call returns successfully, this bitmask will have
2094 /// its Permissions bits set to indicate whether the region is
2095 /// readable/writable/executable. If this call fails, the
2096 /// bitmask values are undefined.
2099 /// Returns true if it was able to determine the attributes of the
2100 /// memory region. False if not.
2101 //------------------------------------------------------------------
2102 virtual bool GetLoadAddressPermissions(lldb::addr_t load_addr,
2103 uint32_t &permissions);
2105 //------------------------------------------------------------------
2106 /// Determines whether executing JIT-compiled code in this process
2110 /// True if execution of JIT code is possible; false otherwise.
2111 //------------------------------------------------------------------
2114 //------------------------------------------------------------------
2115 /// Sets whether executing JIT-compiled code in this process
2118 /// @param[in] can_jit
2119 /// True if execution of JIT code is possible; false otherwise.
2120 //------------------------------------------------------------------
2121 void SetCanJIT(bool can_jit);
2123 //------------------------------------------------------------------
2124 /// Determines whether executing function calls using the interpreter
2125 /// is possible for this process.
2128 /// True if possible; false otherwise.
2129 //------------------------------------------------------------------
2130 bool CanInterpretFunctionCalls() { return m_can_interpret_function_calls; }
2132 //------------------------------------------------------------------
2133 /// Sets whether executing function calls using the interpreter
2134 /// is possible for this process.
2136 /// @param[in] can_interpret_function_calls
2137 /// True if possible; false otherwise.
2138 //------------------------------------------------------------------
2139 void SetCanInterpretFunctionCalls(bool can_interpret_function_calls) {
2140 m_can_interpret_function_calls = can_interpret_function_calls;
2143 //------------------------------------------------------------------
2144 /// Sets whether executing code in this process is possible.
2145 /// This could be either through JIT or interpreting.
2147 /// @param[in] can_run_code
2148 /// True if execution of code is possible; false otherwise.
2149 //------------------------------------------------------------------
2150 void SetCanRunCode(bool can_run_code);
2152 //------------------------------------------------------------------
2153 /// Actually deallocate memory in the process.
2155 /// This function will deallocate memory in the process's address
2156 /// space that was allocated with AllocateMemory.
2159 /// A return value from AllocateMemory, pointing to the memory you
2160 /// want to deallocate.
2163 /// \btrue if the memory was deallocated, \bfalse otherwise.
2164 //------------------------------------------------------------------
2165 virtual Error DoDeallocateMemory(lldb::addr_t ptr) {
2167 error.SetErrorStringWithFormat(
2168 "error: %s does not support deallocating in the debug process",
2169 GetPluginName().GetCString());
2173 //------------------------------------------------------------------
2174 /// The public interface to deallocating memory in the process.
2176 /// This function will deallocate memory in the process's address
2177 /// space that was allocated with AllocateMemory.
2180 /// A return value from AllocateMemory, pointing to the memory you
2181 /// want to deallocate.
2184 /// \btrue if the memory was deallocated, \bfalse otherwise.
2185 //------------------------------------------------------------------
2186 Error DeallocateMemory(lldb::addr_t ptr);
2188 //------------------------------------------------------------------
2189 /// Get any available STDOUT.
2191 /// Calling this method is a valid operation only if all of the
2192 /// following conditions are true:
2193 /// 1) The process was launched, and not attached to.
2194 /// 2) The process was not launched with eLaunchFlagDisableSTDIO.
2195 /// 3) The process was launched without supplying a valid file path
2198 /// Note that the implementation will probably need to start a read
2199 /// thread in the background to make sure that the pipe is drained
2200 /// and the STDOUT buffered appropriately, to prevent the process
2201 /// from deadlocking trying to write to a full buffer.
2203 /// Events will be queued indicating that there is STDOUT available
2204 /// that can be retrieved using this function.
2207 /// A buffer that will receive any STDOUT bytes that are
2208 /// currently available.
2210 /// @param[in] buf_size
2211 /// The size in bytes for the buffer \a buf.
2214 /// The number of bytes written into \a buf. If this value is
2215 /// equal to \a buf_size, another call to this function should
2216 /// be made to retrieve more STDOUT data.
2217 //------------------------------------------------------------------
2218 virtual size_t GetSTDOUT(char *buf, size_t buf_size, Error &error);
2220 //------------------------------------------------------------------
2221 /// Get any available STDERR.
2223 /// Calling this method is a valid operation only if all of the
2224 /// following conditions are true:
2225 /// 1) The process was launched, and not attached to.
2226 /// 2) The process was not launched with eLaunchFlagDisableSTDIO.
2227 /// 3) The process was launched without supplying a valid file path
2230 /// Note that the implementation will probably need to start a read
2231 /// thread in the background to make sure that the pipe is drained
2232 /// and the STDERR buffered appropriately, to prevent the process
2233 /// from deadlocking trying to write to a full buffer.
2235 /// Events will be queued indicating that there is STDERR available
2236 /// that can be retrieved using this function.
2239 /// A buffer that will receive any STDERR bytes that are
2240 /// currently available.
2242 /// @param[out] buf_size
2243 /// The size in bytes for the buffer \a buf.
2246 /// The number of bytes written into \a buf. If this value is
2247 /// equal to \a buf_size, another call to this function should
2248 /// be made to retrieve more STDERR data.
2249 //------------------------------------------------------------------
2250 virtual size_t GetSTDERR(char *buf, size_t buf_size, Error &error);
2252 //------------------------------------------------------------------
2253 /// Puts data into this process's STDIN.
2255 /// Calling this method is a valid operation only if all of the
2256 /// following conditions are true:
2257 /// 1) The process was launched, and not attached to.
2258 /// 2) The process was not launched with eLaunchFlagDisableSTDIO.
2259 /// 3) The process was launched without supplying a valid file path
2263 /// A buffer that contains the data to write to the process's STDIN.
2265 /// @param[in] buf_size
2266 /// The size in bytes for the buffer \a buf.
2269 /// The number of bytes written into \a buf. If this value is
2270 /// less than \a buf_size, another call to this function should
2271 /// be made to write the rest of the data.
2272 //------------------------------------------------------------------
2273 virtual size_t PutSTDIN(const char *buf, size_t buf_size, Error &error) {
2274 error.SetErrorString("stdin unsupported");
2278 //------------------------------------------------------------------
2279 /// Get any available profile data.
2282 /// A buffer that will receive any profile data bytes that are
2283 /// currently available.
2285 /// @param[out] buf_size
2286 /// The size in bytes for the buffer \a buf.
2289 /// The number of bytes written into \a buf. If this value is
2290 /// equal to \a buf_size, another call to this function should
2291 /// be made to retrieve more profile data.
2292 //------------------------------------------------------------------
2293 virtual size_t GetAsyncProfileData(char *buf, size_t buf_size, Error &error);
2295 //----------------------------------------------------------------------
2296 // Process Breakpoints
2297 //----------------------------------------------------------------------
2298 size_t GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site);
2300 virtual Error EnableBreakpointSite(BreakpointSite *bp_site) {
2302 error.SetErrorStringWithFormat(
2303 "error: %s does not support enabling breakpoints",
2304 GetPluginName().GetCString());
2308 virtual Error DisableBreakpointSite(BreakpointSite *bp_site) {
2310 error.SetErrorStringWithFormat(
2311 "error: %s does not support disabling breakpoints",
2312 GetPluginName().GetCString());
2316 // This is implemented completely using the lldb::Process API. Subclasses
2317 // don't need to implement this function unless the standard flow of
2318 // read existing opcode, write breakpoint opcode, verify breakpoint opcode
2319 // doesn't work for a specific process plug-in.
2320 virtual Error EnableSoftwareBreakpoint(BreakpointSite *bp_site);
2322 // This is implemented completely using the lldb::Process API. Subclasses
2323 // don't need to implement this function unless the standard flow of
2324 // restoring original opcode in memory and verifying the restored opcode
2325 // doesn't work for a specific process plug-in.
2326 virtual Error DisableSoftwareBreakpoint(BreakpointSite *bp_site);
2328 BreakpointSiteList &GetBreakpointSiteList();
2330 const BreakpointSiteList &GetBreakpointSiteList() const;
2332 void DisableAllBreakpointSites();
2334 Error ClearBreakpointSiteByID(lldb::user_id_t break_id);
2336 lldb::break_id_t CreateBreakpointSite(const lldb::BreakpointLocationSP &owner,
2339 Error DisableBreakpointSiteByID(lldb::user_id_t break_id);
2341 Error EnableBreakpointSiteByID(lldb::user_id_t break_id);
2343 // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove
2344 // themselves from the owner's list of this breakpoint sites.
2345 void RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
2346 lldb::user_id_t owner_loc_id,
2347 lldb::BreakpointSiteSP &bp_site_sp);
2349 //----------------------------------------------------------------------
2350 // Process Watchpoints (optional)
2351 //----------------------------------------------------------------------
2352 virtual Error EnableWatchpoint(Watchpoint *wp, bool notify = true);
2354 virtual Error DisableWatchpoint(Watchpoint *wp, bool notify = true);
2356 //------------------------------------------------------------------
2358 //------------------------------------------------------------------
2359 virtual bool UpdateThreadList(ThreadList &old_thread_list,
2360 ThreadList &new_thread_list) = 0;
2362 void UpdateThreadListIfNeeded();
2364 ThreadList &GetThreadList() { return m_thread_list; }
2366 // When ExtendedBacktraces are requested, the HistoryThreads that are
2367 // created need an owner -- they're saved here in the Process. The
2368 // threads in this list are not iterated over - driver programs need to
2369 // request the extended backtrace calls starting from a root concrete
2370 // thread one by one.
2371 ThreadList &GetExtendedThreadList() { return m_extended_thread_list; }
2373 ThreadList::ThreadIterable Threads() { return m_thread_list.Threads(); }
2375 uint32_t GetNextThreadIndexID(uint64_t thread_id);
2377 lldb::ThreadSP CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context);
2379 // Returns true if an index id has been assigned to a thread.
2380 bool HasAssignedIndexIDToThread(uint64_t sb_thread_id);
2382 // Given a thread_id, it will assign a more reasonable index id for display to
2384 // If the thread_id has previously been assigned, the same index id will be
2386 uint32_t AssignIndexIDToThread(uint64_t thread_id);
2388 //------------------------------------------------------------------
2390 //------------------------------------------------------------------
2392 void UpdateQueueListIfNeeded();
2394 QueueList &GetQueueList() {
2395 UpdateQueueListIfNeeded();
2396 return m_queue_list;
2399 QueueList::QueueIterable Queues() {
2400 UpdateQueueListIfNeeded();
2401 return m_queue_list.Queues();
2404 //------------------------------------------------------------------
2406 //------------------------------------------------------------------
2407 lldb::StateType GetNextEvent(lldb::EventSP &event_sp);
2409 // Returns the process state when it is stopped. If specified, event_sp_ptr
2410 // is set to the event which triggered the stop. If wait_always = false,
2411 // and the process is already stopped, this function returns immediately.
2412 // If the process is hijacked and use_run_lock is true (the default), then
2414 // function releases the run lock after the stop. Setting use_run_lock to
2416 // will avoid this behavior.
2418 WaitForProcessToStop(const Timeout<std::micro> &timeout,
2419 lldb::EventSP *event_sp_ptr = nullptr,
2420 bool wait_always = true,
2421 lldb::ListenerSP hijack_listener = lldb::ListenerSP(),
2422 Stream *stream = nullptr, bool use_run_lock = true);
2424 uint32_t GetIOHandlerID() const { return m_iohandler_sync.GetValue(); }
2426 //--------------------------------------------------------------------------------------
2427 /// Waits for the process state to be running within a given msec timeout.
2429 /// The main purpose of this is to implement an interlock waiting for
2430 /// HandlePrivateEvent
2431 /// to push an IOHandler.
2433 /// @param[in] timeout_msec
2434 /// The maximum time length to wait for the process to transition to the
2435 /// eStateRunning state, specified in milliseconds.
2436 //--------------------------------------------------------------------------------------
2437 void SyncIOHandler(uint32_t iohandler_id, uint64_t timeout_msec);
2439 lldb::StateType GetStateChangedEvents(
2440 lldb::EventSP &event_sp, const Timeout<std::micro> &timeout,
2442 hijack_listener); // Pass an empty ListenerSP to use builtin listener
2444 //--------------------------------------------------------------------------------------
2445 /// Centralize the code that handles and prints descriptions for process state
2448 /// @param[in] event_sp
2449 /// The process state changed event
2451 /// @param[in] stream
2452 /// The output stream to get the state change description
2454 /// @param[in,out] pop_process_io_handler
2455 /// If this value comes in set to \b true, then pop the Process IOHandler
2457 /// Else this variable will be set to \b true or \b false to indicate if
2459 /// needs to have its process IOHandler popped.
2462 /// \b true if the event describes a process state changed event, \b false
2464 //--------------------------------------------------------------------------------------
2465 static bool HandleProcessStateChangedEvent(const lldb::EventSP &event_sp,
2467 bool &pop_process_io_handler);
2469 Event *PeekAtStateChangedEvents();
2471 class ProcessEventHijacker {
2473 ProcessEventHijacker(Process &process, lldb::ListenerSP listener_sp)
2474 : m_process(process) {
2475 m_process.HijackProcessEvents(listener_sp);
2478 ~ProcessEventHijacker() { m_process.RestoreProcessEvents(); }
2484 friend class ProcessEventHijacker;
2485 friend class ProcessProperties;
2486 //------------------------------------------------------------------
2487 /// If you need to ensure that you and only you will hear about some public
2488 /// event, then make a new listener, set to listen to process events, and
2489 /// then call this with that listener. Then you will have to wait on that
2490 /// listener explicitly for events (rather than using the GetNextEvent &
2492 /// calls above. Be sure to call RestoreProcessEvents when you are done.
2494 /// @param[in] listener
2495 /// This is the new listener to whom all process events will be delivered.
2498 /// Returns \b true if the new listener could be installed,
2499 /// \b false otherwise.
2500 //------------------------------------------------------------------
2501 bool HijackProcessEvents(lldb::ListenerSP listener_sp);
2503 //------------------------------------------------------------------
2504 /// Restores the process event broadcasting to its normal state.
2506 //------------------------------------------------------------------
2507 void RestoreProcessEvents();
2509 const lldb::ABISP &GetABI();
2511 OperatingSystem *GetOperatingSystem() { return m_os_ap.get(); }
2513 ArchSpec::StopInfoOverrideCallbackType GetStopInfoOverrideCallback() const {
2514 return m_stop_info_override_callback;
2517 virtual LanguageRuntime *GetLanguageRuntime(lldb::LanguageType language,
2518 bool retry_if_null = true);
2520 virtual CPPLanguageRuntime *GetCPPLanguageRuntime(bool retry_if_null = true);
2522 virtual ObjCLanguageRuntime *
2523 GetObjCLanguageRuntime(bool retry_if_null = true);
2525 bool IsPossibleDynamicValue(ValueObject &in_value);
2527 bool IsRunning() const;
2529 DynamicCheckerFunctions *GetDynamicCheckers() {
2530 return m_dynamic_checkers_ap.get();
2533 void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers);
2535 //------------------------------------------------------------------
2536 /// Call this to set the lldb in the mode where it breaks on new thread
2537 /// creations, and then auto-restarts. This is useful when you are trying
2538 /// to run only one thread, but either that thread or the kernel is creating
2539 /// new threads in the process. If you stop when the thread is created, you
2540 /// can immediately suspend it, and keep executing only the one thread you
2544 /// Returns \b true if we were able to start up the notification
2545 /// \b false otherwise.
2546 //------------------------------------------------------------------
2547 virtual bool StartNoticingNewThreads() { return true; }
2549 //------------------------------------------------------------------
2550 /// Call this to turn off the stop & notice new threads mode.
2553 /// Returns \b true if we were able to start up the notification
2554 /// \b false otherwise.
2555 //------------------------------------------------------------------
2556 virtual bool StopNoticingNewThreads() { return true; }
2558 void SetRunningUserExpression(bool on);
2560 //------------------------------------------------------------------
2561 // lldb::ExecutionContextScope pure virtual functions
2562 //------------------------------------------------------------------
2563 lldb::TargetSP CalculateTarget() override;
2565 lldb::ProcessSP CalculateProcess() override { return shared_from_this(); }
2567 lldb::ThreadSP CalculateThread() override { return lldb::ThreadSP(); }
2569 lldb::StackFrameSP CalculateStackFrame() override {
2570 return lldb::StackFrameSP();
2573 void CalculateExecutionContext(ExecutionContext &exe_ctx) override;
2575 void SetSTDIOFileDescriptor(int file_descriptor);
2577 //------------------------------------------------------------------
2578 // Add a permanent region of memory that should never be read or
2579 // written to. This can be used to ensure that memory reads or writes
2580 // to certain areas of memory never end up being sent to the
2581 // DoReadMemory or DoWriteMemory functions which can improve
2583 //------------------------------------------------------------------
2584 void AddInvalidMemoryRegion(const LoadRange ®ion);
2586 //------------------------------------------------------------------
2587 // Remove a permanent region of memory that should never be read or
2588 // written to that was previously added with AddInvalidMemoryRegion.
2589 //------------------------------------------------------------------
2590 bool RemoveInvalidMemoryRange(const LoadRange ®ion);
2592 //------------------------------------------------------------------
2593 // If the setup code of a thread plan needs to do work that might involve
2594 // calling a function in the target, it should not do that work directly
2595 // in one of the thread plan functions (DidPush/WillResume) because
2596 // such work needs to be handled carefully. Instead, put that work in
2597 // a PreResumeAction callback, and register it with the process. It will
2598 // get done before the actual "DoResume" gets called.
2599 //------------------------------------------------------------------
2601 typedef bool(PreResumeActionCallback)(void *);
2603 void AddPreResumeAction(PreResumeActionCallback callback, void *baton);
2605 bool RunPreResumeActions();
2607 void ClearPreResumeActions();
2609 void ClearPreResumeAction(PreResumeActionCallback callback, void *baton);
2611 ProcessRunLock &GetRunLock();
2613 virtual Error SendEventData(const char *data) {
2614 Error return_error("Sending an event is not supported for this process.");
2615 return return_error;
2618 lldb::ThreadCollectionSP GetHistoryThreads(lldb::addr_t addr);
2620 lldb::InstrumentationRuntimeSP
2621 GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type);
2623 //------------------------------------------------------------------
2624 /// Try to fetch the module specification for a module with the
2625 /// given file name and architecture. Process sub-classes have to
2626 /// override this method if they support platforms where the
2627 /// Platform object can't get the module spec for all module.
2629 /// @param[in] module_file_spec
2630 /// The file name of the module to get specification for.
2633 /// The architecture of the module to get specification for.
2635 /// @param[out] module_spec
2636 /// The fetched module specification if the return value is
2637 /// \b true, unchanged otherwise.
2640 /// Returns \b true if the module spec fetched successfully,
2641 /// \b false otherwise.
2642 //------------------------------------------------------------------
2643 virtual bool GetModuleSpec(const FileSpec &module_file_spec,
2644 const ArchSpec &arch, ModuleSpec &module_spec);
2646 virtual void PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs,
2647 const llvm::Triple &triple) {}
2649 //------------------------------------------------------------------
2650 /// Try to find the load address of a file.
2651 /// The load address is defined as the address of the first memory
2652 /// region what contains data mapped from the specified file.
2655 /// The name of the file whose load address we are looking for
2657 /// @param[out] is_loaded
2658 /// \b True if the file is loaded into the memory and false
2661 /// @param[out] load_addr
2662 /// The load address of the file if it is loaded into the
2663 /// processes address space, LLDB_INVALID_ADDRESS otherwise.
2664 //------------------------------------------------------------------
2665 virtual Error GetFileLoadAddress(const FileSpec &file, bool &is_loaded,
2666 lldb::addr_t &load_addr) {
2667 return Error("Not supported");
2670 size_t AddImageToken(lldb::addr_t image_ptr);
2672 lldb::addr_t GetImagePtrFromToken(size_t token) const;
2674 void ResetImageToken(size_t token);
2676 //------------------------------------------------------------------
2677 /// Find the next branch instruction to set a breakpoint on
2679 /// When instruction stepping through a source line, instead of
2680 /// stepping through each instruction, we can put a breakpoint on
2681 /// the next branch instruction (within the range of instructions
2682 /// we are stepping through) and continue the process to there,
2683 /// yielding significant performance benefits over instruction
2686 /// @param[in] default_stop_addr
2687 /// The address of the instruction where lldb would put a
2688 /// breakpoint normally.
2690 /// @param[in] range_bounds
2691 /// The range which the breakpoint must be contained within.
2692 /// Typically a source line.
2695 /// The address of the next branch instruction, or the end of
2696 /// the range provided in range_bounds. If there are any
2697 /// problems with the disassembly or getting the instructions,
2698 /// the original default_stop_addr will be returned.
2699 //------------------------------------------------------------------
2700 Address AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
2701 AddressRange range_bounds);
2703 //------------------------------------------------------------------
2704 /// Configure asynchronous structured data feature.
2706 /// Each Process type that supports using an asynchronous StructuredData
2707 /// feature should implement this to enable/disable/configure the feature.
2708 /// The default implementation here will always return an error indiciating
2709 /// the feature is unsupported.
2711 /// StructuredDataPlugin implementations will call this to configure
2712 /// a feature that has been reported as being supported.
2714 /// @param[in] type_name
2715 /// The StructuredData type name as previously discovered by
2716 /// the Process-derived instance.
2718 /// @param[in] config
2719 /// Configuration data for the feature being enabled. This config
2720 /// data, which may be null, will be passed along to the feature
2721 /// to process. The feature will dictate whether this is a dictionary,
2722 /// an array or some other object. If the feature needs to be
2723 /// set up properly before it can be enabled, then the config should
2724 /// also take an enable/disable flag.
2727 /// Returns the result of attempting to configure the feature.
2728 //------------------------------------------------------------------
2730 ConfigureStructuredData(const ConstString &type_name,
2731 const StructuredData::ObjectSP &config_sp);
2733 //------------------------------------------------------------------
2734 /// Broadcasts the given structured data object from the given
2737 /// StructuredDataPlugin instances can use this to optionally
2738 /// broadcast any of their data if they want to make it available
2739 /// for clients. The data will come in on the structured data
2740 /// event bit (eBroadcastBitStructuredData).
2742 /// @param[in] object_sp
2743 /// The structured data object to broadcast.
2745 /// @param[in] plugin_sp
2746 /// The plugin that will be reported in the event's plugin
2748 //------------------------------------------------------------------
2749 void BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
2750 const lldb::StructuredDataPluginSP &plugin_sp);
2752 //------------------------------------------------------------------
2753 /// Returns the StructuredDataPlugin associated with a given type
2754 /// name, if there is one.
2756 /// There will only be a plugin for a given StructuredDataType if the
2757 /// debugged process monitor claims that the feature is supported.
2758 /// This is one way to tell whether a feature is available.
2761 /// The plugin if one is available for the specified feature;
2762 /// otherwise, returns an empty shared pointer.
2763 //------------------------------------------------------------------
2764 lldb::StructuredDataPluginSP
2765 GetStructuredDataPlugin(const ConstString &type_name) const;
2768 void SetState(lldb::EventSP &event_sp);
2770 lldb::StateType GetPrivateState();
2772 //------------------------------------------------------------------
2773 /// The "private" side of resuming a process. This doesn't alter the
2774 /// state of m_run_lock, but just causes the process to resume.
2777 /// An Error object describing the success or failure of the resume.
2778 //------------------------------------------------------------------
2779 Error PrivateResume();
2781 //------------------------------------------------------------------
2782 // Called internally
2783 //------------------------------------------------------------------
2784 void CompleteAttach();
2786 //------------------------------------------------------------------
2787 /// Print a user-visible warning one time per Process
2789 /// A facility for printing a warning to the user once per repeat_key.
2791 /// warning_type is from the Process::Warnings enums.
2792 /// repeat_key is a pointer value that will be used to ensure that the
2793 /// warning message is not printed multiple times. For instance, with a
2794 /// warning about a function being optimized, you can pass the CompileUnit
2795 /// pointer to have the warning issued for only the first function in a
2796 /// CU, or the Function pointer to have it issued once for every function,
2797 /// or a Module pointer to have it issued once per Module.
2799 /// Classes outside Process should call a specific PrintWarning method
2800 /// so that the warning strings are all centralized in Process, instead of
2801 /// calling PrintWarning() directly.
2803 /// @param [in] warning_type
2804 /// One of the types defined in Process::Warnings.
2806 /// @param [in] repeat_key
2807 /// A pointer value used to ensure that the warning is only printed once.
2808 /// May be nullptr, indicating that the warning is printed unconditionally
2812 /// printf style format string
2813 //------------------------------------------------------------------
2814 void PrintWarning(uint64_t warning_type, const void *repeat_key,
2815 const char *fmt, ...) __attribute__((format(printf, 4, 5)));
2817 //------------------------------------------------------------------
2818 // NextEventAction provides a way to register an action on the next
2819 // event that is delivered to this process. There is currently only
2820 // one next event action allowed in the process at one time. If a
2821 // new "NextEventAction" is added while one is already present, the
2822 // old action will be discarded (with HandleBeingUnshipped called
2823 // after it is discarded.)
2825 // If you want to resume the process as a result of a resume action,
2826 // call RequestResume, don't call Resume directly.
2827 //------------------------------------------------------------------
2828 class NextEventAction {
2830 typedef enum EventActionResult {
2831 eEventActionSuccess,
2834 } EventActionResult;
2836 NextEventAction(Process *process) : m_process(process) {}
2838 virtual ~NextEventAction() = default;
2840 virtual EventActionResult PerformAction(lldb::EventSP &event_sp) = 0;
2841 virtual void HandleBeingUnshipped() {}
2842 virtual EventActionResult HandleBeingInterrupted() = 0;
2843 virtual const char *GetExitString() = 0;
2844 void RequestResume() { m_process->m_resume_requested = true; }
2850 void SetNextEventAction(Process::NextEventAction *next_event_action) {
2851 if (m_next_event_action_ap.get())
2852 m_next_event_action_ap->HandleBeingUnshipped();
2854 m_next_event_action_ap.reset(next_event_action);
2857 // This is the completer for Attaching:
2858 class AttachCompletionHandler : public NextEventAction {
2860 AttachCompletionHandler(Process *process, uint32_t exec_count);
2862 ~AttachCompletionHandler() override = default;
2864 EventActionResult PerformAction(lldb::EventSP &event_sp) override;
2865 EventActionResult HandleBeingInterrupted() override;
2866 const char *GetExitString() override;
2869 uint32_t m_exec_count;
2870 std::string m_exit_string;
2873 bool PrivateStateThreadIsValid() const {
2874 lldb::StateType state = m_private_state.GetValue();
2875 return state != lldb::eStateInvalid && state != lldb::eStateDetached &&
2876 state != lldb::eStateExited && m_private_state_thread.IsJoinable();
2879 void ForceNextEventDelivery() { m_force_next_event_delivery = true; }
2881 //------------------------------------------------------------------
2882 /// Loads any plugins associated with asynchronous structured data
2883 /// and maps the relevant supported type name to the plugin.
2885 /// Processes can receive asynchronous structured data from the
2886 /// process monitor. This method will load and map any structured
2887 /// data plugins that support the given set of supported type names.
2888 /// Later, if any of these features are enabled, the process monitor
2889 /// is free to generate asynchronous structured data. The data must
2890 /// come in as a single \b StructuredData::Dictionary. That dictionary
2891 /// must have a string field named 'type', with a value that equals
2892 /// the relevant type name string (one of the values in
2893 /// \b supported_type_names).
2895 /// @param[in] supported_type_names
2896 /// An array of zero or more type names. Each must be unique.
2897 /// For each entry in the list, a StructuredDataPlugin will be
2898 /// searched for that supports the structured data type name.
2899 //------------------------------------------------------------------
2900 void MapSupportedStructuredDataPlugins(
2901 const StructuredData::Array &supported_type_names);
2903 //------------------------------------------------------------------
2904 /// Route the incoming structured data dictionary to the right plugin.
2906 /// The incoming structured data must be a dictionary, and it must
2907 /// have a key named 'type' that stores a string value. The string
2908 /// value must be the name of the structured data feature that
2909 /// knows how to handle it.
2911 /// @param[in] object_sp
2912 /// When non-null and pointing to a dictionary, the 'type'
2913 /// key's string value is used to look up the plugin that
2914 /// was registered for that structured data type. It then
2915 /// calls the following method on the StructuredDataPlugin
2919 /// HandleArrivalOfStructuredData(Process &process,
2920 /// const ConstString &type_name,
2921 /// const StructuredData::ObjectSP
2925 /// True if the structured data was routed to a plugin; otherwise,
2927 //------------------------------------------------------------------
2928 bool RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp);
2930 //------------------------------------------------------------------
2932 //------------------------------------------------------------------
2933 typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP>
2934 LanguageRuntimeCollection;
2935 typedef std::unordered_set<const void *> WarningsPointerSet;
2936 typedef std::map<uint64_t, WarningsPointerSet> WarningsCollection;
2938 struct PreResumeCallbackAndBaton {
2939 bool (*callback)(void *);
2941 PreResumeCallbackAndBaton(PreResumeActionCallback in_callback,
2943 : callback(in_callback), baton(in_baton) {}
2944 bool operator== (const PreResumeCallbackAndBaton &rhs) {
2945 return callback == rhs.callback && baton == rhs.baton;
2949 using StructuredDataPluginMap =
2950 std::map<ConstString, lldb::StructuredDataPluginSP>;
2952 //------------------------------------------------------------------
2954 //------------------------------------------------------------------
2955 std::weak_ptr<Target> m_target_sp; ///< The target that owns this process.
2956 ThreadSafeValue<lldb::StateType> m_public_state;
2957 ThreadSafeValue<lldb::StateType>
2958 m_private_state; // The actual state of our process
2959 Broadcaster m_private_state_broadcaster; // This broadcaster feeds state
2960 // changed events into the private
2961 // state thread's listener.
2962 Broadcaster m_private_state_control_broadcaster; // This is the control
2963 // broadcaster, used to
2964 // pause, resume & stop the
2965 // private state thread.
2966 lldb::ListenerSP m_private_state_listener_sp; // This is the listener for the
2967 // private state thread.
2968 HostThread m_private_state_thread; ///< Thread ID for the thread that watches
2969 ///internal state events
2970 ProcessModID m_mod_id; ///< Tracks the state of the process over stops and
2971 ///other alterations.
2972 uint32_t m_process_unique_id; ///< Each lldb_private::Process class that is
2973 ///created gets a unique integer ID that
2974 ///increments with each new instance
2975 uint32_t m_thread_index_id; ///< Each thread is created with a 1 based index
2976 ///that won't get re-used.
2977 std::map<uint64_t, uint32_t> m_thread_id_to_index_id_map;
2978 int m_exit_status; ///< The exit status of the process, or -1 if not set.
2979 std::string m_exit_string; ///< A textual description of why a process exited.
2980 std::mutex m_exit_status_mutex; ///< Mutex so m_exit_status m_exit_string can
2981 ///be safely accessed from multiple threads
2982 std::recursive_mutex m_thread_mutex;
2983 ThreadList m_thread_list_real; ///< The threads for this process as are known
2984 ///to the protocol we are debugging with
2985 ThreadList m_thread_list; ///< The threads for this process as the user will
2986 ///see them. This is usually the same as
2987 ///< m_thread_list_real, but might be different if there is an OS plug-in
2988 ///creating memory threads
2989 ThreadList m_extended_thread_list; ///< Owner for extended threads that may be
2990 ///generated, cleared on natural stops
2991 uint32_t m_extended_thread_stop_id; ///< The natural stop id when
2992 ///extended_thread_list was last updated
2994 m_queue_list; ///< The list of libdispatch queues at a given stop point
2995 uint32_t m_queue_list_stop_id; ///< The natural stop id when queue list was
2997 std::vector<Notifications> m_notifications; ///< The list of notifications
2998 ///that this process can deliver.
2999 std::vector<lldb::addr_t> m_image_tokens;
3000 lldb::ListenerSP m_listener_sp; ///< Shared pointer to the listener used for
3001 ///public events. Can not be empty.
3002 BreakpointSiteList m_breakpoint_site_list; ///< This is the list of breakpoint
3003 ///locations we intend to insert in
3005 lldb::DynamicLoaderUP m_dyld_ap;
3006 lldb::JITLoaderListUP m_jit_loaders_ap;
3007 lldb::DynamicCheckerFunctionsUP m_dynamic_checkers_ap; ///< The functions used
3008 ///by the expression
3009 ///parser to validate
3012 lldb::OperatingSystemUP m_os_ap;
3013 lldb::SystemRuntimeUP m_system_runtime_ap;
3015 m_unix_signals_sp; /// This is the current signal set for this process.
3016 lldb::ABISP m_abi_sp;
3017 lldb::IOHandlerSP m_process_input_reader;
3018 Communication m_stdio_communication;
3019 std::recursive_mutex m_stdio_communication_mutex;
3020 bool m_stdin_forward; /// Remember if stdin must be forwarded to remote debug
3022 std::string m_stdout_data;
3023 std::string m_stderr_data;
3024 std::recursive_mutex m_profile_data_comm_mutex;
3025 std::vector<std::string> m_profile_data;
3026 Predicate<uint32_t> m_iohandler_sync;
3027 MemoryCache m_memory_cache;
3028 AllocatedMemoryCache m_allocated_memory_cache;
3029 bool m_should_detach; /// Should we detach if the process object goes away
3030 /// with an explicit call to Kill or Detach?
3031 LanguageRuntimeCollection m_language_runtimes;
3032 InstrumentationRuntimeCollection m_instrumentation_runtimes;
3033 std::unique_ptr<NextEventAction> m_next_event_action_ap;
3034 std::vector<PreResumeCallbackAndBaton> m_pre_resume_actions;
3035 ProcessRunLock m_public_run_lock;
3036 ProcessRunLock m_private_run_lock;
3037 ArchSpec::StopInfoOverrideCallbackType m_stop_info_override_callback;
3038 bool m_currently_handling_do_on_removals;
3039 bool m_resume_requested; // If m_currently_handling_event or
3040 // m_currently_handling_do_on_removals are true,
3041 // Resume will only request a resume, using this flag
3043 bool m_finalizing; // This is set at the beginning of Process::Finalize() to
3044 // stop functions from looking up or creating things during
3046 bool m_finalize_called; // This is set at the end of Process::Finalize()
3047 bool m_clear_thread_plans_on_stop;
3048 bool m_force_next_event_delivery;
3049 lldb::StateType m_last_broadcast_state; /// This helps with the Public event
3051 /// ShouldBroadcastEvent.
3052 std::map<lldb::addr_t, lldb::addr_t> m_resolved_indirect_addresses;
3053 bool m_destroy_in_process;
3054 bool m_can_interpret_function_calls; // Some targets, e.g the OSX kernel,
3055 // don't support the ability to modify
3057 WarningsCollection m_warnings_issued; // A set of object pointers which have
3058 // already had warnings printed
3059 std::mutex m_run_thread_plan_lock;
3060 StructuredDataPluginMap m_structured_data_plugin_map;
3062 enum { eCanJITDontKnow = 0, eCanJITYes, eCanJITNo } m_can_jit;
3064 size_t RemoveBreakpointOpcodesFromBuffer(lldb::addr_t addr, size_t size,
3065 uint8_t *buf) const;
3067 void SynchronouslyNotifyStateChanged(lldb::StateType state);
3069 void SetPublicState(lldb::StateType new_state, bool restarted);
3071 void SetPrivateState(lldb::StateType state);
3073 bool StartPrivateStateThread(bool is_secondary_thread = false);
3075 void StopPrivateStateThread();
3077 void PausePrivateStateThread();
3079 void ResumePrivateStateThread();
3082 struct PrivateStateThreadArgs {
3083 PrivateStateThreadArgs(Process *p, bool s)
3084 : process(p), is_secondary_thread(s){};
3086 bool is_secondary_thread;
3089 // arg is a pointer to a new'ed PrivateStateThreadArgs structure.
3090 // PrivateStateThread will free it for you.
3091 static lldb::thread_result_t PrivateStateThread(void *arg);
3093 // The starts up the private state thread that will watch for events from the
3095 // Pass true for is_secondary_thread in the case where you have to temporarily
3097 // secondary state thread to handle events from a hand-called function on the
3099 // private state thread.
3101 lldb::thread_result_t RunPrivateStateThread(bool is_secondary_thread);
3104 void HandlePrivateEvent(lldb::EventSP &event_sp);
3106 Error HaltPrivate();
3108 lldb::StateType WaitForProcessStopPrivate(lldb::EventSP &event_sp,
3109 const Timeout<std::micro> &timeout);
3111 // This waits for both the state change broadcaster, and the control
3113 // If control_only, it only waits for the control broadcaster.
3115 bool GetEventsPrivate(lldb::EventSP &event_sp,
3116 const Timeout<std::micro> &timeout, bool control_only);
3119 GetStateChangedEventsPrivate(lldb::EventSP &event_sp,
3120 const Timeout<std::micro> &timeout);
3122 size_t WriteMemoryPrivate(lldb::addr_t addr, const void *buf, size_t size,
3125 void AppendSTDOUT(const char *s, size_t len);
3127 void AppendSTDERR(const char *s, size_t len);
3129 void BroadcastAsyncProfileData(const std::string &one_profile_data);
3131 static void STDIOReadThreadBytesReceived(void *baton, const void *src,
3134 bool PushProcessIOHandler();
3136 bool PopProcessIOHandler();
3138 bool ProcessIOHandlerIsActive();
3140 bool ProcessIOHandlerExists() const {
3141 return static_cast<bool>(m_process_input_reader);
3144 Error StopForDestroyOrDetach(lldb::EventSP &exit_event_sp);
3146 bool StateChangedIsExternallyHijacked();
3148 void LoadOperatingSystemPlugin(bool flush);
3151 //------------------------------------------------------------------
3152 /// This is the part of the event handling that for a process event.
3153 /// It decides what to do with the event and returns true if the
3154 /// event needs to be propagated to the user, and false otherwise.
3155 /// If the event is not propagated, this call will most likely set
3156 /// the target to executing again.
3157 /// There is only one place where this call should be called,
3158 /// HandlePrivateEvent.
3159 /// Don't call it from anywhere else...
3161 /// @param[in] event_ptr
3162 /// This is the event we are handling.
3165 /// Returns \b true if the event should be reported to the
3166 /// user, \b false otherwise.
3167 //------------------------------------------------------------------
3168 bool ShouldBroadcastEvent(Event *event_ptr);
3170 void ControlPrivateStateThread(uint32_t signal);
3172 DISALLOW_COPY_AND_ASSIGN(Process);
3175 } // namespace lldb_private
3177 #endif // liblldb_Process_h_