1 //===-- Process.h -----------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLDB_TARGET_PROCESS_H
10 #define LLDB_TARGET_PROCESS_H
11 
12 #include "lldb/Host/Config.h"
13 
14 #include <limits.h>
15 
16 #include <chrono>
17 #include <list>
18 #include <memory>
19 #include <mutex>
20 #include <string>
21 #include <unordered_set>
22 #include <vector>
23 
24 #include "lldb/Breakpoint/BreakpointSiteList.h"
25 #include "lldb/Core/Communication.h"
26 #include "lldb/Core/LoadedModuleInfoList.h"
27 #include "lldb/Core/PluginInterface.h"
28 #include "lldb/Core/ThreadSafeValue.h"
29 #include "lldb/Core/UserSettingsController.h"
30 #include "lldb/Host/HostThread.h"
31 #include "lldb/Host/ProcessLaunchInfo.h"
32 #include "lldb/Host/ProcessRunLock.h"
33 #include "lldb/Interpreter/Options.h"
34 #include "lldb/Symbol/ObjectFile.h"
35 #include "lldb/Target/ExecutionContextScope.h"
36 #include "lldb/Target/InstrumentationRuntime.h"
37 #include "lldb/Target/Memory.h"
38 #include "lldb/Target/QueueList.h"
39 #include "lldb/Target/ThreadList.h"
40 #include "lldb/Target/ThreadPlanStack.h"
41 #include "lldb/Target/Trace.h"
42 #include "lldb/Utility/ArchSpec.h"
43 #include "lldb/Utility/Broadcaster.h"
44 #include "lldb/Utility/Event.h"
45 #include "lldb/Utility/Listener.h"
46 #include "lldb/Utility/NameMatches.h"
47 #include "lldb/Utility/ProcessInfo.h"
48 #include "lldb/Utility/Status.h"
49 #include "lldb/Utility/StructuredData.h"
50 #include "lldb/Utility/TraceOptions.h"
51 #include "lldb/Utility/UnimplementedError.h"
52 #include "lldb/Utility/UserIDResolver.h"
53 #include "lldb/lldb-private.h"
54 
55 #include "llvm/ADT/ArrayRef.h"
56 #include "llvm/Support/Threading.h"
57 #include "llvm/Support/VersionTuple.h"
58 
59 namespace lldb_private {
60 
61 template <typename B, typename S> struct Range;
62 
63 class ProcessExperimentalProperties : public Properties {
64 public:
65   ProcessExperimentalProperties();
66 };
67 
68 class ProcessProperties : public Properties {
69 public:
70   // Pass nullptr for "process" if the ProcessProperties are to be the global
71   // copy
72   ProcessProperties(lldb_private::Process *process);
73 
74   ~ProcessProperties() override;
75 
76   bool GetDisableMemoryCache() const;
77   uint64_t GetMemoryCacheLineSize() const;
78   Args GetExtraStartupCommands() const;
79   void SetExtraStartupCommands(const Args &args);
80   FileSpec GetPythonOSPluginPath() const;
81   void SetPythonOSPluginPath(const FileSpec &file);
82   bool GetIgnoreBreakpointsInExpressions() const;
83   void SetIgnoreBreakpointsInExpressions(bool ignore);
84   bool GetUnwindOnErrorInExpressions() const;
85   void SetUnwindOnErrorInExpressions(bool ignore);
86   bool GetStopOnSharedLibraryEvents() const;
87   void SetStopOnSharedLibraryEvents(bool stop);
88   bool GetDetachKeepsStopped() const;
89   void SetDetachKeepsStopped(bool keep_stopped);
90   bool GetWarningsOptimization() const;
91   bool GetWarningsUnsupportedLanguage() const;
92   bool GetStopOnExec() const;
93   std::chrono::seconds GetUtilityExpressionTimeout() const;
94   bool GetOSPluginReportsAllThreads() const;
95   void SetOSPluginReportsAllThreads(bool does_report);
96   bool GetSteppingRunsAllThreads() const;
97 
98 protected:
99   Process *m_process; // Can be nullptr for global ProcessProperties
100   std::unique_ptr<ProcessExperimentalProperties> m_experimental_properties_up;
101 };
102 
103 typedef std::shared_ptr<ProcessProperties> ProcessPropertiesSP;
104 
105 // ProcessAttachInfo
106 //
107 // Describes any information that is required to attach to a process.
108 
109 class ProcessAttachInfo : public ProcessInstanceInfo {
110 public:
ProcessAttachInfo()111   ProcessAttachInfo()
112       : ProcessInstanceInfo(), m_listener_sp(), m_hijack_listener_sp(),
113         m_plugin_name(), m_resume_count(0), m_wait_for_launch(false),
114         m_ignore_existing(true), m_continue_once_attached(false),
115         m_detach_on_error(true), m_async(false) {}
116 
ProcessAttachInfo(const ProcessLaunchInfo & launch_info)117   ProcessAttachInfo(const ProcessLaunchInfo &launch_info)
118       : ProcessInstanceInfo(), m_listener_sp(), m_hijack_listener_sp(),
119         m_plugin_name(), m_resume_count(0), m_wait_for_launch(false),
120         m_ignore_existing(true), m_continue_once_attached(false),
121         m_detach_on_error(true), m_async(false) {
122     ProcessInfo::operator=(launch_info);
123     SetProcessPluginName(launch_info.GetProcessPluginName());
124     SetResumeCount(launch_info.GetResumeCount());
125     SetListener(launch_info.GetListener());
126     SetHijackListener(launch_info.GetHijackListener());
127     m_detach_on_error = launch_info.GetDetachOnError();
128   }
129 
GetWaitForLaunch()130   bool GetWaitForLaunch() const { return m_wait_for_launch; }
131 
SetWaitForLaunch(bool b)132   void SetWaitForLaunch(bool b) { m_wait_for_launch = b; }
133 
GetAsync()134   bool GetAsync() const { return m_async; }
135 
SetAsync(bool b)136   void SetAsync(bool b) { m_async = b; }
137 
GetIgnoreExisting()138   bool GetIgnoreExisting() const { return m_ignore_existing; }
139 
SetIgnoreExisting(bool b)140   void SetIgnoreExisting(bool b) { m_ignore_existing = b; }
141 
GetContinueOnceAttached()142   bool GetContinueOnceAttached() const { return m_continue_once_attached; }
143 
SetContinueOnceAttached(bool b)144   void SetContinueOnceAttached(bool b) { m_continue_once_attached = b; }
145 
GetResumeCount()146   uint32_t GetResumeCount() const { return m_resume_count; }
147 
SetResumeCount(uint32_t c)148   void SetResumeCount(uint32_t c) { m_resume_count = c; }
149 
GetProcessPluginName()150   const char *GetProcessPluginName() const {
151     return (m_plugin_name.empty() ? nullptr : m_plugin_name.c_str());
152   }
153 
SetProcessPluginName(llvm::StringRef plugin)154   void SetProcessPluginName(llvm::StringRef plugin) {
155     m_plugin_name = std::string(plugin);
156   }
157 
Clear()158   void Clear() {
159     ProcessInstanceInfo::Clear();
160     m_plugin_name.clear();
161     m_resume_count = 0;
162     m_wait_for_launch = false;
163     m_ignore_existing = true;
164     m_continue_once_attached = false;
165   }
166 
ProcessInfoSpecified()167   bool ProcessInfoSpecified() const {
168     if (GetExecutableFile())
169       return true;
170     if (GetProcessID() != LLDB_INVALID_PROCESS_ID)
171       return true;
172     if (GetParentProcessID() != LLDB_INVALID_PROCESS_ID)
173       return true;
174     return false;
175   }
176 
GetHijackListener()177   lldb::ListenerSP GetHijackListener() const { return m_hijack_listener_sp; }
178 
SetHijackListener(const lldb::ListenerSP & listener_sp)179   void SetHijackListener(const lldb::ListenerSP &listener_sp) {
180     m_hijack_listener_sp = listener_sp;
181   }
182 
GetDetachOnError()183   bool GetDetachOnError() const { return m_detach_on_error; }
184 
SetDetachOnError(bool enable)185   void SetDetachOnError(bool enable) { m_detach_on_error = enable; }
186 
187   // Get and set the actual listener that will be used for the process events
GetListener()188   lldb::ListenerSP GetListener() const { return m_listener_sp; }
189 
SetListener(const lldb::ListenerSP & listener_sp)190   void SetListener(const lldb::ListenerSP &listener_sp) {
191     m_listener_sp = listener_sp;
192   }
193 
194   lldb::ListenerSP GetListenerForProcess(Debugger &debugger);
195 
196 protected:
197   lldb::ListenerSP m_listener_sp;
198   lldb::ListenerSP m_hijack_listener_sp;
199   std::string m_plugin_name;
200   uint32_t m_resume_count; // How many times do we resume after launching
201   bool m_wait_for_launch;
202   bool m_ignore_existing;
203   bool m_continue_once_attached; // Supports the use-case scenario of
204                                  // immediately continuing the process once
205                                  // attached.
206   bool m_detach_on_error; // If we are debugging remotely, instruct the stub to
207                           // detach rather than killing the target on error.
208   bool m_async; // Use an async attach where we start the attach and return
209                 // immediately (used by GUI programs with --waitfor so they can
210                 // call SBProcess::Stop() to cancel attach)
211 };
212 
213 class ProcessLaunchCommandOptions : public Options {
214 public:
ProcessLaunchCommandOptions()215   ProcessLaunchCommandOptions() : Options() {
216     // Keep default values of all options in one place: OptionParsingStarting
217     // ()
218     OptionParsingStarting(nullptr);
219   }
220 
221   ~ProcessLaunchCommandOptions() override = default;
222 
223   Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
224                         ExecutionContext *execution_context) override;
225 
OptionParsingStarting(ExecutionContext * execution_context)226   void OptionParsingStarting(ExecutionContext *execution_context) override {
227     launch_info.Clear();
228     disable_aslr = eLazyBoolCalculate;
229   }
230 
231   llvm::ArrayRef<OptionDefinition> GetDefinitions() override;
232 
233   // Instance variables to hold the values for command options.
234 
235   ProcessLaunchInfo launch_info;
236   lldb_private::LazyBool disable_aslr;
237 };
238 
239 // This class tracks the Modification state of the process.  Things that can
240 // currently modify the program are running the program (which will up the
241 // StopID) and writing memory (which will up the MemoryID.)
242 // FIXME: Should we also include modification of register states?
243 
244 class ProcessModID {
245   friend bool operator==(const ProcessModID &lhs, const ProcessModID &rhs);
246 
247 public:
ProcessModID()248   ProcessModID()
249       : m_stop_id(0), m_last_natural_stop_id(0), m_resume_id(0), m_memory_id(0),
250         m_last_user_expression_resume(0), m_running_user_expression(false),
251         m_running_utility_function(0) {}
252 
ProcessModID(const ProcessModID & rhs)253   ProcessModID(const ProcessModID &rhs)
254       : m_stop_id(rhs.m_stop_id), m_memory_id(rhs.m_memory_id) {}
255 
256   const ProcessModID &operator=(const ProcessModID &rhs) {
257     if (this != &rhs) {
258       m_stop_id = rhs.m_stop_id;
259       m_memory_id = rhs.m_memory_id;
260     }
261     return *this;
262   }
263 
264   ~ProcessModID() = default;
265 
BumpStopID()266   void BumpStopID() {
267     m_stop_id++;
268     if (!IsLastResumeForUserExpression())
269       m_last_natural_stop_id++;
270   }
271 
BumpMemoryID()272   void BumpMemoryID() { m_memory_id++; }
273 
BumpResumeID()274   void BumpResumeID() {
275     m_resume_id++;
276     if (m_running_user_expression > 0)
277       m_last_user_expression_resume = m_resume_id;
278   }
279 
IsRunningUtilityFunction()280   bool IsRunningUtilityFunction() const {
281     return m_running_utility_function > 0;
282   }
283 
GetStopID()284   uint32_t GetStopID() const { return m_stop_id; }
GetLastNaturalStopID()285   uint32_t GetLastNaturalStopID() const { return m_last_natural_stop_id; }
GetMemoryID()286   uint32_t GetMemoryID() const { return m_memory_id; }
GetResumeID()287   uint32_t GetResumeID() const { return m_resume_id; }
GetLastUserExpressionResumeID()288   uint32_t GetLastUserExpressionResumeID() const {
289     return m_last_user_expression_resume;
290   }
291 
MemoryIDEqual(const ProcessModID & compare)292   bool MemoryIDEqual(const ProcessModID &compare) const {
293     return m_memory_id == compare.m_memory_id;
294   }
295 
StopIDEqual(const ProcessModID & compare)296   bool StopIDEqual(const ProcessModID &compare) const {
297     return m_stop_id == compare.m_stop_id;
298   }
299 
SetInvalid()300   void SetInvalid() { m_stop_id = UINT32_MAX; }
301 
IsValid()302   bool IsValid() const { return m_stop_id != UINT32_MAX; }
303 
IsLastResumeForUserExpression()304   bool IsLastResumeForUserExpression() const {
305     // If we haven't yet resumed the target, then it can't be for a user
306     // expression...
307     if (m_resume_id == 0)
308       return false;
309 
310     return m_resume_id == m_last_user_expression_resume;
311   }
312 
SetRunningUserExpression(bool on)313   void SetRunningUserExpression(bool on) {
314     if (on)
315       m_running_user_expression++;
316     else
317       m_running_user_expression--;
318   }
319 
SetRunningUtilityFunction(bool on)320   void SetRunningUtilityFunction(bool on) {
321     if (on)
322       m_running_utility_function++;
323     else {
324       assert(m_running_utility_function > 0 &&
325              "Called SetRunningUtilityFunction(false) without calling "
326              "SetRunningUtilityFunction(true) before?");
327       m_running_utility_function--;
328     }
329   }
330 
SetStopEventForLastNaturalStopID(lldb::EventSP event_sp)331   void SetStopEventForLastNaturalStopID(lldb::EventSP event_sp) {
332     m_last_natural_stop_event = std::move(event_sp);
333   }
334 
GetStopEventForStopID(uint32_t stop_id)335   lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const {
336     if (stop_id == m_last_natural_stop_id)
337       return m_last_natural_stop_event;
338     return lldb::EventSP();
339   }
340 
341 private:
342   uint32_t m_stop_id;
343   uint32_t m_last_natural_stop_id;
344   uint32_t m_resume_id;
345   uint32_t m_memory_id;
346   uint32_t m_last_user_expression_resume;
347   uint32_t m_running_user_expression;
348   uint32_t m_running_utility_function;
349   lldb::EventSP m_last_natural_stop_event;
350 };
351 
352 inline bool operator==(const ProcessModID &lhs, const ProcessModID &rhs) {
353   if (lhs.StopIDEqual(rhs) && lhs.MemoryIDEqual(rhs))
354     return true;
355   else
356     return false;
357 }
358 
359 inline bool operator!=(const ProcessModID &lhs, const ProcessModID &rhs) {
360   return (!lhs.StopIDEqual(rhs) || !lhs.MemoryIDEqual(rhs));
361 }
362 
363 /// \class Process Process.h "lldb/Target/Process.h"
364 /// A plug-in interface definition class for debugging a process.
365 class Process : public std::enable_shared_from_this<Process>,
366                 public ProcessProperties,
367                 public Broadcaster,
368                 public ExecutionContextScope,
369                 public PluginInterface {
370   friend class FunctionCaller; // For WaitForStateChangeEventsPrivate
371   friend class Debugger; // For PopProcessIOHandler and ProcessIOHandlerIsActive
372   friend class DynamicLoader; // For LoadOperatingSystemPlugin
373   friend class ProcessEventData;
374   friend class StopInfo;
375   friend class Target;
376   friend class ThreadList;
377 
378 public:
379   /// Broadcaster event bits definitions.
380   enum {
381     eBroadcastBitStateChanged = (1 << 0),
382     eBroadcastBitInterrupt = (1 << 1),
383     eBroadcastBitSTDOUT = (1 << 2),
384     eBroadcastBitSTDERR = (1 << 3),
385     eBroadcastBitProfileData = (1 << 4),
386     eBroadcastBitStructuredData = (1 << 5),
387   };
388 
389   enum {
390     eBroadcastInternalStateControlStop = (1 << 0),
391     eBroadcastInternalStateControlPause = (1 << 1),
392     eBroadcastInternalStateControlResume = (1 << 2)
393   };
394 
395   /// Process warning types.
396   enum Warnings { eWarningsOptimization = 1, eWarningsUnsupportedLanguage = 2 };
397 
398   typedef Range<lldb::addr_t, lldb::addr_t> LoadRange;
399   // We use a read/write lock to allow on or more clients to access the process
400   // state while the process is stopped (reader). We lock the write lock to
401   // control access to the process while it is running (readers, or clients
402   // that want the process stopped can block waiting for the process to stop,
403   // or just try to lock it to see if they can immediately access the stopped
404   // process. If the try read lock fails, then the process is running.
405   typedef ProcessRunLock::ProcessRunLocker StopLocker;
406 
407   // These two functions fill out the Broadcaster interface:
408 
409   static ConstString &GetStaticBroadcasterClass();
410 
GetBroadcasterClass()411   ConstString &GetBroadcasterClass() const override {
412     return GetStaticBroadcasterClass();
413   }
414 
415 /// A notification structure that can be used by clients to listen
416 /// for changes in a process's lifetime.
417 ///
418 /// \see RegisterNotificationCallbacks (const Notifications&) @see
419 /// UnregisterNotificationCallbacks (const Notifications&)
420   typedef struct {
421     void *baton;
422     void (*initialize)(void *baton, Process *process);
423     void (*process_state_changed)(void *baton, Process *process,
424                                   lldb::StateType state);
425   } Notifications;
426 
427   class ProcessEventData : public EventData {
428     friend class Process;
429 
430   public:
431     ProcessEventData();
432     ProcessEventData(const lldb::ProcessSP &process, lldb::StateType state);
433 
434     ~ProcessEventData() override;
435 
436     static ConstString GetFlavorString();
437 
438     ConstString GetFlavor() const override;
439 
GetProcessSP()440     lldb::ProcessSP GetProcessSP() const { return m_process_wp.lock(); }
441 
GetState()442     lldb::StateType GetState() const { return m_state; }
GetRestarted()443     bool GetRestarted() const { return m_restarted; }
444 
GetNumRestartedReasons()445     size_t GetNumRestartedReasons() { return m_restarted_reasons.size(); }
446 
GetRestartedReasonAtIndex(size_t idx)447     const char *GetRestartedReasonAtIndex(size_t idx) {
448       return ((idx < m_restarted_reasons.size())
449                   ? m_restarted_reasons[idx].c_str()
450                   : nullptr);
451     }
452 
GetInterrupted()453     bool GetInterrupted() const { return m_interrupted; }
454 
455     void Dump(Stream *s) const override;
456 
457     virtual bool ShouldStop(Event *event_ptr, bool &found_valid_stopinfo);
458 
459     void DoOnRemoval(Event *event_ptr) override;
460 
461     static const Process::ProcessEventData *
462     GetEventDataFromEvent(const Event *event_ptr);
463 
464     static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr);
465 
466     static lldb::StateType GetStateFromEvent(const Event *event_ptr);
467 
468     static bool GetRestartedFromEvent(const Event *event_ptr);
469 
470     static size_t GetNumRestartedReasons(const Event *event_ptr);
471 
472     static const char *GetRestartedReasonAtIndex(const Event *event_ptr,
473                                                  size_t idx);
474 
475     static void AddRestartedReason(Event *event_ptr, const char *reason);
476 
477     static void SetRestartedInEvent(Event *event_ptr, bool new_value);
478 
479     static bool GetInterruptedFromEvent(const Event *event_ptr);
480 
481     static void SetInterruptedInEvent(Event *event_ptr, bool new_value);
482 
483     static bool SetUpdateStateOnRemoval(Event *event_ptr);
484 
485   private:
SetUpdateStateOnRemoval()486     void SetUpdateStateOnRemoval() { m_update_state++; }
487 
SetRestarted(bool new_value)488     void SetRestarted(bool new_value) { m_restarted = new_value; }
489 
SetInterrupted(bool new_value)490     void SetInterrupted(bool new_value) { m_interrupted = new_value; }
491 
AddRestartedReason(const char * reason)492     void AddRestartedReason(const char *reason) {
493       m_restarted_reasons.push_back(reason);
494     }
495 
496     lldb::ProcessWP m_process_wp;
497     lldb::StateType m_state;
498     std::vector<std::string> m_restarted_reasons;
499     bool m_restarted; // For "eStateStopped" events, this is true if the target
500                       // was automatically restarted.
501     int m_update_state;
502     bool m_interrupted;
503 
504     ProcessEventData(const ProcessEventData &) = delete;
505     const ProcessEventData &operator=(const ProcessEventData &) = delete;
506   };
507 
508   /// Construct with a shared pointer to a target, and the Process listener.
509   /// Uses the Host UnixSignalsSP by default.
510   Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp);
511 
512   /// Construct with a shared pointer to a target, the Process listener, and
513   /// the appropriate UnixSignalsSP for the process.
514   Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp,
515           const lldb::UnixSignalsSP &unix_signals_sp);
516 
517   /// Destructor.
518   ///
519   /// The destructor is virtual since this class is designed to be inherited
520   /// from by the plug-in instance.
521   ~Process() override;
522 
523   static void SettingsInitialize();
524 
525   static void SettingsTerminate();
526 
527   static const ProcessPropertiesSP &GetGlobalProperties();
528 
529   /// Find a Process plug-in that can debug \a module using the currently
530   /// selected architecture.
531   ///
532   /// Scans all loaded plug-in interfaces that implement versions of the
533   /// Process plug-in interface and returns the first instance that can debug
534   /// the file.
535   ///
536   /// \see Process::CanDebug ()
537   static lldb::ProcessSP FindPlugin(lldb::TargetSP target_sp,
538                                     llvm::StringRef plugin_name,
539                                     lldb::ListenerSP listener_sp,
540                                     const FileSpec *crash_file_path,
541                                     bool can_connect);
542 
543   /// Static function that can be used with the \b host function
544   /// Host::StartMonitoringChildProcess ().
545   ///
546   /// This function can be used by lldb_private::Process subclasses when they
547   /// want to watch for a local process and have its exit status automatically
548   /// set when the host child process exits. Subclasses should call
549   /// Host::StartMonitoringChildProcess () with:
550   ///     callback = Process::SetHostProcessExitStatus
551   ///     pid = Process::GetID()
552   ///     monitor_signals = false
553   static bool
554   SetProcessExitStatus(lldb::pid_t pid, // The process ID we want to monitor
555                        bool exited,
556                        int signo,   // Zero for no signal
557                        int status); // Exit value of process if signal is zero
558 
559   lldb::ByteOrder GetByteOrder() const;
560 
561   uint32_t GetAddressByteSize() const;
562 
563   /// Sets the stored pid.
564   ///
565   /// This does not change the pid of underlying process.
GetID()566   lldb::pid_t GetID() const { return m_pid; }
567 
568   /// Returns the pid of the process or LLDB_INVALID_PROCESS_ID if there is
569   /// no known pid.
SetID(lldb::pid_t new_pid)570   void SetID(lldb::pid_t new_pid) { m_pid = new_pid; }
571 
GetUniqueID()572   uint32_t GetUniqueID() const { return m_process_unique_id; }
573 
574   /// Check if a plug-in instance can debug the file in \a module.
575   ///
576   /// Each plug-in is given a chance to say whether it can debug the file in
577   /// \a module. If the Process plug-in instance can debug a file on the
578   /// current system, it should return \b true.
579   ///
580   /// \return
581   ///     Returns \b true if this Process plug-in instance can
582   ///     debug the executable, \b false otherwise.
583   virtual bool CanDebug(lldb::TargetSP target,
584                         bool plugin_specified_by_name) = 0;
585 
586   /// This object is about to be destroyed, do any necessary cleanup.
587   ///
588   /// Subclasses that override this method should always call this superclass
589   /// method.
590   virtual void Finalize();
591 
592   /// Return whether this object is valid (i.e. has not been finalized.)
593   ///
594   /// \return
595   ///     Returns \b true if this Process has not been finalized
596   ///     and \b false otherwise.
IsValid()597   bool IsValid() const { return !m_finalize_called; }
598 
599   /// Return a multi-word command object that can be used to expose plug-in
600   /// specific commands.
601   ///
602   /// This object will be used to resolve plug-in commands and can be
603   /// triggered by a call to:
604   ///
605   ///     (lldb) process command <args>
606   ///
607   /// \return
608   ///     A CommandObject which can be one of the concrete subclasses
609   ///     of CommandObject like CommandObjectRaw, CommandObjectParsed,
610   ///     or CommandObjectMultiword.
GetPluginCommandObject()611   virtual CommandObject *GetPluginCommandObject() { return nullptr; }
612 
613   /// Launch a new process.
614   ///
615   /// Launch a new process by spawning a new process using the target object's
616   /// executable module's file as the file to launch.
617   ///
618   /// This function is not meant to be overridden by Process subclasses. It
619   /// will first call Process::WillLaunch (Module *) and if that returns \b
620   /// true, Process::DoLaunch (Module*, char const *[],char const *[],const
621   /// char *,const char *, const char *) will be called to actually do the
622   /// launching. If DoLaunch returns \b true, then Process::DidLaunch() will
623   /// be called.
624   ///
625   /// \param[in] launch_info
626   ///     Details regarding the environment, STDIN/STDOUT/STDERR
627   ///     redirection, working path, etc. related to the requested launch.
628   ///
629   /// \return
630   ///     An error object. Call GetID() to get the process ID if
631   ///     the error object is success.
632   virtual Status Launch(ProcessLaunchInfo &launch_info);
633 
634   virtual Status LoadCore();
635 
DoLoadCore()636   virtual Status DoLoadCore() {
637     Status error;
638     error.SetErrorStringWithFormat(
639         "error: %s does not support loading core files.",
640         GetPluginName().GetCString());
641     return error;
642   }
643 
644   // FUTURE WORK: GetLoadImageUtilityFunction are the first use we've
645   // had of having other plugins cache data in the Process.  This is handy for
646   // long-living plugins - like the Platform - which manage interactions whose
647   // lifetime is governed by the Process lifetime.  If we find we need to do
648   // this more often, we should construct a general solution to the problem.
649   // The consensus suggestion was that we have a token based registry in the
650   // Process. Some undecided questions are  (1) who manages the tokens.  It's
651   // probably best that you add the element  and get back a token that
652   // represents it.  That will avoid collisions.  But there may be some utility
653   // in the registerer controlling the token? (2) whether the thing added
654   // should be simply owned by Process, and just go away when it does (3)
655   // whether the registree should be notified of the Process' demise.
656   //
657   // We are postponing designing this till we have at least a second use case.
658   /// Get the cached UtilityFunction that assists in loading binary images
659   /// into the process.
660   ///
661   /// \param[in] platform
662   ///     The platform fetching the UtilityFunction.
663   /// \param[in] factory
664   ///     A function that will be called only once per-process in a
665   ///     thread-safe way to create the UtilityFunction if it has not
666   ///     been initialized yet.
667   ///
668   /// \return
669   ///     The cached utility function or null if the platform is not the
670   ///     same as the target's platform.
671   UtilityFunction *GetLoadImageUtilityFunction(
672       Platform *platform,
673       llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory);
674 
675   /// Get the dynamic loader plug-in for this process.
676   ///
677   /// The default action is to let the DynamicLoader plug-ins check the main
678   /// executable and the DynamicLoader will select itself automatically.
679   /// Subclasses can override this if inspecting the executable is not
680   /// desired, or if Process subclasses can only use a specific DynamicLoader
681   /// plug-in.
682   virtual DynamicLoader *GetDynamicLoader();
683 
684   // Returns AUXV structure found in many ELF-based environments.
685   //
686   // The default action is to return an empty data buffer.
687   //
688   // \return
689   //    A data extractor containing the contents of the AUXV data.
690   virtual DataExtractor GetAuxvData();
691 
692   /// Sometimes processes know how to retrieve and load shared libraries. This
693   /// is normally done by DynamicLoader plug-ins, but sometimes the connection
694   /// to the process allows retrieving this information. The dynamic loader
695   /// plug-ins can use this function if they can't determine the current
696   /// shared library load state.
697   ///
698   /// \return
699   ///    A status object indicating if the operation was sucessful or not.
LoadModules()700   virtual llvm::Error LoadModules() {
701     return llvm::make_error<llvm::StringError>("Not implemented.",
702                                                llvm::inconvertibleErrorCode());
703   }
704 
705   /// Query remote GDBServer for a detailed loaded library list
706   /// \return
707   ///    The list of modules currently loaded by the process, or an error.
GetLoadedModuleList()708   virtual llvm::Expected<LoadedModuleInfoList> GetLoadedModuleList() {
709     return llvm::createStringError(llvm::inconvertibleErrorCode(),
710                                    "Not implemented");
711   }
712 
713 protected:
714   virtual JITLoaderList &GetJITLoaders();
715 
716 public:
717   /// Get the system runtime plug-in for this process.
718   ///
719   /// \return
720   ///   Returns a pointer to the SystemRuntime plugin for this Process
721   ///   if one is available.  Else returns nullptr.
722   virtual SystemRuntime *GetSystemRuntime();
723 
724   /// Attach to an existing process using the process attach info.
725   ///
726   /// This function is not meant to be overridden by Process subclasses. It
727   /// will first call WillAttach (lldb::pid_t) or WillAttach (const char *),
728   /// and if that returns \b true, DoAttach (lldb::pid_t) or DoAttach (const
729   /// char *) will be called to actually do the attach. If DoAttach returns \b
730   /// true, then Process::DidAttach() will be called.
731   ///
732   /// \param[in] attach_info
733   ///     The process attach info.
734   ///
735   /// \return
736   ///     Returns \a pid if attaching was successful, or
737   ///     LLDB_INVALID_PROCESS_ID if attaching fails.
738   virtual Status Attach(ProcessAttachInfo &attach_info);
739 
740   /// Attach to a remote system via a URL
741   ///
742   /// \param[in] remote_url
743   ///     The URL format that we are connecting to.
744   ///
745   /// \return
746   ///     Returns an error object.
747   virtual Status ConnectRemote(llvm::StringRef remote_url);
748 
GetShouldDetach()749   bool GetShouldDetach() const { return m_should_detach; }
750 
SetShouldDetach(bool b)751   void SetShouldDetach(bool b) { m_should_detach = b; }
752 
753   /// Get the image vector for the current process.
754   ///
755   /// \return
756   ///     The constant reference to the member m_image_tokens.
GetImageTokens()757   const std::vector<lldb::addr_t>& GetImageTokens() { return m_image_tokens; }
758 
759   /// Get the image information address for the current process.
760   ///
761   /// Some runtimes have system functions that can help dynamic loaders locate
762   /// the dynamic loader information needed to observe shared libraries being
763   /// loaded or unloaded. This function is in the Process interface (as
764   /// opposed to the DynamicLoader interface) to ensure that remote debugging
765   /// can take advantage of this functionality.
766   ///
767   /// \return
768   ///     The address of the dynamic loader information, or
769   ///     LLDB_INVALID_ADDRESS if this is not supported by this
770   ///     interface.
771   virtual lldb::addr_t GetImageInfoAddress();
772 
773   /// Called when the process is about to broadcast a public stop.
774   ///
775   /// There are public and private stops. Private stops are when the process
776   /// is doing things like stepping and the client doesn't need to know about
777   /// starts and stop that implement a thread plan. Single stepping over a
778   /// source line in code might end up being implemented by one or more
779   /// process starts and stops. Public stops are when clients will be notified
780   /// that the process is stopped. These events typically trigger UI updates
781   /// (thread stack frames to be displayed, variables to be displayed, and
782   /// more). This function can be overriden and allows process subclasses to
783   /// do something before the eBroadcastBitStateChanged event is sent to
784   /// public clients.
WillPublicStop()785   virtual void WillPublicStop() {}
786 
787 /// Register for process and thread notifications.
788 ///
789 /// Clients can register notification callbacks by filling out a
790 /// Process::Notifications structure and calling this function.
791 ///
792 /// \param[in] callbacks
793 ///     A structure that contains the notification baton and
794 ///     callback functions.
795 ///
796 /// \see Process::Notifications
797   void RegisterNotificationCallbacks(const Process::Notifications &callbacks);
798 
799 /// Unregister for process and thread notifications.
800 ///
801 /// Clients can unregister notification callbacks by passing a copy of the
802 /// original baton and callbacks in \a callbacks.
803 ///
804 /// \param[in] callbacks
805 ///     A structure that contains the notification baton and
806 ///     callback functions.
807 ///
808 /// \return
809 ///     Returns \b true if the notification callbacks were
810 ///     successfully removed from the process, \b false otherwise.
811 ///
812 /// \see Process::Notifications
813   bool UnregisterNotificationCallbacks(const Process::Notifications &callbacks);
814 
815   //==================================================================
816   // Built in Process Control functions
817   //==================================================================
818   /// Resumes all of a process's threads as configured using the Thread run
819   /// control functions.
820   ///
821   /// Threads for a process should be updated with one of the run control
822   /// actions (resume, step, or suspend) that they should take when the
823   /// process is resumed. If no run control action is given to a thread it
824   /// will be resumed by default.
825   ///
826   /// This function is not meant to be overridden by Process subclasses. This
827   /// function will take care of disabling any breakpoints that threads may be
828   /// stopped at, single stepping, and re-enabling breakpoints, and enabling
829   /// the basic flow control that the plug-in instances need not worry about.
830   ///
831   /// N.B. This function also sets the Write side of the Run Lock, which is
832   /// unset when the corresponding stop event is pulled off the Public Event
833   /// Queue.  If you need to resume the process without setting the Run Lock,
834   /// use PrivateResume (though you should only do that from inside the
835   /// Process class.
836   ///
837   /// \return
838   ///     Returns an error object.
839   ///
840   /// \see Thread:Resume()
841   /// \see Thread:Step()
842   /// \see Thread:Suspend()
843   Status Resume();
844 
845   Status ResumeSynchronous(Stream *stream);
846 
847   /// Halts a running process.
848   ///
849   /// This function is not meant to be overridden by Process subclasses. If
850   /// the process is successfully halted, a eStateStopped process event with
851   /// GetInterrupted will be broadcast.  If false, we will halt the process
852   /// with no events generated by the halt.
853   ///
854   /// \param[in] clear_thread_plans
855   ///     If true, when the process stops, clear all thread plans.
856   ///
857   /// \param[in] use_run_lock
858   ///     Whether to release the run lock after the stop.
859   ///
860   /// \return
861   ///     Returns an error object.  If the error is empty, the process is
862   ///     halted.
863   ///     otherwise the halt has failed.
864   Status Halt(bool clear_thread_plans = false, bool use_run_lock = true);
865 
866   /// Detaches from a running or stopped process.
867   ///
868   /// This function is not meant to be overridden by Process subclasses.
869   ///
870   /// \param[in] keep_stopped
871   ///     If true, don't resume the process on detach.
872   ///
873   /// \return
874   ///     Returns an error object.
875   Status Detach(bool keep_stopped);
876 
877   /// Kills the process and shuts down all threads that were spawned to track
878   /// and monitor the process.
879   ///
880   /// This function is not meant to be overridden by Process subclasses.
881   ///
882   /// \param[in] force_kill
883   ///     Whether lldb should force a kill (instead of a detach) from
884   ///     the inferior process.  Normally if lldb launched a binary and
885   ///     Destory is called, lldb kills it.  If lldb attached to a
886   ///     running process and Destory is called, lldb detaches.  If
887   ///     this behavior needs to be over-ridden, this is the bool that
888   ///     can be used.
889   ///
890   /// \return
891   ///     Returns an error object.
892   Status Destroy(bool force_kill);
893 
894   /// Sends a process a UNIX signal \a signal.
895   ///
896   /// This function is not meant to be overridden by Process subclasses.
897   ///
898   /// \return
899   ///     Returns an error object.
900   Status Signal(int signal);
901 
902   void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp);
903 
904   const lldb::UnixSignalsSP &GetUnixSignals();
905 
906   //==================================================================
907   // Plug-in Process Control Overrides
908   //==================================================================
909 
910   /// Called before attaching to a process.
911   ///
912   /// Allow Process plug-ins to execute some code before attaching a process.
913   ///
914   /// \return
915   ///     Returns an error object.
WillAttachToProcessWithID(lldb::pid_t pid)916   virtual Status WillAttachToProcessWithID(lldb::pid_t pid) { return Status(); }
917 
918   /// Called before attaching to a process.
919   ///
920   /// Allow Process plug-ins to execute some code before attaching a process.
921   ///
922   /// \return
923   ///     Returns an error object.
WillAttachToProcessWithName(const char * process_name,bool wait_for_launch)924   virtual Status WillAttachToProcessWithName(const char *process_name,
925                                              bool wait_for_launch) {
926     return Status();
927   }
928 
929   /// Attach to a remote system via a URL
930   ///
931   /// \param[in] remote_url
932   ///     The URL format that we are connecting to.
933   ///
934   /// \return
935   ///     Returns an error object.
DoConnectRemote(llvm::StringRef remote_url)936   virtual Status DoConnectRemote(llvm::StringRef remote_url) {
937     Status error;
938     error.SetErrorString("remote connections are not supported");
939     return error;
940   }
941 
942   /// Attach to an existing process using a process ID.
943   ///
944   /// \param[in] pid
945   ///     The process ID that we should attempt to attach to.
946   ///
947   /// \param[in] attach_info
948   ///     Information on how to do the attach. For example, GetUserID()
949   ///     will return the uid to attach as.
950   ///
951   /// \return
952   ///     Returns a successful Status attaching was successful, or
953   ///     an appropriate (possibly platform-specific) error code if
954   ///     attaching fails.
955   /// hanming : need flag
DoAttachToProcessWithID(lldb::pid_t pid,const ProcessAttachInfo & attach_info)956   virtual Status DoAttachToProcessWithID(lldb::pid_t pid,
957                                          const ProcessAttachInfo &attach_info) {
958     Status error;
959     error.SetErrorStringWithFormat(
960         "error: %s does not support attaching to a process by pid",
961         GetPluginName().GetCString());
962     return error;
963   }
964 
965   /// Attach to an existing process using a partial process name.
966   ///
967   /// \param[in] process_name
968   ///     The name of the process to attach to.
969   ///
970   /// \param[in] attach_info
971   ///     Information on how to do the attach. For example, GetUserID()
972   ///     will return the uid to attach as.
973   ///
974   /// \return
975   ///     Returns a successful Status attaching was successful, or
976   ///     an appropriate (possibly platform-specific) error code if
977   ///     attaching fails.
978   virtual Status
DoAttachToProcessWithName(const char * process_name,const ProcessAttachInfo & attach_info)979   DoAttachToProcessWithName(const char *process_name,
980                             const ProcessAttachInfo &attach_info) {
981     Status error;
982     error.SetErrorString("attach by name is not supported");
983     return error;
984   }
985 
986   /// Called after attaching a process.
987   ///
988   /// \param[in] process_arch
989   ///     If you can figure out the process architecture after attach, fill it
990   ///     in here.
991   ///
992   /// Allow Process plug-ins to execute some code after attaching to a
993   /// process.
DidAttach(ArchSpec & process_arch)994   virtual void DidAttach(ArchSpec &process_arch) { process_arch.Clear(); }
995 
996   /// Called after a process re-execs itself.
997   ///
998   /// Allow Process plug-ins to execute some code after a process has exec'ed
999   /// itself. Subclasses typically should override DoDidExec() as the
1000   /// lldb_private::Process class needs to remove its dynamic loader, runtime,
1001   /// ABI and other plug-ins, as well as unload all shared libraries.
1002   virtual void DidExec();
1003 
1004   /// Subclasses of Process should implement this function if they need to do
1005   /// anything after a process exec's itself.
DoDidExec()1006   virtual void DoDidExec() {}
1007 
1008   /// Called before launching to a process.
1009   ///
1010   /// Allow Process plug-ins to execute some code before launching a process.
1011   ///
1012   /// \return
1013   ///     Returns an error object.
WillLaunch(Module * module)1014   virtual Status WillLaunch(Module *module) { return Status(); }
1015 
1016   /// Launch a new process.
1017   ///
1018   /// Launch a new process by spawning a new process using \a exe_module's
1019   /// file as the file to launch. Launch details are provided in \a
1020   /// launch_info.
1021   ///
1022   /// \param[in] exe_module
1023   ///     The module from which to extract the file specification and
1024   ///     launch.
1025   ///
1026   /// \param[in] launch_info
1027   ///     Details (e.g. arguments, stdio redirection, etc.) for the
1028   ///     requested launch.
1029   ///
1030   /// \return
1031   ///     An Status instance indicating success or failure of the
1032   ///     operation.
DoLaunch(Module * exe_module,ProcessLaunchInfo & launch_info)1033   virtual Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) {
1034     Status error;
1035     error.SetErrorStringWithFormat(
1036         "error: %s does not support launching processes",
1037         GetPluginName().GetCString());
1038     return error;
1039   }
1040 
1041   /// Called after launching a process.
1042   ///
1043   /// Allow Process plug-ins to execute some code after launching a process.
DidLaunch()1044   virtual void DidLaunch() {}
1045 
1046   /// Called before resuming to a process.
1047   ///
1048   /// Allow Process plug-ins to execute some code before resuming a process.
1049   ///
1050   /// \return
1051   ///     Returns an error object.
WillResume()1052   virtual Status WillResume() { return Status(); }
1053 
1054   /// Resumes all of a process's threads as configured using the Thread run
1055   /// control functions.
1056   ///
1057   /// Threads for a process should be updated with one of the run control
1058   /// actions (resume, step, or suspend) that they should take when the
1059   /// process is resumed. If no run control action is given to a thread it
1060   /// will be resumed by default.
1061   ///
1062   /// \return
1063   ///     Returns \b true if the process successfully resumes using
1064   ///     the thread run control actions, \b false otherwise.
1065   ///
1066   /// \see Thread:Resume()
1067   /// \see Thread:Step()
1068   /// \see Thread:Suspend()
DoResume()1069   virtual Status DoResume() {
1070     Status error;
1071     error.SetErrorStringWithFormat(
1072         "error: %s does not support resuming processes",
1073         GetPluginName().GetCString());
1074     return error;
1075   }
1076 
1077   /// Called after resuming a process.
1078   ///
1079   /// Allow Process plug-ins to execute some code after resuming a process.
DidResume()1080   virtual void DidResume() {}
1081 
1082   /// Called before halting to a process.
1083   ///
1084   /// Allow Process plug-ins to execute some code before halting a process.
1085   ///
1086   /// \return
1087   ///     Returns an error object.
WillHalt()1088   virtual Status WillHalt() { return Status(); }
1089 
1090   /// Halts a running process.
1091   ///
1092   /// DoHalt must produce one and only one stop StateChanged event if it
1093   /// actually stops the process.  If the stop happens through some natural
1094   /// event (for instance a SIGSTOP), then forwarding that event will do.
1095   /// Otherwise, you must generate the event manually. This function is called
1096   /// from the context of the private state thread.
1097   ///
1098   /// \param[out] caused_stop
1099   ///     If true, then this Halt caused the stop, otherwise, the
1100   ///     process was already stopped.
1101   ///
1102   /// \return
1103   ///     Returns \b true if the process successfully halts, \b false
1104   ///     otherwise.
DoHalt(bool & caused_stop)1105   virtual Status DoHalt(bool &caused_stop) {
1106     Status error;
1107     error.SetErrorStringWithFormat(
1108         "error: %s does not support halting processes",
1109         GetPluginName().GetCString());
1110     return error;
1111   }
1112 
1113   /// Called after halting a process.
1114   ///
1115   /// Allow Process plug-ins to execute some code after halting a process.
DidHalt()1116   virtual void DidHalt() {}
1117 
1118   /// Called before detaching from a process.
1119   ///
1120   /// Allow Process plug-ins to execute some code before detaching from a
1121   /// process.
1122   ///
1123   /// \return
1124   ///     Returns an error object.
WillDetach()1125   virtual Status WillDetach() { return Status(); }
1126 
1127   /// Detaches from a running or stopped process.
1128   ///
1129   /// \return
1130   ///     Returns \b true if the process successfully detaches, \b
1131   ///     false otherwise.
DoDetach(bool keep_stopped)1132   virtual Status DoDetach(bool keep_stopped) {
1133     Status error;
1134     error.SetErrorStringWithFormat(
1135         "error: %s does not support detaching from processes",
1136         GetPluginName().GetCString());
1137     return error;
1138   }
1139 
1140   /// Called after detaching from a process.
1141   ///
1142   /// Allow Process plug-ins to execute some code after detaching from a
1143   /// process.
DidDetach()1144   virtual void DidDetach() {}
1145 
DetachRequiresHalt()1146   virtual bool DetachRequiresHalt() { return false; }
1147 
1148   /// Called before sending a signal to a process.
1149   ///
1150   /// Allow Process plug-ins to execute some code before sending a signal to a
1151   /// process.
1152   ///
1153   /// \return
1154   ///     Returns no error if it is safe to proceed with a call to
1155   ///     Process::DoSignal(int), otherwise an error describing what
1156   ///     prevents the signal from being sent.
WillSignal()1157   virtual Status WillSignal() { return Status(); }
1158 
1159   /// Sends a process a UNIX signal \a signal.
1160   ///
1161   /// \return
1162   ///     Returns an error object.
DoSignal(int signal)1163   virtual Status DoSignal(int signal) {
1164     Status error;
1165     error.SetErrorStringWithFormat(
1166         "error: %s does not support sending signals to processes",
1167         GetPluginName().GetCString());
1168     return error;
1169   }
1170 
WillDestroy()1171   virtual Status WillDestroy() { return Status(); }
1172 
1173   virtual Status DoDestroy() = 0;
1174 
DidDestroy()1175   virtual void DidDestroy() {}
1176 
DestroyRequiresHalt()1177   virtual bool DestroyRequiresHalt() { return true; }
1178 
1179   /// Called after sending a signal to a process.
1180   ///
1181   /// Allow Process plug-ins to execute some code after sending a signal to a
1182   /// process.
DidSignal()1183   virtual void DidSignal() {}
1184 
1185   /// Currently called as part of ShouldStop.
1186   /// FIXME: Should really happen when the target stops before the
1187   /// event is taken from the queue...
1188   ///
1189   /// This callback is called as the event
1190   /// is about to be queued up to allow Process plug-ins to execute some code
1191   /// prior to clients being notified that a process was stopped. Common
1192   /// operations include updating the thread list, invalidating any thread
1193   /// state (registers, stack, etc) prior to letting the notification go out.
1194   ///
1195   virtual void RefreshStateAfterStop() = 0;
1196 
1197   /// Sometimes the connection to a process can detect the host OS version
1198   /// that the process is running on. The current platform should be checked
1199   /// first in case the platform is connected, but clients can fall back onto
1200   /// this function if the platform fails to identify the host OS version. The
1201   /// platform should be checked first in case you are running a simulator
1202   /// platform that might itself be running natively, but have different
1203   /// heuristics for figuring out which OS is is emulating.
1204   ///
1205   /// \return
1206   ///     Returns the version tuple of the host OS. In case of failure an empty
1207   ///     VersionTuple is returner.
GetHostOSVersion()1208   virtual llvm::VersionTuple GetHostOSVersion() { return llvm::VersionTuple(); }
1209 
1210   /// \return the macCatalyst version of the host OS.
GetHostMacCatalystVersion()1211   virtual llvm::VersionTuple GetHostMacCatalystVersion() { return {}; }
1212 
1213   /// Get the target object pointer for this module.
1214   ///
1215   /// \return
1216   ///     A Target object pointer to the target that owns this
1217   ///     module.
GetTarget()1218   Target &GetTarget() { return *m_target_wp.lock(); }
1219 
1220   /// Get the const target object pointer for this module.
1221   ///
1222   /// \return
1223   ///     A const Target object pointer to the target that owns this
1224   ///     module.
GetTarget()1225   const Target &GetTarget() const { return *m_target_wp.lock(); }
1226 
1227   /// Flush all data in the process.
1228   ///
1229   /// Flush the memory caches, all threads, and any other cached data in the
1230   /// process.
1231   ///
1232   /// This function can be called after a world changing event like adding a
1233   /// new symbol file, or after the process makes a large context switch (from
1234   /// boot ROM to booted into an OS).
1235   void Flush();
1236 
1237   /// Get accessor for the current process state.
1238   ///
1239   /// \return
1240   ///     The current state of the process.
1241   ///
1242   /// \see lldb::StateType
1243   lldb::StateType GetState();
1244 
1245   lldb::ExpressionResults
1246   RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp,
1247                 const EvaluateExpressionOptions &options,
1248                 DiagnosticManager &diagnostic_manager);
1249 
1250   static const char *ExecutionResultAsCString(lldb::ExpressionResults result);
1251 
1252   void GetStatus(Stream &ostrm);
1253 
1254   size_t GetThreadStatus(Stream &ostrm, bool only_threads_with_stop_reason,
1255                          uint32_t start_frame, uint32_t num_frames,
1256                          uint32_t num_frames_with_source,
1257                          bool stop_format);
1258 
1259   void SendAsyncInterrupt();
1260 
1261   // Notify this process class that modules got loaded.
1262   //
1263   // If subclasses override this method, they must call this version before
1264   // doing anything in the subclass version of the function.
1265   virtual void ModulesDidLoad(ModuleList &module_list);
1266 
1267   /// Retrieve the list of shared libraries that are loaded for this process
1268   /// This method is used on pre-macOS 10.12, pre-iOS 10, pre-tvOS 10, pre-
1269   /// watchOS 3 systems.  The following two methods are for newer versions of
1270   /// those OSes.
1271   ///
1272   /// For certain platforms, the time it takes for the DynamicLoader plugin to
1273   /// read all of the shared libraries out of memory over a slow communication
1274   /// channel may be too long.  In that instance, the gdb-remote stub may be
1275   /// able to retrieve the necessary information about the solibs out of
1276   /// memory and return a concise summary sufficient for the DynamicLoader
1277   /// plugin.
1278   ///
1279   /// \param [in] image_list_address
1280   ///     The address where the table of shared libraries is stored in memory,
1281   ///     if that is appropriate for this platform.  Else this may be
1282   ///     passed as LLDB_INVALID_ADDRESS.
1283   ///
1284   /// \param [in] image_count
1285   ///     The number of shared libraries that are present in this process, if
1286   ///     that is appropriate for this platofrm  Else this may be passed as
1287   ///     LLDB_INVALID_ADDRESS.
1288   ///
1289   /// \return
1290   ///     A StructuredDataSP object which, if non-empty, will contain the
1291   ///     information the DynamicLoader needs to get the initial scan of
1292   ///     solibs resolved.
1293   virtual lldb_private::StructuredData::ObjectSP
GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address,lldb::addr_t image_count)1294   GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address,
1295                                  lldb::addr_t image_count) {
1296     return StructuredData::ObjectSP();
1297   }
1298 
1299   // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1300   // return the full list of loaded shared libraries without needing any input.
1301   virtual lldb_private::StructuredData::ObjectSP
GetLoadedDynamicLibrariesInfos()1302   GetLoadedDynamicLibrariesInfos() {
1303     return StructuredData::ObjectSP();
1304   }
1305 
1306   // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1307   // return information about binaries given their load addresses.
GetLoadedDynamicLibrariesInfos(const std::vector<lldb::addr_t> & load_addresses)1308   virtual lldb_private::StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos(
1309       const std::vector<lldb::addr_t> &load_addresses) {
1310     return StructuredData::ObjectSP();
1311   }
1312 
1313   // Get information about the library shared cache, if that exists
1314   //
1315   // On macOS 10.12, tvOS 10, iOS 10, watchOS 3 and newer, debugserver can
1316   // return information about the library shared cache (a set of standard
1317   // libraries that are loaded at the same location for all processes on a
1318   // system) in use.
GetSharedCacheInfo()1319   virtual lldb_private::StructuredData::ObjectSP GetSharedCacheInfo() {
1320     return StructuredData::ObjectSP();
1321   }
1322 
1323   /// Print a user-visible warning about a module being built with
1324   /// optimization
1325   ///
1326   /// Prints a async warning message to the user one time per Module where a
1327   /// function is found that was compiled with optimization, per Process.
1328   ///
1329   /// \param [in] sc
1330   ///     A SymbolContext with eSymbolContextFunction and eSymbolContextModule
1331   ///     pre-computed.
1332   void PrintWarningOptimization(const SymbolContext &sc);
1333 
1334   /// Print a user-visible warning about a function written in a
1335   /// language that this version of LLDB doesn't support.
1336   ///
1337   /// \see PrintWarningOptimization
1338   void PrintWarningUnsupportedLanguage(const SymbolContext &sc);
1339 
1340   virtual bool GetProcessInfo(ProcessInstanceInfo &info);
1341 
1342   /// Get the exit status for a process.
1343   ///
1344   /// \return
1345   ///     The process's return code, or -1 if the current process
1346   ///     state is not eStateExited.
1347   int GetExitStatus();
1348 
1349   /// Get a textual description of what the process exited.
1350   ///
1351   /// \return
1352   ///     The textual description of why the process exited, or nullptr
1353   ///     if there is no description available.
1354   const char *GetExitDescription();
1355 
DidExit()1356   virtual void DidExit() {}
1357 
1358   /// Get the Modification ID of the process.
1359   ///
1360   /// \return
1361   ///     The modification ID of the process.
GetModID()1362   ProcessModID GetModID() const { return m_mod_id; }
1363 
GetModIDRef()1364   const ProcessModID &GetModIDRef() const { return m_mod_id; }
1365 
GetStopID()1366   uint32_t GetStopID() const { return m_mod_id.GetStopID(); }
1367 
GetResumeID()1368   uint32_t GetResumeID() const { return m_mod_id.GetResumeID(); }
1369 
GetLastUserExpressionResumeID()1370   uint32_t GetLastUserExpressionResumeID() const {
1371     return m_mod_id.GetLastUserExpressionResumeID();
1372   }
1373 
GetLastNaturalStopID()1374   uint32_t GetLastNaturalStopID() const {
1375     return m_mod_id.GetLastNaturalStopID();
1376   }
1377 
GetStopEventForStopID(uint32_t stop_id)1378   lldb::EventSP GetStopEventForStopID(uint32_t stop_id) const {
1379     return m_mod_id.GetStopEventForStopID(stop_id);
1380   }
1381 
1382   /// Set accessor for the process exit status (return code).
1383   ///
1384   /// Sometimes a child exits and the exit can be detected by global functions
1385   /// (signal handler for SIGCHLD for example). This accessor allows the exit
1386   /// status to be set from an external source.
1387   ///
1388   /// Setting this will cause a eStateExited event to be posted to the process
1389   /// event queue.
1390   ///
1391   /// \param[in] exit_status
1392   ///     The value for the process's return code.
1393   ///
1394   /// \see lldb::StateType
1395   virtual bool SetExitStatus(int exit_status, const char *cstr);
1396 
1397   /// Check if a process is still alive.
1398   ///
1399   /// \return
1400   ///     Returns \b true if the process is still valid, \b false
1401   ///     otherwise.
1402   virtual bool IsAlive();
1403 
IsLiveDebugSession()1404   virtual bool IsLiveDebugSession() const { return true; };
1405 
1406   /// Before lldb detaches from a process, it warns the user that they are
1407   /// about to lose their debug session. In some cases, this warning doesn't
1408   /// need to be emitted -- for instance, with core file debugging where the
1409   /// user can reconstruct the "state" by simply re-running the debugger on
1410   /// the core file.
1411   ///
1412   /// \return
1413   ///     Returns \b true if the user should be warned about detaching from
1414   ///     this process.
WarnBeforeDetach()1415   virtual bool WarnBeforeDetach() const { return true; }
1416 
1417   /// Actually do the reading of memory from a process.
1418   ///
1419   /// Subclasses must override this function and can return fewer bytes than
1420   /// requested when memory requests are too large. This class will break up
1421   /// the memory requests and keep advancing the arguments along as needed.
1422   ///
1423   /// \param[in] vm_addr
1424   ///     A virtual load address that indicates where to start reading
1425   ///     memory from.
1426   ///
1427   /// \param[in] size
1428   ///     The number of bytes to read.
1429   ///
1430   /// \param[out] buf
1431   ///     A byte buffer that is at least \a size bytes long that
1432   ///     will receive the memory bytes.
1433   ///
1434   /// \param[out] error
1435   ///     An error that indicates the success or failure of this
1436   ///     operation. If error indicates success (error.Success()),
1437   ///     then the value returned can be trusted, otherwise zero
1438   ///     will be returned.
1439   ///
1440   /// \return
1441   ///     The number of bytes that were actually read into \a buf.
1442   ///     Zero is returned in the case of an error.
1443   virtual size_t DoReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1444                               Status &error) = 0;
1445 
1446   /// Read of memory from a process.
1447   ///
1448   /// This function will read memory from the current process's address space
1449   /// and remove any traps that may have been inserted into the memory.
1450   ///
1451   /// This function is not meant to be overridden by Process subclasses, the
1452   /// subclasses should implement Process::DoReadMemory (lldb::addr_t, size_t,
1453   /// void *).
1454   ///
1455   /// \param[in] vm_addr
1456   ///     A virtual load address that indicates where to start reading
1457   ///     memory from.
1458   ///
1459   /// \param[out] buf
1460   ///     A byte buffer that is at least \a size bytes long that
1461   ///     will receive the memory bytes.
1462   ///
1463   /// \param[in] size
1464   ///     The number of bytes to read.
1465   ///
1466   /// \param[out] error
1467   ///     An error that indicates the success or failure of this
1468   ///     operation. If error indicates success (error.Success()),
1469   ///     then the value returned can be trusted, otherwise zero
1470   ///     will be returned.
1471   ///
1472   /// \return
1473   ///     The number of bytes that were actually read into \a buf. If
1474   ///     the returned number is greater than zero, yet less than \a
1475   ///     size, then this function will get called again with \a
1476   ///     vm_addr, \a buf, and \a size updated appropriately. Zero is
1477   ///     returned in the case of an error.
1478   virtual size_t ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
1479                             Status &error);
1480 
1481   /// Read of memory from a process.
1482   ///
1483   /// This function has the same semantics of ReadMemory except that it
1484   /// bypasses caching.
1485   ///
1486   /// \param[in] vm_addr
1487   ///     A virtual load address that indicates where to start reading
1488   ///     memory from.
1489   ///
1490   /// \param[out] buf
1491   ///     A byte buffer that is at least \a size bytes long that
1492   ///     will receive the memory bytes.
1493   ///
1494   /// \param[in] size
1495   ///     The number of bytes to read.
1496   ///
1497   /// \param[out] error
1498   ///     An error that indicates the success or failure of this
1499   ///     operation. If error indicates success (error.Success()),
1500   ///     then the value returned can be trusted, otherwise zero
1501   ///     will be returned.
1502   ///
1503   /// \return
1504   ///     The number of bytes that were actually read into \a buf. If
1505   ///     the returned number is greater than zero, yet less than \a
1506   ///     size, then this function will get called again with \a
1507   ///     vm_addr, \a buf, and \a size updated appropriately. Zero is
1508   ///     returned in the case of an error.
1509   size_t ReadMemoryFromInferior(lldb::addr_t vm_addr, void *buf, size_t size,
1510                                 Status &error);
1511 
1512   /// Read a NULL terminated string from memory
1513   ///
1514   /// This function will read a cache page at a time until a NULL string
1515   /// terminator is found. It will stop reading if an aligned sequence of NULL
1516   /// termination \a type_width bytes is not found before reading \a
1517   /// cstr_max_len bytes.  The results are always guaranteed to be NULL
1518   /// terminated, and that no more than (max_bytes - type_width) bytes will be
1519   /// read.
1520   ///
1521   /// \param[in] vm_addr
1522   ///     The virtual load address to start the memory read.
1523   ///
1524   /// \param[in] str
1525   ///     A character buffer containing at least max_bytes.
1526   ///
1527   /// \param[in] max_bytes
1528   ///     The maximum number of bytes to read.
1529   ///
1530   /// \param[in] error
1531   ///     The error status of the read operation.
1532   ///
1533   /// \param[in] type_width
1534   ///     The size of the null terminator (1 to 4 bytes per
1535   ///     character).  Defaults to 1.
1536   ///
1537   /// \return
1538   ///     The error status or the number of bytes prior to the null terminator.
1539   size_t ReadStringFromMemory(lldb::addr_t vm_addr, char *str, size_t max_bytes,
1540                               Status &error, size_t type_width = 1);
1541 
1542   /// Read a NULL terminated C string from memory
1543   ///
1544   /// This function will read a cache page at a time until the NULL
1545   /// C string terminator is found. It will stop reading if the NULL
1546   /// termination byte isn't found before reading \a cstr_max_len bytes, and
1547   /// the results are always guaranteed to be NULL terminated (at most
1548   /// cstr_max_len - 1 bytes will be read).
1549   size_t ReadCStringFromMemory(lldb::addr_t vm_addr, char *cstr,
1550                                size_t cstr_max_len, Status &error);
1551 
1552   size_t ReadCStringFromMemory(lldb::addr_t vm_addr, std::string &out_str,
1553                                Status &error);
1554 
1555   /// Reads an unsigned integer of the specified byte size from process
1556   /// memory.
1557   ///
1558   /// \param[in] load_addr
1559   ///     A load address of the integer to read.
1560   ///
1561   /// \param[in] byte_size
1562   ///     The size in byte of the integer to read.
1563   ///
1564   /// \param[in] fail_value
1565   ///     The value to return if we fail to read an integer.
1566   ///
1567   /// \param[out] error
1568   ///     An error that indicates the success or failure of this
1569   ///     operation. If error indicates success (error.Success()),
1570   ///     then the value returned can be trusted, otherwise zero
1571   ///     will be returned.
1572   ///
1573   /// \return
1574   ///     The unsigned integer that was read from the process memory
1575   ///     space. If the integer was smaller than a uint64_t, any
1576   ///     unused upper bytes will be zero filled. If the process
1577   ///     byte order differs from the host byte order, the integer
1578   ///     value will be appropriately byte swapped into host byte
1579   ///     order.
1580   uint64_t ReadUnsignedIntegerFromMemory(lldb::addr_t load_addr,
1581                                          size_t byte_size, uint64_t fail_value,
1582                                          Status &error);
1583 
1584   int64_t ReadSignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size,
1585                                       int64_t fail_value, Status &error);
1586 
1587   lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error);
1588 
1589   bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
1590                             Status &error);
1591 
1592   /// Actually do the writing of memory to a process.
1593   ///
1594   /// \param[in] vm_addr
1595   ///     A virtual load address that indicates where to start writing
1596   ///     memory to.
1597   ///
1598   /// \param[in] buf
1599   ///     A byte buffer that is at least \a size bytes long that
1600   ///     contains the data to write.
1601   ///
1602   /// \param[in] size
1603   ///     The number of bytes to write.
1604   ///
1605   /// \param[out] error
1606   ///     An error value in case the memory write fails.
1607   ///
1608   /// \return
1609   ///     The number of bytes that were actually written.
DoWriteMemory(lldb::addr_t vm_addr,const void * buf,size_t size,Status & error)1610   virtual size_t DoWriteMemory(lldb::addr_t vm_addr, const void *buf,
1611                                size_t size, Status &error) {
1612     error.SetErrorStringWithFormat(
1613         "error: %s does not support writing to processes",
1614         GetPluginName().GetCString());
1615     return 0;
1616   }
1617 
1618   /// Write all or part of a scalar value to memory.
1619   ///
1620   /// The value contained in \a scalar will be swapped to match the byte order
1621   /// of the process that is being debugged. If \a size is less than the size
1622   /// of scalar, the least significant \a size bytes from scalar will be
1623   /// written. If \a size is larger than the byte size of scalar, then the
1624   /// extra space will be padded with zeros and the scalar value will be
1625   /// placed in the least significant bytes in memory.
1626   ///
1627   /// \param[in] vm_addr
1628   ///     A virtual load address that indicates where to start writing
1629   ///     memory to.
1630   ///
1631   /// \param[in] scalar
1632   ///     The scalar to write to the debugged process.
1633   ///
1634   /// \param[in] size
1635   ///     This value can be smaller or larger than the scalar value
1636   ///     itself. If \a size is smaller than the size of \a scalar,
1637   ///     the least significant bytes in \a scalar will be used. If
1638   ///     \a size is larger than the byte size of \a scalar, then
1639   ///     the extra space will be padded with zeros. If \a size is
1640   ///     set to UINT32_MAX, then the size of \a scalar will be used.
1641   ///
1642   /// \param[out] error
1643   ///     An error value in case the memory write fails.
1644   ///
1645   /// \return
1646   ///     The number of bytes that were actually written.
1647   size_t WriteScalarToMemory(lldb::addr_t vm_addr, const Scalar &scalar,
1648                              size_t size, Status &error);
1649 
1650   size_t ReadScalarIntegerFromMemory(lldb::addr_t addr, uint32_t byte_size,
1651                                      bool is_signed, Scalar &scalar,
1652                                      Status &error);
1653 
1654   /// Write memory to a process.
1655   ///
1656   /// This function will write memory to the current process's address space
1657   /// and maintain any traps that might be present due to software
1658   /// breakpoints.
1659   ///
1660   /// This function is not meant to be overridden by Process subclasses, the
1661   /// subclasses should implement Process::DoWriteMemory (lldb::addr_t,
1662   /// size_t, void *).
1663   ///
1664   /// \param[in] vm_addr
1665   ///     A virtual load address that indicates where to start writing
1666   ///     memory to.
1667   ///
1668   /// \param[in] buf
1669   ///     A byte buffer that is at least \a size bytes long that
1670   ///     contains the data to write.
1671   ///
1672   /// \param[in] size
1673   ///     The number of bytes to write.
1674   ///
1675   /// \return
1676   ///     The number of bytes that were actually written.
1677   // TODO: change this to take an ArrayRef<uint8_t>
1678   size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
1679                      Status &error);
1680 
1681   /// Actually allocate memory in the process.
1682   ///
1683   /// This function will allocate memory in the process's address space.  This
1684   /// can't rely on the generic function calling mechanism, since that
1685   /// requires this function.
1686   ///
1687   /// \param[in] size
1688   ///     The size of the allocation requested.
1689   ///
1690   /// \return
1691   ///     The address of the allocated buffer in the process, or
1692   ///     LLDB_INVALID_ADDRESS if the allocation failed.
1693 
DoAllocateMemory(size_t size,uint32_t permissions,Status & error)1694   virtual lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions,
1695                                         Status &error) {
1696     error.SetErrorStringWithFormat(
1697         "error: %s does not support allocating in the debug process",
1698         GetPluginName().GetCString());
1699     return LLDB_INVALID_ADDRESS;
1700   }
1701 
1702   virtual Status WriteObjectFile(std::vector<ObjectFile::LoadableData> entries);
1703 
1704   /// The public interface to allocating memory in the process.
1705   ///
1706   /// This function will allocate memory in the process's address space.  This
1707   /// can't rely on the generic function calling mechanism, since that
1708   /// requires this function.
1709   ///
1710   /// \param[in] size
1711   ///     The size of the allocation requested.
1712   ///
1713   /// \param[in] permissions
1714   ///     Or together any of the lldb::Permissions bits.  The permissions on
1715   ///     a given memory allocation can't be changed after allocation.  Note
1716   ///     that a block that isn't set writable can still be written on from
1717   ///     lldb,
1718   ///     just not by the process itself.
1719   ///
1720   /// \param[in,out] error
1721   ///     An error object to fill in if things go wrong.
1722   /// \return
1723   ///     The address of the allocated buffer in the process, or
1724   ///     LLDB_INVALID_ADDRESS if the allocation failed.
1725   lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error);
1726 
1727   /// The public interface to allocating memory in the process, this also
1728   /// clears the allocated memory.
1729   ///
1730   /// This function will allocate memory in the process's address space.  This
1731   /// can't rely on the generic function calling mechanism, since that
1732   /// requires this function.
1733   ///
1734   /// \param[in] size
1735   ///     The size of the allocation requested.
1736   ///
1737   /// \param[in] permissions
1738   ///     Or together any of the lldb::Permissions bits.  The permissions on
1739   ///     a given memory allocation can't be changed after allocation.  Note
1740   ///     that a block that isn't set writable can still be written on from
1741   ///     lldb,
1742   ///     just not by the process itself.
1743   ///
1744   /// \param[in,out] error
1745   ///     An error object to fill in if things go wrong.
1746   ///
1747   /// \return
1748   ///     The address of the allocated buffer in the process, or
1749   ///     LLDB_INVALID_ADDRESS if the allocation failed.
1750 
1751   lldb::addr_t CallocateMemory(size_t size, uint32_t permissions,
1752                                Status &error);
1753 
1754   /// Resolve dynamically loaded indirect functions.
1755   ///
1756   /// \param[in] address
1757   ///     The load address of the indirect function to resolve.
1758   ///
1759   /// \param[out] error
1760   ///     An error value in case the resolve fails.
1761   ///
1762   /// \return
1763   ///     The address of the resolved function.
1764   ///     LLDB_INVALID_ADDRESS if the resolution failed.
1765   virtual lldb::addr_t ResolveIndirectFunction(const Address *address,
1766                                                Status &error);
1767 
1768   /// Locate the memory region that contains load_addr.
1769   ///
1770   /// If load_addr is within the address space the process has mapped
1771   /// range_info will be filled in with the start and end of that range as
1772   /// well as the permissions for that range and range_info.GetMapped will
1773   /// return true.
1774   ///
1775   /// If load_addr is outside any mapped region then range_info will have its
1776   /// start address set to load_addr and the end of the range will indicate
1777   /// the start of the next mapped range or be set to LLDB_INVALID_ADDRESS if
1778   /// there are no valid mapped ranges between load_addr and the end of the
1779   /// process address space.
1780   ///
1781   /// GetMemoryRegionInfo will only return an error if it is unimplemented for
1782   /// the current process.
1783   ///
1784   /// \param[in] load_addr
1785   ///     The load address to query the range_info for.
1786   ///
1787   /// \param[out] range_info
1788   ///     An range_info value containing the details of the range.
1789   ///
1790   /// \return
1791   ///     An error value.
GetMemoryRegionInfo(lldb::addr_t load_addr,MemoryRegionInfo & range_info)1792   virtual Status GetMemoryRegionInfo(lldb::addr_t load_addr,
1793                                      MemoryRegionInfo &range_info) {
1794     Status error;
1795     error.SetErrorString("Process::GetMemoryRegionInfo() not supported");
1796     return error;
1797   }
1798 
1799   /// Obtain all the mapped memory regions within this process.
1800   ///
1801   /// \param[out] region_list
1802   ///     A vector to contain MemoryRegionInfo objects for all mapped
1803   ///     ranges.
1804   ///
1805   /// \return
1806   ///     An error value.
1807   virtual Status
1808   GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list);
1809 
GetWatchpointSupportInfo(uint32_t & num)1810   virtual Status GetWatchpointSupportInfo(uint32_t &num) {
1811     Status error;
1812     num = 0;
1813     error.SetErrorString("Process::GetWatchpointSupportInfo() not supported");
1814     return error;
1815   }
1816 
GetWatchpointSupportInfo(uint32_t & num,bool & after)1817   virtual Status GetWatchpointSupportInfo(uint32_t &num, bool &after) {
1818     Status error;
1819     num = 0;
1820     after = true;
1821     error.SetErrorString("Process::GetWatchpointSupportInfo() not supported");
1822     return error;
1823   }
1824 
1825   lldb::ModuleSP ReadModuleFromMemory(const FileSpec &file_spec,
1826                                       lldb::addr_t header_addr,
1827                                       size_t size_to_read = 512);
1828 
1829   /// Attempt to get the attributes for a region of memory in the process.
1830   ///
1831   /// It may be possible for the remote debug server to inspect attributes for
1832   /// a region of memory in the process, such as whether there is a valid page
1833   /// of memory at a given address or whether that page is
1834   /// readable/writable/executable by the process.
1835   ///
1836   /// \param[in] load_addr
1837   ///     The address of interest in the process.
1838   ///
1839   /// \param[out] permissions
1840   ///     If this call returns successfully, this bitmask will have
1841   ///     its Permissions bits set to indicate whether the region is
1842   ///     readable/writable/executable.  If this call fails, the
1843   ///     bitmask values are undefined.
1844   ///
1845   /// \return
1846   ///     Returns true if it was able to determine the attributes of the
1847   ///     memory region.  False if not.
1848   virtual bool GetLoadAddressPermissions(lldb::addr_t load_addr,
1849                                          uint32_t &permissions);
1850 
1851   /// Determines whether executing JIT-compiled code in this process is
1852   /// possible.
1853   ///
1854   /// \return
1855   ///     True if execution of JIT code is possible; false otherwise.
1856   bool CanJIT();
1857 
1858   /// Sets whether executing JIT-compiled code in this process is possible.
1859   ///
1860   /// \param[in] can_jit
1861   ///     True if execution of JIT code is possible; false otherwise.
1862   void SetCanJIT(bool can_jit);
1863 
1864   /// Determines whether executing function calls using the interpreter is
1865   /// possible for this process.
1866   ///
1867   /// \return
1868   ///     True if possible; false otherwise.
CanInterpretFunctionCalls()1869   bool CanInterpretFunctionCalls() { return m_can_interpret_function_calls; }
1870 
1871   /// Sets whether executing function calls using the interpreter is possible
1872   /// for this process.
1873   ///
1874   /// \param[in] can_interpret_function_calls
1875   ///     True if possible; false otherwise.
SetCanInterpretFunctionCalls(bool can_interpret_function_calls)1876   void SetCanInterpretFunctionCalls(bool can_interpret_function_calls) {
1877     m_can_interpret_function_calls = can_interpret_function_calls;
1878   }
1879 
1880   /// Sets whether executing code in this process is possible. This could be
1881   /// either through JIT or interpreting.
1882   ///
1883   /// \param[in] can_run_code
1884   ///     True if execution of code is possible; false otherwise.
1885   void SetCanRunCode(bool can_run_code);
1886 
1887   /// Actually deallocate memory in the process.
1888   ///
1889   /// This function will deallocate memory in the process's address space that
1890   /// was allocated with AllocateMemory.
1891   ///
1892   /// \param[in] ptr
1893   ///     A return value from AllocateMemory, pointing to the memory you
1894   ///     want to deallocate.
1895   ///
1896   /// \return
1897   ///     \btrue if the memory was deallocated, \bfalse otherwise.
DoDeallocateMemory(lldb::addr_t ptr)1898   virtual Status DoDeallocateMemory(lldb::addr_t ptr) {
1899     Status error;
1900     error.SetErrorStringWithFormat(
1901         "error: %s does not support deallocating in the debug process",
1902         GetPluginName().GetCString());
1903     return error;
1904   }
1905 
1906   /// The public interface to deallocating memory in the process.
1907   ///
1908   /// This function will deallocate memory in the process's address space that
1909   /// was allocated with AllocateMemory.
1910   ///
1911   /// \param[in] ptr
1912   ///     A return value from AllocateMemory, pointing to the memory you
1913   ///     want to deallocate.
1914   ///
1915   /// \return
1916   ///     \btrue if the memory was deallocated, \bfalse otherwise.
1917   Status DeallocateMemory(lldb::addr_t ptr);
1918 
1919   /// Get any available STDOUT.
1920   ///
1921   /// Calling this method is a valid operation only if all of the following
1922   /// conditions are true: 1) The process was launched, and not attached to.
1923   /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 3) The
1924   /// process was launched without supplying a valid file path
1925   ///    for STDOUT.
1926   ///
1927   /// Note that the implementation will probably need to start a read thread
1928   /// in the background to make sure that the pipe is drained and the STDOUT
1929   /// buffered appropriately, to prevent the process from deadlocking trying
1930   /// to write to a full buffer.
1931   ///
1932   /// Events will be queued indicating that there is STDOUT available that can
1933   /// be retrieved using this function.
1934   ///
1935   /// \param[out] buf
1936   ///     A buffer that will receive any STDOUT bytes that are
1937   ///     currently available.
1938   ///
1939   /// \param[in] buf_size
1940   ///     The size in bytes for the buffer \a buf.
1941   ///
1942   /// \return
1943   ///     The number of bytes written into \a buf. If this value is
1944   ///     equal to \a buf_size, another call to this function should
1945   ///     be made to retrieve more STDOUT data.
1946   virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error);
1947 
1948   /// Get any available STDERR.
1949   ///
1950   /// Calling this method is a valid operation only if all of the following
1951   /// conditions are true: 1) The process was launched, and not attached to.
1952   /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 3) The
1953   /// process was launched without supplying a valid file path
1954   ///    for STDERR.
1955   ///
1956   /// Note that the implementation will probably need to start a read thread
1957   /// in the background to make sure that the pipe is drained and the STDERR
1958   /// buffered appropriately, to prevent the process from deadlocking trying
1959   /// to write to a full buffer.
1960   ///
1961   /// Events will be queued indicating that there is STDERR available that can
1962   /// be retrieved using this function.
1963   ///
1964   /// \param[in] buf
1965   ///     A buffer that will receive any STDERR bytes that are
1966   ///     currently available.
1967   ///
1968   /// \param[out] buf_size
1969   ///     The size in bytes for the buffer \a buf.
1970   ///
1971   /// \return
1972   ///     The number of bytes written into \a buf. If this value is
1973   ///     equal to \a buf_size, another call to this function should
1974   ///     be made to retrieve more STDERR data.
1975   virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error);
1976 
1977   /// Puts data into this process's STDIN.
1978   ///
1979   /// Calling this method is a valid operation only if all of the following
1980   /// conditions are true: 1) The process was launched, and not attached to.
1981   /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 3) The
1982   /// process was launched without supplying a valid file path
1983   ///    for STDIN.
1984   ///
1985   /// \param[in] buf
1986   ///     A buffer that contains the data to write to the process's STDIN.
1987   ///
1988   /// \param[in] buf_size
1989   ///     The size in bytes for the buffer \a buf.
1990   ///
1991   /// \return
1992   ///     The number of bytes written into \a buf. If this value is
1993   ///     less than \a buf_size, another call to this function should
1994   ///     be made to write the rest of the data.
PutSTDIN(const char * buf,size_t buf_size,Status & error)1995   virtual size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) {
1996     error.SetErrorString("stdin unsupported");
1997     return 0;
1998   }
1999 
2000   /// Get any available profile data.
2001   ///
2002   /// \param[out] buf
2003   ///     A buffer that will receive any profile data bytes that are
2004   ///     currently available.
2005   ///
2006   /// \param[out] buf_size
2007   ///     The size in bytes for the buffer \a buf.
2008   ///
2009   /// \return
2010   ///     The number of bytes written into \a buf. If this value is
2011   ///     equal to \a buf_size, another call to this function should
2012   ///     be made to retrieve more profile data.
2013   virtual size_t GetAsyncProfileData(char *buf, size_t buf_size, Status &error);
2014 
2015   // Process Breakpoints
2016   size_t GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site);
2017 
EnableBreakpointSite(BreakpointSite * bp_site)2018   virtual Status EnableBreakpointSite(BreakpointSite *bp_site) {
2019     Status error;
2020     error.SetErrorStringWithFormat(
2021         "error: %s does not support enabling breakpoints",
2022         GetPluginName().GetCString());
2023     return error;
2024   }
2025 
DisableBreakpointSite(BreakpointSite * bp_site)2026   virtual Status DisableBreakpointSite(BreakpointSite *bp_site) {
2027     Status error;
2028     error.SetErrorStringWithFormat(
2029         "error: %s does not support disabling breakpoints",
2030         GetPluginName().GetCString());
2031     return error;
2032   }
2033 
2034   // This is implemented completely using the lldb::Process API. Subclasses
2035   // don't need to implement this function unless the standard flow of read
2036   // existing opcode, write breakpoint opcode, verify breakpoint opcode doesn't
2037   // work for a specific process plug-in.
2038   virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site);
2039 
2040   // This is implemented completely using the lldb::Process API. Subclasses
2041   // don't need to implement this function unless the standard flow of
2042   // restoring original opcode in memory and verifying the restored opcode
2043   // doesn't work for a specific process plug-in.
2044   virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site);
2045 
2046   BreakpointSiteList &GetBreakpointSiteList();
2047 
2048   const BreakpointSiteList &GetBreakpointSiteList() const;
2049 
2050   void DisableAllBreakpointSites();
2051 
2052   Status ClearBreakpointSiteByID(lldb::user_id_t break_id);
2053 
2054   lldb::break_id_t CreateBreakpointSite(const lldb::BreakpointLocationSP &owner,
2055                                         bool use_hardware);
2056 
2057   Status DisableBreakpointSiteByID(lldb::user_id_t break_id);
2058 
2059   Status EnableBreakpointSiteByID(lldb::user_id_t break_id);
2060 
2061   // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove themselves
2062   // from the owner's list of this breakpoint sites.
2063   void RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
2064                                      lldb::user_id_t owner_loc_id,
2065                                      lldb::BreakpointSiteSP &bp_site_sp);
2066 
2067   // Process Watchpoints (optional)
2068   virtual Status EnableWatchpoint(Watchpoint *wp, bool notify = true);
2069 
2070   virtual Status DisableWatchpoint(Watchpoint *wp, bool notify = true);
2071 
2072   // Thread Queries
2073   virtual bool UpdateThreadList(ThreadList &old_thread_list,
2074                                 ThreadList &new_thread_list) = 0;
2075 
2076   void UpdateThreadListIfNeeded();
2077 
GetThreadList()2078   ThreadList &GetThreadList() { return m_thread_list; }
2079 
2080   // When ExtendedBacktraces are requested, the HistoryThreads that are created
2081   // need an owner -- they're saved here in the Process.  The threads in this
2082   // list are not iterated over - driver programs need to request the extended
2083   // backtrace calls starting from a root concrete thread one by one.
GetExtendedThreadList()2084   ThreadList &GetExtendedThreadList() { return m_extended_thread_list; }
2085 
Threads()2086   ThreadList::ThreadIterable Threads() { return m_thread_list.Threads(); }
2087 
2088   uint32_t GetNextThreadIndexID(uint64_t thread_id);
2089 
2090   lldb::ThreadSP CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context);
2091 
2092   // Returns true if an index id has been assigned to a thread.
2093   bool HasAssignedIndexIDToThread(uint64_t sb_thread_id);
2094 
2095   // Given a thread_id, it will assign a more reasonable index id for display
2096   // to the user. If the thread_id has previously been assigned, the same index
2097   // id will be used.
2098   uint32_t AssignIndexIDToThread(uint64_t thread_id);
2099 
2100   // Queue Queries
2101 
2102   void UpdateQueueListIfNeeded();
2103 
GetQueueList()2104   QueueList &GetQueueList() {
2105     UpdateQueueListIfNeeded();
2106     return m_queue_list;
2107   }
2108 
Queues()2109   QueueList::QueueIterable Queues() {
2110     UpdateQueueListIfNeeded();
2111     return m_queue_list.Queues();
2112   }
2113 
2114   // Event Handling
2115   lldb::StateType GetNextEvent(lldb::EventSP &event_sp);
2116 
2117   // Returns the process state when it is stopped. If specified, event_sp_ptr
2118   // is set to the event which triggered the stop. If wait_always = false, and
2119   // the process is already stopped, this function returns immediately. If the
2120   // process is hijacked and use_run_lock is true (the default), then this
2121   // function releases the run lock after the stop. Setting use_run_lock to
2122   // false will avoid this behavior.
2123   lldb::StateType
2124   WaitForProcessToStop(const Timeout<std::micro> &timeout,
2125                        lldb::EventSP *event_sp_ptr = nullptr,
2126                        bool wait_always = true,
2127                        lldb::ListenerSP hijack_listener = lldb::ListenerSP(),
2128                        Stream *stream = nullptr, bool use_run_lock = true);
2129 
GetIOHandlerID()2130   uint32_t GetIOHandlerID() const { return m_iohandler_sync.GetValue(); }
2131 
2132   /// Waits for the process state to be running within a given msec timeout.
2133   ///
2134   /// The main purpose of this is to implement an interlock waiting for
2135   /// HandlePrivateEvent to push an IOHandler.
2136   ///
2137   /// \param[in] timeout
2138   ///     The maximum time length to wait for the process to transition to the
2139   ///     eStateRunning state.
2140   void SyncIOHandler(uint32_t iohandler_id, const Timeout<std::micro> &timeout);
2141 
2142   lldb::StateType GetStateChangedEvents(
2143       lldb::EventSP &event_sp, const Timeout<std::micro> &timeout,
2144       lldb::ListenerSP
2145           hijack_listener); // Pass an empty ListenerSP to use builtin listener
2146 
2147   /// Centralize the code that handles and prints descriptions for process
2148   /// state changes.
2149   ///
2150   /// \param[in] event_sp
2151   ///     The process state changed event
2152   ///
2153   /// \param[in] stream
2154   ///     The output stream to get the state change description
2155   ///
2156   /// \param[in,out] pop_process_io_handler
2157   ///     If this value comes in set to \b true, then pop the Process IOHandler
2158   ///     if needed.
2159   ///     Else this variable will be set to \b true or \b false to indicate if
2160   ///     the process
2161   ///     needs to have its process IOHandler popped.
2162   ///
2163   /// \return
2164   ///     \b true if the event describes a process state changed event, \b false
2165   ///     otherwise.
2166   static bool HandleProcessStateChangedEvent(const lldb::EventSP &event_sp,
2167                                              Stream *stream,
2168                                              bool &pop_process_io_handler);
2169 
2170   Event *PeekAtStateChangedEvents();
2171 
2172   class ProcessEventHijacker {
2173   public:
ProcessEventHijacker(Process & process,lldb::ListenerSP listener_sp)2174     ProcessEventHijacker(Process &process, lldb::ListenerSP listener_sp)
2175         : m_process(process) {
2176       m_process.HijackProcessEvents(std::move(listener_sp));
2177     }
2178 
~ProcessEventHijacker()2179     ~ProcessEventHijacker() { m_process.RestoreProcessEvents(); }
2180 
2181   private:
2182     Process &m_process;
2183   };
2184 
2185   friend class ProcessEventHijacker;
2186   friend class ProcessProperties;
2187   /// If you need to ensure that you and only you will hear about some public
2188   /// event, then make a new listener, set to listen to process events, and
2189   /// then call this with that listener.  Then you will have to wait on that
2190   /// listener explicitly for events (rather than using the GetNextEvent &
2191   /// WaitFor* calls above.  Be sure to call RestoreProcessEvents when you are
2192   /// done.
2193   ///
2194   /// \param[in] listener_sp
2195   ///     This is the new listener to whom all process events will be delivered.
2196   ///
2197   /// \return
2198   ///     Returns \b true if the new listener could be installed,
2199   ///     \b false otherwise.
2200   bool HijackProcessEvents(lldb::ListenerSP listener_sp);
2201 
2202   /// Restores the process event broadcasting to its normal state.
2203   ///
2204   void RestoreProcessEvents();
2205 
2206   bool StateChangedIsHijackedForSynchronousResume();
2207 
2208   bool StateChangedIsExternallyHijacked();
2209 
2210   const lldb::ABISP &GetABI();
2211 
GetOperatingSystem()2212   OperatingSystem *GetOperatingSystem() { return m_os_up.get(); }
2213 
2214   std::vector<LanguageRuntime *> GetLanguageRuntimes();
2215 
2216   LanguageRuntime *GetLanguageRuntime(lldb::LanguageType language);
2217 
2218   bool IsPossibleDynamicValue(ValueObject &in_value);
2219 
2220   bool IsRunning() const;
2221 
GetDynamicCheckers()2222   DynamicCheckerFunctions *GetDynamicCheckers() {
2223     return m_dynamic_checkers_up.get();
2224   }
2225 
2226   void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers);
2227 
2228 /// Prune ThreadPlanStacks for unreported threads.
2229 ///
2230 /// \param[in] tid
2231 ///     The tid whose Plan Stack we are seeking to prune.
2232 ///
2233 /// \return
2234 ///     \b true if the TID is found or \b false if not.
2235 bool PruneThreadPlansForTID(lldb::tid_t tid);
2236 
2237 /// Prune ThreadPlanStacks for all unreported threads.
2238 void PruneThreadPlans();
2239 
2240   /// Find the thread plan stack associated with thread with \a tid.
2241   ///
2242   /// \param[in] tid
2243   ///     The tid whose Plan Stack we are seeking.
2244   ///
2245   /// \return
2246   ///     Returns a ThreadPlan if the TID is found or nullptr if not.
2247   ThreadPlanStack *FindThreadPlans(lldb::tid_t tid);
2248 
2249   /// Dump the thread plans associated with thread with \a tid.
2250   ///
2251   /// \param[in,out] strm
2252   ///     The stream to which to dump the output
2253   ///
2254   /// \param[in] tid
2255   ///     The tid whose Plan Stack we are dumping
2256   ///
2257   /// \param[in] desc_level
2258   ///     How much detail to dump
2259   ///
2260   /// \param[in] internal
2261   ///     If \b true dump all plans, if false only user initiated plans
2262   ///
2263   /// \param[in] condense_trivial
2264   ///     If true, only dump a header if the plan stack is just the base plan.
2265   ///
2266   /// \param[in] skip_unreported_plans
2267   ///     If true, only dump a plan if it is currently backed by an
2268   ///     lldb_private::Thread *.
2269   ///
2270   /// \return
2271   ///     Returns \b true if TID was found, \b false otherwise
2272   bool DumpThreadPlansForTID(Stream &strm, lldb::tid_t tid,
2273                              lldb::DescriptionLevel desc_level, bool internal,
2274                              bool condense_trivial, bool skip_unreported_plans);
2275 
2276   /// Dump all the thread plans for this process.
2277   ///
2278   /// \param[in,out] strm
2279   ///     The stream to which to dump the output
2280   ///
2281   /// \param[in] desc_level
2282   ///     How much detail to dump
2283   ///
2284   /// \param[in] internal
2285   ///     If \b true dump all plans, if false only user initiated plans
2286   ///
2287   /// \param[in] condense_trivial
2288   ///     If true, only dump a header if the plan stack is just the base plan.
2289   ///
2290   /// \param[in] skip_unreported_plans
2291   ///     If true, skip printing all thread plan stacks that don't currently
2292   ///     have a backing lldb_private::Thread *.
2293   void DumpThreadPlans(Stream &strm, lldb::DescriptionLevel desc_level,
2294                        bool internal, bool condense_trivial,
2295                        bool skip_unreported_plans);
2296 
2297   /// Call this to set the lldb in the mode where it breaks on new thread
2298   /// creations, and then auto-restarts.  This is useful when you are trying
2299   /// to run only one thread, but either that thread or the kernel is creating
2300   /// new threads in the process.  If you stop when the thread is created, you
2301   /// can immediately suspend it, and keep executing only the one thread you
2302   /// intend.
2303   ///
2304   /// \return
2305   ///     Returns \b true if we were able to start up the notification
2306   ///     \b false otherwise.
StartNoticingNewThreads()2307   virtual bool StartNoticingNewThreads() { return true; }
2308 
2309   /// Call this to turn off the stop & notice new threads mode.
2310   ///
2311   /// \return
2312   ///     Returns \b true if we were able to start up the notification
2313   ///     \b false otherwise.
StopNoticingNewThreads()2314   virtual bool StopNoticingNewThreads() { return true; }
2315 
2316   void SetRunningUserExpression(bool on);
2317   void SetRunningUtilityFunction(bool on);
2318 
2319   // lldb::ExecutionContextScope pure virtual functions
2320   lldb::TargetSP CalculateTarget() override;
2321 
CalculateProcess()2322   lldb::ProcessSP CalculateProcess() override { return shared_from_this(); }
2323 
CalculateThread()2324   lldb::ThreadSP CalculateThread() override { return lldb::ThreadSP(); }
2325 
CalculateStackFrame()2326   lldb::StackFrameSP CalculateStackFrame() override {
2327     return lldb::StackFrameSP();
2328   }
2329 
2330   void CalculateExecutionContext(ExecutionContext &exe_ctx) override;
2331 
2332   void SetSTDIOFileDescriptor(int file_descriptor);
2333 
2334   // Add a permanent region of memory that should never be read or written to.
2335   // This can be used to ensure that memory reads or writes to certain areas of
2336   // memory never end up being sent to the DoReadMemory or DoWriteMemory
2337   // functions which can improve performance.
2338   void AddInvalidMemoryRegion(const LoadRange &region);
2339 
2340   // Remove a permanent region of memory that should never be read or written
2341   // to that was previously added with AddInvalidMemoryRegion.
2342   bool RemoveInvalidMemoryRange(const LoadRange &region);
2343 
2344   // If the setup code of a thread plan needs to do work that might involve
2345   // calling a function in the target, it should not do that work directly in
2346   // one of the thread plan functions (DidPush/WillResume) because such work
2347   // needs to be handled carefully.  Instead, put that work in a
2348   // PreResumeAction callback, and register it with the process.  It will get
2349   // done before the actual "DoResume" gets called.
2350 
2351   typedef bool(PreResumeActionCallback)(void *);
2352 
2353   void AddPreResumeAction(PreResumeActionCallback callback, void *baton);
2354 
2355   bool RunPreResumeActions();
2356 
2357   void ClearPreResumeActions();
2358 
2359   void ClearPreResumeAction(PreResumeActionCallback callback, void *baton);
2360 
2361   ProcessRunLock &GetRunLock();
2362 
2363   bool CurrentThreadIsPrivateStateThread();
2364 
SendEventData(const char * data)2365   virtual Status SendEventData(const char *data) {
2366     Status return_error("Sending an event is not supported for this process.");
2367     return return_error;
2368   }
2369 
2370   lldb::ThreadCollectionSP GetHistoryThreads(lldb::addr_t addr);
2371 
2372   lldb::InstrumentationRuntimeSP
2373   GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type);
2374 
2375   /// Try to fetch the module specification for a module with the given file
2376   /// name and architecture. Process sub-classes have to override this method
2377   /// if they support platforms where the Platform object can't get the module
2378   /// spec for all module.
2379   ///
2380   /// \param[in] module_file_spec
2381   ///     The file name of the module to get specification for.
2382   ///
2383   /// \param[in] arch
2384   ///     The architecture of the module to get specification for.
2385   ///
2386   /// \param[out] module_spec
2387   ///     The fetched module specification if the return value is
2388   ///     \b true, unchanged otherwise.
2389   ///
2390   /// \return
2391   ///     Returns \b true if the module spec fetched successfully,
2392   ///     \b false otherwise.
2393   virtual bool GetModuleSpec(const FileSpec &module_file_spec,
2394                              const ArchSpec &arch, ModuleSpec &module_spec);
2395 
PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs,const llvm::Triple & triple)2396   virtual void PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs,
2397                                    const llvm::Triple &triple) {}
2398 
2399   /// Try to find the load address of a file.
2400   /// The load address is defined as the address of the first memory region
2401   /// what contains data mapped from the specified file.
2402   ///
2403   /// \param[in] file
2404   ///     The name of the file whose load address we are looking for
2405   ///
2406   /// \param[out] is_loaded
2407   ///     \b True if the file is loaded into the memory and false
2408   ///     otherwise.
2409   ///
2410   /// \param[out] load_addr
2411   ///     The load address of the file if it is loaded into the
2412   ///     processes address space, LLDB_INVALID_ADDRESS otherwise.
GetFileLoadAddress(const FileSpec & file,bool & is_loaded,lldb::addr_t & load_addr)2413   virtual Status GetFileLoadAddress(const FileSpec &file, bool &is_loaded,
2414                                     lldb::addr_t &load_addr) {
2415     return Status("Not supported");
2416   }
2417 
2418   size_t AddImageToken(lldb::addr_t image_ptr);
2419 
2420   lldb::addr_t GetImagePtrFromToken(size_t token) const;
2421 
2422   void ResetImageToken(size_t token);
2423 
2424   /// Find the next branch instruction to set a breakpoint on
2425   ///
2426   /// When instruction stepping through a source line, instead of stepping
2427   /// through each instruction, we can put a breakpoint on the next branch
2428   /// instruction (within the range of instructions we are stepping through)
2429   /// and continue the process to there, yielding significant performance
2430   /// benefits over instruction stepping.
2431   ///
2432   /// \param[in] default_stop_addr
2433   ///     The address of the instruction where lldb would put a
2434   ///     breakpoint normally.
2435   ///
2436   /// \param[in] range_bounds
2437   ///     The range which the breakpoint must be contained within.
2438   ///     Typically a source line.
2439   ///
2440   /// \return
2441   ///     The address of the next branch instruction, or the end of
2442   ///     the range provided in range_bounds.  If there are any
2443   ///     problems with the disassembly or getting the instructions,
2444   ///     the original default_stop_addr will be returned.
2445   Address AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
2446                                                 AddressRange range_bounds);
2447 
2448   /// Configure asynchronous structured data feature.
2449   ///
2450   /// Each Process type that supports using an asynchronous StructuredData
2451   /// feature should implement this to enable/disable/configure the feature.
2452   /// The default implementation here will always return an error indiciating
2453   /// the feature is unsupported.
2454   ///
2455   /// StructuredDataPlugin implementations will call this to configure a
2456   /// feature that has been reported as being supported.
2457   ///
2458   /// \param[in] type_name
2459   ///     The StructuredData type name as previously discovered by
2460   ///     the Process-derived instance.
2461   ///
2462   /// \param[in] config_sp
2463   ///     Configuration data for the feature being enabled.  This config
2464   ///     data, which may be null, will be passed along to the feature
2465   ///     to process.  The feature will dictate whether this is a dictionary,
2466   ///     an array or some other object.  If the feature needs to be
2467   ///     set up properly before it can be enabled, then the config should
2468   ///     also take an enable/disable flag.
2469   ///
2470   /// \return
2471   ///     Returns the result of attempting to configure the feature.
2472   virtual Status
2473   ConfigureStructuredData(ConstString type_name,
2474                           const StructuredData::ObjectSP &config_sp);
2475 
2476   /// Broadcasts the given structured data object from the given plugin.
2477   ///
2478   /// StructuredDataPlugin instances can use this to optionally broadcast any
2479   /// of their data if they want to make it available for clients.  The data
2480   /// will come in on the structured data event bit
2481   /// (eBroadcastBitStructuredData).
2482   ///
2483   /// \param[in] object_sp
2484   ///     The structured data object to broadcast.
2485   ///
2486   /// \param[in] plugin_sp
2487   ///     The plugin that will be reported in the event's plugin
2488   ///     parameter.
2489   void BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
2490                                const lldb::StructuredDataPluginSP &plugin_sp);
2491 
2492   /// Returns the StructuredDataPlugin associated with a given type name, if
2493   /// there is one.
2494   ///
2495   /// There will only be a plugin for a given StructuredDataType if the
2496   /// debugged process monitor claims that the feature is supported. This is
2497   /// one way to tell whether a feature is available.
2498   ///
2499   /// \return
2500   ///     The plugin if one is available for the specified feature;
2501   ///     otherwise, returns an empty shared pointer.
2502   lldb::StructuredDataPluginSP
2503   GetStructuredDataPlugin(ConstString type_name) const;
2504 
2505   /// Starts tracing with the configuration provided in options. To enable
2506   /// tracing on the complete process the thread_id in the options should be
2507   /// set to LLDB_INVALID_THREAD_ID. The API returns a user_id which is needed
2508   /// by other API's that manipulate the trace instance. The handling of
2509   /// erroneous or unsupported configuration is left to the trace technology
2510   /// implementations in the server, as they could be returned as an error, or
2511   /// rounded to a valid configuration to start tracing. In the later case the
2512   /// GetTraceConfig should supply the actual used trace configuration.
StartTrace(const TraceOptions & options,Status & error)2513   virtual lldb::user_id_t StartTrace(const TraceOptions &options,
2514                                      Status &error) {
2515     error.SetErrorString("Not implemented");
2516     return LLDB_INVALID_UID;
2517   }
2518 
2519   /// Stops the tracing instance leading to deletion of the trace data. The
2520   /// tracing instance is identified by the user_id which is obtained when
2521   /// tracing was started from the StartTrace. In case tracing of the complete
2522   /// process needs to be stopped the thread_id should be set to
2523   /// LLDB_INVALID_THREAD_ID. In the other case that tracing on an individual
2524   /// thread needs to be stopped a thread_id can be supplied.
StopTrace(lldb::user_id_t uid,lldb::tid_t thread_id)2525   virtual Status StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) {
2526     return Status("Not implemented");
2527   }
2528 
2529   /// Provides the trace data as raw bytes. A buffer needs to be supplied to
2530   /// copy the trace data. The exact behavior of this API may vary across
2531   /// trace technology, as some may support partial reading of the trace data
2532   /// from a specified offset while some may not. The thread_id should be used
2533   /// to select a particular thread for trace extraction.
2534   virtual Status GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
2535                          llvm::MutableArrayRef<uint8_t> &buffer,
2536                          size_t offset = 0) {
2537     return Status("Not implemented");
2538   }
2539 
2540   /// Similar API as above except for obtaining meta data
2541   virtual Status GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
2542                              llvm::MutableArrayRef<uint8_t> &buffer,
2543                              size_t offset = 0) {
2544     return Status("Not implemented");
2545   }
2546 
2547   /// API to obtain the trace configuration used by a trace instance.
2548   /// Configurations that may be specific to some trace technology should be
2549   /// stored in the custom parameters. The options are transported to the
2550   /// server, which shall interpret accordingly. The thread_id can be
2551   /// specified in the options to obtain the configuration used by a specific
2552   /// thread. The thread_id specified should also match the uid otherwise an
2553   /// error will be returned.
GetTraceConfig(lldb::user_id_t uid,TraceOptions & options)2554   virtual Status GetTraceConfig(lldb::user_id_t uid, TraceOptions &options) {
2555     return Status("Not implemented");
2556   }
2557 
2558   ///  Get the processor tracing type supported for this process.
2559   ///  Responses might be different depending on the architecture and
2560   ///  capabilities of the underlying OS.
2561   ///
2562   ///  \return
2563   ///     The supported trace type or an \a llvm::Error if tracing is
2564   ///     not supported for the inferior.
2565   virtual llvm::Expected<TraceTypeInfo> GetSupportedTraceType();
2566 
2567   // This calls a function of the form "void * (*)(void)".
2568   bool CallVoidArgVoidPtrReturn(const Address *address,
2569                                 lldb::addr_t &returned_func,
2570                                 bool trap_exceptions = false);
2571 
2572 protected:
2573   void SetState(lldb::EventSP &event_sp);
2574 
2575   lldb::StateType GetPrivateState();
2576 
2577   /// The "private" side of resuming a process.  This doesn't alter the state
2578   /// of m_run_lock, but just causes the process to resume.
2579   ///
2580   /// \return
2581   ///     An Status object describing the success or failure of the resume.
2582   Status PrivateResume();
2583 
2584   // Called internally
2585   void CompleteAttach();
2586 
2587   /// Print a user-visible warning one time per Process
2588   ///
2589   /// A facility for printing a warning to the user once per repeat_key.
2590   ///
2591   /// warning_type is from the Process::Warnings enums. repeat_key is a
2592   /// pointer value that will be used to ensure that the warning message is
2593   /// not printed multiple times.  For instance, with a warning about a
2594   /// function being optimized, you can pass the CompileUnit pointer to have
2595   /// the warning issued for only the first function in a CU, or the Function
2596   /// pointer to have it issued once for every function, or a Module pointer
2597   /// to have it issued once per Module.
2598   ///
2599   /// Classes outside Process should call a specific PrintWarning method so
2600   /// that the warning strings are all centralized in Process, instead of
2601   /// calling PrintWarning() directly.
2602   ///
2603   /// \param [in] warning_type
2604   ///     One of the types defined in Process::Warnings.
2605   ///
2606   /// \param [in] repeat_key
2607   ///     A pointer value used to ensure that the warning is only printed once.
2608   ///     May be nullptr, indicating that the warning is printed unconditionally
2609   ///     every time.
2610   ///
2611   /// \param [in] fmt
2612   ///     printf style format string
2613   void PrintWarning(uint64_t warning_type, const void *repeat_key,
2614                     const char *fmt, ...) __attribute__((format(printf, 4, 5)));
2615 
2616   // NextEventAction provides a way to register an action on the next event
2617   // that is delivered to this process.  There is currently only one next event
2618   // action allowed in the process at one time.  If a new "NextEventAction" is
2619   // added while one is already present, the old action will be discarded (with
2620   // HandleBeingUnshipped called after it is discarded.)
2621   //
2622   // If you want to resume the process as a result of a resume action, call
2623   // RequestResume, don't call Resume directly.
2624   class NextEventAction {
2625   public:
2626     enum EventActionResult {
2627       eEventActionSuccess,
2628       eEventActionRetry,
2629       eEventActionExit
2630     };
2631 
NextEventAction(Process * process)2632     NextEventAction(Process *process) : m_process(process) {}
2633 
2634     virtual ~NextEventAction() = default;
2635 
2636     virtual EventActionResult PerformAction(lldb::EventSP &event_sp) = 0;
HandleBeingUnshipped()2637     virtual void HandleBeingUnshipped() {}
2638     virtual EventActionResult HandleBeingInterrupted() = 0;
2639     virtual const char *GetExitString() = 0;
RequestResume()2640     void RequestResume() { m_process->m_resume_requested = true; }
2641 
2642   protected:
2643     Process *m_process;
2644   };
2645 
SetNextEventAction(Process::NextEventAction * next_event_action)2646   void SetNextEventAction(Process::NextEventAction *next_event_action) {
2647     if (m_next_event_action_up.get())
2648       m_next_event_action_up->HandleBeingUnshipped();
2649 
2650     m_next_event_action_up.reset(next_event_action);
2651   }
2652 
2653   // This is the completer for Attaching:
2654   class AttachCompletionHandler : public NextEventAction {
2655   public:
2656     AttachCompletionHandler(Process *process, uint32_t exec_count);
2657 
2658     ~AttachCompletionHandler() override = default;
2659 
2660     EventActionResult PerformAction(lldb::EventSP &event_sp) override;
2661     EventActionResult HandleBeingInterrupted() override;
2662     const char *GetExitString() override;
2663 
2664   private:
2665     uint32_t m_exec_count;
2666     std::string m_exit_string;
2667   };
2668 
PrivateStateThreadIsValid()2669   bool PrivateStateThreadIsValid() const {
2670     lldb::StateType state = m_private_state.GetValue();
2671     return state != lldb::eStateInvalid && state != lldb::eStateDetached &&
2672            state != lldb::eStateExited && m_private_state_thread.IsJoinable();
2673   }
2674 
ForceNextEventDelivery()2675   void ForceNextEventDelivery() { m_force_next_event_delivery = true; }
2676 
2677   /// Loads any plugins associated with asynchronous structured data and maps
2678   /// the relevant supported type name to the plugin.
2679   ///
2680   /// Processes can receive asynchronous structured data from the process
2681   /// monitor.  This method will load and map any structured data plugins that
2682   /// support the given set of supported type names. Later, if any of these
2683   /// features are enabled, the process monitor is free to generate
2684   /// asynchronous structured data.  The data must come in as a single \b
2685   /// StructuredData::Dictionary.  That dictionary must have a string field
2686   /// named 'type', with a value that equals the relevant type name string
2687   /// (one of the values in \b supported_type_names).
2688   ///
2689   /// \param[in] supported_type_names
2690   ///     An array of zero or more type names.  Each must be unique.
2691   ///     For each entry in the list, a StructuredDataPlugin will be
2692   ///     searched for that supports the structured data type name.
2693   void MapSupportedStructuredDataPlugins(
2694       const StructuredData::Array &supported_type_names);
2695 
2696   /// Route the incoming structured data dictionary to the right plugin.
2697   ///
2698   /// The incoming structured data must be a dictionary, and it must have a
2699   /// key named 'type' that stores a string value.  The string value must be
2700   /// the name of the structured data feature that knows how to handle it.
2701   ///
2702   /// \param[in] object_sp
2703   ///     When non-null and pointing to a dictionary, the 'type'
2704   ///     key's string value is used to look up the plugin that
2705   ///     was registered for that structured data type.  It then
2706   ///     calls the following method on the StructuredDataPlugin
2707   ///     instance:
2708   ///
2709   ///     virtual void
2710   ///     HandleArrivalOfStructuredData(Process &process,
2711   ///                                   ConstString type_name,
2712   ///                                   const StructuredData::ObjectSP
2713   ///                                   &object_sp)
2714   ///
2715   /// \return
2716   ///     True if the structured data was routed to a plugin; otherwise,
2717   ///     false.
2718   bool RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp);
2719 
2720   // Type definitions
2721   typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP>
2722       LanguageRuntimeCollection;
2723   typedef std::unordered_set<const void *> WarningsPointerSet;
2724   typedef std::map<uint64_t, WarningsPointerSet> WarningsCollection;
2725 
2726   struct PreResumeCallbackAndBaton {
2727     bool (*callback)(void *);
2728     void *baton;
PreResumeCallbackAndBatonPreResumeCallbackAndBaton2729     PreResumeCallbackAndBaton(PreResumeActionCallback in_callback,
2730                               void *in_baton)
2731         : callback(in_callback), baton(in_baton) {}
2732     bool operator== (const PreResumeCallbackAndBaton &rhs) {
2733       return callback == rhs.callback && baton == rhs.baton;
2734     }
2735   };
2736 
2737   using StructuredDataPluginMap =
2738       std::map<ConstString, lldb::StructuredDataPluginSP>;
2739 
2740   // Member variables
2741   std::weak_ptr<Target> m_target_wp; ///< The target that owns this process.
2742   lldb::pid_t m_pid = LLDB_INVALID_PROCESS_ID;
2743   ThreadSafeValue<lldb::StateType> m_public_state;
2744   ThreadSafeValue<lldb::StateType>
2745       m_private_state;                     // The actual state of our process
2746   Broadcaster m_private_state_broadcaster; // This broadcaster feeds state
2747                                            // changed events into the private
2748                                            // state thread's listener.
2749   Broadcaster m_private_state_control_broadcaster; // This is the control
2750                                                    // broadcaster, used to
2751                                                    // pause, resume & stop the
2752                                                    // private state thread.
2753   lldb::ListenerSP m_private_state_listener_sp; // This is the listener for the
2754                                                 // private state thread.
2755   HostThread m_private_state_thread; ///< Thread ID for the thread that watches
2756                                      ///internal state events
2757   ProcessModID m_mod_id; ///< Tracks the state of the process over stops and
2758                          ///other alterations.
2759   uint32_t m_process_unique_id; ///< Each lldb_private::Process class that is
2760                                 ///created gets a unique integer ID that
2761                                 ///increments with each new instance
2762   uint32_t m_thread_index_id;   ///< Each thread is created with a 1 based index
2763                                 ///that won't get re-used.
2764   std::map<uint64_t, uint32_t> m_thread_id_to_index_id_map;
2765   int m_exit_status; ///< The exit status of the process, or -1 if not set.
2766   std::string m_exit_string; ///< A textual description of why a process exited.
2767   std::mutex m_exit_status_mutex; ///< Mutex so m_exit_status m_exit_string can
2768                                   ///be safely accessed from multiple threads
2769   std::recursive_mutex m_thread_mutex;
2770   ThreadList m_thread_list_real; ///< The threads for this process as are known
2771                                  ///to the protocol we are debugging with
2772   ThreadList m_thread_list; ///< The threads for this process as the user will
2773                             ///see them. This is usually the same as
2774   ///< m_thread_list_real, but might be different if there is an OS plug-in
2775   ///creating memory threads
2776   ThreadPlanStackMap m_thread_plans; ///< This is the list of thread plans for
2777                                      /// threads in m_thread_list, as well as
2778                                      /// threads we knew existed, but haven't
2779                                      /// determined that they have died yet.
2780   ThreadList m_extended_thread_list; ///< Owner for extended threads that may be
2781                                      ///generated, cleared on natural stops
2782   uint32_t m_extended_thread_stop_id; ///< The natural stop id when
2783                                       ///extended_thread_list was last updated
2784   QueueList
2785       m_queue_list; ///< The list of libdispatch queues at a given stop point
2786   uint32_t m_queue_list_stop_id; ///< The natural stop id when queue list was
2787                                  ///last fetched
2788   std::vector<Notifications> m_notifications; ///< The list of notifications
2789                                               ///that this process can deliver.
2790   std::vector<lldb::addr_t> m_image_tokens;
2791   lldb::ListenerSP m_listener_sp; ///< Shared pointer to the listener used for
2792                                   ///public events.  Can not be empty.
2793   BreakpointSiteList m_breakpoint_site_list; ///< This is the list of breakpoint
2794                                              ///locations we intend to insert in
2795                                              ///the target.
2796   lldb::DynamicLoaderUP m_dyld_up;
2797   lldb::JITLoaderListUP m_jit_loaders_up;
2798   lldb::DynamicCheckerFunctionsUP m_dynamic_checkers_up; ///< The functions used
2799                                                          /// by the expression
2800                                                          /// parser to validate
2801                                                          /// data that
2802                                                          /// expressions use.
2803   lldb::OperatingSystemUP m_os_up;
2804   lldb::SystemRuntimeUP m_system_runtime_up;
2805   lldb::UnixSignalsSP
2806       m_unix_signals_sp; /// This is the current signal set for this process.
2807   lldb::ABISP m_abi_sp;
2808   lldb::IOHandlerSP m_process_input_reader;
2809   Communication m_stdio_communication;
2810   std::recursive_mutex m_stdio_communication_mutex;
2811   bool m_stdin_forward; /// Remember if stdin must be forwarded to remote debug
2812                         /// server
2813   std::string m_stdout_data;
2814   std::string m_stderr_data;
2815   std::recursive_mutex m_profile_data_comm_mutex;
2816   std::vector<std::string> m_profile_data;
2817   Predicate<uint32_t> m_iohandler_sync;
2818   MemoryCache m_memory_cache;
2819   AllocatedMemoryCache m_allocated_memory_cache;
2820   bool m_should_detach; /// Should we detach if the process object goes away
2821                         /// with an explicit call to Kill or Detach?
2822   LanguageRuntimeCollection m_language_runtimes;
2823   std::recursive_mutex m_language_runtimes_mutex;
2824   InstrumentationRuntimeCollection m_instrumentation_runtimes;
2825   std::unique_ptr<NextEventAction> m_next_event_action_up;
2826   std::vector<PreResumeCallbackAndBaton> m_pre_resume_actions;
2827   ProcessRunLock m_public_run_lock;
2828   ProcessRunLock m_private_run_lock;
2829   bool m_currently_handling_do_on_removals;
2830   bool m_resume_requested; // If m_currently_handling_event or
2831                            // m_currently_handling_do_on_removals are true,
2832                            // Resume will only request a resume, using this
2833                            // flag to check.
2834   bool m_finalizing; // This is set at the beginning of Process::Finalize() to
2835                      // stop functions from looking up or creating things
2836                      // during a finalize call
2837   bool m_finalize_called; // This is set at the end of Process::Finalize()
2838   bool m_clear_thread_plans_on_stop;
2839   bool m_force_next_event_delivery;
2840   lldb::StateType m_last_broadcast_state; /// This helps with the Public event
2841                                           /// coalescing in
2842                                           /// ShouldBroadcastEvent.
2843   std::map<lldb::addr_t, lldb::addr_t> m_resolved_indirect_addresses;
2844   bool m_destroy_in_process;
2845   bool m_can_interpret_function_calls;  // Some targets, e.g the OSX kernel,
2846                                         // don't support the ability to modify
2847                                         // the stack.
2848   WarningsCollection m_warnings_issued; // A set of object pointers which have
2849                                         // already had warnings printed
2850   std::mutex m_run_thread_plan_lock;
2851   StructuredDataPluginMap m_structured_data_plugin_map;
2852 
2853   enum { eCanJITDontKnow = 0, eCanJITYes, eCanJITNo } m_can_jit;
2854 
2855   std::unique_ptr<UtilityFunction> m_dlopen_utility_func_up;
2856   llvm::once_flag m_dlopen_utility_func_flag_once;
2857 
2858   size_t RemoveBreakpointOpcodesFromBuffer(lldb::addr_t addr, size_t size,
2859                                            uint8_t *buf) const;
2860 
2861   void SynchronouslyNotifyStateChanged(lldb::StateType state);
2862 
2863   void SetPublicState(lldb::StateType new_state, bool restarted);
2864 
2865   void SetPrivateState(lldb::StateType state);
2866 
2867   bool StartPrivateStateThread(bool is_secondary_thread = false);
2868 
2869   void StopPrivateStateThread();
2870 
2871   void PausePrivateStateThread();
2872 
2873   void ResumePrivateStateThread();
2874 
2875 private:
2876   struct PrivateStateThreadArgs {
PrivateStateThreadArgsPrivateStateThreadArgs2877     PrivateStateThreadArgs(Process *p, bool s)
2878         : process(p), is_secondary_thread(s){};
2879     Process *process;
2880     bool is_secondary_thread;
2881   };
2882 
2883   // arg is a pointer to a new'ed PrivateStateThreadArgs structure.
2884   // PrivateStateThread will free it for you.
2885   static lldb::thread_result_t PrivateStateThread(void *arg);
2886 
2887   // The starts up the private state thread that will watch for events from the
2888   // debugee. Pass true for is_secondary_thread in the case where you have to
2889   // temporarily spin up a secondary state thread to handle events from a hand-
2890   // called function on the primary private state thread.
2891 
2892   lldb::thread_result_t RunPrivateStateThread(bool is_secondary_thread);
2893 
2894 protected:
2895   void HandlePrivateEvent(lldb::EventSP &event_sp);
2896 
2897   Status HaltPrivate();
2898 
2899   lldb::StateType WaitForProcessStopPrivate(lldb::EventSP &event_sp,
2900                                             const Timeout<std::micro> &timeout);
2901 
2902   // This waits for both the state change broadcaster, and the control
2903   // broadcaster. If control_only, it only waits for the control broadcaster.
2904 
2905   bool GetEventsPrivate(lldb::EventSP &event_sp,
2906                         const Timeout<std::micro> &timeout, bool control_only);
2907 
2908   lldb::StateType
2909   GetStateChangedEventsPrivate(lldb::EventSP &event_sp,
2910                                const Timeout<std::micro> &timeout);
2911 
2912   size_t WriteMemoryPrivate(lldb::addr_t addr, const void *buf, size_t size,
2913                             Status &error);
2914 
2915   void AppendSTDOUT(const char *s, size_t len);
2916 
2917   void AppendSTDERR(const char *s, size_t len);
2918 
2919   void BroadcastAsyncProfileData(const std::string &one_profile_data);
2920 
2921   static void STDIOReadThreadBytesReceived(void *baton, const void *src,
2922                                            size_t src_len);
2923 
2924   bool PushProcessIOHandler();
2925 
2926   bool PopProcessIOHandler();
2927 
2928   bool ProcessIOHandlerIsActive();
2929 
ProcessIOHandlerExists()2930   bool ProcessIOHandlerExists() const {
2931     return static_cast<bool>(m_process_input_reader);
2932   }
2933 
2934   Status StopForDestroyOrDetach(lldb::EventSP &exit_event_sp);
2935 
2936   virtual Status UpdateAutomaticSignalFiltering();
2937 
2938   void LoadOperatingSystemPlugin(bool flush);
2939 
2940 private:
2941   /// This is the part of the event handling that for a process event. It
2942   /// decides what to do with the event and returns true if the event needs to
2943   /// be propagated to the user, and false otherwise. If the event is not
2944   /// propagated, this call will most likely set the target to executing
2945   /// again. There is only one place where this call should be called,
2946   /// HandlePrivateEvent. Don't call it from anywhere else...
2947   ///
2948   /// \param[in] event_ptr
2949   ///     This is the event we are handling.
2950   ///
2951   /// \return
2952   ///     Returns \b true if the event should be reported to the
2953   ///     user, \b false otherwise.
2954   bool ShouldBroadcastEvent(Event *event_ptr);
2955 
2956   void ControlPrivateStateThread(uint32_t signal);
2957 
2958   Process(const Process &) = delete;
2959   const Process &operator=(const Process &) = delete;
2960 };
2961 
2962 /// RAII guard that should be acquired when an utility function is called within
2963 /// a given process.
2964 class UtilityFunctionScope {
2965   Process *m_process;
2966 
2967 public:
UtilityFunctionScope(Process * p)2968   UtilityFunctionScope(Process *p) : m_process(p) {
2969     if (m_process)
2970       m_process->SetRunningUtilityFunction(true);
2971   }
~UtilityFunctionScope()2972   ~UtilityFunctionScope() {
2973     if (m_process)
2974       m_process->SetRunningUtilityFunction(false);
2975   }
2976 };
2977 
2978 } // namespace lldb_private
2979 
2980 #endif // LLDB_TARGET_PROCESS_H
2981