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