1 //===-- Process.h -----------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef liblldb_Process_h_
11 #define liblldb_Process_h_
13 #include "lldb/Host/Config.h"
24 #include <unordered_set>
27 // Other libraries and framework includes
29 #include "lldb/Breakpoint/BreakpointSiteList.h"
30 #include "lldb/Core/Broadcaster.h"
31 #include "lldb/Core/Communication.h"
32 #include "lldb/Core/Event.h"
33 #include "lldb/Core/Listener.h"
34 #include "lldb/Core/LoadedModuleInfoList.h"
35 #include "lldb/Core/PluginInterface.h"
36 #include "lldb/Core/ThreadSafeValue.h"
37 #include "lldb/Core/UserSettingsController.h"
38 #include "lldb/Host/HostThread.h"
39 #include "lldb/Host/ProcessRunLock.h"
40 #include "lldb/Interpreter/Options.h"
41 #include "lldb/Symbol/ObjectFile.h"
42 #include "lldb/Target/ExecutionContextScope.h"
43 #include "lldb/Target/InstrumentationRuntime.h"
44 #include "lldb/Target/Memory.h"
45 #include "lldb/Target/ProcessInfo.h"
46 #include "lldb/Target/ProcessLaunchInfo.h"
47 #include "lldb/Target/QueueList.h"
48 #include "lldb/Target/ThreadList.h"
49 #include "lldb/Utility/ArchSpec.h"
50 #include "lldb/Utility/NameMatches.h"
51 #include "lldb/Utility/Status.h"
52 #include "lldb/Utility/StructuredData.h"
53 #include "lldb/Utility/TraceOptions.h"
54 #include "lldb/lldb-private.h"
56 #include "llvm/ADT/ArrayRef.h"
57 #include "llvm/Support/VersionTuple.h"
59 namespace lldb_private {
61 template <typename B, typename S> struct Range;
63 //----------------------------------------------------------------------
65 //----------------------------------------------------------------------
66 class ProcessProperties : public Properties {
68 // Pass nullptr for "process" if the ProcessProperties are to be the global
70 ProcessProperties(lldb_private::Process *process);
72 ~ProcessProperties() override;
74 bool GetDisableMemoryCache() const;
76 uint64_t GetMemoryCacheLineSize() const;
78 Args GetExtraStartupCommands() const;
80 void SetExtraStartupCommands(const Args &args);
82 FileSpec GetPythonOSPluginPath() const;
84 void SetPythonOSPluginPath(const FileSpec &file);
86 bool GetIgnoreBreakpointsInExpressions() const;
88 void SetIgnoreBreakpointsInExpressions(bool ignore);
90 bool GetUnwindOnErrorInExpressions() const;
92 void SetUnwindOnErrorInExpressions(bool ignore);
94 bool GetStopOnSharedLibraryEvents() const;
96 void SetStopOnSharedLibraryEvents(bool stop);
98 bool GetDetachKeepsStopped() const;
100 void SetDetachKeepsStopped(bool keep_stopped);
102 bool GetWarningsOptimization() const;
104 bool GetStopOnExec() const;
107 static void OptionValueChangedCallback(void *baton,
108 OptionValue *option_value);
110 Process *m_process; // Can be nullptr for global ProcessProperties
113 typedef std::shared_ptr<ProcessProperties> ProcessPropertiesSP;
115 //----------------------------------------------------------------------
116 // ProcessInstanceInfo
118 // Describes an existing process and any discoverable information that pertains
120 //----------------------------------------------------------------------
121 class ProcessInstanceInfo : public ProcessInfo {
123 ProcessInstanceInfo()
124 : ProcessInfo(), m_euid(UINT32_MAX), m_egid(UINT32_MAX),
125 m_parent_pid(LLDB_INVALID_PROCESS_ID) {}
127 ProcessInstanceInfo(const char *name, const ArchSpec &arch, lldb::pid_t pid)
128 : ProcessInfo(name, arch, pid), m_euid(UINT32_MAX), m_egid(UINT32_MAX),
129 m_parent_pid(LLDB_INVALID_PROCESS_ID) {}
132 ProcessInfo::Clear();
135 m_parent_pid = LLDB_INVALID_PROCESS_ID;
138 uint32_t GetEffectiveUserID() const { return m_euid; }
140 uint32_t GetEffectiveGroupID() const { return m_egid; }
142 bool EffectiveUserIDIsValid() const { return m_euid != UINT32_MAX; }
144 bool EffectiveGroupIDIsValid() const { return m_egid != UINT32_MAX; }
146 void SetEffectiveUserID(uint32_t uid) { m_euid = uid; }
148 void SetEffectiveGroupID(uint32_t gid) { m_egid = gid; }
150 lldb::pid_t GetParentProcessID() const { return m_parent_pid; }
152 void SetParentProcessID(lldb::pid_t pid) { m_parent_pid = pid; }
154 bool ParentProcessIDIsValid() const {
155 return m_parent_pid != LLDB_INVALID_PROCESS_ID;
158 void Dump(Stream &s, Platform *platform) const;
160 static void DumpTableHeader(Stream &s, Platform *platform, bool show_args,
163 void DumpAsTableRow(Stream &s, Platform *platform, bool show_args,
169 lldb::pid_t m_parent_pid;
172 //----------------------------------------------------------------------
175 // Describes any information that is required to attach to a process.
176 //----------------------------------------------------------------------
178 class ProcessAttachInfo : public ProcessInstanceInfo {
181 : ProcessInstanceInfo(), m_listener_sp(), m_hijack_listener_sp(),
182 m_plugin_name(), m_resume_count(0), m_wait_for_launch(false),
183 m_ignore_existing(true), m_continue_once_attached(false),
184 m_detach_on_error(true), m_async(false) {}
186 ProcessAttachInfo(const ProcessLaunchInfo &launch_info)
187 : ProcessInstanceInfo(), m_listener_sp(), m_hijack_listener_sp(),
188 m_plugin_name(), m_resume_count(0), m_wait_for_launch(false),
189 m_ignore_existing(true), m_continue_once_attached(false),
190 m_detach_on_error(true), m_async(false) {
191 ProcessInfo::operator=(launch_info);
192 SetProcessPluginName(launch_info.GetProcessPluginName());
193 SetResumeCount(launch_info.GetResumeCount());
194 SetListener(launch_info.GetListener());
195 SetHijackListener(launch_info.GetHijackListener());
196 m_detach_on_error = launch_info.GetDetachOnError();
199 bool GetWaitForLaunch() const { return m_wait_for_launch; }
201 void SetWaitForLaunch(bool b) { m_wait_for_launch = b; }
203 bool GetAsync() const { return m_async; }
205 void SetAsync(bool b) { m_async = b; }
207 bool GetIgnoreExisting() const { return m_ignore_existing; }
209 void SetIgnoreExisting(bool b) { m_ignore_existing = b; }
211 bool GetContinueOnceAttached() const { return m_continue_once_attached; }
213 void SetContinueOnceAttached(bool b) { m_continue_once_attached = b; }
215 uint32_t GetResumeCount() const { return m_resume_count; }
217 void SetResumeCount(uint32_t c) { m_resume_count = c; }
219 const char *GetProcessPluginName() const {
220 return (m_plugin_name.empty() ? nullptr : m_plugin_name.c_str());
223 void SetProcessPluginName(llvm::StringRef plugin) { m_plugin_name = plugin; }
226 ProcessInstanceInfo::Clear();
227 m_plugin_name.clear();
229 m_wait_for_launch = false;
230 m_ignore_existing = true;
231 m_continue_once_attached = false;
234 bool ProcessInfoSpecified() const {
235 if (GetExecutableFile())
237 if (GetProcessID() != LLDB_INVALID_PROCESS_ID)
239 if (GetParentProcessID() != LLDB_INVALID_PROCESS_ID)
244 lldb::ListenerSP GetHijackListener() const { return m_hijack_listener_sp; }
246 void SetHijackListener(const lldb::ListenerSP &listener_sp) {
247 m_hijack_listener_sp = listener_sp;
250 bool GetDetachOnError() const { return m_detach_on_error; }
252 void SetDetachOnError(bool enable) { m_detach_on_error = enable; }
254 // Get and set the actual listener that will be used for the process events
255 lldb::ListenerSP GetListener() const { return m_listener_sp; }
257 void SetListener(const lldb::ListenerSP &listener_sp) {
258 m_listener_sp = listener_sp;
261 lldb::ListenerSP GetListenerForProcess(Debugger &debugger);
264 lldb::ListenerSP m_listener_sp;
265 lldb::ListenerSP m_hijack_listener_sp;
266 std::string m_plugin_name;
267 uint32_t m_resume_count; // How many times do we resume after launching
268 bool m_wait_for_launch;
269 bool m_ignore_existing;
270 bool m_continue_once_attached; // Supports the use-case scenario of
271 // immediately continuing the process once
273 bool m_detach_on_error; // If we are debugging remotely, instruct the stub to
274 // detach rather than killing the target on error.
275 bool m_async; // Use an async attach where we start the attach and return
276 // immediately (used by GUI programs with --waitfor so they can
277 // call SBProcess::Stop() to cancel attach)
280 class ProcessLaunchCommandOptions : public Options {
282 ProcessLaunchCommandOptions() : Options() {
283 // Keep default values of all options in one place: OptionParsingStarting
285 OptionParsingStarting(nullptr);
288 ~ProcessLaunchCommandOptions() override = default;
290 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
291 ExecutionContext *execution_context) override;
293 void OptionParsingStarting(ExecutionContext *execution_context) override {
295 disable_aslr = eLazyBoolCalculate;
298 llvm::ArrayRef<OptionDefinition> GetDefinitions() override;
300 // Instance variables to hold the values for command options.
302 ProcessLaunchInfo launch_info;
303 lldb_private::LazyBool disable_aslr;
306 //----------------------------------------------------------------------
307 // ProcessInstanceInfoMatch
309 // A class to help matching one ProcessInstanceInfo to another.
310 //----------------------------------------------------------------------
312 class ProcessInstanceInfoMatch {
314 ProcessInstanceInfoMatch()
315 : m_match_info(), m_name_match_type(NameMatch::Ignore),
316 m_match_all_users(false) {}
318 ProcessInstanceInfoMatch(const char *process_name,
319 NameMatch process_name_match_type)
320 : m_match_info(), m_name_match_type(process_name_match_type),
321 m_match_all_users(false) {
322 m_match_info.GetExecutableFile().SetFile(process_name, false,
323 FileSpec::Style::native);
326 ProcessInstanceInfo &GetProcessInfo() { return m_match_info; }
328 const ProcessInstanceInfo &GetProcessInfo() const { return m_match_info; }
330 bool GetMatchAllUsers() const { return m_match_all_users; }
332 void SetMatchAllUsers(bool b) { m_match_all_users = b; }
334 NameMatch GetNameMatchType() const { return m_name_match_type; }
336 void SetNameMatchType(NameMatch name_match_type) {
337 m_name_match_type = name_match_type;
340 bool NameMatches(const char *process_name) const;
342 bool Matches(const ProcessInstanceInfo &proc_info) const;
344 bool MatchAllProcesses() const;
348 ProcessInstanceInfo m_match_info;
349 NameMatch m_name_match_type;
350 bool m_match_all_users;
353 class ProcessInstanceInfoList {
355 ProcessInstanceInfoList() = default;
357 void Clear() { m_infos.clear(); }
359 size_t GetSize() { return m_infos.size(); }
361 void Append(const ProcessInstanceInfo &info) { m_infos.push_back(info); }
363 const char *GetProcessNameAtIndex(size_t idx) {
364 return ((idx < m_infos.size()) ? m_infos[idx].GetName() : nullptr);
367 size_t GetProcessNameLengthAtIndex(size_t idx) {
368 return ((idx < m_infos.size()) ? m_infos[idx].GetNameLength() : 0);
371 lldb::pid_t GetProcessIDAtIndex(size_t idx) {
372 return ((idx < m_infos.size()) ? m_infos[idx].GetProcessID() : 0);
375 bool GetInfoAtIndex(size_t idx, ProcessInstanceInfo &info) {
376 if (idx < m_infos.size()) {
383 // You must ensure "idx" is valid before calling this function
384 const ProcessInstanceInfo &GetProcessInfoAtIndex(size_t idx) const {
385 assert(idx < m_infos.size());
390 typedef std::vector<ProcessInstanceInfo> collection;
394 // This class tracks the Modification state of the process. Things that can
395 // currently modify the program are running the program (which will up the
396 // StopID) and writing memory (which will up the MemoryID.)
397 // FIXME: Should we also include modification of register states?
400 friend bool operator==(const ProcessModID &lhs, const ProcessModID &rhs);
404 : m_stop_id(0), m_last_natural_stop_id(0), m_resume_id(0), m_memory_id(0),
405 m_last_user_expression_resume(0), m_running_user_expression(false) {}
407 ProcessModID(const ProcessModID &rhs)
408 : m_stop_id(rhs.m_stop_id), m_memory_id(rhs.m_memory_id) {}
410 const ProcessModID &operator=(const ProcessModID &rhs) {
412 m_stop_id = rhs.m_stop_id;
413 m_memory_id = rhs.m_memory_id;
418 ~ProcessModID() = default;
422 if (!IsLastResumeForUserExpression())
423 m_last_natural_stop_id++;
426 void BumpMemoryID() { m_memory_id++; }
428 void BumpResumeID() {
430 if (m_running_user_expression > 0)
431 m_last_user_expression_resume = m_resume_id;
434 uint32_t GetStopID() const { return m_stop_id; }
435 uint32_t GetLastNaturalStopID() const { return m_last_natural_stop_id; }
436 uint32_t GetMemoryID() const { return m_memory_id; }
437 uint32_t GetResumeID() const { return m_resume_id; }
438 uint32_t GetLastUserExpressionResumeID() const {
439 return m_last_user_expression_resume;
442 bool MemoryIDEqual(const ProcessModID &compare) const {
443 return m_memory_id == compare.m_memory_id;
446 bool StopIDEqual(const ProcessModID &compare) const {
447 return m_stop_id == compare.m_stop_id;
450 void SetInvalid() { m_stop_id = UINT32_MAX; }
452 bool IsValid() const { return m_stop_id != UINT32_MAX; }
454 bool IsLastResumeForUserExpression() const {
455 // If we haven't yet resumed the target, then it can't be for a user
457 if (m_resume_id == 0)
460 return m_resume_id == m_last_user_expression_resume;
463 void SetRunningUserExpression(bool on) {
465 m_running_user_expression++;
467 m_running_user_expression--;
470 void SetStopEventForLastNaturalStopID(lldb::EventSP event_sp) {
471 m_last_natural_stop_event = event_sp;
474 lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const {
475 if (stop_id == m_last_natural_stop_id)
476 return m_last_natural_stop_event;
477 return lldb::EventSP();
482 uint32_t m_last_natural_stop_id;
483 uint32_t m_resume_id;
484 uint32_t m_memory_id;
485 uint32_t m_last_user_expression_resume;
486 uint32_t m_running_user_expression;
487 lldb::EventSP m_last_natural_stop_event;
490 inline bool operator==(const ProcessModID &lhs, const ProcessModID &rhs) {
491 if (lhs.StopIDEqual(rhs) && lhs.MemoryIDEqual(rhs))
497 inline bool operator!=(const ProcessModID &lhs, const ProcessModID &rhs) {
498 return (!lhs.StopIDEqual(rhs) || !lhs.MemoryIDEqual(rhs));
501 //----------------------------------------------------------------------
502 /// @class Process Process.h "lldb/Target/Process.h"
503 /// A plug-in interface definition class for debugging a process.
504 //----------------------------------------------------------------------
505 class Process : public std::enable_shared_from_this<Process>,
506 public ProcessProperties,
509 public ExecutionContextScope,
510 public PluginInterface {
511 friend class FunctionCaller; // For WaitForStateChangeEventsPrivate
512 friend class Debugger; // For PopProcessIOHandler and ProcessIOHandlerIsActive
513 friend class DynamicLoader; // For LoadOperatingSystemPlugin
514 friend class ProcessEventData;
515 friend class StopInfo;
517 friend class ThreadList;
520 //------------------------------------------------------------------
521 /// Broadcaster event bits definitions.
522 //------------------------------------------------------------------
524 eBroadcastBitStateChanged = (1 << 0),
525 eBroadcastBitInterrupt = (1 << 1),
526 eBroadcastBitSTDOUT = (1 << 2),
527 eBroadcastBitSTDERR = (1 << 3),
528 eBroadcastBitProfileData = (1 << 4),
529 eBroadcastBitStructuredData = (1 << 5),
533 eBroadcastInternalStateControlStop = (1 << 0),
534 eBroadcastInternalStateControlPause = (1 << 1),
535 eBroadcastInternalStateControlResume = (1 << 2)
538 //------------------------------------------------------------------
539 /// Process warning types.
540 //------------------------------------------------------------------
541 enum Warnings { eWarningsOptimization = 1 };
543 typedef Range<lldb::addr_t, lldb::addr_t> LoadRange;
544 // We use a read/write lock to allow on or more clients to access the process
545 // state while the process is stopped (reader). We lock the write lock to
546 // control access to the process while it is running (readers, or clients
547 // that want the process stopped can block waiting for the process to stop,
548 // or just try to lock it to see if they can immediately access the stopped
549 // process. If the try read lock fails, then the process is running.
550 typedef ProcessRunLock::ProcessRunLocker StopLocker;
552 // These two functions fill out the Broadcaster interface:
554 static ConstString &GetStaticBroadcasterClass();
556 ConstString &GetBroadcasterClass() const override {
557 return GetStaticBroadcasterClass();
560 //------------------------------------------------------------------
561 /// A notification structure that can be used by clients to listen
562 /// for changes in a process's lifetime.
564 /// @see RegisterNotificationCallbacks (const Notifications&) @see
565 /// UnregisterNotificationCallbacks (const Notifications&)
566 //------------------------------------------------------------------
570 void (*initialize)(void *baton, Process *process);
571 void (*process_state_changed)(void *baton, Process *process,
572 lldb::StateType state);
575 class ProcessEventData : public EventData {
576 friend class Process;
580 ProcessEventData(const lldb::ProcessSP &process, lldb::StateType state);
582 ~ProcessEventData() override;
584 static const ConstString &GetFlavorString();
586 const ConstString &GetFlavor() const override;
588 lldb::ProcessSP GetProcessSP() const { return m_process_wp.lock(); }
590 lldb::StateType GetState() const { return m_state; }
591 bool GetRestarted() const { return m_restarted; }
593 size_t GetNumRestartedReasons() { return m_restarted_reasons.size(); }
595 const char *GetRestartedReasonAtIndex(size_t idx) {
596 return ((idx < m_restarted_reasons.size())
597 ? m_restarted_reasons[idx].c_str()
601 bool GetInterrupted() const { return m_interrupted; }
603 void Dump(Stream *s) const override;
605 void DoOnRemoval(Event *event_ptr) override;
607 static const Process::ProcessEventData *
608 GetEventDataFromEvent(const Event *event_ptr);
610 static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr);
612 static lldb::StateType GetStateFromEvent(const Event *event_ptr);
614 static bool GetRestartedFromEvent(const Event *event_ptr);
616 static size_t GetNumRestartedReasons(const Event *event_ptr);
618 static const char *GetRestartedReasonAtIndex(const Event *event_ptr,
621 static void AddRestartedReason(Event *event_ptr, const char *reason);
623 static void SetRestartedInEvent(Event *event_ptr, bool new_value);
625 static bool GetInterruptedFromEvent(const Event *event_ptr);
627 static void SetInterruptedInEvent(Event *event_ptr, bool new_value);
629 static bool SetUpdateStateOnRemoval(Event *event_ptr);
632 void SetUpdateStateOnRemoval() { m_update_state++; }
634 void SetRestarted(bool new_value) { m_restarted = new_value; }
636 void SetInterrupted(bool new_value) { m_interrupted = new_value; }
638 void AddRestartedReason(const char *reason) {
639 m_restarted_reasons.push_back(reason);
642 lldb::ProcessWP m_process_wp;
643 lldb::StateType m_state;
644 std::vector<std::string> m_restarted_reasons;
645 bool m_restarted; // For "eStateStopped" events, this is true if the target
646 // was automatically restarted.
650 DISALLOW_COPY_AND_ASSIGN(ProcessEventData);
654 //------------------------------------------------------------------
655 /// Construct with a shared pointer to a target, and the Process listener.
656 /// Uses the Host UnixSignalsSP by default.
657 //------------------------------------------------------------------
658 Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp);
660 //------------------------------------------------------------------
661 /// Construct with a shared pointer to a target, the Process listener, and
662 /// the appropriate UnixSignalsSP for the process.
663 //------------------------------------------------------------------
664 Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp,
665 const lldb::UnixSignalsSP &unix_signals_sp);
667 //------------------------------------------------------------------
670 /// The destructor is virtual since this class is designed to be inherited
671 /// from by the plug-in instance.
672 //------------------------------------------------------------------
675 static void SettingsInitialize();
677 static void SettingsTerminate();
679 static const ProcessPropertiesSP &GetGlobalProperties();
681 //------------------------------------------------------------------
682 /// Find a Process plug-in that can debug \a module using the currently
683 /// selected architecture.
685 /// Scans all loaded plug-in interfaces that implement versions of the
686 /// Process plug-in interface and returns the first instance that can debug
689 /// @param[in] module_sp
690 /// The module shared pointer that this process will debug.
692 /// @param[in] plugin_name
693 /// If nullptr, select the best plug-in for the binary. If non-nullptr
694 /// then look for a plugin whose PluginInfo's name matches
697 /// @see Process::CanDebug ()
698 //------------------------------------------------------------------
699 static lldb::ProcessSP FindPlugin(lldb::TargetSP target_sp,
700 llvm::StringRef plugin_name,
701 lldb::ListenerSP listener_sp,
702 const FileSpec *crash_file_path);
704 //------------------------------------------------------------------
705 /// Static function that can be used with the \b host function
706 /// Host::StartMonitoringChildProcess ().
708 /// This function can be used by lldb_private::Process subclasses when they
709 /// want to watch for a local process and have its exit status automatically
710 /// set when the host child process exits. Subclasses should call
711 /// Host::StartMonitoringChildProcess () with:
712 /// callback = Process::SetHostProcessExitStatus
713 /// pid = Process::GetID()
714 /// monitor_signals = false
715 //------------------------------------------------------------------
717 SetProcessExitStatus(lldb::pid_t pid, // The process ID we want to monitor
719 int signo, // Zero for no signal
720 int status); // Exit value of process if signal is zero
722 lldb::ByteOrder GetByteOrder() const;
724 uint32_t GetAddressByteSize() const;
726 uint32_t GetUniqueID() const { return m_process_unique_id; }
728 //------------------------------------------------------------------
729 /// Check if a plug-in instance can debug the file in \a module.
731 /// Each plug-in is given a chance to say whether it can debug the file in
732 /// \a module. If the Process plug-in instance can debug a file on the
733 /// current system, it should return \b true.
736 /// Returns \b true if this Process plug-in instance can
737 /// debug the executable, \b false otherwise.
738 //------------------------------------------------------------------
739 virtual bool CanDebug(lldb::TargetSP target,
740 bool plugin_specified_by_name) = 0;
742 //------------------------------------------------------------------
743 /// This object is about to be destroyed, do any necessary cleanup.
745 /// Subclasses that override this method should always call this superclass
747 //------------------------------------------------------------------
748 virtual void Finalize();
750 //------------------------------------------------------------------
751 /// Return whether this object is valid (i.e. has not been finalized.)
754 /// Returns \b true if this Process has not been finalized
755 /// and \b false otherwise.
756 //------------------------------------------------------------------
757 bool IsValid() const { return !m_finalize_called; }
759 //------------------------------------------------------------------
760 /// Return a multi-word command object that can be used to expose plug-in
761 /// specific commands.
763 /// This object will be used to resolve plug-in commands and can be
764 /// triggered by a call to:
766 /// (lldb) process command <args>
769 /// A CommandObject which can be one of the concrete subclasses
770 /// of CommandObject like CommandObjectRaw, CommandObjectParsed,
771 /// or CommandObjectMultiword.
772 //------------------------------------------------------------------
773 virtual CommandObject *GetPluginCommandObject() { return nullptr; }
775 //------------------------------------------------------------------
776 /// Launch a new process.
778 /// Launch a new process by spawning a new process using the target object's
779 /// executable module's file as the file to launch.
781 /// This function is not meant to be overridden by Process subclasses. It
782 /// will first call Process::WillLaunch (Module *) and if that returns \b
783 /// true, Process::DoLaunch (Module*, char const *[],char const *[],const
784 /// char *,const char *, const char *) will be called to actually do the
785 /// launching. If DoLaunch returns \b true, then Process::DidLaunch() will
788 /// @param[in] launch_info
789 /// Details regarding the environment, STDIN/STDOUT/STDERR
790 /// redirection, working path, etc. related to the requested launch.
793 /// An error object. Call GetID() to get the process ID if
794 /// the error object is success.
795 //------------------------------------------------------------------
796 virtual Status Launch(ProcessLaunchInfo &launch_info);
798 virtual Status LoadCore();
800 virtual Status DoLoadCore() {
802 error.SetErrorStringWithFormat(
803 "error: %s does not support loading core files.",
804 GetPluginName().GetCString());
808 //------------------------------------------------------------------
809 // FUTURE WORK: GetLoadImageUtilityFunction are the first use we've
810 // had of having other plugins cache data in the Process. This is handy for
811 // long-living plugins - like the Platform - which manage interactions whose
812 // lifetime is governed by the Process lifetime. If we find we need to do
813 // this more often, we should construct a general solution to the problem.
814 // The consensus suggestion was that we have a token based registry in the
815 // Process. Some undecided questions are (1) who manages the tokens. It's
816 // probably best that you add the element and get back a token that
817 // represents it. That will avoid collisions. But there may be some utility
818 // in the registerer controlling the token? (2) whether the thing added
819 // should be simply owned by Process, and just go away when it does (3)
820 // whether the registree should be notified of the Process' demise.
822 // We are postponing designing this till we have at least a second use case.
823 //------------------------------------------------------------------
824 //------------------------------------------------------------------
825 /// Get the cached UtilityFunction that assists in loading binary images
826 /// into the process.
828 /// @param[in] platform
829 /// The platform fetching the UtilityFunction.
830 /// @param[in] factory
831 /// A function that will be called only once per-process in a
832 /// thread-safe way to create the UtilityFunction if it has not
833 /// been initialized yet.
836 /// The cached utility function or null if the platform is not the
837 /// same as the target's platform.
838 //------------------------------------------------------------------
839 UtilityFunction *GetLoadImageUtilityFunction(
841 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory);
843 //------------------------------------------------------------------
844 /// Get the dynamic loader plug-in for this process.
846 /// The default action is to let the DynamicLoader plug-ins check the main
847 /// executable and the DynamicLoader will select itself automatically.
848 /// Subclasses can override this if inspecting the executable is not
849 /// desired, or if Process subclasses can only use a specific DynamicLoader
851 //------------------------------------------------------------------
852 virtual DynamicLoader *GetDynamicLoader();
854 //------------------------------------------------------------------
855 // Returns AUXV structure found in many ELF-based environments.
857 // The default action is to return an empty data buffer.
860 // A data buffer containing the contents of the AUXV data.
861 //------------------------------------------------------------------
862 virtual const lldb::DataBufferSP GetAuxvData();
864 //------------------------------------------------------------------
865 /// Sometimes processes know how to retrieve and load shared libraries. This
866 /// is normally done by DynamicLoader plug-ins, but sometimes the connection
867 /// to the process allows retrieving this information. The dynamic loader
868 /// plug-ins can use this function if they can't determine the current
869 /// shared library load state.
872 /// The number of shared libraries that were loaded
873 //------------------------------------------------------------------
874 virtual size_t LoadModules() { return 0; }
876 virtual size_t LoadModules(LoadedModuleInfoList &) { return 0; }
879 virtual JITLoaderList &GetJITLoaders();
882 //------------------------------------------------------------------
883 /// Get the system runtime plug-in for this process.
886 /// Returns a pointer to the SystemRuntime plugin for this Process
887 /// if one is available. Else returns nullptr.
888 //------------------------------------------------------------------
889 virtual SystemRuntime *GetSystemRuntime();
891 //------------------------------------------------------------------
892 /// Attach to an existing process using the process attach info.
894 /// This function is not meant to be overridden by Process subclasses. It
895 /// will first call WillAttach (lldb::pid_t) or WillAttach (const char *),
896 /// and if that returns \b true, DoAttach (lldb::pid_t) or DoAttach (const
897 /// char *) will be called to actually do the attach. If DoAttach returns \b
898 /// true, then Process::DidAttach() will be called.
901 /// The process ID that we should attempt to attach to.
904 /// Returns \a pid if attaching was successful, or
905 /// LLDB_INVALID_PROCESS_ID if attaching fails.
906 //------------------------------------------------------------------
907 virtual Status Attach(ProcessAttachInfo &attach_info);
909 //------------------------------------------------------------------
910 /// Attach to a remote system via a URL
913 /// A stream where output intended for the user
914 /// (if the driver has a way to display that) generated during
915 /// the connection. This may be nullptr if no output is needed.A
917 /// @param[in] remote_url
918 /// The URL format that we are connecting to.
921 /// Returns an error object.
922 //------------------------------------------------------------------
923 virtual Status ConnectRemote(Stream *strm, llvm::StringRef remote_url);
925 bool GetShouldDetach() const { return m_should_detach; }
927 void SetShouldDetach(bool b) { m_should_detach = b; }
929 //------------------------------------------------------------------
930 /// Get the image information address for the current process.
932 /// Some runtimes have system functions that can help dynamic loaders locate
933 /// the dynamic loader information needed to observe shared libraries being
934 /// loaded or unloaded. This function is in the Process interface (as
935 /// opposed to the DynamicLoader interface) to ensure that remote debugging
936 /// can take advantage of this functionality.
939 /// The address of the dynamic loader information, or
940 /// LLDB_INVALID_ADDRESS if this is not supported by this
942 //------------------------------------------------------------------
943 virtual lldb::addr_t GetImageInfoAddress();
945 //------------------------------------------------------------------
946 /// Called when the process is about to broadcast a public stop.
948 /// There are public and private stops. Private stops are when the process
949 /// is doing things like stepping and the client doesn't need to know about
950 /// starts and stop that implement a thread plan. Single stepping over a
951 /// source line in code might end up being implemented by one or more
952 /// process starts and stops. Public stops are when clients will be notified
953 /// that the process is stopped. These events typically trigger UI updates
954 /// (thread stack frames to be displayed, variables to be displayed, and
955 /// more). This function can be overriden and allows process subclasses to
956 /// do something before the eBroadcastBitStateChanged event is sent to
958 //------------------------------------------------------------------
959 virtual void WillPublicStop() {}
961 //------------------------------------------------------------------
962 /// Register for process and thread notifications.
964 /// Clients can register notification callbacks by filling out a
965 /// Process::Notifications structure and calling this function.
967 /// @param[in] callbacks
968 /// A structure that contains the notification baton and
969 /// callback functions.
971 /// @see Process::Notifications
972 //------------------------------------------------------------------
974 void RegisterNotificationCallbacks(const Process::Notifications &callbacks);
977 //------------------------------------------------------------------
978 /// Unregister for process and thread notifications.
980 /// Clients can unregister notification callbacks by passing a copy of the
981 /// original baton and callbacks in \a callbacks.
983 /// @param[in] callbacks
984 /// A structure that contains the notification baton and
985 /// callback functions.
988 /// Returns \b true if the notification callbacks were
989 /// successfully removed from the process, \b false otherwise.
991 /// @see Process::Notifications
992 //------------------------------------------------------------------
994 bool UnregisterNotificationCallbacks(const Process::Notifications &callbacks);
997 //==================================================================
998 // Built in Process Control functions
999 //==================================================================
1000 //------------------------------------------------------------------
1001 /// Resumes all of a process's threads as configured using the Thread run
1002 /// control functions.
1004 /// Threads for a process should be updated with one of the run control
1005 /// actions (resume, step, or suspend) that they should take when the
1006 /// process is resumed. If no run control action is given to a thread it
1007 /// will be resumed by default.
1009 /// This function is not meant to be overridden by Process subclasses. This
1010 /// function will take care of disabling any breakpoints that threads may be
1011 /// stopped at, single stepping, and re-enabling breakpoints, and enabling
1012 /// the basic flow control that the plug-in instances need not worry about.
1014 /// N.B. This function also sets the Write side of the Run Lock, which is
1015 /// unset when the corresponding stop event is pulled off the Public Event
1016 /// Queue. If you need to resume the process without setting the Run Lock,
1017 /// use PrivateResume (though you should only do that from inside the
1021 /// Returns an error object.
1023 /// @see Thread:Resume()
1024 /// @see Thread:Step()
1025 /// @see Thread:Suspend()
1026 //------------------------------------------------------------------
1029 Status ResumeSynchronous(Stream *stream);
1031 //------------------------------------------------------------------
1032 /// Halts a running process.
1034 /// This function is not meant to be overridden by Process subclasses. If
1035 /// the process is successfully halted, a eStateStopped process event with
1036 /// GetInterrupted will be broadcast. If false, we will halt the process
1037 /// with no events generated by the halt.
1039 /// @param[in] clear_thread_plans
1040 /// If true, when the process stops, clear all thread plans.
1042 /// @param[in] use_run_lock
1043 /// Whether to release the run lock after the stop.
1046 /// Returns an error object. If the error is empty, the process is
1048 /// otherwise the halt has failed.
1049 //------------------------------------------------------------------
1050 Status Halt(bool clear_thread_plans = false, bool use_run_lock = true);
1052 //------------------------------------------------------------------
1053 /// Detaches from a running or stopped process.
1055 /// This function is not meant to be overridden by Process subclasses.
1057 /// @param[in] keep_stopped
1058 /// If true, don't resume the process on detach.
1061 /// Returns an error object.
1062 //------------------------------------------------------------------
1063 Status Detach(bool keep_stopped);
1065 //------------------------------------------------------------------
1066 /// Kills the process and shuts down all threads that were spawned to track
1067 /// and monitor the process.
1069 /// This function is not meant to be overridden by Process subclasses.
1071 /// @param[in] force_kill
1072 /// Whether lldb should force a kill (instead of a detach) from
1073 /// the inferior process. Normally if lldb launched a binary and
1074 /// Destory is called, lldb kills it. If lldb attached to a
1075 /// running process and Destory is called, lldb detaches. If
1076 /// this behavior needs to be over-ridden, this is the bool that
1080 /// Returns an error object.
1081 //------------------------------------------------------------------
1082 Status Destroy(bool force_kill);
1084 //------------------------------------------------------------------
1085 /// Sends a process a UNIX signal \a signal.
1087 /// This function is not meant to be overridden by Process subclasses.
1090 /// Returns an error object.
1091 //------------------------------------------------------------------
1092 Status Signal(int signal);
1094 void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp);
1096 const lldb::UnixSignalsSP &GetUnixSignals();
1098 //==================================================================
1099 // Plug-in Process Control Overrides
1100 //==================================================================
1102 //------------------------------------------------------------------
1103 /// Called before attaching to a process.
1105 /// Allow Process plug-ins to execute some code before attaching a process.
1108 /// Returns an error object.
1109 //------------------------------------------------------------------
1110 virtual Status WillAttachToProcessWithID(lldb::pid_t pid) { return Status(); }
1112 //------------------------------------------------------------------
1113 /// Called before attaching to a process.
1115 /// Allow Process plug-ins to execute some code before attaching a process.
1118 /// Returns an error object.
1119 //------------------------------------------------------------------
1120 virtual Status WillAttachToProcessWithName(const char *process_name,
1121 bool wait_for_launch) {
1125 //------------------------------------------------------------------
1126 /// Attach to a remote system via a URL
1129 /// A stream where output intended for the user
1130 /// (if the driver has a way to display that) generated during
1131 /// the connection. This may be nullptr if no output is needed.A
1133 /// @param[in] remote_url
1134 /// The URL format that we are connecting to.
1137 /// Returns an error object.
1138 //------------------------------------------------------------------
1139 virtual Status DoConnectRemote(Stream *strm, llvm::StringRef remote_url) {
1141 error.SetErrorString("remote connections are not supported");
1145 //------------------------------------------------------------------
1146 /// Attach to an existing process using a process ID.
1149 /// The process ID that we should attempt to attach to.
1151 /// @param[in] attach_info
1152 /// Information on how to do the attach. For example, GetUserID()
1153 /// will return the uid to attach as.
1156 /// Returns a successful Status attaching was successful, or
1157 /// an appropriate (possibly platform-specific) error code if
1158 /// attaching fails.
1159 /// hanming : need flag
1160 //------------------------------------------------------------------
1161 virtual Status DoAttachToProcessWithID(lldb::pid_t pid,
1162 const ProcessAttachInfo &attach_info) {
1164 error.SetErrorStringWithFormat(
1165 "error: %s does not support attaching to a process by pid",
1166 GetPluginName().GetCString());
1170 //------------------------------------------------------------------
1171 /// Attach to an existing process using a partial process name.
1173 /// @param[in] process_name
1174 /// The name of the process to attach to.
1176 /// @param[in] attach_info
1177 /// Information on how to do the attach. For example, GetUserID()
1178 /// will return the uid to attach as.
1181 /// Returns a successful Status attaching was successful, or
1182 /// an appropriate (possibly platform-specific) error code if
1183 /// attaching fails.
1184 //------------------------------------------------------------------
1186 DoAttachToProcessWithName(const char *process_name,
1187 const ProcessAttachInfo &attach_info) {
1189 error.SetErrorString("attach by name is not supported");
1193 //------------------------------------------------------------------
1194 /// Called after attaching a process.
1196 /// @param[in] process_arch
1197 /// If you can figure out the process architecture after attach, fill it
1200 /// Allow Process plug-ins to execute some code after attaching to a
1202 //------------------------------------------------------------------
1203 virtual void DidAttach(ArchSpec &process_arch) { process_arch.Clear(); }
1205 //------------------------------------------------------------------
1206 /// Called after a process re-execs itself.
1208 /// Allow Process plug-ins to execute some code after a process has exec'ed
1209 /// itself. Subclasses typically should override DoDidExec() as the
1210 /// lldb_private::Process class needs to remove its dynamic loader, runtime,
1211 /// ABI and other plug-ins, as well as unload all shared libraries.
1212 //------------------------------------------------------------------
1213 virtual void DidExec();
1215 //------------------------------------------------------------------
1216 /// Subclasses of Process should implement this function if they need to do
1217 /// anything after a process exec's itself.
1218 //------------------------------------------------------------------
1219 virtual void DoDidExec() {}
1221 //------------------------------------------------------------------
1222 /// Called before launching to a process.
1224 /// Allow Process plug-ins to execute some code before launching a process.
1227 /// Returns an error object.
1228 //------------------------------------------------------------------
1229 virtual Status WillLaunch(Module *module) { return Status(); }
1231 //------------------------------------------------------------------
1232 /// Launch a new process.
1234 /// Launch a new process by spawning a new process using \a exe_module's
1235 /// file as the file to launch. Launch details are provided in \a
1238 /// @param[in] exe_module
1239 /// The module from which to extract the file specification and
1242 /// @param[in] launch_info
1243 /// Details (e.g. arguments, stdio redirection, etc.) for the
1244 /// requested launch.
1247 /// An Status instance indicating success or failure of the
1249 //------------------------------------------------------------------
1250 virtual Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) {
1252 error.SetErrorStringWithFormat(
1253 "error: %s does not support launching processes",
1254 GetPluginName().GetCString());
1258 //------------------------------------------------------------------
1259 /// Called after launching a process.
1261 /// Allow Process plug-ins to execute some code after launching a process.
1262 //------------------------------------------------------------------
1263 virtual void DidLaunch() {}
1265 //------------------------------------------------------------------
1266 /// Called before resuming to a process.
1268 /// Allow Process plug-ins to execute some code before resuming a process.
1271 /// Returns an error object.
1272 //------------------------------------------------------------------
1273 virtual Status WillResume() { return Status(); }
1275 //------------------------------------------------------------------
1276 /// Resumes all of a process's threads as configured using the Thread run
1277 /// control functions.
1279 /// Threads for a process should be updated with one of the run control
1280 /// actions (resume, step, or suspend) that they should take when the
1281 /// process is resumed. If no run control action is given to a thread it
1282 /// will be resumed by default.
1285 /// Returns \b true if the process successfully resumes using
1286 /// the thread run control actions, \b false otherwise.
1288 /// @see Thread:Resume()
1289 /// @see Thread:Step()
1290 /// @see Thread:Suspend()
1291 //------------------------------------------------------------------
1292 virtual Status DoResume() {
1294 error.SetErrorStringWithFormat(
1295 "error: %s does not support resuming processes",
1296 GetPluginName().GetCString());
1300 //------------------------------------------------------------------
1301 /// Called after resuming a process.
1303 /// Allow Process plug-ins to execute some code after resuming a process.
1304 //------------------------------------------------------------------
1305 virtual void DidResume() {}
1307 //------------------------------------------------------------------
1308 /// Called before halting to a process.
1310 /// Allow Process plug-ins to execute some code before halting a process.
1313 /// Returns an error object.
1314 //------------------------------------------------------------------
1315 virtual Status WillHalt() { return Status(); }
1317 //------------------------------------------------------------------
1318 /// Halts a running process.
1320 /// DoHalt must produce one and only one stop StateChanged event if it
1321 /// actually stops the process. If the stop happens through some natural
1322 /// event (for instance a SIGSTOP), then forwarding that event will do.
1323 /// Otherwise, you must generate the event manually. This function is called
1324 /// from the context of the private state thread.
1326 /// @param[out] caused_stop
1327 /// If true, then this Halt caused the stop, otherwise, the
1328 /// process was already stopped.
1331 /// Returns \b true if the process successfully halts, \b false
1333 //------------------------------------------------------------------
1334 virtual Status DoHalt(bool &caused_stop) {
1336 error.SetErrorStringWithFormat(
1337 "error: %s does not support halting processes",
1338 GetPluginName().GetCString());
1342 //------------------------------------------------------------------
1343 /// Called after halting a process.
1345 /// Allow Process plug-ins to execute some code after halting a process.
1346 //------------------------------------------------------------------
1347 virtual void DidHalt() {}
1349 //------------------------------------------------------------------
1350 /// Called before detaching from a process.
1352 /// Allow Process plug-ins to execute some code before detaching from a
1356 /// Returns an error object.
1357 //------------------------------------------------------------------
1358 virtual Status WillDetach() { return Status(); }
1360 //------------------------------------------------------------------
1361 /// Detaches from a running or stopped process.
1364 /// Returns \b true if the process successfully detaches, \b
1365 /// false otherwise.
1366 //------------------------------------------------------------------
1367 virtual Status DoDetach(bool keep_stopped) {
1369 error.SetErrorStringWithFormat(
1370 "error: %s does not support detaching from processes",
1371 GetPluginName().GetCString());
1375 //------------------------------------------------------------------
1376 /// Called after detaching from a process.
1378 /// Allow Process plug-ins to execute some code after detaching from a
1380 //------------------------------------------------------------------
1381 virtual void DidDetach() {}
1383 virtual bool DetachRequiresHalt() { return false; }
1385 //------------------------------------------------------------------
1386 /// Called before sending a signal to a process.
1388 /// Allow Process plug-ins to execute some code before sending a signal to a
1392 /// Returns no error if it is safe to proceed with a call to
1393 /// Process::DoSignal(int), otherwise an error describing what
1394 /// prevents the signal from being sent.
1395 //------------------------------------------------------------------
1396 virtual Status WillSignal() { return Status(); }
1398 //------------------------------------------------------------------
1399 /// Sends a process a UNIX signal \a signal.
1402 /// Returns an error object.
1403 //------------------------------------------------------------------
1404 virtual Status DoSignal(int signal) {
1406 error.SetErrorStringWithFormat(
1407 "error: %s does not support sending signals to processes",
1408 GetPluginName().GetCString());
1412 virtual Status WillDestroy() { return Status(); }
1414 virtual Status DoDestroy() = 0;
1416 virtual void DidDestroy() {}
1418 virtual bool DestroyRequiresHalt() { return true; }
1420 //------------------------------------------------------------------
1421 /// Called after sending a signal to a process.
1423 /// Allow Process plug-ins to execute some code after sending a signal to a
1425 //------------------------------------------------------------------
1426 virtual void DidSignal() {}
1428 //------------------------------------------------------------------
1429 /// Currently called as part of ShouldStop.
1430 /// FIXME: Should really happen when the target stops before the
1431 /// event is taken from the queue...
1433 /// This callback is called as the event
1434 /// is about to be queued up to allow Process plug-ins to execute some code
1435 /// prior to clients being notified that a process was stopped. Common
1436 /// operations include updating the thread list, invalidating any thread
1437 /// state (registers, stack, etc) prior to letting the notification go out.
1439 //------------------------------------------------------------------
1440 virtual void RefreshStateAfterStop() = 0;
1442 //------------------------------------------------------------------
1443 /// Sometimes the connection to a process can detect the host OS version
1444 /// that the process is running on. The current platform should be checked
1445 /// first in case the platform is connected, but clients can fall back onto
1446 /// this function if the platform fails to identify the host OS version. The
1447 /// platform should be checked first in case you are running a simulator
1448 /// platform that might itself be running natively, but have different
1449 /// heuristics for figuring out which OS is is emulating.
1452 /// Returns the version tuple of the host OS. In case of failure an empty
1453 /// VersionTuple is returner.
1454 //------------------------------------------------------------------
1455 virtual llvm::VersionTuple GetHostOSVersion() { return llvm::VersionTuple(); }
1457 //------------------------------------------------------------------
1458 /// Get the target object pointer for this module.
1461 /// A Target object pointer to the target that owns this
1463 //------------------------------------------------------------------
1464 Target &GetTarget() { return *m_target_wp.lock(); }
1466 //------------------------------------------------------------------
1467 /// Get the const target object pointer for this module.
1470 /// A const Target object pointer to the target that owns this
1472 //------------------------------------------------------------------
1473 const Target &GetTarget() const { return *m_target_wp.lock(); }
1475 //------------------------------------------------------------------
1476 /// Flush all data in the process.
1478 /// Flush the memory caches, all threads, and any other cached data in the
1481 /// This function can be called after a world changing event like adding a
1482 /// new symbol file, or after the process makes a large context switch (from
1483 /// boot ROM to booted into an OS).
1484 //------------------------------------------------------------------
1487 //------------------------------------------------------------------
1488 /// Get accessor for the current process state.
1491 /// The current state of the process.
1493 /// @see lldb::StateType
1494 //------------------------------------------------------------------
1495 lldb::StateType GetState();
1497 lldb::ExpressionResults
1498 RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp,
1499 const EvaluateExpressionOptions &options,
1500 DiagnosticManager &diagnostic_manager);
1502 static const char *ExecutionResultAsCString(lldb::ExpressionResults result);
1504 void GetStatus(Stream &ostrm);
1506 size_t GetThreadStatus(Stream &ostrm, bool only_threads_with_stop_reason,
1507 uint32_t start_frame, uint32_t num_frames,
1508 uint32_t num_frames_with_source,
1511 void SendAsyncInterrupt();
1513 //------------------------------------------------------------------
1514 // Notify this process class that modules got loaded.
1516 // If subclasses override this method, they must call this version before
1517 // doing anything in the subclass version of the function.
1518 //------------------------------------------------------------------
1519 virtual void ModulesDidLoad(ModuleList &module_list);
1521 //------------------------------------------------------------------
1522 /// Retrieve the list of shared libraries that are loaded for this process
1523 /// This method is used on pre-macOS 10.12, pre-iOS 10, pre-tvOS 10, pre-
1524 /// watchOS 3 systems. The following two methods are for newer versions of
1527 /// For certain platforms, the time it takes for the DynamicLoader plugin to
1528 /// read all of the shared libraries out of memory over a slow communication
1529 /// channel may be too long. In that instance, the gdb-remote stub may be
1530 /// able to retrieve the necessary information about the solibs out of
1531 /// memory and return a concise summary sufficient for the DynamicLoader
1534 /// @param [in] image_list_address
1535 /// The address where the table of shared libraries is stored in memory,
1536 /// if that is appropriate for this platform. Else this may be
1537 /// passed as LLDB_INVALID_ADDRESS.
1539 /// @param [in] image_count
1540 /// The number of shared libraries that are present in this process, if
1541 /// that is appropriate for this platofrm Else this may be passed as
1542 /// LLDB_INVALID_ADDRESS.
1545 /// A StructureDataSP object which, if non-empty, will contain the
1546 /// information the DynamicLoader needs to get the initial scan of
1547 /// solibs resolved.
1548 //------------------------------------------------------------------
1549 virtual lldb_private::StructuredData::ObjectSP
1550 GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address,
1551 lldb::addr_t image_count) {
1552 return StructuredData::ObjectSP();
1555 // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1556 // return the full list of loaded shared libraries without needing any input.
1557 virtual lldb_private::StructuredData::ObjectSP
1558 GetLoadedDynamicLibrariesInfos() {
1559 return StructuredData::ObjectSP();
1562 // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1563 // return information about binaries given their load addresses.
1564 virtual lldb_private::StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos(
1565 const std::vector<lldb::addr_t> &load_addresses) {
1566 return StructuredData::ObjectSP();
1569 //------------------------------------------------------------------
1570 // Get information about the library shared cache, if that exists
1572 // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1573 // return information about the library shared cache (a set of standard
1574 // libraries that are loaded at the same location for all processes on a
1576 //------------------------------------------------------------------
1577 virtual lldb_private::StructuredData::ObjectSP GetSharedCacheInfo() {
1578 return StructuredData::ObjectSP();
1581 //------------------------------------------------------------------
1582 /// Print a user-visible warning about a module being built with
1585 /// Prints a async warning message to the user one time per Module where a
1586 /// function is found that was compiled with optimization, per Process.
1589 /// A SymbolContext with eSymbolContextFunction and eSymbolContextModule
1591 //------------------------------------------------------------------
1592 void PrintWarningOptimization(const SymbolContext &sc);
1594 virtual bool GetProcessInfo(ProcessInstanceInfo &info);
1597 //------------------------------------------------------------------
1598 /// Get the exit status for a process.
1601 /// The process's return code, or -1 if the current process
1602 /// state is not eStateExited.
1603 //------------------------------------------------------------------
1604 int GetExitStatus();
1606 //------------------------------------------------------------------
1607 /// Get a textual description of what the process exited.
1610 /// The textual description of why the process exited, or nullptr
1611 /// if there is no description available.
1612 //------------------------------------------------------------------
1613 const char *GetExitDescription();
1615 virtual void DidExit() {}
1617 //------------------------------------------------------------------
1618 /// Get the Modification ID of the process.
1621 /// The modification ID of the process.
1622 //------------------------------------------------------------------
1623 ProcessModID GetModID() const { return m_mod_id; }
1625 const ProcessModID &GetModIDRef() const { return m_mod_id; }
1627 uint32_t GetStopID() const { return m_mod_id.GetStopID(); }
1629 uint32_t GetResumeID() const { return m_mod_id.GetResumeID(); }
1631 uint32_t GetLastUserExpressionResumeID() const {
1632 return m_mod_id.GetLastUserExpressionResumeID();
1635 uint32_t GetLastNaturalStopID() const {
1636 return m_mod_id.GetLastNaturalStopID();
1639 lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const {
1640 return m_mod_id.GetStopEventForStopID(stop_id);
1643 //------------------------------------------------------------------
1644 /// Set accessor for the process exit status (return code).
1646 /// Sometimes a child exits and the exit can be detected by global functions
1647 /// (signal handler for SIGCHLD for example). This accessor allows the exit
1648 /// status to be set from an external source.
1650 /// Setting this will cause a eStateExited event to be posted to the process
1653 /// @param[in] exit_status
1654 /// The value for the process's return code.
1656 /// @see lldb::StateType
1657 //------------------------------------------------------------------
1658 virtual bool SetExitStatus(int exit_status, const char *cstr);
1660 //------------------------------------------------------------------
1661 /// Check if a process is still alive.
1664 /// Returns \b true if the process is still valid, \b false
1666 //------------------------------------------------------------------
1667 virtual bool IsAlive();
1669 //------------------------------------------------------------------
1670 /// Before lldb detaches from a process, it warns the user that they are
1671 /// about to lose their debug session. In some cases, this warning doesn't
1672 /// need to be emitted -- for instance, with core file debugging where the
1673 /// user can reconstruct the "state" by simply re-running the debugger on
1677 // true if the user should be warned about detaching from this process.
1678 //------------------------------------------------------------------
1679 virtual bool WarnBeforeDetach() const { return true; }
1681 //------------------------------------------------------------------
1682 /// Actually do the reading of memory from a process.
1684 /// Subclasses must override this function and can return fewer bytes than
1685 /// requested when memory requests are too large. This class will break up
1686 /// the memory requests and keep advancing the arguments along as needed.
1688 /// @param[in] vm_addr
1689 /// A virtual load address that indicates where to start reading
1693 /// The number of bytes to read.
1696 /// A byte buffer that is at least \a size bytes long that
1697 /// will receive the memory bytes.
1699 /// @param[out] error
1700 /// An error that indicates the success or failure of this
1701 /// operation. If error indicates success (error.Success()),
1702 /// then the value returned can be trusted, otherwise zero
1703 /// will be returned.
1706 /// The number of bytes that were actually read into \a buf.
1707 /// Zero is returned in the case of an error.
1708 //------------------------------------------------------------------
1709 virtual size_t DoReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1712 //------------------------------------------------------------------
1713 /// Read of memory from a process.
1715 /// This function will read memory from the current process's address space
1716 /// and remove any traps that may have been inserted into the memory.
1718 /// This function is not meant to be overridden by Process subclasses, the
1719 /// subclasses should implement Process::DoReadMemory (lldb::addr_t, size_t,
1722 /// @param[in] vm_addr
1723 /// A virtual load address that indicates where to start reading
1727 /// A byte buffer that is at least \a size bytes long that
1728 /// will receive the memory bytes.
1731 /// The number of bytes to read.
1733 /// @param[out] error
1734 /// An error that indicates the success or failure of this
1735 /// operation. If error indicates success (error.Success()),
1736 /// then the value returned can be trusted, otherwise zero
1737 /// will be returned.
1740 /// The number of bytes that were actually read into \a buf. If
1741 /// the returned number is greater than zero, yet less than \a
1742 /// size, then this function will get called again with \a
1743 /// vm_addr, \a buf, and \a size updated appropriately. Zero is
1744 /// returned in the case of an error.
1745 //------------------------------------------------------------------
1746 virtual size_t ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1749 //------------------------------------------------------------------
1750 /// Read a NULL terminated string from memory
1752 /// This function will read a cache page at a time until a NULL string
1753 /// terminator is found. It will stop reading if an aligned sequence of NULL
1754 /// termination \a type_width bytes is not found before reading \a
1755 /// cstr_max_len bytes. The results are always guaranteed to be NULL
1756 /// terminated, and that no more than (max_bytes - type_width) bytes will be
1759 /// @param[in] vm_addr
1760 /// The virtual load address to start the memory read.
1763 /// A character buffer containing at least max_bytes.
1765 /// @param[in] max_bytes
1766 /// The maximum number of bytes to read.
1768 /// @param[in] error
1769 /// The error status of the read operation.
1771 /// @param[in] type_width
1772 /// The size of the null terminator (1 to 4 bytes per
1773 /// character). Defaults to 1.
1776 /// The error status or the number of bytes prior to the null terminator.
1777 //------------------------------------------------------------------
1778 size_t ReadStringFromMemory(lldb::addr_t vm_addr, char *str, size_t max_bytes,
1779 Status &error, size_t type_width = 1);
1781 //------------------------------------------------------------------
1782 /// Read a NULL terminated C string from memory
1784 /// This function will read a cache page at a time until the NULL
1785 /// C string terminator is found. It will stop reading if the NULL
1786 /// termination byte isn't found before reading \a cstr_max_len bytes, and
1787 /// the results are always guaranteed to be NULL terminated (at most
1788 /// cstr_max_len - 1 bytes will be read).
1789 //------------------------------------------------------------------
1790 size_t ReadCStringFromMemory(lldb::addr_t vm_addr, char *cstr,
1791 size_t cstr_max_len, Status &error);
1793 size_t ReadCStringFromMemory(lldb::addr_t vm_addr, std::string &out_str,
1796 size_t ReadMemoryFromInferior(lldb::addr_t vm_addr, void *buf, size_t size,
1799 //------------------------------------------------------------------
1800 /// Reads an unsigned integer of the specified byte size from process
1803 /// @param[in] load_addr
1804 /// A load address of the integer to read.
1806 /// @param[in] byte_size
1807 /// The size in byte of the integer to read.
1809 /// @param[in] fail_value
1810 /// The value to return if we fail to read an integer.
1812 /// @param[out] error
1813 /// An error that indicates the success or failure of this
1814 /// operation. If error indicates success (error.Success()),
1815 /// then the value returned can be trusted, otherwise zero
1816 /// will be returned.
1819 /// The unsigned integer that was read from the process memory
1820 /// space. If the integer was smaller than a uint64_t, any
1821 /// unused upper bytes will be zero filled. If the process
1822 /// byte order differs from the host byte order, the integer
1823 /// value will be appropriately byte swapped into host byte
1825 //------------------------------------------------------------------
1826 uint64_t ReadUnsignedIntegerFromMemory(lldb::addr_t load_addr,
1827 size_t byte_size, uint64_t fail_value,
1830 int64_t ReadSignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size,
1831 int64_t fail_value, Status &error);
1833 lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error);
1835 bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
1838 //------------------------------------------------------------------
1839 /// Actually do the writing of memory to a process.
1841 /// @param[in] vm_addr
1842 /// A virtual load address that indicates where to start writing
1846 /// A byte buffer that is at least \a size bytes long that
1847 /// contains the data to write.
1850 /// The number of bytes to write.
1852 /// @param[out] error
1853 /// An error value in case the memory write fails.
1856 /// The number of bytes that were actually written.
1857 //------------------------------------------------------------------
1858 virtual size_t DoWriteMemory(lldb::addr_t vm_addr, const void *buf,
1859 size_t size, Status &error) {
1860 error.SetErrorStringWithFormat(
1861 "error: %s does not support writing to processes",
1862 GetPluginName().GetCString());
1866 //------------------------------------------------------------------
1867 /// Write all or part of a scalar value to memory.
1869 /// The value contained in \a scalar will be swapped to match the byte order
1870 /// of the process that is being debugged. If \a size is less than the size
1871 /// of scalar, the least significant \a size bytes from scalar will be
1872 /// written. If \a size is larger than the byte size of scalar, then the
1873 /// extra space will be padded with zeros and the scalar value will be
1874 /// placed in the least significant bytes in memory.
1876 /// @param[in] vm_addr
1877 /// A virtual load address that indicates where to start writing
1880 /// @param[in] scalar
1881 /// The scalar to write to the debugged process.
1884 /// This value can be smaller or larger than the scalar value
1885 /// itself. If \a size is smaller than the size of \a scalar,
1886 /// the least significant bytes in \a scalar will be used. If
1887 /// \a size is larger than the byte size of \a scalar, then
1888 /// the extra space will be padded with zeros. If \a size is
1889 /// set to UINT32_MAX, then the size of \a scalar will be used.
1891 /// @param[out] error
1892 /// An error value in case the memory write fails.
1895 /// The number of bytes that were actually written.
1896 //------------------------------------------------------------------
1897 size_t WriteScalarToMemory(lldb::addr_t vm_addr, const Scalar &scalar,
1898 size_t size, Status &error);
1900 size_t ReadScalarIntegerFromMemory(lldb::addr_t addr, uint32_t byte_size,
1901 bool is_signed, Scalar &scalar,
1904 //------------------------------------------------------------------
1905 /// Write memory to a process.
1907 /// This function will write memory to the current process's address space
1908 /// and maintain any traps that might be present due to software
1911 /// This function is not meant to be overridden by Process subclasses, the
1912 /// subclasses should implement Process::DoWriteMemory (lldb::addr_t,
1913 /// size_t, void *).
1915 /// @param[in] vm_addr
1916 /// A virtual load address that indicates where to start writing
1920 /// A byte buffer that is at least \a size bytes long that
1921 /// contains the data to write.
1924 /// The number of bytes to write.
1927 /// The number of bytes that were actually written.
1928 //------------------------------------------------------------------
1929 // TODO: change this to take an ArrayRef<uint8_t>
1930 size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1933 //------------------------------------------------------------------
1934 /// Actually allocate memory in the process.
1936 /// This function will allocate memory in the process's address space. This
1937 /// can't rely on the generic function calling mechanism, since that
1938 /// requires this function.
1941 /// The size of the allocation requested.
1944 /// The address of the allocated buffer in the process, or
1945 /// LLDB_INVALID_ADDRESS if the allocation failed.
1946 //------------------------------------------------------------------
1948 virtual lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions,
1950 error.SetErrorStringWithFormat(
1951 "error: %s does not support allocating in the debug process",
1952 GetPluginName().GetCString());
1953 return LLDB_INVALID_ADDRESS;
1956 virtual Status WriteObjectFile(std::vector<ObjectFile::LoadableData> entries);
1958 //------------------------------------------------------------------
1959 /// The public interface to allocating memory in the process.
1961 /// This function will allocate memory in the process's address space. This
1962 /// can't rely on the generic function calling mechanism, since that
1963 /// requires this function.
1966 /// The size of the allocation requested.
1968 /// @param[in] permissions
1969 /// Or together any of the lldb::Permissions bits. The permissions on
1970 /// a given memory allocation can't be changed after allocation. Note
1971 /// that a block that isn't set writable can still be written on from
1973 /// just not by the process itself.
1975 /// @param[in,out] error
1976 /// An error object to fill in if things go wrong.
1978 /// The address of the allocated buffer in the process, or
1979 /// LLDB_INVALID_ADDRESS if the allocation failed.
1980 //------------------------------------------------------------------
1981 lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error);
1983 //------------------------------------------------------------------
1984 /// The public interface to allocating memory in the process, this also
1985 /// clears the allocated memory.
1987 /// This function will allocate memory in the process's address space. This
1988 /// can't rely on the generic function calling mechanism, since that
1989 /// requires this function.
1992 /// The size of the allocation requested.
1994 /// @param[in] permissions
1995 /// Or together any of the lldb::Permissions bits. The permissions on
1996 /// a given memory allocation can't be changed after allocation. Note
1997 /// that a block that isn't set writable can still be written on from
1999 /// just not by the process itself.
2001 /// @param[in/out] error
2002 /// An error object to fill in if things go wrong.
2004 /// The address of the allocated buffer in the process, or
2005 /// LLDB_INVALID_ADDRESS if the allocation failed.
2006 //------------------------------------------------------------------
2008 lldb::addr_t CallocateMemory(size_t size, uint32_t permissions,
2011 //------------------------------------------------------------------
2012 /// Resolve dynamically loaded indirect functions.
2014 /// @param[in] address
2015 /// The load address of the indirect function to resolve.
2017 /// @param[out] error
2018 /// An error value in case the resolve fails.
2021 /// The address of the resolved function.
2022 /// LLDB_INVALID_ADDRESS if the resolution failed.
2023 //------------------------------------------------------------------
2024 virtual lldb::addr_t ResolveIndirectFunction(const Address *address,
2027 //------------------------------------------------------------------
2028 /// Locate the memory region that contains load_addr.
2030 /// If load_addr is within the address space the process has mapped
2031 /// range_info will be filled in with the start and end of that range as
2032 /// well as the permissions for that range and range_info.GetMapped will
2035 /// If load_addr is outside any mapped region then range_info will have its
2036 /// start address set to load_addr and the end of the range will indicate
2037 /// the start of the next mapped range or be set to LLDB_INVALID_ADDRESS if
2038 /// there are no valid mapped ranges between load_addr and the end of the
2039 /// process address space.
2041 /// GetMemoryRegionInfo will only return an error if it is unimplemented for
2042 /// the current process.
2044 /// @param[in] load_addr
2045 /// The load address to query the range_info for.
2047 /// @param[out] range_info
2048 /// An range_info value containing the details of the range.
2052 //------------------------------------------------------------------
2053 virtual Status GetMemoryRegionInfo(lldb::addr_t load_addr,
2054 MemoryRegionInfo &range_info) {
2056 error.SetErrorString("Process::GetMemoryRegionInfo() not supported");
2060 //------------------------------------------------------------------
2061 /// Obtain all the mapped memory regions within this process.
2063 /// @param[out] region_list
2064 /// A vector to contain MemoryRegionInfo objects for all mapped
2069 //------------------------------------------------------------------
2071 GetMemoryRegions(std::vector<lldb::MemoryRegionInfoSP> ®ion_list);
2073 virtual Status GetWatchpointSupportInfo(uint32_t &num) {
2076 error.SetErrorString("Process::GetWatchpointSupportInfo() not supported");
2080 virtual Status GetWatchpointSupportInfo(uint32_t &num, bool &after) {
2084 error.SetErrorString("Process::GetWatchpointSupportInfo() not supported");
2088 lldb::ModuleSP ReadModuleFromMemory(const FileSpec &file_spec,
2089 lldb::addr_t header_addr,
2090 size_t size_to_read = 512);
2092 //------------------------------------------------------------------
2093 /// Attempt to get the attributes for a region of memory in the process.
2095 /// It may be possible for the remote debug server to inspect attributes for
2096 /// a region of memory in the process, such as whether there is a valid page
2097 /// of memory at a given address or whether that page is
2098 /// readable/writable/executable by the process.
2100 /// @param[in] load_addr
2101 /// The address of interest in the process.
2103 /// @param[out] permissions
2104 /// If this call returns successfully, this bitmask will have
2105 /// its Permissions bits set to indicate whether the region is
2106 /// readable/writable/executable. If this call fails, the
2107 /// bitmask values are undefined.
2110 /// Returns true if it was able to determine the attributes of the
2111 /// memory region. False if not.
2112 //------------------------------------------------------------------
2113 virtual bool GetLoadAddressPermissions(lldb::addr_t load_addr,
2114 uint32_t &permissions);
2116 //------------------------------------------------------------------
2117 /// Determines whether executing JIT-compiled code in this process is
2121 /// True if execution of JIT code is possible; false otherwise.
2122 //------------------------------------------------------------------
2125 //------------------------------------------------------------------
2126 /// Sets whether executing JIT-compiled code in this process is possible.
2128 /// @param[in] can_jit
2129 /// True if execution of JIT code is possible; false otherwise.
2130 //------------------------------------------------------------------
2131 void SetCanJIT(bool can_jit);
2133 //------------------------------------------------------------------
2134 /// Determines whether executing function calls using the interpreter is
2135 /// possible for this process.
2138 /// True if possible; false otherwise.
2139 //------------------------------------------------------------------
2140 bool CanInterpretFunctionCalls() { return m_can_interpret_function_calls; }
2142 //------------------------------------------------------------------
2143 /// Sets whether executing function calls using the interpreter is possible
2144 /// for this process.
2146 /// @param[in] can_interpret_function_calls
2147 /// True if possible; false otherwise.
2148 //------------------------------------------------------------------
2149 void SetCanInterpretFunctionCalls(bool can_interpret_function_calls) {
2150 m_can_interpret_function_calls = can_interpret_function_calls;
2153 //------------------------------------------------------------------
2154 /// Sets whether executing code in this process is possible. This could be
2155 /// either through JIT or interpreting.
2157 /// @param[in] can_run_code
2158 /// True if execution of code is possible; false otherwise.
2159 //------------------------------------------------------------------
2160 void SetCanRunCode(bool can_run_code);
2162 //------------------------------------------------------------------
2163 /// Actually deallocate memory in the process.
2165 /// This function will deallocate memory in the process's address space that
2166 /// was allocated with AllocateMemory.
2169 /// A return value from AllocateMemory, pointing to the memory you
2170 /// want to deallocate.
2173 /// \btrue if the memory was deallocated, \bfalse otherwise.
2174 //------------------------------------------------------------------
2175 virtual Status DoDeallocateMemory(lldb::addr_t ptr) {
2177 error.SetErrorStringWithFormat(
2178 "error: %s does not support deallocating in the debug process",
2179 GetPluginName().GetCString());
2183 //------------------------------------------------------------------
2184 /// The public interface to deallocating memory in the process.
2186 /// This function will deallocate memory in the process's address space that
2187 /// was allocated with AllocateMemory.
2190 /// A return value from AllocateMemory, pointing to the memory you
2191 /// want to deallocate.
2194 /// \btrue if the memory was deallocated, \bfalse otherwise.
2195 //------------------------------------------------------------------
2196 Status DeallocateMemory(lldb::addr_t ptr);
2198 //------------------------------------------------------------------
2199 /// Get any available STDOUT.
2201 /// Calling this method is a valid operation only if all of the following
2202 /// conditions are true: 1) The process was launched, and not attached to.
2203 /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 3) The
2204 /// process was launched without supplying a valid file path
2207 /// Note that the implementation will probably need to start a read thread
2208 /// in the background to make sure that the pipe is drained and the STDOUT
2209 /// buffered appropriately, to prevent the process from deadlocking trying
2210 /// to write to a full buffer.
2212 /// Events will be queued indicating that there is STDOUT available that can
2213 /// be retrieved using this function.
2216 /// A buffer that will receive any STDOUT bytes that are
2217 /// currently available.
2219 /// @param[in] buf_size
2220 /// The size in bytes for the buffer \a buf.
2223 /// The number of bytes written into \a buf. If this value is
2224 /// equal to \a buf_size, another call to this function should
2225 /// be made to retrieve more STDOUT data.
2226 //------------------------------------------------------------------
2227 virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error);
2229 //------------------------------------------------------------------
2230 /// Get any available STDERR.
2232 /// Calling this method is a valid operation only if all of the following
2233 /// conditions are true: 1) The process was launched, and not attached to.
2234 /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 3) The
2235 /// process was launched without supplying a valid file path
2238 /// Note that the implementation will probably need to start a read thread
2239 /// in the background to make sure that the pipe is drained and the STDERR
2240 /// buffered appropriately, to prevent the process from deadlocking trying
2241 /// to write to a full buffer.
2243 /// Events will be queued indicating that there is STDERR available that can
2244 /// be retrieved using this function.
2247 /// A buffer that will receive any STDERR bytes that are
2248 /// currently available.
2250 /// @param[out] buf_size
2251 /// The size in bytes for the buffer \a buf.
2254 /// The number of bytes written into \a buf. If this value is
2255 /// equal to \a buf_size, another call to this function should
2256 /// be made to retrieve more STDERR data.
2257 //------------------------------------------------------------------
2258 virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error);
2260 //------------------------------------------------------------------
2261 /// Puts data into this process's STDIN.
2263 /// Calling this method is a valid operation only if all of the following
2264 /// conditions are true: 1) The process was launched, and not attached to.
2265 /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 3) The
2266 /// process was launched without supplying a valid file path
2270 /// A buffer that contains the data to write to the process's STDIN.
2272 /// @param[in] buf_size
2273 /// The size in bytes for the buffer \a buf.
2276 /// The number of bytes written into \a buf. If this value is
2277 /// less than \a buf_size, another call to this function should
2278 /// be made to write the rest of the data.
2279 //------------------------------------------------------------------
2280 virtual size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) {
2281 error.SetErrorString("stdin unsupported");
2285 //------------------------------------------------------------------
2286 /// Get any available profile data.
2289 /// A buffer that will receive any profile data bytes that are
2290 /// currently available.
2292 /// @param[out] buf_size
2293 /// The size in bytes for the buffer \a buf.
2296 /// The number of bytes written into \a buf. If this value is
2297 /// equal to \a buf_size, another call to this function should
2298 /// be made to retrieve more profile data.
2299 //------------------------------------------------------------------
2300 virtual size_t GetAsyncProfileData(char *buf, size_t buf_size, Status &error);
2302 //----------------------------------------------------------------------
2303 // Process Breakpoints
2304 //----------------------------------------------------------------------
2305 size_t GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site);
2307 virtual Status EnableBreakpointSite(BreakpointSite *bp_site) {
2309 error.SetErrorStringWithFormat(
2310 "error: %s does not support enabling breakpoints",
2311 GetPluginName().GetCString());
2315 virtual Status DisableBreakpointSite(BreakpointSite *bp_site) {
2317 error.SetErrorStringWithFormat(
2318 "error: %s does not support disabling breakpoints",
2319 GetPluginName().GetCString());
2323 // This is implemented completely using the lldb::Process API. Subclasses
2324 // don't need to implement this function unless the standard flow of read
2325 // existing opcode, write breakpoint opcode, verify breakpoint opcode doesn't
2326 // work for a specific process plug-in.
2327 virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site);
2329 // This is implemented completely using the lldb::Process API. Subclasses
2330 // don't need to implement this function unless the standard flow of
2331 // restoring original opcode in memory and verifying the restored opcode
2332 // doesn't work for a specific process plug-in.
2333 virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site);
2335 BreakpointSiteList &GetBreakpointSiteList();
2337 const BreakpointSiteList &GetBreakpointSiteList() const;
2339 void DisableAllBreakpointSites();
2341 Status ClearBreakpointSiteByID(lldb::user_id_t break_id);
2343 lldb::break_id_t CreateBreakpointSite(const lldb::BreakpointLocationSP &owner,
2346 Status DisableBreakpointSiteByID(lldb::user_id_t break_id);
2348 Status EnableBreakpointSiteByID(lldb::user_id_t break_id);
2350 // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove themselves
2351 // from the owner's list of this breakpoint sites.
2352 void RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
2353 lldb::user_id_t owner_loc_id,
2354 lldb::BreakpointSiteSP &bp_site_sp);
2356 //----------------------------------------------------------------------
2357 // Process Watchpoints (optional)
2358 //----------------------------------------------------------------------
2359 virtual Status EnableWatchpoint(Watchpoint *wp, bool notify = true);
2361 virtual Status DisableWatchpoint(Watchpoint *wp, bool notify = true);
2363 //------------------------------------------------------------------
2365 //------------------------------------------------------------------
2366 virtual bool UpdateThreadList(ThreadList &old_thread_list,
2367 ThreadList &new_thread_list) = 0;
2369 void UpdateThreadListIfNeeded();
2371 ThreadList &GetThreadList() { return m_thread_list; }
2373 // When ExtendedBacktraces are requested, the HistoryThreads that are created
2374 // need an owner -- they're saved here in the Process. The threads in this
2375 // list are not iterated over - driver programs need to request the extended
2376 // backtrace calls starting from a root concrete thread one by one.
2377 ThreadList &GetExtendedThreadList() { return m_extended_thread_list; }
2379 ThreadList::ThreadIterable Threads() { return m_thread_list.Threads(); }
2381 uint32_t GetNextThreadIndexID(uint64_t thread_id);
2383 lldb::ThreadSP CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context);
2385 // Returns true if an index id has been assigned to a thread.
2386 bool HasAssignedIndexIDToThread(uint64_t sb_thread_id);
2388 // Given a thread_id, it will assign a more reasonable index id for display
2389 // to the user. If the thread_id has previously been assigned, the same index
2391 uint32_t AssignIndexIDToThread(uint64_t thread_id);
2393 //------------------------------------------------------------------
2395 //------------------------------------------------------------------
2397 void UpdateQueueListIfNeeded();
2399 QueueList &GetQueueList() {
2400 UpdateQueueListIfNeeded();
2401 return m_queue_list;
2404 QueueList::QueueIterable Queues() {
2405 UpdateQueueListIfNeeded();
2406 return m_queue_list.Queues();
2409 //------------------------------------------------------------------
2411 //------------------------------------------------------------------
2412 lldb::StateType GetNextEvent(lldb::EventSP &event_sp);
2414 // Returns the process state when it is stopped. If specified, event_sp_ptr
2415 // is set to the event which triggered the stop. If wait_always = false, and
2416 // the process is already stopped, this function returns immediately. If the
2417 // process is hijacked and use_run_lock is true (the default), then this
2418 // function releases the run lock after the stop. Setting use_run_lock to
2419 // false will avoid this behavior.
2421 WaitForProcessToStop(const Timeout<std::micro> &timeout,
2422 lldb::EventSP *event_sp_ptr = nullptr,
2423 bool wait_always = true,
2424 lldb::ListenerSP hijack_listener = lldb::ListenerSP(),
2425 Stream *stream = nullptr, bool use_run_lock = true);
2427 uint32_t GetIOHandlerID() const { return m_iohandler_sync.GetValue(); }
2429 //--------------------------------------------------------------------------------------
2430 /// Waits for the process state to be running within a given msec timeout.
2432 /// The main purpose of this is to implement an interlock waiting for
2433 /// HandlePrivateEvent to push an IOHandler.
2435 /// @param[in] timeout
2436 /// The maximum time length to wait for the process to transition to the
2437 /// eStateRunning state.
2438 //--------------------------------------------------------------------------------------
2439 void SyncIOHandler(uint32_t iohandler_id, const Timeout<std::micro> &timeout);
2441 lldb::StateType GetStateChangedEvents(
2442 lldb::EventSP &event_sp, const Timeout<std::micro> &timeout,
2444 hijack_listener); // Pass an empty ListenerSP to use builtin listener
2446 //--------------------------------------------------------------------------------------
2447 /// Centralize the code that handles and prints descriptions for process
2450 /// @param[in] event_sp
2451 /// The process state changed event
2453 /// @param[in] stream
2454 /// The output stream to get the state change description
2456 /// @param[in,out] pop_process_io_handler
2457 /// If this value comes in set to \b true, then pop the Process IOHandler
2459 /// Else this variable will be set to \b true or \b false to indicate if
2461 /// needs to have its process IOHandler popped.
2464 /// \b true if the event describes a process state changed event, \b false
2466 //--------------------------------------------------------------------------------------
2467 static bool HandleProcessStateChangedEvent(const lldb::EventSP &event_sp,
2469 bool &pop_process_io_handler);
2471 Event *PeekAtStateChangedEvents();
2473 class ProcessEventHijacker {
2475 ProcessEventHijacker(Process &process, lldb::ListenerSP listener_sp)
2476 : m_process(process) {
2477 m_process.HijackProcessEvents(listener_sp);
2480 ~ProcessEventHijacker() { m_process.RestoreProcessEvents(); }
2486 friend class ProcessEventHijacker;
2487 friend class ProcessProperties;
2488 //------------------------------------------------------------------
2489 /// If you need to ensure that you and only you will hear about some public
2490 /// event, then make a new listener, set to listen to process events, and
2491 /// then call this with that listener. Then you will have to wait on that
2492 /// listener explicitly for events (rather than using the GetNextEvent &
2493 /// WaitFor* calls above. Be sure to call RestoreProcessEvents when you are
2496 /// @param[in] listener
2497 /// This is the new listener to whom all process events will be delivered.
2500 /// Returns \b true if the new listener could be installed,
2501 /// \b false otherwise.
2502 //------------------------------------------------------------------
2503 bool HijackProcessEvents(lldb::ListenerSP listener_sp);
2505 //------------------------------------------------------------------
2506 /// Restores the process event broadcasting to its normal state.
2508 //------------------------------------------------------------------
2509 void RestoreProcessEvents();
2511 const lldb::ABISP &GetABI();
2513 OperatingSystem *GetOperatingSystem() { return m_os_ap.get(); }
2515 virtual LanguageRuntime *GetLanguageRuntime(lldb::LanguageType language,
2516 bool retry_if_null = true);
2518 virtual CPPLanguageRuntime *GetCPPLanguageRuntime(bool retry_if_null = true);
2520 virtual ObjCLanguageRuntime *
2521 GetObjCLanguageRuntime(bool retry_if_null = true);
2523 bool IsPossibleDynamicValue(ValueObject &in_value);
2525 bool IsRunning() const;
2527 DynamicCheckerFunctions *GetDynamicCheckers() {
2528 return m_dynamic_checkers_ap.get();
2531 void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers);
2533 //------------------------------------------------------------------
2534 /// Call this to set the lldb in the mode where it breaks on new thread
2535 /// creations, and then auto-restarts. This is useful when you are trying
2536 /// to run only one thread, but either that thread or the kernel is creating
2537 /// new threads in the process. If you stop when the thread is created, you
2538 /// can immediately suspend it, and keep executing only the one thread you
2542 /// Returns \b true if we were able to start up the notification
2543 /// \b false otherwise.
2544 //------------------------------------------------------------------
2545 virtual bool StartNoticingNewThreads() { return true; }
2547 //------------------------------------------------------------------
2548 /// Call this to turn off the stop & notice new threads mode.
2551 /// Returns \b true if we were able to start up the notification
2552 /// \b false otherwise.
2553 //------------------------------------------------------------------
2554 virtual bool StopNoticingNewThreads() { return true; }
2556 void SetRunningUserExpression(bool on);
2558 //------------------------------------------------------------------
2559 // lldb::ExecutionContextScope pure virtual functions
2560 //------------------------------------------------------------------
2561 lldb::TargetSP CalculateTarget() override;
2563 lldb::ProcessSP CalculateProcess() override { return shared_from_this(); }
2565 lldb::ThreadSP CalculateThread() override { return lldb::ThreadSP(); }
2567 lldb::StackFrameSP CalculateStackFrame() override {
2568 return lldb::StackFrameSP();
2571 void CalculateExecutionContext(ExecutionContext &exe_ctx) override;
2573 void SetSTDIOFileDescriptor(int file_descriptor);
2575 //------------------------------------------------------------------
2576 // Add a permanent region of memory that should never be read or written to.
2577 // This can be used to ensure that memory reads or writes to certain areas of
2578 // memory never end up being sent to the DoReadMemory or DoWriteMemory
2579 // functions which can improve performance.
2580 //------------------------------------------------------------------
2581 void AddInvalidMemoryRegion(const LoadRange ®ion);
2583 //------------------------------------------------------------------
2584 // Remove a permanent region of memory that should never be read or written
2585 // to that was previously added with AddInvalidMemoryRegion.
2586 //------------------------------------------------------------------
2587 bool RemoveInvalidMemoryRange(const LoadRange ®ion);
2589 //------------------------------------------------------------------
2590 // If the setup code of a thread plan needs to do work that might involve
2591 // calling a function in the target, it should not do that work directly in
2592 // one of the thread plan functions (DidPush/WillResume) because such work
2593 // needs to be handled carefully. Instead, put that work in a
2594 // PreResumeAction callback, and register it with the process. It will get
2595 // done before the actual "DoResume" gets called.
2596 //------------------------------------------------------------------
2598 typedef bool(PreResumeActionCallback)(void *);
2600 void AddPreResumeAction(PreResumeActionCallback callback, void *baton);
2602 bool RunPreResumeActions();
2604 void ClearPreResumeActions();
2606 void ClearPreResumeAction(PreResumeActionCallback callback, void *baton);
2608 ProcessRunLock &GetRunLock();
2610 virtual Status SendEventData(const char *data) {
2611 Status return_error("Sending an event is not supported for this process.");
2612 return return_error;
2615 lldb::ThreadCollectionSP GetHistoryThreads(lldb::addr_t addr);
2617 lldb::InstrumentationRuntimeSP
2618 GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type);
2620 //------------------------------------------------------------------
2621 /// Try to fetch the module specification for a module with the given file
2622 /// name and architecture. Process sub-classes have to override this method
2623 /// if they support platforms where the Platform object can't get the module
2624 /// spec for all module.
2626 /// @param[in] module_file_spec
2627 /// The file name of the module to get specification for.
2630 /// The architecture of the module to get specification for.
2632 /// @param[out] module_spec
2633 /// The fetched module specification if the return value is
2634 /// \b true, unchanged otherwise.
2637 /// Returns \b true if the module spec fetched successfully,
2638 /// \b false otherwise.
2639 //------------------------------------------------------------------
2640 virtual bool GetModuleSpec(const FileSpec &module_file_spec,
2641 const ArchSpec &arch, ModuleSpec &module_spec);
2643 virtual void PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs,
2644 const llvm::Triple &triple) {}
2646 //------------------------------------------------------------------
2647 /// Try to find the load address of a file.
2648 /// The load address is defined as the address of the first memory region
2649 /// what contains data mapped from the specified file.
2652 /// The name of the file whose load address we are looking for
2654 /// @param[out] is_loaded
2655 /// \b True if the file is loaded into the memory and false
2658 /// @param[out] load_addr
2659 /// The load address of the file if it is loaded into the
2660 /// processes address space, LLDB_INVALID_ADDRESS otherwise.
2661 //------------------------------------------------------------------
2662 virtual Status GetFileLoadAddress(const FileSpec &file, bool &is_loaded,
2663 lldb::addr_t &load_addr) {
2664 return Status("Not supported");
2667 size_t AddImageToken(lldb::addr_t image_ptr);
2669 lldb::addr_t GetImagePtrFromToken(size_t token) const;
2671 void ResetImageToken(size_t token);
2673 //------------------------------------------------------------------
2674 /// Find the next branch instruction to set a breakpoint on
2676 /// When instruction stepping through a source line, instead of stepping
2677 /// through each instruction, we can put a breakpoint on the next branch
2678 /// instruction (within the range of instructions we are stepping through)
2679 /// and continue the process to there, yielding significant performance
2680 /// benefits over instruction stepping.
2682 /// @param[in] default_stop_addr
2683 /// The address of the instruction where lldb would put a
2684 /// breakpoint normally.
2686 /// @param[in] range_bounds
2687 /// The range which the breakpoint must be contained within.
2688 /// Typically a source line.
2691 /// The address of the next branch instruction, or the end of
2692 /// the range provided in range_bounds. If there are any
2693 /// problems with the disassembly or getting the instructions,
2694 /// the original default_stop_addr will be returned.
2695 //------------------------------------------------------------------
2696 Address AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
2697 AddressRange range_bounds);
2699 //------------------------------------------------------------------
2700 /// Configure asynchronous structured data feature.
2702 /// Each Process type that supports using an asynchronous StructuredData
2703 /// feature should implement this to enable/disable/configure the feature.
2704 /// The default implementation here will always return an error indiciating
2705 /// the feature is unsupported.
2707 /// StructuredDataPlugin implementations will call this to configure a
2708 /// feature that has been reported as being supported.
2710 /// @param[in] type_name
2711 /// The StructuredData type name as previously discovered by
2712 /// the Process-derived instance.
2714 /// @param[in] config
2715 /// Configuration data for the feature being enabled. This config
2716 /// data, which may be null, will be passed along to the feature
2717 /// to process. The feature will dictate whether this is a dictionary,
2718 /// an array or some other object. If the feature needs to be
2719 /// set up properly before it can be enabled, then the config should
2720 /// also take an enable/disable flag.
2723 /// Returns the result of attempting to configure the feature.
2724 //------------------------------------------------------------------
2726 ConfigureStructuredData(const ConstString &type_name,
2727 const StructuredData::ObjectSP &config_sp);
2729 //------------------------------------------------------------------
2730 /// Broadcasts the given structured data object from the given plugin.
2732 /// StructuredDataPlugin instances can use this to optionally broadcast any
2733 /// of their data if they want to make it available for clients. The data
2734 /// will come in on the structured data event bit
2735 /// (eBroadcastBitStructuredData).
2737 /// @param[in] object_sp
2738 /// The structured data object to broadcast.
2740 /// @param[in] plugin_sp
2741 /// The plugin that will be reported in the event's plugin
2743 //------------------------------------------------------------------
2744 void BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
2745 const lldb::StructuredDataPluginSP &plugin_sp);
2747 //------------------------------------------------------------------
2748 /// Returns the StructuredDataPlugin associated with a given type name, if
2751 /// There will only be a plugin for a given StructuredDataType if the
2752 /// debugged process monitor claims that the feature is supported. This is
2753 /// one way to tell whether a feature is available.
2756 /// The plugin if one is available for the specified feature;
2757 /// otherwise, returns an empty shared pointer.
2758 //------------------------------------------------------------------
2759 lldb::StructuredDataPluginSP
2760 GetStructuredDataPlugin(const ConstString &type_name) const;
2762 //------------------------------------------------------------------
2763 /// Starts tracing with the configuration provided in options. To enable
2764 /// tracing on the complete process the thread_id in the options should be
2765 /// set to LLDB_INVALID_THREAD_ID. The API returns a user_id which is needed
2766 /// by other API's that manipulate the trace instance. The handling of
2767 /// erroneous or unsupported configuration is left to the trace technology
2768 /// implementations in the server, as they could be returned as an error, or
2769 /// rounded to a valid configuration to start tracing. In the later case the
2770 /// GetTraceConfig should supply the actual used trace configuration.
2771 //------------------------------------------------------------------
2772 virtual lldb::user_id_t StartTrace(const TraceOptions &options,
2774 error.SetErrorString("Not implemented");
2775 return LLDB_INVALID_UID;
2778 //------------------------------------------------------------------
2779 /// Stops the tracing instance leading to deletion of the trace data. The
2780 /// tracing instance is identified by the user_id which is obtained when
2781 /// tracing was started from the StartTrace. In case tracing of the complete
2782 /// process needs to be stopped the thread_id should be set to
2783 /// LLDB_INVALID_THREAD_ID. In the other case that tracing on an individual
2784 /// thread needs to be stopped a thread_id can be supplied.
2785 //------------------------------------------------------------------
2786 virtual Status StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) {
2787 return Status("Not implemented");
2790 //------------------------------------------------------------------
2791 /// Provides the trace data as raw bytes. A buffer needs to be supplied to
2792 /// copy the trace data. The exact behavior of this API may vary across
2793 /// trace technology, as some may support partial reading of the trace data
2794 /// from a specified offset while some may not. The thread_id should be used
2795 /// to select a particular thread for trace extraction.
2796 //------------------------------------------------------------------
2797 virtual Status GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
2798 llvm::MutableArrayRef<uint8_t> &buffer,
2799 size_t offset = 0) {
2800 return Status("Not implemented");
2803 //------------------------------------------------------------------
2804 /// Similar API as above except for obtaining meta data
2805 //------------------------------------------------------------------
2806 virtual Status GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
2807 llvm::MutableArrayRef<uint8_t> &buffer,
2808 size_t offset = 0) {
2809 return Status("Not implemented");
2812 //------------------------------------------------------------------
2813 /// API to obtain the trace configuration used by a trace instance.
2814 /// Configurations that may be specific to some trace technology should be
2815 /// stored in the custom parameters. The options are transported to the
2816 /// server, which shall interpret accordingly. The thread_id can be
2817 /// specified in the options to obtain the configuration used by a specific
2818 /// thread. The thread_id specified should also match the uid otherwise an
2819 /// error will be returned.
2820 //------------------------------------------------------------------
2821 virtual Status GetTraceConfig(lldb::user_id_t uid, TraceOptions &options) {
2822 return Status("Not implemented");
2826 void SetState(lldb::EventSP &event_sp);
2828 lldb::StateType GetPrivateState();
2830 //------------------------------------------------------------------
2831 /// The "private" side of resuming a process. This doesn't alter the state
2832 /// of m_run_lock, but just causes the process to resume.
2835 /// An Status object describing the success or failure of the resume.
2836 //------------------------------------------------------------------
2837 Status PrivateResume();
2839 //------------------------------------------------------------------
2840 // Called internally
2841 //------------------------------------------------------------------
2842 void CompleteAttach();
2844 //------------------------------------------------------------------
2845 /// Print a user-visible warning one time per Process
2847 /// A facility for printing a warning to the user once per repeat_key.
2849 /// warning_type is from the Process::Warnings enums. repeat_key is a
2850 /// pointer value that will be used to ensure that the warning message is
2851 /// not printed multiple times. For instance, with a warning about a
2852 /// function being optimized, you can pass the CompileUnit pointer to have
2853 /// the warning issued for only the first function in a CU, or the Function
2854 /// pointer to have it issued once for every function, or a Module pointer
2855 /// to have it issued once per Module.
2857 /// Classes outside Process should call a specific PrintWarning method so
2858 /// that the warning strings are all centralized in Process, instead of
2859 /// calling PrintWarning() directly.
2861 /// @param [in] warning_type
2862 /// One of the types defined in Process::Warnings.
2864 /// @param [in] repeat_key
2865 /// A pointer value used to ensure that the warning is only printed once.
2866 /// May be nullptr, indicating that the warning is printed unconditionally
2870 /// printf style format string
2871 //------------------------------------------------------------------
2872 void PrintWarning(uint64_t warning_type, const void *repeat_key,
2873 const char *fmt, ...) __attribute__((format(printf, 4, 5)));
2875 //------------------------------------------------------------------
2876 // NextEventAction provides a way to register an action on the next event
2877 // that is delivered to this process. There is currently only one next event
2878 // action allowed in the process at one time. If a new "NextEventAction" is
2879 // added while one is already present, the old action will be discarded (with
2880 // HandleBeingUnshipped called after it is discarded.)
2882 // If you want to resume the process as a result of a resume action, call
2883 // RequestResume, don't call Resume directly.
2884 //------------------------------------------------------------------
2885 class NextEventAction {
2887 typedef enum EventActionResult {
2888 eEventActionSuccess,
2891 } EventActionResult;
2893 NextEventAction(Process *process) : m_process(process) {}
2895 virtual ~NextEventAction() = default;
2897 virtual EventActionResult PerformAction(lldb::EventSP &event_sp) = 0;
2898 virtual void HandleBeingUnshipped() {}
2899 virtual EventActionResult HandleBeingInterrupted() = 0;
2900 virtual const char *GetExitString() = 0;
2901 void RequestResume() { m_process->m_resume_requested = true; }
2907 void SetNextEventAction(Process::NextEventAction *next_event_action) {
2908 if (m_next_event_action_ap.get())
2909 m_next_event_action_ap->HandleBeingUnshipped();
2911 m_next_event_action_ap.reset(next_event_action);
2914 // This is the completer for Attaching:
2915 class AttachCompletionHandler : public NextEventAction {
2917 AttachCompletionHandler(Process *process, uint32_t exec_count);
2919 ~AttachCompletionHandler() override = default;
2921 EventActionResult PerformAction(lldb::EventSP &event_sp) override;
2922 EventActionResult HandleBeingInterrupted() override;
2923 const char *GetExitString() override;
2926 uint32_t m_exec_count;
2927 std::string m_exit_string;
2930 bool PrivateStateThreadIsValid() const {
2931 lldb::StateType state = m_private_state.GetValue();
2932 return state != lldb::eStateInvalid && state != lldb::eStateDetached &&
2933 state != lldb::eStateExited && m_private_state_thread.IsJoinable();
2936 void ForceNextEventDelivery() { m_force_next_event_delivery = true; }
2938 //------------------------------------------------------------------
2939 /// Loads any plugins associated with asynchronous structured data and maps
2940 /// the relevant supported type name to the plugin.
2942 /// Processes can receive asynchronous structured data from the process
2943 /// monitor. This method will load and map any structured data plugins that
2944 /// support the given set of supported type names. Later, if any of these
2945 /// features are enabled, the process monitor is free to generate
2946 /// asynchronous structured data. The data must come in as a single \b
2947 /// StructuredData::Dictionary. That dictionary must have a string field
2948 /// named 'type', with a value that equals the relevant type name string
2949 /// (one of the values in \b supported_type_names).
2951 /// @param[in] supported_type_names
2952 /// An array of zero or more type names. Each must be unique.
2953 /// For each entry in the list, a StructuredDataPlugin will be
2954 /// searched for that supports the structured data type name.
2955 //------------------------------------------------------------------
2956 void MapSupportedStructuredDataPlugins(
2957 const StructuredData::Array &supported_type_names);
2959 //------------------------------------------------------------------
2960 /// Route the incoming structured data dictionary to the right plugin.
2962 /// The incoming structured data must be a dictionary, and it must have a
2963 /// key named 'type' that stores a string value. The string value must be
2964 /// the name of the structured data feature that knows how to handle it.
2966 /// @param[in] object_sp
2967 /// When non-null and pointing to a dictionary, the 'type'
2968 /// key's string value is used to look up the plugin that
2969 /// was registered for that structured data type. It then
2970 /// calls the following method on the StructuredDataPlugin
2974 /// HandleArrivalOfStructuredData(Process &process,
2975 /// const ConstString &type_name,
2976 /// const StructuredData::ObjectSP
2980 /// True if the structured data was routed to a plugin; otherwise,
2982 //------------------------------------------------------------------
2983 bool RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp);
2985 //------------------------------------------------------------------
2987 //------------------------------------------------------------------
2988 typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP>
2989 LanguageRuntimeCollection;
2990 typedef std::unordered_set<const void *> WarningsPointerSet;
2991 typedef std::map<uint64_t, WarningsPointerSet> WarningsCollection;
2993 struct PreResumeCallbackAndBaton {
2994 bool (*callback)(void *);
2996 PreResumeCallbackAndBaton(PreResumeActionCallback in_callback,
2998 : callback(in_callback), baton(in_baton) {}
2999 bool operator== (const PreResumeCallbackAndBaton &rhs) {
3000 return callback == rhs.callback && baton == rhs.baton;
3004 using StructuredDataPluginMap =
3005 std::map<ConstString, lldb::StructuredDataPluginSP>;
3007 //------------------------------------------------------------------
3009 //------------------------------------------------------------------
3010 std::weak_ptr<Target> m_target_wp; ///< The target that owns this process.
3011 ThreadSafeValue<lldb::StateType> m_public_state;
3012 ThreadSafeValue<lldb::StateType>
3013 m_private_state; // The actual state of our process
3014 Broadcaster m_private_state_broadcaster; // This broadcaster feeds state
3015 // changed events into the private
3016 // state thread's listener.
3017 Broadcaster m_private_state_control_broadcaster; // This is the control
3018 // broadcaster, used to
3019 // pause, resume & stop the
3020 // private state thread.
3021 lldb::ListenerSP m_private_state_listener_sp; // This is the listener for the
3022 // private state thread.
3023 HostThread m_private_state_thread; ///< Thread ID for the thread that watches
3024 ///internal state events
3025 ProcessModID m_mod_id; ///< Tracks the state of the process over stops and
3026 ///other alterations.
3027 uint32_t m_process_unique_id; ///< Each lldb_private::Process class that is
3028 ///created gets a unique integer ID that
3029 ///increments with each new instance
3030 uint32_t m_thread_index_id; ///< Each thread is created with a 1 based index
3031 ///that won't get re-used.
3032 std::map<uint64_t, uint32_t> m_thread_id_to_index_id_map;
3033 int m_exit_status; ///< The exit status of the process, or -1 if not set.
3034 std::string m_exit_string; ///< A textual description of why a process exited.
3035 std::mutex m_exit_status_mutex; ///< Mutex so m_exit_status m_exit_string can
3036 ///be safely accessed from multiple threads
3037 std::recursive_mutex m_thread_mutex;
3038 ThreadList m_thread_list_real; ///< The threads for this process as are known
3039 ///to the protocol we are debugging with
3040 ThreadList m_thread_list; ///< The threads for this process as the user will
3041 ///see them. This is usually the same as
3042 ///< m_thread_list_real, but might be different if there is an OS plug-in
3043 ///creating memory threads
3044 ThreadList m_extended_thread_list; ///< Owner for extended threads that may be
3045 ///generated, cleared on natural stops
3046 uint32_t m_extended_thread_stop_id; ///< The natural stop id when
3047 ///extended_thread_list was last updated
3049 m_queue_list; ///< The list of libdispatch queues at a given stop point
3050 uint32_t m_queue_list_stop_id; ///< The natural stop id when queue list was
3052 std::vector<Notifications> m_notifications; ///< The list of notifications
3053 ///that this process can deliver.
3054 std::vector<lldb::addr_t> m_image_tokens;
3055 lldb::ListenerSP m_listener_sp; ///< Shared pointer to the listener used for
3056 ///public events. Can not be empty.
3057 BreakpointSiteList m_breakpoint_site_list; ///< This is the list of breakpoint
3058 ///locations we intend to insert in
3060 lldb::DynamicLoaderUP m_dyld_ap;
3061 lldb::JITLoaderListUP m_jit_loaders_ap;
3062 lldb::DynamicCheckerFunctionsUP m_dynamic_checkers_ap; ///< The functions used
3063 ///by the expression
3064 ///parser to validate
3067 lldb::OperatingSystemUP m_os_ap;
3068 lldb::SystemRuntimeUP m_system_runtime_ap;
3070 m_unix_signals_sp; /// This is the current signal set for this process.
3071 lldb::ABISP m_abi_sp;
3072 lldb::IOHandlerSP m_process_input_reader;
3073 Communication m_stdio_communication;
3074 std::recursive_mutex m_stdio_communication_mutex;
3075 bool m_stdin_forward; /// Remember if stdin must be forwarded to remote debug
3077 std::string m_stdout_data;
3078 std::string m_stderr_data;
3079 std::recursive_mutex m_profile_data_comm_mutex;
3080 std::vector<std::string> m_profile_data;
3081 Predicate<uint32_t> m_iohandler_sync;
3082 MemoryCache m_memory_cache;
3083 AllocatedMemoryCache m_allocated_memory_cache;
3084 bool m_should_detach; /// Should we detach if the process object goes away
3085 /// with an explicit call to Kill or Detach?
3086 LanguageRuntimeCollection m_language_runtimes;
3087 InstrumentationRuntimeCollection m_instrumentation_runtimes;
3088 std::unique_ptr<NextEventAction> m_next_event_action_ap;
3089 std::vector<PreResumeCallbackAndBaton> m_pre_resume_actions;
3090 ProcessRunLock m_public_run_lock;
3091 ProcessRunLock m_private_run_lock;
3092 bool m_currently_handling_do_on_removals;
3093 bool m_resume_requested; // If m_currently_handling_event or
3094 // m_currently_handling_do_on_removals are true,
3095 // Resume will only request a resume, using this
3097 bool m_finalizing; // This is set at the beginning of Process::Finalize() to
3098 // stop functions from looking up or creating things
3099 // during a finalize call
3100 bool m_finalize_called; // This is set at the end of Process::Finalize()
3101 bool m_clear_thread_plans_on_stop;
3102 bool m_force_next_event_delivery;
3103 lldb::StateType m_last_broadcast_state; /// This helps with the Public event
3105 /// ShouldBroadcastEvent.
3106 std::map<lldb::addr_t, lldb::addr_t> m_resolved_indirect_addresses;
3107 bool m_destroy_in_process;
3108 bool m_can_interpret_function_calls; // Some targets, e.g the OSX kernel,
3109 // don't support the ability to modify
3111 WarningsCollection m_warnings_issued; // A set of object pointers which have
3112 // already had warnings printed
3113 std::mutex m_run_thread_plan_lock;
3114 StructuredDataPluginMap m_structured_data_plugin_map;
3116 enum { eCanJITDontKnow = 0, eCanJITYes, eCanJITNo } m_can_jit;
3118 std::unique_ptr<UtilityFunction> m_dlopen_utility_func_up;
3119 std::once_flag m_dlopen_utility_func_flag_once;
3121 size_t RemoveBreakpointOpcodesFromBuffer(lldb::addr_t addr, size_t size,
3122 uint8_t *buf) const;
3124 void SynchronouslyNotifyStateChanged(lldb::StateType state);
3126 void SetPublicState(lldb::StateType new_state, bool restarted);
3128 void SetPrivateState(lldb::StateType state);
3130 bool StartPrivateStateThread(bool is_secondary_thread = false);
3132 void StopPrivateStateThread();
3134 void PausePrivateStateThread();
3136 void ResumePrivateStateThread();
3139 struct PrivateStateThreadArgs {
3140 PrivateStateThreadArgs(Process *p, bool s)
3141 : process(p), is_secondary_thread(s){};
3143 bool is_secondary_thread;
3146 // arg is a pointer to a new'ed PrivateStateThreadArgs structure.
3147 // PrivateStateThread will free it for you.
3148 static lldb::thread_result_t PrivateStateThread(void *arg);
3150 // The starts up the private state thread that will watch for events from the
3151 // debugee. Pass true for is_secondary_thread in the case where you have to
3152 // temporarily spin up a secondary state thread to handle events from a hand-
3153 // called function on the primary private state thread.
3155 lldb::thread_result_t RunPrivateStateThread(bool is_secondary_thread);
3158 void HandlePrivateEvent(lldb::EventSP &event_sp);
3160 Status HaltPrivate();
3162 lldb::StateType WaitForProcessStopPrivate(lldb::EventSP &event_sp,
3163 const Timeout<std::micro> &timeout);
3165 // This waits for both the state change broadcaster, and the control
3166 // broadcaster. If control_only, it only waits for the control broadcaster.
3168 bool GetEventsPrivate(lldb::EventSP &event_sp,
3169 const Timeout<std::micro> &timeout, bool control_only);
3172 GetStateChangedEventsPrivate(lldb::EventSP &event_sp,
3173 const Timeout<std::micro> &timeout);
3175 size_t WriteMemoryPrivate(lldb::addr_t addr, const void *buf, size_t size,
3178 void AppendSTDOUT(const char *s, size_t len);
3180 void AppendSTDERR(const char *s, size_t len);
3182 void BroadcastAsyncProfileData(const std::string &one_profile_data);
3184 static void STDIOReadThreadBytesReceived(void *baton, const void *src,
3187 bool PushProcessIOHandler();
3189 bool PopProcessIOHandler();
3191 bool ProcessIOHandlerIsActive();
3193 bool ProcessIOHandlerExists() const {
3194 return static_cast<bool>(m_process_input_reader);
3197 Status StopForDestroyOrDetach(lldb::EventSP &exit_event_sp);
3199 virtual Status UpdateAutomaticSignalFiltering();
3201 bool StateChangedIsExternallyHijacked();
3203 void LoadOperatingSystemPlugin(bool flush);
3206 //------------------------------------------------------------------
3207 /// This is the part of the event handling that for a process event. It
3208 /// decides what to do with the event and returns true if the event needs to
3209 /// be propagated to the user, and false otherwise. If the event is not
3210 /// propagated, this call will most likely set the target to executing
3211 /// again. There is only one place where this call should be called,
3212 /// HandlePrivateEvent. Don't call it from anywhere else...
3214 /// @param[in] event_ptr
3215 /// This is the event we are handling.
3218 /// Returns \b true if the event should be reported to the
3219 /// user, \b false otherwise.
3220 //------------------------------------------------------------------
3221 bool ShouldBroadcastEvent(Event *event_ptr);
3223 void ControlPrivateStateThread(uint32_t signal);
3225 DISALLOW_COPY_AND_ASSIGN(Process);
3228 } // namespace lldb_private
3230 #endif // liblldb_Process_h_