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