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