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