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