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