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