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