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