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