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