Process.h revision 6b1763b5ab8f182029807293d74a66e1e1c6bafd
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    /// Flush all data in the process.
2274    ///
2275    /// Flush the memory caches, all threads, and any other cached data
2276    /// in the process.
2277    ///
2278    /// This function can be called after a world changing event like
2279    /// adding a new symbol file, or after the process makes a large
2280    /// context switch (from boot ROM to booted into an OS).
2281    //------------------------------------------------------------------
2282    void
2283    Flush ();
2284
2285    //------------------------------------------------------------------
2286    /// Get accessor for the current process state.
2287    ///
2288    /// @return
2289    ///     The current state of the process.
2290    ///
2291    /// @see lldb::StateType
2292    //------------------------------------------------------------------
2293    lldb::StateType
2294    GetState ();
2295
2296    ExecutionResults
2297    RunThreadPlan (ExecutionContext &exe_ctx,
2298                    lldb::ThreadPlanSP &thread_plan_sp,
2299                    bool stop_others,
2300                    bool try_all_threads,
2301                    bool discard_on_error,
2302                    uint32_t single_thread_timeout_usec,
2303                    Stream &errors);
2304
2305    static const char *
2306    ExecutionResultAsCString (ExecutionResults result);
2307
2308    void
2309    GetStatus (Stream &ostrm);
2310
2311    size_t
2312    GetThreadStatus (Stream &ostrm,
2313                     bool only_threads_with_stop_reason,
2314                     uint32_t start_frame,
2315                     uint32_t num_frames,
2316                     uint32_t num_frames_with_source);
2317
2318protected:
2319
2320    void
2321    SetState (lldb::EventSP &event_sp);
2322
2323    lldb::StateType
2324    GetPrivateState ();
2325
2326    //------------------------------------------------------------------
2327    /// The "private" side of resuming a process.  This doesn't alter the
2328    /// state of m_run_lock, but just causes the process to resume.
2329    ///
2330    /// @return
2331    ///     An Error object describing the success or failure of the resume.
2332    //------------------------------------------------------------------
2333    Error
2334    PrivateResume ();
2335
2336    //------------------------------------------------------------------
2337    // Called internally
2338    //------------------------------------------------------------------
2339    void
2340    CompleteAttach ();
2341
2342public:
2343    //------------------------------------------------------------------
2344    /// Get the exit status for a process.
2345    ///
2346    /// @return
2347    ///     The process's return code, or -1 if the current process
2348    ///     state is not eStateExited.
2349    //------------------------------------------------------------------
2350    int
2351    GetExitStatus ();
2352
2353    //------------------------------------------------------------------
2354    /// Get a textual description of what the process exited.
2355    ///
2356    /// @return
2357    ///     The textual description of why the process exited, or NULL
2358    ///     if there is no description available.
2359    //------------------------------------------------------------------
2360    const char *
2361    GetExitDescription ();
2362
2363
2364    virtual void
2365    DidExit ()
2366    {
2367    }
2368
2369    //------------------------------------------------------------------
2370    /// Get the Modification ID of the process.
2371    ///
2372    /// @return
2373    ///     The modification ID of the process.
2374    //------------------------------------------------------------------
2375    ProcessModID
2376    GetModID () const
2377    {
2378        return m_mod_id;
2379    }
2380
2381    const ProcessModID &
2382    GetModIDRef () const
2383    {
2384        return m_mod_id;
2385    }
2386
2387    uint32_t
2388    GetStopID () const
2389    {
2390        return m_mod_id.GetStopID();
2391    }
2392
2393    uint32_t
2394    GetResumeID () const
2395    {
2396        return m_mod_id.GetResumeID();
2397    }
2398
2399    uint32_t
2400    GetLastUserExpressionResumeID () const
2401    {
2402        return m_mod_id.GetLastUserExpressionResumeID();
2403    }
2404
2405    //------------------------------------------------------------------
2406    /// Set accessor for the process exit status (return code).
2407    ///
2408    /// Sometimes a child exits and the exit can be detected by global
2409    /// functions (signal handler for SIGCHLD for example). This
2410    /// accessor allows the exit status to be set from an external
2411    /// source.
2412    ///
2413    /// Setting this will cause a eStateExited event to be posted to
2414    /// the process event queue.
2415    ///
2416    /// @param[in] exit_status
2417    ///     The value for the process's return code.
2418    ///
2419    /// @see lldb::StateType
2420    //------------------------------------------------------------------
2421    virtual bool
2422    SetExitStatus (int exit_status, const char *cstr);
2423
2424    //------------------------------------------------------------------
2425    /// Check if a process is still alive.
2426    ///
2427    /// @return
2428    ///     Returns \b true if the process is still valid, \b false
2429    ///     otherwise.
2430    //------------------------------------------------------------------
2431    virtual bool
2432    IsAlive () = 0;
2433
2434    //------------------------------------------------------------------
2435    /// Actually do the reading of memory from a process.
2436    ///
2437    /// Subclasses must override this function and can return fewer
2438    /// bytes than requested when memory requests are too large. This
2439    /// class will break up the memory requests and keep advancing the
2440    /// arguments along as needed.
2441    ///
2442    /// @param[in] vm_addr
2443    ///     A virtual load address that indicates where to start reading
2444    ///     memory from.
2445    ///
2446    /// @param[in] size
2447    ///     The number of bytes to read.
2448    ///
2449    /// @param[out] buf
2450    ///     A byte buffer that is at least \a size bytes long that
2451    ///     will receive the memory bytes.
2452    ///
2453    /// @return
2454    ///     The number of bytes that were actually read into \a buf.
2455    //------------------------------------------------------------------
2456    virtual size_t
2457    DoReadMemory (lldb::addr_t vm_addr,
2458                  void *buf,
2459                  size_t size,
2460                  Error &error) = 0;
2461
2462    //------------------------------------------------------------------
2463    /// Read of memory from a process.
2464    ///
2465    /// This function will read memory from the current process's
2466    /// address space and remove any traps that may have been inserted
2467    /// into the memory.
2468    ///
2469    /// This function is not meant to be overridden by Process
2470    /// subclasses, the subclasses should implement
2471    /// Process::DoReadMemory (lldb::addr_t, size_t, void *).
2472    ///
2473    /// @param[in] vm_addr
2474    ///     A virtual load address that indicates where to start reading
2475    ///     memory from.
2476    ///
2477    /// @param[out] buf
2478    ///     A byte buffer that is at least \a size bytes long that
2479    ///     will receive the memory bytes.
2480    ///
2481    /// @param[in] size
2482    ///     The number of bytes to read.
2483    ///
2484    /// @return
2485    ///     The number of bytes that were actually read into \a buf. If
2486    ///     the returned number is greater than zero, yet less than \a
2487    ///     size, then this function will get called again with \a
2488    ///     vm_addr, \a buf, and \a size updated appropriately. Zero is
2489    ///     returned to indicate an error.
2490    //------------------------------------------------------------------
2491    virtual size_t
2492    ReadMemory (lldb::addr_t vm_addr,
2493                void *buf,
2494                size_t size,
2495                Error &error);
2496
2497    //------------------------------------------------------------------
2498    /// Read a NULL terminated C string from memory
2499    ///
2500    /// This function will read a cache page at a time until the NULL
2501    /// C stirng terminator is found. It will stop reading if the NULL
2502    /// termination byte isn't found before reading \a cstr_max_len
2503    /// bytes, and the results are always guaranteed to be NULL
2504    /// terminated (at most cstr_max_len - 1 bytes will be read).
2505    //------------------------------------------------------------------
2506    size_t
2507    ReadCStringFromMemory (lldb::addr_t vm_addr,
2508                           char *cstr,
2509                           size_t cstr_max_len,
2510                           Error &error);
2511
2512    size_t
2513    ReadCStringFromMemory (lldb::addr_t vm_addr,
2514                           std::string &out_str,
2515                           Error &error);
2516
2517    size_t
2518    ReadMemoryFromInferior (lldb::addr_t vm_addr,
2519                            void *buf,
2520                            size_t size,
2521                            Error &error);
2522
2523    //------------------------------------------------------------------
2524    /// Reads an unsigned integer of the specified byte size from
2525    /// process memory.
2526    ///
2527    /// @param[in] load_addr
2528    ///     A load address of the integer to read.
2529    ///
2530    /// @param[in] byte_size
2531    ///     The size in byte of the integer to read.
2532    ///
2533    /// @param[in] fail_value
2534    ///     The value to return if we fail to read an integer.
2535    ///
2536    /// @param[out] error
2537    ///     An error that indicates the success or failure of this
2538    ///     operation. If error indicates success (error.Success()),
2539    ///     then the value returned can be trusted, otherwise zero
2540    ///     will be returned.
2541    ///
2542    /// @return
2543    ///     The unsigned integer that was read from the process memory
2544    ///     space. If the integer was smaller than a uint64_t, any
2545    ///     unused upper bytes will be zero filled. If the process
2546    ///     byte order differs from the host byte order, the integer
2547    ///     value will be appropriately byte swapped into host byte
2548    ///     order.
2549    //------------------------------------------------------------------
2550    uint64_t
2551    ReadUnsignedIntegerFromMemory (lldb::addr_t load_addr,
2552                                   size_t byte_size,
2553                                   uint64_t fail_value,
2554                                   Error &error);
2555
2556    lldb::addr_t
2557    ReadPointerFromMemory (lldb::addr_t vm_addr,
2558                           Error &error);
2559
2560    bool
2561    WritePointerToMemory (lldb::addr_t vm_addr,
2562                          lldb::addr_t ptr_value,
2563                          Error &error);
2564
2565    //------------------------------------------------------------------
2566    /// Actually do the writing of memory to a process.
2567    ///
2568    /// @param[in] vm_addr
2569    ///     A virtual load address that indicates where to start writing
2570    ///     memory to.
2571    ///
2572    /// @param[in] buf
2573    ///     A byte buffer that is at least \a size bytes long that
2574    ///     contains the data to write.
2575    ///
2576    /// @param[in] size
2577    ///     The number of bytes to write.
2578    ///
2579    /// @param[out] error
2580    ///     An error value in case the memory write fails.
2581    ///
2582    /// @return
2583    ///     The number of bytes that were actually written.
2584    //------------------------------------------------------------------
2585    virtual size_t
2586    DoWriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error)
2587    {
2588        error.SetErrorStringWithFormat("error: %s does not support writing to processes", GetShortPluginName());
2589        return 0;
2590    }
2591
2592
2593    //------------------------------------------------------------------
2594    /// Write all or part of a scalar value to memory.
2595    ///
2596    /// The value contained in \a scalar will be swapped to match the
2597    /// byte order of the process that is being debugged. If \a size is
2598    /// less than the size of scalar, the least significate \a size bytes
2599    /// from scalar will be written. If \a size is larger than the byte
2600    /// size of scalar, then the extra space will be padded with zeros
2601    /// and the scalar value will be placed in the least significant
2602    /// bytes in memory.
2603    ///
2604    /// @param[in] vm_addr
2605    ///     A virtual load address that indicates where to start writing
2606    ///     memory to.
2607    ///
2608    /// @param[in] scalar
2609    ///     The scalar to write to the debugged process.
2610    ///
2611    /// @param[in] size
2612    ///     This value can be smaller or larger than the scalar value
2613    ///     itself. If \a size is smaller than the size of \a scalar,
2614    ///     the least significant bytes in \a scalar will be used. If
2615    ///     \a size is larger than the byte size of \a scalar, then
2616    ///     the extra space will be padded with zeros. If \a size is
2617    ///     set to UINT32_MAX, then the size of \a scalar will be used.
2618    ///
2619    /// @param[out] error
2620    ///     An error value in case the memory write fails.
2621    ///
2622    /// @return
2623    ///     The number of bytes that were actually written.
2624    //------------------------------------------------------------------
2625    size_t
2626    WriteScalarToMemory (lldb::addr_t vm_addr,
2627                         const Scalar &scalar,
2628                         uint32_t size,
2629                         Error &error);
2630
2631    size_t
2632    ReadScalarIntegerFromMemory (lldb::addr_t addr,
2633                                 uint32_t byte_size,
2634                                 bool is_signed,
2635                                 Scalar &scalar,
2636                                 Error &error);
2637
2638    //------------------------------------------------------------------
2639    /// Write memory to a process.
2640    ///
2641    /// This function will write memory to the current process's
2642    /// address space and maintain any traps that might be present due
2643    /// to software breakpoints.
2644    ///
2645    /// This function is not meant to be overridden by Process
2646    /// subclasses, the subclasses should implement
2647    /// Process::DoWriteMemory (lldb::addr_t, size_t, void *).
2648    ///
2649    /// @param[in] vm_addr
2650    ///     A virtual load address that indicates where to start writing
2651    ///     memory to.
2652    ///
2653    /// @param[in] buf
2654    ///     A byte buffer that is at least \a size bytes long that
2655    ///     contains the data to write.
2656    ///
2657    /// @param[in] size
2658    ///     The number of bytes to write.
2659    ///
2660    /// @return
2661    ///     The number of bytes that were actually written.
2662    //------------------------------------------------------------------
2663    size_t
2664    WriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error);
2665
2666
2667    //------------------------------------------------------------------
2668    /// Actually allocate memory in the process.
2669    ///
2670    /// This function will allocate memory in the process's address
2671    /// space.  This can't rely on the generic function calling mechanism,
2672    /// since that requires this function.
2673    ///
2674    /// @param[in] size
2675    ///     The size of the allocation requested.
2676    ///
2677    /// @return
2678    ///     The address of the allocated buffer in the process, or
2679    ///     LLDB_INVALID_ADDRESS if the allocation failed.
2680    //------------------------------------------------------------------
2681
2682    virtual lldb::addr_t
2683    DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2684    {
2685        error.SetErrorStringWithFormat("error: %s does not support allocating in the debug process", GetShortPluginName());
2686        return LLDB_INVALID_ADDRESS;
2687    }
2688
2689
2690    //------------------------------------------------------------------
2691    /// The public interface to allocating memory in the process.
2692    ///
2693    /// This function will allocate memory in the process's address
2694    /// space.  This can't rely on the generic function calling mechanism,
2695    /// since that requires this function.
2696    ///
2697    /// @param[in] size
2698    ///     The size of the allocation requested.
2699    ///
2700    /// @param[in] permissions
2701    ///     Or together any of the lldb::Permissions bits.  The permissions on
2702    ///     a given memory allocation can't be changed after allocation.  Note
2703    ///     that a block that isn't set writable can still be written on from lldb,
2704    ///     just not by the process itself.
2705    ///
2706    /// @param[in/out] error
2707    ///     An error object to fill in if things go wrong.
2708    /// @return
2709    ///     The address of the allocated buffer in the process, or
2710    ///     LLDB_INVALID_ADDRESS if the allocation failed.
2711    //------------------------------------------------------------------
2712
2713    lldb::addr_t
2714    AllocateMemory (size_t size, uint32_t permissions, Error &error);
2715
2716    virtual Error
2717    GetMemoryRegionInfo (lldb::addr_t load_addr,
2718                        MemoryRegionInfo &range_info)
2719    {
2720        Error error;
2721        error.SetErrorString ("Process::GetMemoryRegionInfo() not supported");
2722        return error;
2723    }
2724
2725    lldb::ModuleSP
2726    ReadModuleFromMemory (const FileSpec& file_spec,
2727                          lldb::addr_t header_addr,
2728                          bool add_image_to_target,
2729                          bool load_sections_in_target);
2730
2731    //------------------------------------------------------------------
2732    /// Attempt to get the attributes for a region of memory in the process.
2733    ///
2734    /// It may be possible for the remote debug server to inspect attributes
2735    /// for a region of memory in the process, such as whether there is a
2736    /// valid page of memory at a given address or whether that page is
2737    /// readable/writable/executable by the process.
2738    ///
2739    /// @param[in] load_addr
2740    ///     The address of interest in the process.
2741    ///
2742    /// @param[out] permissions
2743    ///     If this call returns successfully, this bitmask will have
2744    ///     its Permissions bits set to indicate whether the region is
2745    ///     readable/writable/executable.  If this call fails, the
2746    ///     bitmask values are undefined.
2747    ///
2748    /// @return
2749    ///     Returns true if it was able to determine the attributes of the
2750    ///     memory region.  False if not.
2751    //------------------------------------------------------------------
2752
2753    virtual bool
2754    GetLoadAddressPermissions (lldb::addr_t load_addr, uint32_t &permissions)
2755    {
2756        MemoryRegionInfo range_info;
2757        permissions = 0;
2758        Error error (GetMemoryRegionInfo (load_addr, range_info));
2759        if (!error.Success())
2760            return false;
2761        if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow
2762            || range_info.GetWritable() == MemoryRegionInfo::eDontKnow
2763            || range_info.GetExecutable() == MemoryRegionInfo::eDontKnow)
2764        {
2765            return false;
2766        }
2767
2768        if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2769            permissions |= lldb::ePermissionsReadable;
2770
2771        if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2772            permissions |= lldb::ePermissionsWritable;
2773
2774        if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2775            permissions |= lldb::ePermissionsExecutable;
2776
2777        return true;
2778    }
2779
2780    //------------------------------------------------------------------
2781    /// Determines whether executing JIT-compiled code in this process
2782    /// is possible.
2783    ///
2784    /// @return
2785    ///     True if execution of JIT code is possible; false otherwise.
2786    //------------------------------------------------------------------
2787    bool CanJIT ();
2788
2789    //------------------------------------------------------------------
2790    /// Sets whether executing JIT-compiled code in this process
2791    /// is possible.
2792    ///
2793    /// @param[in] can_jit
2794    ///     True if execution of JIT code is possible; false otherwise.
2795    //------------------------------------------------------------------
2796    void SetCanJIT (bool can_jit);
2797
2798    //------------------------------------------------------------------
2799    /// Actually deallocate memory in the process.
2800    ///
2801    /// This function will deallocate memory in the process's address
2802    /// space that was allocated with AllocateMemory.
2803    ///
2804    /// @param[in] ptr
2805    ///     A return value from AllocateMemory, pointing to the memory you
2806    ///     want to deallocate.
2807    ///
2808    /// @return
2809    ///     \btrue if the memory was deallocated, \bfalse otherwise.
2810    //------------------------------------------------------------------
2811
2812    virtual Error
2813    DoDeallocateMemory (lldb::addr_t ptr)
2814    {
2815        Error error;
2816        error.SetErrorStringWithFormat("error: %s does not support deallocating in the debug process", GetShortPluginName());
2817        return error;
2818    }
2819
2820
2821    //------------------------------------------------------------------
2822    /// The public interface to deallocating memory in the process.
2823    ///
2824    /// This function will deallocate memory in the process's address
2825    /// space that was allocated with AllocateMemory.
2826    ///
2827    /// @param[in] ptr
2828    ///     A return value from AllocateMemory, pointing to the memory you
2829    ///     want to deallocate.
2830    ///
2831    /// @return
2832    ///     \btrue if the memory was deallocated, \bfalse otherwise.
2833    //------------------------------------------------------------------
2834
2835    Error
2836    DeallocateMemory (lldb::addr_t ptr);
2837
2838    //------------------------------------------------------------------
2839    /// Get any available STDOUT.
2840    ///
2841    /// If the process was launched without supplying valid file paths
2842    /// for stdin, stdout, and stderr, then the Process class might
2843    /// try to cache the STDOUT for the process if it is able. Events
2844    /// will be queued indicating that there is STDOUT available that
2845    /// can be retrieved using this function.
2846    ///
2847    /// @param[out] buf
2848    ///     A buffer that will receive any STDOUT bytes that are
2849    ///     currently available.
2850    ///
2851    /// @param[out] buf_size
2852    ///     The size in bytes for the buffer \a buf.
2853    ///
2854    /// @return
2855    ///     The number of bytes written into \a buf. If this value is
2856    ///     equal to \a buf_size, another call to this function should
2857    ///     be made to retrieve more STDOUT data.
2858    //------------------------------------------------------------------
2859    virtual size_t
2860    GetSTDOUT (char *buf, size_t buf_size, Error &error);
2861
2862    //------------------------------------------------------------------
2863    /// Get any available STDERR.
2864    ///
2865    /// If the process was launched without supplying valid file paths
2866    /// for stdin, stdout, and stderr, then the Process class might
2867    /// try to cache the STDERR for the process if it is able. Events
2868    /// will be queued indicating that there is STDERR available that
2869    /// can be retrieved using this function.
2870    ///
2871    /// @param[out] buf
2872    ///     A buffer that will receive any STDERR bytes that are
2873    ///     currently available.
2874    ///
2875    /// @param[out] buf_size
2876    ///     The size in bytes for the buffer \a buf.
2877    ///
2878    /// @return
2879    ///     The number of bytes written into \a buf. If this value is
2880    ///     equal to \a buf_size, another call to this function should
2881    ///     be made to retrieve more STDERR data.
2882    //------------------------------------------------------------------
2883    virtual size_t
2884    GetSTDERR (char *buf, size_t buf_size, Error &error);
2885
2886    virtual size_t
2887    PutSTDIN (const char *buf, size_t buf_size, Error &error)
2888    {
2889        error.SetErrorString("stdin unsupported");
2890        return 0;
2891    }
2892
2893    //----------------------------------------------------------------------
2894    // Process Breakpoints
2895    //----------------------------------------------------------------------
2896    size_t
2897    GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site);
2898
2899    virtual Error
2900    EnableBreakpoint (BreakpointSite *bp_site)
2901    {
2902        Error error;
2903        error.SetErrorStringWithFormat("error: %s does not support enabling breakpoints", GetShortPluginName());
2904        return error;
2905    }
2906
2907
2908    virtual Error
2909    DisableBreakpoint (BreakpointSite *bp_site)
2910    {
2911        Error error;
2912        error.SetErrorStringWithFormat("error: %s does not support disabling breakpoints", GetShortPluginName());
2913        return error;
2914    }
2915
2916
2917    // This is implemented completely using the lldb::Process API. Subclasses
2918    // don't need to implement this function unless the standard flow of
2919    // read existing opcode, write breakpoint opcode, verify breakpoint opcode
2920    // doesn't work for a specific process plug-in.
2921    virtual Error
2922    EnableSoftwareBreakpoint (BreakpointSite *bp_site);
2923
2924    // This is implemented completely using the lldb::Process API. Subclasses
2925    // don't need to implement this function unless the standard flow of
2926    // restoring original opcode in memory and verifying the restored opcode
2927    // doesn't work for a specific process plug-in.
2928    virtual Error
2929    DisableSoftwareBreakpoint (BreakpointSite *bp_site);
2930
2931    BreakpointSiteList &
2932    GetBreakpointSiteList();
2933
2934    const BreakpointSiteList &
2935    GetBreakpointSiteList() const;
2936
2937    void
2938    DisableAllBreakpointSites ();
2939
2940    Error
2941    ClearBreakpointSiteByID (lldb::user_id_t break_id);
2942
2943    lldb::break_id_t
2944    CreateBreakpointSite (const lldb::BreakpointLocationSP &owner,
2945                          bool use_hardware);
2946
2947    Error
2948    DisableBreakpointSiteByID (lldb::user_id_t break_id);
2949
2950    Error
2951    EnableBreakpointSiteByID (lldb::user_id_t break_id);
2952
2953
2954    // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove
2955    // themselves from the owner's list of this breakpoint sites.  This has to
2956    // be a static function because you can't be sure that removing the
2957    // breakpoint from it's containing map won't delete the breakpoint site,
2958    // and doing that in an instance method isn't copasetic.
2959    void
2960    RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id,
2961                                   lldb::user_id_t owner_loc_id,
2962                                   lldb::BreakpointSiteSP &bp_site_sp);
2963
2964    //----------------------------------------------------------------------
2965    // Process Watchpoints (optional)
2966    //----------------------------------------------------------------------
2967    virtual Error
2968    EnableWatchpoint (Watchpoint *wp);
2969
2970    virtual Error
2971    DisableWatchpoint (Watchpoint *wp);
2972
2973    //------------------------------------------------------------------
2974    // Thread Queries
2975    //------------------------------------------------------------------
2976    virtual bool
2977    UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list) = 0;
2978
2979    void
2980    UpdateThreadListIfNeeded ();
2981
2982    ThreadList &
2983    GetThreadList ()
2984    {
2985        return m_thread_list;
2986    }
2987
2988
2989    uint32_t
2990    GetNextThreadIndexID ();
2991
2992    //------------------------------------------------------------------
2993    // Event Handling
2994    //------------------------------------------------------------------
2995    lldb::StateType
2996    GetNextEvent (lldb::EventSP &event_sp);
2997
2998    lldb::StateType
2999    WaitForProcessToStop (const TimeValue *timeout);
3000
3001    lldb::StateType
3002    WaitForStateChangedEvents (const TimeValue *timeout, lldb::EventSP &event_sp);
3003
3004    Event *
3005    PeekAtStateChangedEvents ();
3006
3007
3008    class
3009    ProcessEventHijacker
3010    {
3011    public:
3012        ProcessEventHijacker (Process &process, Listener *listener) :
3013            m_process (process),
3014            m_listener (listener)
3015        {
3016            m_process.HijackProcessEvents (listener);
3017        }
3018        ~ProcessEventHijacker ()
3019        {
3020            m_process.RestoreProcessEvents();
3021        }
3022
3023    private:
3024        Process &m_process;
3025        Listener *m_listener;
3026    };
3027    friend class ProcessEventHijacker;
3028    //------------------------------------------------------------------
3029    /// If you need to ensure that you and only you will hear about some public
3030    /// event, then make a new listener, set to listen to process events, and
3031    /// then call this with that listener.  Then you will have to wait on that
3032    /// listener explicitly for events (rather than using the GetNextEvent & WaitFor*
3033    /// calls above.  Be sure to call RestoreProcessEvents when you are done.
3034    ///
3035    /// @param[in] listener
3036    ///     This is the new listener to whom all process events will be delivered.
3037    ///
3038    /// @return
3039    ///     Returns \b true if the new listener could be installed,
3040    ///     \b false otherwise.
3041    //------------------------------------------------------------------
3042    bool
3043    HijackProcessEvents (Listener *listener);
3044
3045    //------------------------------------------------------------------
3046    /// Restores the process event broadcasting to its normal state.
3047    ///
3048    //------------------------------------------------------------------
3049    void
3050    RestoreProcessEvents ();
3051
3052protected:
3053    //------------------------------------------------------------------
3054    /// This is the part of the event handling that for a process event.
3055    /// It decides what to do with the event and returns true if the
3056    /// event needs to be propagated to the user, and false otherwise.
3057    /// If the event is not propagated, this call will most likely set
3058    /// the target to executing again.
3059    ///
3060    /// @param[in] event_ptr
3061    ///     This is the event we are handling.
3062    ///
3063    /// @return
3064    ///     Returns \b true if the event should be reported to the
3065    ///     user, \b false otherwise.
3066    //------------------------------------------------------------------
3067    bool
3068    ShouldBroadcastEvent (Event *event_ptr);
3069
3070public:
3071    const lldb::ABISP &
3072    GetABI ();
3073
3074    OperatingSystem *
3075    GetOperatingSystem ()
3076    {
3077        return m_os_ap.get();
3078    }
3079
3080
3081    virtual LanguageRuntime *
3082    GetLanguageRuntime (lldb::LanguageType language, bool retry_if_null = true);
3083
3084    virtual CPPLanguageRuntime *
3085    GetCPPLanguageRuntime (bool retry_if_null = true);
3086
3087    virtual ObjCLanguageRuntime *
3088    GetObjCLanguageRuntime (bool retry_if_null = true);
3089
3090    bool
3091    IsPossibleDynamicValue (ValueObject& in_value);
3092
3093    bool
3094    IsRunning () const;
3095
3096    DynamicCheckerFunctions *GetDynamicCheckers()
3097    {
3098        return m_dynamic_checkers_ap.get();
3099    }
3100
3101    void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
3102    {
3103        m_dynamic_checkers_ap.reset(dynamic_checkers);
3104    }
3105
3106    //------------------------------------------------------------------
3107    /// Call this to set the lldb in the mode where it breaks on new thread
3108    /// creations, and then auto-restarts.  This is useful when you are trying
3109    /// to run only one thread, but either that thread or the kernel is creating
3110    /// new threads in the process.  If you stop when the thread is created, you
3111    /// can immediately suspend it, and keep executing only the one thread you intend.
3112    ///
3113    /// @return
3114    ///     Returns \b true if we were able to start up the notification
3115    ///     \b false otherwise.
3116    //------------------------------------------------------------------
3117    virtual bool
3118    StartNoticingNewThreads()
3119    {
3120        return true;
3121    }
3122
3123    //------------------------------------------------------------------
3124    /// Call this to turn off the stop & notice new threads mode.
3125    ///
3126    /// @return
3127    ///     Returns \b true if we were able to start up the notification
3128    ///     \b false otherwise.
3129    //------------------------------------------------------------------
3130    virtual bool
3131    StopNoticingNewThreads()
3132    {
3133        return true;
3134    }
3135
3136    void
3137    SetRunningUserExpression (bool on);
3138
3139    //------------------------------------------------------------------
3140    // lldb::ExecutionContextScope pure virtual functions
3141    //------------------------------------------------------------------
3142    virtual lldb::TargetSP
3143    CalculateTarget ();
3144
3145    virtual lldb::ProcessSP
3146    CalculateProcess ()
3147    {
3148        return shared_from_this();
3149    }
3150
3151    virtual lldb::ThreadSP
3152    CalculateThread ()
3153    {
3154        return lldb::ThreadSP();
3155    }
3156
3157    virtual lldb::StackFrameSP
3158    CalculateStackFrame ()
3159    {
3160        return lldb::StackFrameSP();
3161    }
3162
3163    virtual void
3164    CalculateExecutionContext (ExecutionContext &exe_ctx);
3165
3166    void
3167    SetSTDIOFileDescriptor (int file_descriptor);
3168
3169    //------------------------------------------------------------------
3170    // Add a permanent region of memory that should never be read or
3171    // written to. This can be used to ensure that memory reads or writes
3172    // to certain areas of memory never end up being sent to the
3173    // DoReadMemory or DoWriteMemory functions which can improve
3174    // performance.
3175    //------------------------------------------------------------------
3176    void
3177    AddInvalidMemoryRegion (const LoadRange &region);
3178
3179    //------------------------------------------------------------------
3180    // Remove a permanent region of memory that should never be read or
3181    // written to that was previously added with AddInvalidMemoryRegion.
3182    //------------------------------------------------------------------
3183    bool
3184    RemoveInvalidMemoryRange (const LoadRange &region);
3185
3186    //------------------------------------------------------------------
3187    // If the setup code of a thread plan needs to do work that might involve
3188    // calling a function in the target, it should not do that work directly
3189    // in one of the thread plan functions (DidPush/WillResume) because
3190    // such work needs to be handled carefully.  Instead, put that work in
3191    // a PreResumeAction callback, and register it with the process.  It will
3192    // get done before the actual "DoResume" gets called.
3193    //------------------------------------------------------------------
3194
3195    typedef bool (PreResumeActionCallback)(void *);
3196
3197    void
3198    AddPreResumeAction (PreResumeActionCallback callback, void *baton);
3199
3200    bool
3201    RunPreResumeActions ();
3202
3203    void
3204    ClearPreResumeActions ();
3205
3206    ReadWriteLock &
3207    GetRunLock ()
3208    {
3209        return m_run_lock;
3210    }
3211
3212protected:
3213    //------------------------------------------------------------------
3214    // NextEventAction provides a way to register an action on the next
3215    // event that is delivered to this process.  There is currently only
3216    // one next event action allowed in the process at one time.  If a
3217    // new "NextEventAction" is added while one is already present, the
3218    // old action will be discarded (with HandleBeingUnshipped called
3219    // after it is discarded.)
3220    //------------------------------------------------------------------
3221    class NextEventAction
3222    {
3223    public:
3224        typedef enum EventActionResult
3225        {
3226            eEventActionSuccess,
3227            eEventActionRetry,
3228            eEventActionExit
3229        } EventActionResult;
3230
3231        NextEventAction (Process *process) :
3232            m_process(process)
3233        {
3234        }
3235
3236        virtual
3237        ~NextEventAction()
3238        {
3239        }
3240
3241        virtual EventActionResult PerformAction (lldb::EventSP &event_sp) = 0;
3242        virtual void HandleBeingUnshipped () {};
3243        virtual EventActionResult HandleBeingInterrupted () = 0;
3244        virtual const char *GetExitString() = 0;
3245    protected:
3246        Process *m_process;
3247    };
3248
3249    void SetNextEventAction (Process::NextEventAction *next_event_action)
3250    {
3251        if (m_next_event_action_ap.get())
3252            m_next_event_action_ap->HandleBeingUnshipped();
3253
3254        m_next_event_action_ap.reset(next_event_action);
3255    }
3256
3257    // This is the completer for Attaching:
3258    class AttachCompletionHandler : public NextEventAction
3259    {
3260    public:
3261        AttachCompletionHandler (Process *process, uint32_t exec_count) :
3262            NextEventAction (process),
3263            m_exec_count (exec_count)
3264        {
3265        }
3266
3267        virtual
3268        ~AttachCompletionHandler()
3269        {
3270        }
3271
3272        virtual EventActionResult PerformAction (lldb::EventSP &event_sp);
3273        virtual EventActionResult HandleBeingInterrupted ();
3274        virtual const char *GetExitString();
3275    private:
3276        uint32_t m_exec_count;
3277        std::string m_exit_string;
3278    };
3279
3280    bool
3281    HijackPrivateProcessEvents (Listener *listener);
3282
3283    void
3284    RestorePrivateProcessEvents ();
3285
3286    bool
3287    PrivateStateThreadIsValid () const
3288    {
3289        return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3290    }
3291
3292    //------------------------------------------------------------------
3293    // Type definitions
3294    //------------------------------------------------------------------
3295    typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP> LanguageRuntimeCollection;
3296
3297    struct PreResumeCallbackAndBaton
3298    {
3299        bool (*callback) (void *);
3300        void *baton;
3301        PreResumeCallbackAndBaton (PreResumeActionCallback in_callback, void *in_baton) :
3302            callback (in_callback),
3303            baton (in_baton)
3304        {
3305        }
3306    };
3307
3308    //------------------------------------------------------------------
3309    // Member variables
3310    //------------------------------------------------------------------
3311    Target &                    m_target;               ///< The target that owns this process.
3312    ThreadSafeValue<lldb::StateType>  m_public_state;
3313    ThreadSafeValue<lldb::StateType>  m_private_state; // The actual state of our process
3314    Broadcaster                 m_private_state_broadcaster;  // This broadcaster feeds state changed events into the private state thread's listener.
3315    Broadcaster                 m_private_state_control_broadcaster; // This is the control broadcaster, used to pause, resume & stop the private state thread.
3316    Listener                    m_private_state_listener;     // This is the listener for the private state thread.
3317    Predicate<bool>             m_private_state_control_wait; /// This Predicate is used to signal that a control operation is complete.
3318    lldb::thread_t              m_private_state_thread;  // Thread ID for the thread that watches interal state events
3319    ProcessModID                m_mod_id;               ///< Tracks the state of the process over stops and other alterations.
3320    uint32_t                    m_thread_index_id;      ///< Each thread is created with a 1 based index that won't get re-used.
3321    int                         m_exit_status;          ///< The exit status of the process, or -1 if not set.
3322    std::string                 m_exit_string;          ///< A textual description of why a process exited.
3323    ThreadList                  m_thread_list;          ///< The threads for this process.
3324    std::vector<Notifications>  m_notifications;        ///< The list of notifications that this process can deliver.
3325    std::vector<lldb::addr_t>   m_image_tokens;
3326    Listener                    &m_listener;
3327    BreakpointSiteList          m_breakpoint_site_list; ///< This is the list of breakpoint locations we intend to insert in the target.
3328    std::auto_ptr<DynamicLoader> m_dyld_ap;
3329    std::auto_ptr<DynamicCheckerFunctions> m_dynamic_checkers_ap; ///< The functions used by the expression parser to validate data that expressions use.
3330    std::auto_ptr<OperatingSystem> m_os_ap;
3331    UnixSignals                 m_unix_signals;         /// This is the current signal set for this process.
3332    lldb::ABISP                 m_abi_sp;
3333    lldb::InputReaderSP         m_process_input_reader;
3334    Communication 				m_stdio_communication;
3335    Mutex        				m_stdio_communication_mutex;
3336    std::string                 m_stdout_data;
3337    std::string                 m_stderr_data;
3338    MemoryCache                 m_memory_cache;
3339    AllocatedMemoryCache        m_allocated_memory_cache;
3340    bool                        m_should_detach;   /// Should we detach if the process object goes away with an explicit call to Kill or Detach?
3341    LanguageRuntimeCollection 	m_language_runtimes;
3342    std::auto_ptr<NextEventAction> m_next_event_action_ap;
3343    std::vector<PreResumeCallbackAndBaton> m_pre_resume_actions;
3344    ReadWriteLock               m_run_lock;
3345
3346    enum {
3347        eCanJITDontKnow= 0,
3348        eCanJITYes,
3349        eCanJITNo
3350    } m_can_jit;
3351
3352    size_t
3353    RemoveBreakpointOpcodesFromBuffer (lldb::addr_t addr, size_t size, uint8_t *buf) const;
3354
3355    void
3356    SynchronouslyNotifyStateChanged (lldb::StateType state);
3357
3358    void
3359    SetPublicState (lldb::StateType new_state);
3360
3361    void
3362    SetPrivateState (lldb::StateType state);
3363
3364    bool
3365    StartPrivateStateThread (bool force = false);
3366
3367    void
3368    StopPrivateStateThread ();
3369
3370    void
3371    PausePrivateStateThread ();
3372
3373    void
3374    ResumePrivateStateThread ();
3375
3376    static void *
3377    PrivateStateThread (void *arg);
3378
3379    void *
3380    RunPrivateStateThread ();
3381
3382    void
3383    HandlePrivateEvent (lldb::EventSP &event_sp);
3384
3385    lldb::StateType
3386    WaitForProcessStopPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
3387
3388    // This waits for both the state change broadcaster, and the control broadcaster.
3389    // If control_only, it only waits for the control broadcaster.
3390
3391    bool
3392    WaitForEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp, bool control_only);
3393
3394    lldb::StateType
3395    WaitForStateChangedEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
3396
3397    lldb::StateType
3398    WaitForState (const TimeValue *timeout,
3399                  const lldb::StateType *match_states,
3400                  const uint32_t num_match_states);
3401
3402    size_t
3403    WriteMemoryPrivate (lldb::addr_t addr, const void *buf, size_t size, Error &error);
3404
3405    void
3406    AppendSTDOUT (const char *s, size_t len);
3407
3408    void
3409    AppendSTDERR (const char *s, size_t len);
3410
3411    static void
3412    STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len);
3413
3414    void
3415    PushProcessInputReader ();
3416
3417    void
3418    PopProcessInputReader ();
3419
3420    void
3421    ResetProcessInputReader ();
3422
3423    static size_t
3424    ProcessInputReaderCallback (void *baton,
3425                                InputReader &reader,
3426                                lldb::InputReaderAction notification,
3427                                const char *bytes,
3428                                size_t bytes_len);
3429
3430
3431private:
3432    //------------------------------------------------------------------
3433    // For Process only
3434    //------------------------------------------------------------------
3435    void ControlPrivateStateThread (uint32_t signal);
3436
3437    DISALLOW_COPY_AND_ASSIGN (Process);
3438
3439};
3440
3441} // namespace lldb_private
3442
3443#endif  // liblldb_Process_h_
3444