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