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