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