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"
22 #include <unordered_set>
25 #include "lldb/Breakpoint/BreakpointSiteList.h"
26 #include "lldb/Core/Communication.h"
27 #include "lldb/Core/LoadedModuleInfoList.h"
28 #include "lldb/Core/PluginInterface.h"
29 #include "lldb/Core/ThreadSafeValue.h"
30 #include "lldb/Core/UserSettingsController.h"
31 #include "lldb/Host/HostThread.h"
32 #include "lldb/Host/ProcessRunLock.h"
33 #include "lldb/Interpreter/Options.h"
34 #include "lldb/Symbol/ObjectFile.h"
35 #include "lldb/Target/ExecutionContextScope.h"
36 #include "lldb/Target/InstrumentationRuntime.h"
37 #include "lldb/Target/Memory.h"
38 #include "lldb/Target/ProcessInfo.h"
39 #include "lldb/Target/ProcessLaunchInfo.h"
40 #include "lldb/Target/QueueList.h"
41 #include "lldb/Target/ThreadList.h"
42 #include "lldb/Utility/ArchSpec.h"
43 #include "lldb/Utility/Broadcaster.h"
44 #include "lldb/Utility/Event.h"
45 #include "lldb/Utility/Listener.h"
46 #include "lldb/Utility/NameMatches.h"
47 #include "lldb/Utility/Status.h"
48 #include "lldb/Utility/StructuredData.h"
49 #include "lldb/Utility/TraceOptions.h"
50 #include "lldb/lldb-private.h"
52 #include "llvm/ADT/ArrayRef.h"
53 #include "llvm/Support/VersionTuple.h"
55 namespace lldb_private {
57 template <typename B, typename S> struct Range;
59 //----------------------------------------------------------------------
61 //----------------------------------------------------------------------
62 class ProcessProperties : public Properties {
64 // Pass nullptr for "process" if the ProcessProperties are to be the global
66 ProcessProperties(lldb_private::Process *process);
68 ~ProcessProperties() override;
70 bool GetDisableMemoryCache() const;
72 uint64_t GetMemoryCacheLineSize() const;
74 Args GetExtraStartupCommands() const;
76 void SetExtraStartupCommands(const Args &args);
78 FileSpec GetPythonOSPluginPath() const;
80 void SetPythonOSPluginPath(const FileSpec &file);
82 bool GetIgnoreBreakpointsInExpressions() const;
84 void SetIgnoreBreakpointsInExpressions(bool ignore);
86 bool GetUnwindOnErrorInExpressions() const;
88 void SetUnwindOnErrorInExpressions(bool ignore);
90 bool GetStopOnSharedLibraryEvents() const;
92 void SetStopOnSharedLibraryEvents(bool stop);
94 bool GetDetachKeepsStopped() const;
96 void SetDetachKeepsStopped(bool keep_stopped);
98 bool GetWarningsOptimization() const;
100 bool GetStopOnExec() const;
103 static void OptionValueChangedCallback(void *baton,
104 OptionValue *option_value);
106 Process *m_process; // Can be nullptr for global ProcessProperties
109 typedef std::shared_ptr<ProcessProperties> ProcessPropertiesSP;
111 //----------------------------------------------------------------------
112 // ProcessInstanceInfo
114 // Describes an existing process and any discoverable information that pertains
116 //----------------------------------------------------------------------
117 class ProcessInstanceInfo : public ProcessInfo {
119 ProcessInstanceInfo()
120 : ProcessInfo(), m_euid(UINT32_MAX), m_egid(UINT32_MAX),
121 m_parent_pid(LLDB_INVALID_PROCESS_ID) {}
123 ProcessInstanceInfo(const char *name, const ArchSpec &arch, lldb::pid_t pid)
124 : ProcessInfo(name, arch, pid), m_euid(UINT32_MAX), m_egid(UINT32_MAX),
125 m_parent_pid(LLDB_INVALID_PROCESS_ID) {}
128 ProcessInfo::Clear();
131 m_parent_pid = LLDB_INVALID_PROCESS_ID;
134 uint32_t GetEffectiveUserID() const { return m_euid; }
136 uint32_t GetEffectiveGroupID() const { return m_egid; }
138 bool EffectiveUserIDIsValid() const { return m_euid != UINT32_MAX; }
140 bool EffectiveGroupIDIsValid() const { return m_egid != UINT32_MAX; }
142 void SetEffectiveUserID(uint32_t uid) { m_euid = uid; }
144 void SetEffectiveGroupID(uint32_t gid) { m_egid = gid; }
146 lldb::pid_t GetParentProcessID() const { return m_parent_pid; }
148 void SetParentProcessID(lldb::pid_t pid) { m_parent_pid = pid; }
150 bool ParentProcessIDIsValid() const {
151 return m_parent_pid != LLDB_INVALID_PROCESS_ID;
154 void Dump(Stream &s, Platform *platform) const;
156 static void DumpTableHeader(Stream &s, Platform *platform, bool show_args,
159 void DumpAsTableRow(Stream &s, Platform *platform, bool show_args,
165 lldb::pid_t m_parent_pid;
168 //----------------------------------------------------------------------
171 // Describes any information that is required to attach to a process.
172 //----------------------------------------------------------------------
174 class ProcessAttachInfo : public ProcessInstanceInfo {
177 : ProcessInstanceInfo(), m_listener_sp(), m_hijack_listener_sp(),
178 m_plugin_name(), m_resume_count(0), m_wait_for_launch(false),
179 m_ignore_existing(true), m_continue_once_attached(false),
180 m_detach_on_error(true), m_async(false) {}
182 ProcessAttachInfo(const ProcessLaunchInfo &launch_info)
183 : ProcessInstanceInfo(), m_listener_sp(), m_hijack_listener_sp(),
184 m_plugin_name(), m_resume_count(0), m_wait_for_launch(false),
185 m_ignore_existing(true), m_continue_once_attached(false),
186 m_detach_on_error(true), m_async(false) {
187 ProcessInfo::operator=(launch_info);
188 SetProcessPluginName(launch_info.GetProcessPluginName());
189 SetResumeCount(launch_info.GetResumeCount());
190 SetListener(launch_info.GetListener());
191 SetHijackListener(launch_info.GetHijackListener());
192 m_detach_on_error = launch_info.GetDetachOnError();
195 bool GetWaitForLaunch() const { return m_wait_for_launch; }
197 void SetWaitForLaunch(bool b) { m_wait_for_launch = b; }
199 bool GetAsync() const { return m_async; }
201 void SetAsync(bool b) { m_async = b; }
203 bool GetIgnoreExisting() const { return m_ignore_existing; }
205 void SetIgnoreExisting(bool b) { m_ignore_existing = b; }
207 bool GetContinueOnceAttached() const { return m_continue_once_attached; }
209 void SetContinueOnceAttached(bool b) { m_continue_once_attached = b; }
211 uint32_t GetResumeCount() const { return m_resume_count; }
213 void SetResumeCount(uint32_t c) { m_resume_count = c; }
215 const char *GetProcessPluginName() const {
216 return (m_plugin_name.empty() ? nullptr : m_plugin_name.c_str());
219 void SetProcessPluginName(llvm::StringRef plugin) { m_plugin_name = plugin; }
222 ProcessInstanceInfo::Clear();
223 m_plugin_name.clear();
225 m_wait_for_launch = false;
226 m_ignore_existing = true;
227 m_continue_once_attached = false;
230 bool ProcessInfoSpecified() const {
231 if (GetExecutableFile())
233 if (GetProcessID() != LLDB_INVALID_PROCESS_ID)
235 if (GetParentProcessID() != LLDB_INVALID_PROCESS_ID)
240 lldb::ListenerSP GetHijackListener() const { return m_hijack_listener_sp; }
242 void SetHijackListener(const lldb::ListenerSP &listener_sp) {
243 m_hijack_listener_sp = listener_sp;
246 bool GetDetachOnError() const { return m_detach_on_error; }
248 void SetDetachOnError(bool enable) { m_detach_on_error = enable; }
250 // Get and set the actual listener that will be used for the process events
251 lldb::ListenerSP GetListener() const { return m_listener_sp; }
253 void SetListener(const lldb::ListenerSP &listener_sp) {
254 m_listener_sp = listener_sp;
257 lldb::ListenerSP GetListenerForProcess(Debugger &debugger);
260 lldb::ListenerSP m_listener_sp;
261 lldb::ListenerSP m_hijack_listener_sp;
262 std::string m_plugin_name;
263 uint32_t m_resume_count; // How many times do we resume after launching
264 bool m_wait_for_launch;
265 bool m_ignore_existing;
266 bool m_continue_once_attached; // Supports the use-case scenario of
267 // immediately continuing the process once
269 bool m_detach_on_error; // If we are debugging remotely, instruct the stub to
270 // detach rather than killing the target on error.
271 bool m_async; // Use an async attach where we start the attach and return
272 // immediately (used by GUI programs with --waitfor so they can
273 // call SBProcess::Stop() to cancel attach)
276 class ProcessLaunchCommandOptions : public Options {
278 ProcessLaunchCommandOptions() : Options() {
279 // Keep default values of all options in one place: OptionParsingStarting
281 OptionParsingStarting(nullptr);
284 ~ProcessLaunchCommandOptions() override = default;
286 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
287 ExecutionContext *execution_context) override;
289 void OptionParsingStarting(ExecutionContext *execution_context) override {
291 disable_aslr = eLazyBoolCalculate;
294 llvm::ArrayRef<OptionDefinition> GetDefinitions() override;
296 // Instance variables to hold the values for command options.
298 ProcessLaunchInfo launch_info;
299 lldb_private::LazyBool disable_aslr;
302 //----------------------------------------------------------------------
303 // ProcessInstanceInfoMatch
305 // A class to help matching one ProcessInstanceInfo to another.
306 //----------------------------------------------------------------------
308 class ProcessInstanceInfoMatch {
310 ProcessInstanceInfoMatch()
311 : m_match_info(), m_name_match_type(NameMatch::Ignore),
312 m_match_all_users(false) {}
314 ProcessInstanceInfoMatch(const char *process_name,
315 NameMatch process_name_match_type)
316 : m_match_info(), m_name_match_type(process_name_match_type),
317 m_match_all_users(false) {
318 m_match_info.GetExecutableFile().SetFile(process_name,
319 FileSpec::Style::native);
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
391 // currently modify the program are running the program (which will up the
392 // StopID) and writing memory (which will up the MemoryID.)
393 // FIXME: Should we also include modification of register states?
396 friend bool operator==(const ProcessModID &lhs, const ProcessModID &rhs);
400 : m_stop_id(0), m_last_natural_stop_id(0), m_resume_id(0), m_memory_id(0),
401 m_last_user_expression_resume(0), m_running_user_expression(false),
402 m_running_utility_function(0) {}
404 ProcessModID(const ProcessModID &rhs)
405 : m_stop_id(rhs.m_stop_id), m_memory_id(rhs.m_memory_id) {}
407 const ProcessModID &operator=(const ProcessModID &rhs) {
409 m_stop_id = rhs.m_stop_id;
410 m_memory_id = rhs.m_memory_id;
415 ~ProcessModID() = default;
419 if (!IsLastResumeForUserExpression())
420 m_last_natural_stop_id++;
423 void BumpMemoryID() { m_memory_id++; }
425 void BumpResumeID() {
427 if (m_running_user_expression > 0)
428 m_last_user_expression_resume = m_resume_id;
431 bool IsRunningUtilityFunction() const {
432 return m_running_utility_function > 0;
435 uint32_t GetStopID() const { return m_stop_id; }
436 uint32_t GetLastNaturalStopID() const { return m_last_natural_stop_id; }
437 uint32_t GetMemoryID() const { return m_memory_id; }
438 uint32_t GetResumeID() const { return m_resume_id; }
439 uint32_t GetLastUserExpressionResumeID() const {
440 return m_last_user_expression_resume;
443 bool MemoryIDEqual(const ProcessModID &compare) const {
444 return m_memory_id == compare.m_memory_id;
447 bool StopIDEqual(const ProcessModID &compare) const {
448 return m_stop_id == compare.m_stop_id;
451 void SetInvalid() { m_stop_id = UINT32_MAX; }
453 bool IsValid() const { return m_stop_id != UINT32_MAX; }
455 bool IsLastResumeForUserExpression() const {
456 // If we haven't yet resumed the target, then it can't be for a user
458 if (m_resume_id == 0)
461 return m_resume_id == m_last_user_expression_resume;
464 void SetRunningUserExpression(bool on) {
466 m_running_user_expression++;
468 m_running_user_expression--;
471 void SetRunningUtilityFunction(bool on) {
473 m_running_utility_function++;
475 assert(m_running_utility_function > 0 &&
476 "Called SetRunningUtilityFunction(false) without calling "
477 "SetRunningUtilityFunction(true) before?");
478 m_running_utility_function--;
482 void SetStopEventForLastNaturalStopID(lldb::EventSP event_sp) {
483 m_last_natural_stop_event = event_sp;
486 lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const {
487 if (stop_id == m_last_natural_stop_id)
488 return m_last_natural_stop_event;
489 return lldb::EventSP();
494 uint32_t m_last_natural_stop_id;
495 uint32_t m_resume_id;
496 uint32_t m_memory_id;
497 uint32_t m_last_user_expression_resume;
498 uint32_t m_running_user_expression;
499 uint32_t m_running_utility_function;
500 lldb::EventSP m_last_natural_stop_event;
503 inline bool operator==(const ProcessModID &lhs, const ProcessModID &rhs) {
504 if (lhs.StopIDEqual(rhs) && lhs.MemoryIDEqual(rhs))
510 inline bool operator!=(const ProcessModID &lhs, const ProcessModID &rhs) {
511 return (!lhs.StopIDEqual(rhs) || !lhs.MemoryIDEqual(rhs));
514 //----------------------------------------------------------------------
515 /// @class Process Process.h "lldb/Target/Process.h"
516 /// A plug-in interface definition class for debugging a process.
517 //----------------------------------------------------------------------
518 class Process : public std::enable_shared_from_this<Process>,
519 public ProcessProperties,
522 public ExecutionContextScope,
523 public PluginInterface {
524 friend class FunctionCaller; // For WaitForStateChangeEventsPrivate
525 friend class Debugger; // For PopProcessIOHandler and ProcessIOHandlerIsActive
526 friend class DynamicLoader; // For LoadOperatingSystemPlugin
527 friend class ProcessEventData;
528 friend class StopInfo;
530 friend class ThreadList;
533 //------------------------------------------------------------------
534 /// Broadcaster event bits definitions.
535 //------------------------------------------------------------------
537 eBroadcastBitStateChanged = (1 << 0),
538 eBroadcastBitInterrupt = (1 << 1),
539 eBroadcastBitSTDOUT = (1 << 2),
540 eBroadcastBitSTDERR = (1 << 3),
541 eBroadcastBitProfileData = (1 << 4),
542 eBroadcastBitStructuredData = (1 << 5),
546 eBroadcastInternalStateControlStop = (1 << 0),
547 eBroadcastInternalStateControlPause = (1 << 1),
548 eBroadcastInternalStateControlResume = (1 << 2)
551 //------------------------------------------------------------------
552 /// Process warning types.
553 //------------------------------------------------------------------
554 enum Warnings { eWarningsOptimization = 1 };
556 typedef Range<lldb::addr_t, lldb::addr_t> LoadRange;
557 // We use a read/write lock to allow on or more clients to access the process
558 // state while the process is stopped (reader). We lock the write lock to
559 // control access to the process while it is running (readers, or clients
560 // that want the process stopped can block waiting for the process to stop,
561 // or just try to lock it to see if they can immediately access the stopped
562 // process. If the try read lock fails, then the process is running.
563 typedef ProcessRunLock::ProcessRunLocker StopLocker;
565 // These two functions fill out the Broadcaster interface:
567 static ConstString &GetStaticBroadcasterClass();
569 ConstString &GetBroadcasterClass() const override {
570 return GetStaticBroadcasterClass();
573 //------------------------------------------------------------------
574 /// A notification structure that can be used by clients to listen
575 /// for changes in a process's lifetime.
577 /// @see RegisterNotificationCallbacks (const Notifications&) @see
578 /// UnregisterNotificationCallbacks (const Notifications&)
579 //------------------------------------------------------------------
583 void (*initialize)(void *baton, Process *process);
584 void (*process_state_changed)(void *baton, Process *process,
585 lldb::StateType state);
588 class ProcessEventData : public EventData {
589 friend class Process;
593 ProcessEventData(const lldb::ProcessSP &process, lldb::StateType state);
595 ~ProcessEventData() override;
597 static const ConstString &GetFlavorString();
599 const ConstString &GetFlavor() const override;
601 lldb::ProcessSP GetProcessSP() const { return m_process_wp.lock(); }
603 lldb::StateType GetState() const { return m_state; }
604 bool GetRestarted() const { return m_restarted; }
606 size_t GetNumRestartedReasons() { return m_restarted_reasons.size(); }
608 const char *GetRestartedReasonAtIndex(size_t idx) {
609 return ((idx < m_restarted_reasons.size())
610 ? m_restarted_reasons[idx].c_str()
614 bool GetInterrupted() const { return m_interrupted; }
616 void Dump(Stream *s) const override;
618 void DoOnRemoval(Event *event_ptr) override;
620 static const Process::ProcessEventData *
621 GetEventDataFromEvent(const Event *event_ptr);
623 static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr);
625 static lldb::StateType GetStateFromEvent(const Event *event_ptr);
627 static bool GetRestartedFromEvent(const Event *event_ptr);
629 static size_t GetNumRestartedReasons(const Event *event_ptr);
631 static const char *GetRestartedReasonAtIndex(const Event *event_ptr,
634 static void AddRestartedReason(Event *event_ptr, const char *reason);
636 static void SetRestartedInEvent(Event *event_ptr, bool new_value);
638 static bool GetInterruptedFromEvent(const Event *event_ptr);
640 static void SetInterruptedInEvent(Event *event_ptr, bool new_value);
642 static bool SetUpdateStateOnRemoval(Event *event_ptr);
645 void SetUpdateStateOnRemoval() { m_update_state++; }
647 void SetRestarted(bool new_value) { m_restarted = new_value; }
649 void SetInterrupted(bool new_value) { m_interrupted = new_value; }
651 void AddRestartedReason(const char *reason) {
652 m_restarted_reasons.push_back(reason);
655 lldb::ProcessWP m_process_wp;
656 lldb::StateType m_state;
657 std::vector<std::string> m_restarted_reasons;
658 bool m_restarted; // For "eStateStopped" events, this is true if the target
659 // was automatically restarted.
663 DISALLOW_COPY_AND_ASSIGN(ProcessEventData);
667 //------------------------------------------------------------------
668 /// Construct with a shared pointer to a target, and the Process listener.
669 /// Uses the Host UnixSignalsSP by default.
670 //------------------------------------------------------------------
671 Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp);
673 //------------------------------------------------------------------
674 /// Construct with a shared pointer to a target, the Process listener, and
675 /// the appropriate UnixSignalsSP for the process.
676 //------------------------------------------------------------------
677 Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp,
678 const lldb::UnixSignalsSP &unix_signals_sp);
680 //------------------------------------------------------------------
683 /// The destructor is virtual since this class is designed to be inherited
684 /// from by the plug-in instance.
685 //------------------------------------------------------------------
688 static void SettingsInitialize();
690 static void SettingsTerminate();
692 static const ProcessPropertiesSP &GetGlobalProperties();
694 //------------------------------------------------------------------
695 /// Find a Process plug-in that can debug \a module using the currently
696 /// selected architecture.
698 /// Scans all loaded plug-in interfaces that implement versions of the
699 /// Process plug-in interface and returns the first instance that can debug
702 /// @param[in] module_sp
703 /// The module shared pointer that this process will debug.
705 /// @param[in] plugin_name
706 /// If nullptr, select the best plug-in for the binary. If non-nullptr
707 /// then look for a plugin whose PluginInfo's name matches
710 /// @see Process::CanDebug ()
711 //------------------------------------------------------------------
712 static lldb::ProcessSP FindPlugin(lldb::TargetSP target_sp,
713 llvm::StringRef plugin_name,
714 lldb::ListenerSP listener_sp,
715 const FileSpec *crash_file_path);
717 //------------------------------------------------------------------
718 /// Static function that can be used with the \b host function
719 /// Host::StartMonitoringChildProcess ().
721 /// This function can be used by lldb_private::Process subclasses when they
722 /// want to watch for a local process and have its exit status automatically
723 /// set when the host child process exits. Subclasses should call
724 /// Host::StartMonitoringChildProcess () with:
725 /// callback = Process::SetHostProcessExitStatus
726 /// pid = Process::GetID()
727 /// monitor_signals = false
728 //------------------------------------------------------------------
730 SetProcessExitStatus(lldb::pid_t pid, // The process ID we want to monitor
732 int signo, // Zero for no signal
733 int status); // Exit value of process if signal is zero
735 lldb::ByteOrder GetByteOrder() const;
737 uint32_t GetAddressByteSize() const;
739 uint32_t GetUniqueID() const { return m_process_unique_id; }
741 //------------------------------------------------------------------
742 /// Check if a plug-in instance can debug the file in \a module.
744 /// Each plug-in is given a chance to say whether it can debug the file in
745 /// \a module. If the Process plug-in instance can debug a file on the
746 /// current system, it should return \b true.
749 /// Returns \b true if this Process plug-in instance can
750 /// debug the executable, \b false otherwise.
751 //------------------------------------------------------------------
752 virtual bool CanDebug(lldb::TargetSP target,
753 bool plugin_specified_by_name) = 0;
755 //------------------------------------------------------------------
756 /// This object is about to be destroyed, do any necessary cleanup.
758 /// Subclasses that override this method should always call this superclass
760 //------------------------------------------------------------------
761 virtual void Finalize();
763 //------------------------------------------------------------------
764 /// Return whether this object is valid (i.e. has not been finalized.)
767 /// Returns \b true if this Process has not been finalized
768 /// and \b false otherwise.
769 //------------------------------------------------------------------
770 bool IsValid() const { return !m_finalize_called; }
772 //------------------------------------------------------------------
773 /// Return a multi-word command object that can be used to expose plug-in
774 /// specific commands.
776 /// This object will be used to resolve plug-in commands and can be
777 /// triggered by a call to:
779 /// (lldb) process command <args>
782 /// A CommandObject which can be one of the concrete subclasses
783 /// of CommandObject like CommandObjectRaw, CommandObjectParsed,
784 /// or CommandObjectMultiword.
785 //------------------------------------------------------------------
786 virtual CommandObject *GetPluginCommandObject() { return nullptr; }
788 //------------------------------------------------------------------
789 /// Launch a new process.
791 /// Launch a new process by spawning a new process using the target object's
792 /// executable module's file as the file to launch.
794 /// This function is not meant to be overridden by Process subclasses. It
795 /// will first call Process::WillLaunch (Module *) and if that returns \b
796 /// true, Process::DoLaunch (Module*, char const *[],char const *[],const
797 /// char *,const char *, const char *) will be called to actually do the
798 /// launching. If DoLaunch returns \b true, then Process::DidLaunch() will
801 /// @param[in] launch_info
802 /// Details regarding the environment, STDIN/STDOUT/STDERR
803 /// redirection, working path, etc. related to the requested launch.
806 /// An error object. Call GetID() to get the process ID if
807 /// the error object is success.
808 //------------------------------------------------------------------
809 virtual Status Launch(ProcessLaunchInfo &launch_info);
811 virtual Status LoadCore();
813 virtual Status DoLoadCore() {
815 error.SetErrorStringWithFormat(
816 "error: %s does not support loading core files.",
817 GetPluginName().GetCString());
821 //------------------------------------------------------------------
822 // FUTURE WORK: GetLoadImageUtilityFunction are the first use we've
823 // had of having other plugins cache data in the Process. This is handy for
824 // long-living plugins - like the Platform - which manage interactions whose
825 // lifetime is governed by the Process lifetime. If we find we need to do
826 // this more often, we should construct a general solution to the problem.
827 // The consensus suggestion was that we have a token based registry in the
828 // Process. Some undecided questions are (1) who manages the tokens. It's
829 // probably best that you add the element and get back a token that
830 // represents it. That will avoid collisions. But there may be some utility
831 // in the registerer controlling the token? (2) whether the thing added
832 // should be simply owned by Process, and just go away when it does (3)
833 // whether the registree should be notified of the Process' demise.
835 // We are postponing designing this till we have at least a second use case.
836 //------------------------------------------------------------------
837 //------------------------------------------------------------------
838 /// Get the cached UtilityFunction that assists in loading binary images
839 /// into the process.
841 /// @param[in] platform
842 /// The platform fetching the UtilityFunction.
843 /// @param[in] factory
844 /// A function that will be called only once per-process in a
845 /// thread-safe way to create the UtilityFunction if it has not
846 /// been initialized yet.
849 /// The cached utility function or null if the platform is not the
850 /// same as the target's platform.
851 //------------------------------------------------------------------
852 UtilityFunction *GetLoadImageUtilityFunction(
854 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory);
856 //------------------------------------------------------------------
857 /// Get the dynamic loader plug-in for this process.
859 /// The default action is to let the DynamicLoader plug-ins check the main
860 /// executable and the DynamicLoader will select itself automatically.
861 /// Subclasses can override this if inspecting the executable is not
862 /// desired, or if Process subclasses can only use a specific DynamicLoader
864 //------------------------------------------------------------------
865 virtual DynamicLoader *GetDynamicLoader();
867 //------------------------------------------------------------------
868 // Returns AUXV structure found in many ELF-based environments.
870 // The default action is to return an empty data buffer.
873 // A data buffer containing the contents of the AUXV data.
874 //------------------------------------------------------------------
875 virtual const lldb::DataBufferSP GetAuxvData();
877 //------------------------------------------------------------------
878 /// Sometimes processes know how to retrieve and load shared libraries. This
879 /// is normally done by DynamicLoader plug-ins, but sometimes the connection
880 /// to the process allows retrieving this information. The dynamic loader
881 /// plug-ins can use this function if they can't determine the current
882 /// shared library load state.
885 /// The number of shared libraries that were loaded
886 //------------------------------------------------------------------
887 virtual size_t LoadModules() { return 0; }
889 virtual size_t LoadModules(LoadedModuleInfoList &) { return 0; }
892 virtual JITLoaderList &GetJITLoaders();
895 //------------------------------------------------------------------
896 /// Get the system runtime plug-in for this process.
899 /// Returns a pointer to the SystemRuntime plugin for this Process
900 /// if one is available. Else returns nullptr.
901 //------------------------------------------------------------------
902 virtual SystemRuntime *GetSystemRuntime();
904 //------------------------------------------------------------------
905 /// Attach to an existing process using the process attach info.
907 /// This function is not meant to be overridden by Process subclasses. It
908 /// will first call WillAttach (lldb::pid_t) or WillAttach (const char *),
909 /// and if that returns \b true, DoAttach (lldb::pid_t) or DoAttach (const
910 /// char *) will be called to actually do the attach. If DoAttach returns \b
911 /// true, then Process::DidAttach() will be called.
914 /// The process ID that we should attempt to attach to.
917 /// Returns \a pid if attaching was successful, or
918 /// LLDB_INVALID_PROCESS_ID if attaching fails.
919 //------------------------------------------------------------------
920 virtual Status Attach(ProcessAttachInfo &attach_info);
922 //------------------------------------------------------------------
923 /// Attach to a remote system via a URL
926 /// A stream where output intended for the user
927 /// (if the driver has a way to display that) generated during
928 /// the connection. This may be nullptr if no output is needed.A
930 /// @param[in] remote_url
931 /// The URL format that we are connecting to.
934 /// Returns an error object.
935 //------------------------------------------------------------------
936 virtual Status ConnectRemote(Stream *strm, llvm::StringRef remote_url);
938 bool GetShouldDetach() const { return m_should_detach; }
940 void SetShouldDetach(bool b) { m_should_detach = b; }
942 //------------------------------------------------------------------
943 /// Get the image information address for the current process.
945 /// Some runtimes have system functions that can help dynamic loaders locate
946 /// the dynamic loader information needed to observe shared libraries being
947 /// loaded or unloaded. This function is in the Process interface (as
948 /// opposed to the DynamicLoader interface) to ensure that remote debugging
949 /// can take advantage of this functionality.
952 /// The address of the dynamic loader information, or
953 /// LLDB_INVALID_ADDRESS if this is not supported by this
955 //------------------------------------------------------------------
956 virtual lldb::addr_t GetImageInfoAddress();
958 //------------------------------------------------------------------
959 /// Called when the process is about to broadcast a public stop.
961 /// There are public and private stops. Private stops are when the process
962 /// is doing things like stepping and the client doesn't need to know about
963 /// starts and stop that implement a thread plan. Single stepping over a
964 /// source line in code might end up being implemented by one or more
965 /// process starts and stops. Public stops are when clients will be notified
966 /// that the process is stopped. These events typically trigger UI updates
967 /// (thread stack frames to be displayed, variables to be displayed, and
968 /// more). This function can be overriden and allows process subclasses to
969 /// do something before the eBroadcastBitStateChanged event is sent to
971 //------------------------------------------------------------------
972 virtual void WillPublicStop() {}
974 //------------------------------------------------------------------
975 /// Register for process and thread notifications.
977 /// Clients can register notification callbacks by filling out a
978 /// Process::Notifications structure and calling this function.
980 /// @param[in] callbacks
981 /// A structure that contains the notification baton and
982 /// callback functions.
984 /// @see Process::Notifications
985 //------------------------------------------------------------------
987 void RegisterNotificationCallbacks(const Process::Notifications &callbacks);
990 //------------------------------------------------------------------
991 /// Unregister for process and thread notifications.
993 /// Clients can unregister notification callbacks by passing a copy of the
994 /// original baton and callbacks in \a callbacks.
996 /// @param[in] callbacks
997 /// A structure that contains the notification baton and
998 /// callback functions.
1001 /// Returns \b true if the notification callbacks were
1002 /// successfully removed from the process, \b false otherwise.
1004 /// @see Process::Notifications
1005 //------------------------------------------------------------------
1007 bool UnregisterNotificationCallbacks(const Process::Notifications &callbacks);
1010 //==================================================================
1011 // Built in Process Control functions
1012 //==================================================================
1013 //------------------------------------------------------------------
1014 /// Resumes all of a process's threads as configured using the Thread run
1015 /// control functions.
1017 /// Threads for a process should be updated with one of the run control
1018 /// actions (resume, step, or suspend) that they should take when the
1019 /// process is resumed. If no run control action is given to a thread it
1020 /// will be resumed by default.
1022 /// This function is not meant to be overridden by Process subclasses. This
1023 /// function will take care of disabling any breakpoints that threads may be
1024 /// stopped at, single stepping, and re-enabling breakpoints, and enabling
1025 /// the basic flow control that the plug-in instances need not worry about.
1027 /// N.B. This function also sets the Write side of the Run Lock, which is
1028 /// unset when the corresponding stop event is pulled off the Public Event
1029 /// Queue. If you need to resume the process without setting the Run Lock,
1030 /// use PrivateResume (though you should only do that from inside the
1034 /// Returns an error object.
1036 /// @see Thread:Resume()
1037 /// @see Thread:Step()
1038 /// @see Thread:Suspend()
1039 //------------------------------------------------------------------
1042 Status ResumeSynchronous(Stream *stream);
1044 //------------------------------------------------------------------
1045 /// Halts a running process.
1047 /// This function is not meant to be overridden by Process subclasses. If
1048 /// the process is successfully halted, a eStateStopped process event with
1049 /// GetInterrupted will be broadcast. If false, we will halt the process
1050 /// with no events generated by the halt.
1052 /// @param[in] clear_thread_plans
1053 /// If true, when the process stops, clear all thread plans.
1055 /// @param[in] use_run_lock
1056 /// Whether to release the run lock after the stop.
1059 /// Returns an error object. If the error is empty, the process is
1061 /// otherwise the halt has failed.
1062 //------------------------------------------------------------------
1063 Status Halt(bool clear_thread_plans = false, bool use_run_lock = true);
1065 //------------------------------------------------------------------
1066 /// Detaches from a running or stopped process.
1068 /// This function is not meant to be overridden by Process subclasses.
1070 /// @param[in] keep_stopped
1071 /// If true, don't resume the process on detach.
1074 /// Returns an error object.
1075 //------------------------------------------------------------------
1076 Status Detach(bool keep_stopped);
1078 //------------------------------------------------------------------
1079 /// Kills the process and shuts down all threads that were spawned to track
1080 /// and monitor the process.
1082 /// This function is not meant to be overridden by Process subclasses.
1084 /// @param[in] force_kill
1085 /// Whether lldb should force a kill (instead of a detach) from
1086 /// the inferior process. Normally if lldb launched a binary and
1087 /// Destory is called, lldb kills it. If lldb attached to a
1088 /// running process and Destory is called, lldb detaches. If
1089 /// this behavior needs to be over-ridden, this is the bool that
1093 /// Returns an error object.
1094 //------------------------------------------------------------------
1095 Status Destroy(bool force_kill);
1097 //------------------------------------------------------------------
1098 /// Sends a process a UNIX signal \a signal.
1100 /// This function is not meant to be overridden by Process subclasses.
1103 /// Returns an error object.
1104 //------------------------------------------------------------------
1105 Status Signal(int signal);
1107 void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp);
1109 const lldb::UnixSignalsSP &GetUnixSignals();
1111 //==================================================================
1112 // Plug-in Process Control Overrides
1113 //==================================================================
1115 //------------------------------------------------------------------
1116 /// Called before attaching to a process.
1118 /// Allow Process plug-ins to execute some code before attaching a process.
1121 /// Returns an error object.
1122 //------------------------------------------------------------------
1123 virtual Status WillAttachToProcessWithID(lldb::pid_t pid) { return Status(); }
1125 //------------------------------------------------------------------
1126 /// Called before attaching to a process.
1128 /// Allow Process plug-ins to execute some code before attaching a process.
1131 /// Returns an error object.
1132 //------------------------------------------------------------------
1133 virtual Status WillAttachToProcessWithName(const char *process_name,
1134 bool wait_for_launch) {
1138 //------------------------------------------------------------------
1139 /// Attach to a remote system via a URL
1142 /// A stream where output intended for the user
1143 /// (if the driver has a way to display that) generated during
1144 /// the connection. This may be nullptr if no output is needed.A
1146 /// @param[in] remote_url
1147 /// The URL format that we are connecting to.
1150 /// Returns an error object.
1151 //------------------------------------------------------------------
1152 virtual Status DoConnectRemote(Stream *strm, llvm::StringRef remote_url) {
1154 error.SetErrorString("remote connections are not supported");
1158 //------------------------------------------------------------------
1159 /// Attach to an existing process using a process ID.
1162 /// The process ID that we should attempt to attach to.
1164 /// @param[in] attach_info
1165 /// Information on how to do the attach. For example, GetUserID()
1166 /// will return the uid to attach as.
1169 /// Returns a successful Status attaching was successful, or
1170 /// an appropriate (possibly platform-specific) error code if
1171 /// attaching fails.
1172 /// hanming : need flag
1173 //------------------------------------------------------------------
1174 virtual Status DoAttachToProcessWithID(lldb::pid_t pid,
1175 const ProcessAttachInfo &attach_info) {
1177 error.SetErrorStringWithFormat(
1178 "error: %s does not support attaching to a process by pid",
1179 GetPluginName().GetCString());
1183 //------------------------------------------------------------------
1184 /// Attach to an existing process using a partial process name.
1186 /// @param[in] process_name
1187 /// The name of the process to attach to.
1189 /// @param[in] attach_info
1190 /// Information on how to do the attach. For example, GetUserID()
1191 /// will return the uid to attach as.
1194 /// Returns a successful Status attaching was successful, or
1195 /// an appropriate (possibly platform-specific) error code if
1196 /// attaching fails.
1197 //------------------------------------------------------------------
1199 DoAttachToProcessWithName(const char *process_name,
1200 const ProcessAttachInfo &attach_info) {
1202 error.SetErrorString("attach by name is not supported");
1206 //------------------------------------------------------------------
1207 /// Called after attaching a process.
1209 /// @param[in] process_arch
1210 /// If you can figure out the process architecture after attach, fill it
1213 /// Allow Process plug-ins to execute some code after attaching to a
1215 //------------------------------------------------------------------
1216 virtual void DidAttach(ArchSpec &process_arch) { process_arch.Clear(); }
1218 //------------------------------------------------------------------
1219 /// Called after a process re-execs itself.
1221 /// Allow Process plug-ins to execute some code after a process has exec'ed
1222 /// itself. Subclasses typically should override DoDidExec() as the
1223 /// lldb_private::Process class needs to remove its dynamic loader, runtime,
1224 /// ABI and other plug-ins, as well as unload all shared libraries.
1225 //------------------------------------------------------------------
1226 virtual void DidExec();
1228 //------------------------------------------------------------------
1229 /// Subclasses of Process should implement this function if they need to do
1230 /// anything after a process exec's itself.
1231 //------------------------------------------------------------------
1232 virtual void DoDidExec() {}
1234 //------------------------------------------------------------------
1235 /// Called before launching to a process.
1237 /// Allow Process plug-ins to execute some code before launching a process.
1240 /// Returns an error object.
1241 //------------------------------------------------------------------
1242 virtual Status WillLaunch(Module *module) { return Status(); }
1244 //------------------------------------------------------------------
1245 /// Launch a new process.
1247 /// Launch a new process by spawning a new process using \a exe_module's
1248 /// file as the file to launch. Launch details are provided in \a
1251 /// @param[in] exe_module
1252 /// The module from which to extract the file specification and
1255 /// @param[in] launch_info
1256 /// Details (e.g. arguments, stdio redirection, etc.) for the
1257 /// requested launch.
1260 /// An Status instance indicating success or failure of the
1262 //------------------------------------------------------------------
1263 virtual Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) {
1265 error.SetErrorStringWithFormat(
1266 "error: %s does not support launching processes",
1267 GetPluginName().GetCString());
1271 //------------------------------------------------------------------
1272 /// Called after launching a process.
1274 /// Allow Process plug-ins to execute some code after launching a process.
1275 //------------------------------------------------------------------
1276 virtual void DidLaunch() {}
1278 //------------------------------------------------------------------
1279 /// Called before resuming to a process.
1281 /// Allow Process plug-ins to execute some code before resuming a process.
1284 /// Returns an error object.
1285 //------------------------------------------------------------------
1286 virtual Status WillResume() { return Status(); }
1288 //------------------------------------------------------------------
1289 /// Resumes all of a process's threads as configured using the Thread run
1290 /// control functions.
1292 /// Threads for a process should be updated with one of the run control
1293 /// actions (resume, step, or suspend) that they should take when the
1294 /// process is resumed. If no run control action is given to a thread it
1295 /// will be resumed by default.
1298 /// Returns \b true if the process successfully resumes using
1299 /// the thread run control actions, \b false otherwise.
1301 /// @see Thread:Resume()
1302 /// @see Thread:Step()
1303 /// @see Thread:Suspend()
1304 //------------------------------------------------------------------
1305 virtual Status DoResume() {
1307 error.SetErrorStringWithFormat(
1308 "error: %s does not support resuming processes",
1309 GetPluginName().GetCString());
1313 //------------------------------------------------------------------
1314 /// Called after resuming a process.
1316 /// Allow Process plug-ins to execute some code after resuming a process.
1317 //------------------------------------------------------------------
1318 virtual void DidResume() {}
1320 //------------------------------------------------------------------
1321 /// Called before halting to a process.
1323 /// Allow Process plug-ins to execute some code before halting a process.
1326 /// Returns an error object.
1327 //------------------------------------------------------------------
1328 virtual Status WillHalt() { return Status(); }
1330 //------------------------------------------------------------------
1331 /// Halts a running process.
1333 /// DoHalt must produce one and only one stop StateChanged event if it
1334 /// actually stops the process. If the stop happens through some natural
1335 /// event (for instance a SIGSTOP), then forwarding that event will do.
1336 /// Otherwise, you must generate the event manually. This function is called
1337 /// from the context of the private state thread.
1339 /// @param[out] caused_stop
1340 /// If true, then this Halt caused the stop, otherwise, the
1341 /// process was already stopped.
1344 /// Returns \b true if the process successfully halts, \b false
1346 //------------------------------------------------------------------
1347 virtual Status DoHalt(bool &caused_stop) {
1349 error.SetErrorStringWithFormat(
1350 "error: %s does not support halting processes",
1351 GetPluginName().GetCString());
1355 //------------------------------------------------------------------
1356 /// Called after halting a process.
1358 /// Allow Process plug-ins to execute some code after halting a process.
1359 //------------------------------------------------------------------
1360 virtual void DidHalt() {}
1362 //------------------------------------------------------------------
1363 /// Called before detaching from a process.
1365 /// Allow Process plug-ins to execute some code before detaching from a
1369 /// Returns an error object.
1370 //------------------------------------------------------------------
1371 virtual Status WillDetach() { return Status(); }
1373 //------------------------------------------------------------------
1374 /// Detaches from a running or stopped process.
1377 /// Returns \b true if the process successfully detaches, \b
1378 /// false otherwise.
1379 //------------------------------------------------------------------
1380 virtual Status DoDetach(bool keep_stopped) {
1382 error.SetErrorStringWithFormat(
1383 "error: %s does not support detaching from processes",
1384 GetPluginName().GetCString());
1388 //------------------------------------------------------------------
1389 /// Called after detaching from a process.
1391 /// Allow Process plug-ins to execute some code after detaching from a
1393 //------------------------------------------------------------------
1394 virtual void DidDetach() {}
1396 virtual bool DetachRequiresHalt() { return false; }
1398 //------------------------------------------------------------------
1399 /// Called before sending a signal to a process.
1401 /// Allow Process plug-ins to execute some code before sending a signal to a
1405 /// Returns no error if it is safe to proceed with a call to
1406 /// Process::DoSignal(int), otherwise an error describing what
1407 /// prevents the signal from being sent.
1408 //------------------------------------------------------------------
1409 virtual Status WillSignal() { return Status(); }
1411 //------------------------------------------------------------------
1412 /// Sends a process a UNIX signal \a signal.
1415 /// Returns an error object.
1416 //------------------------------------------------------------------
1417 virtual Status DoSignal(int signal) {
1419 error.SetErrorStringWithFormat(
1420 "error: %s does not support sending signals to processes",
1421 GetPluginName().GetCString());
1425 virtual Status WillDestroy() { return Status(); }
1427 virtual Status DoDestroy() = 0;
1429 virtual void DidDestroy() {}
1431 virtual bool DestroyRequiresHalt() { return true; }
1433 //------------------------------------------------------------------
1434 /// Called after sending a signal to a process.
1436 /// Allow Process plug-ins to execute some code after sending a signal to a
1438 //------------------------------------------------------------------
1439 virtual void DidSignal() {}
1441 //------------------------------------------------------------------
1442 /// Currently called as part of ShouldStop.
1443 /// FIXME: Should really happen when the target stops before the
1444 /// event is taken from the queue...
1446 /// This callback is called as the event
1447 /// is about to be queued up to allow Process plug-ins to execute some code
1448 /// prior to clients being notified that a process was stopped. Common
1449 /// operations include updating the thread list, invalidating any thread
1450 /// state (registers, stack, etc) prior to letting the notification go out.
1452 //------------------------------------------------------------------
1453 virtual void RefreshStateAfterStop() = 0;
1455 //------------------------------------------------------------------
1456 /// Sometimes the connection to a process can detect the host OS version
1457 /// that the process is running on. The current platform should be checked
1458 /// first in case the platform is connected, but clients can fall back onto
1459 /// this function if the platform fails to identify the host OS version. The
1460 /// platform should be checked first in case you are running a simulator
1461 /// platform that might itself be running natively, but have different
1462 /// heuristics for figuring out which OS is is emulating.
1465 /// Returns the version tuple of the host OS. In case of failure an empty
1466 /// VersionTuple is returner.
1467 //------------------------------------------------------------------
1468 virtual llvm::VersionTuple GetHostOSVersion() { return llvm::VersionTuple(); }
1470 //------------------------------------------------------------------
1471 /// Get the target object pointer for this module.
1474 /// A Target object pointer to the target that owns this
1476 //------------------------------------------------------------------
1477 Target &GetTarget() { return *m_target_wp.lock(); }
1479 //------------------------------------------------------------------
1480 /// Get the const target object pointer for this module.
1483 /// A const Target object pointer to the target that owns this
1485 //------------------------------------------------------------------
1486 const Target &GetTarget() const { return *m_target_wp.lock(); }
1488 //------------------------------------------------------------------
1489 /// Flush all data in the process.
1491 /// Flush the memory caches, all threads, and any other cached data in the
1494 /// This function can be called after a world changing event like adding a
1495 /// new symbol file, or after the process makes a large context switch (from
1496 /// boot ROM to booted into an OS).
1497 //------------------------------------------------------------------
1500 //------------------------------------------------------------------
1501 /// Get accessor for the current process state.
1504 /// The current state of the process.
1506 /// @see lldb::StateType
1507 //------------------------------------------------------------------
1508 lldb::StateType GetState();
1510 lldb::ExpressionResults
1511 RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp,
1512 const EvaluateExpressionOptions &options,
1513 DiagnosticManager &diagnostic_manager);
1515 static const char *ExecutionResultAsCString(lldb::ExpressionResults result);
1517 void GetStatus(Stream &ostrm);
1519 size_t GetThreadStatus(Stream &ostrm, bool only_threads_with_stop_reason,
1520 uint32_t start_frame, uint32_t num_frames,
1521 uint32_t num_frames_with_source,
1524 void SendAsyncInterrupt();
1526 //------------------------------------------------------------------
1527 // Notify this process class that modules got loaded.
1529 // If subclasses override this method, they must call this version before
1530 // doing anything in the subclass version of the function.
1531 //------------------------------------------------------------------
1532 virtual void ModulesDidLoad(ModuleList &module_list);
1534 //------------------------------------------------------------------
1535 /// Retrieve the list of shared libraries that are loaded for this process
1536 /// This method is used on pre-macOS 10.12, pre-iOS 10, pre-tvOS 10, pre-
1537 /// watchOS 3 systems. The following two methods are for newer versions of
1540 /// For certain platforms, the time it takes for the DynamicLoader plugin to
1541 /// read all of the shared libraries out of memory over a slow communication
1542 /// channel may be too long. In that instance, the gdb-remote stub may be
1543 /// able to retrieve the necessary information about the solibs out of
1544 /// memory and return a concise summary sufficient for the DynamicLoader
1547 /// @param [in] image_list_address
1548 /// The address where the table of shared libraries is stored in memory,
1549 /// if that is appropriate for this platform. Else this may be
1550 /// passed as LLDB_INVALID_ADDRESS.
1552 /// @param [in] image_count
1553 /// The number of shared libraries that are present in this process, if
1554 /// that is appropriate for this platofrm Else this may be passed as
1555 /// LLDB_INVALID_ADDRESS.
1558 /// A StructureDataSP object which, if non-empty, will contain the
1559 /// information the DynamicLoader needs to get the initial scan of
1560 /// solibs resolved.
1561 //------------------------------------------------------------------
1562 virtual lldb_private::StructuredData::ObjectSP
1563 GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address,
1564 lldb::addr_t image_count) {
1565 return StructuredData::ObjectSP();
1568 // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1569 // return the full list of loaded shared libraries without needing any input.
1570 virtual lldb_private::StructuredData::ObjectSP
1571 GetLoadedDynamicLibrariesInfos() {
1572 return StructuredData::ObjectSP();
1575 // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1576 // return information about binaries given their load addresses.
1577 virtual lldb_private::StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos(
1578 const std::vector<lldb::addr_t> &load_addresses) {
1579 return StructuredData::ObjectSP();
1582 //------------------------------------------------------------------
1583 // Get information about the library shared cache, if that exists
1585 // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1586 // return information about the library shared cache (a set of standard
1587 // libraries that are loaded at the same location for all processes on a
1589 //------------------------------------------------------------------
1590 virtual lldb_private::StructuredData::ObjectSP GetSharedCacheInfo() {
1591 return StructuredData::ObjectSP();
1594 //------------------------------------------------------------------
1595 /// Print a user-visible warning about a module being built with
1598 /// Prints a async warning message to the user one time per Module where a
1599 /// function is found that was compiled with optimization, per Process.
1602 /// A SymbolContext with eSymbolContextFunction and eSymbolContextModule
1604 //------------------------------------------------------------------
1605 void PrintWarningOptimization(const SymbolContext &sc);
1607 virtual bool GetProcessInfo(ProcessInstanceInfo &info);
1610 //------------------------------------------------------------------
1611 /// Get the exit status for a process.
1614 /// The process's return code, or -1 if the current process
1615 /// state is not eStateExited.
1616 //------------------------------------------------------------------
1617 int GetExitStatus();
1619 //------------------------------------------------------------------
1620 /// Get a textual description of what the process exited.
1623 /// The textual description of why the process exited, or nullptr
1624 /// if there is no description available.
1625 //------------------------------------------------------------------
1626 const char *GetExitDescription();
1628 virtual void DidExit() {}
1630 //------------------------------------------------------------------
1631 /// Get the Modification ID of the process.
1634 /// The modification ID of the process.
1635 //------------------------------------------------------------------
1636 ProcessModID GetModID() const { return m_mod_id; }
1638 const ProcessModID &GetModIDRef() const { return m_mod_id; }
1640 uint32_t GetStopID() const { return m_mod_id.GetStopID(); }
1642 uint32_t GetResumeID() const { return m_mod_id.GetResumeID(); }
1644 uint32_t GetLastUserExpressionResumeID() const {
1645 return m_mod_id.GetLastUserExpressionResumeID();
1648 uint32_t GetLastNaturalStopID() const {
1649 return m_mod_id.GetLastNaturalStopID();
1652 lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const {
1653 return m_mod_id.GetStopEventForStopID(stop_id);
1656 //------------------------------------------------------------------
1657 /// Set accessor for the process exit status (return code).
1659 /// Sometimes a child exits and the exit can be detected by global functions
1660 /// (signal handler for SIGCHLD for example). This accessor allows the exit
1661 /// status to be set from an external source.
1663 /// Setting this will cause a eStateExited event to be posted to the process
1666 /// @param[in] exit_status
1667 /// The value for the process's return code.
1669 /// @see lldb::StateType
1670 //------------------------------------------------------------------
1671 virtual bool SetExitStatus(int exit_status, const char *cstr);
1673 //------------------------------------------------------------------
1674 /// Check if a process is still alive.
1677 /// Returns \b true if the process is still valid, \b false
1679 //------------------------------------------------------------------
1680 virtual bool IsAlive();
1682 //------------------------------------------------------------------
1683 /// Before lldb detaches from a process, it warns the user that they are
1684 /// about to lose their debug session. In some cases, this warning doesn't
1685 /// need to be emitted -- for instance, with core file debugging where the
1686 /// user can reconstruct the "state" by simply re-running the debugger on
1690 // true if the user should be warned about detaching from this process.
1691 //------------------------------------------------------------------
1692 virtual bool WarnBeforeDetach() const { return true; }
1694 //------------------------------------------------------------------
1695 /// Actually do the reading of memory from a process.
1697 /// Subclasses must override this function and can return fewer bytes than
1698 /// requested when memory requests are too large. This class will break up
1699 /// the memory requests and keep advancing the arguments along as needed.
1701 /// @param[in] vm_addr
1702 /// A virtual load address that indicates where to start reading
1706 /// The number of bytes to read.
1709 /// A byte buffer that is at least \a size bytes long that
1710 /// will receive the memory bytes.
1712 /// @param[out] error
1713 /// An error that indicates the success or failure of this
1714 /// operation. If error indicates success (error.Success()),
1715 /// then the value returned can be trusted, otherwise zero
1716 /// will be returned.
1719 /// The number of bytes that were actually read into \a buf.
1720 /// Zero is returned in the case of an error.
1721 //------------------------------------------------------------------
1722 virtual size_t DoReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1725 //------------------------------------------------------------------
1726 /// Read of memory from a process.
1728 /// This function will read memory from the current process's address space
1729 /// and remove any traps that may have been inserted into the memory.
1731 /// This function is not meant to be overridden by Process subclasses, the
1732 /// subclasses should implement Process::DoReadMemory (lldb::addr_t, size_t,
1735 /// @param[in] vm_addr
1736 /// A virtual load address that indicates where to start reading
1740 /// A byte buffer that is at least \a size bytes long that
1741 /// will receive the memory bytes.
1744 /// The number of bytes to read.
1746 /// @param[out] error
1747 /// An error that indicates the success or failure of this
1748 /// operation. If error indicates success (error.Success()),
1749 /// then the value returned can be trusted, otherwise zero
1750 /// will be returned.
1753 /// The number of bytes that were actually read into \a buf. If
1754 /// the returned number is greater than zero, yet less than \a
1755 /// size, then this function will get called again with \a
1756 /// vm_addr, \a buf, and \a size updated appropriately. Zero is
1757 /// returned in the case of an error.
1758 //------------------------------------------------------------------
1759 virtual size_t ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1762 //------------------------------------------------------------------
1763 /// Read a NULL terminated string from memory
1765 /// This function will read a cache page at a time until a NULL string
1766 /// terminator is found. It will stop reading if an aligned sequence of NULL
1767 /// termination \a type_width bytes is not found before reading \a
1768 /// cstr_max_len bytes. The results are always guaranteed to be NULL
1769 /// terminated, and that no more than (max_bytes - type_width) bytes will be
1772 /// @param[in] vm_addr
1773 /// The virtual load address to start the memory read.
1776 /// A character buffer containing at least max_bytes.
1778 /// @param[in] max_bytes
1779 /// The maximum number of bytes to read.
1781 /// @param[in] error
1782 /// The error status of the read operation.
1784 /// @param[in] type_width
1785 /// The size of the null terminator (1 to 4 bytes per
1786 /// character). Defaults to 1.
1789 /// The error status or the number of bytes prior to the null terminator.
1790 //------------------------------------------------------------------
1791 size_t ReadStringFromMemory(lldb::addr_t vm_addr, char *str, size_t max_bytes,
1792 Status &error, size_t type_width = 1);
1794 //------------------------------------------------------------------
1795 /// Read a NULL terminated C string from memory
1797 /// This function will read a cache page at a time until the NULL
1798 /// C string terminator is found. It will stop reading if the NULL
1799 /// termination byte isn't found before reading \a cstr_max_len bytes, and
1800 /// the results are always guaranteed to be NULL terminated (at most
1801 /// cstr_max_len - 1 bytes will be read).
1802 //------------------------------------------------------------------
1803 size_t ReadCStringFromMemory(lldb::addr_t vm_addr, char *cstr,
1804 size_t cstr_max_len, Status &error);
1806 size_t ReadCStringFromMemory(lldb::addr_t vm_addr, std::string &out_str,
1809 size_t ReadMemoryFromInferior(lldb::addr_t vm_addr, void *buf, size_t size,
1812 //------------------------------------------------------------------
1813 /// Reads an unsigned integer of the specified byte size from process
1816 /// @param[in] load_addr
1817 /// A load address of the integer to read.
1819 /// @param[in] byte_size
1820 /// The size in byte of the integer to read.
1822 /// @param[in] fail_value
1823 /// The value to return if we fail to read an integer.
1825 /// @param[out] error
1826 /// An error that indicates the success or failure of this
1827 /// operation. If error indicates success (error.Success()),
1828 /// then the value returned can be trusted, otherwise zero
1829 /// will be returned.
1832 /// The unsigned integer that was read from the process memory
1833 /// space. If the integer was smaller than a uint64_t, any
1834 /// unused upper bytes will be zero filled. If the process
1835 /// byte order differs from the host byte order, the integer
1836 /// value will be appropriately byte swapped into host byte
1838 //------------------------------------------------------------------
1839 uint64_t ReadUnsignedIntegerFromMemory(lldb::addr_t load_addr,
1840 size_t byte_size, uint64_t fail_value,
1843 int64_t ReadSignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size,
1844 int64_t fail_value, Status &error);
1846 lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error);
1848 bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
1851 //------------------------------------------------------------------
1852 /// Actually do the writing of memory to a process.
1854 /// @param[in] vm_addr
1855 /// A virtual load address that indicates where to start writing
1859 /// A byte buffer that is at least \a size bytes long that
1860 /// contains the data to write.
1863 /// The number of bytes to write.
1865 /// @param[out] error
1866 /// An error value in case the memory write fails.
1869 /// The number of bytes that were actually written.
1870 //------------------------------------------------------------------
1871 virtual size_t DoWriteMemory(lldb::addr_t vm_addr, const void *buf,
1872 size_t size, Status &error) {
1873 error.SetErrorStringWithFormat(
1874 "error: %s does not support writing to processes",
1875 GetPluginName().GetCString());
1879 //------------------------------------------------------------------
1880 /// Write all or part of a scalar value to memory.
1882 /// The value contained in \a scalar will be swapped to match the byte order
1883 /// of the process that is being debugged. If \a size is less than the size
1884 /// of scalar, the least significant \a size bytes from scalar will be
1885 /// written. If \a size is larger than the byte size of scalar, then the
1886 /// extra space will be padded with zeros and the scalar value will be
1887 /// placed in the least significant bytes in memory.
1889 /// @param[in] vm_addr
1890 /// A virtual load address that indicates where to start writing
1893 /// @param[in] scalar
1894 /// The scalar to write to the debugged process.
1897 /// This value can be smaller or larger than the scalar value
1898 /// itself. If \a size is smaller than the size of \a scalar,
1899 /// the least significant bytes in \a scalar will be used. If
1900 /// \a size is larger than the byte size of \a scalar, then
1901 /// the extra space will be padded with zeros. If \a size is
1902 /// set to UINT32_MAX, then the size of \a scalar will be used.
1904 /// @param[out] error
1905 /// An error value in case the memory write fails.
1908 /// The number of bytes that were actually written.
1909 //------------------------------------------------------------------
1910 size_t WriteScalarToMemory(lldb::addr_t vm_addr, const Scalar &scalar,
1911 size_t size, Status &error);
1913 size_t ReadScalarIntegerFromMemory(lldb::addr_t addr, uint32_t byte_size,
1914 bool is_signed, Scalar &scalar,
1917 //------------------------------------------------------------------
1918 /// Write memory to a process.
1920 /// This function will write memory to the current process's address space
1921 /// and maintain any traps that might be present due to software
1924 /// This function is not meant to be overridden by Process subclasses, the
1925 /// subclasses should implement Process::DoWriteMemory (lldb::addr_t,
1926 /// size_t, void *).
1928 /// @param[in] vm_addr
1929 /// A virtual load address that indicates where to start writing
1933 /// A byte buffer that is at least \a size bytes long that
1934 /// contains the data to write.
1937 /// The number of bytes to write.
1940 /// The number of bytes that were actually written.
1941 //------------------------------------------------------------------
1942 // TODO: change this to take an ArrayRef<uint8_t>
1943 size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1946 //------------------------------------------------------------------
1947 /// Actually allocate memory in the process.
1949 /// This function will allocate memory in the process's address space. This
1950 /// can't rely on the generic function calling mechanism, since that
1951 /// requires this function.
1954 /// The size of the allocation requested.
1957 /// The address of the allocated buffer in the process, or
1958 /// LLDB_INVALID_ADDRESS if the allocation failed.
1959 //------------------------------------------------------------------
1961 virtual lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions,
1963 error.SetErrorStringWithFormat(
1964 "error: %s does not support allocating in the debug process",
1965 GetPluginName().GetCString());
1966 return LLDB_INVALID_ADDRESS;
1969 virtual Status WriteObjectFile(std::vector<ObjectFile::LoadableData> entries);
1971 //------------------------------------------------------------------
1972 /// The public interface to allocating memory in the process.
1974 /// This function will allocate memory in the process's address space. This
1975 /// can't rely on the generic function calling mechanism, since that
1976 /// requires this function.
1979 /// The size of the allocation requested.
1981 /// @param[in] permissions
1982 /// Or together any of the lldb::Permissions bits. The permissions on
1983 /// a given memory allocation can't be changed after allocation. Note
1984 /// that a block that isn't set writable can still be written on from
1986 /// just not by the process itself.
1988 /// @param[in,out] error
1989 /// An error object to fill in if things go wrong.
1991 /// The address of the allocated buffer in the process, or
1992 /// LLDB_INVALID_ADDRESS if the allocation failed.
1993 //------------------------------------------------------------------
1994 lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error);
1996 //------------------------------------------------------------------
1997 /// The public interface to allocating memory in the process, this also
1998 /// clears the allocated memory.
2000 /// This function will allocate memory in the process's address space. This
2001 /// can't rely on the generic function calling mechanism, since that
2002 /// requires this function.
2005 /// The size of the allocation requested.
2007 /// @param[in] permissions
2008 /// Or together any of the lldb::Permissions bits. The permissions on
2009 /// a given memory allocation can't be changed after allocation. Note
2010 /// that a block that isn't set writable can still be written on from
2012 /// just not by the process itself.
2014 /// @param[in/out] error
2015 /// An error object to fill in if things go wrong.
2017 /// The address of the allocated buffer in the process, or
2018 /// LLDB_INVALID_ADDRESS if the allocation failed.
2019 //------------------------------------------------------------------
2021 lldb::addr_t CallocateMemory(size_t size, uint32_t permissions,
2024 //------------------------------------------------------------------
2025 /// Resolve dynamically loaded indirect functions.
2027 /// @param[in] address
2028 /// The load address of the indirect function to resolve.
2030 /// @param[out] error
2031 /// An error value in case the resolve fails.
2034 /// The address of the resolved function.
2035 /// LLDB_INVALID_ADDRESS if the resolution failed.
2036 //------------------------------------------------------------------
2037 virtual lldb::addr_t ResolveIndirectFunction(const Address *address,
2040 //------------------------------------------------------------------
2041 /// Locate the memory region that contains load_addr.
2043 /// If load_addr is within the address space the process has mapped
2044 /// range_info will be filled in with the start and end of that range as
2045 /// well as the permissions for that range and range_info.GetMapped will
2048 /// If load_addr is outside any mapped region then range_info will have its
2049 /// start address set to load_addr and the end of the range will indicate
2050 /// the start of the next mapped range or be set to LLDB_INVALID_ADDRESS if
2051 /// there are no valid mapped ranges between load_addr and the end of the
2052 /// process address space.
2054 /// GetMemoryRegionInfo will only return an error if it is unimplemented for
2055 /// the current process.
2057 /// @param[in] load_addr
2058 /// The load address to query the range_info for.
2060 /// @param[out] range_info
2061 /// An range_info value containing the details of the range.
2065 //------------------------------------------------------------------
2066 virtual Status GetMemoryRegionInfo(lldb::addr_t load_addr,
2067 MemoryRegionInfo &range_info) {
2069 error.SetErrorString("Process::GetMemoryRegionInfo() not supported");
2073 //------------------------------------------------------------------
2074 /// Obtain all the mapped memory regions within this process.
2076 /// @param[out] region_list
2077 /// A vector to contain MemoryRegionInfo objects for all mapped
2082 //------------------------------------------------------------------
2084 GetMemoryRegions(lldb_private::MemoryRegionInfos ®ion_list);
2086 virtual Status GetWatchpointSupportInfo(uint32_t &num) {
2089 error.SetErrorString("Process::GetWatchpointSupportInfo() not supported");
2093 virtual Status GetWatchpointSupportInfo(uint32_t &num, bool &after) {
2097 error.SetErrorString("Process::GetWatchpointSupportInfo() not supported");
2101 lldb::ModuleSP ReadModuleFromMemory(const FileSpec &file_spec,
2102 lldb::addr_t header_addr,
2103 size_t size_to_read = 512);
2105 //------------------------------------------------------------------
2106 /// Attempt to get the attributes for a region of memory in the process.
2108 /// It may be possible for the remote debug server to inspect attributes for
2109 /// a region of memory in the process, such as whether there is a valid page
2110 /// of memory at a given address or whether that page is
2111 /// readable/writable/executable by the process.
2113 /// @param[in] load_addr
2114 /// The address of interest in the process.
2116 /// @param[out] permissions
2117 /// If this call returns successfully, this bitmask will have
2118 /// its Permissions bits set to indicate whether the region is
2119 /// readable/writable/executable. If this call fails, the
2120 /// bitmask values are undefined.
2123 /// Returns true if it was able to determine the attributes of the
2124 /// memory region. False if not.
2125 //------------------------------------------------------------------
2126 virtual bool GetLoadAddressPermissions(lldb::addr_t load_addr,
2127 uint32_t &permissions);
2129 //------------------------------------------------------------------
2130 /// Determines whether executing JIT-compiled code in this process is
2134 /// True if execution of JIT code is possible; false otherwise.
2135 //------------------------------------------------------------------
2138 //------------------------------------------------------------------
2139 /// Sets whether executing JIT-compiled code in this process is possible.
2141 /// @param[in] can_jit
2142 /// True if execution of JIT code is possible; false otherwise.
2143 //------------------------------------------------------------------
2144 void SetCanJIT(bool can_jit);
2146 //------------------------------------------------------------------
2147 /// Determines whether executing function calls using the interpreter is
2148 /// possible for this process.
2151 /// True if possible; false otherwise.
2152 //------------------------------------------------------------------
2153 bool CanInterpretFunctionCalls() { return m_can_interpret_function_calls; }
2155 //------------------------------------------------------------------
2156 /// Sets whether executing function calls using the interpreter is possible
2157 /// for this process.
2159 /// @param[in] can_interpret_function_calls
2160 /// True if possible; false otherwise.
2161 //------------------------------------------------------------------
2162 void SetCanInterpretFunctionCalls(bool can_interpret_function_calls) {
2163 m_can_interpret_function_calls = can_interpret_function_calls;
2166 //------------------------------------------------------------------
2167 /// Sets whether executing code in this process is possible. This could be
2168 /// either through JIT or interpreting.
2170 /// @param[in] can_run_code
2171 /// True if execution of code is possible; false otherwise.
2172 //------------------------------------------------------------------
2173 void SetCanRunCode(bool can_run_code);
2175 //------------------------------------------------------------------
2176 /// Actually deallocate memory in the process.
2178 /// This function will deallocate memory in the process's address space that
2179 /// was allocated with AllocateMemory.
2182 /// A return value from AllocateMemory, pointing to the memory you
2183 /// want to deallocate.
2186 /// \btrue if the memory was deallocated, \bfalse otherwise.
2187 //------------------------------------------------------------------
2188 virtual Status DoDeallocateMemory(lldb::addr_t ptr) {
2190 error.SetErrorStringWithFormat(
2191 "error: %s does not support deallocating in the debug process",
2192 GetPluginName().GetCString());
2196 //------------------------------------------------------------------
2197 /// The public interface to deallocating memory in the process.
2199 /// This function will deallocate memory in the process's address space that
2200 /// was allocated with AllocateMemory.
2203 /// A return value from AllocateMemory, pointing to the memory you
2204 /// want to deallocate.
2207 /// \btrue if the memory was deallocated, \bfalse otherwise.
2208 //------------------------------------------------------------------
2209 Status DeallocateMemory(lldb::addr_t ptr);
2211 //------------------------------------------------------------------
2212 /// Get any available STDOUT.
2214 /// Calling this method is a valid operation only if all of the following
2215 /// conditions are true: 1) The process was launched, and not attached to.
2216 /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 3) The
2217 /// process was launched without supplying a valid file path
2220 /// Note that the implementation will probably need to start a read thread
2221 /// in the background to make sure that the pipe is drained and the STDOUT
2222 /// buffered appropriately, to prevent the process from deadlocking trying
2223 /// to write to a full buffer.
2225 /// Events will be queued indicating that there is STDOUT available that can
2226 /// be retrieved using this function.
2229 /// A buffer that will receive any STDOUT bytes that are
2230 /// currently available.
2232 /// @param[in] buf_size
2233 /// The size in bytes for the buffer \a buf.
2236 /// The number of bytes written into \a buf. If this value is
2237 /// equal to \a buf_size, another call to this function should
2238 /// be made to retrieve more STDOUT data.
2239 //------------------------------------------------------------------
2240 virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error);
2242 //------------------------------------------------------------------
2243 /// Get any available STDERR.
2245 /// Calling this method is a valid operation only if all of the following
2246 /// conditions are true: 1) The process was launched, and not attached to.
2247 /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 3) The
2248 /// process was launched without supplying a valid file path
2251 /// Note that the implementation will probably need to start a read thread
2252 /// in the background to make sure that the pipe is drained and the STDERR
2253 /// buffered appropriately, to prevent the process from deadlocking trying
2254 /// to write to a full buffer.
2256 /// Events will be queued indicating that there is STDERR available that can
2257 /// be retrieved using this function.
2260 /// A buffer that will receive any STDERR bytes that are
2261 /// currently available.
2263 /// @param[out] buf_size
2264 /// The size in bytes for the buffer \a buf.
2267 /// The number of bytes written into \a buf. If this value is
2268 /// equal to \a buf_size, another call to this function should
2269 /// be made to retrieve more STDERR data.
2270 //------------------------------------------------------------------
2271 virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error);
2273 //------------------------------------------------------------------
2274 /// Puts data into this process's STDIN.
2276 /// Calling this method is a valid operation only if all of the following
2277 /// conditions are true: 1) The process was launched, and not attached to.
2278 /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 3) The
2279 /// process was launched without supplying a valid file path
2283 /// A buffer that contains the data to write to the process's STDIN.
2285 /// @param[in] buf_size
2286 /// The size in bytes for the buffer \a buf.
2289 /// The number of bytes written into \a buf. If this value is
2290 /// less than \a buf_size, another call to this function should
2291 /// be made to write the rest of the data.
2292 //------------------------------------------------------------------
2293 virtual size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) {
2294 error.SetErrorString("stdin unsupported");
2298 //------------------------------------------------------------------
2299 /// Get any available profile data.
2302 /// A buffer that will receive any profile data bytes that are
2303 /// currently available.
2305 /// @param[out] buf_size
2306 /// The size in bytes for the buffer \a buf.
2309 /// The number of bytes written into \a buf. If this value is
2310 /// equal to \a buf_size, another call to this function should
2311 /// be made to retrieve more profile data.
2312 //------------------------------------------------------------------
2313 virtual size_t GetAsyncProfileData(char *buf, size_t buf_size, Status &error);
2315 //----------------------------------------------------------------------
2316 // Process Breakpoints
2317 //----------------------------------------------------------------------
2318 size_t GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site);
2320 virtual Status EnableBreakpointSite(BreakpointSite *bp_site) {
2322 error.SetErrorStringWithFormat(
2323 "error: %s does not support enabling breakpoints",
2324 GetPluginName().GetCString());
2328 virtual Status DisableBreakpointSite(BreakpointSite *bp_site) {
2330 error.SetErrorStringWithFormat(
2331 "error: %s does not support disabling breakpoints",
2332 GetPluginName().GetCString());
2336 // This is implemented completely using the lldb::Process API. Subclasses
2337 // don't need to implement this function unless the standard flow of read
2338 // existing opcode, write breakpoint opcode, verify breakpoint opcode doesn't
2339 // work for a specific process plug-in.
2340 virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site);
2342 // This is implemented completely using the lldb::Process API. Subclasses
2343 // don't need to implement this function unless the standard flow of
2344 // restoring original opcode in memory and verifying the restored opcode
2345 // doesn't work for a specific process plug-in.
2346 virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site);
2348 BreakpointSiteList &GetBreakpointSiteList();
2350 const BreakpointSiteList &GetBreakpointSiteList() const;
2352 void DisableAllBreakpointSites();
2354 Status ClearBreakpointSiteByID(lldb::user_id_t break_id);
2356 lldb::break_id_t CreateBreakpointSite(const lldb::BreakpointLocationSP &owner,
2359 Status DisableBreakpointSiteByID(lldb::user_id_t break_id);
2361 Status EnableBreakpointSiteByID(lldb::user_id_t break_id);
2363 // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove themselves
2364 // from the owner's list of this breakpoint sites.
2365 void RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
2366 lldb::user_id_t owner_loc_id,
2367 lldb::BreakpointSiteSP &bp_site_sp);
2369 //----------------------------------------------------------------------
2370 // Process Watchpoints (optional)
2371 //----------------------------------------------------------------------
2372 virtual Status EnableWatchpoint(Watchpoint *wp, bool notify = true);
2374 virtual Status DisableWatchpoint(Watchpoint *wp, bool notify = true);
2376 //------------------------------------------------------------------
2378 //------------------------------------------------------------------
2379 virtual bool UpdateThreadList(ThreadList &old_thread_list,
2380 ThreadList &new_thread_list) = 0;
2382 void UpdateThreadListIfNeeded();
2384 ThreadList &GetThreadList() { return m_thread_list; }
2386 // When ExtendedBacktraces are requested, the HistoryThreads that are created
2387 // need an owner -- they're saved here in the Process. The threads in this
2388 // list are not iterated over - driver programs need to request the extended
2389 // backtrace calls starting from a root concrete thread one by one.
2390 ThreadList &GetExtendedThreadList() { return m_extended_thread_list; }
2392 ThreadList::ThreadIterable Threads() { return m_thread_list.Threads(); }
2394 uint32_t GetNextThreadIndexID(uint64_t thread_id);
2396 lldb::ThreadSP CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context);
2398 // Returns true if an index id has been assigned to a thread.
2399 bool HasAssignedIndexIDToThread(uint64_t sb_thread_id);
2401 // Given a thread_id, it will assign a more reasonable index id for display
2402 // to the user. If the thread_id has previously been assigned, the same index
2404 uint32_t AssignIndexIDToThread(uint64_t thread_id);
2406 //------------------------------------------------------------------
2408 //------------------------------------------------------------------
2410 void UpdateQueueListIfNeeded();
2412 QueueList &GetQueueList() {
2413 UpdateQueueListIfNeeded();
2414 return m_queue_list;
2417 QueueList::QueueIterable Queues() {
2418 UpdateQueueListIfNeeded();
2419 return m_queue_list.Queues();
2422 //------------------------------------------------------------------
2424 //------------------------------------------------------------------
2425 lldb::StateType GetNextEvent(lldb::EventSP &event_sp);
2427 // Returns the process state when it is stopped. If specified, event_sp_ptr
2428 // is set to the event which triggered the stop. If wait_always = false, and
2429 // the process is already stopped, this function returns immediately. If the
2430 // process is hijacked and use_run_lock is true (the default), then this
2431 // function releases the run lock after the stop. Setting use_run_lock to
2432 // false will avoid this behavior.
2434 WaitForProcessToStop(const Timeout<std::micro> &timeout,
2435 lldb::EventSP *event_sp_ptr = nullptr,
2436 bool wait_always = true,
2437 lldb::ListenerSP hijack_listener = lldb::ListenerSP(),
2438 Stream *stream = nullptr, bool use_run_lock = true);
2440 uint32_t GetIOHandlerID() const { return m_iohandler_sync.GetValue(); }
2442 //--------------------------------------------------------------------------------------
2443 /// Waits for the process state to be running within a given msec timeout.
2445 /// The main purpose of this is to implement an interlock waiting for
2446 /// HandlePrivateEvent to push an IOHandler.
2448 /// @param[in] timeout
2449 /// The maximum time length to wait for the process to transition to the
2450 /// eStateRunning state.
2451 //--------------------------------------------------------------------------------------
2452 void SyncIOHandler(uint32_t iohandler_id, const Timeout<std::micro> &timeout);
2454 lldb::StateType GetStateChangedEvents(
2455 lldb::EventSP &event_sp, const Timeout<std::micro> &timeout,
2457 hijack_listener); // Pass an empty ListenerSP to use builtin listener
2459 //--------------------------------------------------------------------------------------
2460 /// Centralize the code that handles and prints descriptions for process
2463 /// @param[in] event_sp
2464 /// The process state changed event
2466 /// @param[in] stream
2467 /// The output stream to get the state change description
2469 /// @param[in,out] pop_process_io_handler
2470 /// If this value comes in set to \b true, then pop the Process IOHandler
2472 /// Else this variable will be set to \b true or \b false to indicate if
2474 /// needs to have its process IOHandler popped.
2477 /// \b true if the event describes a process state changed event, \b false
2479 //--------------------------------------------------------------------------------------
2480 static bool HandleProcessStateChangedEvent(const lldb::EventSP &event_sp,
2482 bool &pop_process_io_handler);
2484 Event *PeekAtStateChangedEvents();
2486 class ProcessEventHijacker {
2488 ProcessEventHijacker(Process &process, lldb::ListenerSP listener_sp)
2489 : m_process(process) {
2490 m_process.HijackProcessEvents(listener_sp);
2493 ~ProcessEventHijacker() { m_process.RestoreProcessEvents(); }
2499 friend class ProcessEventHijacker;
2500 friend class ProcessProperties;
2501 //------------------------------------------------------------------
2502 /// If you need to ensure that you and only you will hear about some public
2503 /// event, then make a new listener, set to listen to process events, and
2504 /// then call this with that listener. Then you will have to wait on that
2505 /// listener explicitly for events (rather than using the GetNextEvent &
2506 /// WaitFor* calls above. Be sure to call RestoreProcessEvents when you are
2509 /// @param[in] listener
2510 /// This is the new listener to whom all process events will be delivered.
2513 /// Returns \b true if the new listener could be installed,
2514 /// \b false otherwise.
2515 //------------------------------------------------------------------
2516 bool HijackProcessEvents(lldb::ListenerSP listener_sp);
2518 //------------------------------------------------------------------
2519 /// Restores the process event broadcasting to its normal state.
2521 //------------------------------------------------------------------
2522 void RestoreProcessEvents();
2524 const lldb::ABISP &GetABI();
2526 OperatingSystem *GetOperatingSystem() { return m_os_ap.get(); }
2528 virtual LanguageRuntime *GetLanguageRuntime(lldb::LanguageType language,
2529 bool retry_if_null = true);
2531 virtual CPPLanguageRuntime *GetCPPLanguageRuntime(bool retry_if_null = true);
2533 virtual ObjCLanguageRuntime *
2534 GetObjCLanguageRuntime(bool retry_if_null = true);
2536 bool IsPossibleDynamicValue(ValueObject &in_value);
2538 bool IsRunning() const;
2540 DynamicCheckerFunctions *GetDynamicCheckers() {
2541 return m_dynamic_checkers_ap.get();
2544 void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers);
2546 //------------------------------------------------------------------
2547 /// Call this to set the lldb in the mode where it breaks on new thread
2548 /// creations, and then auto-restarts. This is useful when you are trying
2549 /// to run only one thread, but either that thread or the kernel is creating
2550 /// new threads in the process. If you stop when the thread is created, you
2551 /// can immediately suspend it, and keep executing only the one thread you
2555 /// Returns \b true if we were able to start up the notification
2556 /// \b false otherwise.
2557 //------------------------------------------------------------------
2558 virtual bool StartNoticingNewThreads() { return true; }
2560 //------------------------------------------------------------------
2561 /// Call this to turn off the stop & notice new threads mode.
2564 /// Returns \b true if we were able to start up the notification
2565 /// \b false otherwise.
2566 //------------------------------------------------------------------
2567 virtual bool StopNoticingNewThreads() { return true; }
2569 void SetRunningUserExpression(bool on);
2570 void SetRunningUtilityFunction(bool on);
2572 //------------------------------------------------------------------
2573 // lldb::ExecutionContextScope pure virtual functions
2574 //------------------------------------------------------------------
2575 lldb::TargetSP CalculateTarget() override;
2577 lldb::ProcessSP CalculateProcess() override { return shared_from_this(); }
2579 lldb::ThreadSP CalculateThread() override { return lldb::ThreadSP(); }
2581 lldb::StackFrameSP CalculateStackFrame() override {
2582 return lldb::StackFrameSP();
2585 void CalculateExecutionContext(ExecutionContext &exe_ctx) override;
2587 void SetSTDIOFileDescriptor(int file_descriptor);
2589 //------------------------------------------------------------------
2590 // Add a permanent region of memory that should never be read or written to.
2591 // This can be used to ensure that memory reads or writes to certain areas of
2592 // memory never end up being sent to the DoReadMemory or DoWriteMemory
2593 // functions which can improve performance.
2594 //------------------------------------------------------------------
2595 void AddInvalidMemoryRegion(const LoadRange ®ion);
2597 //------------------------------------------------------------------
2598 // Remove a permanent region of memory that should never be read or written
2599 // to that was previously added with AddInvalidMemoryRegion.
2600 //------------------------------------------------------------------
2601 bool RemoveInvalidMemoryRange(const LoadRange ®ion);
2603 //------------------------------------------------------------------
2604 // If the setup code of a thread plan needs to do work that might involve
2605 // calling a function in the target, it should not do that work directly in
2606 // one of the thread plan functions (DidPush/WillResume) because such work
2607 // needs to be handled carefully. Instead, put that work in a
2608 // PreResumeAction callback, and register it with the process. It will get
2609 // done before the actual "DoResume" gets called.
2610 //------------------------------------------------------------------
2612 typedef bool(PreResumeActionCallback)(void *);
2614 void AddPreResumeAction(PreResumeActionCallback callback, void *baton);
2616 bool RunPreResumeActions();
2618 void ClearPreResumeActions();
2620 void ClearPreResumeAction(PreResumeActionCallback callback, void *baton);
2622 ProcessRunLock &GetRunLock();
2624 virtual Status SendEventData(const char *data) {
2625 Status return_error("Sending an event is not supported for this process.");
2626 return return_error;
2629 lldb::ThreadCollectionSP GetHistoryThreads(lldb::addr_t addr);
2631 lldb::InstrumentationRuntimeSP
2632 GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type);
2634 //------------------------------------------------------------------
2635 /// Try to fetch the module specification for a module with the given file
2636 /// name and architecture. Process sub-classes have to override this method
2637 /// if they support platforms where the Platform object can't get the module
2638 /// spec for all module.
2640 /// @param[in] module_file_spec
2641 /// The file name of the module to get specification for.
2644 /// The architecture of the module to get specification for.
2646 /// @param[out] module_spec
2647 /// The fetched module specification if the return value is
2648 /// \b true, unchanged otherwise.
2651 /// Returns \b true if the module spec fetched successfully,
2652 /// \b false otherwise.
2653 //------------------------------------------------------------------
2654 virtual bool GetModuleSpec(const FileSpec &module_file_spec,
2655 const ArchSpec &arch, ModuleSpec &module_spec);
2657 virtual void PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs,
2658 const llvm::Triple &triple) {}
2660 //------------------------------------------------------------------
2661 /// Try to find the load address of a file.
2662 /// The load address is defined as the address of the first memory region
2663 /// what contains data mapped from the specified file.
2666 /// The name of the file whose load address we are looking for
2668 /// @param[out] is_loaded
2669 /// \b True if the file is loaded into the memory and false
2672 /// @param[out] load_addr
2673 /// The load address of the file if it is loaded into the
2674 /// processes address space, LLDB_INVALID_ADDRESS otherwise.
2675 //------------------------------------------------------------------
2676 virtual Status GetFileLoadAddress(const FileSpec &file, bool &is_loaded,
2677 lldb::addr_t &load_addr) {
2678 return Status("Not supported");
2681 size_t AddImageToken(lldb::addr_t image_ptr);
2683 lldb::addr_t GetImagePtrFromToken(size_t token) const;
2685 void ResetImageToken(size_t token);
2687 //------------------------------------------------------------------
2688 /// Find the next branch instruction to set a breakpoint on
2690 /// When instruction stepping through a source line, instead of stepping
2691 /// through each instruction, we can put a breakpoint on the next branch
2692 /// instruction (within the range of instructions we are stepping through)
2693 /// and continue the process to there, yielding significant performance
2694 /// benefits over instruction stepping.
2696 /// @param[in] default_stop_addr
2697 /// The address of the instruction where lldb would put a
2698 /// breakpoint normally.
2700 /// @param[in] range_bounds
2701 /// The range which the breakpoint must be contained within.
2702 /// Typically a source line.
2705 /// The address of the next branch instruction, or the end of
2706 /// the range provided in range_bounds. If there are any
2707 /// problems with the disassembly or getting the instructions,
2708 /// the original default_stop_addr will be returned.
2709 //------------------------------------------------------------------
2710 Address AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
2711 AddressRange range_bounds);
2713 //------------------------------------------------------------------
2714 /// Configure asynchronous structured data feature.
2716 /// Each Process type that supports using an asynchronous StructuredData
2717 /// feature should implement this to enable/disable/configure the feature.
2718 /// The default implementation here will always return an error indiciating
2719 /// the feature is unsupported.
2721 /// StructuredDataPlugin implementations will call this to configure a
2722 /// feature that has been reported as being supported.
2724 /// @param[in] type_name
2725 /// The StructuredData type name as previously discovered by
2726 /// the Process-derived instance.
2728 /// @param[in] config
2729 /// Configuration data for the feature being enabled. This config
2730 /// data, which may be null, will be passed along to the feature
2731 /// to process. The feature will dictate whether this is a dictionary,
2732 /// an array or some other object. If the feature needs to be
2733 /// set up properly before it can be enabled, then the config should
2734 /// also take an enable/disable flag.
2737 /// Returns the result of attempting to configure the feature.
2738 //------------------------------------------------------------------
2740 ConfigureStructuredData(const ConstString &type_name,
2741 const StructuredData::ObjectSP &config_sp);
2743 //------------------------------------------------------------------
2744 /// Broadcasts the given structured data object from the given plugin.
2746 /// StructuredDataPlugin instances can use this to optionally broadcast any
2747 /// of their data if they want to make it available for clients. The data
2748 /// will come in on the structured data event bit
2749 /// (eBroadcastBitStructuredData).
2751 /// @param[in] object_sp
2752 /// The structured data object to broadcast.
2754 /// @param[in] plugin_sp
2755 /// The plugin that will be reported in the event's plugin
2757 //------------------------------------------------------------------
2758 void BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
2759 const lldb::StructuredDataPluginSP &plugin_sp);
2761 //------------------------------------------------------------------
2762 /// Returns the StructuredDataPlugin associated with a given type name, if
2765 /// There will only be a plugin for a given StructuredDataType if the
2766 /// debugged process monitor claims that the feature is supported. This is
2767 /// one way to tell whether a feature is available.
2770 /// The plugin if one is available for the specified feature;
2771 /// otherwise, returns an empty shared pointer.
2772 //------------------------------------------------------------------
2773 lldb::StructuredDataPluginSP
2774 GetStructuredDataPlugin(const ConstString &type_name) const;
2776 //------------------------------------------------------------------
2777 /// Starts tracing with the configuration provided in options. To enable
2778 /// tracing on the complete process the thread_id in the options should be
2779 /// set to LLDB_INVALID_THREAD_ID. The API returns a user_id which is needed
2780 /// by other API's that manipulate the trace instance. The handling of
2781 /// erroneous or unsupported configuration is left to the trace technology
2782 /// implementations in the server, as they could be returned as an error, or
2783 /// rounded to a valid configuration to start tracing. In the later case the
2784 /// GetTraceConfig should supply the actual used trace configuration.
2785 //------------------------------------------------------------------
2786 virtual lldb::user_id_t StartTrace(const TraceOptions &options,
2788 error.SetErrorString("Not implemented");
2789 return LLDB_INVALID_UID;
2792 //------------------------------------------------------------------
2793 /// Stops the tracing instance leading to deletion of the trace data. The
2794 /// tracing instance is identified by the user_id which is obtained when
2795 /// tracing was started from the StartTrace. In case tracing of the complete
2796 /// process needs to be stopped the thread_id should be set to
2797 /// LLDB_INVALID_THREAD_ID. In the other case that tracing on an individual
2798 /// thread needs to be stopped a thread_id can be supplied.
2799 //------------------------------------------------------------------
2800 virtual Status StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) {
2801 return Status("Not implemented");
2804 //------------------------------------------------------------------
2805 /// Provides the trace data as raw bytes. A buffer needs to be supplied to
2806 /// copy the trace data. The exact behavior of this API may vary across
2807 /// trace technology, as some may support partial reading of the trace data
2808 /// from a specified offset while some may not. The thread_id should be used
2809 /// to select a particular thread for trace extraction.
2810 //------------------------------------------------------------------
2811 virtual Status GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
2812 llvm::MutableArrayRef<uint8_t> &buffer,
2813 size_t offset = 0) {
2814 return Status("Not implemented");
2817 //------------------------------------------------------------------
2818 /// Similar API as above except for obtaining meta data
2819 //------------------------------------------------------------------
2820 virtual Status GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
2821 llvm::MutableArrayRef<uint8_t> &buffer,
2822 size_t offset = 0) {
2823 return Status("Not implemented");
2826 //------------------------------------------------------------------
2827 /// API to obtain the trace configuration used by a trace instance.
2828 /// Configurations that may be specific to some trace technology should be
2829 /// stored in the custom parameters. The options are transported to the
2830 /// server, which shall interpret accordingly. The thread_id can be
2831 /// specified in the options to obtain the configuration used by a specific
2832 /// thread. The thread_id specified should also match the uid otherwise an
2833 /// error will be returned.
2834 //------------------------------------------------------------------
2835 virtual Status GetTraceConfig(lldb::user_id_t uid, TraceOptions &options) {
2836 return Status("Not implemented");
2840 void SetState(lldb::EventSP &event_sp);
2842 lldb::StateType GetPrivateState();
2844 //------------------------------------------------------------------
2845 /// The "private" side of resuming a process. This doesn't alter the state
2846 /// of m_run_lock, but just causes the process to resume.
2849 /// An Status object describing the success or failure of the resume.
2850 //------------------------------------------------------------------
2851 Status PrivateResume();
2853 //------------------------------------------------------------------
2854 // Called internally
2855 //------------------------------------------------------------------
2856 void CompleteAttach();
2858 //------------------------------------------------------------------
2859 /// Print a user-visible warning one time per Process
2861 /// A facility for printing a warning to the user once per repeat_key.
2863 /// warning_type is from the Process::Warnings enums. repeat_key is a
2864 /// pointer value that will be used to ensure that the warning message is
2865 /// not printed multiple times. For instance, with a warning about a
2866 /// function being optimized, you can pass the CompileUnit pointer to have
2867 /// the warning issued for only the first function in a CU, or the Function
2868 /// pointer to have it issued once for every function, or a Module pointer
2869 /// to have it issued once per Module.
2871 /// Classes outside Process should call a specific PrintWarning method so
2872 /// that the warning strings are all centralized in Process, instead of
2873 /// calling PrintWarning() directly.
2875 /// @param [in] warning_type
2876 /// One of the types defined in Process::Warnings.
2878 /// @param [in] repeat_key
2879 /// A pointer value used to ensure that the warning is only printed once.
2880 /// May be nullptr, indicating that the warning is printed unconditionally
2884 /// printf style format string
2885 //------------------------------------------------------------------
2886 void PrintWarning(uint64_t warning_type, const void *repeat_key,
2887 const char *fmt, ...) __attribute__((format(printf, 4, 5)));
2889 //------------------------------------------------------------------
2890 // NextEventAction provides a way to register an action on the next event
2891 // that is delivered to this process. There is currently only one next event
2892 // action allowed in the process at one time. If a new "NextEventAction" is
2893 // added while one is already present, the old action will be discarded (with
2894 // HandleBeingUnshipped called after it is discarded.)
2896 // If you want to resume the process as a result of a resume action, call
2897 // RequestResume, don't call Resume directly.
2898 //------------------------------------------------------------------
2899 class NextEventAction {
2901 typedef enum EventActionResult {
2902 eEventActionSuccess,
2905 } EventActionResult;
2907 NextEventAction(Process *process) : m_process(process) {}
2909 virtual ~NextEventAction() = default;
2911 virtual EventActionResult PerformAction(lldb::EventSP &event_sp) = 0;
2912 virtual void HandleBeingUnshipped() {}
2913 virtual EventActionResult HandleBeingInterrupted() = 0;
2914 virtual const char *GetExitString() = 0;
2915 void RequestResume() { m_process->m_resume_requested = true; }
2921 void SetNextEventAction(Process::NextEventAction *next_event_action) {
2922 if (m_next_event_action_ap.get())
2923 m_next_event_action_ap->HandleBeingUnshipped();
2925 m_next_event_action_ap.reset(next_event_action);
2928 // This is the completer for Attaching:
2929 class AttachCompletionHandler : public NextEventAction {
2931 AttachCompletionHandler(Process *process, uint32_t exec_count);
2933 ~AttachCompletionHandler() override = default;
2935 EventActionResult PerformAction(lldb::EventSP &event_sp) override;
2936 EventActionResult HandleBeingInterrupted() override;
2937 const char *GetExitString() override;
2940 uint32_t m_exec_count;
2941 std::string m_exit_string;
2944 bool PrivateStateThreadIsValid() const {
2945 lldb::StateType state = m_private_state.GetValue();
2946 return state != lldb::eStateInvalid && state != lldb::eStateDetached &&
2947 state != lldb::eStateExited && m_private_state_thread.IsJoinable();
2950 void ForceNextEventDelivery() { m_force_next_event_delivery = true; }
2952 //------------------------------------------------------------------
2953 /// Loads any plugins associated with asynchronous structured data and maps
2954 /// the relevant supported type name to the plugin.
2956 /// Processes can receive asynchronous structured data from the process
2957 /// monitor. This method will load and map any structured data plugins that
2958 /// support the given set of supported type names. Later, if any of these
2959 /// features are enabled, the process monitor is free to generate
2960 /// asynchronous structured data. The data must come in as a single \b
2961 /// StructuredData::Dictionary. That dictionary must have a string field
2962 /// named 'type', with a value that equals the relevant type name string
2963 /// (one of the values in \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 have a
2977 /// key named 'type' that stores a string value. The string value must be
2978 /// the name of the structured data feature that knows how to handle it.
2980 /// @param[in] object_sp
2981 /// When non-null and pointing to a dictionary, the 'type'
2982 /// key's string value is used to look up the plugin that
2983 /// was registered for that structured data type. It then
2984 /// calls the following method on the StructuredDataPlugin
2988 /// HandleArrivalOfStructuredData(Process &process,
2989 /// const ConstString &type_name,
2990 /// const StructuredData::ObjectSP
2994 /// True if the structured data was routed to a plugin; otherwise,
2996 //------------------------------------------------------------------
2997 bool RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp);
2999 //------------------------------------------------------------------
3001 //------------------------------------------------------------------
3002 typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP>
3003 LanguageRuntimeCollection;
3004 typedef std::unordered_set<const void *> WarningsPointerSet;
3005 typedef std::map<uint64_t, WarningsPointerSet> WarningsCollection;
3007 struct PreResumeCallbackAndBaton {
3008 bool (*callback)(void *);
3010 PreResumeCallbackAndBaton(PreResumeActionCallback in_callback,
3012 : callback(in_callback), baton(in_baton) {}
3013 bool operator== (const PreResumeCallbackAndBaton &rhs) {
3014 return callback == rhs.callback && baton == rhs.baton;
3018 using StructuredDataPluginMap =
3019 std::map<ConstString, lldb::StructuredDataPluginSP>;
3021 //------------------------------------------------------------------
3023 //------------------------------------------------------------------
3024 std::weak_ptr<Target> m_target_wp; ///< The target that owns this process.
3025 ThreadSafeValue<lldb::StateType> m_public_state;
3026 ThreadSafeValue<lldb::StateType>
3027 m_private_state; // The actual state of our process
3028 Broadcaster m_private_state_broadcaster; // This broadcaster feeds state
3029 // changed events into the private
3030 // state thread's listener.
3031 Broadcaster m_private_state_control_broadcaster; // This is the control
3032 // broadcaster, used to
3033 // pause, resume & stop the
3034 // private state thread.
3035 lldb::ListenerSP m_private_state_listener_sp; // This is the listener for the
3036 // private state thread.
3037 HostThread m_private_state_thread; ///< Thread ID for the thread that watches
3038 ///internal state events
3039 ProcessModID m_mod_id; ///< Tracks the state of the process over stops and
3040 ///other alterations.
3041 uint32_t m_process_unique_id; ///< Each lldb_private::Process class that is
3042 ///created gets a unique integer ID that
3043 ///increments with each new instance
3044 uint32_t m_thread_index_id; ///< Each thread is created with a 1 based index
3045 ///that won't get re-used.
3046 std::map<uint64_t, uint32_t> m_thread_id_to_index_id_map;
3047 int m_exit_status; ///< The exit status of the process, or -1 if not set.
3048 std::string m_exit_string; ///< A textual description of why a process exited.
3049 std::mutex m_exit_status_mutex; ///< Mutex so m_exit_status m_exit_string can
3050 ///be safely accessed from multiple threads
3051 std::recursive_mutex m_thread_mutex;
3052 ThreadList m_thread_list_real; ///< The threads for this process as are known
3053 ///to the protocol we are debugging with
3054 ThreadList m_thread_list; ///< The threads for this process as the user will
3055 ///see them. This is usually the same as
3056 ///< m_thread_list_real, but might be different if there is an OS plug-in
3057 ///creating memory threads
3058 ThreadList m_extended_thread_list; ///< Owner for extended threads that may be
3059 ///generated, cleared on natural stops
3060 uint32_t m_extended_thread_stop_id; ///< The natural stop id when
3061 ///extended_thread_list was last updated
3063 m_queue_list; ///< The list of libdispatch queues at a given stop point
3064 uint32_t m_queue_list_stop_id; ///< The natural stop id when queue list was
3066 std::vector<Notifications> m_notifications; ///< The list of notifications
3067 ///that this process can deliver.
3068 std::vector<lldb::addr_t> m_image_tokens;
3069 lldb::ListenerSP m_listener_sp; ///< Shared pointer to the listener used for
3070 ///public events. Can not be empty.
3071 BreakpointSiteList m_breakpoint_site_list; ///< This is the list of breakpoint
3072 ///locations we intend to insert in
3074 lldb::DynamicLoaderUP m_dyld_ap;
3075 lldb::JITLoaderListUP m_jit_loaders_ap;
3076 lldb::DynamicCheckerFunctionsUP m_dynamic_checkers_ap; ///< The functions used
3077 ///by the expression
3078 ///parser to validate
3081 lldb::OperatingSystemUP m_os_ap;
3082 lldb::SystemRuntimeUP m_system_runtime_ap;
3084 m_unix_signals_sp; /// This is the current signal set for this process.
3085 lldb::ABISP m_abi_sp;
3086 lldb::IOHandlerSP m_process_input_reader;
3087 Communication m_stdio_communication;
3088 std::recursive_mutex m_stdio_communication_mutex;
3089 bool m_stdin_forward; /// Remember if stdin must be forwarded to remote debug
3091 std::string m_stdout_data;
3092 std::string m_stderr_data;
3093 std::recursive_mutex m_profile_data_comm_mutex;
3094 std::vector<std::string> m_profile_data;
3095 Predicate<uint32_t> m_iohandler_sync;
3096 MemoryCache m_memory_cache;
3097 AllocatedMemoryCache m_allocated_memory_cache;
3098 bool m_should_detach; /// Should we detach if the process object goes away
3099 /// with an explicit call to Kill or Detach?
3100 LanguageRuntimeCollection m_language_runtimes;
3101 InstrumentationRuntimeCollection m_instrumentation_runtimes;
3102 std::unique_ptr<NextEventAction> m_next_event_action_ap;
3103 std::vector<PreResumeCallbackAndBaton> m_pre_resume_actions;
3104 ProcessRunLock m_public_run_lock;
3105 ProcessRunLock m_private_run_lock;
3106 bool m_currently_handling_do_on_removals;
3107 bool m_resume_requested; // If m_currently_handling_event or
3108 // m_currently_handling_do_on_removals are true,
3109 // Resume will only request a resume, using this
3111 bool m_finalizing; // This is set at the beginning of Process::Finalize() to
3112 // stop functions from looking up or creating things
3113 // during a finalize call
3114 bool m_finalize_called; // This is set at the end of Process::Finalize()
3115 bool m_clear_thread_plans_on_stop;
3116 bool m_force_next_event_delivery;
3117 lldb::StateType m_last_broadcast_state; /// This helps with the Public event
3119 /// ShouldBroadcastEvent.
3120 std::map<lldb::addr_t, lldb::addr_t> m_resolved_indirect_addresses;
3121 bool m_destroy_in_process;
3122 bool m_can_interpret_function_calls; // Some targets, e.g the OSX kernel,
3123 // don't support the ability to modify
3125 WarningsCollection m_warnings_issued; // A set of object pointers which have
3126 // already had warnings printed
3127 std::mutex m_run_thread_plan_lock;
3128 StructuredDataPluginMap m_structured_data_plugin_map;
3130 enum { eCanJITDontKnow = 0, eCanJITYes, eCanJITNo } m_can_jit;
3132 std::unique_ptr<UtilityFunction> m_dlopen_utility_func_up;
3133 std::once_flag m_dlopen_utility_func_flag_once;
3135 size_t RemoveBreakpointOpcodesFromBuffer(lldb::addr_t addr, size_t size,
3136 uint8_t *buf) const;
3138 void SynchronouslyNotifyStateChanged(lldb::StateType state);
3140 void SetPublicState(lldb::StateType new_state, bool restarted);
3142 void SetPrivateState(lldb::StateType state);
3144 bool StartPrivateStateThread(bool is_secondary_thread = false);
3146 void StopPrivateStateThread();
3148 void PausePrivateStateThread();
3150 void ResumePrivateStateThread();
3153 struct PrivateStateThreadArgs {
3154 PrivateStateThreadArgs(Process *p, bool s)
3155 : process(p), is_secondary_thread(s){};
3157 bool is_secondary_thread;
3160 // arg is a pointer to a new'ed PrivateStateThreadArgs structure.
3161 // PrivateStateThread will free it for you.
3162 static lldb::thread_result_t PrivateStateThread(void *arg);
3164 // The starts up the private state thread that will watch for events from the
3165 // debugee. Pass true for is_secondary_thread in the case where you have to
3166 // temporarily spin up a secondary state thread to handle events from a hand-
3167 // called function on the primary private state thread.
3169 lldb::thread_result_t RunPrivateStateThread(bool is_secondary_thread);
3172 void HandlePrivateEvent(lldb::EventSP &event_sp);
3174 Status HaltPrivate();
3176 lldb::StateType WaitForProcessStopPrivate(lldb::EventSP &event_sp,
3177 const Timeout<std::micro> &timeout);
3179 // This waits for both the state change broadcaster, and the control
3180 // broadcaster. If control_only, it only waits for the control broadcaster.
3182 bool GetEventsPrivate(lldb::EventSP &event_sp,
3183 const Timeout<std::micro> &timeout, bool control_only);
3186 GetStateChangedEventsPrivate(lldb::EventSP &event_sp,
3187 const Timeout<std::micro> &timeout);
3189 size_t WriteMemoryPrivate(lldb::addr_t addr, const void *buf, size_t size,
3192 void AppendSTDOUT(const char *s, size_t len);
3194 void AppendSTDERR(const char *s, size_t len);
3196 void BroadcastAsyncProfileData(const std::string &one_profile_data);
3198 static void STDIOReadThreadBytesReceived(void *baton, const void *src,
3201 bool PushProcessIOHandler();
3203 bool PopProcessIOHandler();
3205 bool ProcessIOHandlerIsActive();
3207 bool ProcessIOHandlerExists() const {
3208 return static_cast<bool>(m_process_input_reader);
3211 Status StopForDestroyOrDetach(lldb::EventSP &exit_event_sp);
3213 virtual Status UpdateAutomaticSignalFiltering();
3215 bool StateChangedIsExternallyHijacked();
3217 void LoadOperatingSystemPlugin(bool flush);
3220 //------------------------------------------------------------------
3221 /// This is the part of the event handling that for a process event. It
3222 /// decides what to do with the event and returns true if the event needs to
3223 /// be propagated to the user, and false otherwise. If the event is not
3224 /// propagated, this call will most likely set the target to executing
3225 /// again. There is only one place where this call should be called,
3226 /// HandlePrivateEvent. Don't call it from anywhere else...
3228 /// @param[in] event_ptr
3229 /// This is the event we are handling.
3232 /// Returns \b true if the event should be reported to the
3233 /// user, \b false otherwise.
3234 //------------------------------------------------------------------
3235 bool ShouldBroadcastEvent(Event *event_ptr);
3237 void ControlPrivateStateThread(uint32_t signal);
3239 DISALLOW_COPY_AND_ASSIGN(Process);
3242 //------------------------------------------------------------------
3243 /// RAII guard that should be aquired when an utility function is called within
3244 /// a given process.
3245 //------------------------------------------------------------------
3246 class UtilityFunctionScope {
3250 UtilityFunctionScope(Process *p) : m_process(p) {
3252 m_process->SetRunningUtilityFunction(true);
3254 ~UtilityFunctionScope() {
3256 m_process->SetRunningUtilityFunction(false);
3260 } // namespace lldb_private
3262 #endif // liblldb_Process_h_