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