Process.h revision c7129c3ca353eb7f0bc8c2aa0d99b54de21b9de6
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/Interpreter/Args.h"
21#include "lldb/Interpreter/Options.h"
22#include "lldb/Core/Broadcaster.h"
23#include "lldb/Core/Communication.h"
24#include "lldb/Core/Error.h"
25#include "lldb/Core/Event.h"
26#include "lldb/Core/StringList.h"
27#include "lldb/Core/ThreadSafeValue.h"
28#include "lldb/Core/PluginInterface.h"
29#include "lldb/Core/UserSettingsController.h"
30#include "lldb/Breakpoint/BreakpointSiteList.h"
31#include "lldb/Expression/ClangPersistentVariables.h"
32#include "lldb/Expression/IRDynamicChecks.h"
33#include "lldb/Target/ExecutionContextScope.h"
34#include "lldb/Target/ThreadList.h"
35#include "lldb/Target/UnixSignals.h"
36
37namespace lldb_private {
38
39
40typedef enum ProcessPlugins
41{
42    eMacosx,
43    eRemoteDebugger
44} ProcessPlugins;
45
46
47class ProcessInstanceSettings : public InstanceSettings
48{
49public:
50
51    ProcessInstanceSettings (UserSettingsController &owner, bool live_instance = true, const char *name = NULL);
52
53    ProcessInstanceSettings (const ProcessInstanceSettings &rhs);
54
55    virtual
56    ~ProcessInstanceSettings ();
57
58    ProcessInstanceSettings&
59    operator= (const ProcessInstanceSettings &rhs);
60
61
62    void
63    UpdateInstanceSettingsVariable (const ConstString &var_name,
64                                    const char *index_value,
65                                    const char *value,
66                                    const ConstString &instance_name,
67                                    const SettingEntry &entry,
68                                    lldb::VarSetOperationType op,
69                                    Error &err,
70                                    bool pending);
71
72    bool
73    GetInstanceSettingsValue (const SettingEntry &entry,
74                              const ConstString &var_name,
75                              StringList &value,
76                              Error *err);
77
78
79    const Args &
80    GetRunArguments () const
81    {
82        return m_run_args;
83    }
84
85    void
86    SetRunArguments (const Args &args)
87    {
88        m_run_args = args;
89    }
90
91    void
92    GetHostEnvironmentIfNeeded ();
93
94    size_t
95    GetEnvironmentAsArgs (Args &env);
96
97    const char *
98    GetStandardInputPath () const
99    {
100        if (m_input_path.empty())
101            return NULL;
102        return m_input_path.c_str();
103    }
104
105    void
106    SetStandardInputPath (const char *path)
107    {
108        if (path && path[0])
109            m_input_path.assign (path);
110        else
111        {
112            // Make sure we deallocate memory in string...
113            std::string tmp;
114            tmp.swap (m_input_path);
115        }
116    }
117
118    const char *
119    GetStandardOutputPath () const
120    {
121        if (m_output_path.empty())
122            return NULL;
123        return m_output_path.c_str();
124    }
125
126    void
127    SetStandardOutputPath (const char *path)
128    {
129        if (path && path[0])
130            m_output_path.assign (path);
131        else
132        {
133            // Make sure we deallocate memory in string...
134            std::string tmp;
135            tmp.swap (m_output_path);
136        }
137    }
138
139    const char *
140    GetStandardErrorPath () const
141    {
142        if (m_error_path.empty())
143            return NULL;
144        return m_error_path.c_str();
145    }
146
147    void
148    SetStandardErrorPath (const char *path)
149    {
150        if (path && path[0])
151            m_error_path.assign (path);
152        else
153        {
154            // Make sure we deallocate memory in string...
155            std::string tmp;
156            tmp.swap (m_error_path);
157        }
158    }
159
160    bool
161    GetDisableASLR () const
162    {
163        return m_disable_aslr;
164    }
165
166    void
167    SetDisableASLR (bool b)
168    {
169        m_disable_aslr = b;
170    }
171
172    bool
173    GetDisableSTDIO () const
174    {
175        return m_disable_stdio;
176    }
177
178    void
179    SetDisableSTDIO (bool b)
180    {
181        m_disable_stdio = b;
182    }
183
184protected:
185
186    void
187    CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
188                          bool pending);
189
190    const ConstString
191    CreateInstanceName ();
192
193    static const ConstString &
194    RunArgsVarName ();
195
196    static const ConstString &
197    EnvVarsVarName ();
198
199    static const ConstString &
200    InheritHostEnvVarName ();
201
202    static const ConstString &
203    InputPathVarName ();
204
205    static const ConstString &
206    OutputPathVarName ();
207
208    static const ConstString &
209    ErrorPathVarName ();
210
211    static const ConstString &
212    PluginVarName ();
213
214    static const ConstString &
215    DisableASLRVarName();
216
217    static const ConstString &
218    DisableSTDIOVarName ();
219
220private:
221
222    typedef std::map<std::string, std::string> dictionary;
223    Args m_run_args;
224    dictionary m_env_vars;
225    std::string m_input_path;
226    std::string m_output_path;
227    std::string m_error_path;
228    ProcessPlugins m_plugin;
229    bool m_disable_aslr;
230    bool m_disable_stdio;
231    bool m_inherit_host_env;
232    bool m_got_host_env;
233};
234
235
236//----------------------------------------------------------------------
237/// @class Process Process.h "lldb/Target/Process.h"
238/// @brief A plug-in interface definition class for debugging a process.
239//----------------------------------------------------------------------
240class Process :
241    public UserID,
242    public Broadcaster,
243    public ExecutionContextScope,
244    public PluginInterface,
245    public ProcessInstanceSettings
246{
247friend class ThreadList;
248friend class ClangFunction; // For WaitForStateChangeEventsPrivate
249
250public:
251
252    //------------------------------------------------------------------
253    /// Broadcaster event bits definitions.
254    //------------------------------------------------------------------
255    enum
256    {
257        eBroadcastBitStateChanged   = (1 << 0),
258        eBroadcastBitInterrupt      = (1 << 1),
259        eBroadcastBitSTDOUT         = (1 << 2),
260        eBroadcastBitSTDERR         = (1 << 3)
261    };
262
263    enum
264    {
265        eBroadcastInternalStateControlStop = (1<<0),
266        eBroadcastInternalStateControlPause = (1<<1),
267        eBroadcastInternalStateControlResume = (1<<2)
268    };
269
270    //------------------------------------------------------------------
271    /// A notification structure that can be used by clients to listen
272    /// for changes in a process's lifetime.
273    ///
274    /// @see RegisterNotificationCallbacks (const Notifications&)
275    /// @see UnregisterNotificationCallbacks (const Notifications&)
276    //------------------------------------------------------------------
277#ifndef SWIG
278    typedef struct
279    {
280        void *baton;
281        void (*initialize)(void *baton, Process *process);
282        void (*process_state_changed) (void *baton, Process *process, lldb::StateType state);
283    } Notifications;
284
285    class ProcessEventData :
286        public EventData
287    {
288        friend class Process;
289
290        public:
291            ProcessEventData ();
292            ProcessEventData (const lldb::ProcessSP &process, lldb::StateType state);
293
294            virtual ~ProcessEventData();
295
296            static const ConstString &
297            GetFlavorString ();
298
299            virtual const ConstString &
300            GetFlavor () const;
301
302            const lldb::ProcessSP &
303            GetProcessSP() const
304            {
305                return m_process_sp;
306            }
307            lldb::StateType
308            GetState() const
309            {
310                return m_state;
311            }
312            bool
313            GetRestarted () const
314            {
315                return m_restarted;
316            }
317            bool
318            GetInterrupted () const
319            {
320                return m_interrupted;
321            }
322
323            virtual void
324            Dump (Stream *s) const;
325
326            virtual void
327            DoOnRemoval (Event *event_ptr);
328
329            static const Process::ProcessEventData *
330            GetEventDataFromEvent (const Event *event_ptr);
331
332            static lldb::ProcessSP
333            GetProcessFromEvent (const Event *event_ptr);
334
335            static lldb::StateType
336            GetStateFromEvent (const Event *event_ptr);
337
338            static bool
339            GetRestartedFromEvent (const Event *event_ptr);
340
341            static void
342            SetRestartedInEvent (Event *event_ptr, bool new_value);
343
344            static bool
345            GetInterruptedFromEvent (const Event *event_ptr);
346
347            static void
348            SetInterruptedInEvent (Event *event_ptr, bool new_value);
349
350            static bool
351            SetUpdateStateOnRemoval (Event *event_ptr);
352
353       private:
354
355            void
356            SetUpdateStateOnRemoval()
357            {
358                m_update_state = true;
359            }
360            void
361            SetRestarted (bool new_value)
362            {
363                m_restarted = new_value;
364            }
365            void
366            SetInterrupted (bool new_value)
367            {
368                m_interrupted = new_value;
369            }
370
371            lldb::ProcessSP m_process_sp;
372            lldb::StateType m_state;
373            bool m_restarted;  // For "eStateStopped" events, this is true if the target was automatically restarted.
374            bool m_update_state;
375            bool m_interrupted;
376            DISALLOW_COPY_AND_ASSIGN (ProcessEventData);
377
378    };
379
380    class SettingsController : public UserSettingsController
381    {
382    public:
383
384        SettingsController ();
385
386        virtual
387        ~SettingsController ();
388
389        static SettingEntry global_settings_table[];
390        static SettingEntry instance_settings_table[];
391
392    protected:
393
394        lldb::InstanceSettingsSP
395        CreateInstanceSettings (const char *instance_name);
396
397    private:
398
399        // Class-wide settings.
400
401        DISALLOW_COPY_AND_ASSIGN (SettingsController);
402    };
403
404#endif
405
406    static void
407    Initialize ();
408
409    static void
410    DidInitialize ();
411
412    static void
413    Terminate ();
414
415    static lldb::UserSettingsControllerSP &
416    GetSettingsController ();
417
418    void
419    UpdateInstanceName ();
420
421
422    //------------------------------------------------------------------
423    /// Construct with a shared pointer to a target, and the Process listener.
424    //------------------------------------------------------------------
425    Process(Target &target, Listener &listener);
426
427    //------------------------------------------------------------------
428    /// Destructor.
429    ///
430    /// The destructor is virtual since this class is designed to be
431    /// inherited from by the plug-in instance.
432    //------------------------------------------------------------------
433    virtual
434    ~Process();
435
436    //------------------------------------------------------------------
437    /// Find a Process plug-in that can debug \a module using the
438    /// currently selected architecture.
439    ///
440    /// Scans all loaded plug-in interfaces that implement versions of
441    /// the Process plug-in interface and returns the first instance
442    /// that can debug the file.
443    ///
444    /// @param[in] module_sp
445    ///     The module shared pointer that this process will debug.
446    ///
447    /// @param[in] plugin_name
448    ///     If NULL, select the best plug-in for the binary. If non-NULL
449    ///     then look for a plugin whose PluginInfo's name matches
450    ///     this string.
451    ///
452    /// @see Process::CanDebug ()
453    //------------------------------------------------------------------
454    static Process*
455    FindPlugin (Target &target, const char *plugin_name, Listener &listener);
456
457
458
459    //------------------------------------------------------------------
460    /// Static function that can be used with the \b host function
461    /// Host::StartMonitoringChildProcess ().
462    ///
463    /// This function can be used by lldb_private::Process subclasses
464    /// when they want to watch for a local process and have its exit
465    /// status automatically set when the host child process exits.
466    /// Subclasses should call Host::StartMonitoringChildProcess ()
467    /// with:
468    ///     callback = Process::SetHostProcessExitStatus
469    ///     callback_baton = NULL
470    ///     pid = Process::GetID()
471    ///     monitor_signals = false
472    //------------------------------------------------------------------
473    static bool
474    SetProcessExitStatus (void *callback_baton,   // The callback baton which should be set to NULL
475                          lldb::pid_t pid,        // The process ID we want to monitor
476                          int signo,              // Zero for no signal
477                          int status);            // Exit value of process if signal is zero
478
479    lldb::ByteOrder
480    GetByteOrder () const;
481
482    uint32_t
483    GetAddressByteSize () const;
484
485    //------------------------------------------------------------------
486    /// Check if a plug-in instance can debug the file in \a module.
487    ///
488    /// Each plug-in is given a chance to say whether it can debug
489    /// the file in \a module. If the Process plug-in instance can
490    /// debug a file on the current system, it should return \b true.
491    ///
492    /// @return
493    ///     Returns \b true if this Process plug-in instance can
494    ///     debug the executable, \b false otherwise.
495    //------------------------------------------------------------------
496    virtual bool
497    CanDebug (Target &target) = 0;
498
499
500    //------------------------------------------------------------------
501    /// This object is about to be destroyed, do any necessary cleanup.
502    ///
503    /// Subclasses that override this method should always call this
504    /// superclass method.
505    //------------------------------------------------------------------
506    virtual void
507    Finalize();
508
509    //------------------------------------------------------------------
510    /// Launch a new process.
511    ///
512    /// Launch a new process by spawning a new process using the
513    /// target object's executable module's file as the file to launch.
514    /// Arguments are given in \a argv, and the environment variables
515    /// are in \a envp. Standard input and output files can be
516    /// optionally re-directed to \a stdin_path, \a stdout_path, and
517    /// \a stderr_path.
518    ///
519    /// This function is not meant to be overridden by Process
520    /// subclasses. It will first call Process::WillLaunch (Module *)
521    /// and if that returns \b true, Process::DoLaunch (Module*,
522    /// char const *[],char const *[],const char *,const char *,
523    /// const char *) will be called to actually do the launching. If
524    /// DoLaunch returns \b true, then Process::DidLaunch() will be
525    /// called.
526    ///
527    /// @param[in] argv
528    ///     The argument array.
529    ///
530    /// @param[in] envp
531    ///     The environment array.
532    ///
533    /// @param[in] launch_flags
534    ///     Flags to modify the launch (@see lldb::LaunchFlags)
535    ///
536    /// @param[in] stdin_path
537    ///     The path to use when re-directing the STDIN of the new
538    ///     process. If all stdXX_path arguments are NULL, a pseudo
539    ///     terminal will be used.
540    ///
541    /// @param[in] stdout_path
542    ///     The path to use when re-directing the STDOUT of the new
543    ///     process. If all stdXX_path arguments are NULL, a pseudo
544    ///     terminal will be used.
545    ///
546    /// @param[in] stderr_path
547    ///     The path to use when re-directing the STDERR of the new
548    ///     process. If all stdXX_path arguments are NULL, a pseudo
549    ///     terminal will be used.
550    ///
551    /// @param[in] working_directory
552    ///     The working directory to have the child process run in
553    ///
554    /// @return
555    ///     An error object. Call GetID() to get the process ID if
556    ///     the error object is success.
557    //------------------------------------------------------------------
558    virtual Error
559    Launch (char const *argv[],
560            char const *envp[],
561            uint32_t launch_flags,
562            const char *stdin_path,
563            const char *stdout_path,
564            const char *stderr_path,
565            const char *working_directory);
566
567    //------------------------------------------------------------------
568    /// Attach to an existing process using a process ID.
569    ///
570    /// This function is not meant to be overridden by Process
571    /// subclasses. It will first call Process::WillAttach (lldb::pid_t)
572    /// and if that returns \b true, Process::DoAttach (lldb::pid_t) will
573    /// be called to actually do the attach. If DoAttach returns \b
574    /// true, then Process::DidAttach() will be called.
575    ///
576    /// @param[in] pid
577    ///     The process ID that we should attempt to attach to.
578    ///
579    /// @return
580    ///     Returns \a pid if attaching was successful, or
581    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
582    //------------------------------------------------------------------
583    virtual Error
584    Attach (lldb::pid_t pid);
585
586    //------------------------------------------------------------------
587    /// Attach to an existing process by process name.
588    ///
589    /// This function is not meant to be overridden by Process
590    /// subclasses. It will first call
591    /// Process::WillAttach (const char *) and if that returns \b
592    /// true, Process::DoAttach (const char *) will be called to
593    /// actually do the attach. If DoAttach returns \b true, then
594    /// Process::DidAttach() will be called.
595    ///
596    /// @param[in] process_name
597    ///     A process name to match against the current process list.
598    ///
599    /// @return
600    ///     Returns \a pid if attaching was successful, or
601    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
602    //------------------------------------------------------------------
603    virtual Error
604    Attach (const char *process_name, bool wait_for_launch);
605
606    virtual Error
607    ConnectRemote (const char *remote_url);
608    //------------------------------------------------------------------
609    /// List the processes matching the given partial name.
610    ///
611    /// FIXME: Is it too heavyweight to create an entire process object to do this?
612    /// The problem is for remote processes we're going to have to set up the same transport
613    /// to get this data as to actually attach.  So we need to factor out transport
614    /// and process before we can do this separately from the process.
615    ///
616    /// @param[in] name
617    ///     A partial name to match against the current process list.
618    ///
619    /// @param[out] matches
620    ///     The list of process names matching \a name.
621    ///
622    /// @param[in] pids
623    ///     A vector filled with the pids that correspond to the names in \a matches.
624    ///
625    /// @return
626    ///     Returns the number of matching processes.
627    //------------------------------------------------------------------
628
629    virtual uint32_t
630    ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids);
631
632    //------------------------------------------------------------------
633    /// Find the architecture of a process by pid.
634    ///
635    /// FIXME: See comment for ListProcessesMatchingName.
636    ///
637    /// @param[in] pid
638    ///     A pid to inspect.
639    ///
640    /// @return
641    ///     Returns the architecture of the process or an invalid architecture if the process can't be found.
642    //------------------------------------------------------------------
643    virtual ArchSpec
644    GetArchSpecForExistingProcess (lldb::pid_t pid);
645
646    //------------------------------------------------------------------
647    /// Find the architecture of a process by name.
648    ///
649    /// FIXME: See comment for ListProcessesMatchingName.
650    ///
651    /// @param[in] process_name
652    ///     The process name to inspect.
653    ///
654    /// @return
655    ///     Returns the architecture of the process or an invalid architecture if the process can't be found.
656    //------------------------------------------------------------------
657    virtual ArchSpec
658    GetArchSpecForExistingProcess (const char *process_name);
659
660    //------------------------------------------------------------------
661    /// Get the image information address for the current process.
662    ///
663    /// Some runtimes have system functions that can help dynamic
664    /// loaders locate the dynamic loader information needed to observe
665    /// shared libraries being loaded or unloaded. This function is
666    /// in the Process interface (as opposed to the DynamicLoader
667    /// interface) to ensure that remote debugging can take advantage of
668    /// this functionality.
669    ///
670    /// @return
671    ///     The address of the dynamic loader information, or
672    ///     LLDB_INVALID_ADDRESS if this is not supported by this
673    ///     interface.
674    //------------------------------------------------------------------
675    virtual lldb::addr_t
676    GetImageInfoAddress ();
677
678    //------------------------------------------------------------------
679    /// Load a shared library into this process.
680    ///
681    /// Try and load a shared library into the current process. This
682    /// call might fail in the dynamic loader plug-in says it isn't safe
683    /// to try and load shared libraries at the moment.
684    ///
685    /// @param[in] image_spec
686    ///     The image file spec that points to the shared library that
687    ///     you want to load.
688    ///
689    /// @param[out] error
690    ///     An error object that gets filled in with any errors that
691    ///     might occur when trying to load the shared library.
692    ///
693    /// @return
694    ///     A token that represents the shared library that can be
695    ///     later used to unload the shared library. A value of
696    ///     LLDB_INVALID_IMAGE_TOKEN will be returned if the shared
697    ///     library can't be opened.
698    //------------------------------------------------------------------
699    virtual uint32_t
700    LoadImage (const FileSpec &image_spec, Error &error);
701
702    virtual Error
703    UnloadImage (uint32_t image_token);
704
705    //------------------------------------------------------------------
706    /// Register for process and thread notifications.
707    ///
708    /// Clients can register nofication callbacks by filling out a
709    /// Process::Notifications structure and calling this function.
710    ///
711    /// @param[in] callbacks
712    ///     A structure that contains the notification baton and
713    ///     callback functions.
714    ///
715    /// @see Process::Notifications
716    //------------------------------------------------------------------
717#ifndef SWIG
718    void
719    RegisterNotificationCallbacks (const Process::Notifications& callbacks);
720#endif
721    //------------------------------------------------------------------
722    /// Unregister for process and thread notifications.
723    ///
724    /// Clients can unregister nofication callbacks by passing a copy of
725    /// the original baton and callbacks in \a callbacks.
726    ///
727    /// @param[in] callbacks
728    ///     A structure that contains the notification baton and
729    ///     callback functions.
730    ///
731    /// @return
732    ///     Returns \b true if the notification callbacks were
733    ///     successfully removed from the process, \b false otherwise.
734    ///
735    /// @see Process::Notifications
736    //------------------------------------------------------------------
737#ifndef SWIG
738    bool
739    UnregisterNotificationCallbacks (const Process::Notifications& callbacks);
740#endif
741    //==================================================================
742    // Built in Process Control functions
743    //==================================================================
744    //------------------------------------------------------------------
745    /// Resumes all of a process's threads as configured using the
746    /// Thread run control functions.
747    ///
748    /// Threads for a process should be updated with one of the run
749    /// control actions (resume, step, or suspend) that they should take
750    /// when the process is resumed. If no run control action is given
751    /// to a thread it will be resumed by default.
752    ///
753    /// This function is not meant to be overridden by Process
754    /// subclasses. This function will take care of disabling any
755    /// breakpoints that threads may be stopped at, single stepping, and
756    /// re-enabling breakpoints, and enabling the basic flow control
757    /// that the plug-in instances need not worry about.
758    ///
759    /// @return
760    ///     Returns an error object.
761    ///
762    /// @see Thread:Resume()
763    /// @see Thread:Step()
764    /// @see Thread:Suspend()
765    //------------------------------------------------------------------
766    Error
767    Resume ();
768
769    //------------------------------------------------------------------
770    /// Halts a running process.
771    ///
772    /// This function is not meant to be overridden by Process
773    /// subclasses.
774    /// If the process is successfully halted, a eStateStopped
775    /// process event with GetInterrupted will be broadcast.  If false, we will
776    /// halt the process with no events generated by the halt.
777    ///
778    /// @return
779    ///     Returns an error object.  If the error is empty, the process is halted.
780    ///     otherwise the halt has failed.
781    //------------------------------------------------------------------
782    Error
783    Halt ();
784
785    //------------------------------------------------------------------
786    /// Detaches from a running or stopped process.
787    ///
788    /// This function is not meant to be overridden by Process
789    /// subclasses.
790    ///
791    /// @return
792    ///     Returns an error object.
793    //------------------------------------------------------------------
794    Error
795    Detach ();
796
797    //------------------------------------------------------------------
798    /// Kills the process and shuts down all threads that were spawned
799    /// to track and monitor the process.
800    ///
801    /// This function is not meant to be overridden by Process
802    /// subclasses.
803    ///
804    /// @return
805    ///     Returns an error object.
806    //------------------------------------------------------------------
807    Error
808    Destroy();
809
810    //------------------------------------------------------------------
811    /// Sends a process a UNIX signal \a signal.
812    ///
813    /// This function is not meant to be overridden by Process
814    /// subclasses.
815    ///
816    /// @return
817    ///     Returns an error object.
818    //------------------------------------------------------------------
819    Error
820    Signal (int signal);
821
822    virtual UnixSignals &
823    GetUnixSignals ()
824    {
825        return m_unix_signals;
826    }
827
828    //==================================================================
829    // Plug-in Process Control Overrides
830    //==================================================================
831
832    //------------------------------------------------------------------
833    /// Called before attaching to a process.
834    ///
835    /// Allow Process plug-ins to execute some code before attaching a
836    /// process.
837    ///
838    /// @return
839    ///     Returns an error object.
840    //------------------------------------------------------------------
841    virtual Error
842    WillAttachToProcessWithID (lldb::pid_t pid)
843    {
844        return Error();
845    }
846
847    //------------------------------------------------------------------
848    /// Called before attaching to a process.
849    ///
850    /// Allow Process plug-ins to execute some code before attaching a
851    /// process.
852    ///
853    /// @return
854    ///     Returns an error object.
855    //------------------------------------------------------------------
856    virtual Error
857    WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
858    {
859        return Error();
860    }
861
862    virtual Error
863    DoConnectRemote (const char *remote_url)
864    {
865        Error error;
866        error.SetErrorString ("remote connections are not supported");
867        return error;
868    }
869
870    //------------------------------------------------------------------
871    /// Attach to an existing process using a process ID.
872    ///
873    /// @param[in] pid
874    ///     The process ID that we should attempt to attach to.
875    ///
876    /// @return
877    ///     Returns \a pid if attaching was successful, or
878    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
879    //------------------------------------------------------------------
880    virtual Error
881    DoAttachToProcessWithID (lldb::pid_t pid) = 0;
882
883    //------------------------------------------------------------------
884    /// Attach to an existing process using a partial process name.
885    ///
886    /// @param[in] process_name
887    ///     The name of the process to attach to.
888    ///
889    /// @param[in] wait_for_launch
890    ///     If \b true, wait for the process to be launched and attach
891    ///     as soon as possible after it does launch. If \b false, then
892    ///     search for a matching process the currently exists.
893    ///
894    /// @return
895    ///     Returns \a pid if attaching was successful, or
896    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
897    //------------------------------------------------------------------
898    virtual Error
899    DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
900    {
901        Error error;
902        error.SetErrorString("attach by name is not supported");
903        return error;
904    }
905
906    //------------------------------------------------------------------
907    /// Called after attaching a process.
908    ///
909    /// Allow Process plug-ins to execute some code after attaching to
910    /// a process.
911    //------------------------------------------------------------------
912    virtual void
913    DidAttach () {}
914
915
916    //------------------------------------------------------------------
917    /// Called before launching to a process.
918    ///
919    /// Allow Process plug-ins to execute some code before launching a
920    /// process.
921    ///
922    /// @return
923    ///     Returns an error object.
924    //------------------------------------------------------------------
925    virtual Error
926    WillLaunch (Module* module)
927    {
928        return Error();
929    }
930
931    //------------------------------------------------------------------
932    /// Launch a new process.
933    ///
934    /// Launch a new process by spawning a new process using \a module's
935    /// file as the file to launch. Arguments are given in \a argv,
936    /// and the environment variables are in \a envp. Standard input
937    /// and output files can be optionally re-directed to \a stdin_path,
938    /// \a stdout_path, and \a stderr_path.
939    ///
940    /// @param[in] module
941    ///     The module from which to extract the file specification and
942    ///     launch.
943    ///
944    /// @param[in] argv
945    ///     The argument array.
946    ///
947    /// @param[in] envp
948    ///     The environment array.
949    ///
950    /// @param[in] launch_flags
951    ///     Flags to modify the launch (@see lldb::LaunchFlags)
952    ///
953    /// @param[in] stdin_path
954    ///     The path to use when re-directing the STDIN of the new
955    ///     process. If all stdXX_path arguments are NULL, a pseudo
956    ///     terminal will be used.
957    ///
958    /// @param[in] stdout_path
959    ///     The path to use when re-directing the STDOUT of the new
960    ///     process. If all stdXX_path arguments are NULL, a pseudo
961    ///     terminal will be used.
962    ///
963    /// @param[in] stderr_path
964    ///     The path to use when re-directing the STDERR of the new
965    ///     process. If all stdXX_path arguments are NULL, a pseudo
966    ///     terminal will be used.
967    ///
968    /// @param[in] working_directory
969    ///     The working directory to have the child process run in
970    ///
971    /// @return
972    ///     A new valid process ID, or LLDB_INVALID_PROCESS_ID if
973    ///     launching fails.
974    //------------------------------------------------------------------
975    virtual Error
976    DoLaunch (Module* module,
977              char const *argv[],
978              char const *envp[],
979              uint32_t launch_flags,
980              const char *stdin_path,
981              const char *stdout_path,
982              const char *stderr_path,
983              const char *working_directory) = 0;
984
985    //------------------------------------------------------------------
986    /// Called after launching a process.
987    ///
988    /// Allow Process plug-ins to execute some code after launching
989    /// a process.
990    //------------------------------------------------------------------
991    virtual void
992    DidLaunch () {}
993
994
995
996    //------------------------------------------------------------------
997    /// Called before resuming to a process.
998    ///
999    /// Allow Process plug-ins to execute some code before resuming a
1000    /// process.
1001    ///
1002    /// @return
1003    ///     Returns an error object.
1004    //------------------------------------------------------------------
1005    virtual Error
1006    WillResume () { return Error(); }
1007
1008    //------------------------------------------------------------------
1009    /// Resumes all of a process's threads as configured using the
1010    /// Thread run control functions.
1011    ///
1012    /// Threads for a process should be updated with one of the run
1013    /// control actions (resume, step, or suspend) that they should take
1014    /// when the process is resumed. If no run control action is given
1015    /// to a thread it will be resumed by default.
1016    ///
1017    /// @return
1018    ///     Returns \b true if the process successfully resumes using
1019    ///     the thread run control actions, \b false otherwise.
1020    ///
1021    /// @see Thread:Resume()
1022    /// @see Thread:Step()
1023    /// @see Thread:Suspend()
1024    //------------------------------------------------------------------
1025    virtual Error
1026    DoResume () = 0;
1027
1028    //------------------------------------------------------------------
1029    /// Called after resuming a process.
1030    ///
1031    /// Allow Process plug-ins to execute some code after resuming
1032    /// a process.
1033    //------------------------------------------------------------------
1034    virtual void
1035    DidResume () {}
1036
1037
1038    //------------------------------------------------------------------
1039    /// Called before halting to a process.
1040    ///
1041    /// Allow Process plug-ins to execute some code before halting a
1042    /// process.
1043    ///
1044    /// @return
1045    ///     Returns an error object.
1046    //------------------------------------------------------------------
1047    virtual Error
1048    WillHalt () { return Error(); }
1049
1050    //------------------------------------------------------------------
1051    /// Halts a running process.
1052    ///
1053    /// DoHalt must produce one and only one stop StateChanged event if it actually
1054    /// stops the process.  If the stop happens through some natural event (for
1055    /// instance a SIGSTOP), then forwarding that event will do.  Otherwise, you must
1056    /// generate the event manually.  Note also, the private event thread is stopped when
1057    /// DoHalt is run to prevent the events generated while halting to trigger
1058    /// other state changes before the halt is complete.
1059    ///
1060    /// @param[out] caused_stop
1061    ///     If true, then this Halt caused the stop, otherwise, the
1062    ///     process was already stopped.
1063    ///
1064    /// @return
1065    ///     Returns \b true if the process successfully halts, \b false
1066    ///     otherwise.
1067    //------------------------------------------------------------------
1068    virtual Error
1069    DoHalt (bool &caused_stop) = 0;
1070
1071    //------------------------------------------------------------------
1072    /// Called after halting a process.
1073    ///
1074    /// Allow Process plug-ins to execute some code after halting
1075    /// a process.
1076    //------------------------------------------------------------------
1077    virtual void
1078    DidHalt () {}
1079
1080    //------------------------------------------------------------------
1081    /// Called before detaching from a process.
1082    ///
1083    /// Allow Process plug-ins to execute some code before detaching
1084    /// from a process.
1085    ///
1086    /// @return
1087    ///     Returns an error object.
1088    //------------------------------------------------------------------
1089    virtual Error
1090    WillDetach ()
1091    {
1092        return Error();
1093    }
1094
1095    //------------------------------------------------------------------
1096    /// Detaches from a running or stopped process.
1097    ///
1098    /// @return
1099    ///     Returns \b true if the process successfully detaches, \b
1100    ///     false otherwise.
1101    //------------------------------------------------------------------
1102    virtual Error
1103    DoDetach () = 0;
1104
1105    //------------------------------------------------------------------
1106    /// Called after detaching from a process.
1107    ///
1108    /// Allow Process plug-ins to execute some code after detaching
1109    /// from a process.
1110    //------------------------------------------------------------------
1111    virtual void
1112    DidDetach () {}
1113
1114    //------------------------------------------------------------------
1115    /// Called before sending a signal to a process.
1116    ///
1117    /// Allow Process plug-ins to execute some code before sending a
1118    /// signal to a process.
1119    ///
1120    /// @return
1121    ///     Returns no error if it is safe to proceed with a call to
1122    ///     Process::DoSignal(int), otherwise an error describing what
1123    ///     prevents the signal from being sent.
1124    //------------------------------------------------------------------
1125    virtual Error
1126    WillSignal () { return Error(); }
1127
1128    //------------------------------------------------------------------
1129    /// Sends a process a UNIX signal \a signal.
1130    ///
1131    /// @return
1132    ///     Returns an error object.
1133    //------------------------------------------------------------------
1134    virtual Error
1135    DoSignal (int signal) = 0;
1136
1137
1138
1139    virtual Error
1140    WillDestroy () { return Error(); }
1141
1142    virtual Error
1143    DoDestroy () = 0;
1144
1145    virtual void
1146    DidDestroy () { }
1147
1148
1149    //------------------------------------------------------------------
1150    /// Called after sending a signal to a process.
1151    ///
1152    /// Allow Process plug-ins to execute some code after sending a
1153    /// signal to a process.
1154    //------------------------------------------------------------------
1155    virtual void
1156    DidSignal () {}
1157
1158
1159    //------------------------------------------------------------------
1160    /// Currently called as part of ShouldStop.
1161    /// FIXME: Should really happen when the target stops before the
1162    /// event is taken from the queue...
1163    ///
1164    /// This callback is called as the event
1165    /// is about to be queued up to allow Process plug-ins to execute
1166    /// some code prior to clients being notified that a process was
1167    /// stopped. Common operations include updating the thread list,
1168    /// invalidating any thread state (registers, stack, etc) prior to
1169    /// letting the notification go out.
1170    ///
1171    //------------------------------------------------------------------
1172    virtual void
1173    RefreshStateAfterStop () = 0;
1174
1175    //------------------------------------------------------------------
1176    /// Get the target object pointer for this module.
1177    ///
1178    /// @return
1179    ///     A Target object pointer to the target that owns this
1180    ///     module.
1181    //------------------------------------------------------------------
1182    Target &
1183    GetTarget ()
1184    {
1185        return m_target;
1186    }
1187
1188    //------------------------------------------------------------------
1189    /// Get the const target object pointer for this module.
1190    ///
1191    /// @return
1192    ///     A const Target object pointer to the target that owns this
1193    ///     module.
1194    //------------------------------------------------------------------
1195    const Target &
1196    GetTarget () const
1197    {
1198        return m_target;
1199    }
1200
1201
1202    //------------------------------------------------------------------
1203    /// Get accessor for the current process state.
1204    ///
1205    /// @return
1206    ///     The current state of the process.
1207    ///
1208    /// @see lldb::StateType
1209    //------------------------------------------------------------------
1210    lldb::StateType
1211    GetState ();
1212
1213    lldb::ExecutionResults
1214    RunThreadPlan (ExecutionContext &exe_ctx,
1215                    lldb::ThreadPlanSP &thread_plan_sp,
1216                    bool stop_others,
1217                    bool try_all_threads,
1218                    bool discard_on_error,
1219                    uint32_t single_thread_timeout_usec,
1220                    Stream &errors);
1221
1222    static const char *
1223    ExecutionResultAsCString (lldb::ExecutionResults result);
1224
1225protected:
1226    friend class CommandObjectProcessLaunch;
1227    friend class ProcessEventData;
1228    friend class CommandObjectBreakpointCommand;
1229
1230    void
1231    SetState (lldb::EventSP &event_sp);
1232
1233    lldb::StateType
1234    GetPrivateState ();
1235
1236    //------------------------------------------------------------------
1237    // Called internally
1238    //------------------------------------------------------------------
1239    void
1240    CompleteAttach ();
1241
1242public:
1243    //------------------------------------------------------------------
1244    /// Get the exit status for a process.
1245    ///
1246    /// @return
1247    ///     The process's return code, or -1 if the current process
1248    ///     state is not eStateExited.
1249    //------------------------------------------------------------------
1250    int
1251    GetExitStatus ();
1252
1253    //------------------------------------------------------------------
1254    /// Get a textual description of what the process exited.
1255    ///
1256    /// @return
1257    ///     The textual description of why the process exited, or NULL
1258    ///     if there is no description available.
1259    //------------------------------------------------------------------
1260    const char *
1261    GetExitDescription ();
1262
1263
1264    virtual void
1265    DidExit ()
1266    {
1267    }
1268
1269    //------------------------------------------------------------------
1270    /// Get the number of times this process has posted a stop event.
1271    ///
1272    /// @return
1273    ///     The number of times this process has stopped while being
1274    ///     debugged.
1275    //------------------------------------------------------------------
1276    uint32_t
1277    GetStopID () const;
1278
1279    //------------------------------------------------------------------
1280    /// Set accessor for the process exit status (return code).
1281    ///
1282    /// Sometimes a child exits and the exit can be detected by global
1283    /// functions (signal handler for SIGCHLD for example). This
1284    /// accessor allows the exit status to be set from an external
1285    /// source.
1286    ///
1287    /// Setting this will cause a eStateExited event to be posted to
1288    /// the process event queue.
1289    ///
1290    /// @param[in] exit_status
1291    ///     The value for the process's return code.
1292    ///
1293    /// @see lldb::StateType
1294    //------------------------------------------------------------------
1295    virtual bool
1296    SetExitStatus (int exit_status, const char *cstr);
1297
1298    //------------------------------------------------------------------
1299    /// Check if a process is still alive.
1300    ///
1301    /// @return
1302    ///     Returns \b true if the process is still valid, \b false
1303    ///     otherwise.
1304    //------------------------------------------------------------------
1305    virtual bool
1306    IsAlive () = 0;
1307
1308    //------------------------------------------------------------------
1309    /// Actually do the reading of memory from a process.
1310    ///
1311    /// Subclasses must override this function and can return fewer
1312    /// bytes than requested when memory requests are too large. This
1313    /// class will break up the memory requests and keep advancing the
1314    /// arguments along as needed.
1315    ///
1316    /// @param[in] vm_addr
1317    ///     A virtual load address that indicates where to start reading
1318    ///     memory from.
1319    ///
1320    /// @param[in] size
1321    ///     The number of bytes to read.
1322    ///
1323    /// @param[out] buf
1324    ///     A byte buffer that is at least \a size bytes long that
1325    ///     will receive the memory bytes.
1326    ///
1327    /// @return
1328    ///     The number of bytes that were actually read into \a buf.
1329    //------------------------------------------------------------------
1330    virtual size_t
1331    DoReadMemory (lldb::addr_t vm_addr,
1332                  void *buf,
1333                  size_t size,
1334                  Error &error) = 0;
1335
1336    //------------------------------------------------------------------
1337    /// Read of memory from a process.
1338    ///
1339    /// This function will read memory from the current process's
1340    /// address space and remove any traps that may have been inserted
1341    /// into the memory.
1342    ///
1343    /// This function is not meant to be overridden by Process
1344    /// subclasses, the subclasses should implement
1345    /// Process::DoReadMemory (lldb::addr_t, size_t, void *).
1346    ///
1347    /// @param[in] vm_addr
1348    ///     A virtual load address that indicates where to start reading
1349    ///     memory from.
1350    ///
1351    /// @param[out] buf
1352    ///     A byte buffer that is at least \a size bytes long that
1353    ///     will receive the memory bytes.
1354    ///
1355    /// @param[in] size
1356    ///     The number of bytes to read.
1357    ///
1358    /// @return
1359    ///     The number of bytes that were actually read into \a buf. If
1360    ///     the returned number is greater than zero, yet less than \a
1361    ///     size, then this function will get called again with \a
1362    ///     vm_addr, \a buf, and \a size updated appropriately. Zero is
1363    ///     returned to indicate an error.
1364    //------------------------------------------------------------------
1365    size_t
1366    ReadMemory (lldb::addr_t vm_addr,
1367                void *buf,
1368                size_t size,
1369                Error &error);
1370
1371    size_t
1372    ReadMemoryFromInferior (lldb::addr_t vm_addr,
1373                            void *buf,
1374                            size_t size,
1375                            Error &error);
1376
1377    //------------------------------------------------------------------
1378    /// Reads an unsigned integer of the specified byte size from
1379    /// process memory.
1380    ///
1381    /// @param[in] load_addr
1382    ///     A load address of the integer to read.
1383    ///
1384    /// @param[in] byte_size
1385    ///     The size in byte of the integer to read.
1386    ///
1387    /// @param[out] error
1388    ///     An error that indicates the success or failure of this
1389    ///     operation. If error indicates success (error.Success()),
1390    ///     then the value returned can be trusted, otherwise zero
1391    ///     will be returned.
1392    ///
1393    /// @return
1394    ///     The unsigned integer that was read from the process memory
1395    ///     space. If the integer was smaller than a uint64_t, any
1396    ///     unused upper bytes will be zero filled. If the process
1397    ///     byte order differs from the host byte order, the integer
1398    ///     value will be appropriately byte swapped into host byte
1399    ///     order.
1400    //------------------------------------------------------------------
1401    uint64_t
1402    ReadUnsignedInteger (lldb::addr_t load_addr,
1403                         size_t byte_size,
1404                         Error &error);
1405    //------------------------------------------------------------------
1406    /// Actually do the writing of memory to a process.
1407    ///
1408    /// @param[in] vm_addr
1409    ///     A virtual load address that indicates where to start writing
1410    ///     memory to.
1411    ///
1412    /// @param[in] buf
1413    ///     A byte buffer that is at least \a size bytes long that
1414    ///     contains the data to write.
1415    ///
1416    /// @param[in] size
1417    ///     The number of bytes to write.
1418    ///
1419    /// @return
1420    ///     The number of bytes that were actually written.
1421    //------------------------------------------------------------------
1422    virtual size_t
1423    DoWriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error) = 0;
1424
1425    //------------------------------------------------------------------
1426    /// Write memory to a process.
1427    ///
1428    /// This function will write memory to the current process's
1429    /// address space and maintain any traps that might be present due
1430    /// to software breakpoints.
1431    ///
1432    /// This function is not meant to be overridden by Process
1433    /// subclasses, the subclasses should implement
1434    /// Process::DoWriteMemory (lldb::addr_t, size_t, void *).
1435    ///
1436    /// @param[in] vm_addr
1437    ///     A virtual load address that indicates where to start writing
1438    ///     memory to.
1439    ///
1440    /// @param[in] buf
1441    ///     A byte buffer that is at least \a size bytes long that
1442    ///     contains the data to write.
1443    ///
1444    /// @param[in] size
1445    ///     The number of bytes to write.
1446    ///
1447    /// @return
1448    ///     The number of bytes that were actually written.
1449    //------------------------------------------------------------------
1450    size_t
1451    WriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error);
1452
1453
1454    //------------------------------------------------------------------
1455    /// Actually allocate memory in the process.
1456    ///
1457    /// This function will allocate memory in the process's address
1458    /// space.  This can't rely on the generic function calling mechanism,
1459    /// since that requires this function.
1460    ///
1461    /// @param[in] size
1462    ///     The size of the allocation requested.
1463    ///
1464    /// @return
1465    ///     The address of the allocated buffer in the process, or
1466    ///     LLDB_INVALID_ADDRESS if the allocation failed.
1467    //------------------------------------------------------------------
1468
1469    virtual lldb::addr_t
1470    DoAllocateMemory (size_t size, uint32_t permissions, Error &error) = 0;
1471
1472    //------------------------------------------------------------------
1473    /// The public interface to allocating memory in the process.
1474    ///
1475    /// This function will allocate memory in the process's address
1476    /// space.  This can't rely on the generic function calling mechanism,
1477    /// since that requires this function.
1478    ///
1479    /// @param[in] size
1480    ///     The size of the allocation requested.
1481    ///
1482    /// @param[in] permissions
1483    ///     Or together any of the lldb::Permissions bits.  The permissions on
1484    ///     a given memory allocation can't be changed after allocation.  Note
1485    ///     that a block that isn't set writable can still be written on from lldb,
1486    ///     just not by the process itself.
1487    ///
1488    /// @return
1489    ///     The address of the allocated buffer in the process, or
1490    ///     LLDB_INVALID_ADDRESS if the allocation failed.
1491    //------------------------------------------------------------------
1492
1493    lldb::addr_t
1494    AllocateMemory (size_t size, uint32_t permissions, Error &error);
1495
1496    //------------------------------------------------------------------
1497    /// Actually deallocate memory in the process.
1498    ///
1499    /// This function will deallocate memory in the process's address
1500    /// space that was allocated with AllocateMemory.
1501    ///
1502    /// @param[in] ptr
1503    ///     A return value from AllocateMemory, pointing to the memory you
1504    ///     want to deallocate.
1505    ///
1506    /// @return
1507    ///     \btrue if the memory was deallocated, \bfalse otherwise.
1508    //------------------------------------------------------------------
1509
1510    virtual Error
1511    DoDeallocateMemory (lldb::addr_t ptr) = 0;
1512
1513    //------------------------------------------------------------------
1514    /// The public interface to deallocating memory in the process.
1515    ///
1516    /// This function will deallocate memory in the process's address
1517    /// space that was allocated with AllocateMemory.
1518    ///
1519    /// @param[in] ptr
1520    ///     A return value from AllocateMemory, pointing to the memory you
1521    ///     want to deallocate.
1522    ///
1523    /// @return
1524    ///     \btrue if the memory was deallocated, \bfalse otherwise.
1525    //------------------------------------------------------------------
1526
1527    Error
1528    DeallocateMemory (lldb::addr_t ptr);
1529
1530    //------------------------------------------------------------------
1531    /// Get any available STDOUT.
1532    ///
1533    /// If the process was launched without supplying valid file paths
1534    /// for stdin, stdout, and stderr, then the Process class might
1535    /// try to cache the STDOUT for the process if it is able. Events
1536    /// will be queued indicating that there is STDOUT available that
1537    /// can be retrieved using this function.
1538    ///
1539    /// @param[out] buf
1540    ///     A buffer that will receive any STDOUT bytes that are
1541    ///     currently available.
1542    ///
1543    /// @param[out] buf_size
1544    ///     The size in bytes for the buffer \a buf.
1545    ///
1546    /// @return
1547    ///     The number of bytes written into \a buf. If this value is
1548    ///     equal to \a buf_size, another call to this function should
1549    ///     be made to retrieve more STDOUT data.
1550    //------------------------------------------------------------------
1551    virtual size_t
1552    GetSTDOUT (char *buf, size_t buf_size, Error &error)
1553    {
1554        error.SetErrorString("stdout unsupported");
1555        return 0;
1556    }
1557
1558
1559    //------------------------------------------------------------------
1560    /// Get any available STDERR.
1561    ///
1562    /// If the process was launched without supplying valid file paths
1563    /// for stdin, stdout, and stderr, then the Process class might
1564    /// try to cache the STDERR for the process if it is able. Events
1565    /// will be queued indicating that there is STDERR available that
1566    /// can be retrieved using this function.
1567    ///
1568    /// @param[out] buf
1569    ///     A buffer that will receive any STDERR bytes that are
1570    ///     currently available.
1571    ///
1572    /// @param[out] buf_size
1573    ///     The size in bytes for the buffer \a buf.
1574    ///
1575    /// @return
1576    ///     The number of bytes written into \a buf. If this value is
1577    ///     equal to \a buf_size, another call to this function should
1578    ///     be made to retrieve more STDERR data.
1579    //------------------------------------------------------------------
1580    virtual size_t
1581    GetSTDERR (char *buf, size_t buf_size, Error &error)
1582    {
1583        error.SetErrorString("stderr unsupported");
1584        return 0;
1585    }
1586
1587    virtual size_t
1588    PutSTDIN (const char *buf, size_t buf_size, Error &error)
1589    {
1590        error.SetErrorString("stdin unsupported");
1591        return 0;
1592    }
1593
1594    //----------------------------------------------------------------------
1595    // Process Breakpoints
1596    //----------------------------------------------------------------------
1597    virtual size_t
1598    GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site) = 0;
1599
1600    virtual Error
1601    EnableBreakpoint (BreakpointSite *bp_site) = 0;
1602
1603    virtual Error
1604    DisableBreakpoint (BreakpointSite *bp_site) = 0;
1605
1606    // This is implemented completely using the lldb::Process API. Subclasses
1607    // don't need to implement this function unless the standard flow of
1608    // read existing opcode, write breakpoint opcode, verify breakpoint opcode
1609    // doesn't work for a specific process plug-in.
1610    virtual Error
1611    EnableSoftwareBreakpoint (BreakpointSite *bp_site);
1612
1613    // This is implemented completely using the lldb::Process API. Subclasses
1614    // don't need to implement this function unless the standard flow of
1615    // restoring original opcode in memory and verifying the restored opcode
1616    // doesn't work for a specific process plug-in.
1617    virtual Error
1618    DisableSoftwareBreakpoint (BreakpointSite *bp_site);
1619
1620    BreakpointSiteList &
1621    GetBreakpointSiteList();
1622
1623    const BreakpointSiteList &
1624    GetBreakpointSiteList() const;
1625
1626    void
1627    DisableAllBreakpointSites ();
1628
1629    Error
1630    ClearBreakpointSiteByID (lldb::user_id_t break_id);
1631
1632    lldb::break_id_t
1633    CreateBreakpointSite (lldb::BreakpointLocationSP &owner,
1634                          bool use_hardware);
1635
1636    Error
1637    DisableBreakpointSiteByID (lldb::user_id_t break_id);
1638
1639    Error
1640    EnableBreakpointSiteByID (lldb::user_id_t break_id);
1641
1642
1643    // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove
1644    // themselves from the owner's list of this breakpoint sites.  This has to
1645    // be a static function because you can't be sure that removing the
1646    // breakpoint from it's containing map won't delete the breakpoint site,
1647    // and doing that in an instance method isn't copasetic.
1648    void
1649    RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id,
1650                                   lldb::user_id_t owner_loc_id,
1651                                   lldb::BreakpointSiteSP &bp_site_sp);
1652
1653    //----------------------------------------------------------------------
1654    // Process Watchpoints (optional)
1655    //----------------------------------------------------------------------
1656    virtual Error
1657    EnableWatchpoint (WatchpointLocation *bp_loc);
1658
1659    virtual Error
1660    DisableWatchpoint (WatchpointLocation *bp_loc);
1661
1662    //------------------------------------------------------------------
1663    // Thread Queries
1664    //------------------------------------------------------------------
1665    virtual uint32_t
1666    UpdateThreadListIfNeeded () = 0;
1667
1668    ThreadList &
1669    GetThreadList ()
1670    {
1671        return m_thread_list;
1672    }
1673
1674    const ThreadList &
1675    GetThreadList () const
1676    {
1677        return m_thread_list;
1678    }
1679
1680    uint32_t
1681    GetNextThreadIndexID ();
1682
1683    //------------------------------------------------------------------
1684    // Event Handling
1685    //------------------------------------------------------------------
1686    lldb::StateType
1687    GetNextEvent (lldb::EventSP &event_sp);
1688
1689    lldb::StateType
1690    WaitForProcessToStop (const TimeValue *timeout);
1691
1692    lldb::StateType
1693    WaitForStateChangedEvents (const TimeValue *timeout, lldb::EventSP &event_sp);
1694
1695    Event *
1696    PeekAtStateChangedEvents ();
1697
1698
1699    class
1700    ProcessEventHijacker
1701    {
1702    public:
1703        ProcessEventHijacker (Process &process, Listener *listener) :
1704            m_process (process),
1705            m_listener (listener)
1706        {
1707            m_process.HijackProcessEvents (listener);
1708        }
1709        ~ProcessEventHijacker ()
1710        {
1711            m_process.RestoreProcessEvents();
1712        }
1713
1714    private:
1715        Process &m_process;
1716        Listener *m_listener;
1717    };
1718    friend class ProcessEventHijacker;
1719    //------------------------------------------------------------------
1720    /// If you need to ensure that you and only you will hear about some public
1721    /// event, then make a new listener, set to listen to process events, and
1722    /// then call this with that listener.  Then you will have to wait on that
1723    /// listener explicitly for events (rather than using the GetNextEvent & WaitFor*
1724    /// calls above.  Be sure to call RestoreProcessEvents when you are done.
1725    ///
1726    /// @param[in] listener
1727    ///     This is the new listener to whom all process events will be delivered.
1728    ///
1729    /// @return
1730    ///     Returns \b true if the new listener could be installed,
1731    ///     \b false otherwise.
1732    //------------------------------------------------------------------
1733    bool
1734    HijackProcessEvents (Listener *listener);
1735
1736    //------------------------------------------------------------------
1737    /// Restores the process event broadcasting to its normal state.
1738    ///
1739    //------------------------------------------------------------------
1740    void
1741    RestoreProcessEvents ();
1742
1743protected:
1744    //------------------------------------------------------------------
1745    /// This is the part of the event handling that for a process event.
1746    /// It decides what to do with the event and returns true if the
1747    /// event needs to be propagated to the user, and false otherwise.
1748    /// If the event is not propagated, this call will most likely set
1749    /// the target to executing again.
1750    ///
1751    /// @param[in] event_ptr
1752    ///     This is the event we are handling.
1753    ///
1754    /// @return
1755    ///     Returns \b true if the event should be reported to the
1756    ///     user, \b false otherwise.
1757    //------------------------------------------------------------------
1758    bool
1759    ShouldBroadcastEvent (Event *event_ptr);
1760
1761public:
1762    const ABI *
1763    GetABI ();
1764
1765    DynamicLoader *
1766    GetDynamicLoader ()
1767    {
1768        return m_dyld_ap.get();
1769    }
1770
1771    virtual LanguageRuntime *
1772    GetLanguageRuntime (lldb::LanguageType language);
1773
1774    virtual CPPLanguageRuntime *
1775    GetCPPLanguageRuntime ();
1776
1777    virtual ObjCLanguageRuntime *
1778    GetObjCLanguageRuntime ();
1779
1780    bool
1781    IsRunning () const;
1782
1783    DynamicCheckerFunctions *GetDynamicCheckers()
1784    {
1785        return m_dynamic_checkers_ap.get();
1786    }
1787
1788    void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
1789    {
1790        m_dynamic_checkers_ap.reset(dynamic_checkers);
1791    }
1792
1793    //------------------------------------------------------------------
1794    /// Call this to set the lldb in the mode where it breaks on new thread
1795    /// creations, and then auto-restarts.  This is useful when you are trying
1796    /// to run only one thread, but either that thread or the kernel is creating
1797    /// new threads in the process.  If you stop when the thread is created, you
1798    /// can immediately suspend it, and keep executing only the one thread you intend.
1799    ///
1800    /// @return
1801    ///     Returns \b true if we were able to start up the notification
1802    ///     \b false otherwise.
1803    //------------------------------------------------------------------
1804    virtual bool
1805    StartNoticingNewThreads()
1806    {
1807        return true;
1808    }
1809
1810    //------------------------------------------------------------------
1811    /// Call this to turn off the stop & notice new threads mode.
1812    ///
1813    /// @return
1814    ///     Returns \b true if we were able to start up the notification
1815    ///     \b false otherwise.
1816    //------------------------------------------------------------------
1817    virtual bool
1818    StopNoticingNewThreads()
1819    {
1820        return true;
1821    }
1822
1823    //------------------------------------------------------------------
1824    // lldb::ExecutionContextScope pure virtual functions
1825    //------------------------------------------------------------------
1826    virtual Target *
1827    CalculateTarget ()
1828    {
1829        return &m_target;
1830    }
1831
1832    virtual Process *
1833    CalculateProcess ()
1834    {
1835        return this;
1836    }
1837
1838    virtual Thread *
1839    CalculateThread ()
1840    {
1841        return NULL;
1842    }
1843
1844    virtual StackFrame *
1845    CalculateStackFrame ()
1846    {
1847        return NULL;
1848    }
1849
1850    virtual void
1851    CalculateExecutionContext (ExecutionContext &exe_ctx);
1852
1853    lldb::ProcessSP
1854    GetSP ();
1855
1856protected:
1857    //------------------------------------------------------------------
1858    // lldb::ExecutionContextScope pure virtual functions
1859    //------------------------------------------------------------------
1860    class NextEventAction
1861    {
1862    public:
1863        typedef enum EventActionResult
1864        {
1865            eEventActionSuccess,
1866            eEventActionRetry,
1867            eEventActionExit
1868        } EventActionResult;
1869
1870        NextEventAction (Process *process) :
1871            m_process(process)
1872        {}
1873        virtual ~NextEventAction() {}
1874
1875        virtual EventActionResult PerformAction (lldb::EventSP &event_sp) = 0;
1876        virtual void HandleBeingUnshipped () {};
1877        virtual EventActionResult HandleBeingInterrupted () = 0;
1878        virtual const char *GetExitString() = 0;
1879    protected:
1880        Process *m_process;
1881    };
1882
1883    void SetNextEventAction (Process::NextEventAction *next_event_action)
1884    {
1885        if (m_next_event_action_ap.get())
1886            m_next_event_action_ap->HandleBeingUnshipped();
1887
1888        m_next_event_action_ap.reset(next_event_action);
1889    }
1890
1891    // This is the completer for Attaching:
1892    class AttachCompletionHandler : public NextEventAction
1893    {
1894    public:
1895        AttachCompletionHandler (Process *process) :
1896            NextEventAction(process)
1897        {}
1898        virtual ~AttachCompletionHandler() {}
1899
1900        virtual EventActionResult PerformAction (lldb::EventSP &event_sp);
1901        virtual EventActionResult HandleBeingInterrupted ();
1902        virtual const char *GetExitString();
1903    private:
1904        std::string m_exit_string;
1905    };
1906
1907
1908    class MemoryCache
1909    {
1910    public:
1911        //------------------------------------------------------------------
1912        // Constructors and Destructors
1913        //------------------------------------------------------------------
1914        MemoryCache ();
1915
1916        ~MemoryCache ();
1917
1918        void
1919        Clear();
1920
1921        void
1922        Flush (lldb::addr_t addr, size_t size);
1923
1924        size_t
1925        Read (Process *process,
1926              lldb::addr_t addr,
1927              void *dst,
1928              size_t dst_len,
1929              Error &error);
1930
1931    protected:
1932        typedef std::map<lldb::addr_t, lldb::DataBufferSP> collection;
1933        //------------------------------------------------------------------
1934        // Classes that inherit from MemoryCache can see and modify these
1935        //------------------------------------------------------------------
1936        uint32_t m_cache_line_byte_size;
1937        Mutex m_cache_mutex;
1938        collection m_cache;
1939
1940    private:
1941        DISALLOW_COPY_AND_ASSIGN (MemoryCache);
1942    };
1943
1944    bool
1945    HijackPrivateProcessEvents (Listener *listener);
1946
1947    void
1948    RestorePrivateProcessEvents ();
1949
1950    bool
1951    PrivateStateThreadIsValid () const
1952    {
1953        return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
1954    }
1955
1956    //------------------------------------------------------------------
1957    // Member variables
1958    //------------------------------------------------------------------
1959    Target &                    m_target;               ///< The target that owns this process.
1960    ThreadSafeValue<lldb::StateType>  m_public_state;
1961    ThreadSafeValue<lldb::StateType>  m_private_state; // The actual state of our process
1962    Broadcaster                 m_private_state_broadcaster;  // This broadcaster feeds state changed events into the private state thread's listener.
1963    Broadcaster                 m_private_state_control_broadcaster; // This is the control broadcaster, used to pause, resume & stop the private state thread.
1964    Listener                    m_private_state_listener;     // This is the listener for the private state thread.
1965    Predicate<bool>             m_private_state_control_wait; /// This Predicate is used to signal that a control operation is complete.
1966    lldb::thread_t              m_private_state_thread;  // Thread ID for the thread that watches interal state events
1967    uint32_t                    m_stop_id;              ///< A count of many times the process has stopped.
1968    uint32_t                    m_thread_index_id;      ///< Each thread is created with a 1 based index that won't get re-used.
1969    int                         m_exit_status;          ///< The exit status of the process, or -1 if not set.
1970    std::string                 m_exit_string;          ///< A textual description of why a process exited.
1971    ThreadList                  m_thread_list;          ///< The threads for this process.
1972    std::vector<Notifications>  m_notifications;        ///< The list of notifications that this process can deliver.
1973    std::vector<lldb::addr_t>   m_image_tokens;
1974    Listener                    &m_listener;
1975    BreakpointSiteList          m_breakpoint_site_list; ///< This is the list of breakpoint locations we intend
1976                                                        ///< to insert in the target.
1977    std::auto_ptr<DynamicLoader> m_dyld_ap;
1978    std::auto_ptr<DynamicCheckerFunctions>  m_dynamic_checkers_ap; ///< The functions used by the expression parser to validate data that expressions use.
1979    UnixSignals                 m_unix_signals;         /// This is the current signal set for this process.
1980    lldb::ABISP                 m_abi_sp;
1981    lldb::InputReaderSP         m_process_input_reader;
1982    lldb_private::Communication m_stdio_communication;
1983    lldb_private::Mutex         m_stdio_communication_mutex;
1984    std::string                 m_stdout_data;
1985    MemoryCache                 m_memory_cache;
1986
1987    typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP> LanguageRuntimeCollection;
1988    LanguageRuntimeCollection m_language_runtimes;
1989    std::auto_ptr<NextEventAction> m_next_event_action_ap;
1990
1991    size_t
1992    RemoveBreakpointOpcodesFromBuffer (lldb::addr_t addr, size_t size, uint8_t *buf) const;
1993
1994    void
1995    SynchronouslyNotifyStateChanged (lldb::StateType state);
1996
1997    void
1998    SetPublicState (lldb::StateType new_state);
1999
2000    void
2001    SetPrivateState (lldb::StateType state);
2002
2003    bool
2004    StartPrivateStateThread ();
2005
2006    void
2007    StopPrivateStateThread ();
2008
2009    void
2010    PausePrivateStateThread ();
2011
2012    void
2013    ResumePrivateStateThread ();
2014
2015    static void *
2016    PrivateStateThread (void *arg);
2017
2018    void *
2019    RunPrivateStateThread ();
2020
2021    void
2022    HandlePrivateEvent (lldb::EventSP &event_sp);
2023
2024    lldb::StateType
2025    WaitForProcessStopPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
2026
2027    // This waits for both the state change broadcaster, and the control broadcaster.
2028    // If control_only, it only waits for the control broadcaster.
2029
2030    bool
2031    WaitForEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp, bool control_only);
2032
2033    lldb::StateType
2034    WaitForStateChangedEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
2035
2036    lldb::StateType
2037    WaitForState (const TimeValue *timeout,
2038                  const lldb::StateType *match_states,
2039                  const uint32_t num_match_states);
2040
2041    size_t
2042    WriteMemoryPrivate (lldb::addr_t addr, const void *buf, size_t size, Error &error);
2043
2044    void
2045    AppendSTDOUT (const char *s, size_t len);
2046
2047    static void
2048    STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len);
2049
2050    void
2051    PushProcessInputReader ();
2052
2053    void
2054    PopProcessInputReader ();
2055
2056    void
2057    ResetProcessInputReader ();
2058
2059    void
2060    SetUpProcessInputReader (int file_descriptor);
2061
2062    static size_t
2063    ProcessInputReaderCallback (void *baton,
2064                                InputReader &reader,
2065                                lldb::InputReaderAction notification,
2066                                const char *bytes,
2067                                size_t bytes_len);
2068
2069
2070private:
2071    //------------------------------------------------------------------
2072    // For Process only
2073    //------------------------------------------------------------------
2074    void ControlPrivateStateThread (uint32_t signal);
2075
2076    DISALLOW_COPY_AND_ASSIGN (Process);
2077
2078};
2079
2080} // namespace lldb_private
2081
2082#endif  // liblldb_Process_h_
2083