Process.h revision abb3302051246273eb92cca203c9a1b9d9736e05
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#include <limits.h>
15#include <spawn.h>
16
17// C++ Includes
18#include <list>
19#include <iosfwd>
20#include <vector>
21
22// Other libraries and framework includes
23// Project includes
24#include "lldb/lldb-private.h"
25#include "lldb/Core/ArchSpec.h"
26#include "lldb/Core/Broadcaster.h"
27#include "lldb/Core/Communication.h"
28#include "lldb/Core/Error.h"
29#include "lldb/Core/Event.h"
30#include "lldb/Core/StringList.h"
31#include "lldb/Core/ThreadSafeValue.h"
32#include "lldb/Core/PluginInterface.h"
33#include "lldb/Core/UserSettingsController.h"
34#include "lldb/Breakpoint/BreakpointSiteList.h"
35#include "lldb/Expression/ClangPersistentVariables.h"
36#include "lldb/Expression/IRDynamicChecks.h"
37#include "lldb/Host/FileSpec.h"
38#include "lldb/Interpreter/Args.h"
39#include "lldb/Interpreter/Options.h"
40#include "lldb/Target/ExecutionContextScope.h"
41#include "lldb/Target/Memory.h"
42#include "lldb/Target/ThreadList.h"
43#include "lldb/Target/UnixSignals.h"
44
45namespace lldb_private {
46
47//----------------------------------------------------------------------
48// ProcessInstanceSettings
49//----------------------------------------------------------------------
50class ProcessInstanceSettings : public InstanceSettings
51{
52public:
53
54    ProcessInstanceSettings (UserSettingsController &owner, bool live_instance = true, const char *name = NULL);
55
56    ProcessInstanceSettings (const ProcessInstanceSettings &rhs);
57
58    virtual
59    ~ProcessInstanceSettings ();
60
61    ProcessInstanceSettings&
62    operator= (const ProcessInstanceSettings &rhs);
63
64
65    void
66    UpdateInstanceSettingsVariable (const ConstString &var_name,
67                                    const char *index_value,
68                                    const char *value,
69                                    const ConstString &instance_name,
70                                    const SettingEntry &entry,
71                                    VarSetOperationType op,
72                                    Error &err,
73                                    bool pending);
74
75    bool
76    GetInstanceSettingsValue (const SettingEntry &entry,
77                              const ConstString &var_name,
78                              StringList &value,
79                              Error *err);
80
81
82protected:
83
84    void
85    CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
86                          bool pending);
87
88    const ConstString
89    CreateInstanceName ();
90};
91
92//----------------------------------------------------------------------
93// ProcessInfo
94//
95// A base class for information for a process. This can be used to fill
96// out information for a process prior to launching it, or it can be
97// used for an instance of a process and can be filled in with the
98// existing values for that process.
99//----------------------------------------------------------------------
100class ProcessInfo
101{
102public:
103    ProcessInfo () :
104        m_executable (),
105        m_arguments (),
106        m_environment (),
107        m_uid (UINT32_MAX),
108        m_gid (UINT32_MAX),
109        m_arch(),
110        m_pid (LLDB_INVALID_PROCESS_ID)
111    {
112    }
113
114    ProcessInfo (const char *name,
115                 const ArchSpec &arch,
116                 lldb::pid_t pid) :
117        m_executable (name, false),
118        m_arguments (),
119        m_environment(),
120        m_uid (UINT32_MAX),
121        m_gid (UINT32_MAX),
122        m_arch (arch),
123        m_pid (pid)
124    {
125    }
126
127    void
128    Clear ()
129    {
130        m_executable.Clear();
131        m_arguments.Clear();
132        m_environment.Clear();
133        m_uid = UINT32_MAX;
134        m_gid = UINT32_MAX;
135        m_arch.Clear();
136        m_pid = LLDB_INVALID_PROCESS_ID;
137    }
138
139    const char *
140    GetName() const
141    {
142        return m_executable.GetFilename().GetCString();
143    }
144
145    size_t
146    GetNameLength() const
147    {
148        return m_executable.GetFilename().GetLength();
149    }
150
151    void
152    SetName (const char *name)
153    {
154        m_executable.GetFilename().SetCString (name);
155    }
156
157    FileSpec &
158    GetExecutableFile ()
159    {
160        return m_executable;
161    }
162
163    void
164    SetExecutableFile (const FileSpec &exe_file, bool add_exe_file_as_first_arg)
165    {
166        if (exe_file)
167        {
168            m_executable = exe_file;
169            if (add_exe_file_as_first_arg)
170            {
171                m_arguments.Clear();
172                char filename[PATH_MAX];
173                if (exe_file.GetPath(filename, sizeof(filename)))
174                    m_arguments.AppendArgument (filename);
175            }
176        }
177        else
178        {
179            m_executable.Clear();
180            if (add_exe_file_as_first_arg)
181                m_arguments.Clear();
182        }
183    }
184
185    const FileSpec &
186    GetExecutableFile () const
187    {
188        return m_executable;
189    }
190
191    uint32_t
192    GetUserID() const
193    {
194        return m_uid;
195    }
196
197    uint32_t
198    GetGroupID() const
199    {
200        return m_gid;
201    }
202
203    bool
204    UserIDIsValid () const
205    {
206        return m_uid != UINT32_MAX;
207    }
208
209    bool
210    GroupIDIsValid () const
211    {
212        return m_gid != UINT32_MAX;
213    }
214
215    void
216    SetUserID (uint32_t uid)
217    {
218        m_uid = uid;
219    }
220
221    void
222    SetGroupID (uint32_t gid)
223    {
224        m_gid = gid;
225    }
226
227    ArchSpec &
228    GetArchitecture ()
229    {
230        return m_arch;
231    }
232
233    const ArchSpec &
234    GetArchitecture () const
235    {
236        return m_arch;
237    }
238
239    lldb::pid_t
240    GetProcessID () const
241    {
242        return m_pid;
243    }
244
245    void
246    SetProcessID (lldb::pid_t pid)
247    {
248        m_pid = pid;
249    }
250
251    bool
252    ProcessIDIsValid() const
253    {
254        return m_pid != LLDB_INVALID_PROCESS_ID;
255    }
256
257    void
258    Dump (Stream &s, Platform *platform) const;
259
260    Args &
261    GetArguments ()
262    {
263        return m_arguments;
264    }
265
266    const Args &
267    GetArguments () const
268    {
269        return m_arguments;
270    }
271
272    void
273    SetArguments (const Args& args,
274                  bool first_arg_is_executable,
275                  bool first_arg_is_executable_and_argument);
276
277    void
278    SetArguments (char const **argv,
279                  bool first_arg_is_executable,
280                  bool first_arg_is_executable_and_argument);
281
282    Args &
283    GetEnvironmentEntries ()
284    {
285        return m_environment;
286    }
287
288    const Args &
289    GetEnvironmentEntries () const
290    {
291        return m_environment;
292    }
293
294protected:
295    FileSpec m_executable;
296    Args m_arguments;
297    Args m_environment;
298    uint32_t m_uid;
299    uint32_t m_gid;
300    ArchSpec m_arch;
301    lldb::pid_t m_pid;
302};
303
304//----------------------------------------------------------------------
305// ProcessInstanceInfo
306//
307// Describes an existing process and any discoverable information that
308// pertains to that process.
309//----------------------------------------------------------------------
310class ProcessInstanceInfo : public ProcessInfo
311{
312public:
313    ProcessInstanceInfo () :
314        ProcessInfo (),
315        m_euid (UINT32_MAX),
316        m_egid (UINT32_MAX),
317        m_parent_pid (LLDB_INVALID_PROCESS_ID)
318    {
319    }
320
321    ProcessInstanceInfo (const char *name,
322                 const ArchSpec &arch,
323                 lldb::pid_t pid) :
324        ProcessInfo (name, arch, pid),
325        m_euid (UINT32_MAX),
326        m_egid (UINT32_MAX),
327        m_parent_pid (LLDB_INVALID_PROCESS_ID)
328    {
329    }
330
331    void
332    Clear ()
333    {
334        ProcessInfo::Clear();
335        m_euid = UINT32_MAX;
336        m_egid = UINT32_MAX;
337        m_parent_pid = LLDB_INVALID_PROCESS_ID;
338    }
339
340    uint32_t
341    GetEffectiveUserID() const
342    {
343        return m_euid;
344    }
345
346    uint32_t
347    GetEffectiveGroupID() const
348    {
349        return m_egid;
350    }
351
352    bool
353    EffectiveUserIDIsValid () const
354    {
355        return m_euid != UINT32_MAX;
356    }
357
358    bool
359    EffectiveGroupIDIsValid () const
360    {
361        return m_egid != UINT32_MAX;
362    }
363
364    void
365    SetEffectiveUserID (uint32_t uid)
366    {
367        m_euid = uid;
368    }
369
370    void
371    SetEffectiveGroupID (uint32_t gid)
372    {
373        m_egid = gid;
374    }
375
376    lldb::pid_t
377    GetParentProcessID () const
378    {
379        return m_parent_pid;
380    }
381
382    void
383    SetParentProcessID (lldb::pid_t pid)
384    {
385        m_parent_pid = pid;
386    }
387
388    bool
389    ParentProcessIDIsValid() const
390    {
391        return m_parent_pid != LLDB_INVALID_PROCESS_ID;
392    }
393
394    void
395    Dump (Stream &s, Platform *platform) const;
396
397    static void
398    DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose);
399
400    void
401    DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const;
402
403protected:
404    uint32_t m_euid;
405    uint32_t m_egid;
406    lldb::pid_t m_parent_pid;
407};
408
409
410//----------------------------------------------------------------------
411// ProcessLaunchInfo
412//
413// Describes any information that is required to launch a process.
414//----------------------------------------------------------------------
415
416class ProcessLaunchInfo : public ProcessInfo
417{
418public:
419
420    class FileAction
421    {
422    public:
423        enum Action
424        {
425            eFileActionNone,
426            eFileActionClose,
427            eFileActionDuplicate,
428            eFileActionOpen
429        };
430
431
432        FileAction () :
433            m_action (eFileActionNone),
434            m_fd (-1),
435            m_arg (-1),
436            m_path ()
437        {
438        }
439
440        void
441        Clear()
442        {
443            m_action = eFileActionNone;
444            m_fd = -1;
445            m_arg = -1;
446            m_path.clear();
447        }
448
449        bool
450        Close (int fd);
451
452        bool
453        Duplicate (int fd, int dup_fd);
454
455        bool
456        Open (int fd, const char *path, bool read, bool write);
457
458        static bool
459        AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
460                                 const FileAction *info,
461                                 Log *log,
462                                 Error& error);
463
464        int
465        GetFD () const
466        {
467            return m_fd;
468        }
469
470        Action
471        GetAction () const
472        {
473            return m_action;
474        }
475
476        int
477        GetActionArgument () const
478        {
479            return m_arg;
480        }
481
482        const char *
483        GetPath () const
484        {
485            if (m_path.empty())
486                return NULL;
487            return m_path.c_str();
488        }
489
490    protected:
491        Action m_action;    // The action for this file
492        int m_fd;           // An existing file descriptor
493        int m_arg;          // oflag for eFileActionOpen*, dup_fd for eFileActionDuplicate
494        std::string m_path; // A file path to use for opening after fork or posix_spawn
495    };
496
497    ProcessLaunchInfo () :
498        ProcessInfo(),
499        m_flags ()
500    {
501    }
502
503    ProcessLaunchInfo (const char *stdin_path,
504                       const char *stdout_path,
505                       const char *stderr_path,
506                       const char *working_directory,
507                       uint32_t launch_flags) :
508        ProcessInfo(),
509        m_flags (launch_flags)
510    {
511        if (stderr_path)
512        {
513            ProcessLaunchInfo::FileAction file_action;
514            const bool read = true;
515            const bool write = true;
516            if (file_action.Open(STDERR_FILENO, stderr_path, read, write))
517                AppendFileAction (file_action);
518        }
519        if (stdout_path)
520        {
521            ProcessLaunchInfo::FileAction file_action;
522            const bool read = false;
523            const bool write = true;
524            if (file_action.Open(STDOUT_FILENO, stdout_path, read, write))
525                AppendFileAction (file_action);
526        }
527        if (stdin_path)
528        {
529            ProcessLaunchInfo::FileAction file_action;
530            const bool read = true;
531            const bool write = false;
532            if (file_action.Open(STDIN_FILENO, stdin_path, read, write))
533                AppendFileAction (file_action);
534        }
535        if (working_directory)
536            SetWorkingDirectory(working_directory);
537    }
538
539    void
540    AppendFileAction (const FileAction &info)
541    {
542        m_file_actions.push_back(info);
543    }
544
545    bool
546    AppendCloseFileAction (int fd)
547    {
548        FileAction file_action;
549        if (file_action.Close (fd))
550        {
551            AppendFileAction (file_action);
552            return true;
553        }
554        return false;
555    }
556
557    bool
558    AppendDuplciateFileAction (int fd, int dup_fd)
559    {
560        FileAction file_action;
561        if (file_action.Duplicate (fd, dup_fd))
562        {
563            AppendFileAction (file_action);
564            return true;
565        }
566        return false;
567    }
568
569    bool
570    AppendOpenFileAction (int fd, const char *path, bool read, bool write)
571    {
572        FileAction file_action;
573        if (file_action.Open (fd, path, read, write))
574        {
575            AppendFileAction (file_action);
576            return true;
577        }
578        return false;
579    }
580
581    bool
582    AppendSuppressFileAction (int fd, bool read, bool write)
583    {
584        FileAction file_action;
585        if (file_action.Open (fd, "/dev/null", read, write))
586        {
587            AppendFileAction (file_action);
588            return true;
589        }
590        return false;
591    }
592
593    void
594    FinalizeFileActions (Target *target, Process *process);
595
596    size_t
597    GetNumFileActions () const
598    {
599        return m_file_actions.size();
600    }
601
602    const FileAction *
603    GetFileActionAtIndex (size_t idx) const
604    {
605        if (idx < m_file_actions.size())
606            return &m_file_actions[idx];
607        return NULL;
608    }
609
610    const FileAction *
611    GetFileActionForFD (int fd) const
612    {
613        for (uint32_t idx=0, count=m_file_actions.size(); idx < count; ++idx)
614        {
615            if (m_file_actions[idx].GetFD () == fd)
616                return &m_file_actions[idx];
617        }
618        return NULL;
619    }
620
621    Flags &
622    GetFlags ()
623    {
624        return m_flags;
625    }
626
627    const Flags &
628    GetFlags () const
629    {
630        return m_flags;
631    }
632
633    const char *
634    GetWorkingDirectory () const
635    {
636        if (m_working_dir.empty())
637            return NULL;
638        return m_working_dir.c_str();
639    }
640
641    void
642    SetWorkingDirectory (const char *working_dir)
643    {
644        if (working_dir && working_dir[0])
645            m_working_dir.assign (working_dir);
646        else
647            m_working_dir.clear();
648    }
649
650    void
651    SwapWorkingDirectory (std::string &working_dir)
652    {
653        m_working_dir.swap (working_dir);
654    }
655
656
657    const char *
658    GetProcessPluginName () const
659    {
660        if (m_plugin_name.empty())
661            return NULL;
662        return m_plugin_name.c_str();
663    }
664
665    void
666    SetProcessPluginName (const char *plugin)
667    {
668        if (plugin && plugin[0])
669            m_plugin_name.assign (plugin);
670        else
671            m_plugin_name.clear();
672    }
673
674    void
675    Clear ()
676    {
677        ProcessInfo::Clear();
678        m_working_dir.clear();
679        m_plugin_name.clear();
680        m_flags.Clear();
681        m_file_actions.clear();
682    }
683
684protected:
685    std::string m_working_dir;
686    std::string m_plugin_name;
687    Flags m_flags;       // Bitwise OR of bits from lldb::LaunchFlags
688    std::vector<FileAction> m_file_actions; // File actions for any other files
689};
690
691class ProcessLaunchCommandOptions : public Options
692{
693public:
694
695    ProcessLaunchCommandOptions (CommandInterpreter &interpreter) :
696        Options(interpreter)
697    {
698        // Keep default values of all options in one place: OptionParsingStarting ()
699        OptionParsingStarting ();
700    }
701
702    ~ProcessLaunchCommandOptions ()
703    {
704    }
705
706    Error
707    SetOptionValue (uint32_t option_idx, const char *option_arg);
708
709    void
710    OptionParsingStarting ()
711    {
712        launch_info.Clear();
713    }
714
715    const OptionDefinition*
716    GetDefinitions ()
717    {
718        return g_option_table;
719    }
720
721    // Options table: Required for subclasses of Options.
722
723    static OptionDefinition g_option_table[];
724
725    // Instance variables to hold the values for command options.
726
727    ProcessLaunchInfo launch_info;
728};
729
730//----------------------------------------------------------------------
731// ProcessInstanceInfoMatch
732//
733// A class to help matching one ProcessInstanceInfo to another.
734//----------------------------------------------------------------------
735
736class ProcessInstanceInfoMatch
737{
738public:
739    ProcessInstanceInfoMatch () :
740        m_match_info (),
741        m_name_match_type (lldb_private::eNameMatchIgnore),
742        m_match_all_users (false)
743    {
744    }
745
746    ProcessInstanceInfoMatch (const char *process_name,
747                      lldb_private::NameMatchType process_name_match_type) :
748        m_match_info (),
749        m_name_match_type (process_name_match_type),
750        m_match_all_users (false)
751    {
752        m_match_info.SetName (process_name);
753    }
754
755    ProcessInstanceInfo &
756    GetProcessInfo ()
757    {
758        return m_match_info;
759    }
760
761    const ProcessInstanceInfo &
762    GetProcessInfo () const
763    {
764        return m_match_info;
765    }
766
767    bool
768    GetMatchAllUsers () const
769    {
770        return m_match_all_users;
771    }
772
773    void
774    SetMatchAllUsers (bool b)
775    {
776        m_match_all_users = b;
777    }
778
779    lldb_private::NameMatchType
780    GetNameMatchType () const
781    {
782        return m_name_match_type;
783    }
784
785    void
786    SetNameMatchType (lldb_private::NameMatchType name_match_type)
787    {
788        m_name_match_type = name_match_type;
789    }
790
791    bool
792    NameMatches (const char *process_name) const;
793
794    bool
795    Matches (const ProcessInstanceInfo &proc_info) const;
796
797    bool
798    MatchAllProcesses () const;
799    void
800    Clear ();
801
802protected:
803    ProcessInstanceInfo m_match_info;
804    lldb_private::NameMatchType m_name_match_type;
805    bool m_match_all_users;
806};
807
808class ProcessInstanceInfoList
809{
810public:
811    ProcessInstanceInfoList () :
812        m_infos()
813    {
814    }
815
816    void
817    Clear()
818    {
819        m_infos.clear();
820    }
821
822    uint32_t
823    GetSize()
824    {
825        return m_infos.size();
826    }
827
828    void
829    Append (const ProcessInstanceInfo &info)
830    {
831        m_infos.push_back (info);
832    }
833
834    const char *
835    GetProcessNameAtIndex (uint32_t idx)
836    {
837        if (idx < m_infos.size())
838            return m_infos[idx].GetName();
839        return NULL;
840    }
841
842    size_t
843    GetProcessNameLengthAtIndex (uint32_t idx)
844    {
845        if (idx < m_infos.size())
846            return m_infos[idx].GetNameLength();
847        return 0;
848    }
849
850    lldb::pid_t
851    GetProcessIDAtIndex (uint32_t idx)
852    {
853        if (idx < m_infos.size())
854            return m_infos[idx].GetProcessID();
855        return 0;
856    }
857
858    bool
859    GetInfoAtIndex (uint32_t idx, ProcessInstanceInfo &info)
860    {
861        if (idx < m_infos.size())
862        {
863            info = m_infos[idx];
864            return true;
865        }
866        return false;
867    }
868
869    // You must ensure "idx" is valid before calling this function
870    const ProcessInstanceInfo &
871    GetProcessInfoAtIndex (uint32_t idx) const
872    {
873        assert (idx < m_infos.size());
874        return m_infos[idx];
875    }
876
877protected:
878    typedef std::vector<ProcessInstanceInfo> collection;
879    collection m_infos;
880};
881
882
883// This class tracks the Modification state of the process.  Things that can currently modify
884// the program are running the program (which will up the StopID) and writing memory (which
885// will up the MemoryID.)
886// FIXME: Should we also include modification of register states?
887
888class ProcessModID
889{
890friend bool operator== (const ProcessModID &lhs, const ProcessModID &rhs);
891public:
892    ProcessModID () :
893        m_stop_id (0),
894        m_memory_id (0)
895    {}
896
897    ProcessModID (const ProcessModID &rhs) :
898        m_stop_id (rhs.m_stop_id),
899        m_memory_id (rhs.m_memory_id)
900    {}
901
902    const ProcessModID & operator= (const ProcessModID &rhs)
903    {
904        if (this != &rhs)
905        {
906            m_stop_id = rhs.m_stop_id;
907            m_memory_id = rhs.m_memory_id;
908        }
909        return *this;
910    }
911
912    ~ProcessModID () {}
913
914    void BumpStopID () { m_stop_id++; }
915    void BumpMemoryID () { m_memory_id++; }
916
917    uint32_t GetStopID() const { return m_stop_id; }
918    uint32_t GetMemoryID () const { return m_memory_id; }
919
920    bool MemoryIDEqual (const ProcessModID &compare) const
921    {
922        return m_memory_id == compare.m_memory_id;
923    }
924
925    bool StopIDEqual (const ProcessModID &compare) const
926    {
927        return m_stop_id == compare.m_stop_id;
928    }
929
930    void SetInvalid ()
931    {
932        m_stop_id = UINT32_MAX;
933    }
934
935    bool IsValid () const
936    {
937        return m_stop_id != UINT32_MAX;
938    }
939private:
940    uint32_t m_stop_id;
941    uint32_t m_memory_id;
942};
943inline bool operator== (const ProcessModID &lhs, const ProcessModID &rhs)
944{
945    if (lhs.StopIDEqual (rhs)
946        && lhs.MemoryIDEqual (rhs))
947        return true;
948    else
949        return false;
950}
951
952inline bool operator!= (const ProcessModID &lhs, const ProcessModID &rhs)
953{
954    if (!lhs.StopIDEqual (rhs)
955        || !lhs.MemoryIDEqual (rhs))
956        return true;
957    else
958        return false;
959}
960
961//----------------------------------------------------------------------
962/// @class Process Process.h "lldb/Target/Process.h"
963/// @brief A plug-in interface definition class for debugging a process.
964//----------------------------------------------------------------------
965class Process :
966    public ReferenceCountedBaseVirtual<Process>,
967    public UserID,
968    public Broadcaster,
969    public ExecutionContextScope,
970    public PluginInterface,
971    public ProcessInstanceSettings
972{
973friend class ThreadList;
974friend class ClangFunction; // For WaitForStateChangeEventsPrivate
975friend class CommandObjectProcessLaunch;
976friend class ProcessEventData;
977friend class CommandObjectBreakpointCommand;
978friend class StopInfo;
979
980public:
981
982    //------------------------------------------------------------------
983    /// Broadcaster event bits definitions.
984    //------------------------------------------------------------------
985    enum
986    {
987        eBroadcastBitStateChanged   = (1 << 0),
988        eBroadcastBitInterrupt      = (1 << 1),
989        eBroadcastBitSTDOUT         = (1 << 2),
990        eBroadcastBitSTDERR         = (1 << 3)
991    };
992
993    enum
994    {
995        eBroadcastInternalStateControlStop = (1<<0),
996        eBroadcastInternalStateControlPause = (1<<1),
997        eBroadcastInternalStateControlResume = (1<<2)
998    };
999
1000    //------------------------------------------------------------------
1001    /// A notification structure that can be used by clients to listen
1002    /// for changes in a process's lifetime.
1003    ///
1004    /// @see RegisterNotificationCallbacks (const Notifications&)
1005    /// @see UnregisterNotificationCallbacks (const Notifications&)
1006    //------------------------------------------------------------------
1007#ifndef SWIG
1008    typedef struct
1009    {
1010        void *baton;
1011        void (*initialize)(void *baton, Process *process);
1012        void (*process_state_changed) (void *baton, Process *process, lldb::StateType state);
1013    } Notifications;
1014
1015    class ProcessEventData :
1016        public EventData
1017    {
1018        friend class Process;
1019
1020        public:
1021            ProcessEventData ();
1022            ProcessEventData (const lldb::ProcessSP &process, lldb::StateType state);
1023
1024            virtual ~ProcessEventData();
1025
1026            static const ConstString &
1027            GetFlavorString ();
1028
1029            virtual const ConstString &
1030            GetFlavor () const;
1031
1032            const lldb::ProcessSP &
1033            GetProcessSP() const
1034            {
1035                return m_process_sp;
1036            }
1037            lldb::StateType
1038            GetState() const
1039            {
1040                return m_state;
1041            }
1042            bool
1043            GetRestarted () const
1044            {
1045                return m_restarted;
1046            }
1047            bool
1048            GetInterrupted () const
1049            {
1050                return m_interrupted;
1051            }
1052
1053            virtual void
1054            Dump (Stream *s) const;
1055
1056            virtual void
1057            DoOnRemoval (Event *event_ptr);
1058
1059            static const Process::ProcessEventData *
1060            GetEventDataFromEvent (const Event *event_ptr);
1061
1062            static lldb::ProcessSP
1063            GetProcessFromEvent (const Event *event_ptr);
1064
1065            static lldb::StateType
1066            GetStateFromEvent (const Event *event_ptr);
1067
1068            static bool
1069            GetRestartedFromEvent (const Event *event_ptr);
1070
1071            static void
1072            SetRestartedInEvent (Event *event_ptr, bool new_value);
1073
1074            static bool
1075            GetInterruptedFromEvent (const Event *event_ptr);
1076
1077            static void
1078            SetInterruptedInEvent (Event *event_ptr, bool new_value);
1079
1080            static bool
1081            SetUpdateStateOnRemoval (Event *event_ptr);
1082
1083       private:
1084
1085            void
1086            SetUpdateStateOnRemoval()
1087            {
1088                m_update_state++;
1089            }
1090            void
1091            SetRestarted (bool new_value)
1092            {
1093                m_restarted = new_value;
1094            }
1095            void
1096            SetInterrupted (bool new_value)
1097            {
1098                m_interrupted = new_value;
1099            }
1100
1101            lldb::ProcessSP m_process_sp;
1102            lldb::StateType m_state;
1103            bool m_restarted;  // For "eStateStopped" events, this is true if the target was automatically restarted.
1104            int m_update_state;
1105            bool m_interrupted;
1106            DISALLOW_COPY_AND_ASSIGN (ProcessEventData);
1107
1108    };
1109
1110    class SettingsController : public UserSettingsController
1111    {
1112    public:
1113
1114        SettingsController ();
1115
1116        virtual
1117        ~SettingsController ();
1118
1119        static SettingEntry global_settings_table[];
1120        static SettingEntry instance_settings_table[];
1121
1122    protected:
1123
1124        lldb::InstanceSettingsSP
1125        CreateInstanceSettings (const char *instance_name);
1126
1127    private:
1128
1129        // Class-wide settings.
1130
1131        DISALLOW_COPY_AND_ASSIGN (SettingsController);
1132    };
1133
1134
1135#endif
1136
1137    static void
1138    SettingsInitialize ();
1139
1140    static void
1141    SettingsTerminate ();
1142
1143    static lldb::UserSettingsControllerSP &
1144    GetSettingsController ();
1145
1146    void
1147    UpdateInstanceName ();
1148
1149
1150    //------------------------------------------------------------------
1151    /// Construct with a shared pointer to a target, and the Process listener.
1152    //------------------------------------------------------------------
1153    Process(Target &target, Listener &listener);
1154
1155    //------------------------------------------------------------------
1156    /// Destructor.
1157    ///
1158    /// The destructor is virtual since this class is designed to be
1159    /// inherited from by the plug-in instance.
1160    //------------------------------------------------------------------
1161    virtual
1162    ~Process();
1163
1164    //------------------------------------------------------------------
1165    /// Find a Process plug-in that can debug \a module using the
1166    /// currently selected architecture.
1167    ///
1168    /// Scans all loaded plug-in interfaces that implement versions of
1169    /// the Process plug-in interface and returns the first instance
1170    /// that can debug the file.
1171    ///
1172    /// @param[in] module_sp
1173    ///     The module shared pointer that this process will debug.
1174    ///
1175    /// @param[in] plugin_name
1176    ///     If NULL, select the best plug-in for the binary. If non-NULL
1177    ///     then look for a plugin whose PluginInfo's name matches
1178    ///     this string.
1179    ///
1180    /// @see Process::CanDebug ()
1181    //------------------------------------------------------------------
1182    static Process*
1183    FindPlugin (Target &target, const char *plugin_name, Listener &listener);
1184
1185
1186
1187    //------------------------------------------------------------------
1188    /// Static function that can be used with the \b host function
1189    /// Host::StartMonitoringChildProcess ().
1190    ///
1191    /// This function can be used by lldb_private::Process subclasses
1192    /// when they want to watch for a local process and have its exit
1193    /// status automatically set when the host child process exits.
1194    /// Subclasses should call Host::StartMonitoringChildProcess ()
1195    /// with:
1196    ///     callback = Process::SetHostProcessExitStatus
1197    ///     callback_baton = NULL
1198    ///     pid = Process::GetID()
1199    ///     monitor_signals = false
1200    //------------------------------------------------------------------
1201    static bool
1202    SetProcessExitStatus (void *callback_baton,   // The callback baton which should be set to NULL
1203                          lldb::pid_t pid,        // The process ID we want to monitor
1204                          int signo,              // Zero for no signal
1205                          int status);            // Exit value of process if signal is zero
1206
1207    lldb::ByteOrder
1208    GetByteOrder () const;
1209
1210    uint32_t
1211    GetAddressByteSize () const;
1212
1213    //------------------------------------------------------------------
1214    /// Check if a plug-in instance can debug the file in \a module.
1215    ///
1216    /// Each plug-in is given a chance to say whether it can debug
1217    /// the file in \a module. If the Process plug-in instance can
1218    /// debug a file on the current system, it should return \b true.
1219    ///
1220    /// @return
1221    ///     Returns \b true if this Process plug-in instance can
1222    ///     debug the executable, \b false otherwise.
1223    //------------------------------------------------------------------
1224    virtual bool
1225    CanDebug (Target &target,
1226              bool plugin_specified_by_name) = 0;
1227
1228
1229    //------------------------------------------------------------------
1230    /// This object is about to be destroyed, do any necessary cleanup.
1231    ///
1232    /// Subclasses that override this method should always call this
1233    /// superclass method.
1234    //------------------------------------------------------------------
1235    virtual void
1236    Finalize();
1237
1238    //------------------------------------------------------------------
1239    /// Launch a new process.
1240    ///
1241    /// Launch a new process by spawning a new process using the
1242    /// target object's executable module's file as the file to launch.
1243    /// Arguments are given in \a argv, and the environment variables
1244    /// are in \a envp. Standard input and output files can be
1245    /// optionally re-directed to \a stdin_path, \a stdout_path, and
1246    /// \a stderr_path.
1247    ///
1248    /// This function is not meant to be overridden by Process
1249    /// subclasses. It will first call Process::WillLaunch (Module *)
1250    /// and if that returns \b true, Process::DoLaunch (Module*,
1251    /// char const *[],char const *[],const char *,const char *,
1252    /// const char *) will be called to actually do the launching. If
1253    /// DoLaunch returns \b true, then Process::DidLaunch() will be
1254    /// called.
1255    ///
1256    /// @param[in] argv
1257    ///     The argument array.
1258    ///
1259    /// @param[in] envp
1260    ///     The environment array.
1261    ///
1262    /// @param[in] launch_flags
1263    ///     Flags to modify the launch (@see lldb::LaunchFlags)
1264    ///
1265    /// @param[in] stdin_path
1266    ///     The path to use when re-directing the STDIN of the new
1267    ///     process. If all stdXX_path arguments are NULL, a pseudo
1268    ///     terminal will be used.
1269    ///
1270    /// @param[in] stdout_path
1271    ///     The path to use when re-directing the STDOUT of the new
1272    ///     process. If all stdXX_path arguments are NULL, a pseudo
1273    ///     terminal will be used.
1274    ///
1275    /// @param[in] stderr_path
1276    ///     The path to use when re-directing the STDERR of the new
1277    ///     process. If all stdXX_path arguments are NULL, a pseudo
1278    ///     terminal will be used.
1279    ///
1280    /// @param[in] working_directory
1281    ///     The working directory to have the child process run in
1282    ///
1283    /// @return
1284    ///     An error object. Call GetID() to get the process ID if
1285    ///     the error object is success.
1286    //------------------------------------------------------------------
1287    virtual Error
1288    Launch (const ProcessLaunchInfo &launch_info);
1289
1290    //------------------------------------------------------------------
1291    /// Attach to an existing process using a process ID.
1292    ///
1293    /// This function is not meant to be overridden by Process
1294    /// subclasses. It will first call Process::WillAttach (lldb::pid_t)
1295    /// and if that returns \b true, Process::DoAttach (lldb::pid_t) will
1296    /// be called to actually do the attach. If DoAttach returns \b
1297    /// true, then Process::DidAttach() will be called.
1298    ///
1299    /// @param[in] pid
1300    ///     The process ID that we should attempt to attach to.
1301    ///
1302    /// @return
1303    ///     Returns \a pid if attaching was successful, or
1304    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
1305    //------------------------------------------------------------------
1306    virtual Error
1307    Attach (lldb::pid_t pid);
1308
1309    //------------------------------------------------------------------
1310    /// Attach to an existing process by process name.
1311    ///
1312    /// This function is not meant to be overridden by Process
1313    /// subclasses. It will first call
1314    /// Process::WillAttach (const char *) and if that returns \b
1315    /// true, Process::DoAttach (const char *) will be called to
1316    /// actually do the attach. If DoAttach returns \b true, then
1317    /// Process::DidAttach() will be called.
1318    ///
1319    /// @param[in] process_name
1320    ///     A process name to match against the current process list.
1321    ///
1322    /// @return
1323    ///     Returns \a pid if attaching was successful, or
1324    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
1325    //------------------------------------------------------------------
1326    virtual Error
1327    Attach (const char *process_name, bool wait_for_launch);
1328
1329    virtual Error
1330    ConnectRemote (const char *remote_url);
1331
1332    bool
1333    AttachedToProcess() const
1334    {
1335        return m_attached_to_process;
1336    }
1337
1338    //------------------------------------------------------------------
1339    /// Get the image information address for the current process.
1340    ///
1341    /// Some runtimes have system functions that can help dynamic
1342    /// loaders locate the dynamic loader information needed to observe
1343    /// shared libraries being loaded or unloaded. This function is
1344    /// in the Process interface (as opposed to the DynamicLoader
1345    /// interface) to ensure that remote debugging can take advantage of
1346    /// this functionality.
1347    ///
1348    /// @return
1349    ///     The address of the dynamic loader information, or
1350    ///     LLDB_INVALID_ADDRESS if this is not supported by this
1351    ///     interface.
1352    //------------------------------------------------------------------
1353    virtual lldb::addr_t
1354    GetImageInfoAddress ();
1355
1356    //------------------------------------------------------------------
1357    /// Load a shared library into this process.
1358    ///
1359    /// Try and load a shared library into the current process. This
1360    /// call might fail in the dynamic loader plug-in says it isn't safe
1361    /// to try and load shared libraries at the moment.
1362    ///
1363    /// @param[in] image_spec
1364    ///     The image file spec that points to the shared library that
1365    ///     you want to load.
1366    ///
1367    /// @param[out] error
1368    ///     An error object that gets filled in with any errors that
1369    ///     might occur when trying to load the shared library.
1370    ///
1371    /// @return
1372    ///     A token that represents the shared library that can be
1373    ///     later used to unload the shared library. A value of
1374    ///     LLDB_INVALID_IMAGE_TOKEN will be returned if the shared
1375    ///     library can't be opened.
1376    //------------------------------------------------------------------
1377    virtual uint32_t
1378    LoadImage (const FileSpec &image_spec, Error &error);
1379
1380    virtual Error
1381    UnloadImage (uint32_t image_token);
1382
1383    //------------------------------------------------------------------
1384    /// Register for process and thread notifications.
1385    ///
1386    /// Clients can register nofication callbacks by filling out a
1387    /// Process::Notifications structure and calling this function.
1388    ///
1389    /// @param[in] callbacks
1390    ///     A structure that contains the notification baton and
1391    ///     callback functions.
1392    ///
1393    /// @see Process::Notifications
1394    //------------------------------------------------------------------
1395#ifndef SWIG
1396    void
1397    RegisterNotificationCallbacks (const Process::Notifications& callbacks);
1398#endif
1399    //------------------------------------------------------------------
1400    /// Unregister for process and thread notifications.
1401    ///
1402    /// Clients can unregister nofication callbacks by passing a copy of
1403    /// the original baton and callbacks in \a callbacks.
1404    ///
1405    /// @param[in] callbacks
1406    ///     A structure that contains the notification baton and
1407    ///     callback functions.
1408    ///
1409    /// @return
1410    ///     Returns \b true if the notification callbacks were
1411    ///     successfully removed from the process, \b false otherwise.
1412    ///
1413    /// @see Process::Notifications
1414    //------------------------------------------------------------------
1415#ifndef SWIG
1416    bool
1417    UnregisterNotificationCallbacks (const Process::Notifications& callbacks);
1418#endif
1419    //==================================================================
1420    // Built in Process Control functions
1421    //==================================================================
1422    //------------------------------------------------------------------
1423    /// Resumes all of a process's threads as configured using the
1424    /// Thread run control functions.
1425    ///
1426    /// Threads for a process should be updated with one of the run
1427    /// control actions (resume, step, or suspend) that they should take
1428    /// when the process is resumed. If no run control action is given
1429    /// to a thread it will be resumed by default.
1430    ///
1431    /// This function is not meant to be overridden by Process
1432    /// subclasses. This function will take care of disabling any
1433    /// breakpoints that threads may be stopped at, single stepping, and
1434    /// re-enabling breakpoints, and enabling the basic flow control
1435    /// that the plug-in instances need not worry about.
1436    ///
1437    /// @return
1438    ///     Returns an error object.
1439    ///
1440    /// @see Thread:Resume()
1441    /// @see Thread:Step()
1442    /// @see Thread:Suspend()
1443    //------------------------------------------------------------------
1444    Error
1445    Resume ();
1446
1447    //------------------------------------------------------------------
1448    /// Halts a running process.
1449    ///
1450    /// This function is not meant to be overridden by Process
1451    /// subclasses.
1452    /// If the process is successfully halted, a eStateStopped
1453    /// process event with GetInterrupted will be broadcast.  If false, we will
1454    /// halt the process with no events generated by the halt.
1455    ///
1456    /// @return
1457    ///     Returns an error object.  If the error is empty, the process is halted.
1458    ///     otherwise the halt has failed.
1459    //------------------------------------------------------------------
1460    Error
1461    Halt ();
1462
1463    //------------------------------------------------------------------
1464    /// Detaches from a running or stopped process.
1465    ///
1466    /// This function is not meant to be overridden by Process
1467    /// subclasses.
1468    ///
1469    /// @return
1470    ///     Returns an error object.
1471    //------------------------------------------------------------------
1472    Error
1473    Detach ();
1474
1475    //------------------------------------------------------------------
1476    /// Kills the process and shuts down all threads that were spawned
1477    /// to track and monitor the process.
1478    ///
1479    /// This function is not meant to be overridden by Process
1480    /// subclasses.
1481    ///
1482    /// @return
1483    ///     Returns an error object.
1484    //------------------------------------------------------------------
1485    Error
1486    Destroy();
1487
1488    //------------------------------------------------------------------
1489    /// Sends a process a UNIX signal \a signal.
1490    ///
1491    /// This function is not meant to be overridden by Process
1492    /// subclasses.
1493    ///
1494    /// @return
1495    ///     Returns an error object.
1496    //------------------------------------------------------------------
1497    Error
1498    Signal (int signal);
1499
1500    virtual UnixSignals &
1501    GetUnixSignals ()
1502    {
1503        return m_unix_signals;
1504    }
1505
1506    //==================================================================
1507    // Plug-in Process Control Overrides
1508    //==================================================================
1509
1510    //------------------------------------------------------------------
1511    /// Called before attaching to a process.
1512    ///
1513    /// Allow Process plug-ins to execute some code before attaching a
1514    /// process.
1515    ///
1516    /// @return
1517    ///     Returns an error object.
1518    //------------------------------------------------------------------
1519    virtual Error
1520    WillAttachToProcessWithID (lldb::pid_t pid)
1521    {
1522        return Error();
1523    }
1524
1525    //------------------------------------------------------------------
1526    /// Called before attaching to a process.
1527    ///
1528    /// Allow Process plug-ins to execute some code before attaching a
1529    /// process.
1530    ///
1531    /// @return
1532    ///     Returns an error object.
1533    //------------------------------------------------------------------
1534    virtual Error
1535    WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
1536    {
1537        return Error();
1538    }
1539
1540    virtual Error
1541    DoConnectRemote (const char *remote_url)
1542    {
1543        Error error;
1544        error.SetErrorString ("remote connections are not supported");
1545        return error;
1546    }
1547
1548    //------------------------------------------------------------------
1549    /// Attach to an existing process using a process ID.
1550    ///
1551    /// @param[in] pid
1552    ///     The process ID that we should attempt to attach to.
1553    ///
1554    /// @return
1555    ///     Returns \a pid if attaching was successful, or
1556    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
1557    //------------------------------------------------------------------
1558    virtual Error
1559    DoAttachToProcessWithID (lldb::pid_t pid) = 0;
1560
1561    //------------------------------------------------------------------
1562    /// Attach to an existing process using a partial process name.
1563    ///
1564    /// @param[in] process_name
1565    ///     The name of the process to attach to.
1566    ///
1567    /// @param[in] wait_for_launch
1568    ///     If \b true, wait for the process to be launched and attach
1569    ///     as soon as possible after it does launch. If \b false, then
1570    ///     search for a matching process the currently exists.
1571    ///
1572    /// @return
1573    ///     Returns \a pid if attaching was successful, or
1574    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
1575    //------------------------------------------------------------------
1576    virtual Error
1577    DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
1578    {
1579        Error error;
1580        error.SetErrorString("attach by name is not supported");
1581        return error;
1582    }
1583
1584    //------------------------------------------------------------------
1585    /// Called after attaching a process.
1586    ///
1587    /// Allow Process plug-ins to execute some code after attaching to
1588    /// a process.
1589    //------------------------------------------------------------------
1590    virtual void
1591    DidAttach () {}
1592
1593
1594    //------------------------------------------------------------------
1595    /// Called before launching to a process.
1596    ///
1597    /// Allow Process plug-ins to execute some code before launching a
1598    /// process.
1599    ///
1600    /// @return
1601    ///     Returns an error object.
1602    //------------------------------------------------------------------
1603    virtual Error
1604    WillLaunch (Module* module)
1605    {
1606        return Error();
1607    }
1608
1609    //------------------------------------------------------------------
1610    /// Launch a new process.
1611    ///
1612    /// Launch a new process by spawning a new process using \a module's
1613    /// file as the file to launch. Arguments are given in \a argv,
1614    /// and the environment variables are in \a envp. Standard input
1615    /// and output files can be optionally re-directed to \a stdin_path,
1616    /// \a stdout_path, and \a stderr_path.
1617    ///
1618    /// @param[in] module
1619    ///     The module from which to extract the file specification and
1620    ///     launch.
1621    ///
1622    /// @param[in] argv
1623    ///     The argument array.
1624    ///
1625    /// @param[in] envp
1626    ///     The environment array.
1627    ///
1628    /// @param[in] launch_flags
1629    ///     Flags to modify the launch (@see lldb::LaunchFlags)
1630    ///
1631    /// @param[in] stdin_path
1632    ///     The path to use when re-directing the STDIN of the new
1633    ///     process. If all stdXX_path arguments are NULL, a pseudo
1634    ///     terminal will be used.
1635    ///
1636    /// @param[in] stdout_path
1637    ///     The path to use when re-directing the STDOUT of the new
1638    ///     process. If all stdXX_path arguments are NULL, a pseudo
1639    ///     terminal will be used.
1640    ///
1641    /// @param[in] stderr_path
1642    ///     The path to use when re-directing the STDERR of the new
1643    ///     process. If all stdXX_path arguments are NULL, a pseudo
1644    ///     terminal will be used.
1645    ///
1646    /// @param[in] working_directory
1647    ///     The working directory to have the child process run in
1648    ///
1649    /// @return
1650    ///     A new valid process ID, or LLDB_INVALID_PROCESS_ID if
1651    ///     launching fails.
1652    //------------------------------------------------------------------
1653    virtual Error
1654    DoLaunch (Module *exe_module,
1655              const ProcessLaunchInfo &launch_info) = 0;
1656
1657    //------------------------------------------------------------------
1658    /// Called after launching a process.
1659    ///
1660    /// Allow Process plug-ins to execute some code after launching
1661    /// a process.
1662    //------------------------------------------------------------------
1663    virtual void
1664    DidLaunch () {}
1665
1666
1667
1668    //------------------------------------------------------------------
1669    /// Called before resuming to a process.
1670    ///
1671    /// Allow Process plug-ins to execute some code before resuming a
1672    /// process.
1673    ///
1674    /// @return
1675    ///     Returns an error object.
1676    //------------------------------------------------------------------
1677    virtual Error
1678    WillResume () { return Error(); }
1679
1680    //------------------------------------------------------------------
1681    /// Resumes all of a process's threads as configured using the
1682    /// Thread run control functions.
1683    ///
1684    /// Threads for a process should be updated with one of the run
1685    /// control actions (resume, step, or suspend) that they should take
1686    /// when the process is resumed. If no run control action is given
1687    /// to a thread it will be resumed by default.
1688    ///
1689    /// @return
1690    ///     Returns \b true if the process successfully resumes using
1691    ///     the thread run control actions, \b false otherwise.
1692    ///
1693    /// @see Thread:Resume()
1694    /// @see Thread:Step()
1695    /// @see Thread:Suspend()
1696    //------------------------------------------------------------------
1697    virtual Error
1698    DoResume () = 0;
1699
1700    //------------------------------------------------------------------
1701    /// Called after resuming a process.
1702    ///
1703    /// Allow Process plug-ins to execute some code after resuming
1704    /// a process.
1705    //------------------------------------------------------------------
1706    virtual void
1707    DidResume () {}
1708
1709
1710    //------------------------------------------------------------------
1711    /// Called before halting to a process.
1712    ///
1713    /// Allow Process plug-ins to execute some code before halting a
1714    /// process.
1715    ///
1716    /// @return
1717    ///     Returns an error object.
1718    //------------------------------------------------------------------
1719    virtual Error
1720    WillHalt () { return Error(); }
1721
1722    //------------------------------------------------------------------
1723    /// Halts a running process.
1724    ///
1725    /// DoHalt must produce one and only one stop StateChanged event if it actually
1726    /// stops the process.  If the stop happens through some natural event (for
1727    /// instance a SIGSTOP), then forwarding that event will do.  Otherwise, you must
1728    /// generate the event manually.  Note also, the private event thread is stopped when
1729    /// DoHalt is run to prevent the events generated while halting to trigger
1730    /// other state changes before the halt is complete.
1731    ///
1732    /// @param[out] caused_stop
1733    ///     If true, then this Halt caused the stop, otherwise, the
1734    ///     process was already stopped.
1735    ///
1736    /// @return
1737    ///     Returns \b true if the process successfully halts, \b false
1738    ///     otherwise.
1739    //------------------------------------------------------------------
1740    virtual Error
1741    DoHalt (bool &caused_stop) = 0;
1742
1743    //------------------------------------------------------------------
1744    /// Called after halting a process.
1745    ///
1746    /// Allow Process plug-ins to execute some code after halting
1747    /// a process.
1748    //------------------------------------------------------------------
1749    virtual void
1750    DidHalt () {}
1751
1752    //------------------------------------------------------------------
1753    /// Called before detaching from a process.
1754    ///
1755    /// Allow Process plug-ins to execute some code before detaching
1756    /// from a process.
1757    ///
1758    /// @return
1759    ///     Returns an error object.
1760    //------------------------------------------------------------------
1761    virtual Error
1762    WillDetach ()
1763    {
1764        return Error();
1765    }
1766
1767    //------------------------------------------------------------------
1768    /// Detaches from a running or stopped process.
1769    ///
1770    /// @return
1771    ///     Returns \b true if the process successfully detaches, \b
1772    ///     false otherwise.
1773    //------------------------------------------------------------------
1774    virtual Error
1775    DoDetach () = 0;
1776
1777    //------------------------------------------------------------------
1778    /// Called after detaching from a process.
1779    ///
1780    /// Allow Process plug-ins to execute some code after detaching
1781    /// from a process.
1782    //------------------------------------------------------------------
1783    virtual void
1784    DidDetach () {}
1785
1786    //------------------------------------------------------------------
1787    /// Called before sending a signal to a process.
1788    ///
1789    /// Allow Process plug-ins to execute some code before sending a
1790    /// signal to a process.
1791    ///
1792    /// @return
1793    ///     Returns no error if it is safe to proceed with a call to
1794    ///     Process::DoSignal(int), otherwise an error describing what
1795    ///     prevents the signal from being sent.
1796    //------------------------------------------------------------------
1797    virtual Error
1798    WillSignal () { return Error(); }
1799
1800    //------------------------------------------------------------------
1801    /// Sends a process a UNIX signal \a signal.
1802    ///
1803    /// @return
1804    ///     Returns an error object.
1805    //------------------------------------------------------------------
1806    virtual Error
1807    DoSignal (int signal) = 0;
1808
1809
1810
1811    virtual Error
1812    WillDestroy () { return Error(); }
1813
1814    virtual Error
1815    DoDestroy () = 0;
1816
1817    virtual void
1818    DidDestroy () { }
1819
1820
1821    //------------------------------------------------------------------
1822    /// Called after sending a signal to a process.
1823    ///
1824    /// Allow Process plug-ins to execute some code after sending a
1825    /// signal to a process.
1826    //------------------------------------------------------------------
1827    virtual void
1828    DidSignal () {}
1829
1830
1831    //------------------------------------------------------------------
1832    /// Currently called as part of ShouldStop.
1833    /// FIXME: Should really happen when the target stops before the
1834    /// event is taken from the queue...
1835    ///
1836    /// This callback is called as the event
1837    /// is about to be queued up to allow Process plug-ins to execute
1838    /// some code prior to clients being notified that a process was
1839    /// stopped. Common operations include updating the thread list,
1840    /// invalidating any thread state (registers, stack, etc) prior to
1841    /// letting the notification go out.
1842    ///
1843    //------------------------------------------------------------------
1844    virtual void
1845    RefreshStateAfterStop () = 0;
1846
1847    //------------------------------------------------------------------
1848    /// Get the target object pointer for this module.
1849    ///
1850    /// @return
1851    ///     A Target object pointer to the target that owns this
1852    ///     module.
1853    //------------------------------------------------------------------
1854    Target &
1855    GetTarget ()
1856    {
1857        return m_target;
1858    }
1859
1860    //------------------------------------------------------------------
1861    /// Get the const target object pointer for this module.
1862    ///
1863    /// @return
1864    ///     A const Target object pointer to the target that owns this
1865    ///     module.
1866    //------------------------------------------------------------------
1867    const Target &
1868    GetTarget () const
1869    {
1870        return m_target;
1871    }
1872
1873
1874    //------------------------------------------------------------------
1875    /// Get accessor for the current process state.
1876    ///
1877    /// @return
1878    ///     The current state of the process.
1879    ///
1880    /// @see lldb::StateType
1881    //------------------------------------------------------------------
1882    lldb::StateType
1883    GetState ();
1884
1885    ExecutionResults
1886    RunThreadPlan (ExecutionContext &exe_ctx,
1887                    lldb::ThreadPlanSP &thread_plan_sp,
1888                    bool stop_others,
1889                    bool try_all_threads,
1890                    bool discard_on_error,
1891                    uint32_t single_thread_timeout_usec,
1892                    Stream &errors);
1893
1894    static const char *
1895    ExecutionResultAsCString (ExecutionResults result);
1896
1897    void
1898    GetStatus (Stream &ostrm);
1899
1900    size_t
1901    GetThreadStatus (Stream &ostrm,
1902                     bool only_threads_with_stop_reason,
1903                     uint32_t start_frame,
1904                     uint32_t num_frames,
1905                     uint32_t num_frames_with_source);
1906
1907protected:
1908
1909    void
1910    SetState (lldb::EventSP &event_sp);
1911
1912    lldb::StateType
1913    GetPrivateState ();
1914
1915    //------------------------------------------------------------------
1916    // Called internally
1917    //------------------------------------------------------------------
1918    void
1919    CompleteAttach ();
1920
1921public:
1922    //------------------------------------------------------------------
1923    /// Get the exit status for a process.
1924    ///
1925    /// @return
1926    ///     The process's return code, or -1 if the current process
1927    ///     state is not eStateExited.
1928    //------------------------------------------------------------------
1929    int
1930    GetExitStatus ();
1931
1932    //------------------------------------------------------------------
1933    /// Get a textual description of what the process exited.
1934    ///
1935    /// @return
1936    ///     The textual description of why the process exited, or NULL
1937    ///     if there is no description available.
1938    //------------------------------------------------------------------
1939    const char *
1940    GetExitDescription ();
1941
1942
1943    virtual void
1944    DidExit ()
1945    {
1946    }
1947
1948    //------------------------------------------------------------------
1949    /// Get the Modification ID of the process.
1950    ///
1951    /// @return
1952    ///     The modification ID of the process.
1953    //------------------------------------------------------------------
1954    ProcessModID
1955    GetModID () const
1956    {
1957        return m_mod_id;
1958    }
1959
1960    uint32_t
1961    GetStopID () const
1962    {
1963        return m_mod_id.GetStopID();
1964    }
1965
1966    //------------------------------------------------------------------
1967    /// Set accessor for the process exit status (return code).
1968    ///
1969    /// Sometimes a child exits and the exit can be detected by global
1970    /// functions (signal handler for SIGCHLD for example). This
1971    /// accessor allows the exit status to be set from an external
1972    /// source.
1973    ///
1974    /// Setting this will cause a eStateExited event to be posted to
1975    /// the process event queue.
1976    ///
1977    /// @param[in] exit_status
1978    ///     The value for the process's return code.
1979    ///
1980    /// @see lldb::StateType
1981    //------------------------------------------------------------------
1982    virtual bool
1983    SetExitStatus (int exit_status, const char *cstr);
1984
1985    //------------------------------------------------------------------
1986    /// Check if a process is still alive.
1987    ///
1988    /// @return
1989    ///     Returns \b true if the process is still valid, \b false
1990    ///     otherwise.
1991    //------------------------------------------------------------------
1992    virtual bool
1993    IsAlive () = 0;
1994
1995    //------------------------------------------------------------------
1996    /// Actually do the reading of memory from a process.
1997    ///
1998    /// Subclasses must override this function and can return fewer
1999    /// bytes than requested when memory requests are too large. This
2000    /// class will break up the memory requests and keep advancing the
2001    /// arguments along as needed.
2002    ///
2003    /// @param[in] vm_addr
2004    ///     A virtual load address that indicates where to start reading
2005    ///     memory from.
2006    ///
2007    /// @param[in] size
2008    ///     The number of bytes to read.
2009    ///
2010    /// @param[out] buf
2011    ///     A byte buffer that is at least \a size bytes long that
2012    ///     will receive the memory bytes.
2013    ///
2014    /// @return
2015    ///     The number of bytes that were actually read into \a buf.
2016    //------------------------------------------------------------------
2017    virtual size_t
2018    DoReadMemory (lldb::addr_t vm_addr,
2019                  void *buf,
2020                  size_t size,
2021                  Error &error) = 0;
2022
2023    //------------------------------------------------------------------
2024    /// Read of memory from a process.
2025    ///
2026    /// This function will read memory from the current process's
2027    /// address space and remove any traps that may have been inserted
2028    /// into the memory.
2029    ///
2030    /// This function is not meant to be overridden by Process
2031    /// subclasses, the subclasses should implement
2032    /// Process::DoReadMemory (lldb::addr_t, size_t, void *).
2033    ///
2034    /// @param[in] vm_addr
2035    ///     A virtual load address that indicates where to start reading
2036    ///     memory from.
2037    ///
2038    /// @param[out] buf
2039    ///     A byte buffer that is at least \a size bytes long that
2040    ///     will receive the memory bytes.
2041    ///
2042    /// @param[in] size
2043    ///     The number of bytes to read.
2044    ///
2045    /// @return
2046    ///     The number of bytes that were actually read into \a buf. If
2047    ///     the returned number is greater than zero, yet less than \a
2048    ///     size, then this function will get called again with \a
2049    ///     vm_addr, \a buf, and \a size updated appropriately. Zero is
2050    ///     returned to indicate an error.
2051    //------------------------------------------------------------------
2052    size_t
2053    ReadMemory (lldb::addr_t vm_addr,
2054                void *buf,
2055                size_t size,
2056                Error &error);
2057
2058    //------------------------------------------------------------------
2059    /// Read a NULL terminated C string from memory
2060    ///
2061    /// This function will read a cache page at a time until the NULL
2062    /// C stirng terminator is found. It will stop reading if the NULL
2063    /// termination byte isn't found before reading \a cstr_max_len
2064    /// bytes, and the results are always guaranteed to be NULL
2065    /// terminated (at most cstr_max_len - 1 bytes will be read).
2066    //------------------------------------------------------------------
2067    size_t
2068    ReadCStringFromMemory (lldb::addr_t vm_addr,
2069                           char *cstr,
2070                           size_t cstr_max_len);
2071
2072    size_t
2073    ReadMemoryFromInferior (lldb::addr_t vm_addr,
2074                            void *buf,
2075                            size_t size,
2076                            Error &error);
2077
2078    //------------------------------------------------------------------
2079    /// Reads an unsigned integer of the specified byte size from
2080    /// process memory.
2081    ///
2082    /// @param[in] load_addr
2083    ///     A load address of the integer to read.
2084    ///
2085    /// @param[in] byte_size
2086    ///     The size in byte of the integer to read.
2087    ///
2088    /// @param[in] fail_value
2089    ///     The value to return if we fail to read an integer.
2090    ///
2091    /// @param[out] error
2092    ///     An error that indicates the success or failure of this
2093    ///     operation. If error indicates success (error.Success()),
2094    ///     then the value returned can be trusted, otherwise zero
2095    ///     will be returned.
2096    ///
2097    /// @return
2098    ///     The unsigned integer that was read from the process memory
2099    ///     space. If the integer was smaller than a uint64_t, any
2100    ///     unused upper bytes will be zero filled. If the process
2101    ///     byte order differs from the host byte order, the integer
2102    ///     value will be appropriately byte swapped into host byte
2103    ///     order.
2104    //------------------------------------------------------------------
2105    uint64_t
2106    ReadUnsignedIntegerFromMemory (lldb::addr_t load_addr,
2107                                   size_t byte_size,
2108                                   uint64_t fail_value,
2109                                   Error &error);
2110
2111    lldb::addr_t
2112    ReadPointerFromMemory (lldb::addr_t vm_addr,
2113                           Error &error);
2114
2115    bool
2116    WritePointerToMemory (lldb::addr_t vm_addr,
2117                          lldb::addr_t ptr_value,
2118                          Error &error);
2119
2120    //------------------------------------------------------------------
2121    /// Actually do the writing of memory to a process.
2122    ///
2123    /// @param[in] vm_addr
2124    ///     A virtual load address that indicates where to start writing
2125    ///     memory to.
2126    ///
2127    /// @param[in] buf
2128    ///     A byte buffer that is at least \a size bytes long that
2129    ///     contains the data to write.
2130    ///
2131    /// @param[in] size
2132    ///     The number of bytes to write.
2133    ///
2134    /// @param[out] error
2135    ///     An error value in case the memory write fails.
2136    ///
2137    /// @return
2138    ///     The number of bytes that were actually written.
2139    //------------------------------------------------------------------
2140    virtual size_t
2141    DoWriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error) = 0;
2142
2143    //------------------------------------------------------------------
2144    /// Write all or part of a scalar value to memory.
2145    ///
2146    /// The value contained in \a scalar will be swapped to match the
2147    /// byte order of the process that is being debugged. If \a size is
2148    /// less than the size of scalar, the least significate \a size bytes
2149    /// from scalar will be written. If \a size is larger than the byte
2150    /// size of scalar, then the extra space will be padded with zeros
2151    /// and the scalar value will be placed in the least significant
2152    /// bytes in memory.
2153    ///
2154    /// @param[in] vm_addr
2155    ///     A virtual load address that indicates where to start writing
2156    ///     memory to.
2157    ///
2158    /// @param[in] scalar
2159    ///     The scalar to write to the debugged process.
2160    ///
2161    /// @param[in] size
2162    ///     This value can be smaller or larger than the scalar value
2163    ///     itself. If \a size is smaller than the size of \a scalar,
2164    ///     the least significant bytes in \a scalar will be used. If
2165    ///     \a size is larger than the byte size of \a scalar, then
2166    ///     the extra space will be padded with zeros. If \a size is
2167    ///     set to UINT32_MAX, then the size of \a scalar will be used.
2168    ///
2169    /// @param[out] error
2170    ///     An error value in case the memory write fails.
2171    ///
2172    /// @return
2173    ///     The number of bytes that were actually written.
2174    //------------------------------------------------------------------
2175    size_t
2176    WriteScalarToMemory (lldb::addr_t vm_addr,
2177                         const Scalar &scalar,
2178                         uint32_t size,
2179                         Error &error);
2180
2181    size_t
2182    ReadScalarIntegerFromMemory (lldb::addr_t addr,
2183                                 uint32_t byte_size,
2184                                 bool is_signed,
2185                                 Scalar &scalar,
2186                                 Error &error);
2187
2188    //------------------------------------------------------------------
2189    /// Write memory to a process.
2190    ///
2191    /// This function will write memory to the current process's
2192    /// address space and maintain any traps that might be present due
2193    /// to software breakpoints.
2194    ///
2195    /// This function is not meant to be overridden by Process
2196    /// subclasses, the subclasses should implement
2197    /// Process::DoWriteMemory (lldb::addr_t, size_t, void *).
2198    ///
2199    /// @param[in] vm_addr
2200    ///     A virtual load address that indicates where to start writing
2201    ///     memory to.
2202    ///
2203    /// @param[in] buf
2204    ///     A byte buffer that is at least \a size bytes long that
2205    ///     contains the data to write.
2206    ///
2207    /// @param[in] size
2208    ///     The number of bytes to write.
2209    ///
2210    /// @return
2211    ///     The number of bytes that were actually written.
2212    //------------------------------------------------------------------
2213    size_t
2214    WriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error);
2215
2216
2217    //------------------------------------------------------------------
2218    /// Actually allocate memory in the process.
2219    ///
2220    /// This function will allocate memory in the process's address
2221    /// space.  This can't rely on the generic function calling mechanism,
2222    /// since that requires this function.
2223    ///
2224    /// @param[in] size
2225    ///     The size of the allocation requested.
2226    ///
2227    /// @return
2228    ///     The address of the allocated buffer in the process, or
2229    ///     LLDB_INVALID_ADDRESS if the allocation failed.
2230    //------------------------------------------------------------------
2231
2232    virtual lldb::addr_t
2233    DoAllocateMemory (size_t size, uint32_t permissions, Error &error) = 0;
2234
2235    //------------------------------------------------------------------
2236    /// The public interface to allocating memory in the process.
2237    ///
2238    /// This function will allocate memory in the process's address
2239    /// space.  This can't rely on the generic function calling mechanism,
2240    /// since that requires this function.
2241    ///
2242    /// @param[in] size
2243    ///     The size of the allocation requested.
2244    ///
2245    /// @param[in] permissions
2246    ///     Or together any of the lldb::Permissions bits.  The permissions on
2247    ///     a given memory allocation can't be changed after allocation.  Note
2248    ///     that a block that isn't set writable can still be written on from lldb,
2249    ///     just not by the process itself.
2250    ///
2251    /// @param[in/out] error
2252    ///     An error object to fill in if things go wrong.
2253    /// @return
2254    ///     The address of the allocated buffer in the process, or
2255    ///     LLDB_INVALID_ADDRESS if the allocation failed.
2256    //------------------------------------------------------------------
2257
2258    lldb::addr_t
2259    AllocateMemory (size_t size, uint32_t permissions, Error &error);
2260
2261    //------------------------------------------------------------------
2262    /// Determines whether executing JIT-compiled code in this process
2263    /// is possible.
2264    ///
2265    /// @return
2266    ///     True if execution of JIT code is possible; false otherwise.
2267    //------------------------------------------------------------------
2268    bool CanJIT ();
2269
2270    //------------------------------------------------------------------
2271    /// Sets whether executing JIT-compiled code in this process
2272    /// is possible.
2273    ///
2274    /// @param[in] can_jit
2275    ///     True if execution of JIT code is possible; false otherwise.
2276    //------------------------------------------------------------------
2277    void SetCanJIT (bool can_jit);
2278
2279    //------------------------------------------------------------------
2280    /// Actually deallocate memory in the process.
2281    ///
2282    /// This function will deallocate memory in the process's address
2283    /// space that was allocated with AllocateMemory.
2284    ///
2285    /// @param[in] ptr
2286    ///     A return value from AllocateMemory, pointing to the memory you
2287    ///     want to deallocate.
2288    ///
2289    /// @return
2290    ///     \btrue if the memory was deallocated, \bfalse otherwise.
2291    //------------------------------------------------------------------
2292
2293    virtual Error
2294    DoDeallocateMemory (lldb::addr_t ptr) = 0;
2295
2296    //------------------------------------------------------------------
2297    /// The public interface to deallocating memory in the process.
2298    ///
2299    /// This function will deallocate memory in the process's address
2300    /// space that was allocated with AllocateMemory.
2301    ///
2302    /// @param[in] ptr
2303    ///     A return value from AllocateMemory, pointing to the memory you
2304    ///     want to deallocate.
2305    ///
2306    /// @return
2307    ///     \btrue if the memory was deallocated, \bfalse otherwise.
2308    //------------------------------------------------------------------
2309
2310    Error
2311    DeallocateMemory (lldb::addr_t ptr);
2312
2313    //------------------------------------------------------------------
2314    /// Get any available STDOUT.
2315    ///
2316    /// If the process was launched without supplying valid file paths
2317    /// for stdin, stdout, and stderr, then the Process class might
2318    /// try to cache the STDOUT for the process if it is able. Events
2319    /// will be queued indicating that there is STDOUT available that
2320    /// can be retrieved using this function.
2321    ///
2322    /// @param[out] buf
2323    ///     A buffer that will receive any STDOUT bytes that are
2324    ///     currently available.
2325    ///
2326    /// @param[out] buf_size
2327    ///     The size in bytes for the buffer \a buf.
2328    ///
2329    /// @return
2330    ///     The number of bytes written into \a buf. If this value is
2331    ///     equal to \a buf_size, another call to this function should
2332    ///     be made to retrieve more STDOUT data.
2333    //------------------------------------------------------------------
2334    virtual size_t
2335    GetSTDOUT (char *buf, size_t buf_size, Error &error)
2336    {
2337        error.SetErrorString("stdout unsupported");
2338        return 0;
2339    }
2340
2341
2342    //------------------------------------------------------------------
2343    /// Get any available STDERR.
2344    ///
2345    /// If the process was launched without supplying valid file paths
2346    /// for stdin, stdout, and stderr, then the Process class might
2347    /// try to cache the STDERR for the process if it is able. Events
2348    /// will be queued indicating that there is STDERR available that
2349    /// can be retrieved using this function.
2350    ///
2351    /// @param[out] buf
2352    ///     A buffer that will receive any STDERR bytes that are
2353    ///     currently available.
2354    ///
2355    /// @param[out] buf_size
2356    ///     The size in bytes for the buffer \a buf.
2357    ///
2358    /// @return
2359    ///     The number of bytes written into \a buf. If this value is
2360    ///     equal to \a buf_size, another call to this function should
2361    ///     be made to retrieve more STDERR data.
2362    //------------------------------------------------------------------
2363    virtual size_t
2364    GetSTDERR (char *buf, size_t buf_size, Error &error)
2365    {
2366        error.SetErrorString("stderr unsupported");
2367        return 0;
2368    }
2369
2370    virtual size_t
2371    PutSTDIN (const char *buf, size_t buf_size, Error &error)
2372    {
2373        error.SetErrorString("stdin unsupported");
2374        return 0;
2375    }
2376
2377    //----------------------------------------------------------------------
2378    // Process Breakpoints
2379    //----------------------------------------------------------------------
2380    size_t
2381    GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site);
2382
2383    virtual Error
2384    EnableBreakpoint (BreakpointSite *bp_site) = 0;
2385
2386    virtual Error
2387    DisableBreakpoint (BreakpointSite *bp_site) = 0;
2388
2389    // This is implemented completely using the lldb::Process API. Subclasses
2390    // don't need to implement this function unless the standard flow of
2391    // read existing opcode, write breakpoint opcode, verify breakpoint opcode
2392    // doesn't work for a specific process plug-in.
2393    virtual Error
2394    EnableSoftwareBreakpoint (BreakpointSite *bp_site);
2395
2396    // This is implemented completely using the lldb::Process API. Subclasses
2397    // don't need to implement this function unless the standard flow of
2398    // restoring original opcode in memory and verifying the restored opcode
2399    // doesn't work for a specific process plug-in.
2400    virtual Error
2401    DisableSoftwareBreakpoint (BreakpointSite *bp_site);
2402
2403    BreakpointSiteList &
2404    GetBreakpointSiteList();
2405
2406    const BreakpointSiteList &
2407    GetBreakpointSiteList() const;
2408
2409    void
2410    DisableAllBreakpointSites ();
2411
2412    Error
2413    ClearBreakpointSiteByID (lldb::user_id_t break_id);
2414
2415    lldb::break_id_t
2416    CreateBreakpointSite (lldb::BreakpointLocationSP &owner,
2417                          bool use_hardware);
2418
2419    Error
2420    DisableBreakpointSiteByID (lldb::user_id_t break_id);
2421
2422    Error
2423    EnableBreakpointSiteByID (lldb::user_id_t break_id);
2424
2425
2426    // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove
2427    // themselves from the owner's list of this breakpoint sites.  This has to
2428    // be a static function because you can't be sure that removing the
2429    // breakpoint from it's containing map won't delete the breakpoint site,
2430    // and doing that in an instance method isn't copasetic.
2431    void
2432    RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id,
2433                                   lldb::user_id_t owner_loc_id,
2434                                   lldb::BreakpointSiteSP &bp_site_sp);
2435
2436    //----------------------------------------------------------------------
2437    // Process Watchpoints (optional)
2438    //----------------------------------------------------------------------
2439    virtual Error
2440    EnableWatchpoint (Watchpoint *wp);
2441
2442    virtual Error
2443    DisableWatchpoint (Watchpoint *wp);
2444
2445    //------------------------------------------------------------------
2446    // Thread Queries
2447    //------------------------------------------------------------------
2448    virtual uint32_t
2449    UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list) = 0;
2450
2451    void
2452    UpdateThreadListIfNeeded ();
2453
2454    ThreadList &
2455    GetThreadList ()
2456    {
2457        return m_thread_list;
2458    }
2459
2460
2461    uint32_t
2462    GetNextThreadIndexID ();
2463
2464    //------------------------------------------------------------------
2465    // Event Handling
2466    //------------------------------------------------------------------
2467    lldb::StateType
2468    GetNextEvent (lldb::EventSP &event_sp);
2469
2470    lldb::StateType
2471    WaitForProcessToStop (const TimeValue *timeout);
2472
2473    lldb::StateType
2474    WaitForStateChangedEvents (const TimeValue *timeout, lldb::EventSP &event_sp);
2475
2476    Event *
2477    PeekAtStateChangedEvents ();
2478
2479
2480    class
2481    ProcessEventHijacker
2482    {
2483    public:
2484        ProcessEventHijacker (Process &process, Listener *listener) :
2485            m_process (process),
2486            m_listener (listener)
2487        {
2488            m_process.HijackProcessEvents (listener);
2489        }
2490        ~ProcessEventHijacker ()
2491        {
2492            m_process.RestoreProcessEvents();
2493        }
2494
2495    private:
2496        Process &m_process;
2497        Listener *m_listener;
2498    };
2499    friend class ProcessEventHijacker;
2500    //------------------------------------------------------------------
2501    /// If you need to ensure that you and only you will hear about some public
2502    /// event, then make a new listener, set to listen to process events, and
2503    /// then call this with that listener.  Then you will have to wait on that
2504    /// listener explicitly for events (rather than using the GetNextEvent & WaitFor*
2505    /// calls above.  Be sure to call RestoreProcessEvents when you are done.
2506    ///
2507    /// @param[in] listener
2508    ///     This is the new listener to whom all process events will be delivered.
2509    ///
2510    /// @return
2511    ///     Returns \b true if the new listener could be installed,
2512    ///     \b false otherwise.
2513    //------------------------------------------------------------------
2514    bool
2515    HijackProcessEvents (Listener *listener);
2516
2517    //------------------------------------------------------------------
2518    /// Restores the process event broadcasting to its normal state.
2519    ///
2520    //------------------------------------------------------------------
2521    void
2522    RestoreProcessEvents ();
2523
2524protected:
2525    //------------------------------------------------------------------
2526    /// This is the part of the event handling that for a process event.
2527    /// It decides what to do with the event and returns true if the
2528    /// event needs to be propagated to the user, and false otherwise.
2529    /// If the event is not propagated, this call will most likely set
2530    /// the target to executing again.
2531    ///
2532    /// @param[in] event_ptr
2533    ///     This is the event we are handling.
2534    ///
2535    /// @return
2536    ///     Returns \b true if the event should be reported to the
2537    ///     user, \b false otherwise.
2538    //------------------------------------------------------------------
2539    bool
2540    ShouldBroadcastEvent (Event *event_ptr);
2541
2542public:
2543    const lldb::ABISP &
2544    GetABI ();
2545
2546    DynamicLoader *
2547    GetDynamicLoader ()
2548    {
2549        return m_dyld_ap.get();
2550    }
2551
2552    OperatingSystem *
2553    GetOperatingSystem ()
2554    {
2555        return m_os_ap.get();
2556    }
2557
2558
2559    virtual LanguageRuntime *
2560    GetLanguageRuntime (lldb::LanguageType language);
2561
2562    virtual CPPLanguageRuntime *
2563    GetCPPLanguageRuntime ();
2564
2565    virtual ObjCLanguageRuntime *
2566    GetObjCLanguageRuntime ();
2567
2568    bool
2569    IsRunning () const;
2570
2571    DynamicCheckerFunctions *GetDynamicCheckers()
2572    {
2573        return m_dynamic_checkers_ap.get();
2574    }
2575
2576    void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
2577    {
2578        m_dynamic_checkers_ap.reset(dynamic_checkers);
2579    }
2580
2581    //------------------------------------------------------------------
2582    /// Call this to set the lldb in the mode where it breaks on new thread
2583    /// creations, and then auto-restarts.  This is useful when you are trying
2584    /// to run only one thread, but either that thread or the kernel is creating
2585    /// new threads in the process.  If you stop when the thread is created, you
2586    /// can immediately suspend it, and keep executing only the one thread you intend.
2587    ///
2588    /// @return
2589    ///     Returns \b true if we were able to start up the notification
2590    ///     \b false otherwise.
2591    //------------------------------------------------------------------
2592    virtual bool
2593    StartNoticingNewThreads()
2594    {
2595        return true;
2596    }
2597
2598    //------------------------------------------------------------------
2599    /// Call this to turn off the stop & notice new threads mode.
2600    ///
2601    /// @return
2602    ///     Returns \b true if we were able to start up the notification
2603    ///     \b false otherwise.
2604    //------------------------------------------------------------------
2605    virtual bool
2606    StopNoticingNewThreads()
2607    {
2608        return true;
2609    }
2610
2611    //------------------------------------------------------------------
2612    // lldb::ExecutionContextScope pure virtual functions
2613    //------------------------------------------------------------------
2614    virtual Target *
2615    CalculateTarget ()
2616    {
2617        return &m_target;
2618    }
2619
2620    virtual Process *
2621    CalculateProcess ()
2622    {
2623        return this;
2624    }
2625
2626    virtual Thread *
2627    CalculateThread ()
2628    {
2629        return NULL;
2630    }
2631
2632    virtual StackFrame *
2633    CalculateStackFrame ()
2634    {
2635        return NULL;
2636    }
2637
2638    virtual void
2639    CalculateExecutionContext (ExecutionContext &exe_ctx);
2640
2641    lldb::ProcessSP
2642    GetSP ();
2643
2644protected:
2645    //------------------------------------------------------------------
2646    // NextEventAction provides a way to register an action on the next
2647    // event that is delivered to this process.  There is currently only
2648    // one next event action allowed in the process at one time.  If a
2649    // new "NextEventAction" is added while one is already present, the
2650    // old action will be discarded (with HandleBeingUnshipped called
2651    // after it is discarded.)
2652    //------------------------------------------------------------------
2653    class NextEventAction
2654    {
2655    public:
2656        typedef enum EventActionResult
2657        {
2658            eEventActionSuccess,
2659            eEventActionRetry,
2660            eEventActionExit
2661        } EventActionResult;
2662
2663        NextEventAction (Process *process) :
2664            m_process(process)
2665        {}
2666        virtual ~NextEventAction() {}
2667
2668        virtual EventActionResult PerformAction (lldb::EventSP &event_sp) = 0;
2669        virtual void HandleBeingUnshipped () {};
2670        virtual EventActionResult HandleBeingInterrupted () = 0;
2671        virtual const char *GetExitString() = 0;
2672    protected:
2673        Process *m_process;
2674    };
2675
2676    void SetNextEventAction (Process::NextEventAction *next_event_action)
2677    {
2678        if (m_next_event_action_ap.get())
2679            m_next_event_action_ap->HandleBeingUnshipped();
2680
2681        m_next_event_action_ap.reset(next_event_action);
2682    }
2683
2684    // This is the completer for Attaching:
2685    class AttachCompletionHandler : public NextEventAction
2686    {
2687    public:
2688        AttachCompletionHandler (Process *process) :
2689            NextEventAction(process)
2690        {}
2691        virtual ~AttachCompletionHandler() {}
2692
2693        virtual EventActionResult PerformAction (lldb::EventSP &event_sp);
2694        virtual EventActionResult HandleBeingInterrupted ();
2695        virtual const char *GetExitString();
2696    private:
2697        std::string m_exit_string;
2698    };
2699
2700    bool
2701    HijackPrivateProcessEvents (Listener *listener);
2702
2703    void
2704    RestorePrivateProcessEvents ();
2705
2706    bool
2707    PrivateStateThreadIsValid () const
2708    {
2709        return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
2710    }
2711
2712    //------------------------------------------------------------------
2713    // Member variables
2714    //------------------------------------------------------------------
2715    Target &                    m_target;               ///< The target that owns this process.
2716    ThreadSafeValue<lldb::StateType>  m_public_state;
2717    ThreadSafeValue<lldb::StateType>  m_private_state; // The actual state of our process
2718    Broadcaster                 m_private_state_broadcaster;  // This broadcaster feeds state changed events into the private state thread's listener.
2719    Broadcaster                 m_private_state_control_broadcaster; // This is the control broadcaster, used to pause, resume & stop the private state thread.
2720    Listener                    m_private_state_listener;     // This is the listener for the private state thread.
2721    Predicate<bool>             m_private_state_control_wait; /// This Predicate is used to signal that a control operation is complete.
2722    lldb::thread_t              m_private_state_thread;  // Thread ID for the thread that watches interal state events
2723    ProcessModID                m_mod_id;              ///< Tracks the state of the process over stops and other alterations.
2724    uint32_t                    m_thread_index_id;      ///< Each thread is created with a 1 based index that won't get re-used.
2725    int                         m_exit_status;          ///< The exit status of the process, or -1 if not set.
2726    std::string                 m_exit_string;          ///< A textual description of why a process exited.
2727    ThreadList                  m_thread_list;          ///< The threads for this process.
2728    std::vector<Notifications>  m_notifications;        ///< The list of notifications that this process can deliver.
2729    std::vector<lldb::addr_t>   m_image_tokens;
2730    Listener                    &m_listener;
2731    BreakpointSiteList          m_breakpoint_site_list; ///< This is the list of breakpoint locations we intend
2732                                                        ///< to insert in the target.
2733    std::auto_ptr<DynamicLoader> m_dyld_ap;
2734    std::auto_ptr<DynamicCheckerFunctions>  m_dynamic_checkers_ap; ///< The functions used by the expression parser to validate data that expressions use.
2735    std::auto_ptr<OperatingSystem>     m_os_ap;
2736    UnixSignals                 m_unix_signals;         /// This is the current signal set for this process.
2737    lldb::ABISP                 m_abi_sp;
2738    lldb::InputReaderSP         m_process_input_reader;
2739    lldb_private::Communication m_stdio_communication;
2740    lldb_private::Mutex         m_stdio_communication_mutex;
2741    std::string                 m_stdout_data;
2742    MemoryCache                 m_memory_cache;
2743    AllocatedMemoryCache        m_allocated_memory_cache;
2744    bool                        m_attached_to_process;   /// Did we launch the process or attach to it?
2745
2746    typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP> LanguageRuntimeCollection;
2747    LanguageRuntimeCollection m_language_runtimes;
2748    std::auto_ptr<NextEventAction> m_next_event_action_ap;
2749
2750    enum {
2751        eCanJITDontKnow= 0,
2752        eCanJITYes,
2753        eCanJITNo
2754    } m_can_jit;
2755
2756    size_t
2757    RemoveBreakpointOpcodesFromBuffer (lldb::addr_t addr, size_t size, uint8_t *buf) const;
2758
2759    void
2760    SynchronouslyNotifyStateChanged (lldb::StateType state);
2761
2762    void
2763    SetPublicState (lldb::StateType new_state);
2764
2765    void
2766    SetPrivateState (lldb::StateType state);
2767
2768    bool
2769    StartPrivateStateThread ();
2770
2771    void
2772    StopPrivateStateThread ();
2773
2774    void
2775    PausePrivateStateThread ();
2776
2777    void
2778    ResumePrivateStateThread ();
2779
2780    static void *
2781    PrivateStateThread (void *arg);
2782
2783    void *
2784    RunPrivateStateThread ();
2785
2786    void
2787    HandlePrivateEvent (lldb::EventSP &event_sp);
2788
2789    lldb::StateType
2790    WaitForProcessStopPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
2791
2792    // This waits for both the state change broadcaster, and the control broadcaster.
2793    // If control_only, it only waits for the control broadcaster.
2794
2795    bool
2796    WaitForEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp, bool control_only);
2797
2798    lldb::StateType
2799    WaitForStateChangedEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
2800
2801    lldb::StateType
2802    WaitForState (const TimeValue *timeout,
2803                  const lldb::StateType *match_states,
2804                  const uint32_t num_match_states);
2805
2806    size_t
2807    WriteMemoryPrivate (lldb::addr_t addr, const void *buf, size_t size, Error &error);
2808
2809    void
2810    AppendSTDOUT (const char *s, size_t len);
2811
2812    static void
2813    STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len);
2814
2815    void
2816    PushProcessInputReader ();
2817
2818    void
2819    PopProcessInputReader ();
2820
2821    void
2822    ResetProcessInputReader ();
2823
2824    void
2825    SetUpProcessInputReader (int file_descriptor);
2826
2827    static size_t
2828    ProcessInputReaderCallback (void *baton,
2829                                InputReader &reader,
2830                                lldb::InputReaderAction notification,
2831                                const char *bytes,
2832                                size_t bytes_len);
2833
2834
2835private:
2836    //------------------------------------------------------------------
2837    // For Process only
2838    //------------------------------------------------------------------
2839    void ControlPrivateStateThread (uint32_t signal);
2840
2841    DISALLOW_COPY_AND_ASSIGN (Process);
2842
2843};
2844
2845} // namespace lldb_private
2846
2847#endif  // liblldb_Process_h_
2848