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/Broadcaster.h"
31 #include "lldb/Core/Communication.h"
32 #include "lldb/Core/Event.h"
33 #include "lldb/Core/Listener.h"
34 #include "lldb/Core/LoadedModuleInfoList.h"
35 #include "lldb/Core/PluginInterface.h"
36 #include "lldb/Core/ThreadSafeValue.h"
37 #include "lldb/Core/UserSettingsController.h"
38 #include "lldb/Host/HostThread.h"
39 #include "lldb/Host/ProcessRunLock.h"
40 #include "lldb/Interpreter/Options.h"
41 #include "lldb/Target/ExecutionContextScope.h"
42 #include "lldb/Target/InstrumentationRuntime.h"
43 #include "lldb/Target/Memory.h"
44 #include "lldb/Target/ProcessInfo.h"
45 #include "lldb/Target/ProcessLaunchInfo.h"
46 #include "lldb/Target/QueueList.h"
47 #include "lldb/Target/ThreadList.h"
48 #include "lldb/Utility/ArchSpec.h"
49 #include "lldb/Utility/NameMatches.h"
50 #include "lldb/Utility/Status.h"
51 #include "lldb/Utility/StructuredData.h"
52 #include "lldb/Utility/TraceOptions.h"
53 #include "lldb/lldb-private.h"
55 #include "llvm/ADT/ArrayRef.h"
57 namespace lldb_private {
59 template <typename B, typename S> struct Range;
61 //----------------------------------------------------------------------
63 //----------------------------------------------------------------------
64 class ProcessProperties : public Properties {
66 // Pass nullptr for "process" if the ProcessProperties are to be the global
68 ProcessProperties(lldb_private::Process *process);
70 ~ProcessProperties() override;
72 bool GetDisableMemoryCache() const;
74 uint64_t GetMemoryCacheLineSize() const;
76 Args GetExtraStartupCommands() const;
78 void SetExtraStartupCommands(const Args &args);
80 FileSpec GetPythonOSPluginPath() const;
82 void SetPythonOSPluginPath(const FileSpec &file);
84 bool GetIgnoreBreakpointsInExpressions() const;
86 void SetIgnoreBreakpointsInExpressions(bool ignore);
88 bool GetUnwindOnErrorInExpressions() const;
90 void SetUnwindOnErrorInExpressions(bool ignore);
92 bool GetStopOnSharedLibraryEvents() const;
94 void SetStopOnSharedLibraryEvents(bool stop);
96 bool GetDetachKeepsStopped() const;
98 void SetDetachKeepsStopped(bool keep_stopped);
100 bool GetWarningsOptimization() const;
102 bool GetStopOnExec() const;
105 static void OptionValueChangedCallback(void *baton,
106 OptionValue *option_value);
108 Process *m_process; // Can be nullptr for global ProcessProperties
111 typedef std::shared_ptr<ProcessProperties> ProcessPropertiesSP;
113 //----------------------------------------------------------------------
114 // ProcessInstanceInfo
116 // Describes an existing process and any discoverable information that
117 // pertains to that process.
118 //----------------------------------------------------------------------
119 class ProcessInstanceInfo : public ProcessInfo {
121 ProcessInstanceInfo()
122 : ProcessInfo(), m_euid(UINT32_MAX), m_egid(UINT32_MAX),
123 m_parent_pid(LLDB_INVALID_PROCESS_ID) {}
125 ProcessInstanceInfo(const char *name, const ArchSpec &arch, lldb::pid_t pid)
126 : ProcessInfo(name, arch, pid), m_euid(UINT32_MAX), m_egid(UINT32_MAX),
127 m_parent_pid(LLDB_INVALID_PROCESS_ID) {}
130 ProcessInfo::Clear();
133 m_parent_pid = LLDB_INVALID_PROCESS_ID;
136 uint32_t GetEffectiveUserID() const { return m_euid; }
138 uint32_t GetEffectiveGroupID() const { return m_egid; }
140 bool EffectiveUserIDIsValid() const { return m_euid != UINT32_MAX; }
142 bool EffectiveGroupIDIsValid() const { return m_egid != UINT32_MAX; }
144 void SetEffectiveUserID(uint32_t uid) { m_euid = uid; }
146 void SetEffectiveGroupID(uint32_t gid) { m_egid = gid; }
148 lldb::pid_t GetParentProcessID() const { return m_parent_pid; }
150 void SetParentProcessID(lldb::pid_t pid) { m_parent_pid = pid; }
152 bool ParentProcessIDIsValid() const {
153 return m_parent_pid != LLDB_INVALID_PROCESS_ID;
156 void Dump(Stream &s, Platform *platform) const;
158 static void DumpTableHeader(Stream &s, Platform *platform, bool show_args,
161 void DumpAsTableRow(Stream &s, Platform *platform, bool show_args,
167 lldb::pid_t m_parent_pid;
170 //----------------------------------------------------------------------
173 // Describes any information that is required to attach to a process.
174 //----------------------------------------------------------------------
176 class ProcessAttachInfo : public ProcessInstanceInfo {
179 : ProcessInstanceInfo(), m_listener_sp(), m_hijack_listener_sp(),
180 m_plugin_name(), m_resume_count(0), m_wait_for_launch(false),
181 m_ignore_existing(true), m_continue_once_attached(false),
182 m_detach_on_error(true), m_async(false) {}
184 ProcessAttachInfo(const ProcessLaunchInfo &launch_info)
185 : ProcessInstanceInfo(), m_listener_sp(), m_hijack_listener_sp(),
186 m_plugin_name(), m_resume_count(0), m_wait_for_launch(false),
187 m_ignore_existing(true), m_continue_once_attached(false),
188 m_detach_on_error(true), m_async(false) {
189 ProcessInfo::operator=(launch_info);
190 SetProcessPluginName(launch_info.GetProcessPluginName());
191 SetResumeCount(launch_info.GetResumeCount());
192 SetListener(launch_info.GetListener());
193 SetHijackListener(launch_info.GetHijackListener());
194 m_detach_on_error = launch_info.GetDetachOnError();
197 bool GetWaitForLaunch() const { return m_wait_for_launch; }
199 void SetWaitForLaunch(bool b) { m_wait_for_launch = b; }
201 bool GetAsync() const { return m_async; }
203 void SetAsync(bool b) { m_async = b; }
205 bool GetIgnoreExisting() const { return m_ignore_existing; }
207 void SetIgnoreExisting(bool b) { m_ignore_existing = b; }
209 bool GetContinueOnceAttached() const { return m_continue_once_attached; }
211 void SetContinueOnceAttached(bool b) { m_continue_once_attached = b; }
213 uint32_t GetResumeCount() const { return m_resume_count; }
215 void SetResumeCount(uint32_t c) { m_resume_count = c; }
217 const char *GetProcessPluginName() const {
218 return (m_plugin_name.empty() ? nullptr : m_plugin_name.c_str());
221 void SetProcessPluginName(llvm::StringRef plugin) { m_plugin_name = plugin; }
224 ProcessInstanceInfo::Clear();
225 m_plugin_name.clear();
227 m_wait_for_launch = false;
228 m_ignore_existing = true;
229 m_continue_once_attached = false;
232 bool ProcessInfoSpecified() const {
233 if (GetExecutableFile())
235 if (GetProcessID() != LLDB_INVALID_PROCESS_ID)
237 if (GetParentProcessID() != LLDB_INVALID_PROCESS_ID)
242 lldb::ListenerSP GetHijackListener() const { return m_hijack_listener_sp; }
244 void SetHijackListener(const lldb::ListenerSP &listener_sp) {
245 m_hijack_listener_sp = listener_sp;
248 bool GetDetachOnError() const { return m_detach_on_error; }
250 void SetDetachOnError(bool enable) { m_detach_on_error = enable; }
252 // Get and set the actual listener that will be used for the process events
253 lldb::ListenerSP GetListener() const { return m_listener_sp; }
255 void SetListener(const lldb::ListenerSP &listener_sp) {
256 m_listener_sp = listener_sp;
259 lldb::ListenerSP GetListenerForProcess(Debugger &debugger);
262 lldb::ListenerSP m_listener_sp;
263 lldb::ListenerSP m_hijack_listener_sp;
264 std::string m_plugin_name;
265 uint32_t m_resume_count; // How many times do we resume after launching
266 bool m_wait_for_launch;
267 bool m_ignore_existing;
268 bool m_continue_once_attached; // Supports the use-case scenario of
269 // immediately continuing the process once
271 bool m_detach_on_error; // If we are debugging remotely, instruct the stub to
272 // detach rather than killing the target on error.
273 bool m_async; // Use an async attach where we start the attach and return
274 // immediately (used by GUI programs with --waitfor so they can
275 // call SBProcess::Stop() to cancel attach)
278 class ProcessLaunchCommandOptions : public Options {
280 ProcessLaunchCommandOptions() : Options() {
281 // Keep default values of all options in one place: OptionParsingStarting ()
282 OptionParsingStarting(nullptr);
285 ~ProcessLaunchCommandOptions() override = default;
287 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
288 ExecutionContext *execution_context) override;
290 void OptionParsingStarting(ExecutionContext *execution_context) override {
292 disable_aslr = eLazyBoolCalculate;
295 llvm::ArrayRef<OptionDefinition> GetDefinitions() override;
297 // Instance variables to hold the values for command options.
299 ProcessLaunchInfo launch_info;
300 lldb_private::LazyBool disable_aslr;
303 //----------------------------------------------------------------------
304 // ProcessInstanceInfoMatch
306 // A class to help matching one ProcessInstanceInfo to another.
307 //----------------------------------------------------------------------
309 class ProcessInstanceInfoMatch {
311 ProcessInstanceInfoMatch()
312 : m_match_info(), m_name_match_type(NameMatch::Ignore),
313 m_match_all_users(false) {}
315 ProcessInstanceInfoMatch(const char *process_name,
316 NameMatch process_name_match_type)
317 : m_match_info(), m_name_match_type(process_name_match_type),
318 m_match_all_users(false) {
319 m_match_info.GetExecutableFile().SetFile(process_name, false);
322 ProcessInstanceInfo &GetProcessInfo() { return m_match_info; }
324 const ProcessInstanceInfo &GetProcessInfo() const { return m_match_info; }
326 bool GetMatchAllUsers() const { return m_match_all_users; }
328 void SetMatchAllUsers(bool b) { m_match_all_users = b; }
330 NameMatch GetNameMatchType() const { return m_name_match_type; }
332 void SetNameMatchType(NameMatch name_match_type) {
333 m_name_match_type = name_match_type;
336 bool NameMatches(const char *process_name) const;
338 bool Matches(const ProcessInstanceInfo &proc_info) const;
340 bool MatchAllProcesses() const;
344 ProcessInstanceInfo m_match_info;
345 NameMatch m_name_match_type;
346 bool m_match_all_users;
349 class ProcessInstanceInfoList {
351 ProcessInstanceInfoList() = default;
353 void Clear() { m_infos.clear(); }
355 size_t GetSize() { return m_infos.size(); }
357 void Append(const ProcessInstanceInfo &info) { m_infos.push_back(info); }
359 const char *GetProcessNameAtIndex(size_t idx) {
360 return ((idx < m_infos.size()) ? m_infos[idx].GetName() : nullptr);
363 size_t GetProcessNameLengthAtIndex(size_t idx) {
364 return ((idx < m_infos.size()) ? m_infos[idx].GetNameLength() : 0);
367 lldb::pid_t GetProcessIDAtIndex(size_t idx) {
368 return ((idx < m_infos.size()) ? m_infos[idx].GetProcessID() : 0);
371 bool GetInfoAtIndex(size_t idx, ProcessInstanceInfo &info) {
372 if (idx < m_infos.size()) {
379 // You must ensure "idx" is valid before calling this function
380 const ProcessInstanceInfo &GetProcessInfoAtIndex(size_t idx) const {
381 assert(idx < m_infos.size());
386 typedef std::vector<ProcessInstanceInfo> collection;
390 // This class tracks the Modification state of the process. Things that can
392 // the program are running the program (which will up the StopID) and writing
394 // will up the MemoryID.)
395 // FIXME: Should we also include modification of register states?
398 friend bool operator==(const ProcessModID &lhs, const ProcessModID &rhs);
402 : m_stop_id(0), m_last_natural_stop_id(0), m_resume_id(0), m_memory_id(0),
403 m_last_user_expression_resume(0), m_running_user_expression(false) {}
405 ProcessModID(const ProcessModID &rhs)
406 : m_stop_id(rhs.m_stop_id), m_memory_id(rhs.m_memory_id) {}
408 const ProcessModID &operator=(const ProcessModID &rhs) {
410 m_stop_id = rhs.m_stop_id;
411 m_memory_id = rhs.m_memory_id;
416 ~ProcessModID() = default;
420 if (!IsLastResumeForUserExpression())
421 m_last_natural_stop_id++;
424 void BumpMemoryID() { m_memory_id++; }
426 void BumpResumeID() {
428 if (m_running_user_expression > 0)
429 m_last_user_expression_resume = m_resume_id;
432 uint32_t GetStopID() const { return m_stop_id; }
433 uint32_t GetLastNaturalStopID() const { return m_last_natural_stop_id; }
434 uint32_t GetMemoryID() const { return m_memory_id; }
435 uint32_t GetResumeID() const { return m_resume_id; }
436 uint32_t GetLastUserExpressionResumeID() const {
437 return m_last_user_expression_resume;
440 bool MemoryIDEqual(const ProcessModID &compare) const {
441 return m_memory_id == compare.m_memory_id;
444 bool StopIDEqual(const ProcessModID &compare) const {
445 return m_stop_id == compare.m_stop_id;
448 void SetInvalid() { m_stop_id = UINT32_MAX; }
450 bool IsValid() const { return m_stop_id != UINT32_MAX; }
452 bool IsLastResumeForUserExpression() const {
453 // If we haven't yet resumed the target, then it can't be for a user
455 if (m_resume_id == 0)
458 return m_resume_id == m_last_user_expression_resume;
461 void SetRunningUserExpression(bool on) {
463 m_running_user_expression++;
465 m_running_user_expression--;
468 void SetStopEventForLastNaturalStopID(lldb::EventSP event_sp) {
469 m_last_natural_stop_event = event_sp;
472 lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const {
473 if (stop_id == m_last_natural_stop_id)
474 return m_last_natural_stop_event;
475 return lldb::EventSP();
480 uint32_t m_last_natural_stop_id;
481 uint32_t m_resume_id;
482 uint32_t m_memory_id;
483 uint32_t m_last_user_expression_resume;
484 uint32_t m_running_user_expression;
485 lldb::EventSP m_last_natural_stop_event;
488 inline bool operator==(const ProcessModID &lhs, const ProcessModID &rhs) {
489 if (lhs.StopIDEqual(rhs) && lhs.MemoryIDEqual(rhs))
495 inline bool operator!=(const ProcessModID &lhs, const ProcessModID &rhs) {
496 return (!lhs.StopIDEqual(rhs) || !lhs.MemoryIDEqual(rhs));
499 //----------------------------------------------------------------------
500 /// @class Process Process.h "lldb/Target/Process.h"
501 /// @brief A plug-in interface definition class for debugging a process.
502 //----------------------------------------------------------------------
503 class Process : public std::enable_shared_from_this<Process>,
504 public ProcessProperties,
507 public ExecutionContextScope,
508 public PluginInterface {
509 friend class FunctionCaller; // For WaitForStateChangeEventsPrivate
510 friend class Debugger; // For PopProcessIOHandler and ProcessIOHandlerIsActive
511 friend class DynamicLoader; // For LoadOperatingSystemPlugin
512 friend class ProcessEventData;
513 friend class StopInfo;
515 friend class ThreadList;
518 //------------------------------------------------------------------
519 /// Broadcaster event bits definitions.
520 //------------------------------------------------------------------
522 eBroadcastBitStateChanged = (1 << 0),
523 eBroadcastBitInterrupt = (1 << 1),
524 eBroadcastBitSTDOUT = (1 << 2),
525 eBroadcastBitSTDERR = (1 << 3),
526 eBroadcastBitProfileData = (1 << 4),
527 eBroadcastBitStructuredData = (1 << 5),
531 eBroadcastInternalStateControlStop = (1 << 0),
532 eBroadcastInternalStateControlPause = (1 << 1),
533 eBroadcastInternalStateControlResume = (1 << 2)
536 //------------------------------------------------------------------
537 /// Process warning types.
538 //------------------------------------------------------------------
539 enum Warnings { eWarningsOptimization = 1 };
541 typedef Range<lldb::addr_t, lldb::addr_t> LoadRange;
542 // We use a read/write lock to allow on or more clients to
543 // access the process state while the process is stopped (reader).
544 // We lock the write lock to control access to the process
545 // while it is running (readers, or clients that want the process
546 // stopped can block waiting for the process to stop, or just
547 // try to lock it to see if they can immediately access the stopped
548 // process. If the try read lock fails, then the process is running.
549 typedef ProcessRunLock::ProcessRunLocker StopLocker;
551 // These two functions fill out the Broadcaster interface:
553 static ConstString &GetStaticBroadcasterClass();
555 ConstString &GetBroadcasterClass() const override {
556 return GetStaticBroadcasterClass();
559 //------------------------------------------------------------------
560 /// A notification structure that can be used by clients to listen
561 /// for changes in a process's lifetime.
563 /// @see RegisterNotificationCallbacks (const Notifications&)
564 /// @see UnregisterNotificationCallbacks (const Notifications&)
565 //------------------------------------------------------------------
569 void (*initialize)(void *baton, Process *process);
570 void (*process_state_changed)(void *baton, Process *process,
571 lldb::StateType state);
574 class ProcessEventData : public EventData {
575 friend class Process;
579 ProcessEventData(const lldb::ProcessSP &process, lldb::StateType state);
581 ~ProcessEventData() override;
583 static const ConstString &GetFlavorString();
585 const ConstString &GetFlavor() const override;
587 lldb::ProcessSP GetProcessSP() const { return m_process_wp.lock(); }
589 lldb::StateType GetState() const { return m_state; }
590 bool GetRestarted() const { return m_restarted; }
592 size_t GetNumRestartedReasons() { return m_restarted_reasons.size(); }
594 const char *GetRestartedReasonAtIndex(size_t idx) {
595 return ((idx < m_restarted_reasons.size())
596 ? m_restarted_reasons[idx].c_str()
600 bool GetInterrupted() const { return m_interrupted; }
602 void Dump(Stream *s) const override;
604 void DoOnRemoval(Event *event_ptr) override;
606 static const Process::ProcessEventData *
607 GetEventDataFromEvent(const Event *event_ptr);
609 static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr);
611 static lldb::StateType GetStateFromEvent(const Event *event_ptr);
613 static bool GetRestartedFromEvent(const Event *event_ptr);
615 static size_t GetNumRestartedReasons(const Event *event_ptr);
617 static const char *GetRestartedReasonAtIndex(const Event *event_ptr,
620 static void AddRestartedReason(Event *event_ptr, const char *reason);
622 static void SetRestartedInEvent(Event *event_ptr, bool new_value);
624 static bool GetInterruptedFromEvent(const Event *event_ptr);
626 static void SetInterruptedInEvent(Event *event_ptr, bool new_value);
628 static bool SetUpdateStateOnRemoval(Event *event_ptr);
631 void SetUpdateStateOnRemoval() { m_update_state++; }
633 void SetRestarted(bool new_value) { m_restarted = new_value; }
635 void SetInterrupted(bool new_value) { m_interrupted = new_value; }
637 void AddRestartedReason(const char *reason) {
638 m_restarted_reasons.push_back(reason);
641 lldb::ProcessWP m_process_wp;
642 lldb::StateType m_state;
643 std::vector<std::string> m_restarted_reasons;
644 bool m_restarted; // For "eStateStopped" events, this is true if the target
645 // was automatically restarted.
649 DISALLOW_COPY_AND_ASSIGN(ProcessEventData);
653 //------------------------------------------------------------------
654 /// Construct with a shared pointer to a target, and the Process listener.
655 /// Uses the Host UnixSignalsSP by default.
656 //------------------------------------------------------------------
657 Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp);
659 //------------------------------------------------------------------
660 /// Construct with a shared pointer to a target, the Process listener,
661 /// and the appropriate UnixSignalsSP for the process.
662 //------------------------------------------------------------------
663 Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp,
664 const lldb::UnixSignalsSP &unix_signals_sp);
666 //------------------------------------------------------------------
669 /// The destructor is virtual since this class is designed to be
670 /// inherited from by the plug-in instance.
671 //------------------------------------------------------------------
674 static void SettingsInitialize();
676 static void SettingsTerminate();
678 static const ProcessPropertiesSP &GetGlobalProperties();
680 //------------------------------------------------------------------
681 /// Find a Process plug-in that can debug \a module using the
682 /// currently selected architecture.
684 /// Scans all loaded plug-in interfaces that implement versions of
685 /// the Process plug-in interface and returns the first instance
686 /// that can debug the file.
688 /// @param[in] module_sp
689 /// The module shared pointer that this process will debug.
691 /// @param[in] plugin_name
692 /// If nullptr, select the best plug-in for the binary. If non-nullptr
693 /// then look for a plugin whose PluginInfo's name matches
696 /// @see Process::CanDebug ()
697 //------------------------------------------------------------------
698 static lldb::ProcessSP FindPlugin(lldb::TargetSP target_sp,
699 llvm::StringRef plugin_name,
700 lldb::ListenerSP listener_sp,
701 const FileSpec *crash_file_path);
703 //------------------------------------------------------------------
704 /// Static function that can be used with the \b host function
705 /// Host::StartMonitoringChildProcess ().
707 /// This function can be used by lldb_private::Process subclasses
708 /// when they want to watch for a local process and have its exit
709 /// status automatically set when the host child process exits.
710 /// Subclasses should call Host::StartMonitoringChildProcess ()
712 /// callback = Process::SetHostProcessExitStatus
713 /// pid = Process::GetID()
714 /// monitor_signals = false
715 //------------------------------------------------------------------
717 SetProcessExitStatus(lldb::pid_t pid, // The process ID we want to monitor
719 int signo, // Zero for no signal
720 int status); // Exit value of process if signal is zero
722 lldb::ByteOrder GetByteOrder() const;
724 uint32_t GetAddressByteSize() const;
726 uint32_t GetUniqueID() const { return m_process_unique_id; }
728 //------------------------------------------------------------------
729 /// Check if a plug-in instance can debug the file in \a module.
731 /// Each plug-in is given a chance to say whether it can debug
732 /// the file in \a module. If the Process plug-in instance can
733 /// debug a file on the current system, it should return \b true.
736 /// Returns \b true if this Process plug-in instance can
737 /// debug the executable, \b false otherwise.
738 //------------------------------------------------------------------
739 virtual bool CanDebug(lldb::TargetSP target,
740 bool plugin_specified_by_name) = 0;
742 //------------------------------------------------------------------
743 /// This object is about to be destroyed, do any necessary cleanup.
745 /// Subclasses that override this method should always call this
746 /// superclass method.
747 //------------------------------------------------------------------
748 virtual void Finalize();
750 //------------------------------------------------------------------
751 /// Return whether this object is valid (i.e. has not been finalized.)
754 /// Returns \b true if this Process has not been finalized
755 /// and \b false otherwise.
756 //------------------------------------------------------------------
757 bool IsValid() const { return !m_finalize_called; }
759 //------------------------------------------------------------------
760 /// Return a multi-word command object that can be used to expose
761 /// plug-in specific commands.
763 /// This object will be used to resolve plug-in commands and can be
764 /// triggered by a call to:
766 /// (lldb) process commmand <args>
769 /// A CommandObject which can be one of the concrete subclasses
770 /// of CommandObject like CommandObjectRaw, CommandObjectParsed,
771 /// or CommandObjectMultiword.
772 //------------------------------------------------------------------
773 virtual CommandObject *GetPluginCommandObject() { return nullptr; }
775 //------------------------------------------------------------------
776 /// Launch a new process.
778 /// Launch a new process by spawning a new process using the
779 /// target object's executable module's file as the file to launch.
781 /// This function is not meant to be overridden by Process
782 /// subclasses. It will first call Process::WillLaunch (Module *)
783 /// and if that returns \b true, Process::DoLaunch (Module*,
784 /// char const *[],char const *[],const char *,const char *,
785 /// const char *) will be called to actually do the launching. If
786 /// DoLaunch returns \b true, then Process::DidLaunch() will be
789 /// @param[in] launch_info
790 /// Details regarding the environment, STDIN/STDOUT/STDERR
791 /// redirection, working path, etc. related to the requested launch.
794 /// An error object. Call GetID() to get the process ID if
795 /// the error object is success.
796 //------------------------------------------------------------------
797 virtual Status Launch(ProcessLaunchInfo &launch_info);
799 virtual Status LoadCore();
801 virtual Status DoLoadCore() {
803 error.SetErrorStringWithFormat(
804 "error: %s does not support loading core files.",
805 GetPluginName().GetCString());
809 //------------------------------------------------------------------
810 /// Get the dynamic loader plug-in for this process.
812 /// The default action is to let the DynamicLoader plug-ins check
813 /// the main executable and the DynamicLoader will select itself
814 /// automatically. Subclasses can override this if inspecting the
815 /// executable is not desired, or if Process subclasses can only
816 /// use a specific DynamicLoader plug-in.
817 //------------------------------------------------------------------
818 virtual DynamicLoader *GetDynamicLoader();
820 //------------------------------------------------------------------
821 // Returns AUXV structure found in many ELF-based environments.
823 // The default action is to return an empty data buffer.
826 // A data buffer containing the contents of the AUXV data.
827 //------------------------------------------------------------------
828 virtual const lldb::DataBufferSP GetAuxvData();
830 //------------------------------------------------------------------
831 /// Sometimes processes know how to retrieve and load shared libraries.
832 /// This is normally done by DynamicLoader plug-ins, but sometimes the
833 /// connection to the process allows retrieving this information. The
834 /// dynamic loader plug-ins can use this function if they can't
835 /// determine the current shared library load state.
838 /// The number of shared libraries that were loaded
839 //------------------------------------------------------------------
840 virtual size_t LoadModules() { return 0; }
842 virtual size_t LoadModules(LoadedModuleInfoList &) { return 0; }
845 virtual JITLoaderList &GetJITLoaders();
848 //------------------------------------------------------------------
849 /// Get the system runtime plug-in for this process.
852 /// Returns a pointer to the SystemRuntime plugin for this Process
853 /// if one is available. Else returns nullptr.
854 //------------------------------------------------------------------
855 virtual SystemRuntime *GetSystemRuntime();
857 //------------------------------------------------------------------
858 /// Attach to an existing process using the process attach info.
860 /// This function is not meant to be overridden by Process
861 /// subclasses. It will first call WillAttach (lldb::pid_t)
862 /// or WillAttach (const char *), and if that returns \b
863 /// true, DoAttach (lldb::pid_t) or DoAttach (const char *) will
864 /// be called to actually do the attach. If DoAttach returns \b
865 /// true, then Process::DidAttach() will be called.
868 /// The process ID that we should attempt to attach to.
871 /// Returns \a pid if attaching was successful, or
872 /// LLDB_INVALID_PROCESS_ID if attaching fails.
873 //------------------------------------------------------------------
874 virtual Status Attach(ProcessAttachInfo &attach_info);
876 //------------------------------------------------------------------
877 /// Attach to a remote system via a URL
880 /// A stream where output intended for the user
881 /// (if the driver has a way to display that) generated during
882 /// the connection. This may be nullptr if no output is needed.A
884 /// @param[in] remote_url
885 /// The URL format that we are connecting to.
888 /// Returns an error object.
889 //------------------------------------------------------------------
890 virtual Status ConnectRemote(Stream *strm, llvm::StringRef remote_url);
892 bool GetShouldDetach() const { return m_should_detach; }
894 void SetShouldDetach(bool b) { m_should_detach = b; }
896 //------------------------------------------------------------------
897 /// Get the image information address for the current process.
899 /// Some runtimes have system functions that can help dynamic
900 /// loaders locate the dynamic loader information needed to observe
901 /// shared libraries being loaded or unloaded. This function is
902 /// in the Process interface (as opposed to the DynamicLoader
903 /// interface) to ensure that remote debugging can take advantage of
904 /// this functionality.
907 /// The address of the dynamic loader information, or
908 /// LLDB_INVALID_ADDRESS if this is not supported by this
910 //------------------------------------------------------------------
911 virtual lldb::addr_t GetImageInfoAddress();
913 //------------------------------------------------------------------
914 /// Called when the process is about to broadcast a public stop.
916 /// There are public and private stops. Private stops are when the
917 /// process is doing things like stepping and the client doesn't
918 /// need to know about starts and stop that implement a thread plan.
919 /// Single stepping over a source line in code might end up being
920 /// implemented by one or more process starts and stops. Public stops
921 /// are when clients will be notified that the process is stopped.
922 /// These events typically trigger UI updates (thread stack frames to
923 /// be displayed, variables to be displayed, and more). This function
924 /// can be overriden and allows process subclasses to do something
925 /// before the eBroadcastBitStateChanged event is sent to public
927 //------------------------------------------------------------------
928 virtual void WillPublicStop() {}
930 //------------------------------------------------------------------
931 /// Register for process and thread notifications.
933 /// Clients can register notification callbacks by filling out a
934 /// Process::Notifications structure and calling this function.
936 /// @param[in] callbacks
937 /// A structure that contains the notification baton and
938 /// callback functions.
940 /// @see Process::Notifications
941 //------------------------------------------------------------------
943 void RegisterNotificationCallbacks(const Process::Notifications &callbacks);
946 //------------------------------------------------------------------
947 /// Unregister for process and thread notifications.
949 /// Clients can unregister notification callbacks by passing a copy of
950 /// the original baton and callbacks in \a callbacks.
952 /// @param[in] callbacks
953 /// A structure that contains the notification baton and
954 /// callback functions.
957 /// Returns \b true if the notification callbacks were
958 /// successfully removed from the process, \b false otherwise.
960 /// @see Process::Notifications
961 //------------------------------------------------------------------
963 bool UnregisterNotificationCallbacks(const Process::Notifications &callbacks);
966 //==================================================================
967 // Built in Process Control functions
968 //==================================================================
969 //------------------------------------------------------------------
970 /// Resumes all of a process's threads as configured using the
971 /// Thread run control functions.
973 /// Threads for a process should be updated with one of the run
974 /// control actions (resume, step, or suspend) that they should take
975 /// when the process is resumed. If no run control action is given
976 /// to a thread it will be resumed by default.
978 /// This function is not meant to be overridden by Process
979 /// subclasses. This function will take care of disabling any
980 /// breakpoints that threads may be stopped at, single stepping, and
981 /// re-enabling breakpoints, and enabling the basic flow control
982 /// that the plug-in instances need not worry about.
984 /// N.B. This function also sets the Write side of the Run Lock,
985 /// which is unset when the corresponding stop event is pulled off
986 /// the Public Event Queue. If you need to resume the process without
987 /// setting the Run Lock, use PrivateResume (though you should only do
988 /// that from inside the Process class.
991 /// Returns an error object.
993 /// @see Thread:Resume()
994 /// @see Thread:Step()
995 /// @see Thread:Suspend()
996 //------------------------------------------------------------------
999 Status ResumeSynchronous(Stream *stream);
1001 //------------------------------------------------------------------
1002 /// Halts a running process.
1004 /// This function is not meant to be overridden by Process
1006 /// If the process is successfully halted, a eStateStopped
1007 /// process event with GetInterrupted will be broadcast. If false, we will
1008 /// halt the process with no events generated by the halt.
1010 /// @param[in] clear_thread_plans
1011 /// If true, when the process stops, clear all thread plans.
1013 /// @param[in] use_run_lock
1014 /// Whether to release the run lock after the stop.
1017 /// Returns an error object. If the error is empty, the process is
1019 /// otherwise the halt has failed.
1020 //------------------------------------------------------------------
1021 Status Halt(bool clear_thread_plans = false, bool use_run_lock = true);
1023 //------------------------------------------------------------------
1024 /// Detaches from a running or stopped process.
1026 /// This function is not meant to be overridden by Process
1029 /// @param[in] keep_stopped
1030 /// If true, don't resume the process on detach.
1033 /// Returns an error object.
1034 //------------------------------------------------------------------
1035 Status Detach(bool keep_stopped);
1037 //------------------------------------------------------------------
1038 /// Kills the process and shuts down all threads that were spawned
1039 /// to track and monitor the process.
1041 /// This function is not meant to be overridden by Process
1044 /// @param[in] force_kill
1045 /// Whether lldb should force a kill (instead of a detach) from
1046 /// the inferior process. Normally if lldb launched a binary and
1047 /// Destory is called, lldb kills it. If lldb attached to a
1048 /// running process and Destory is called, lldb detaches. If
1049 /// this behavior needs to be over-ridden, this is the bool that
1053 /// Returns an error object.
1054 //------------------------------------------------------------------
1055 Status Destroy(bool force_kill);
1057 //------------------------------------------------------------------
1058 /// Sends a process a UNIX signal \a signal.
1060 /// This function is not meant to be overridden by Process
1064 /// Returns an error object.
1065 //------------------------------------------------------------------
1066 Status Signal(int signal);
1068 void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp);
1070 const lldb::UnixSignalsSP &GetUnixSignals();
1072 //==================================================================
1073 // Plug-in Process Control Overrides
1074 //==================================================================
1076 //------------------------------------------------------------------
1077 /// Called before attaching to a process.
1079 /// Allow Process plug-ins to execute some code before attaching a
1083 /// Returns an error object.
1084 //------------------------------------------------------------------
1085 virtual Status WillAttachToProcessWithID(lldb::pid_t pid) { return Status(); }
1087 //------------------------------------------------------------------
1088 /// Called before attaching to a process.
1090 /// Allow Process plug-ins to execute some code before attaching a
1094 /// Returns an error object.
1095 //------------------------------------------------------------------
1096 virtual Status WillAttachToProcessWithName(const char *process_name,
1097 bool wait_for_launch) {
1101 //------------------------------------------------------------------
1102 /// Attach to a remote system via a URL
1105 /// A stream where output intended for the user
1106 /// (if the driver has a way to display that) generated during
1107 /// the connection. This may be nullptr if no output is needed.A
1109 /// @param[in] remote_url
1110 /// The URL format that we are connecting to.
1113 /// Returns an error object.
1114 //------------------------------------------------------------------
1115 virtual Status DoConnectRemote(Stream *strm, llvm::StringRef remote_url) {
1117 error.SetErrorString("remote connections are not supported");
1121 //------------------------------------------------------------------
1122 /// Attach to an existing process using a process ID.
1125 /// The process ID that we should attempt to attach to.
1127 /// @param[in] attach_info
1128 /// Information on how to do the attach. For example, GetUserID()
1129 /// will return the uid to attach as.
1132 /// Returns a successful Status attaching was successful, or
1133 /// an appropriate (possibly platform-specific) error code if
1134 /// attaching fails.
1135 /// hanming : need flag
1136 //------------------------------------------------------------------
1137 virtual Status DoAttachToProcessWithID(lldb::pid_t pid,
1138 const ProcessAttachInfo &attach_info) {
1140 error.SetErrorStringWithFormat(
1141 "error: %s does not support attaching to a process by pid",
1142 GetPluginName().GetCString());
1146 //------------------------------------------------------------------
1147 /// Attach to an existing process using a partial process name.
1149 /// @param[in] process_name
1150 /// The name of the process to attach to.
1152 /// @param[in] attach_info
1153 /// Information on how to do the attach. For example, GetUserID()
1154 /// will return the uid to attach as.
1157 /// Returns a successful Status attaching was successful, or
1158 /// an appropriate (possibly platform-specific) error code if
1159 /// attaching fails.
1160 //------------------------------------------------------------------
1162 DoAttachToProcessWithName(const char *process_name,
1163 const ProcessAttachInfo &attach_info) {
1165 error.SetErrorString("attach by name is not supported");
1169 //------------------------------------------------------------------
1170 /// Called after attaching a process.
1172 /// @param[in] process_arch
1173 /// If you can figure out the process architecture after attach, fill it
1176 /// Allow Process plug-ins to execute some code after attaching to
1178 //------------------------------------------------------------------
1179 virtual void DidAttach(ArchSpec &process_arch) { process_arch.Clear(); }
1181 //------------------------------------------------------------------
1182 /// Called after a process re-execs itself.
1184 /// Allow Process plug-ins to execute some code after a process has
1185 /// exec'ed itself. Subclasses typically should override DoDidExec()
1186 /// as the lldb_private::Process class needs to remove its dynamic
1187 /// loader, runtime, ABI and other plug-ins, as well as unload all
1188 /// shared libraries.
1189 //------------------------------------------------------------------
1190 virtual void DidExec();
1192 //------------------------------------------------------------------
1193 /// Subclasses of Process should implement this function if they
1194 /// need to do anything after a process exec's itself.
1195 //------------------------------------------------------------------
1196 virtual void DoDidExec() {}
1198 //------------------------------------------------------------------
1199 /// Called before launching to a process.
1201 /// Allow Process plug-ins to execute some code before launching a
1205 /// Returns an error object.
1206 //------------------------------------------------------------------
1207 virtual Status WillLaunch(Module *module) { return Status(); }
1209 //------------------------------------------------------------------
1210 /// Launch a new process.
1212 /// Launch a new process by spawning a new process using
1213 /// \a exe_module's file as the file to launch. Launch details are
1214 /// provided in \a launch_info.
1216 /// @param[in] exe_module
1217 /// The module from which to extract the file specification and
1220 /// @param[in] launch_info
1221 /// Details (e.g. arguments, stdio redirection, etc.) for the
1222 /// requested launch.
1225 /// An Status instance indicating success or failure of the
1227 //------------------------------------------------------------------
1228 virtual Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) {
1230 error.SetErrorStringWithFormat(
1231 "error: %s does not support launching processes",
1232 GetPluginName().GetCString());
1236 //------------------------------------------------------------------
1237 /// Called after launching a process.
1239 /// Allow Process plug-ins to execute some code after launching
1241 //------------------------------------------------------------------
1242 virtual void DidLaunch() {}
1244 //------------------------------------------------------------------
1245 /// Called before resuming to a process.
1247 /// Allow Process plug-ins to execute some code before resuming a
1251 /// Returns an error object.
1252 //------------------------------------------------------------------
1253 virtual Status WillResume() { return Status(); }
1255 //------------------------------------------------------------------
1256 /// Resumes all of a process's threads as configured using the
1257 /// Thread run control functions.
1259 /// Threads for a process should be updated with one of the run
1260 /// control actions (resume, step, or suspend) that they should take
1261 /// when the process is resumed. If no run control action is given
1262 /// to a thread it will be resumed by default.
1265 /// Returns \b true if the process successfully resumes using
1266 /// the thread run control actions, \b false otherwise.
1268 /// @see Thread:Resume()
1269 /// @see Thread:Step()
1270 /// @see Thread:Suspend()
1271 //------------------------------------------------------------------
1272 virtual Status DoResume() {
1274 error.SetErrorStringWithFormat(
1275 "error: %s does not support resuming processes",
1276 GetPluginName().GetCString());
1280 //------------------------------------------------------------------
1281 /// Called after resuming a process.
1283 /// Allow Process plug-ins to execute some code after resuming
1285 //------------------------------------------------------------------
1286 virtual void DidResume() {}
1288 //------------------------------------------------------------------
1289 /// Called before halting to a process.
1291 /// Allow Process plug-ins to execute some code before halting a
1295 /// Returns an error object.
1296 //------------------------------------------------------------------
1297 virtual Status WillHalt() { return Status(); }
1299 //------------------------------------------------------------------
1300 /// Halts a running process.
1302 /// DoHalt must produce one and only one stop StateChanged event if it
1304 /// stops the process. If the stop happens through some natural event (for
1305 /// instance a SIGSTOP), then forwarding that event will do. Otherwise, you
1307 /// generate the event manually. This function is called from the context of
1309 /// private state thread.
1311 /// @param[out] caused_stop
1312 /// If true, then this Halt caused the stop, otherwise, the
1313 /// process was already stopped.
1316 /// Returns \b true if the process successfully halts, \b false
1318 //------------------------------------------------------------------
1319 virtual Status DoHalt(bool &caused_stop) {
1321 error.SetErrorStringWithFormat(
1322 "error: %s does not support halting processes",
1323 GetPluginName().GetCString());
1327 //------------------------------------------------------------------
1328 /// Called after halting a process.
1330 /// Allow Process plug-ins to execute some code after halting
1332 //------------------------------------------------------------------
1333 virtual void DidHalt() {}
1335 //------------------------------------------------------------------
1336 /// Called before detaching from a process.
1338 /// Allow Process plug-ins to execute some code before detaching
1342 /// Returns an error object.
1343 //------------------------------------------------------------------
1344 virtual Status WillDetach() { return Status(); }
1346 //------------------------------------------------------------------
1347 /// Detaches from a running or stopped process.
1350 /// Returns \b true if the process successfully detaches, \b
1351 /// false otherwise.
1352 //------------------------------------------------------------------
1353 virtual Status DoDetach(bool keep_stopped) {
1355 error.SetErrorStringWithFormat(
1356 "error: %s does not support detaching from processes",
1357 GetPluginName().GetCString());
1361 //------------------------------------------------------------------
1362 /// Called after detaching from a process.
1364 /// Allow Process plug-ins to execute some code after detaching
1366 //------------------------------------------------------------------
1367 virtual void DidDetach() {}
1369 virtual bool DetachRequiresHalt() { return false; }
1371 //------------------------------------------------------------------
1372 /// Called before sending a signal to a process.
1374 /// Allow Process plug-ins to execute some code before sending a
1375 /// signal to a process.
1378 /// Returns no error if it is safe to proceed with a call to
1379 /// Process::DoSignal(int), otherwise an error describing what
1380 /// prevents the signal from being sent.
1381 //------------------------------------------------------------------
1382 virtual Status WillSignal() { return Status(); }
1384 //------------------------------------------------------------------
1385 /// Sends a process a UNIX signal \a signal.
1388 /// Returns an error object.
1389 //------------------------------------------------------------------
1390 virtual Status DoSignal(int signal) {
1392 error.SetErrorStringWithFormat(
1393 "error: %s does not support sending signals to processes",
1394 GetPluginName().GetCString());
1398 virtual Status WillDestroy() { return Status(); }
1400 virtual Status DoDestroy() = 0;
1402 virtual void DidDestroy() {}
1404 virtual bool DestroyRequiresHalt() { return true; }
1406 //------------------------------------------------------------------
1407 /// Called after sending a signal to a process.
1409 /// Allow Process plug-ins to execute some code after sending a
1410 /// signal to a process.
1411 //------------------------------------------------------------------
1412 virtual void DidSignal() {}
1414 //------------------------------------------------------------------
1415 /// Currently called as part of ShouldStop.
1416 /// FIXME: Should really happen when the target stops before the
1417 /// event is taken from the queue...
1419 /// This callback is called as the event
1420 /// is about to be queued up to allow Process plug-ins to execute
1421 /// some code prior to clients being notified that a process was
1422 /// stopped. Common operations include updating the thread list,
1423 /// invalidating any thread state (registers, stack, etc) prior to
1424 /// letting the notification go out.
1426 //------------------------------------------------------------------
1427 virtual void RefreshStateAfterStop() = 0;
1429 //------------------------------------------------------------------
1430 /// Sometimes the connection to a process can detect the host OS
1431 /// version that the process is running on. The current platform
1432 /// should be checked first in case the platform is connected, but
1433 /// clients can fall back onto this function if the platform fails
1434 /// to identify the host OS version. The platform should be checked
1435 /// first in case you are running a simulator platform that might
1436 /// itself be running natively, but have different heuristics for
1437 /// figuring out which OS is is emulating.
1439 /// @param[out] major
1440 /// The major OS version, or UINT32_MAX if it can't be determined
1442 /// @param[out] minor
1443 /// The minor OS version, or UINT32_MAX if it can't be determined
1445 /// @param[out] update
1446 /// The update OS version, or UINT32_MAX if it can't be determined
1449 /// Returns \b true if the host OS version info was filled in
1450 /// and \b false otherwise.
1451 //------------------------------------------------------------------
1452 virtual bool GetHostOSVersion(uint32_t &major, uint32_t &minor,
1456 update = UINT32_MAX;
1460 //------------------------------------------------------------------
1461 /// Get the target object pointer for this module.
1464 /// A Target object pointer to the target that owns this
1466 //------------------------------------------------------------------
1467 Target &GetTarget() { return *m_target_sp.lock(); }
1469 //------------------------------------------------------------------
1470 /// Get the const target object pointer for this module.
1473 /// A const Target object pointer to the target that owns this
1475 //------------------------------------------------------------------
1476 const Target &GetTarget() const { return *m_target_sp.lock(); }
1478 //------------------------------------------------------------------
1479 /// Flush all data in the process.
1481 /// Flush the memory caches, all threads, and any other cached data
1484 /// This function can be called after a world changing event like
1485 /// adding a new symbol file, or after the process makes a large
1486 /// context switch (from boot ROM to booted into an OS).
1487 //------------------------------------------------------------------
1490 //------------------------------------------------------------------
1491 /// Get accessor for the current process state.
1494 /// The current state of the process.
1496 /// @see lldb::StateType
1497 //------------------------------------------------------------------
1498 lldb::StateType GetState();
1500 lldb::ExpressionResults
1501 RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp,
1502 const EvaluateExpressionOptions &options,
1503 DiagnosticManager &diagnostic_manager);
1505 static const char *ExecutionResultAsCString(lldb::ExpressionResults result);
1507 void GetStatus(Stream &ostrm);
1509 size_t GetThreadStatus(Stream &ostrm, bool only_threads_with_stop_reason,
1510 uint32_t start_frame, uint32_t num_frames,
1511 uint32_t num_frames_with_source,
1514 void SendAsyncInterrupt();
1516 //------------------------------------------------------------------
1517 // Notify this process class that modules got loaded.
1519 // If subclasses override this method, they must call this version
1520 // before doing anything in the subclass version of the function.
1521 //------------------------------------------------------------------
1522 virtual void ModulesDidLoad(ModuleList &module_list);
1524 //------------------------------------------------------------------
1525 /// Retrieve the list of shared libraries that are loaded for this process
1526 /// This method is used on pre-macOS 10.12, pre-iOS 10, pre-tvOS 10,
1527 /// pre-watchOS 3 systems. The following two methods are for newer versions
1530 /// For certain platforms, the time it takes for the DynamicLoader plugin to
1531 /// read all of the shared libraries out of memory over a slow communication
1532 /// channel may be too long. In that instance, the gdb-remote stub may be
1533 /// able to retrieve the necessary information about the solibs out of memory
1534 /// and return a concise summary sufficient for the DynamicLoader plugin.
1536 /// @param [in] image_list_address
1537 /// The address where the table of shared libraries is stored in memory,
1538 /// if that is appropriate for this platform. Else this may be
1539 /// passed as LLDB_INVALID_ADDRESS.
1541 /// @param [in] image_count
1542 /// The number of shared libraries that are present in this process, if
1543 /// that is appropriate for this platofrm Else this may be passed as
1544 /// LLDB_INVALID_ADDRESS.
1547 /// A StructureDataSP object which, if non-empty, will contain the
1548 /// information the DynamicLoader needs to get the initial scan of
1549 /// solibs resolved.
1550 //------------------------------------------------------------------
1551 virtual lldb_private::StructuredData::ObjectSP
1552 GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address,
1553 lldb::addr_t image_count) {
1554 return StructuredData::ObjectSP();
1557 // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1559 // the full list of loaded shared libraries without needing any input.
1560 virtual lldb_private::StructuredData::ObjectSP
1561 GetLoadedDynamicLibrariesInfos() {
1562 return StructuredData::ObjectSP();
1565 // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1567 // information about binaries given their load addresses.
1568 virtual lldb_private::StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos(
1569 const std::vector<lldb::addr_t> &load_addresses) {
1570 return StructuredData::ObjectSP();
1573 //------------------------------------------------------------------
1574 // Get information about the library shared cache, if that exists
1576 // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1578 // information about the library shared cache (a set of standard libraries
1580 // loaded at the same location for all processes on a system) in use.
1581 //------------------------------------------------------------------
1582 virtual lldb_private::StructuredData::ObjectSP GetSharedCacheInfo() {
1583 return StructuredData::ObjectSP();
1586 //------------------------------------------------------------------
1587 /// Print a user-visible warning about a module being built with optimization
1589 /// Prints a async warning message to the user one time per Module
1590 /// where a function is found that was compiled with optimization, per
1594 /// A SymbolContext with eSymbolContextFunction and eSymbolContextModule
1596 //------------------------------------------------------------------
1597 void PrintWarningOptimization(const SymbolContext &sc);
1599 virtual bool GetProcessInfo(ProcessInstanceInfo &info);
1602 //------------------------------------------------------------------
1603 /// Get the exit status for a process.
1606 /// The process's return code, or -1 if the current process
1607 /// state is not eStateExited.
1608 //------------------------------------------------------------------
1609 int GetExitStatus();
1611 //------------------------------------------------------------------
1612 /// Get a textual description of what the process exited.
1615 /// The textual description of why the process exited, or nullptr
1616 /// if there is no description available.
1617 //------------------------------------------------------------------
1618 const char *GetExitDescription();
1620 virtual void DidExit() {}
1622 //------------------------------------------------------------------
1623 /// Get the Modification ID of the process.
1626 /// The modification ID of the process.
1627 //------------------------------------------------------------------
1628 ProcessModID GetModID() const { return m_mod_id; }
1630 const ProcessModID &GetModIDRef() const { return m_mod_id; }
1632 uint32_t GetStopID() const { return m_mod_id.GetStopID(); }
1634 uint32_t GetResumeID() const { return m_mod_id.GetResumeID(); }
1636 uint32_t GetLastUserExpressionResumeID() const {
1637 return m_mod_id.GetLastUserExpressionResumeID();
1640 uint32_t GetLastNaturalStopID() const {
1641 return m_mod_id.GetLastNaturalStopID();
1644 lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const {
1645 return m_mod_id.GetStopEventForStopID(stop_id);
1648 //------------------------------------------------------------------
1649 /// Set accessor for the process exit status (return code).
1651 /// Sometimes a child exits and the exit can be detected by global
1652 /// functions (signal handler for SIGCHLD for example). This
1653 /// accessor allows the exit status to be set from an external
1656 /// Setting this will cause a eStateExited event to be posted to
1657 /// the process event queue.
1659 /// @param[in] exit_status
1660 /// The value for the process's return code.
1662 /// @see lldb::StateType
1663 //------------------------------------------------------------------
1664 virtual bool SetExitStatus(int exit_status, const char *cstr);
1666 //------------------------------------------------------------------
1667 /// Check if a process is still alive.
1670 /// Returns \b true if the process is still valid, \b false
1672 //------------------------------------------------------------------
1673 virtual bool IsAlive();
1675 //------------------------------------------------------------------
1676 /// Before lldb detaches from a process, it warns the user that they are about
1677 /// to lose their debug session.
1678 /// In some cases, this warning doesn't need to be emitted -- for instance,
1679 /// with core file debugging where
1680 /// the user can reconstruct the "state" by simply re-running the debugger on
1684 // true if the user should be warned about detaching from this process.
1685 //------------------------------------------------------------------
1686 virtual bool WarnBeforeDetach() const { return true; }
1688 //------------------------------------------------------------------
1689 /// Actually do the reading of memory from a process.
1691 /// Subclasses must override this function and can return fewer
1692 /// bytes than requested when memory requests are too large. This
1693 /// class will break up the memory requests and keep advancing the
1694 /// arguments along as needed.
1696 /// @param[in] vm_addr
1697 /// A virtual load address that indicates where to start reading
1701 /// The number of bytes to read.
1704 /// A byte buffer that is at least \a size bytes long that
1705 /// will receive the memory bytes.
1708 /// The number of bytes that were actually read into \a buf.
1709 //------------------------------------------------------------------
1710 virtual size_t DoReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1713 //------------------------------------------------------------------
1714 /// Read of memory from a process.
1716 /// This function will read memory from the current process's
1717 /// address space and remove any traps that may have been inserted
1718 /// into the memory.
1720 /// This function is not meant to be overridden by Process
1721 /// subclasses, the subclasses should implement
1722 /// Process::DoReadMemory (lldb::addr_t, size_t, void *).
1724 /// @param[in] vm_addr
1725 /// A virtual load address that indicates where to start reading
1729 /// A byte buffer that is at least \a size bytes long that
1730 /// will receive the memory bytes.
1733 /// The number of bytes to read.
1736 /// The number of bytes that were actually read into \a buf. If
1737 /// the returned number is greater than zero, yet less than \a
1738 /// size, then this function will get called again with \a
1739 /// vm_addr, \a buf, and \a size updated appropriately. Zero is
1740 /// returned to indicate an error.
1741 //------------------------------------------------------------------
1742 virtual size_t ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1745 //------------------------------------------------------------------
1746 /// Read a NULL terminated string from memory
1748 /// This function will read a cache page at a time until a NULL
1749 /// string terminator is found. It will stop reading if an aligned
1750 /// sequence of NULL termination \a type_width bytes is not found
1751 /// before reading \a cstr_max_len bytes. The results are always
1752 /// guaranteed to be NULL terminated, and that no more than
1753 /// (max_bytes - type_width) bytes will be read.
1755 /// @param[in] vm_addr
1756 /// The virtual load address to start the memory read.
1759 /// A character buffer containing at least max_bytes.
1761 /// @param[in] max_bytes
1762 /// The maximum number of bytes to read.
1764 /// @param[in] error
1765 /// The error status of the read operation.
1767 /// @param[in] type_width
1768 /// The size of the null terminator (1 to 4 bytes per
1769 /// character). Defaults to 1.
1772 /// The error status or the number of bytes prior to the null terminator.
1773 //------------------------------------------------------------------
1774 size_t ReadStringFromMemory(lldb::addr_t vm_addr, char *str, size_t max_bytes,
1775 Status &error, size_t type_width = 1);
1777 //------------------------------------------------------------------
1778 /// Read a NULL terminated C string from memory
1780 /// This function will read a cache page at a time until the NULL
1781 /// C string terminator is found. It will stop reading if the NULL
1782 /// termination byte isn't found before reading \a cstr_max_len
1783 /// bytes, and the results are always guaranteed to be NULL
1784 /// terminated (at most cstr_max_len - 1 bytes will be read).
1785 //------------------------------------------------------------------
1786 size_t ReadCStringFromMemory(lldb::addr_t vm_addr, char *cstr,
1787 size_t cstr_max_len, Status &error);
1789 size_t ReadCStringFromMemory(lldb::addr_t vm_addr, std::string &out_str,
1792 size_t ReadMemoryFromInferior(lldb::addr_t vm_addr, void *buf, size_t size,
1795 //------------------------------------------------------------------
1796 /// Reads an unsigned integer of the specified byte size from
1799 /// @param[in] load_addr
1800 /// A load address of the integer to read.
1802 /// @param[in] byte_size
1803 /// The size in byte of the integer to read.
1805 /// @param[in] fail_value
1806 /// The value to return if we fail to read an integer.
1808 /// @param[out] error
1809 /// An error that indicates the success or failure of this
1810 /// operation. If error indicates success (error.Success()),
1811 /// then the value returned can be trusted, otherwise zero
1812 /// will be returned.
1815 /// The unsigned integer that was read from the process memory
1816 /// space. If the integer was smaller than a uint64_t, any
1817 /// unused upper bytes will be zero filled. If the process
1818 /// byte order differs from the host byte order, the integer
1819 /// value will be appropriately byte swapped into host byte
1821 //------------------------------------------------------------------
1822 uint64_t ReadUnsignedIntegerFromMemory(lldb::addr_t load_addr,
1823 size_t byte_size, uint64_t fail_value,
1826 int64_t ReadSignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size,
1827 int64_t fail_value, Status &error);
1829 lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error);
1831 bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
1834 //------------------------------------------------------------------
1835 /// Actually do the writing of memory to a process.
1837 /// @param[in] vm_addr
1838 /// A virtual load address that indicates where to start writing
1842 /// A byte buffer that is at least \a size bytes long that
1843 /// contains the data to write.
1846 /// The number of bytes to write.
1848 /// @param[out] error
1849 /// An error value in case the memory write fails.
1852 /// The number of bytes that were actually written.
1853 //------------------------------------------------------------------
1854 virtual size_t DoWriteMemory(lldb::addr_t vm_addr, const void *buf,
1855 size_t size, Status &error) {
1856 error.SetErrorStringWithFormat(
1857 "error: %s does not support writing to processes",
1858 GetPluginName().GetCString());
1862 //------------------------------------------------------------------
1863 /// Write all or part of a scalar value to memory.
1865 /// The value contained in \a scalar will be swapped to match the
1866 /// byte order of the process that is being debugged. If \a size is
1867 /// less than the size of scalar, the least significant \a size bytes
1868 /// from scalar will be written. If \a size is larger than the byte
1869 /// size of scalar, then the extra space will be padded with zeros
1870 /// and the scalar value will be placed in the least significant
1871 /// bytes in memory.
1873 /// @param[in] vm_addr
1874 /// A virtual load address that indicates where to start writing
1877 /// @param[in] scalar
1878 /// The scalar to write to the debugged process.
1881 /// This value can be smaller or larger than the scalar value
1882 /// itself. If \a size is smaller than the size of \a scalar,
1883 /// the least significant bytes in \a scalar will be used. If
1884 /// \a size is larger than the byte size of \a scalar, then
1885 /// the extra space will be padded with zeros. If \a size is
1886 /// set to UINT32_MAX, then the size of \a scalar will be used.
1888 /// @param[out] error
1889 /// An error value in case the memory write fails.
1892 /// The number of bytes that were actually written.
1893 //------------------------------------------------------------------
1894 size_t WriteScalarToMemory(lldb::addr_t vm_addr, const Scalar &scalar,
1895 size_t size, Status &error);
1897 size_t ReadScalarIntegerFromMemory(lldb::addr_t addr, uint32_t byte_size,
1898 bool is_signed, Scalar &scalar,
1901 //------------------------------------------------------------------
1902 /// Write memory to a process.
1904 /// This function will write memory to the current process's
1905 /// address space and maintain any traps that might be present due
1906 /// to software breakpoints.
1908 /// This function is not meant to be overridden by Process
1909 /// subclasses, the subclasses should implement
1910 /// Process::DoWriteMemory (lldb::addr_t, size_t, void *).
1912 /// @param[in] vm_addr
1913 /// A virtual load address that indicates where to start writing
1917 /// A byte buffer that is at least \a size bytes long that
1918 /// contains the data to write.
1921 /// The number of bytes to write.
1924 /// The number of bytes that were actually written.
1925 //------------------------------------------------------------------
1926 // TODO: change this to take an ArrayRef<uint8_t>
1927 size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1930 //------------------------------------------------------------------
1931 /// Actually allocate memory in the process.
1933 /// This function will allocate memory in the process's address
1934 /// space. This can't rely on the generic function calling mechanism,
1935 /// since that requires this function.
1938 /// The size of the allocation requested.
1941 /// The address of the allocated buffer in the process, or
1942 /// LLDB_INVALID_ADDRESS if the allocation failed.
1943 //------------------------------------------------------------------
1945 virtual lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions,
1947 error.SetErrorStringWithFormat(
1948 "error: %s does not support allocating in the debug process",
1949 GetPluginName().GetCString());
1950 return LLDB_INVALID_ADDRESS;
1953 //------------------------------------------------------------------
1954 /// The public interface to allocating memory in the process.
1956 /// This function will allocate memory in the process's address
1957 /// space. This can't rely on the generic function calling mechanism,
1958 /// since that requires this function.
1961 /// The size of the allocation requested.
1963 /// @param[in] permissions
1964 /// Or together any of the lldb::Permissions bits. The permissions on
1965 /// a given memory allocation can't be changed after allocation. Note
1966 /// that a block that isn't set writable can still be written on from
1968 /// just not by the process itself.
1970 /// @param[in,out] error
1971 /// An error object to fill in if things go wrong.
1973 /// The address of the allocated buffer in the process, or
1974 /// LLDB_INVALID_ADDRESS if the allocation failed.
1975 //------------------------------------------------------------------
1976 lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error);
1978 //------------------------------------------------------------------
1979 /// The public interface to allocating memory in the process, this also
1980 /// clears the allocated memory.
1982 /// This function will allocate memory in the process's address
1983 /// space. This can't rely on the generic function calling mechanism,
1984 /// since that requires this function.
1987 /// The size of the allocation requested.
1989 /// @param[in] permissions
1990 /// Or together any of the lldb::Permissions bits. The permissions on
1991 /// a given memory allocation can't be changed after allocation. Note
1992 /// that a block that isn't set writable can still be written on from
1994 /// just not by the process itself.
1996 /// @param[in/out] error
1997 /// An error object to fill in if things go wrong.
1999 /// The address of the allocated buffer in the process, or
2000 /// LLDB_INVALID_ADDRESS if the allocation failed.
2001 //------------------------------------------------------------------
2003 lldb::addr_t CallocateMemory(size_t size, uint32_t permissions,
2006 //------------------------------------------------------------------
2007 /// Resolve dynamically loaded indirect functions.
2009 /// @param[in] address
2010 /// The load address of the indirect function to resolve.
2012 /// @param[out] error
2013 /// An error value in case the resolve fails.
2016 /// The address of the resolved function.
2017 /// LLDB_INVALID_ADDRESS if the resolution failed.
2018 //------------------------------------------------------------------
2019 virtual lldb::addr_t ResolveIndirectFunction(const Address *address,
2022 //------------------------------------------------------------------
2023 /// Locate the memory region that contains load_addr.
2025 /// If load_addr is within the address space the process has mapped
2026 /// range_info will be filled in with the start and end of that range
2027 /// as well as the permissions for that range and range_info.GetMapped
2028 /// will return true.
2030 /// If load_addr is outside any mapped region then range_info will
2031 /// have its start address set to load_addr and the end of the
2032 /// range will indicate the start of the next mapped range or be
2033 /// set to LLDB_INVALID_ADDRESS if there are no valid mapped ranges
2034 /// between load_addr and the end of the process address space.
2036 /// GetMemoryRegionInfo will only return an error if it is
2037 /// unimplemented for the current process.
2039 /// @param[in] load_addr
2040 /// The load address to query the range_info for.
2042 /// @param[out] range_info
2043 /// An range_info value containing the details of the range.
2047 //------------------------------------------------------------------
2048 virtual Status GetMemoryRegionInfo(lldb::addr_t load_addr,
2049 MemoryRegionInfo &range_info) {
2051 error.SetErrorString("Process::GetMemoryRegionInfo() not supported");
2055 //------------------------------------------------------------------
2056 /// Obtain all the mapped memory regions within this process.
2058 /// @param[out] region_list
2059 /// A vector to contain MemoryRegionInfo objects for all mapped
2064 //------------------------------------------------------------------
2066 GetMemoryRegions(std::vector<lldb::MemoryRegionInfoSP> ®ion_list);
2068 virtual Status GetWatchpointSupportInfo(uint32_t &num) {
2071 error.SetErrorString("Process::GetWatchpointSupportInfo() not supported");
2075 virtual Status GetWatchpointSupportInfo(uint32_t &num, bool &after) {
2079 error.SetErrorString("Process::GetWatchpointSupportInfo() not supported");
2083 lldb::ModuleSP ReadModuleFromMemory(const FileSpec &file_spec,
2084 lldb::addr_t header_addr,
2085 size_t size_to_read = 512);
2087 //------------------------------------------------------------------
2088 /// Attempt to get the attributes for a region of memory in the process.
2090 /// It may be possible for the remote debug server to inspect attributes
2091 /// for a region of memory in the process, such as whether there is a
2092 /// valid page of memory at a given address or whether that page is
2093 /// readable/writable/executable by the process.
2095 /// @param[in] load_addr
2096 /// The address of interest in the process.
2098 /// @param[out] permissions
2099 /// If this call returns successfully, this bitmask will have
2100 /// its Permissions bits set to indicate whether the region is
2101 /// readable/writable/executable. If this call fails, the
2102 /// bitmask values are undefined.
2105 /// Returns true if it was able to determine the attributes of the
2106 /// memory region. False if not.
2107 //------------------------------------------------------------------
2108 virtual bool GetLoadAddressPermissions(lldb::addr_t load_addr,
2109 uint32_t &permissions);
2111 //------------------------------------------------------------------
2112 /// Determines whether executing JIT-compiled code in this process
2116 /// True if execution of JIT code is possible; false otherwise.
2117 //------------------------------------------------------------------
2120 //------------------------------------------------------------------
2121 /// Sets whether executing JIT-compiled code in this process
2124 /// @param[in] can_jit
2125 /// True if execution of JIT code is possible; false otherwise.
2126 //------------------------------------------------------------------
2127 void SetCanJIT(bool can_jit);
2129 //------------------------------------------------------------------
2130 /// Determines whether executing function calls using the interpreter
2131 /// is possible for this process.
2134 /// True if possible; false otherwise.
2135 //------------------------------------------------------------------
2136 bool CanInterpretFunctionCalls() { return m_can_interpret_function_calls; }
2138 //------------------------------------------------------------------
2139 /// Sets whether executing function calls using the interpreter
2140 /// is possible for this process.
2142 /// @param[in] can_interpret_function_calls
2143 /// True if possible; false otherwise.
2144 //------------------------------------------------------------------
2145 void SetCanInterpretFunctionCalls(bool can_interpret_function_calls) {
2146 m_can_interpret_function_calls = can_interpret_function_calls;
2149 //------------------------------------------------------------------
2150 /// Sets whether executing code in this process is possible.
2151 /// This could be either through JIT or interpreting.
2153 /// @param[in] can_run_code
2154 /// True if execution of code is possible; false otherwise.
2155 //------------------------------------------------------------------
2156 void SetCanRunCode(bool can_run_code);
2158 //------------------------------------------------------------------
2159 /// Actually deallocate memory in the process.
2161 /// This function will deallocate memory in the process's address
2162 /// space that was allocated with AllocateMemory.
2165 /// A return value from AllocateMemory, pointing to the memory you
2166 /// want to deallocate.
2169 /// \btrue if the memory was deallocated, \bfalse otherwise.
2170 //------------------------------------------------------------------
2171 virtual Status DoDeallocateMemory(lldb::addr_t ptr) {
2173 error.SetErrorStringWithFormat(
2174 "error: %s does not support deallocating in the debug process",
2175 GetPluginName().GetCString());
2179 //------------------------------------------------------------------
2180 /// The public interface to deallocating memory in the process.
2182 /// This function will deallocate memory in the process's address
2183 /// space that was allocated with AllocateMemory.
2186 /// A return value from AllocateMemory, pointing to the memory you
2187 /// want to deallocate.
2190 /// \btrue if the memory was deallocated, \bfalse otherwise.
2191 //------------------------------------------------------------------
2192 Status DeallocateMemory(lldb::addr_t ptr);
2194 //------------------------------------------------------------------
2195 /// Get any available STDOUT.
2197 /// Calling this method is a valid operation only if all of the
2198 /// following conditions are true:
2199 /// 1) The process was launched, and not attached to.
2200 /// 2) The process was not launched with eLaunchFlagDisableSTDIO.
2201 /// 3) The process was launched without supplying a valid file path
2204 /// Note that the implementation will probably need to start a read
2205 /// thread in the background to make sure that the pipe is drained
2206 /// and the STDOUT buffered appropriately, to prevent the process
2207 /// from deadlocking trying to write to a full buffer.
2209 /// Events will be queued indicating that there is STDOUT available
2210 /// that can be retrieved using this function.
2213 /// A buffer that will receive any STDOUT bytes that are
2214 /// currently available.
2216 /// @param[in] buf_size
2217 /// The size in bytes for the buffer \a buf.
2220 /// The number of bytes written into \a buf. If this value is
2221 /// equal to \a buf_size, another call to this function should
2222 /// be made to retrieve more STDOUT data.
2223 //------------------------------------------------------------------
2224 virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error);
2226 //------------------------------------------------------------------
2227 /// Get any available STDERR.
2229 /// Calling this method is a valid operation only if all of the
2230 /// following conditions are true:
2231 /// 1) The process was launched, and not attached to.
2232 /// 2) The process was not launched with eLaunchFlagDisableSTDIO.
2233 /// 3) The process was launched without supplying a valid file path
2236 /// Note that the implementation will probably need to start a read
2237 /// thread in the background to make sure that the pipe is drained
2238 /// and the STDERR buffered appropriately, to prevent the process
2239 /// from deadlocking trying to write to a full buffer.
2241 /// Events will be queued indicating that there is STDERR available
2242 /// that can be retrieved using this function.
2245 /// A buffer that will receive any STDERR bytes that are
2246 /// currently available.
2248 /// @param[out] buf_size
2249 /// The size in bytes for the buffer \a buf.
2252 /// The number of bytes written into \a buf. If this value is
2253 /// equal to \a buf_size, another call to this function should
2254 /// be made to retrieve more STDERR data.
2255 //------------------------------------------------------------------
2256 virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error);
2258 //------------------------------------------------------------------
2259 /// Puts data into this process's STDIN.
2261 /// Calling this method is a valid operation only if all of the
2262 /// following conditions are true:
2263 /// 1) The process was launched, and not attached to.
2264 /// 2) The process was not launched with eLaunchFlagDisableSTDIO.
2265 /// 3) The process was launched without supplying a valid file path
2269 /// A buffer that contains the data to write to the process's STDIN.
2271 /// @param[in] buf_size
2272 /// The size in bytes for the buffer \a buf.
2275 /// The number of bytes written into \a buf. If this value is
2276 /// less than \a buf_size, another call to this function should
2277 /// be made to write the rest of the data.
2278 //------------------------------------------------------------------
2279 virtual size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) {
2280 error.SetErrorString("stdin unsupported");
2284 //------------------------------------------------------------------
2285 /// Get any available profile data.
2288 /// A buffer that will receive any profile data bytes that are
2289 /// currently available.
2291 /// @param[out] buf_size
2292 /// The size in bytes for the buffer \a buf.
2295 /// The number of bytes written into \a buf. If this value is
2296 /// equal to \a buf_size, another call to this function should
2297 /// be made to retrieve more profile data.
2298 //------------------------------------------------------------------
2299 virtual size_t GetAsyncProfileData(char *buf, size_t buf_size, Status &error);
2301 //----------------------------------------------------------------------
2302 // Process Breakpoints
2303 //----------------------------------------------------------------------
2304 size_t GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site);
2306 virtual Status EnableBreakpointSite(BreakpointSite *bp_site) {
2308 error.SetErrorStringWithFormat(
2309 "error: %s does not support enabling breakpoints",
2310 GetPluginName().GetCString());
2314 virtual Status DisableBreakpointSite(BreakpointSite *bp_site) {
2316 error.SetErrorStringWithFormat(
2317 "error: %s does not support disabling breakpoints",
2318 GetPluginName().GetCString());
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 // read existing opcode, write breakpoint opcode, verify breakpoint opcode
2325 // doesn't work for a specific process plug-in.
2326 virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site);
2328 // This is implemented completely using the lldb::Process API. Subclasses
2329 // don't need to implement this function unless the standard flow of
2330 // restoring original opcode in memory and verifying the restored opcode
2331 // doesn't work for a specific process plug-in.
2332 virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site);
2334 BreakpointSiteList &GetBreakpointSiteList();
2336 const BreakpointSiteList &GetBreakpointSiteList() const;
2338 void DisableAllBreakpointSites();
2340 Status ClearBreakpointSiteByID(lldb::user_id_t break_id);
2342 lldb::break_id_t CreateBreakpointSite(const lldb::BreakpointLocationSP &owner,
2345 Status DisableBreakpointSiteByID(lldb::user_id_t break_id);
2347 Status EnableBreakpointSiteByID(lldb::user_id_t break_id);
2349 // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove
2350 // themselves from the owner's list of this breakpoint sites.
2351 void RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
2352 lldb::user_id_t owner_loc_id,
2353 lldb::BreakpointSiteSP &bp_site_sp);
2355 //----------------------------------------------------------------------
2356 // Process Watchpoints (optional)
2357 //----------------------------------------------------------------------
2358 virtual Status EnableWatchpoint(Watchpoint *wp, bool notify = true);
2360 virtual Status DisableWatchpoint(Watchpoint *wp, bool notify = true);
2362 //------------------------------------------------------------------
2364 //------------------------------------------------------------------
2365 virtual bool UpdateThreadList(ThreadList &old_thread_list,
2366 ThreadList &new_thread_list) = 0;
2368 void UpdateThreadListIfNeeded();
2370 ThreadList &GetThreadList() { return m_thread_list; }
2372 // When ExtendedBacktraces are requested, the HistoryThreads that are
2373 // created need an owner -- they're saved here in the Process. The
2374 // threads in this list are not iterated over - driver programs need to
2375 // request the extended backtrace calls starting from a root concrete
2376 // thread one by one.
2377 ThreadList &GetExtendedThreadList() { return m_extended_thread_list; }
2379 ThreadList::ThreadIterable Threads() { return m_thread_list.Threads(); }
2381 uint32_t GetNextThreadIndexID(uint64_t thread_id);
2383 lldb::ThreadSP CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context);
2385 // Returns true if an index id has been assigned to a thread.
2386 bool HasAssignedIndexIDToThread(uint64_t sb_thread_id);
2388 // Given a thread_id, it will assign a more reasonable index id for display to
2390 // If the thread_id has previously been assigned, the same index id will be
2392 uint32_t AssignIndexIDToThread(uint64_t thread_id);
2394 //------------------------------------------------------------------
2396 //------------------------------------------------------------------
2398 void UpdateQueueListIfNeeded();
2400 QueueList &GetQueueList() {
2401 UpdateQueueListIfNeeded();
2402 return m_queue_list;
2405 QueueList::QueueIterable Queues() {
2406 UpdateQueueListIfNeeded();
2407 return m_queue_list.Queues();
2410 //------------------------------------------------------------------
2412 //------------------------------------------------------------------
2413 lldb::StateType GetNextEvent(lldb::EventSP &event_sp);
2415 // Returns the process state when it is stopped. If specified, event_sp_ptr
2416 // is set to the event which triggered the stop. If wait_always = false,
2417 // and the process is already stopped, this function returns immediately.
2418 // If the process is hijacked and use_run_lock is true (the default), then
2420 // function releases the run lock after the stop. Setting use_run_lock to
2422 // will avoid this behavior.
2424 WaitForProcessToStop(const Timeout<std::micro> &timeout,
2425 lldb::EventSP *event_sp_ptr = nullptr,
2426 bool wait_always = true,
2427 lldb::ListenerSP hijack_listener = lldb::ListenerSP(),
2428 Stream *stream = nullptr, bool use_run_lock = true);
2430 uint32_t GetIOHandlerID() const { return m_iohandler_sync.GetValue(); }
2432 //--------------------------------------------------------------------------------------
2433 /// Waits for the process state to be running within a given msec timeout.
2435 /// The main purpose of this is to implement an interlock waiting for
2436 /// HandlePrivateEvent
2437 /// to push an IOHandler.
2439 /// @param[in] timeout_msec
2440 /// The maximum time length to wait for the process to transition to the
2441 /// eStateRunning state, specified in milliseconds.
2442 //--------------------------------------------------------------------------------------
2443 void SyncIOHandler(uint32_t iohandler_id, uint64_t timeout_msec);
2445 lldb::StateType GetStateChangedEvents(
2446 lldb::EventSP &event_sp, const Timeout<std::micro> &timeout,
2448 hijack_listener); // Pass an empty ListenerSP to use builtin listener
2450 //--------------------------------------------------------------------------------------
2451 /// Centralize the code that handles and prints descriptions for process state
2454 /// @param[in] event_sp
2455 /// The process state changed event
2457 /// @param[in] stream
2458 /// The output stream to get the state change description
2460 /// @param[in,out] pop_process_io_handler
2461 /// If this value comes in set to \b true, then pop the Process IOHandler
2463 /// Else this variable will be set to \b true or \b false to indicate if
2465 /// needs to have its process IOHandler popped.
2468 /// \b true if the event describes a process state changed event, \b false
2470 //--------------------------------------------------------------------------------------
2471 static bool HandleProcessStateChangedEvent(const lldb::EventSP &event_sp,
2473 bool &pop_process_io_handler);
2475 Event *PeekAtStateChangedEvents();
2477 class ProcessEventHijacker {
2479 ProcessEventHijacker(Process &process, lldb::ListenerSP listener_sp)
2480 : m_process(process) {
2481 m_process.HijackProcessEvents(listener_sp);
2484 ~ProcessEventHijacker() { m_process.RestoreProcessEvents(); }
2490 friend class ProcessEventHijacker;
2491 friend class ProcessProperties;
2492 //------------------------------------------------------------------
2493 /// If you need to ensure that you and only you will hear about some public
2494 /// event, then make a new listener, set to listen to process events, and
2495 /// then call this with that listener. Then you will have to wait on that
2496 /// listener explicitly for events (rather than using the GetNextEvent &
2498 /// calls above. Be sure to call RestoreProcessEvents when you are done.
2500 /// @param[in] listener
2501 /// This is the new listener to whom all process events will be delivered.
2504 /// Returns \b true if the new listener could be installed,
2505 /// \b false otherwise.
2506 //------------------------------------------------------------------
2507 bool HijackProcessEvents(lldb::ListenerSP listener_sp);
2509 //------------------------------------------------------------------
2510 /// Restores the process event broadcasting to its normal state.
2512 //------------------------------------------------------------------
2513 void RestoreProcessEvents();
2515 const lldb::ABISP &GetABI();
2517 OperatingSystem *GetOperatingSystem() { return m_os_ap.get(); }
2519 virtual LanguageRuntime *GetLanguageRuntime(lldb::LanguageType language,
2520 bool retry_if_null = true);
2522 virtual CPPLanguageRuntime *GetCPPLanguageRuntime(bool retry_if_null = true);
2524 virtual ObjCLanguageRuntime *
2525 GetObjCLanguageRuntime(bool retry_if_null = true);
2527 bool IsPossibleDynamicValue(ValueObject &in_value);
2529 bool IsRunning() const;
2531 DynamicCheckerFunctions *GetDynamicCheckers() {
2532 return m_dynamic_checkers_ap.get();
2535 void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers);
2537 //------------------------------------------------------------------
2538 /// Call this to set the lldb in the mode where it breaks on new thread
2539 /// creations, and then auto-restarts. This is useful when you are trying
2540 /// to run only one thread, but either that thread or the kernel is creating
2541 /// new threads in the process. If you stop when the thread is created, you
2542 /// can immediately suspend it, and keep executing only the one thread you
2546 /// Returns \b true if we were able to start up the notification
2547 /// \b false otherwise.
2548 //------------------------------------------------------------------
2549 virtual bool StartNoticingNewThreads() { return true; }
2551 //------------------------------------------------------------------
2552 /// Call this to turn off the stop & notice new threads mode.
2555 /// Returns \b true if we were able to start up the notification
2556 /// \b false otherwise.
2557 //------------------------------------------------------------------
2558 virtual bool StopNoticingNewThreads() { return true; }
2560 void SetRunningUserExpression(bool on);
2562 //------------------------------------------------------------------
2563 // lldb::ExecutionContextScope pure virtual functions
2564 //------------------------------------------------------------------
2565 lldb::TargetSP CalculateTarget() override;
2567 lldb::ProcessSP CalculateProcess() override { return shared_from_this(); }
2569 lldb::ThreadSP CalculateThread() override { return lldb::ThreadSP(); }
2571 lldb::StackFrameSP CalculateStackFrame() override {
2572 return lldb::StackFrameSP();
2575 void CalculateExecutionContext(ExecutionContext &exe_ctx) override;
2577 void SetSTDIOFileDescriptor(int file_descriptor);
2579 //------------------------------------------------------------------
2580 // Add a permanent region of memory that should never be read or
2581 // written to. This can be used to ensure that memory reads or writes
2582 // to certain areas of memory never end up being sent to the
2583 // DoReadMemory or DoWriteMemory functions which can improve
2585 //------------------------------------------------------------------
2586 void AddInvalidMemoryRegion(const LoadRange ®ion);
2588 //------------------------------------------------------------------
2589 // Remove a permanent region of memory that should never be read or
2590 // written to that was previously added with AddInvalidMemoryRegion.
2591 //------------------------------------------------------------------
2592 bool RemoveInvalidMemoryRange(const LoadRange ®ion);
2594 //------------------------------------------------------------------
2595 // If the setup code of a thread plan needs to do work that might involve
2596 // calling a function in the target, it should not do that work directly
2597 // in one of the thread plan functions (DidPush/WillResume) because
2598 // such work needs to be handled carefully. Instead, put that work in
2599 // a PreResumeAction callback, and register it with the process. It will
2600 // get done before the actual "DoResume" gets called.
2601 //------------------------------------------------------------------
2603 typedef bool(PreResumeActionCallback)(void *);
2605 void AddPreResumeAction(PreResumeActionCallback callback, void *baton);
2607 bool RunPreResumeActions();
2609 void ClearPreResumeActions();
2611 void ClearPreResumeAction(PreResumeActionCallback callback, void *baton);
2613 ProcessRunLock &GetRunLock();
2615 virtual Status SendEventData(const char *data) {
2616 Status return_error("Sending an event is not supported for this process.");
2617 return return_error;
2620 lldb::ThreadCollectionSP GetHistoryThreads(lldb::addr_t addr);
2622 lldb::InstrumentationRuntimeSP
2623 GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type);
2625 //------------------------------------------------------------------
2626 /// Try to fetch the module specification for a module with the
2627 /// given file name and architecture. Process sub-classes have to
2628 /// override this method if they support platforms where the
2629 /// Platform object can't get the module spec for all module.
2631 /// @param[in] module_file_spec
2632 /// The file name of the module to get specification for.
2635 /// The architecture of the module to get specification for.
2637 /// @param[out] module_spec
2638 /// The fetched module specification if the return value is
2639 /// \b true, unchanged otherwise.
2642 /// Returns \b true if the module spec fetched successfully,
2643 /// \b false otherwise.
2644 //------------------------------------------------------------------
2645 virtual bool GetModuleSpec(const FileSpec &module_file_spec,
2646 const ArchSpec &arch, ModuleSpec &module_spec);
2648 virtual void PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs,
2649 const llvm::Triple &triple) {}
2651 //------------------------------------------------------------------
2652 /// Try to find the load address of a file.
2653 /// The load address is defined as the address of the first memory
2654 /// region what contains data mapped from the specified file.
2657 /// The name of the file whose load address we are looking for
2659 /// @param[out] is_loaded
2660 /// \b True if the file is loaded into the memory and false
2663 /// @param[out] load_addr
2664 /// The load address of the file if it is loaded into the
2665 /// processes address space, LLDB_INVALID_ADDRESS otherwise.
2666 //------------------------------------------------------------------
2667 virtual Status GetFileLoadAddress(const FileSpec &file, bool &is_loaded,
2668 lldb::addr_t &load_addr) {
2669 return Status("Not supported");
2672 size_t AddImageToken(lldb::addr_t image_ptr);
2674 lldb::addr_t GetImagePtrFromToken(size_t token) const;
2676 void ResetImageToken(size_t token);
2678 //------------------------------------------------------------------
2679 /// Find the next branch instruction to set a breakpoint on
2681 /// When instruction stepping through a source line, instead of
2682 /// stepping through each instruction, we can put a breakpoint on
2683 /// the next branch instruction (within the range of instructions
2684 /// we are stepping through) and continue the process to there,
2685 /// yielding significant performance benefits over instruction
2688 /// @param[in] default_stop_addr
2689 /// The address of the instruction where lldb would put a
2690 /// breakpoint normally.
2692 /// @param[in] range_bounds
2693 /// The range which the breakpoint must be contained within.
2694 /// Typically a source line.
2697 /// The address of the next branch instruction, or the end of
2698 /// the range provided in range_bounds. If there are any
2699 /// problems with the disassembly or getting the instructions,
2700 /// the original default_stop_addr will be returned.
2701 //------------------------------------------------------------------
2702 Address AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
2703 AddressRange range_bounds);
2705 //------------------------------------------------------------------
2706 /// Configure asynchronous structured data feature.
2708 /// Each Process type that supports using an asynchronous StructuredData
2709 /// feature should implement this to enable/disable/configure the feature.
2710 /// The default implementation here will always return an error indiciating
2711 /// the feature is unsupported.
2713 /// StructuredDataPlugin implementations will call this to configure
2714 /// a feature that has been reported as being supported.
2716 /// @param[in] type_name
2717 /// The StructuredData type name as previously discovered by
2718 /// the Process-derived instance.
2720 /// @param[in] config
2721 /// Configuration data for the feature being enabled. This config
2722 /// data, which may be null, will be passed along to the feature
2723 /// to process. The feature will dictate whether this is a dictionary,
2724 /// an array or some other object. If the feature needs to be
2725 /// set up properly before it can be enabled, then the config should
2726 /// also take an enable/disable flag.
2729 /// Returns the result of attempting to configure the feature.
2730 //------------------------------------------------------------------
2732 ConfigureStructuredData(const ConstString &type_name,
2733 const StructuredData::ObjectSP &config_sp);
2735 //------------------------------------------------------------------
2736 /// Broadcasts the given structured data object from the given
2739 /// StructuredDataPlugin instances can use this to optionally
2740 /// broadcast any of their data if they want to make it available
2741 /// for clients. The data will come in on the structured data
2742 /// event bit (eBroadcastBitStructuredData).
2744 /// @param[in] object_sp
2745 /// The structured data object to broadcast.
2747 /// @param[in] plugin_sp
2748 /// The plugin that will be reported in the event's plugin
2750 //------------------------------------------------------------------
2751 void BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
2752 const lldb::StructuredDataPluginSP &plugin_sp);
2754 //------------------------------------------------------------------
2755 /// Returns the StructuredDataPlugin associated with a given type
2756 /// name, if there is one.
2758 /// There will only be a plugin for a given StructuredDataType if the
2759 /// debugged process monitor claims that the feature is supported.
2760 /// This is one way to tell whether a feature is available.
2763 /// The plugin if one is available for the specified feature;
2764 /// otherwise, returns an empty shared pointer.
2765 //------------------------------------------------------------------
2766 lldb::StructuredDataPluginSP
2767 GetStructuredDataPlugin(const ConstString &type_name) const;
2769 //------------------------------------------------------------------
2770 /// Starts tracing with the configuration provided in options. To
2771 /// enable tracing on the complete process the thread_id in the
2772 /// options should be set to LLDB_INVALID_THREAD_ID. The API returns
2773 /// a user_id which is needed by other API's that manipulate the
2775 /// The handling of erroneous or unsupported configuration is left
2776 /// to the trace technology implementations in the server, as they
2777 /// could be returned as an error, or rounded to a valid
2778 /// configuration to start tracing. In the later case the
2779 /// GetTraceConfig should supply the actual used trace
2781 //------------------------------------------------------------------
2782 virtual lldb::user_id_t StartTrace(const TraceOptions &options,
2784 error.SetErrorString("Not implemented");
2785 return LLDB_INVALID_UID;
2788 //------------------------------------------------------------------
2789 /// Stops the tracing instance leading to deletion of the trace
2790 /// data. The tracing instance is identified by the user_id which
2791 /// is obtained when tracing was started from the StartTrace.
2792 /// In case tracing of the complete process needs to be stopped
2793 /// the thread_id should be set to LLDB_INVALID_THREAD_ID.
2794 /// In the other case that tracing on an individual thread needs
2795 /// to be stopped a thread_id can be supplied.
2796 //------------------------------------------------------------------
2797 virtual Status StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) {
2798 return Status("Not implemented");
2801 //------------------------------------------------------------------
2802 /// Provides the trace data as raw bytes. A buffer needs to be
2803 /// supplied to copy the trace data. The exact behavior of this API
2804 /// may vary across trace technology, as some may support partial
2805 /// reading of the trace data from a specified offset while some
2806 /// may not. The thread_id should be used to select a particular
2807 /// thread for trace extraction.
2808 //------------------------------------------------------------------
2809 virtual Status GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
2810 llvm::MutableArrayRef<uint8_t> &buffer,
2811 size_t offset = 0) {
2812 return Status("Not implemented");
2815 //------------------------------------------------------------------
2816 /// Similar API as above except for obtaining meta data
2817 //------------------------------------------------------------------
2818 virtual Status GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
2819 llvm::MutableArrayRef<uint8_t> &buffer,
2820 size_t offset = 0) {
2821 return Status("Not implemented");
2824 //------------------------------------------------------------------
2825 /// API to obtain the trace configuration used by a trace instance.
2826 /// Configurations that may be specific to some trace technology
2827 /// should be stored in the custom parameters. The options are
2828 /// transported to the server, which shall interpret accordingly.
2829 /// The thread_id can be specified in the options to obtain the
2830 /// configuration used by a specific thread. The thread_id specified
2831 /// should also match the uid otherwise an error will be returned.
2832 //------------------------------------------------------------------
2833 virtual Status GetTraceConfig(lldb::user_id_t uid, TraceOptions &options) {
2834 return Status("Not implemented");
2838 void SetState(lldb::EventSP &event_sp);
2840 lldb::StateType GetPrivateState();
2842 //------------------------------------------------------------------
2843 /// The "private" side of resuming a process. This doesn't alter the
2844 /// state of m_run_lock, but just causes the process to resume.
2847 /// An Status object describing the success or failure of the resume.
2848 //------------------------------------------------------------------
2849 Status PrivateResume();
2851 //------------------------------------------------------------------
2852 // Called internally
2853 //------------------------------------------------------------------
2854 void CompleteAttach();
2856 //------------------------------------------------------------------
2857 /// Print a user-visible warning one time per Process
2859 /// A facility for printing a warning to the user once per repeat_key.
2861 /// warning_type is from the Process::Warnings enums.
2862 /// repeat_key is a pointer value that will be used to ensure that the
2863 /// warning message is not printed multiple times. For instance, with a
2864 /// warning about a function being optimized, you can pass the CompileUnit
2865 /// pointer to have the warning issued for only the first function in a
2866 /// CU, or the Function pointer to have it issued once for every function,
2867 /// or a Module pointer to have it issued once per Module.
2869 /// Classes outside Process should call a specific PrintWarning method
2870 /// so that the warning strings are all centralized in Process, instead of
2871 /// calling PrintWarning() directly.
2873 /// @param [in] warning_type
2874 /// One of the types defined in Process::Warnings.
2876 /// @param [in] repeat_key
2877 /// A pointer value used to ensure that the warning is only printed once.
2878 /// May be nullptr, indicating that the warning is printed unconditionally
2882 /// printf style format string
2883 //------------------------------------------------------------------
2884 void PrintWarning(uint64_t warning_type, const void *repeat_key,
2885 const char *fmt, ...) __attribute__((format(printf, 4, 5)));
2887 //------------------------------------------------------------------
2888 // NextEventAction provides a way to register an action on the next
2889 // event that is delivered to this process. There is currently only
2890 // one next event action allowed in the process at one time. If a
2891 // new "NextEventAction" is added while one is already present, the
2892 // old action will be discarded (with HandleBeingUnshipped called
2893 // after it is discarded.)
2895 // If you want to resume the process as a result of a resume action,
2896 // call RequestResume, don't call Resume directly.
2897 //------------------------------------------------------------------
2898 class NextEventAction {
2900 typedef enum EventActionResult {
2901 eEventActionSuccess,
2904 } EventActionResult;
2906 NextEventAction(Process *process) : m_process(process) {}
2908 virtual ~NextEventAction() = default;
2910 virtual EventActionResult PerformAction(lldb::EventSP &event_sp) = 0;
2911 virtual void HandleBeingUnshipped() {}
2912 virtual EventActionResult HandleBeingInterrupted() = 0;
2913 virtual const char *GetExitString() = 0;
2914 void RequestResume() { m_process->m_resume_requested = true; }
2920 void SetNextEventAction(Process::NextEventAction *next_event_action) {
2921 if (m_next_event_action_ap.get())
2922 m_next_event_action_ap->HandleBeingUnshipped();
2924 m_next_event_action_ap.reset(next_event_action);
2927 // This is the completer for Attaching:
2928 class AttachCompletionHandler : public NextEventAction {
2930 AttachCompletionHandler(Process *process, uint32_t exec_count);
2932 ~AttachCompletionHandler() override = default;
2934 EventActionResult PerformAction(lldb::EventSP &event_sp) override;
2935 EventActionResult HandleBeingInterrupted() override;
2936 const char *GetExitString() override;
2939 uint32_t m_exec_count;
2940 std::string m_exit_string;
2943 bool PrivateStateThreadIsValid() const {
2944 lldb::StateType state = m_private_state.GetValue();
2945 return state != lldb::eStateInvalid && state != lldb::eStateDetached &&
2946 state != lldb::eStateExited && m_private_state_thread.IsJoinable();
2949 void ForceNextEventDelivery() { m_force_next_event_delivery = true; }
2951 //------------------------------------------------------------------
2952 /// Loads any plugins associated with asynchronous structured data
2953 /// and maps the relevant supported type name to the plugin.
2955 /// Processes can receive asynchronous structured data from the
2956 /// process monitor. This method will load and map any structured
2957 /// data plugins that support the given set of supported type names.
2958 /// Later, if any of these features are enabled, the process monitor
2959 /// is free to generate asynchronous structured data. The data must
2960 /// come in as a single \b StructuredData::Dictionary. That dictionary
2961 /// must have a string field named 'type', with a value that equals
2962 /// the relevant type name string (one of the values in
2963 /// \b supported_type_names).
2965 /// @param[in] supported_type_names
2966 /// An array of zero or more type names. Each must be unique.
2967 /// For each entry in the list, a StructuredDataPlugin will be
2968 /// searched for that supports the structured data type name.
2969 //------------------------------------------------------------------
2970 void MapSupportedStructuredDataPlugins(
2971 const StructuredData::Array &supported_type_names);
2973 //------------------------------------------------------------------
2974 /// Route the incoming structured data dictionary to the right plugin.
2976 /// The incoming structured data must be a dictionary, and it must
2977 /// have a key named 'type' that stores a string value. The string
2978 /// value must be the name of the structured data feature that
2979 /// knows how to handle it.
2981 /// @param[in] object_sp
2982 /// When non-null and pointing to a dictionary, the 'type'
2983 /// key's string value is used to look up the plugin that
2984 /// was registered for that structured data type. It then
2985 /// calls the following method on the StructuredDataPlugin
2989 /// HandleArrivalOfStructuredData(Process &process,
2990 /// const ConstString &type_name,
2991 /// const StructuredData::ObjectSP
2995 /// True if the structured data was routed to a plugin; otherwise,
2997 //------------------------------------------------------------------
2998 bool RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp);
3000 //------------------------------------------------------------------
3002 //------------------------------------------------------------------
3003 typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP>
3004 LanguageRuntimeCollection;
3005 typedef std::unordered_set<const void *> WarningsPointerSet;
3006 typedef std::map<uint64_t, WarningsPointerSet> WarningsCollection;
3008 struct PreResumeCallbackAndBaton {
3009 bool (*callback)(void *);
3011 PreResumeCallbackAndBaton(PreResumeActionCallback in_callback,
3013 : callback(in_callback), baton(in_baton) {}
3014 bool operator== (const PreResumeCallbackAndBaton &rhs) {
3015 return callback == rhs.callback && baton == rhs.baton;
3019 using StructuredDataPluginMap =
3020 std::map<ConstString, lldb::StructuredDataPluginSP>;
3022 //------------------------------------------------------------------
3024 //------------------------------------------------------------------
3025 std::weak_ptr<Target> m_target_sp; ///< The target that owns this process.
3026 ThreadSafeValue<lldb::StateType> m_public_state;
3027 ThreadSafeValue<lldb::StateType>
3028 m_private_state; // The actual state of our process
3029 Broadcaster m_private_state_broadcaster; // This broadcaster feeds state
3030 // changed events into the private
3031 // state thread's listener.
3032 Broadcaster m_private_state_control_broadcaster; // This is the control
3033 // broadcaster, used to
3034 // pause, resume & stop the
3035 // private state thread.
3036 lldb::ListenerSP m_private_state_listener_sp; // This is the listener for the
3037 // private state thread.
3038 HostThread m_private_state_thread; ///< Thread ID for the thread that watches
3039 ///internal state events
3040 ProcessModID m_mod_id; ///< Tracks the state of the process over stops and
3041 ///other alterations.
3042 uint32_t m_process_unique_id; ///< Each lldb_private::Process class that is
3043 ///created gets a unique integer ID that
3044 ///increments with each new instance
3045 uint32_t m_thread_index_id; ///< Each thread is created with a 1 based index
3046 ///that won't get re-used.
3047 std::map<uint64_t, uint32_t> m_thread_id_to_index_id_map;
3048 int m_exit_status; ///< The exit status of the process, or -1 if not set.
3049 std::string m_exit_string; ///< A textual description of why a process exited.
3050 std::mutex m_exit_status_mutex; ///< Mutex so m_exit_status m_exit_string can
3051 ///be safely accessed from multiple threads
3052 std::recursive_mutex m_thread_mutex;
3053 ThreadList m_thread_list_real; ///< The threads for this process as are known
3054 ///to the protocol we are debugging with
3055 ThreadList m_thread_list; ///< The threads for this process as the user will
3056 ///see them. This is usually the same as
3057 ///< m_thread_list_real, but might be different if there is an OS plug-in
3058 ///creating memory threads
3059 ThreadList m_extended_thread_list; ///< Owner for extended threads that may be
3060 ///generated, cleared on natural stops
3061 uint32_t m_extended_thread_stop_id; ///< The natural stop id when
3062 ///extended_thread_list was last updated
3064 m_queue_list; ///< The list of libdispatch queues at a given stop point
3065 uint32_t m_queue_list_stop_id; ///< The natural stop id when queue list was
3067 std::vector<Notifications> m_notifications; ///< The list of notifications
3068 ///that this process can deliver.
3069 std::vector<lldb::addr_t> m_image_tokens;
3070 lldb::ListenerSP m_listener_sp; ///< Shared pointer to the listener used for
3071 ///public events. Can not be empty.
3072 BreakpointSiteList m_breakpoint_site_list; ///< This is the list of breakpoint
3073 ///locations we intend to insert in
3075 lldb::DynamicLoaderUP m_dyld_ap;
3076 lldb::JITLoaderListUP m_jit_loaders_ap;
3077 lldb::DynamicCheckerFunctionsUP m_dynamic_checkers_ap; ///< The functions used
3078 ///by the expression
3079 ///parser to validate
3082 lldb::OperatingSystemUP m_os_ap;
3083 lldb::SystemRuntimeUP m_system_runtime_ap;
3085 m_unix_signals_sp; /// This is the current signal set for this process.
3086 lldb::ABISP m_abi_sp;
3087 lldb::IOHandlerSP m_process_input_reader;
3088 Communication m_stdio_communication;
3089 std::recursive_mutex m_stdio_communication_mutex;
3090 bool m_stdin_forward; /// Remember if stdin must be forwarded to remote debug
3092 std::string m_stdout_data;
3093 std::string m_stderr_data;
3094 std::recursive_mutex m_profile_data_comm_mutex;
3095 std::vector<std::string> m_profile_data;
3096 Predicate<uint32_t> m_iohandler_sync;
3097 MemoryCache m_memory_cache;
3098 AllocatedMemoryCache m_allocated_memory_cache;
3099 bool m_should_detach; /// Should we detach if the process object goes away
3100 /// with an explicit call to Kill or Detach?
3101 LanguageRuntimeCollection m_language_runtimes;
3102 InstrumentationRuntimeCollection m_instrumentation_runtimes;
3103 std::unique_ptr<NextEventAction> m_next_event_action_ap;
3104 std::vector<PreResumeCallbackAndBaton> m_pre_resume_actions;
3105 ProcessRunLock m_public_run_lock;
3106 ProcessRunLock m_private_run_lock;
3107 bool m_currently_handling_do_on_removals;
3108 bool m_resume_requested; // If m_currently_handling_event or
3109 // m_currently_handling_do_on_removals are true,
3110 // Resume will only request a resume, using this flag
3112 bool m_finalizing; // This is set at the beginning of Process::Finalize() to
3113 // stop functions from looking up or creating things during
3115 bool m_finalize_called; // This is set at the end of Process::Finalize()
3116 bool m_clear_thread_plans_on_stop;
3117 bool m_force_next_event_delivery;
3118 lldb::StateType m_last_broadcast_state; /// This helps with the Public event
3120 /// ShouldBroadcastEvent.
3121 std::map<lldb::addr_t, lldb::addr_t> m_resolved_indirect_addresses;
3122 bool m_destroy_in_process;
3123 bool m_can_interpret_function_calls; // Some targets, e.g the OSX kernel,
3124 // don't support the ability to modify
3126 WarningsCollection m_warnings_issued; // A set of object pointers which have
3127 // already had warnings printed
3128 std::mutex m_run_thread_plan_lock;
3129 StructuredDataPluginMap m_structured_data_plugin_map;
3131 enum { eCanJITDontKnow = 0, eCanJITYes, eCanJITNo } m_can_jit;
3133 size_t RemoveBreakpointOpcodesFromBuffer(lldb::addr_t addr, size_t size,
3134 uint8_t *buf) const;
3136 void SynchronouslyNotifyStateChanged(lldb::StateType state);
3138 void SetPublicState(lldb::StateType new_state, bool restarted);
3140 void SetPrivateState(lldb::StateType state);
3142 bool StartPrivateStateThread(bool is_secondary_thread = false);
3144 void StopPrivateStateThread();
3146 void PausePrivateStateThread();
3148 void ResumePrivateStateThread();
3151 struct PrivateStateThreadArgs {
3152 PrivateStateThreadArgs(Process *p, bool s)
3153 : process(p), is_secondary_thread(s){};
3155 bool is_secondary_thread;
3158 // arg is a pointer to a new'ed PrivateStateThreadArgs structure.
3159 // PrivateStateThread will free it for you.
3160 static lldb::thread_result_t PrivateStateThread(void *arg);
3162 // The starts up the private state thread that will watch for events from the
3164 // Pass true for is_secondary_thread in the case where you have to temporarily
3166 // secondary state thread to handle events from a hand-called function on the
3168 // private state thread.
3170 lldb::thread_result_t RunPrivateStateThread(bool is_secondary_thread);
3173 void HandlePrivateEvent(lldb::EventSP &event_sp);
3175 Status HaltPrivate();
3177 lldb::StateType WaitForProcessStopPrivate(lldb::EventSP &event_sp,
3178 const Timeout<std::micro> &timeout);
3180 // This waits for both the state change broadcaster, and the control
3182 // If control_only, it only waits for the control broadcaster.
3184 bool GetEventsPrivate(lldb::EventSP &event_sp,
3185 const Timeout<std::micro> &timeout, bool control_only);
3188 GetStateChangedEventsPrivate(lldb::EventSP &event_sp,
3189 const Timeout<std::micro> &timeout);
3191 size_t WriteMemoryPrivate(lldb::addr_t addr, const void *buf, size_t size,
3194 void AppendSTDOUT(const char *s, size_t len);
3196 void AppendSTDERR(const char *s, size_t len);
3198 void BroadcastAsyncProfileData(const std::string &one_profile_data);
3200 static void STDIOReadThreadBytesReceived(void *baton, const void *src,
3203 bool PushProcessIOHandler();
3205 bool PopProcessIOHandler();
3207 bool ProcessIOHandlerIsActive();
3209 bool ProcessIOHandlerExists() const {
3210 return static_cast<bool>(m_process_input_reader);
3213 Status StopForDestroyOrDetach(lldb::EventSP &exit_event_sp);
3215 virtual Status UpdateAutomaticSignalFiltering();
3217 bool StateChangedIsExternallyHijacked();
3219 void LoadOperatingSystemPlugin(bool flush);
3222 //------------------------------------------------------------------
3223 /// This is the part of the event handling that for a process event.
3224 /// It decides what to do with the event and returns true if the
3225 /// event needs to be propagated to the user, and false otherwise.
3226 /// If the event is not propagated, this call will most likely set
3227 /// the target to executing again.
3228 /// There is only one place where this call should be called,
3229 /// HandlePrivateEvent.
3230 /// Don't call it from anywhere else...
3232 /// @param[in] event_ptr
3233 /// This is the event we are handling.
3236 /// Returns \b true if the event should be reported to the
3237 /// user, \b false otherwise.
3238 //------------------------------------------------------------------
3239 bool ShouldBroadcastEvent(Event *event_ptr);
3241 void ControlPrivateStateThread(uint32_t signal);
3243 DISALLOW_COPY_AND_ASSIGN(Process);
3246 } // namespace lldb_private
3248 #endif // liblldb_Process_h_