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