Process.h revision 54e7afa84d945f9137f9372ecde432f9e1a702fc
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// C Includes
14// C++ Includes
15#include <list>
16
17// Other libraries and framework includes
18// Project includes
19#include "lldb/lldb-private.h"
20#include "lldb/Core/Broadcaster.h"
21#include "lldb/Core/Error.h"
22#include "lldb/Core/Event.h"
23#include "lldb/Core/ThreadSafeValue.h"
24#include "lldb/Core/ThreadSafeSTLMap.h"
25#include "lldb/Core/PluginInterface.h"
26#include "lldb/Breakpoint/BreakpointSiteList.h"
27#include "lldb/Target/ExecutionContextScope.h"
28#include "lldb/Target/ObjCObjectPrinter.h"
29#include "lldb/Target/ThreadList.h"
30#include "lldb/Target/UnixSignals.h"
31
32namespace lldb_private {
33
34//----------------------------------------------------------------------
35/// @class Process Process.h "lldb/Target/Process.h"
36/// @brief A plug-in interface definition class for debugging a process.
37//----------------------------------------------------------------------
38class Process :
39    public UserID,
40    public Broadcaster,
41    public ExecutionContextScope,
42    public PluginInterface
43{
44friend class ThreadList;
45
46public:
47
48    //------------------------------------------------------------------
49    /// Broadcaster event bits definitions.
50    //------------------------------------------------------------------
51    enum
52    {
53        eBroadcastBitStateChanged   = (1 << 0),
54        eBroadcastBitInterrupt      = (1 << 1),
55        eBroadcastBitSTDOUT         = (1 << 2),
56        eBroadcastBitSTDERR         = (1 << 3)
57    };
58
59    enum
60    {
61        eBroadcastInternalStateControlStop = (1<<0),
62        eBroadcastInternalStateControlPause = (1<<1),
63        eBroadcastInternalStateControlResume = (1<<2)
64    };
65
66    //------------------------------------------------------------------
67    /// A notification structure that can be used by clients to listen
68    /// for changes in a process's lifetime.
69    ///
70    /// @see RegisterNotificationCallbacks (const Notifications&)
71    /// @see UnregisterNotificationCallbacks (const Notifications&)
72    //------------------------------------------------------------------
73#ifndef SWIG
74    typedef struct
75    {
76        void *baton;
77        void (*initialize)(void *baton, Process *process);
78        void (*process_state_changed) (void *baton, Process *process, lldb::StateType state);
79    } Notifications;
80
81    class ProcessEventData :
82        public EventData
83    {
84        public:
85            ProcessEventData ();
86            ProcessEventData (const lldb::ProcessSP &process, lldb::StateType state);
87
88            virtual ~ProcessEventData();
89
90            static const ConstString &
91            GetFlavorString ();
92
93            virtual const ConstString &
94            GetFlavor () const;
95
96            const lldb::ProcessSP &
97            GetProcessSP() const;
98
99            lldb::StateType
100            GetState() const;
101
102            bool
103            GetRestarted () const;
104
105            virtual void
106            Dump (Stream *s) const;
107
108            virtual void
109            DoOnRemoval (Event *event_ptr);
110
111            static const Process::ProcessEventData *
112            GetEventDataFromEvent (const Event *event_ptr);
113
114            static lldb::ProcessSP
115            GetProcessFromEvent (const Event *event_ptr);
116
117            static lldb::StateType
118            GetStateFromEvent (const Event *event_ptr);
119
120            static bool
121            GetRestartedFromEvent (const Event *event_ptr);
122
123            static void
124            SetRestartedInEvent (Event *event_ptr, bool new_value);
125
126            static bool
127            SetUpdateStateOnRemoval (Event *event_ptr);
128
129
130       private:
131
132            void
133            SetUpdateStateOnRemoval();
134
135            void
136            SetRestarted (bool new_value);
137
138            lldb::ProcessSP m_process_sp;
139            lldb::StateType m_state;
140            bool m_restarted;  // For "eStateStopped" events, this is true if the target was automatically restarted.
141            bool m_update_state;
142            DISALLOW_COPY_AND_ASSIGN (ProcessEventData);
143
144    };
145#endif
146
147    //------------------------------------------------------------------
148    /// Construct with a shared pointer to a target, and the Process listener.
149    //------------------------------------------------------------------
150    Process(Target &target, Listener &listener);
151
152    //------------------------------------------------------------------
153    /// Destructor.
154    ///
155    /// The destructor is virtual since this class is designed to be
156    /// inherited from by the plug-in instance.
157    //------------------------------------------------------------------
158    virtual
159    ~Process();
160
161    //------------------------------------------------------------------
162    /// Find a Process plug-in that can debug \a module using the
163    /// currently selected architecture.
164    ///
165    /// Scans all loaded plug-in interfaces that implement versions of
166    /// the Process plug-in interface and returns the first instance
167    /// that can debug the file.
168    ///
169    /// @param[in] module_sp
170    ///     The module shared pointer that this process will debug.
171    ///
172    /// @param[in] plugin_name
173    ///     If NULL, select the best plug-in for the binary. If non-NULL
174    ///     then look for a plugin whose PluginInfo's name matches
175    ///     this string.
176    ///
177    /// @see Process::CanDebug ()
178    //------------------------------------------------------------------
179    static Process*
180    FindPlugin (Target &target, const char *plugin_name, Listener &listener);
181
182
183
184    //------------------------------------------------------------------
185    /// Static function that can be used with the \b host function
186    /// Host::StartMonitoringChildProcess ().
187    ///
188    /// This function can be used by lldb_private::Process subclasses
189    /// when they want to watch for a local process and have its exit
190    /// status automatically set when the host child process exits.
191    /// Subclasses should call Host::StartMonitoringChildProcess ()
192    /// with:
193    ///     callback = Process::SetHostProcessExitStatus
194    ///     callback_baton = NULL
195    ///     pid = Process::GetID()
196    ///     monitor_signals = false
197    //------------------------------------------------------------------
198    static bool
199    SetProcessExitStatus (void *callback_baton,   // The callback baton which should be set to NULL
200                          lldb::pid_t pid,        // The process ID we want to monitor
201                          int signo,              // Zero for no signal
202                          int status);            // Exit value of process if signal is zero
203
204    //------------------------------------------------------------------
205    /// Check if a plug-in instance can debug the file in \a module.
206    ///
207    /// Each plug-in is given a chance to say wether it can debug
208    /// the file in \a module. If the Process plug-in instance can
209    /// debug a file on the current system, it should return \b true.
210    ///
211    /// @return
212    ///     Returns \b true if this Process plug-in instance can
213    ///     debug the executable, \b false otherwise.
214    //------------------------------------------------------------------
215    virtual bool
216    CanDebug (Target &target) = 0;
217
218
219    //------------------------------------------------------------------
220    /// This object is about to be destroyed, do any necessary cleanup.
221    ///
222    /// Subclasses that override this method should always call this
223    /// superclass method.
224    //------------------------------------------------------------------
225    virtual void
226    Finalize();
227
228    //------------------------------------------------------------------
229    /// Launch a new process.
230    ///
231    /// Launch a new process by spawning a new process using the
232    /// target object's executable module's file as the file to launch.
233    /// Arguments are given in \a argv, and the environment variables
234    /// are in \a envp. Standard input and output files can be
235    /// optionally re-directed to \a stdin_path, \a stdout_path, and
236    /// \a stderr_path.
237    ///
238    /// This function is not meant to be overridden by Process
239    /// subclasses. It will first call Process::WillLaunch (Module *)
240    /// and if that returns \b true, Process::DoLaunch (Module*,
241    /// char const *[],char const *[],const char *,const char *,
242    /// const char *) will be called to actually do the launching. If
243    /// DoLaunch returns \b true, then Process::DidLaunch() will be
244    /// called.
245    ///
246    /// @param[in] argv
247    ///     The argument array.
248    ///
249    /// @param[in] envp
250    ///     The environment array.
251    ///
252    /// @param[in] stdin_path
253    ///     The path to use when re-directing the STDIN of the new
254    ///     process. If all stdXX_path arguments are NULL, a pseudo
255    ///     terminal will be used.
256    ///
257    /// @param[in] stdout_path
258    ///     The path to use when re-directing the STDOUT of the new
259    ///     process. If all stdXX_path arguments are NULL, a pseudo
260    ///     terminal will be used.
261    ///
262    /// @param[in] stderr_path
263    ///     The path to use when re-directing the STDERR of the new
264    ///     process. If all stdXX_path arguments are NULL, a pseudo
265    ///     terminal will be used.
266    ///
267    /// @return
268    ///     An error object. Call GetID() to get the process ID if
269    ///     the error object is success.
270    //------------------------------------------------------------------
271    virtual Error
272    Launch (char const *argv[],
273            char const *envp[],
274            const char *stdin_path,
275            const char *stdout_path,
276            const char *stderr_path);
277
278    //------------------------------------------------------------------
279    /// Attach to an existing process using a process ID.
280    ///
281    /// This function is not meant to be overridden by Process
282    /// subclasses. It will first call Process::WillAttach (lldb::pid_t)
283    /// and if that returns \b true, Process::DoAttach (lldb::pid_t) will
284    /// be called to actually do the attach. If DoAttach returns \b
285    /// true, then Process::DidAttach() will be called.
286    ///
287    /// @param[in] pid
288    ///     The process ID that we should attempt to attach to.
289    ///
290    /// @return
291    ///     Returns \a pid if attaching was successful, or
292    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
293    //------------------------------------------------------------------
294    virtual Error
295    Attach (lldb::pid_t pid);
296
297    //------------------------------------------------------------------
298    /// Attach to an existing process by process name.
299    ///
300    /// This function is not meant to be overridden by Process
301    /// subclasses. It will first call
302    /// Process::WillAttach (const char *) and if that returns \b
303    /// true, Process::DoAttach (const char *) will be called to
304    /// actually do the attach. If DoAttach returns \b true, then
305    /// Process::DidAttach() will be called.
306    ///
307    /// @param[in] process_name
308    ///     A process name to match against the current process list.
309    ///
310    /// @return
311    ///     Returns \a pid if attaching was successful, or
312    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
313    //------------------------------------------------------------------
314    virtual Error
315    Attach (const char *process_name, bool wait_for_launch);
316
317    uint32_t
318    GetAddressByteSize();
319
320    //------------------------------------------------------------------
321    /// Get the image information address for the current process.
322    ///
323    /// Some runtimes have system functions that can help dynamic
324    /// loaders locate the dynamic loader information needed to observe
325    /// shared libraries being loaded or unloaded. This function is
326    /// in the Process interface (as opposed to the DynamicLoader
327    /// interface) to ensure that remote debugging can take advantage of
328    /// this functionality.
329    ///
330    /// @return
331    ///     The address of the dynamic loader information, or
332    ///     LLDB_INVALID_ADDRESS if this is not supported by this
333    ///     interface.
334    //------------------------------------------------------------------
335    virtual lldb::addr_t
336    GetImageInfoAddress ();
337
338    //------------------------------------------------------------------
339    /// Register for process and thread notifications.
340    ///
341    /// Clients can register nofication callbacks by filling out a
342    /// Process::Notifications structure and calling this function.
343    ///
344    /// @param[in] callbacks
345    ///     A structure that contains the notification baton and
346    ///     callback functions.
347    ///
348    /// @see Process::Notifications
349    //------------------------------------------------------------------
350#ifndef SWIG
351    void
352    RegisterNotificationCallbacks (const Process::Notifications& callbacks);
353#endif
354    //------------------------------------------------------------------
355    /// Unregister for process and thread notifications.
356    ///
357    /// Clients can unregister nofication callbacks by passing a copy of
358    /// the original baton and callbacks in \a callbacks.
359    ///
360    /// @param[in] callbacks
361    ///     A structure that contains the notification baton and
362    ///     callback functions.
363    ///
364    /// @return
365    ///     Returns \b true if the notification callbacks were
366    ///     successfully removed from the process, \b false otherwise.
367    ///
368    /// @see Process::Notifications
369    //------------------------------------------------------------------
370#ifndef SWIG
371    bool
372    UnregisterNotificationCallbacks (const Process::Notifications& callbacks);
373#endif
374    //==================================================================
375    // Built in Process Control functions
376    //==================================================================
377    //------------------------------------------------------------------
378    /// Resumes all of a process's threads as configured using the
379    /// Thread run control functions.
380    ///
381    /// Threads for a process should be updated with one of the run
382    /// control actions (resume, step, or suspend) that they should take
383    /// when the process is resumed. If no run control action is given
384    /// to a thread it will be resumed by default.
385    ///
386    /// This function is not meant to be overridden by Process
387    /// subclasses. This function will take care of disabling any
388    /// breakpoints that threads may be stopped at, single stepping, and
389    /// re-enabling breakpoints, and enabling the basic flow control
390    /// that the plug-in instances need not worry about.
391    ///
392    /// @return
393    ///     Returns an error object.
394    ///
395    /// @see Thread:Resume()
396    /// @see Thread:Step()
397    /// @see Thread:Suspend()
398    //------------------------------------------------------------------
399    virtual Error
400    Resume ();
401
402    //------------------------------------------------------------------
403    /// Halts a running process.
404    ///
405    /// This function is not meant to be overridden by Process
406    /// subclasses.
407    ///
408    /// @return
409    ///     Returns an error object.
410    //------------------------------------------------------------------
411    virtual Error
412    Halt ();
413
414    //------------------------------------------------------------------
415    /// Detaches from a running or stopped process.
416    ///
417    /// This function is not meant to be overridden by Process
418    /// subclasses.
419    ///
420    /// @return
421    ///     Returns an error object.
422    //------------------------------------------------------------------
423    virtual Error
424    Detach ();
425
426    //------------------------------------------------------------------
427    /// Kills the process and shuts down all threads that were spawned
428    /// to track and monitor the process.
429    ///
430    /// This function is not meant to be overridden by Process
431    /// subclasses.
432    ///
433    /// @return
434    ///     Returns an error object.
435    //------------------------------------------------------------------
436    virtual Error
437    Destroy();
438
439    //------------------------------------------------------------------
440    /// Sends a process a UNIX signal \a signal.
441    ///
442    /// This function is not meant to be overridden by Process
443    /// subclasses.
444    ///
445    /// @return
446    ///     Returns an error object.
447    //------------------------------------------------------------------
448    virtual Error
449    Signal (int signal);
450
451    virtual UnixSignals &
452    GetUnixSignals ();
453
454
455    //==================================================================
456    // Plug-in Process Control Overrides
457    //==================================================================
458
459    //------------------------------------------------------------------
460    /// Called before attaching to a process.
461    ///
462    /// Allow Process plug-ins to execute some code before attaching a
463    /// process.
464    ///
465    /// @return
466    ///     Returns an error object.
467    //------------------------------------------------------------------
468    virtual Error
469    WillAttachToProcessWithID (lldb::pid_t pid)
470    {
471        return Error();
472    }
473
474    //------------------------------------------------------------------
475    /// Called before attaching to a process.
476    ///
477    /// Allow Process plug-ins to execute some code before attaching a
478    /// process.
479    ///
480    /// @return
481    ///     Returns an error object.
482    //------------------------------------------------------------------
483    virtual Error
484    WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
485    {
486        return Error();
487    }
488
489    //------------------------------------------------------------------
490    /// Attach to an existing process using a process ID.
491    ///
492    /// @param[in] pid
493    ///     The process ID that we should attempt to attach to.
494    ///
495    /// @return
496    ///     Returns \a pid if attaching was successful, or
497    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
498    //------------------------------------------------------------------
499    virtual Error
500    DoAttachToProcessWithID (lldb::pid_t pid) = 0;
501
502    //------------------------------------------------------------------
503    /// Attach to an existing process using a partial process name.
504    ///
505    /// @param[in] process_name
506    ///     The name of the process to attach to.
507    ///
508    /// @param[in] wait_for_launch
509    ///     If \b true, wait for the process to be launched and attach
510    ///     as soon as possible after it does launch. If \b false, then
511    ///     search for a matching process the currently exists.
512    ///
513    /// @return
514    ///     Returns \a pid if attaching was successful, or
515    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
516    //------------------------------------------------------------------
517    virtual Error
518    DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
519    {
520        Error error;
521        error.SetErrorString("attach by name is not supported");
522        return error;
523    }
524
525    //------------------------------------------------------------------
526    /// Called after attaching a process.
527    ///
528    /// Allow Process plug-ins to execute some code after attaching to
529    /// a process.
530    //------------------------------------------------------------------
531    virtual void
532    DidAttach () {}
533
534
535    //------------------------------------------------------------------
536    /// Called before launching to a process.
537    ///
538    /// Allow Process plug-ins to execute some code before launching a
539    /// process.
540    ///
541    /// @return
542    ///     Returns an error object.
543    //------------------------------------------------------------------
544    virtual Error
545    WillLaunch (Module* module)
546    {
547        return Error();
548    }
549
550    //------------------------------------------------------------------
551    /// Launch a new process.
552    ///
553    /// Launch a new process by spawning a new process using \a module's
554    /// file as the file to launch. Arguments are given in \a argv,
555    /// and the environment variables are in \a envp. Standard input
556    /// and output files can be optionally re-directed to \a stdin_path,
557    /// \a stdout_path, and \a stderr_path.
558    ///
559    /// @param[in] module
560    ///     The module from which to extract the file specification and
561    ///     launch.
562    ///
563    /// @param[in] argv
564    ///     The argument array.
565    ///
566    /// @param[in] envp
567    ///     The environment array.
568    ///
569    /// @param[in] stdin_path
570    ///     The path to use when re-directing the STDIN of the new
571    ///     process. If all stdXX_path arguments are NULL, a pseudo
572    ///     terminal will be used.
573    ///
574    /// @param[in] stdout_path
575    ///     The path to use when re-directing the STDOUT of the new
576    ///     process. If all stdXX_path arguments are NULL, a pseudo
577    ///     terminal will be used.
578    ///
579    /// @param[in] stderr_path
580    ///     The path to use when re-directing the STDERR of the new
581    ///     process. If all stdXX_path arguments are NULL, a pseudo
582    ///     terminal will be used.
583    ///
584    /// @return
585    ///     A new valid process ID, or LLDB_INVALID_PROCESS_ID if
586    ///     launching fails.
587    //------------------------------------------------------------------
588    virtual Error
589    DoLaunch (Module* module,
590              char const *argv[],
591              char const *envp[],
592              const char *stdin_path,
593              const char *stdout_path,
594              const char *stderr_path) = 0;
595
596    //------------------------------------------------------------------
597    /// Called after launching a process.
598    ///
599    /// Allow Process plug-ins to execute some code after launching
600    /// a process.
601    //------------------------------------------------------------------
602    virtual void
603    DidLaunch () {}
604
605
606
607    //------------------------------------------------------------------
608    /// Called before resuming to a process.
609    ///
610    /// Allow Process plug-ins to execute some code before resuming a
611    /// process.
612    ///
613    /// @return
614    ///     Returns an error object.
615    //------------------------------------------------------------------
616    virtual Error
617    WillResume () { return Error(); }
618
619    //------------------------------------------------------------------
620    /// Resumes all of a process's threads as configured using the
621    /// Thread run control functions.
622    ///
623    /// Threads for a process should be updated with one of the run
624    /// control actions (resume, step, or suspend) that they should take
625    /// when the process is resumed. If no run control action is given
626    /// to a thread it will be resumed by default.
627    ///
628    /// @return
629    ///     Returns \b true if the process successfully resumes using
630    ///     the thread run control actions, \b false otherwise.
631    ///
632    /// @see Thread:Resume()
633    /// @see Thread:Step()
634    /// @see Thread:Suspend()
635    //------------------------------------------------------------------
636    virtual Error
637    DoResume () = 0;
638
639    //------------------------------------------------------------------
640    /// Called after resuming a process.
641    ///
642    /// Allow Process plug-ins to execute some code after resuming
643    /// a process.
644    //------------------------------------------------------------------
645    virtual void
646    DidResume () {}
647
648
649    //------------------------------------------------------------------
650    /// Called before halting to a process.
651    ///
652    /// Allow Process plug-ins to execute some code before halting a
653    /// process.
654    ///
655    /// @return
656    ///     Returns an error object.
657    //------------------------------------------------------------------
658    virtual Error
659    WillHalt () { return Error(); }
660
661    //------------------------------------------------------------------
662    /// Halts a running process.
663    ///
664    /// @return
665    ///     Returns \b true if the process successfully halts, \b false
666    ///     otherwise.
667    //------------------------------------------------------------------
668    virtual Error
669    DoHalt () = 0;
670
671    //------------------------------------------------------------------
672    /// Called after halting a process.
673    ///
674    /// Allow Process plug-ins to execute some code after halting
675    /// a process.
676    //------------------------------------------------------------------
677    virtual void
678    DidHalt () {}
679
680    //------------------------------------------------------------------
681    /// Called before detaching from a process.
682    ///
683    /// Allow Process plug-ins to execute some code before detaching
684    /// from a process.
685    ///
686    /// @return
687    ///     Returns an error object.
688    //------------------------------------------------------------------
689    virtual Error
690    WillDetach ()
691    {
692        return Error();
693    }
694
695    //------------------------------------------------------------------
696    /// Detaches from a running or stopped process.
697    ///
698    /// @return
699    ///     Returns \b true if the process successfully detaches, \b
700    ///     false otherwise.
701    //------------------------------------------------------------------
702    virtual Error
703    DoDetach () = 0;
704
705    //------------------------------------------------------------------
706    /// Called after detaching from a process.
707    ///
708    /// Allow Process plug-ins to execute some code after detaching
709    /// from a process.
710    //------------------------------------------------------------------
711    virtual void
712    DidDetach () {}
713
714    //------------------------------------------------------------------
715    /// Called before sending a signal to a process.
716    ///
717    /// Allow Process plug-ins to execute some code before sending a
718    /// signal to a process.
719    ///
720    /// @return
721    ///     Returns no error if it is safe to proceed with a call to
722    ///     Process::DoSignal(int), otherwise an error describing what
723    ///     prevents the signal from being sent.
724    //------------------------------------------------------------------
725    virtual Error
726    WillSignal () { return Error(); }
727
728    //------------------------------------------------------------------
729    /// Sends a process a UNIX signal \a signal.
730    ///
731    /// @return
732    ///     Returns an error object.
733    //------------------------------------------------------------------
734    virtual Error
735    DoSignal (int signal) = 0;
736
737
738
739    virtual Error
740    WillDestroy () { return Error(); }
741
742    virtual Error
743    DoDestroy () = 0;
744
745    virtual void
746    DidDestroy () { }
747
748
749    //------------------------------------------------------------------
750    /// Called after sending a signal to a process.
751    ///
752    /// Allow Process plug-ins to execute some code after sending a
753    /// signal to a process.
754    //------------------------------------------------------------------
755    virtual void
756    DidSignal () {}
757
758
759    //------------------------------------------------------------------
760    /// Currently called as part of ShouldStop.
761    /// FIXME: Should really happen when the target stops before the
762    /// event is taken from the queue...
763    ///
764    /// This callback is called as the event
765    /// is about to be queued up to allow Process plug-ins to execute
766    /// some code prior to clients being notified that a process was
767    /// stopped. Common operations include updating the thread list,
768    /// invalidating any thread state (registers, stack, etc) prior to
769    /// letting the notification go out.
770    ///
771    //------------------------------------------------------------------
772    virtual void
773    RefreshStateAfterStop () = 0;
774
775    //------------------------------------------------------------------
776    /// Get the target object pointer for this module.
777    ///
778    /// @return
779    ///     A Target object pointer to the target that owns this
780    ///     module.
781    //------------------------------------------------------------------
782    Target &
783    GetTarget ();
784
785    //------------------------------------------------------------------
786    /// Get the const target object pointer for this module.
787    ///
788    /// @return
789    ///     A const Target object pointer to the target that owns this
790    ///     module.
791    //------------------------------------------------------------------
792    const Target &
793    GetTarget () const;
794
795    //------------------------------------------------------------------
796    /// Get accessor for the current process state.
797    ///
798    /// @return
799    ///     The current state of the process.
800    ///
801    /// @see lldb::StateType
802    //------------------------------------------------------------------
803    lldb::StateType
804    GetState ();
805
806protected:
807    friend class CommandObjectProcessLaunch;
808    friend class ProcessEventData;
809    friend class CommandObjectBreakpointCommand;
810
811    void
812    SetState (lldb::EventSP &event_sp);
813
814    lldb::StateType
815    GetPrivateState ();
816
817public:
818    //------------------------------------------------------------------
819    /// Get the exit status for a process.
820    ///
821    /// @return
822    ///     The process's return code, or -1 if the current process
823    ///     state is not eStateExited.
824    //------------------------------------------------------------------
825    int
826    GetExitStatus ();
827
828    //------------------------------------------------------------------
829    /// Get a textual description of what the process exited.
830    ///
831    /// @return
832    ///     The textual description of why the process exited, or NULL
833    ///     if there is no description available.
834    //------------------------------------------------------------------
835    const char *
836    GetExitDescription ();
837
838
839    virtual void
840    DidExit ()
841    {
842    }
843
844    //------------------------------------------------------------------
845    /// Get the number of times this process has posted a stop event.
846    ///
847    /// @return
848    ///     The number of times this process has stopped while being
849    ///     debugged.
850    //------------------------------------------------------------------
851    uint32_t
852    GetStopID () const;
853
854    //------------------------------------------------------------------
855    /// Set accessor for the process exit status (return code).
856    ///
857    /// Sometimes a child exits and the exit can be detected by global
858    /// functions (signal handler for SIGCHLD for example). This
859    /// accessor allows the exit status to be set from an external
860    /// source.
861    ///
862    /// Setting this will cause a eStateExited event to be posted to
863    /// the process event queue.
864    ///
865    /// @param[in] exit_status
866    ///     The value for the process's return code.
867    ///
868    /// @see lldb::StateType
869    //------------------------------------------------------------------
870    virtual void
871    SetExitStatus (int exit_status, const char *cstr);
872
873    //------------------------------------------------------------------
874    /// Check if a process is still alive.
875    ///
876    /// @return
877    ///     Returns \b true if the process is still valid, \b false
878    ///     otherwise.
879    //------------------------------------------------------------------
880    virtual bool
881    IsAlive () = 0;
882
883    //------------------------------------------------------------------
884    /// Actually do the reading of memory from a process.
885    ///
886    /// Subclasses must override this function and can return fewer
887    /// bytes than requested when memory requests are too large. This
888    /// class will break up the memory requests and keep advancing the
889    /// arguments along as needed.
890    ///
891    /// @param[in] vm_addr
892    ///     A virtual load address that indicates where to start reading
893    ///     memory from.
894    ///
895    /// @param[in] size
896    ///     The number of bytes to read.
897    ///
898    /// @param[out] buf
899    ///     A byte buffer that is at least \a size bytes long that
900    ///     will receive the memory bytes.
901    ///
902    /// @return
903    ///     The number of bytes that were actually read into \a buf.
904    //------------------------------------------------------------------
905    virtual size_t
906    DoReadMemory (lldb::addr_t vm_addr,
907                  void *buf,
908                  size_t size,
909                  Error &error) = 0;
910
911    //------------------------------------------------------------------
912    /// Read of memory from a process.
913    ///
914    /// This function will read memory from the current process's
915    /// address space and remove any traps that may have been inserted
916    /// into the memory.
917    ///
918    /// This function is not meant to be overridden by Process
919    /// subclasses, the subclasses should implement
920    /// Process::DoReadMemory (lldb::addr_t, size_t, void *).
921    ///
922    /// @param[in] vm_addr
923    ///     A virtual load address that indicates where to start reading
924    ///     memory from.
925    ///
926    /// @param[out] buf
927    ///     A byte buffer that is at least \a size bytes long that
928    ///     will receive the memory bytes.
929    ///
930    /// @param[in] size
931    ///     The number of bytes to read.
932    ///
933    /// @return
934    ///     The number of bytes that were actually read into \a buf. If
935    ///     the returned number is greater than zero, yet less than \a
936    ///     size, then this function will get called again with \a
937    ///     vm_addr, \a buf, and \a size updated appropriately. Zero is
938    ///     returned to indicate an error.
939    //------------------------------------------------------------------
940    size_t
941    ReadMemory (lldb::addr_t vm_addr,
942                void *buf,
943                size_t size,
944                Error &error);
945
946    //------------------------------------------------------------------
947    /// Actually do the writing of memory to a process.
948    ///
949    /// @param[in] vm_addr
950    ///     A virtual load address that indicates where to start writing
951    ///     memory to.
952    ///
953    /// @param[in] buf
954    ///     A byte buffer that is at least \a size bytes long that
955    ///     contains the data to write.
956    ///
957    /// @param[in] size
958    ///     The number of bytes to write.
959    ///
960    /// @return
961    ///     The number of bytes that were actually written.
962    //------------------------------------------------------------------
963    virtual size_t
964    DoWriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error) = 0;
965
966    //------------------------------------------------------------------
967    /// Write memory to a process.
968    ///
969    /// This function will write memory to the current process's
970    /// address space and maintain any traps that might be present due
971    /// to software breakpoints.
972    ///
973    /// This function is not meant to be overridden by Process
974    /// subclasses, the subclasses should implement
975    /// Process::DoWriteMemory (lldb::addr_t, size_t, void *).
976    ///
977    /// @param[in] vm_addr
978    ///     A virtual load address that indicates where to start writing
979    ///     memory to.
980    ///
981    /// @param[in] buf
982    ///     A byte buffer that is at least \a size bytes long that
983    ///     contains the data to write.
984    ///
985    /// @param[in] size
986    ///     The number of bytes to write.
987    ///
988    /// @return
989    ///     The number of bytes that were actually written.
990    //------------------------------------------------------------------
991    size_t
992    WriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error);
993
994
995    //------------------------------------------------------------------
996    /// Actually allocate memory in the process.
997    ///
998    /// This function will allocate memory in the process's address
999    /// space.  This can't rely on the generic function calling mechanism,
1000    /// since that requires this function.
1001    ///
1002    /// @param[in] size
1003    ///     The size of the allocation requested.
1004    ///
1005    /// @return
1006    ///     The address of the allocated buffer in the process, or
1007    ///     LLDB_INVALID_ADDRESS if the allocation failed.
1008    //------------------------------------------------------------------
1009
1010    virtual lldb::addr_t
1011    DoAllocateMemory (size_t size, uint32_t permissions, Error &error) = 0;
1012
1013    //------------------------------------------------------------------
1014    /// The public interface to allocating memory in the process.
1015    ///
1016    /// This function will allocate memory in the process's address
1017    /// space.  This can't rely on the generic function calling mechanism,
1018    /// since that requires this function.
1019    ///
1020    /// @param[in] size
1021    ///     The size of the allocation requested.
1022    ///
1023    /// @param[in] permissions
1024    ///     Or together any of the lldb::Permissions bits.  The permissions on
1025    ///     a given memory allocation can't be changed after allocation.  Note
1026    ///     that a block that isn't set writable can still be written on from lldb,
1027    ///     just not by the process itself.
1028    ///
1029    /// @return
1030    ///     The address of the allocated buffer in the process, or
1031    ///     LLDB_INVALID_ADDRESS if the allocation failed.
1032    //------------------------------------------------------------------
1033
1034    lldb::addr_t
1035    AllocateMemory (size_t size, uint32_t permissions, Error &error);
1036
1037    //------------------------------------------------------------------
1038    /// Actually deallocate memory in the process.
1039    ///
1040    /// This function will deallocate memory in the process's address
1041    /// space that was allocated with AllocateMemory.
1042    ///
1043    /// @param[in] ptr
1044    ///     A return value from AllocateMemory, pointing to the memory you
1045    ///     want to deallocate.
1046    ///
1047    /// @return
1048    ///     \btrue if the memory was deallocated, \bfalse otherwise.
1049    //------------------------------------------------------------------
1050
1051    virtual Error
1052    DoDeallocateMemory (lldb::addr_t ptr) = 0;
1053
1054    //------------------------------------------------------------------
1055    /// The public interface to deallocating memory in the process.
1056    ///
1057    /// This function will deallocate memory in the process's address
1058    /// space that was allocated with AllocateMemory.
1059    ///
1060    /// @param[in] ptr
1061    ///     A return value from AllocateMemory, pointing to the memory you
1062    ///     want to deallocate.
1063    ///
1064    /// @return
1065    ///     \btrue if the memory was deallocated, \bfalse otherwise.
1066    //------------------------------------------------------------------
1067
1068    Error
1069    DeallocateMemory (lldb::addr_t ptr);
1070
1071    //------------------------------------------------------------------
1072    /// Get any available STDOUT.
1073    ///
1074    /// If the process was launched without supplying valid file paths
1075    /// for stdin, stdout, and stderr, then the Process class might
1076    /// try to cache the STDOUT for the process if it is able. Events
1077    /// will be queued indicating that there is STDOUT available that
1078    /// can be retrieved using this function.
1079    ///
1080    /// @param[out] buf
1081    ///     A buffer that will receive any STDOUT bytes that are
1082    ///     currently available.
1083    ///
1084    /// @param[out] buf_size
1085    ///     The size in bytes for the buffer \a buf.
1086    ///
1087    /// @return
1088    ///     The number of bytes written into \a buf. If this value is
1089    ///     equal to \a buf_size, another call to this function should
1090    ///     be made to retrieve more STDOUT data.
1091    //------------------------------------------------------------------
1092    virtual size_t
1093    GetSTDOUT (char *buf, size_t buf_size, Error &error)
1094    {
1095        error.SetErrorString("stdout unsupported");
1096        return 0;
1097    }
1098
1099
1100    //------------------------------------------------------------------
1101    /// Get any available STDERR.
1102    ///
1103    /// If the process was launched without supplying valid file paths
1104    /// for stdin, stdout, and stderr, then the Process class might
1105    /// try to cache the STDERR for the process if it is able. Events
1106    /// will be queued indicating that there is STDERR available that
1107    /// can be retrieved using this function.
1108    ///
1109    /// @param[out] buf
1110    ///     A buffer that will receive any STDERR bytes that are
1111    ///     currently available.
1112    ///
1113    /// @param[out] buf_size
1114    ///     The size in bytes for the buffer \a buf.
1115    ///
1116    /// @return
1117    ///     The number of bytes written into \a buf. If this value is
1118    ///     equal to \a buf_size, another call to this function should
1119    ///     be made to retrieve more STDERR data.
1120    //------------------------------------------------------------------
1121    virtual size_t
1122    GetSTDERR (char *buf, size_t buf_size, Error &error)
1123    {
1124        error.SetErrorString("stderr unsupported");
1125        return 0;
1126    }
1127
1128    virtual size_t
1129    PutSTDIN (const char *buf, size_t buf_size, Error &error)
1130    {
1131        error.SetErrorString("stdin unsupported");
1132        return 0;
1133    }
1134
1135    //----------------------------------------------------------------------
1136    // Process Breakpoints
1137    //----------------------------------------------------------------------
1138    virtual size_t
1139    GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site) = 0;
1140
1141    virtual Error
1142    EnableBreakpoint (BreakpointSite *bp_site) = 0;
1143
1144    virtual Error
1145    DisableBreakpoint (BreakpointSite *bp_site) = 0;
1146
1147    // This is implemented completely using the lldb::Process API. Subclasses
1148    // don't need to implement this function unless the standard flow of
1149    // read existing opcode, write breakpoint opcode, verify breakpoint opcode
1150    // doesn't work for a specific process plug-in.
1151    virtual Error
1152    EnableSoftwareBreakpoint (BreakpointSite *bp_site);
1153
1154    // This is implemented completely using the lldb::Process API. Subclasses
1155    // don't need to implement this function unless the standard flow of
1156    // restoring original opcode in memory and verifying the restored opcode
1157    // doesn't work for a specific process plug-in.
1158    virtual Error
1159    DisableSoftwareBreakpoint (BreakpointSite *bp_site);
1160
1161    BreakpointSiteList &
1162    GetBreakpointSiteList();
1163
1164    const BreakpointSiteList &
1165    GetBreakpointSiteList() const;
1166
1167    void
1168    DisableAllBreakpointSites ();
1169
1170    Error
1171    ClearBreakpointSiteByID (lldb::user_id_t break_id);
1172
1173    lldb::user_id_t
1174    CreateBreakpointSite (lldb::BreakpointLocationSP &owner,
1175                          bool use_hardware);
1176
1177    Error
1178    DisableBreakpointSiteByID (lldb::user_id_t break_id);
1179
1180    Error
1181    EnableBreakpointSiteByID (lldb::user_id_t break_id);
1182
1183
1184    // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove
1185    // themselves from the owner's list of this breakpoint sites.  This has to
1186    // be a static function because you can't be sure that removing the
1187    // breakpoint from it's containing map won't delete the breakpoint site,
1188    // and doing that in an instance method isn't copasetic.
1189    void
1190    RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id,
1191                                   lldb::user_id_t owner_loc_id,
1192                                   lldb::BreakpointSiteSP &bp_site_sp);
1193
1194    //----------------------------------------------------------------------
1195    // Process Watchpoints (optional)
1196    //----------------------------------------------------------------------
1197    virtual Error
1198    EnableWatchpoint (WatchpointLocation *bp_loc);
1199
1200    virtual Error
1201    DisableWatchpoint (WatchpointLocation *bp_loc);
1202
1203    //------------------------------------------------------------------
1204    // Thread Queries
1205    //------------------------------------------------------------------
1206    virtual uint32_t
1207    UpdateThreadListIfNeeded () = 0;
1208
1209    ThreadList &
1210    GetThreadList ();
1211
1212    const ThreadList &
1213    GetThreadList () const;
1214
1215    uint32_t
1216    GetNextThreadIndexID ();
1217
1218    //------------------------------------------------------------------
1219    // Event Handling
1220    //------------------------------------------------------------------
1221    lldb::StateType
1222    GetNextEvent (lldb::EventSP &event_sp);
1223
1224    lldb::StateType
1225    WaitForProcessToStop (const TimeValue *timeout);
1226
1227    lldb::StateType
1228    WaitForStateChangedEvents (const TimeValue *timeout, lldb::EventSP &event_sp);
1229
1230    Event *
1231    PeekAtStateChangedEvents ();
1232
1233    //------------------------------------------------------------------
1234    /// This is the part of the event handling that for a process event.
1235    /// It decides what to do with the event and returns true if the
1236    /// event needs to be propagated to the user, and false otherwise.
1237    /// If the event is not propagated, this call will most likely set
1238    /// the target to executing again.
1239    ///
1240    /// @param[in] event_ptr
1241    ///     This is the event we are handling.
1242    ///
1243    /// @return
1244    ///     Returns \b true if the event should be reported to the
1245    ///     user, \b false otherwise.
1246    //------------------------------------------------------------------
1247    bool
1248    ShouldBroadcastEvent (Event *event_ptr);
1249
1250    //------------------------------------------------------------------
1251    /// Gets the byte order for this process.
1252    ///
1253    /// @return
1254    ///     A valid ByteOrder enumeration, or eByteOrderInvalid.
1255    //------------------------------------------------------------------
1256    virtual lldb::ByteOrder
1257    GetByteOrder () const = 0;
1258
1259    const ConstString &
1260    GetTargetTriple ()
1261    {
1262        return m_target_triple;
1263    }
1264
1265    const ABI *
1266    GetABI ();
1267
1268    virtual DynamicLoader *
1269    GetDynamicLoader ();
1270
1271    lldb::addr_t
1272    GetSectionLoadAddress (const Section *section) const;
1273
1274    bool
1275    ResolveLoadAddress (lldb::addr_t load_addr, Address &so_addr) const;
1276
1277    bool
1278    SectionLoaded (const Section *section, lldb::addr_t load_addr);
1279
1280    // The old load address should be specified when unloading to ensure we get
1281    // the correct instance of the section as a shared library could be loaded
1282    // at more than one location.
1283    bool
1284    SectionUnloaded (const Section *section, lldb::addr_t load_addr);
1285
1286    // Unload all instances of a section. This function can be used on systems
1287    // that don't support multiple copies of the same shared library to be
1288    // loaded at the same time.
1289    size_t
1290    SectionUnloaded (const Section *section);
1291
1292    bool
1293    IsRunning () const;
1294
1295    //------------------------------------------------------------------
1296    // lldb::ExecutionContextScope pure virtual functions
1297    //------------------------------------------------------------------
1298    virtual Target *
1299    CalculateTarget ();
1300
1301    virtual Process *
1302    CalculateProcess ();
1303
1304    virtual Thread *
1305    CalculateThread ();
1306
1307    virtual StackFrame *
1308    CalculateStackFrame ();
1309
1310    virtual void
1311    Calculate (ExecutionContext &exe_ctx);
1312
1313    lldb::ProcessSP
1314    GetSP ();
1315
1316    ObjCObjectPrinter &
1317    GetObjCObjectPrinter();
1318
1319protected:
1320    typedef ThreadSafeSTLMap<lldb::addr_t, const Section *> SectionLoadColl;
1321    //------------------------------------------------------------------
1322    // Member variables
1323    //------------------------------------------------------------------
1324    Target &                    m_target;               ///< The target that owns this process.
1325    SectionLoadColl             m_section_load_info;    ///< A mapping of all currently loaded sections.
1326    ThreadSafeValue<lldb::StateType>  m_public_state;
1327    ThreadSafeValue<lldb::StateType>  m_private_state; // The actual state of our process
1328    Broadcaster                 m_private_state_broadcaster;  // This broadcaster feeds state changed events into the private state thread's listener.
1329    Broadcaster                 m_private_state_control_broadcaster; // This is the control broadcaster, used to pause, resume & stop the private state thread.
1330    Listener                    m_private_state_listener;     // This is the listener for the private state thread.
1331    Predicate<bool>             m_private_state_control_wait; /// This Predicate is used to signal that a control operation is complete.
1332    lldb::thread_t              m_private_state_thread;  // Thread ID for the thread that watches interal state events
1333    uint32_t                    m_stop_id;              ///< A count of many times the process has stopped.
1334    uint32_t                    m_thread_index_id;      ///< Each thread is created with a 1 based index that won't get re-used.
1335    int                         m_exit_status;          ///< The exit status of the process, or -1 if not set.
1336    std::string                 m_exit_string;          ///< A textual description of why a process exited.
1337    ThreadList                  m_thread_list;          ///< The threads for this process.
1338    std::vector<Notifications>  m_notifications;        ///< The list of notifications that this process can deliver.
1339    Listener                    &m_listener;
1340    BreakpointSiteList          m_breakpoint_site_list; ///< This is the list of breakpoint locations we intend
1341                                                        ///< to insert in the target.
1342    UnixSignals                 m_unix_signals;         /// This is the current signal set for this process.
1343    ConstString                 m_target_triple;
1344    lldb::ABISP                 m_abi_sp;
1345    ObjCObjectPrinter           m_objc_object_printer;
1346
1347    size_t
1348    RemoveBreakpointOpcodesFromBuffer (lldb::addr_t addr, size_t size, uint8_t *buf) const;
1349
1350    void
1351    SynchronouslyNotifyStateChanged (lldb::StateType state);
1352
1353    void
1354    SetPublicState (lldb::StateType new_state);
1355
1356    void
1357    SetPrivateState (lldb::StateType state);
1358
1359    bool
1360    StartPrivateStateThread ();
1361
1362    void
1363    StopPrivateStateThread ();
1364
1365    void
1366    PausePrivateStateThread ();
1367
1368    void
1369    ResumePrivateStateThread ();
1370
1371    static void *
1372    PrivateStateThread (void *arg);
1373
1374    void *
1375    RunPrivateStateThread ();
1376
1377    void
1378    HandlePrivateEvent (lldb::EventSP &event_sp);
1379
1380    lldb::StateType
1381    WaitForProcessStopPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
1382
1383    Error
1384    CompleteAttach ();
1385
1386
1387    // This waits for both the state change broadcaster, and the control broadcaster.
1388    // If control_only, it only waits for the control broadcaster.
1389
1390    bool
1391    WaitForEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp, bool control_only);
1392
1393    lldb::StateType
1394    WaitForStateChangedEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
1395
1396    lldb::StateType
1397    WaitForState (const TimeValue *timeout,
1398                  const lldb::StateType *match_states,
1399                  const uint32_t num_match_states);
1400
1401    size_t
1402    WriteMemoryPrivate (lldb::addr_t addr, const void *buf, size_t size, Error &error);
1403
1404private:
1405    //------------------------------------------------------------------
1406    // For Process only
1407    //------------------------------------------------------------------
1408    void ControlPrivateStateThread (uint32_t signal);
1409    DISALLOW_COPY_AND_ASSIGN (Process);
1410
1411};
1412
1413} // namespace lldb_private
1414
1415#endif  // liblldb_Process_h_
1416