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