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