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