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