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