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