]> 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++ r304222, 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/NameMatches.h"
52 #include "lldb/Utility/Status.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   Status 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 Status Launch(ProcessLaunchInfo &launch_info);
796
797   virtual Status LoadCore();
798
799   virtual Status DoLoadCore() {
800     Status 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 Status 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 Status 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   Status Resume();
996
997   Status 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   Status 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   Status 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   Status 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   Status 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 Status WillAttachToProcessWithID(lldb::pid_t pid) { return Status(); }
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 Status WillAttachToProcessWithName(const char *process_name,
1095                                              bool wait_for_launch) {
1096     return Status();
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 Status DoConnectRemote(Stream *strm, llvm::StringRef remote_url) {
1114     Status 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 Status attaching was successful, or
1131   ///     an appropriate (possibly platform-specific) error code if
1132   ///     attaching fails.
1133   /// hanming : need flag
1134   //------------------------------------------------------------------
1135   virtual Status DoAttachToProcessWithID(lldb::pid_t pid,
1136                                          const ProcessAttachInfo &attach_info) {
1137     Status 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 Status attaching was successful, or
1156   ///     an appropriate (possibly platform-specific) error code if
1157   ///     attaching fails.
1158   //------------------------------------------------------------------
1159   virtual Status
1160   DoAttachToProcessWithName(const char *process_name,
1161                             const ProcessAttachInfo &attach_info) {
1162     Status 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 Status WillLaunch(Module *module) { return Status(); }
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 Status instance indicating success or failure of the
1224   ///     operation.
1225   //------------------------------------------------------------------
1226   virtual Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) {
1227     Status 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 Status WillResume() { return Status(); }
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 Status DoResume() {
1271     Status 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 Status WillHalt() { return Status(); }
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 Status DoHalt(bool &caused_stop) {
1318     Status 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 Status WillDetach() { return Status(); }
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 Status DoDetach(bool keep_stopped) {
1352     Status 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 Status WillSignal() { return Status(); }
1381
1382   //------------------------------------------------------------------
1383   /// Sends a process a UNIX signal \a signal.
1384   ///
1385   /// @return
1386   ///     Returns an error object.
1387   //------------------------------------------------------------------
1388   virtual Status DoSignal(int signal) {
1389     Status error;
1390     error.SetErrorStringWithFormat(
1391         "error: %s does not support sending signals to processes",
1392         GetPluginName().GetCString());
1393     return error;
1394   }
1395
1396   virtual Status WillDestroy() { return Status(); }
1397
1398   virtual Status 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                               Status &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                             Status &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                               Status &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, Status &error);
1786
1787   size_t ReadCStringFromMemory(lldb::addr_t vm_addr, std::string &out_str,
1788                                Status &error);
1789
1790   size_t ReadMemoryFromInferior(lldb::addr_t vm_addr, void *buf, size_t size,
1791                                 Status &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                                          Status &error);
1823
1824   int64_t ReadSignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size,
1825                                       int64_t fail_value, Status &error);
1826
1827   lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error);
1828
1829   bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
1830                             Status &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, Status &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, Status &error);
1894
1895   size_t ReadScalarIntegerFromMemory(lldb::addr_t addr, uint32_t byte_size,
1896                                      bool is_signed, Scalar &scalar,
1897                                      Status &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                      Status &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                                         Status &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, Status &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,
2002                                Status &error);
2003
2004   //------------------------------------------------------------------
2005   /// Resolve dynamically loaded indirect functions.
2006   ///
2007   /// @param[in] address
2008   ///     The load address of the indirect function to resolve.
2009   ///
2010   /// @param[out] error
2011   ///     An error value in case the resolve fails.
2012   ///
2013   /// @return
2014   ///     The address of the resolved function.
2015   ///     LLDB_INVALID_ADDRESS if the resolution failed.
2016   //------------------------------------------------------------------
2017   virtual lldb::addr_t ResolveIndirectFunction(const Address *address,
2018                                                Status &error);
2019
2020   //------------------------------------------------------------------
2021   /// Locate the memory region that contains load_addr.
2022   ///
2023   /// If load_addr is within the address space the process has mapped
2024   /// range_info will be filled in with the start and end of that range
2025   /// as well as the permissions for that range and range_info.GetMapped
2026   /// will return true.
2027   ///
2028   /// If load_addr is outside any mapped region then range_info will
2029   /// have its start address set to load_addr and the end of the
2030   /// range will indicate the start of the next mapped range or be
2031   /// set to LLDB_INVALID_ADDRESS if there are no valid mapped ranges
2032   /// between load_addr and the end of the process address space.
2033   ///
2034   /// GetMemoryRegionInfo will only return an error if it is
2035   /// unimplemented for the current process.
2036   ///
2037   /// @param[in] load_addr
2038   ///     The load address to query the range_info for.
2039   ///
2040   /// @param[out] range_info
2041   ///     An range_info value containing the details of the range.
2042   ///
2043   /// @return
2044   ///     An error value.
2045   //------------------------------------------------------------------
2046   virtual Status GetMemoryRegionInfo(lldb::addr_t load_addr,
2047                                      MemoryRegionInfo &range_info) {
2048     Status error;
2049     error.SetErrorString("Process::GetMemoryRegionInfo() not supported");
2050     return error;
2051   }
2052
2053   //------------------------------------------------------------------
2054   /// Obtain all the mapped memory regions within this process.
2055   ///
2056   /// @param[out] region_list
2057   ///     A vector to contain MemoryRegionInfo objects for all mapped
2058   ///     ranges.
2059   ///
2060   /// @return
2061   ///     An error value.
2062   //------------------------------------------------------------------
2063   virtual Status
2064   GetMemoryRegions(std::vector<lldb::MemoryRegionInfoSP> &region_list);
2065
2066   virtual Status GetWatchpointSupportInfo(uint32_t &num) {
2067     Status error;
2068     num = 0;
2069     error.SetErrorString("Process::GetWatchpointSupportInfo() not supported");
2070     return error;
2071   }
2072
2073   virtual Status GetWatchpointSupportInfo(uint32_t &num, bool &after) {
2074     Status error;
2075     num = 0;
2076     after = true;
2077     error.SetErrorString("Process::GetWatchpointSupportInfo() not supported");
2078     return error;
2079   }
2080
2081   lldb::ModuleSP ReadModuleFromMemory(const FileSpec &file_spec,
2082                                       lldb::addr_t header_addr,
2083                                       size_t size_to_read = 512);
2084
2085   //------------------------------------------------------------------
2086   /// Attempt to get the attributes for a region of memory in the process.
2087   ///
2088   /// It may be possible for the remote debug server to inspect attributes
2089   /// for a region of memory in the process, such as whether there is a
2090   /// valid page of memory at a given address or whether that page is
2091   /// readable/writable/executable by the process.
2092   ///
2093   /// @param[in] load_addr
2094   ///     The address of interest in the process.
2095   ///
2096   /// @param[out] permissions
2097   ///     If this call returns successfully, this bitmask will have
2098   ///     its Permissions bits set to indicate whether the region is
2099   ///     readable/writable/executable.  If this call fails, the
2100   ///     bitmask values are undefined.
2101   ///
2102   /// @return
2103   ///     Returns true if it was able to determine the attributes of the
2104   ///     memory region.  False if not.
2105   //------------------------------------------------------------------
2106   virtual bool GetLoadAddressPermissions(lldb::addr_t load_addr,
2107                                          uint32_t &permissions);
2108
2109   //------------------------------------------------------------------
2110   /// Determines whether executing JIT-compiled code in this process
2111   /// is possible.
2112   ///
2113   /// @return
2114   ///     True if execution of JIT code is possible; false otherwise.
2115   //------------------------------------------------------------------
2116   bool CanJIT();
2117
2118   //------------------------------------------------------------------
2119   /// Sets whether executing JIT-compiled code in this process
2120   /// is possible.
2121   ///
2122   /// @param[in] can_jit
2123   ///     True if execution of JIT code is possible; false otherwise.
2124   //------------------------------------------------------------------
2125   void SetCanJIT(bool can_jit);
2126
2127   //------------------------------------------------------------------
2128   /// Determines whether executing function calls using the interpreter
2129   /// is possible for this process.
2130   ///
2131   /// @return
2132   ///     True if possible; false otherwise.
2133   //------------------------------------------------------------------
2134   bool CanInterpretFunctionCalls() { return m_can_interpret_function_calls; }
2135
2136   //------------------------------------------------------------------
2137   /// Sets whether executing function calls using the interpreter
2138   /// is possible for this process.
2139   ///
2140   /// @param[in] can_interpret_function_calls
2141   ///     True if possible; false otherwise.
2142   //------------------------------------------------------------------
2143   void SetCanInterpretFunctionCalls(bool can_interpret_function_calls) {
2144     m_can_interpret_function_calls = can_interpret_function_calls;
2145   }
2146
2147   //------------------------------------------------------------------
2148   /// Sets whether executing code in this process is possible.
2149   /// This could be either through JIT or interpreting.
2150   ///
2151   /// @param[in] can_run_code
2152   ///     True if execution of code is possible; false otherwise.
2153   //------------------------------------------------------------------
2154   void SetCanRunCode(bool can_run_code);
2155
2156   //------------------------------------------------------------------
2157   /// Actually deallocate memory in the process.
2158   ///
2159   /// This function will deallocate memory in the process's address
2160   /// space that was allocated with AllocateMemory.
2161   ///
2162   /// @param[in] ptr
2163   ///     A return value from AllocateMemory, pointing to the memory you
2164   ///     want to deallocate.
2165   ///
2166   /// @return
2167   ///     \btrue if the memory was deallocated, \bfalse otherwise.
2168   //------------------------------------------------------------------
2169   virtual Status DoDeallocateMemory(lldb::addr_t ptr) {
2170     Status error;
2171     error.SetErrorStringWithFormat(
2172         "error: %s does not support deallocating in the debug process",
2173         GetPluginName().GetCString());
2174     return error;
2175   }
2176
2177   //------------------------------------------------------------------
2178   /// The public interface to deallocating memory in the process.
2179   ///
2180   /// This function will deallocate memory in the process's address
2181   /// space that was allocated with AllocateMemory.
2182   ///
2183   /// @param[in] ptr
2184   ///     A return value from AllocateMemory, pointing to the memory you
2185   ///     want to deallocate.
2186   ///
2187   /// @return
2188   ///     \btrue if the memory was deallocated, \bfalse otherwise.
2189   //------------------------------------------------------------------
2190   Status DeallocateMemory(lldb::addr_t ptr);
2191
2192   //------------------------------------------------------------------
2193   /// Get any available STDOUT.
2194   ///
2195   /// Calling this method is a valid operation only if all of the
2196   /// following conditions are true:
2197   /// 1) The process was launched, and not attached to.
2198   /// 2) The process was not launched with eLaunchFlagDisableSTDIO.
2199   /// 3) The process was launched without supplying a valid file path
2200   ///    for STDOUT.
2201   ///
2202   /// Note that the implementation will probably need to start a read
2203   /// thread in the background to make sure that the pipe is drained
2204   /// and the STDOUT buffered appropriately, to prevent the process
2205   /// from deadlocking trying to write to a full buffer.
2206   ///
2207   /// Events will be queued indicating that there is STDOUT available
2208   /// that can be retrieved using this function.
2209   ///
2210   /// @param[out] buf
2211   ///     A buffer that will receive any STDOUT bytes that are
2212   ///     currently available.
2213   ///
2214   /// @param[in] buf_size
2215   ///     The size in bytes for the buffer \a buf.
2216   ///
2217   /// @return
2218   ///     The number of bytes written into \a buf. If this value is
2219   ///     equal to \a buf_size, another call to this function should
2220   ///     be made to retrieve more STDOUT data.
2221   //------------------------------------------------------------------
2222   virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error);
2223
2224   //------------------------------------------------------------------
2225   /// Get any available STDERR.
2226   ///
2227   /// Calling this method is a valid operation only if all of the
2228   /// following conditions are true:
2229   /// 1) The process was launched, and not attached to.
2230   /// 2) The process was not launched with eLaunchFlagDisableSTDIO.
2231   /// 3) The process was launched without supplying a valid file path
2232   ///    for STDERR.
2233   ///
2234   /// Note that the implementation will probably need to start a read
2235   /// thread in the background to make sure that the pipe is drained
2236   /// and the STDERR buffered appropriately, to prevent the process
2237   /// from deadlocking trying to write to a full buffer.
2238   ///
2239   /// Events will be queued indicating that there is STDERR available
2240   /// that can be retrieved using this function.
2241   ///
2242   /// @param[in] buf
2243   ///     A buffer that will receive any STDERR bytes that are
2244   ///     currently available.
2245   ///
2246   /// @param[out] buf_size
2247   ///     The size in bytes for the buffer \a buf.
2248   ///
2249   /// @return
2250   ///     The number of bytes written into \a buf. If this value is
2251   ///     equal to \a buf_size, another call to this function should
2252   ///     be made to retrieve more STDERR data.
2253   //------------------------------------------------------------------
2254   virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error);
2255
2256   //------------------------------------------------------------------
2257   /// Puts data into this process's STDIN.
2258   ///
2259   /// Calling this method is a valid operation only if all of the
2260   /// following conditions are true:
2261   /// 1) The process was launched, and not attached to.
2262   /// 2) The process was not launched with eLaunchFlagDisableSTDIO.
2263   /// 3) The process was launched without supplying a valid file path
2264   ///    for STDIN.
2265   ///
2266   /// @param[in] buf
2267   ///     A buffer that contains the data to write to the process's STDIN.
2268   ///
2269   /// @param[in] buf_size
2270   ///     The size in bytes for the buffer \a buf.
2271   ///
2272   /// @return
2273   ///     The number of bytes written into \a buf. If this value is
2274   ///     less than \a buf_size, another call to this function should
2275   ///     be made to write the rest of the data.
2276   //------------------------------------------------------------------
2277   virtual size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) {
2278     error.SetErrorString("stdin unsupported");
2279     return 0;
2280   }
2281
2282   //------------------------------------------------------------------
2283   /// Get any available profile data.
2284   ///
2285   /// @param[out] buf
2286   ///     A buffer that will receive any profile data bytes that are
2287   ///     currently available.
2288   ///
2289   /// @param[out] buf_size
2290   ///     The size in bytes for the buffer \a buf.
2291   ///
2292   /// @return
2293   ///     The number of bytes written into \a buf. If this value is
2294   ///     equal to \a buf_size, another call to this function should
2295   ///     be made to retrieve more profile data.
2296   //------------------------------------------------------------------
2297   virtual size_t GetAsyncProfileData(char *buf, size_t buf_size, Status &error);
2298
2299   //----------------------------------------------------------------------
2300   // Process Breakpoints
2301   //----------------------------------------------------------------------
2302   size_t GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site);
2303
2304   virtual Status EnableBreakpointSite(BreakpointSite *bp_site) {
2305     Status error;
2306     error.SetErrorStringWithFormat(
2307         "error: %s does not support enabling breakpoints",
2308         GetPluginName().GetCString());
2309     return error;
2310   }
2311
2312   virtual Status DisableBreakpointSite(BreakpointSite *bp_site) {
2313     Status error;
2314     error.SetErrorStringWithFormat(
2315         "error: %s does not support disabling breakpoints",
2316         GetPluginName().GetCString());
2317     return error;
2318   }
2319
2320   // This is implemented completely using the lldb::Process API. Subclasses
2321   // don't need to implement this function unless the standard flow of
2322   // read existing opcode, write breakpoint opcode, verify breakpoint opcode
2323   // doesn't work for a specific process plug-in.
2324   virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site);
2325
2326   // This is implemented completely using the lldb::Process API. Subclasses
2327   // don't need to implement this function unless the standard flow of
2328   // restoring original opcode in memory and verifying the restored opcode
2329   // doesn't work for a specific process plug-in.
2330   virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site);
2331
2332   BreakpointSiteList &GetBreakpointSiteList();
2333
2334   const BreakpointSiteList &GetBreakpointSiteList() const;
2335
2336   void DisableAllBreakpointSites();
2337
2338   Status ClearBreakpointSiteByID(lldb::user_id_t break_id);
2339
2340   lldb::break_id_t CreateBreakpointSite(const lldb::BreakpointLocationSP &owner,
2341                                         bool use_hardware);
2342
2343   Status DisableBreakpointSiteByID(lldb::user_id_t break_id);
2344
2345   Status EnableBreakpointSiteByID(lldb::user_id_t break_id);
2346
2347   // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove
2348   // themselves from the owner's list of this breakpoint sites.
2349   void RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
2350                                      lldb::user_id_t owner_loc_id,
2351                                      lldb::BreakpointSiteSP &bp_site_sp);
2352
2353   //----------------------------------------------------------------------
2354   // Process Watchpoints (optional)
2355   //----------------------------------------------------------------------
2356   virtual Status EnableWatchpoint(Watchpoint *wp, bool notify = true);
2357
2358   virtual Status DisableWatchpoint(Watchpoint *wp, bool notify = true);
2359
2360   //------------------------------------------------------------------
2361   // Thread Queries
2362   //------------------------------------------------------------------
2363   virtual bool UpdateThreadList(ThreadList &old_thread_list,
2364                                 ThreadList &new_thread_list) = 0;
2365
2366   void UpdateThreadListIfNeeded();
2367
2368   ThreadList &GetThreadList() { return m_thread_list; }
2369
2370   // When ExtendedBacktraces are requested, the HistoryThreads that are
2371   // created need an owner -- they're saved here in the Process.  The
2372   // threads in this list are not iterated over - driver programs need to
2373   // request the extended backtrace calls starting from a root concrete
2374   // thread one by one.
2375   ThreadList &GetExtendedThreadList() { return m_extended_thread_list; }
2376
2377   ThreadList::ThreadIterable Threads() { return m_thread_list.Threads(); }
2378
2379   uint32_t GetNextThreadIndexID(uint64_t thread_id);
2380
2381   lldb::ThreadSP CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context);
2382
2383   // Returns true if an index id has been assigned to a thread.
2384   bool HasAssignedIndexIDToThread(uint64_t sb_thread_id);
2385
2386   // Given a thread_id, it will assign a more reasonable index id for display to
2387   // the user.
2388   // If the thread_id has previously been assigned, the same index id will be
2389   // used.
2390   uint32_t AssignIndexIDToThread(uint64_t thread_id);
2391
2392   //------------------------------------------------------------------
2393   // Queue Queries
2394   //------------------------------------------------------------------
2395
2396   void UpdateQueueListIfNeeded();
2397
2398   QueueList &GetQueueList() {
2399     UpdateQueueListIfNeeded();
2400     return m_queue_list;
2401   }
2402
2403   QueueList::QueueIterable Queues() {
2404     UpdateQueueListIfNeeded();
2405     return m_queue_list.Queues();
2406   }
2407
2408   //------------------------------------------------------------------
2409   // Event Handling
2410   //------------------------------------------------------------------
2411   lldb::StateType GetNextEvent(lldb::EventSP &event_sp);
2412
2413   // Returns the process state when it is stopped. If specified, event_sp_ptr
2414   // is set to the event which triggered the stop. If wait_always = false,
2415   // and the process is already stopped, this function returns immediately.
2416   // If the process is hijacked and use_run_lock is true (the default), then
2417   // this
2418   // function releases the run lock after the stop. Setting use_run_lock to
2419   // false
2420   // will avoid this behavior.
2421   lldb::StateType
2422   WaitForProcessToStop(const Timeout<std::micro> &timeout,
2423                        lldb::EventSP *event_sp_ptr = nullptr,
2424                        bool wait_always = true,
2425                        lldb::ListenerSP hijack_listener = lldb::ListenerSP(),
2426                        Stream *stream = nullptr, bool use_run_lock = true);
2427
2428   uint32_t GetIOHandlerID() const { return m_iohandler_sync.GetValue(); }
2429
2430   //--------------------------------------------------------------------------------------
2431   /// Waits for the process state to be running within a given msec timeout.
2432   ///
2433   /// The main purpose of this is to implement an interlock waiting for
2434   /// HandlePrivateEvent
2435   /// to push an IOHandler.
2436   ///
2437   /// @param[in] timeout_msec
2438   ///     The maximum time length to wait for the process to transition to the
2439   ///     eStateRunning state, specified in milliseconds.
2440   //--------------------------------------------------------------------------------------
2441   void SyncIOHandler(uint32_t iohandler_id, uint64_t timeout_msec);
2442
2443   lldb::StateType GetStateChangedEvents(
2444       lldb::EventSP &event_sp, const Timeout<std::micro> &timeout,
2445       lldb::ListenerSP
2446           hijack_listener); // Pass an empty ListenerSP to use builtin listener
2447
2448   //--------------------------------------------------------------------------------------
2449   /// Centralize the code that handles and prints descriptions for process state
2450   /// changes.
2451   ///
2452   /// @param[in] event_sp
2453   ///     The process state changed event
2454   ///
2455   /// @param[in] stream
2456   ///     The output stream to get the state change description
2457   ///
2458   /// @param[in,out] pop_process_io_handler
2459   ///     If this value comes in set to \b true, then pop the Process IOHandler
2460   ///     if needed.
2461   ///     Else this variable will be set to \b true or \b false to indicate if
2462   ///     the process
2463   ///     needs to have its process IOHandler popped.
2464   ///
2465   /// @return
2466   ///     \b true if the event describes a process state changed event, \b false
2467   ///     otherwise.
2468   //--------------------------------------------------------------------------------------
2469   static bool HandleProcessStateChangedEvent(const lldb::EventSP &event_sp,
2470                                              Stream *stream,
2471                                              bool &pop_process_io_handler);
2472
2473   Event *PeekAtStateChangedEvents();
2474
2475   class ProcessEventHijacker {
2476   public:
2477     ProcessEventHijacker(Process &process, lldb::ListenerSP listener_sp)
2478         : m_process(process) {
2479       m_process.HijackProcessEvents(listener_sp);
2480     }
2481
2482     ~ProcessEventHijacker() { m_process.RestoreProcessEvents(); }
2483
2484   private:
2485     Process &m_process;
2486   };
2487
2488   friend class ProcessEventHijacker;
2489   friend class ProcessProperties;
2490   //------------------------------------------------------------------
2491   /// If you need to ensure that you and only you will hear about some public
2492   /// event, then make a new listener, set to listen to process events, and
2493   /// then call this with that listener.  Then you will have to wait on that
2494   /// listener explicitly for events (rather than using the GetNextEvent &
2495   /// WaitFor*
2496   /// calls above.  Be sure to call RestoreProcessEvents when you are done.
2497   ///
2498   /// @param[in] listener
2499   ///     This is the new listener to whom all process events will be delivered.
2500   ///
2501   /// @return
2502   ///     Returns \b true if the new listener could be installed,
2503   ///     \b false otherwise.
2504   //------------------------------------------------------------------
2505   bool HijackProcessEvents(lldb::ListenerSP listener_sp);
2506
2507   //------------------------------------------------------------------
2508   /// Restores the process event broadcasting to its normal state.
2509   ///
2510   //------------------------------------------------------------------
2511   void RestoreProcessEvents();
2512
2513   const lldb::ABISP &GetABI();
2514
2515   OperatingSystem *GetOperatingSystem() { return m_os_ap.get(); }
2516
2517   ArchSpec::StopInfoOverrideCallbackType GetStopInfoOverrideCallback() const {
2518     return m_stop_info_override_callback;
2519   }
2520
2521   virtual LanguageRuntime *GetLanguageRuntime(lldb::LanguageType language,
2522                                               bool retry_if_null = true);
2523
2524   virtual CPPLanguageRuntime *GetCPPLanguageRuntime(bool retry_if_null = true);
2525
2526   virtual ObjCLanguageRuntime *
2527   GetObjCLanguageRuntime(bool retry_if_null = true);
2528
2529   bool IsPossibleDynamicValue(ValueObject &in_value);
2530
2531   bool IsRunning() const;
2532
2533   DynamicCheckerFunctions *GetDynamicCheckers() {
2534     return m_dynamic_checkers_ap.get();
2535   }
2536
2537   void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers);
2538
2539   //------------------------------------------------------------------
2540   /// Call this to set the lldb in the mode where it breaks on new thread
2541   /// creations, and then auto-restarts.  This is useful when you are trying
2542   /// to run only one thread, but either that thread or the kernel is creating
2543   /// new threads in the process.  If you stop when the thread is created, you
2544   /// can immediately suspend it, and keep executing only the one thread you
2545   /// intend.
2546   ///
2547   /// @return
2548   ///     Returns \b true if we were able to start up the notification
2549   ///     \b false otherwise.
2550   //------------------------------------------------------------------
2551   virtual bool StartNoticingNewThreads() { return true; }
2552
2553   //------------------------------------------------------------------
2554   /// Call this to turn off the stop & notice new threads mode.
2555   ///
2556   /// @return
2557   ///     Returns \b true if we were able to start up the notification
2558   ///     \b false otherwise.
2559   //------------------------------------------------------------------
2560   virtual bool StopNoticingNewThreads() { return true; }
2561
2562   void SetRunningUserExpression(bool on);
2563
2564   //------------------------------------------------------------------
2565   // lldb::ExecutionContextScope pure virtual functions
2566   //------------------------------------------------------------------
2567   lldb::TargetSP CalculateTarget() override;
2568
2569   lldb::ProcessSP CalculateProcess() override { return shared_from_this(); }
2570
2571   lldb::ThreadSP CalculateThread() override { return lldb::ThreadSP(); }
2572
2573   lldb::StackFrameSP CalculateStackFrame() override {
2574     return lldb::StackFrameSP();
2575   }
2576
2577   void CalculateExecutionContext(ExecutionContext &exe_ctx) override;
2578
2579   void SetSTDIOFileDescriptor(int file_descriptor);
2580
2581   //------------------------------------------------------------------
2582   // Add a permanent region of memory that should never be read or
2583   // written to. This can be used to ensure that memory reads or writes
2584   // to certain areas of memory never end up being sent to the
2585   // DoReadMemory or DoWriteMemory functions which can improve
2586   // performance.
2587   //------------------------------------------------------------------
2588   void AddInvalidMemoryRegion(const LoadRange &region);
2589
2590   //------------------------------------------------------------------
2591   // Remove a permanent region of memory that should never be read or
2592   // written to that was previously added with AddInvalidMemoryRegion.
2593   //------------------------------------------------------------------
2594   bool RemoveInvalidMemoryRange(const LoadRange &region);
2595
2596   //------------------------------------------------------------------
2597   // If the setup code of a thread plan needs to do work that might involve
2598   // calling a function in the target, it should not do that work directly
2599   // in one of the thread plan functions (DidPush/WillResume) because
2600   // such work needs to be handled carefully.  Instead, put that work in
2601   // a PreResumeAction callback, and register it with the process.  It will
2602   // get done before the actual "DoResume" gets called.
2603   //------------------------------------------------------------------
2604
2605   typedef bool(PreResumeActionCallback)(void *);
2606
2607   void AddPreResumeAction(PreResumeActionCallback callback, void *baton);
2608
2609   bool RunPreResumeActions();
2610
2611   void ClearPreResumeActions();
2612
2613   void ClearPreResumeAction(PreResumeActionCallback callback, void *baton);
2614
2615   ProcessRunLock &GetRunLock();
2616
2617   virtual Status SendEventData(const char *data) {
2618     Status return_error("Sending an event is not supported for this process.");
2619     return return_error;
2620   }
2621
2622   lldb::ThreadCollectionSP GetHistoryThreads(lldb::addr_t addr);
2623
2624   lldb::InstrumentationRuntimeSP
2625   GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type);
2626
2627   //------------------------------------------------------------------
2628   /// Try to fetch the module specification for a module with the
2629   /// given file name and architecture. Process sub-classes have to
2630   /// override this method if they support platforms where the
2631   /// Platform object can't get the module spec for all module.
2632   ///
2633   /// @param[in] module_file_spec
2634   ///     The file name of the module to get specification for.
2635   ///
2636   /// @param[in] arch
2637   ///     The architecture of the module to get specification for.
2638   ///
2639   /// @param[out] module_spec
2640   ///     The fetched module specification if the return value is
2641   ///     \b true, unchanged otherwise.
2642   ///
2643   /// @return
2644   ///     Returns \b true if the module spec fetched successfully,
2645   ///     \b false otherwise.
2646   //------------------------------------------------------------------
2647   virtual bool GetModuleSpec(const FileSpec &module_file_spec,
2648                              const ArchSpec &arch, ModuleSpec &module_spec);
2649
2650   virtual void PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs,
2651                                    const llvm::Triple &triple) {}
2652
2653   //------------------------------------------------------------------
2654   /// Try to find the load address of a file.
2655   /// The load address is defined as the address of the first memory
2656   /// region what contains data mapped from the specified file.
2657   ///
2658   /// @param[in] file
2659   ///     The name of the file whose load address we are looking for
2660   ///
2661   /// @param[out] is_loaded
2662   ///     \b True if the file is loaded into the memory and false
2663   ///     otherwise.
2664   ///
2665   /// @param[out] load_addr
2666   ///     The load address of the file if it is loaded into the
2667   ///     processes address space, LLDB_INVALID_ADDRESS otherwise.
2668   //------------------------------------------------------------------
2669   virtual Status GetFileLoadAddress(const FileSpec &file, bool &is_loaded,
2670                                     lldb::addr_t &load_addr) {
2671     return Status("Not supported");
2672   }
2673
2674   size_t AddImageToken(lldb::addr_t image_ptr);
2675
2676   lldb::addr_t GetImagePtrFromToken(size_t token) const;
2677
2678   void ResetImageToken(size_t token);
2679
2680   //------------------------------------------------------------------
2681   /// Find the next branch instruction to set a breakpoint on
2682   ///
2683   /// When instruction stepping through a source line, instead of
2684   /// stepping through each instruction, we can put a breakpoint on
2685   /// the next branch instruction (within the range of instructions
2686   /// we are stepping through) and continue the process to there,
2687   /// yielding significant performance benefits over instruction
2688   /// stepping.
2689   ///
2690   /// @param[in] default_stop_addr
2691   ///     The address of the instruction where lldb would put a
2692   ///     breakpoint normally.
2693   ///
2694   /// @param[in] range_bounds
2695   ///     The range which the breakpoint must be contained within.
2696   ///     Typically a source line.
2697   ///
2698   /// @return
2699   ///     The address of the next branch instruction, or the end of
2700   ///     the range provided in range_bounds.  If there are any
2701   ///     problems with the disassembly or getting the instructions,
2702   ///     the original default_stop_addr will be returned.
2703   //------------------------------------------------------------------
2704   Address AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
2705                                                 AddressRange range_bounds);
2706
2707   //------------------------------------------------------------------
2708   /// Configure asynchronous structured data feature.
2709   ///
2710   /// Each Process type that supports using an asynchronous StructuredData
2711   /// feature should implement this to enable/disable/configure the feature.
2712   /// The default implementation here will always return an error indiciating
2713   /// the feature is unsupported.
2714   ///
2715   /// StructuredDataPlugin implementations will call this to configure
2716   /// a feature that has been reported as being supported.
2717   ///
2718   /// @param[in] type_name
2719   ///     The StructuredData type name as previously discovered by
2720   ///     the Process-derived instance.
2721   ///
2722   /// @param[in] config
2723   ///     Configuration data for the feature being enabled.  This config
2724   ///     data, which may be null, will be passed along to the feature
2725   ///     to process.  The feature will dictate whether this is a dictionary,
2726   ///     an array or some other object.  If the feature needs to be
2727   ///     set up properly before it can be enabled, then the config should
2728   ///     also take an enable/disable flag.
2729   ///
2730   /// @return
2731   ///     Returns the result of attempting to configure the feature.
2732   //------------------------------------------------------------------
2733   virtual Status
2734   ConfigureStructuredData(const ConstString &type_name,
2735                           const StructuredData::ObjectSP &config_sp);
2736
2737   //------------------------------------------------------------------
2738   /// Broadcasts the given structured data object from the given
2739   /// plugin.
2740   ///
2741   /// StructuredDataPlugin instances can use this to optionally
2742   /// broadcast any of their data if they want to make it available
2743   /// for clients.  The data will come in on the structured data
2744   /// event bit (eBroadcastBitStructuredData).
2745   ///
2746   /// @param[in] object_sp
2747   ///     The structured data object to broadcast.
2748   ///
2749   /// @param[in] plugin_sp
2750   ///     The plugin that will be reported in the event's plugin
2751   ///     parameter.
2752   //------------------------------------------------------------------
2753   void BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
2754                                const lldb::StructuredDataPluginSP &plugin_sp);
2755
2756   //------------------------------------------------------------------
2757   /// Returns the StructuredDataPlugin associated with a given type
2758   /// name, if there is one.
2759   ///
2760   /// There will only be a plugin for a given StructuredDataType if the
2761   /// debugged process monitor claims that the feature is supported.
2762   /// This is one way to tell whether a feature is available.
2763   ///
2764   /// @return
2765   ///     The plugin if one is available for the specified feature;
2766   ///     otherwise, returns an empty shared pointer.
2767   //------------------------------------------------------------------
2768   lldb::StructuredDataPluginSP
2769   GetStructuredDataPlugin(const ConstString &type_name) const;
2770
2771   //------------------------------------------------------------------
2772   /// Starts tracing with the configuration provided in options. To
2773   /// enable tracing on the complete process the thread_id in the
2774   /// options should be set to LLDB_INVALID_THREAD_ID. The API returns
2775   /// a user_id which is needed by other API's that manipulate the
2776   /// trace instance.
2777   /// The handling of erroneous or unsupported configuration is left
2778   /// to the trace technology implementations in the server, as they
2779   /// could be returned as an error, or rounded to a valid
2780   /// configuration to start tracing. In the later case the
2781   /// GetTraceConfig should supply the actual used trace
2782   /// configuration.
2783   //------------------------------------------------------------------
2784   virtual lldb::user_id_t StartTrace(const TraceOptions &options,
2785                                      Status &error) {
2786     error.SetErrorString("Not implemented");
2787     return LLDB_INVALID_UID;
2788   }
2789
2790   //------------------------------------------------------------------
2791   /// Stops the tracing instance leading to deletion of the trace
2792   /// data. The tracing instance is identified by the user_id which
2793   /// is obtained when tracing was started from the StartTrace.
2794   /// In case tracing of the complete process needs to be stopped
2795   /// the thread_id should be set to LLDB_INVALID_THREAD_ID.
2796   /// In the other case that tracing on an individual thread needs
2797   /// to be stopped a thread_id can be supplied.
2798   //------------------------------------------------------------------
2799   virtual Status StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) {
2800     return Status("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 Status GetData(lldb::user_id_t uid, lldb::tid_t thread_id,
2812                          llvm::MutableArrayRef<uint8_t> &buffer,
2813                          size_t offset = 0) {
2814     return Status("Not implemented");
2815   }
2816
2817   //------------------------------------------------------------------
2818   /// Similar API as above except for obtaining meta data
2819   //------------------------------------------------------------------
2820   virtual Status GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id,
2821                              llvm::MutableArrayRef<uint8_t> &buffer,
2822                              size_t offset = 0) {
2823     return Status("Not implemented");
2824   }
2825
2826   //------------------------------------------------------------------
2827   /// API to obtain the trace configuration used by a trace instance.
2828   /// Configurations that may be specific to some trace technology
2829   /// should be stored in the custom parameters. The options are
2830   /// transported to the server, which shall interpret accordingly.
2831   /// The thread_id can be specified in the options to obtain the
2832   /// configuration used by a specific thread. The thread_id specified
2833   /// should also match the uid otherwise an error will be returned.
2834   //------------------------------------------------------------------
2835   virtual Status GetTraceConfig(lldb::user_id_t uid, TraceOptions &options) {
2836     return Status("Not implemented");
2837   }
2838
2839 protected:
2840   void SetState(lldb::EventSP &event_sp);
2841
2842   lldb::StateType GetPrivateState();
2843
2844   //------------------------------------------------------------------
2845   /// The "private" side of resuming a process.  This doesn't alter the
2846   /// state of m_run_lock, but just causes the process to resume.
2847   ///
2848   /// @return
2849   ///     An Status object describing the success or failure of the resume.
2850   //------------------------------------------------------------------
2851   Status PrivateResume();
2852
2853   //------------------------------------------------------------------
2854   // Called internally
2855   //------------------------------------------------------------------
2856   void CompleteAttach();
2857
2858   //------------------------------------------------------------------
2859   /// Print a user-visible warning one time per Process
2860   ///
2861   /// A facility for printing a warning to the user once per repeat_key.
2862   ///
2863   /// warning_type is from the Process::Warnings enums.
2864   /// repeat_key is a pointer value that will be used to ensure that the
2865   /// warning message is not printed multiple times.  For instance, with a
2866   /// warning about a function being optimized, you can pass the CompileUnit
2867   /// pointer to have the warning issued for only the first function in a
2868   /// CU, or the Function pointer to have it issued once for every function,
2869   /// or a Module pointer to have it issued once per Module.
2870   ///
2871   /// Classes outside Process should call a specific PrintWarning method
2872   /// so that the warning strings are all centralized in Process, instead of
2873   /// calling PrintWarning() directly.
2874   ///
2875   /// @param [in] warning_type
2876   ///     One of the types defined in Process::Warnings.
2877   ///
2878   /// @param [in] repeat_key
2879   ///     A pointer value used to ensure that the warning is only printed once.
2880   ///     May be nullptr, indicating that the warning is printed unconditionally
2881   ///     every time.
2882   ///
2883   /// @param [in] fmt
2884   ///     printf style format string
2885   //------------------------------------------------------------------
2886   void PrintWarning(uint64_t warning_type, const void *repeat_key,
2887                     const char *fmt, ...) __attribute__((format(printf, 4, 5)));
2888
2889   //------------------------------------------------------------------
2890   // NextEventAction provides a way to register an action on the next
2891   // event that is delivered to this process.  There is currently only
2892   // one next event action allowed in the process at one time.  If a
2893   // new "NextEventAction" is added while one is already present, the
2894   // old action will be discarded (with HandleBeingUnshipped called
2895   // after it is discarded.)
2896   //
2897   // If you want to resume the process as a result of a resume action,
2898   // call RequestResume, don't call Resume directly.
2899   //------------------------------------------------------------------
2900   class NextEventAction {
2901   public:
2902     typedef enum EventActionResult {
2903       eEventActionSuccess,
2904       eEventActionRetry,
2905       eEventActionExit
2906     } EventActionResult;
2907
2908     NextEventAction(Process *process) : m_process(process) {}
2909
2910     virtual ~NextEventAction() = default;
2911
2912     virtual EventActionResult PerformAction(lldb::EventSP &event_sp) = 0;
2913     virtual void HandleBeingUnshipped() {}
2914     virtual EventActionResult HandleBeingInterrupted() = 0;
2915     virtual const char *GetExitString() = 0;
2916     void RequestResume() { m_process->m_resume_requested = true; }
2917
2918   protected:
2919     Process *m_process;
2920   };
2921
2922   void SetNextEventAction(Process::NextEventAction *next_event_action) {
2923     if (m_next_event_action_ap.get())
2924       m_next_event_action_ap->HandleBeingUnshipped();
2925
2926     m_next_event_action_ap.reset(next_event_action);
2927   }
2928
2929   // This is the completer for Attaching:
2930   class AttachCompletionHandler : public NextEventAction {
2931   public:
2932     AttachCompletionHandler(Process *process, uint32_t exec_count);
2933
2934     ~AttachCompletionHandler() override = default;
2935
2936     EventActionResult PerformAction(lldb::EventSP &event_sp) override;
2937     EventActionResult HandleBeingInterrupted() override;
2938     const char *GetExitString() override;
2939
2940   private:
2941     uint32_t m_exec_count;
2942     std::string m_exit_string;
2943   };
2944
2945   bool PrivateStateThreadIsValid() const {
2946     lldb::StateType state = m_private_state.GetValue();
2947     return state != lldb::eStateInvalid && state != lldb::eStateDetached &&
2948            state != lldb::eStateExited && m_private_state_thread.IsJoinable();
2949   }
2950
2951   void ForceNextEventDelivery() { m_force_next_event_delivery = true; }
2952
2953   //------------------------------------------------------------------
2954   /// Loads any plugins associated with asynchronous structured data
2955   /// and maps the relevant supported type name to the plugin.
2956   ///
2957   /// Processes can receive asynchronous structured data from the
2958   /// process monitor.  This method will load and map any structured
2959   /// data plugins that support the given set of supported type names.
2960   /// Later, if any of these features are enabled, the process monitor
2961   /// is free to generate asynchronous structured data.  The data must
2962   /// come in as a single \b StructuredData::Dictionary.  That dictionary
2963   /// must have a string field named 'type', with a value that equals
2964   /// the relevant type name string (one of the values in
2965   /// \b supported_type_names).
2966   ///
2967   /// @param[in] supported_type_names
2968   ///     An array of zero or more type names.  Each must be unique.
2969   ///     For each entry in the list, a StructuredDataPlugin will be
2970   ///     searched for that supports the structured data type name.
2971   //------------------------------------------------------------------
2972   void MapSupportedStructuredDataPlugins(
2973       const StructuredData::Array &supported_type_names);
2974
2975   //------------------------------------------------------------------
2976   /// Route the incoming structured data dictionary to the right plugin.
2977   ///
2978   /// The incoming structured data must be a dictionary, and it must
2979   /// have a key named 'type' that stores a string value.  The string
2980   /// value must be the name of the structured data feature that
2981   /// knows how to handle it.
2982   ///
2983   /// @param[in] object_sp
2984   ///     When non-null and pointing to a dictionary, the 'type'
2985   ///     key's string value is used to look up the plugin that
2986   ///     was registered for that structured data type.  It then
2987   ///     calls the following method on the StructuredDataPlugin
2988   ///     instance:
2989   ///
2990   ///     virtual void
2991   ///     HandleArrivalOfStructuredData(Process &process,
2992   ///                                   const ConstString &type_name,
2993   ///                                   const StructuredData::ObjectSP
2994   ///                                   &object_sp)
2995   ///
2996   /// @return
2997   ///     True if the structured data was routed to a plugin; otherwise,
2998   ///     false.
2999   //------------------------------------------------------------------
3000   bool RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp);
3001
3002   //------------------------------------------------------------------
3003   // Type definitions
3004   //------------------------------------------------------------------
3005   typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP>
3006       LanguageRuntimeCollection;
3007   typedef std::unordered_set<const void *> WarningsPointerSet;
3008   typedef std::map<uint64_t, WarningsPointerSet> WarningsCollection;
3009
3010   struct PreResumeCallbackAndBaton {
3011     bool (*callback)(void *);
3012     void *baton;
3013     PreResumeCallbackAndBaton(PreResumeActionCallback in_callback,
3014                               void *in_baton)
3015         : callback(in_callback), baton(in_baton) {}
3016     bool operator== (const PreResumeCallbackAndBaton &rhs) {
3017       return callback == rhs.callback && baton == rhs.baton;
3018     }
3019   };
3020
3021   using StructuredDataPluginMap =
3022       std::map<ConstString, lldb::StructuredDataPluginSP>;
3023
3024   //------------------------------------------------------------------
3025   // Member variables
3026   //------------------------------------------------------------------
3027   std::weak_ptr<Target> m_target_sp; ///< The target that owns this process.
3028   ThreadSafeValue<lldb::StateType> m_public_state;
3029   ThreadSafeValue<lldb::StateType>
3030       m_private_state;                     // The actual state of our process
3031   Broadcaster m_private_state_broadcaster; // This broadcaster feeds state
3032                                            // changed events into the private
3033                                            // state thread's listener.
3034   Broadcaster m_private_state_control_broadcaster; // This is the control
3035                                                    // broadcaster, used to
3036                                                    // pause, resume & stop the
3037                                                    // private state thread.
3038   lldb::ListenerSP m_private_state_listener_sp; // This is the listener for the
3039                                                 // private state thread.
3040   HostThread m_private_state_thread; ///< Thread ID for the thread that watches
3041                                      ///internal state events
3042   ProcessModID m_mod_id; ///< Tracks the state of the process over stops and
3043                          ///other alterations.
3044   uint32_t m_process_unique_id; ///< Each lldb_private::Process class that is
3045                                 ///created gets a unique integer ID that
3046                                 ///increments with each new instance
3047   uint32_t m_thread_index_id;   ///< Each thread is created with a 1 based index
3048                                 ///that won't get re-used.
3049   std::map<uint64_t, uint32_t> m_thread_id_to_index_id_map;
3050   int m_exit_status; ///< The exit status of the process, or -1 if not set.
3051   std::string m_exit_string; ///< A textual description of why a process exited.
3052   std::mutex m_exit_status_mutex; ///< Mutex so m_exit_status m_exit_string can
3053                                   ///be safely accessed from multiple threads
3054   std::recursive_mutex m_thread_mutex;
3055   ThreadList m_thread_list_real; ///< The threads for this process as are known
3056                                  ///to the protocol we are debugging with
3057   ThreadList m_thread_list; ///< The threads for this process as the user will
3058                             ///see them. This is usually the same as
3059   ///< m_thread_list_real, but might be different if there is an OS plug-in
3060   ///creating memory threads
3061   ThreadList m_extended_thread_list; ///< Owner for extended threads that may be
3062                                      ///generated, cleared on natural stops
3063   uint32_t m_extended_thread_stop_id; ///< The natural stop id when
3064                                       ///extended_thread_list was last updated
3065   QueueList
3066       m_queue_list; ///< The list of libdispatch queues at a given stop point
3067   uint32_t m_queue_list_stop_id; ///< The natural stop id when queue list was
3068                                  ///last fetched
3069   std::vector<Notifications> m_notifications; ///< The list of notifications
3070                                               ///that this process can deliver.
3071   std::vector<lldb::addr_t> m_image_tokens;
3072   lldb::ListenerSP m_listener_sp; ///< Shared pointer to the listener used for
3073                                   ///public events.  Can not be empty.
3074   BreakpointSiteList m_breakpoint_site_list; ///< This is the list of breakpoint
3075                                              ///locations we intend to insert in
3076                                              ///the target.
3077   lldb::DynamicLoaderUP m_dyld_ap;
3078   lldb::JITLoaderListUP m_jit_loaders_ap;
3079   lldb::DynamicCheckerFunctionsUP m_dynamic_checkers_ap; ///< The functions used
3080                                                          ///by the expression
3081                                                          ///parser to validate
3082                                                          ///data that
3083                                                          ///expressions use.
3084   lldb::OperatingSystemUP m_os_ap;
3085   lldb::SystemRuntimeUP m_system_runtime_ap;
3086   lldb::UnixSignalsSP
3087       m_unix_signals_sp; /// This is the current signal set for this process.
3088   lldb::ABISP m_abi_sp;
3089   lldb::IOHandlerSP m_process_input_reader;
3090   Communication m_stdio_communication;
3091   std::recursive_mutex m_stdio_communication_mutex;
3092   bool m_stdin_forward; /// Remember if stdin must be forwarded to remote debug
3093                         /// server
3094   std::string m_stdout_data;
3095   std::string m_stderr_data;
3096   std::recursive_mutex m_profile_data_comm_mutex;
3097   std::vector<std::string> m_profile_data;
3098   Predicate<uint32_t> m_iohandler_sync;
3099   MemoryCache m_memory_cache;
3100   AllocatedMemoryCache m_allocated_memory_cache;
3101   bool m_should_detach; /// Should we detach if the process object goes away
3102                         /// with an explicit call to Kill or Detach?
3103   LanguageRuntimeCollection m_language_runtimes;
3104   InstrumentationRuntimeCollection m_instrumentation_runtimes;
3105   std::unique_ptr<NextEventAction> m_next_event_action_ap;
3106   std::vector<PreResumeCallbackAndBaton> m_pre_resume_actions;
3107   ProcessRunLock m_public_run_lock;
3108   ProcessRunLock m_private_run_lock;
3109   ArchSpec::StopInfoOverrideCallbackType m_stop_info_override_callback;
3110   bool m_currently_handling_do_on_removals;
3111   bool m_resume_requested; // If m_currently_handling_event or
3112                            // m_currently_handling_do_on_removals are true,
3113                            // Resume will only request a resume, using this flag
3114                            // to check.
3115   bool m_finalizing; // This is set at the beginning of Process::Finalize() to
3116                      // stop functions from looking up or creating things during
3117                      // a finalize call
3118   bool m_finalize_called; // This is set at the end of Process::Finalize()
3119   bool m_clear_thread_plans_on_stop;
3120   bool m_force_next_event_delivery;
3121   lldb::StateType m_last_broadcast_state; /// This helps with the Public event
3122                                           /// coalescing in
3123                                           /// ShouldBroadcastEvent.
3124   std::map<lldb::addr_t, lldb::addr_t> m_resolved_indirect_addresses;
3125   bool m_destroy_in_process;
3126   bool m_can_interpret_function_calls;  // Some targets, e.g the OSX kernel,
3127                                         // don't support the ability to modify
3128                                         // the stack.
3129   WarningsCollection m_warnings_issued; // A set of object pointers which have
3130                                         // already had warnings printed
3131   std::mutex m_run_thread_plan_lock;
3132   StructuredDataPluginMap m_structured_data_plugin_map;
3133
3134   enum { eCanJITDontKnow = 0, eCanJITYes, eCanJITNo } m_can_jit;
3135
3136   size_t RemoveBreakpointOpcodesFromBuffer(lldb::addr_t addr, size_t size,
3137                                            uint8_t *buf) const;
3138
3139   void SynchronouslyNotifyStateChanged(lldb::StateType state);
3140
3141   void SetPublicState(lldb::StateType new_state, bool restarted);
3142
3143   void SetPrivateState(lldb::StateType state);
3144
3145   bool StartPrivateStateThread(bool is_secondary_thread = false);
3146
3147   void StopPrivateStateThread();
3148
3149   void PausePrivateStateThread();
3150
3151   void ResumePrivateStateThread();
3152
3153 private:
3154   struct PrivateStateThreadArgs {
3155     PrivateStateThreadArgs(Process *p, bool s)
3156         : process(p), is_secondary_thread(s){};
3157     Process *process;
3158     bool is_secondary_thread;
3159   };
3160
3161   // arg is a pointer to a new'ed PrivateStateThreadArgs structure.
3162   // PrivateStateThread will free it for you.
3163   static lldb::thread_result_t PrivateStateThread(void *arg);
3164
3165   // The starts up the private state thread that will watch for events from the
3166   // debugee.
3167   // Pass true for is_secondary_thread in the case where you have to temporarily
3168   // spin up a
3169   // secondary state thread to handle events from a hand-called function on the
3170   // primary
3171   // private state thread.
3172
3173   lldb::thread_result_t RunPrivateStateThread(bool is_secondary_thread);
3174
3175 protected:
3176   void HandlePrivateEvent(lldb::EventSP &event_sp);
3177
3178   Status HaltPrivate();
3179
3180   lldb::StateType WaitForProcessStopPrivate(lldb::EventSP &event_sp,
3181                                             const Timeout<std::micro> &timeout);
3182
3183   // This waits for both the state change broadcaster, and the control
3184   // broadcaster.
3185   // If control_only, it only waits for the control broadcaster.
3186
3187   bool GetEventsPrivate(lldb::EventSP &event_sp,
3188                         const Timeout<std::micro> &timeout, bool control_only);
3189
3190   lldb::StateType
3191   GetStateChangedEventsPrivate(lldb::EventSP &event_sp,
3192                                const Timeout<std::micro> &timeout);
3193
3194   size_t WriteMemoryPrivate(lldb::addr_t addr, const void *buf, size_t size,
3195                             Status &error);
3196
3197   void AppendSTDOUT(const char *s, size_t len);
3198
3199   void AppendSTDERR(const char *s, size_t len);
3200
3201   void BroadcastAsyncProfileData(const std::string &one_profile_data);
3202
3203   static void STDIOReadThreadBytesReceived(void *baton, const void *src,
3204                                            size_t src_len);
3205
3206   bool PushProcessIOHandler();
3207
3208   bool PopProcessIOHandler();
3209
3210   bool ProcessIOHandlerIsActive();
3211
3212   bool ProcessIOHandlerExists() const {
3213     return static_cast<bool>(m_process_input_reader);
3214   }
3215
3216   Status StopForDestroyOrDetach(lldb::EventSP &exit_event_sp);
3217
3218   virtual Status UpdateAutomaticSignalFiltering();
3219
3220   bool StateChangedIsExternallyHijacked();
3221
3222   void LoadOperatingSystemPlugin(bool flush);
3223
3224 private:
3225   //------------------------------------------------------------------
3226   /// This is the part of the event handling that for a process event.
3227   /// It decides what to do with the event and returns true if the
3228   /// event needs to be propagated to the user, and false otherwise.
3229   /// If the event is not propagated, this call will most likely set
3230   /// the target to executing again.
3231   /// There is only one place where this call should be called,
3232   /// HandlePrivateEvent.
3233   /// Don't call it from anywhere else...
3234   ///
3235   /// @param[in] event_ptr
3236   ///     This is the event we are handling.
3237   ///
3238   /// @return
3239   ///     Returns \b true if the event should be reported to the
3240   ///     user, \b false otherwise.
3241   //------------------------------------------------------------------
3242   bool ShouldBroadcastEvent(Event *event_ptr);
3243
3244   void ControlPrivateStateThread(uint32_t signal);
3245
3246   DISALLOW_COPY_AND_ASSIGN(Process);
3247 };
3248
3249 } // namespace lldb_private
3250
3251 #endif // liblldb_Process_h_