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