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