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