Process.h revision 4f9103faba72fdfc4b4299d6d459bc820ee597b2
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
1450            size_t
1451            GetNumRestartedReasons ()
1452            {
1453                return m_restarted_reasons.size();
1454            }
1455
1456            const char *
1457            GetRestartedReasonAtIndex(size_t idx)
1458            {
1459                if (idx > m_restarted_reasons.size())
1460                    return NULL;
1461                else
1462                    return m_restarted_reasons[idx].c_str();
1463            }
1464
1465            bool
1466            GetInterrupted () const
1467            {
1468                return m_interrupted;
1469            }
1470
1471            virtual void
1472            Dump (Stream *s) const;
1473
1474            virtual void
1475            DoOnRemoval (Event *event_ptr);
1476
1477            static const Process::ProcessEventData *
1478            GetEventDataFromEvent (const Event *event_ptr);
1479
1480            static lldb::ProcessSP
1481            GetProcessFromEvent (const Event *event_ptr);
1482
1483            static lldb::StateType
1484            GetStateFromEvent (const Event *event_ptr);
1485
1486            static bool
1487            GetRestartedFromEvent (const Event *event_ptr);
1488
1489            static size_t
1490            GetNumRestartedReasons(const Event *event_ptr);
1491
1492            static const char *
1493            GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx);
1494
1495            static void
1496            AddRestartedReason (Event *event_ptr, const char *reason);
1497
1498            static void
1499            SetRestartedInEvent (Event *event_ptr, bool new_value);
1500
1501            static bool
1502            GetInterruptedFromEvent (const Event *event_ptr);
1503
1504            static void
1505            SetInterruptedInEvent (Event *event_ptr, bool new_value);
1506
1507            static bool
1508            SetUpdateStateOnRemoval (Event *event_ptr);
1509
1510       private:
1511
1512            void
1513            SetUpdateStateOnRemoval()
1514            {
1515                m_update_state++;
1516            }
1517            void
1518            SetRestarted (bool new_value)
1519            {
1520                m_restarted = new_value;
1521            }
1522            void
1523            SetInterrupted (bool new_value)
1524            {
1525                m_interrupted = new_value;
1526            }
1527            void
1528            AddRestartedReason (const char *reason)
1529            {
1530                m_restarted_reasons.push_back(reason);
1531            }
1532
1533            lldb::ProcessSP m_process_sp;
1534            lldb::StateType m_state;
1535            std::vector<std::string> m_restarted_reasons;
1536            bool m_restarted;  // For "eStateStopped" events, this is true if the target was automatically restarted.
1537            int m_update_state;
1538            bool m_interrupted;
1539            DISALLOW_COPY_AND_ASSIGN (ProcessEventData);
1540
1541    };
1542
1543#endif
1544
1545    static void
1546    SettingsInitialize ();
1547
1548    static void
1549    SettingsTerminate ();
1550
1551    static const ProcessPropertiesSP &
1552    GetGlobalProperties();
1553
1554    //------------------------------------------------------------------
1555    /// Construct with a shared pointer to a target, and the Process listener.
1556    //------------------------------------------------------------------
1557    Process(Target &target, Listener &listener);
1558
1559    //------------------------------------------------------------------
1560    /// Destructor.
1561    ///
1562    /// The destructor is virtual since this class is designed to be
1563    /// inherited from by the plug-in instance.
1564    //------------------------------------------------------------------
1565    virtual
1566    ~Process();
1567
1568    //------------------------------------------------------------------
1569    /// Find a Process plug-in that can debug \a module using the
1570    /// currently selected architecture.
1571    ///
1572    /// Scans all loaded plug-in interfaces that implement versions of
1573    /// the Process plug-in interface and returns the first instance
1574    /// that can debug the file.
1575    ///
1576    /// @param[in] module_sp
1577    ///     The module shared pointer that this process will debug.
1578    ///
1579    /// @param[in] plugin_name
1580    ///     If NULL, select the best plug-in for the binary. If non-NULL
1581    ///     then look for a plugin whose PluginInfo's name matches
1582    ///     this string.
1583    ///
1584    /// @see Process::CanDebug ()
1585    //------------------------------------------------------------------
1586    static lldb::ProcessSP
1587    FindPlugin (Target &target,
1588                const char *plugin_name,
1589                Listener &listener,
1590                const FileSpec *crash_file_path);
1591
1592
1593
1594    //------------------------------------------------------------------
1595    /// Static function that can be used with the \b host function
1596    /// Host::StartMonitoringChildProcess ().
1597    ///
1598    /// This function can be used by lldb_private::Process subclasses
1599    /// when they want to watch for a local process and have its exit
1600    /// status automatically set when the host child process exits.
1601    /// Subclasses should call Host::StartMonitoringChildProcess ()
1602    /// with:
1603    ///     callback = Process::SetHostProcessExitStatus
1604    ///     callback_baton = NULL
1605    ///     pid = Process::GetID()
1606    ///     monitor_signals = false
1607    //------------------------------------------------------------------
1608    static bool
1609    SetProcessExitStatus (void *callback_baton,   // The callback baton which should be set to NULL
1610                          lldb::pid_t pid,        // The process ID we want to monitor
1611                          bool exited,
1612                          int signo,              // Zero for no signal
1613                          int status);            // Exit value of process if signal is zero
1614
1615    lldb::ByteOrder
1616    GetByteOrder () const;
1617
1618    uint32_t
1619    GetAddressByteSize () const;
1620
1621    uint32_t
1622    GetUniqueID() const
1623    {
1624        return m_process_unique_id;
1625    }
1626    //------------------------------------------------------------------
1627    /// Check if a plug-in instance can debug the file in \a module.
1628    ///
1629    /// Each plug-in is given a chance to say whether it can debug
1630    /// the file in \a module. If the Process plug-in instance can
1631    /// debug a file on the current system, it should return \b true.
1632    ///
1633    /// @return
1634    ///     Returns \b true if this Process plug-in instance can
1635    ///     debug the executable, \b false otherwise.
1636    //------------------------------------------------------------------
1637    virtual bool
1638    CanDebug (Target &target,
1639              bool plugin_specified_by_name) = 0;
1640
1641
1642    //------------------------------------------------------------------
1643    /// This object is about to be destroyed, do any necessary cleanup.
1644    ///
1645    /// Subclasses that override this method should always call this
1646    /// superclass method.
1647    //------------------------------------------------------------------
1648    virtual void
1649    Finalize();
1650
1651
1652    //------------------------------------------------------------------
1653    /// Return whether this object is valid (i.e. has not been finalized.)
1654    ///
1655    /// @return
1656    ///     Returns \b true if this Process has not been finalized
1657    ///     and \b false otherwise.
1658    //------------------------------------------------------------------
1659    bool
1660    IsValid() const
1661    {
1662        return !m_finalize_called;
1663    }
1664
1665    //------------------------------------------------------------------
1666    /// Return a multi-word command object that can be used to expose
1667    /// plug-in specific commands.
1668    ///
1669    /// This object will be used to resolve plug-in commands and can be
1670    /// triggered by a call to:
1671    ///
1672    ///     (lldb) process commmand <args>
1673    ///
1674    /// @return
1675    ///     A CommandObject which can be one of the concrete subclasses
1676    ///     of CommandObject like CommandObjectRaw, CommandObjectParsed,
1677    ///     or CommandObjectMultiword.
1678    //------------------------------------------------------------------
1679    virtual CommandObject *
1680    GetPluginCommandObject()
1681    {
1682        return NULL;
1683    }
1684
1685    //------------------------------------------------------------------
1686    /// Launch a new process.
1687    ///
1688    /// Launch a new process by spawning a new process using the
1689    /// target object's executable module's file as the file to launch.
1690    /// Arguments are given in \a argv, and the environment variables
1691    /// are in \a envp. Standard input and output files can be
1692    /// optionally re-directed to \a stdin_path, \a stdout_path, and
1693    /// \a stderr_path.
1694    ///
1695    /// This function is not meant to be overridden by Process
1696    /// subclasses. It will first call Process::WillLaunch (Module *)
1697    /// and if that returns \b true, Process::DoLaunch (Module*,
1698    /// char const *[],char const *[],const char *,const char *,
1699    /// const char *) will be called to actually do the launching. If
1700    /// DoLaunch returns \b true, then Process::DidLaunch() will be
1701    /// called.
1702    ///
1703    /// @param[in] argv
1704    ///     The argument array.
1705    ///
1706    /// @param[in] envp
1707    ///     The environment array.
1708    ///
1709    /// @param[in] launch_flags
1710    ///     Flags to modify the launch (@see lldb::LaunchFlags)
1711    ///
1712    /// @param[in] stdin_path
1713    ///     The path to use when re-directing the STDIN of the new
1714    ///     process. If all stdXX_path arguments are NULL, a pseudo
1715    ///     terminal will be used.
1716    ///
1717    /// @param[in] stdout_path
1718    ///     The path to use when re-directing the STDOUT of the new
1719    ///     process. If all stdXX_path arguments are NULL, a pseudo
1720    ///     terminal will be used.
1721    ///
1722    /// @param[in] stderr_path
1723    ///     The path to use when re-directing the STDERR of the new
1724    ///     process. If all stdXX_path arguments are NULL, a pseudo
1725    ///     terminal will be used.
1726    ///
1727    /// @param[in] working_directory
1728    ///     The working directory to have the child process run in
1729    ///
1730    /// @return
1731    ///     An error object. Call GetID() to get the process ID if
1732    ///     the error object is success.
1733    //------------------------------------------------------------------
1734    virtual Error
1735    Launch (const ProcessLaunchInfo &launch_info);
1736
1737    virtual Error
1738    LoadCore ();
1739
1740    virtual Error
1741    DoLoadCore ()
1742    {
1743        Error error;
1744        error.SetErrorStringWithFormat("error: %s does not support loading core files.", GetShortPluginName());
1745        return error;
1746    }
1747
1748    //------------------------------------------------------------------
1749    /// Get the dynamic loader plug-in for this process.
1750    ///
1751    /// The default action is to let the DynamicLoader plug-ins check
1752    /// the main executable and the DynamicLoader will select itself
1753    /// automatically. Subclasses can override this if inspecting the
1754    /// executable is not desired, or if Process subclasses can only
1755    /// use a specific DynamicLoader plug-in.
1756    //------------------------------------------------------------------
1757    virtual DynamicLoader *
1758    GetDynamicLoader ();
1759
1760    //------------------------------------------------------------------
1761    /// Attach to an existing process using the process attach info.
1762    ///
1763    /// This function is not meant to be overridden by Process
1764    /// subclasses. It will first call WillAttach (lldb::pid_t)
1765    /// or WillAttach (const char *), and if that returns \b
1766    /// true, DoAttach (lldb::pid_t) or DoAttach (const char *) will
1767    /// be called to actually do the attach. If DoAttach returns \b
1768    /// true, then Process::DidAttach() will be called.
1769    ///
1770    /// @param[in] pid
1771    ///     The process ID that we should attempt to attach to.
1772    ///
1773    /// @return
1774    ///     Returns \a pid if attaching was successful, or
1775    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
1776    //------------------------------------------------------------------
1777    virtual Error
1778    Attach (ProcessAttachInfo &attach_info);
1779
1780    //------------------------------------------------------------------
1781    /// Attach to a remote system via a URL
1782    ///
1783    /// @param[in] strm
1784    ///     A stream where output intended for the user
1785    ///     (if the driver has a way to display that) generated during
1786    ///     the connection.  This may be NULL if no output is needed.A
1787    ///
1788    /// @param[in] remote_url
1789    ///     The URL format that we are connecting to.
1790    ///
1791    /// @return
1792    ///     Returns an error object.
1793    //------------------------------------------------------------------
1794    virtual Error
1795    ConnectRemote (Stream *strm, const char *remote_url);
1796
1797    bool
1798    GetShouldDetach () const
1799    {
1800        return m_should_detach;
1801    }
1802
1803    void
1804    SetShouldDetach (bool b)
1805    {
1806        m_should_detach = b;
1807    }
1808
1809    //------------------------------------------------------------------
1810    /// Get the image information address for the current process.
1811    ///
1812    /// Some runtimes have system functions that can help dynamic
1813    /// loaders locate the dynamic loader information needed to observe
1814    /// shared libraries being loaded or unloaded. This function is
1815    /// in the Process interface (as opposed to the DynamicLoader
1816    /// interface) to ensure that remote debugging can take advantage of
1817    /// this functionality.
1818    ///
1819    /// @return
1820    ///     The address of the dynamic loader information, or
1821    ///     LLDB_INVALID_ADDRESS if this is not supported by this
1822    ///     interface.
1823    //------------------------------------------------------------------
1824    virtual lldb::addr_t
1825    GetImageInfoAddress ();
1826
1827    //------------------------------------------------------------------
1828    /// Load a shared library into this process.
1829    ///
1830    /// Try and load a shared library into the current process. This
1831    /// call might fail in the dynamic loader plug-in says it isn't safe
1832    /// to try and load shared libraries at the moment.
1833    ///
1834    /// @param[in] image_spec
1835    ///     The image file spec that points to the shared library that
1836    ///     you want to load.
1837    ///
1838    /// @param[out] error
1839    ///     An error object that gets filled in with any errors that
1840    ///     might occur when trying to load the shared library.
1841    ///
1842    /// @return
1843    ///     A token that represents the shared library that can be
1844    ///     later used to unload the shared library. A value of
1845    ///     LLDB_INVALID_IMAGE_TOKEN will be returned if the shared
1846    ///     library can't be opened.
1847    //------------------------------------------------------------------
1848    virtual uint32_t
1849    LoadImage (const FileSpec &image_spec, Error &error);
1850
1851    virtual Error
1852    UnloadImage (uint32_t image_token);
1853
1854    //------------------------------------------------------------------
1855    /// Register for process and thread notifications.
1856    ///
1857    /// Clients can register nofication callbacks by filling out a
1858    /// Process::Notifications structure and calling this function.
1859    ///
1860    /// @param[in] callbacks
1861    ///     A structure that contains the notification baton and
1862    ///     callback functions.
1863    ///
1864    /// @see Process::Notifications
1865    //------------------------------------------------------------------
1866#ifndef SWIG
1867    void
1868    RegisterNotificationCallbacks (const Process::Notifications& callbacks);
1869#endif
1870    //------------------------------------------------------------------
1871    /// Unregister for process and thread notifications.
1872    ///
1873    /// Clients can unregister nofication callbacks by passing a copy of
1874    /// the original baton and callbacks in \a callbacks.
1875    ///
1876    /// @param[in] callbacks
1877    ///     A structure that contains the notification baton and
1878    ///     callback functions.
1879    ///
1880    /// @return
1881    ///     Returns \b true if the notification callbacks were
1882    ///     successfully removed from the process, \b false otherwise.
1883    ///
1884    /// @see Process::Notifications
1885    //------------------------------------------------------------------
1886#ifndef SWIG
1887    bool
1888    UnregisterNotificationCallbacks (const Process::Notifications& callbacks);
1889#endif
1890    //==================================================================
1891    // Built in Process Control functions
1892    //==================================================================
1893    //------------------------------------------------------------------
1894    /// Resumes all of a process's threads as configured using the
1895    /// Thread run control functions.
1896    ///
1897    /// Threads for a process should be updated with one of the run
1898    /// control actions (resume, step, or suspend) that they should take
1899    /// when the process is resumed. If no run control action is given
1900    /// to a thread it will be resumed by default.
1901    ///
1902    /// This function is not meant to be overridden by Process
1903    /// subclasses. This function will take care of disabling any
1904    /// breakpoints that threads may be stopped at, single stepping, and
1905    /// re-enabling breakpoints, and enabling the basic flow control
1906    /// that the plug-in instances need not worry about.
1907    ///
1908    /// N.B. This function also sets the Write side of the Run Lock,
1909    /// which is unset when the corresponding stop event is pulled off
1910    /// the Public Event Queue.  If you need to resume the process without
1911    /// setting the Run Lock, use PrivateResume (though you should only do
1912    /// that from inside the Process class.
1913    ///
1914    /// @return
1915    ///     Returns an error object.
1916    ///
1917    /// @see Thread:Resume()
1918    /// @see Thread:Step()
1919    /// @see Thread:Suspend()
1920    //------------------------------------------------------------------
1921    Error
1922    Resume();
1923
1924    //------------------------------------------------------------------
1925    /// Halts a running process.
1926    ///
1927    /// This function is not meant to be overridden by Process
1928    /// subclasses.
1929    /// If the process is successfully halted, a eStateStopped
1930    /// process event with GetInterrupted will be broadcast.  If false, we will
1931    /// halt the process with no events generated by the halt.
1932    ///
1933    /// @return
1934    ///     Returns an error object.  If the error is empty, the process is halted.
1935    ///     otherwise the halt has failed.
1936    //------------------------------------------------------------------
1937    Error
1938    Halt ();
1939
1940    //------------------------------------------------------------------
1941    /// Detaches from a running or stopped process.
1942    ///
1943    /// This function is not meant to be overridden by Process
1944    /// subclasses.
1945    ///
1946    /// @return
1947    ///     Returns an error object.
1948    //------------------------------------------------------------------
1949    Error
1950    Detach ();
1951
1952    //------------------------------------------------------------------
1953    /// Kills the process and shuts down all threads that were spawned
1954    /// to track and monitor the process.
1955    ///
1956    /// This function is not meant to be overridden by Process
1957    /// subclasses.
1958    ///
1959    /// @return
1960    ///     Returns an error object.
1961    //------------------------------------------------------------------
1962    Error
1963    Destroy();
1964
1965    //------------------------------------------------------------------
1966    /// Sends a process a UNIX signal \a signal.
1967    ///
1968    /// This function is not meant to be overridden by Process
1969    /// subclasses.
1970    ///
1971    /// @return
1972    ///     Returns an error object.
1973    //------------------------------------------------------------------
1974    Error
1975    Signal (int signal);
1976
1977    virtual UnixSignals &
1978    GetUnixSignals ()
1979    {
1980        return m_unix_signals;
1981    }
1982
1983    //==================================================================
1984    // Plug-in Process Control Overrides
1985    //==================================================================
1986
1987    //------------------------------------------------------------------
1988    /// Called before attaching to a process.
1989    ///
1990    /// Allow Process plug-ins to execute some code before attaching a
1991    /// process.
1992    ///
1993    /// @return
1994    ///     Returns an error object.
1995    //------------------------------------------------------------------
1996    virtual Error
1997    WillAttachToProcessWithID (lldb::pid_t pid)
1998    {
1999        return Error();
2000    }
2001
2002    //------------------------------------------------------------------
2003    /// Called before attaching to a process.
2004    ///
2005    /// Allow Process plug-ins to execute some code before attaching a
2006    /// process.
2007    ///
2008    /// @return
2009    ///     Returns an error object.
2010    //------------------------------------------------------------------
2011    virtual Error
2012    WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
2013    {
2014        return Error();
2015    }
2016
2017    //------------------------------------------------------------------
2018    /// Attach to a remote system via a URL
2019    ///
2020    /// @param[in] strm
2021    ///     A stream where output intended for the user
2022    ///     (if the driver has a way to display that) generated during
2023    ///     the connection.  This may be NULL if no output is needed.A
2024    ///
2025    /// @param[in] remote_url
2026    ///     The URL format that we are connecting to.
2027    ///
2028    /// @return
2029    ///     Returns an error object.
2030    //------------------------------------------------------------------
2031    virtual Error
2032    DoConnectRemote (Stream *strm, const char *remote_url)
2033    {
2034        Error error;
2035        error.SetErrorString ("remote connections are not supported");
2036        return error;
2037    }
2038
2039    //------------------------------------------------------------------
2040    /// Attach to an existing process using a process ID.
2041    ///
2042    /// @param[in] pid
2043    ///     The process ID that we should attempt to attach to.
2044    ///
2045    /// @return
2046    ///     Returns \a pid if attaching was successful, or
2047    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
2048    //------------------------------------------------------------------
2049    virtual Error
2050    DoAttachToProcessWithID (lldb::pid_t pid)
2051    {
2052        Error error;
2053        error.SetErrorStringWithFormat("error: %s does not support attaching to a process by pid", GetShortPluginName());
2054        return error;
2055    }
2056
2057    //------------------------------------------------------------------
2058    /// Attach to an existing process using a process ID.
2059    ///
2060    /// @param[in] pid
2061    ///     The process ID that we should attempt to attach to.
2062    ///
2063    /// @param[in] attach_info
2064    ///     Information on how to do the attach. For example, GetUserID()
2065    ///     will return the uid to attach as.
2066    ///
2067    /// @return
2068    ///     Returns \a pid if attaching was successful, or
2069    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
2070    /// hanming : need flag
2071    //------------------------------------------------------------------
2072    virtual Error
2073    DoAttachToProcessWithID (lldb::pid_t pid,  const ProcessAttachInfo &attach_info)
2074    {
2075        Error error;
2076        error.SetErrorStringWithFormat("error: %s does not support attaching to a process by pid", GetShortPluginName());
2077        return error;
2078    }
2079
2080    //------------------------------------------------------------------
2081    /// Attach to an existing process using a partial process name.
2082    ///
2083    /// @param[in] process_name
2084    ///     The name of the process to attach to.
2085    ///
2086    /// @param[in] wait_for_launch
2087    ///     If \b true, wait for the process to be launched and attach
2088    ///     as soon as possible after it does launch. If \b false, then
2089    ///     search for a matching process the currently exists.
2090    ///
2091    /// @param[in] attach_info
2092    ///     Information on how to do the attach. For example, GetUserID()
2093    ///     will return the uid to attach as.
2094    ///
2095    /// @return
2096    ///     Returns \a pid if attaching was successful, or
2097    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
2098    //------------------------------------------------------------------
2099    virtual Error
2100    DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
2101    {
2102        Error error;
2103        error.SetErrorString("attach by name is not supported");
2104        return error;
2105    }
2106
2107    //------------------------------------------------------------------
2108    /// Called after attaching a process.
2109    ///
2110    /// Allow Process plug-ins to execute some code after attaching to
2111    /// a process.
2112    //------------------------------------------------------------------
2113    virtual void
2114    DidAttach () {}
2115
2116
2117    //------------------------------------------------------------------
2118    /// Called after a process re-execs itself.
2119    ///
2120    /// Allow Process plug-ins to execute some code after a process has
2121    /// exec'ed itself. Subclasses typically should override DoDidExec()
2122    /// as the lldb_private::Process class needs to remove its dynamic
2123    /// loader, runtime, ABI and other plug-ins, as well as unload all
2124    /// shared libraries.
2125    //------------------------------------------------------------------
2126    virtual void
2127    DidExec ();
2128
2129    //------------------------------------------------------------------
2130    /// Subclasses of Process should implement this function if they
2131    /// need to do anything after a process exec's itself.
2132    //------------------------------------------------------------------
2133    virtual void
2134    DoDidExec ()
2135    {
2136    }
2137
2138    //------------------------------------------------------------------
2139    /// Called before launching to a process.
2140    ///
2141    /// Allow Process plug-ins to execute some code before launching a
2142    /// process.
2143    ///
2144    /// @return
2145    ///     Returns an error object.
2146    //------------------------------------------------------------------
2147    virtual Error
2148    WillLaunch (Module* module)
2149    {
2150        return Error();
2151    }
2152
2153    //------------------------------------------------------------------
2154    /// Launch a new process.
2155    ///
2156    /// Launch a new process by spawning a new process using \a module's
2157    /// file as the file to launch. Arguments are given in \a argv,
2158    /// and the environment variables are in \a envp. Standard input
2159    /// and output files can be optionally re-directed to \a stdin_path,
2160    /// \a stdout_path, and \a stderr_path.
2161    ///
2162    /// @param[in] module
2163    ///     The module from which to extract the file specification and
2164    ///     launch.
2165    ///
2166    /// @param[in] argv
2167    ///     The argument array.
2168    ///
2169    /// @param[in] envp
2170    ///     The environment array.
2171    ///
2172    /// @param[in] launch_flags
2173    ///     Flags to modify the launch (@see lldb::LaunchFlags)
2174    ///
2175    /// @param[in] stdin_path
2176    ///     The path to use when re-directing the STDIN of the new
2177    ///     process. If all stdXX_path arguments are NULL, a pseudo
2178    ///     terminal will be used.
2179    ///
2180    /// @param[in] stdout_path
2181    ///     The path to use when re-directing the STDOUT of the new
2182    ///     process. If all stdXX_path arguments are NULL, a pseudo
2183    ///     terminal will be used.
2184    ///
2185    /// @param[in] stderr_path
2186    ///     The path to use when re-directing the STDERR of the new
2187    ///     process. If all stdXX_path arguments are NULL, a pseudo
2188    ///     terminal will be used.
2189    ///
2190    /// @param[in] working_directory
2191    ///     The working directory to have the child process run in
2192    ///
2193    /// @return
2194    ///     A new valid process ID, or LLDB_INVALID_PROCESS_ID if
2195    ///     launching fails.
2196    //------------------------------------------------------------------
2197    virtual Error
2198    DoLaunch (Module *exe_module,
2199              const ProcessLaunchInfo &launch_info)
2200    {
2201        Error error;
2202        error.SetErrorStringWithFormat("error: %s does not support launching processes", GetShortPluginName());
2203        return error;
2204    }
2205
2206
2207    //------------------------------------------------------------------
2208    /// Called after launching a process.
2209    ///
2210    /// Allow Process plug-ins to execute some code after launching
2211    /// a process.
2212    //------------------------------------------------------------------
2213    virtual void
2214    DidLaunch () {}
2215
2216
2217
2218    //------------------------------------------------------------------
2219    /// Called before resuming to a process.
2220    ///
2221    /// Allow Process plug-ins to execute some code before resuming a
2222    /// process.
2223    ///
2224    /// @return
2225    ///     Returns an error object.
2226    //------------------------------------------------------------------
2227    virtual Error
2228    WillResume () { return Error(); }
2229
2230    //------------------------------------------------------------------
2231    /// Resumes all of a process's threads as configured using the
2232    /// Thread run control functions.
2233    ///
2234    /// Threads for a process should be updated with one of the run
2235    /// control actions (resume, step, or suspend) that they should take
2236    /// when the process is resumed. If no run control action is given
2237    /// to a thread it will be resumed by default.
2238    ///
2239    /// @return
2240    ///     Returns \b true if the process successfully resumes using
2241    ///     the thread run control actions, \b false otherwise.
2242    ///
2243    /// @see Thread:Resume()
2244    /// @see Thread:Step()
2245    /// @see Thread:Suspend()
2246    //------------------------------------------------------------------
2247    virtual Error
2248    DoResume ()
2249    {
2250        Error error;
2251        error.SetErrorStringWithFormat("error: %s does not support resuming processes", GetShortPluginName());
2252        return error;
2253    }
2254
2255
2256    //------------------------------------------------------------------
2257    /// Called after resuming a process.
2258    ///
2259    /// Allow Process plug-ins to execute some code after resuming
2260    /// a process.
2261    //------------------------------------------------------------------
2262    virtual void
2263    DidResume () {}
2264
2265
2266    //------------------------------------------------------------------
2267    /// Called before halting to a process.
2268    ///
2269    /// Allow Process plug-ins to execute some code before halting a
2270    /// process.
2271    ///
2272    /// @return
2273    ///     Returns an error object.
2274    //------------------------------------------------------------------
2275    virtual Error
2276    WillHalt () { return Error(); }
2277
2278    //------------------------------------------------------------------
2279    /// Halts a running process.
2280    ///
2281    /// DoHalt must produce one and only one stop StateChanged event if it actually
2282    /// stops the process.  If the stop happens through some natural event (for
2283    /// instance a SIGSTOP), then forwarding that event will do.  Otherwise, you must
2284    /// generate the event manually.  Note also, the private event thread is stopped when
2285    /// DoHalt is run to prevent the events generated while halting to trigger
2286    /// other state changes before the halt is complete.
2287    ///
2288    /// @param[out] caused_stop
2289    ///     If true, then this Halt caused the stop, otherwise, the
2290    ///     process was already stopped.
2291    ///
2292    /// @return
2293    ///     Returns \b true if the process successfully halts, \b false
2294    ///     otherwise.
2295    //------------------------------------------------------------------
2296    virtual Error
2297    DoHalt (bool &caused_stop)
2298    {
2299        Error error;
2300        error.SetErrorStringWithFormat("error: %s does not support halting processes", GetShortPluginName());
2301        return error;
2302    }
2303
2304
2305    //------------------------------------------------------------------
2306    /// Called after halting a process.
2307    ///
2308    /// Allow Process plug-ins to execute some code after halting
2309    /// a process.
2310    //------------------------------------------------------------------
2311    virtual void
2312    DidHalt () {}
2313
2314    //------------------------------------------------------------------
2315    /// Called before detaching from a process.
2316    ///
2317    /// Allow Process plug-ins to execute some code before detaching
2318    /// from a process.
2319    ///
2320    /// @return
2321    ///     Returns an error object.
2322    //------------------------------------------------------------------
2323    virtual Error
2324    WillDetach ()
2325    {
2326        return Error();
2327    }
2328
2329    //------------------------------------------------------------------
2330    /// Detaches from a running or stopped process.
2331    ///
2332    /// @return
2333    ///     Returns \b true if the process successfully detaches, \b
2334    ///     false otherwise.
2335    //------------------------------------------------------------------
2336    virtual Error
2337    DoDetach ()
2338    {
2339        Error error;
2340        error.SetErrorStringWithFormat("error: %s does not support detaching from processes", GetShortPluginName());
2341        return error;
2342    }
2343
2344
2345    //------------------------------------------------------------------
2346    /// Called after detaching from a process.
2347    ///
2348    /// Allow Process plug-ins to execute some code after detaching
2349    /// from a process.
2350    //------------------------------------------------------------------
2351    virtual void
2352    DidDetach () {}
2353
2354    //------------------------------------------------------------------
2355    /// Called before sending a signal to a process.
2356    ///
2357    /// Allow Process plug-ins to execute some code before sending a
2358    /// signal to a process.
2359    ///
2360    /// @return
2361    ///     Returns no error if it is safe to proceed with a call to
2362    ///     Process::DoSignal(int), otherwise an error describing what
2363    ///     prevents the signal from being sent.
2364    //------------------------------------------------------------------
2365    virtual Error
2366    WillSignal () { return Error(); }
2367
2368    //------------------------------------------------------------------
2369    /// Sends a process a UNIX signal \a signal.
2370    ///
2371    /// @return
2372    ///     Returns an error object.
2373    //------------------------------------------------------------------
2374    virtual Error
2375    DoSignal (int signal)
2376    {
2377        Error error;
2378        error.SetErrorStringWithFormat("error: %s does not support senging signals to processes", GetShortPluginName());
2379        return error;
2380    }
2381
2382    virtual Error
2383    WillDestroy () { return Error(); }
2384
2385    virtual Error
2386    DoDestroy () = 0;
2387
2388    virtual void
2389    DidDestroy () { }
2390
2391
2392    //------------------------------------------------------------------
2393    /// Called after sending a signal to a process.
2394    ///
2395    /// Allow Process plug-ins to execute some code after sending a
2396    /// signal to a process.
2397    //------------------------------------------------------------------
2398    virtual void
2399    DidSignal () {}
2400
2401    //------------------------------------------------------------------
2402    /// Currently called as part of ShouldStop.
2403    /// FIXME: Should really happen when the target stops before the
2404    /// event is taken from the queue...
2405    ///
2406    /// This callback is called as the event
2407    /// is about to be queued up to allow Process plug-ins to execute
2408    /// some code prior to clients being notified that a process was
2409    /// stopped. Common operations include updating the thread list,
2410    /// invalidating any thread state (registers, stack, etc) prior to
2411    /// letting the notification go out.
2412    ///
2413    //------------------------------------------------------------------
2414    virtual void
2415    RefreshStateAfterStop () = 0;
2416
2417    //------------------------------------------------------------------
2418    /// Get the target object pointer for this module.
2419    ///
2420    /// @return
2421    ///     A Target object pointer to the target that owns this
2422    ///     module.
2423    //------------------------------------------------------------------
2424    Target &
2425    GetTarget ()
2426    {
2427        return m_target;
2428    }
2429
2430    //------------------------------------------------------------------
2431    /// Get the const target object pointer for this module.
2432    ///
2433    /// @return
2434    ///     A const Target object pointer to the target that owns this
2435    ///     module.
2436    //------------------------------------------------------------------
2437    const Target &
2438    GetTarget () const
2439    {
2440        return m_target;
2441    }
2442
2443    //------------------------------------------------------------------
2444    /// Flush all data in the process.
2445    ///
2446    /// Flush the memory caches, all threads, and any other cached data
2447    /// in the process.
2448    ///
2449    /// This function can be called after a world changing event like
2450    /// adding a new symbol file, or after the process makes a large
2451    /// context switch (from boot ROM to booted into an OS).
2452    //------------------------------------------------------------------
2453    void
2454    Flush ();
2455
2456    //------------------------------------------------------------------
2457    /// Get accessor for the current process state.
2458    ///
2459    /// @return
2460    ///     The current state of the process.
2461    ///
2462    /// @see lldb::StateType
2463    //------------------------------------------------------------------
2464    lldb::StateType
2465    GetState ();
2466
2467    ExecutionResults
2468    RunThreadPlan (ExecutionContext &exe_ctx,
2469                    lldb::ThreadPlanSP &thread_plan_sp,
2470                    bool stop_others,
2471                    bool run_others,
2472                    bool unwind_on_error,
2473                    bool ignore_breakpoints,
2474                    uint32_t timeout_usec,
2475                    Stream &errors);
2476
2477    static const char *
2478    ExecutionResultAsCString (ExecutionResults result);
2479
2480    void
2481    GetStatus (Stream &ostrm);
2482
2483    size_t
2484    GetThreadStatus (Stream &ostrm,
2485                     bool only_threads_with_stop_reason,
2486                     uint32_t start_frame,
2487                     uint32_t num_frames,
2488                     uint32_t num_frames_with_source);
2489
2490    void
2491    SendAsyncInterrupt ();
2492
2493protected:
2494
2495    void
2496    SetState (lldb::EventSP &event_sp);
2497
2498    lldb::StateType
2499    GetPrivateState ();
2500
2501    //------------------------------------------------------------------
2502    /// The "private" side of resuming a process.  This doesn't alter the
2503    /// state of m_run_lock, but just causes the process to resume.
2504    ///
2505    /// @return
2506    ///     An Error object describing the success or failure of the resume.
2507    //------------------------------------------------------------------
2508    Error
2509    PrivateResume ();
2510
2511    //------------------------------------------------------------------
2512    // Called internally
2513    //------------------------------------------------------------------
2514    void
2515    CompleteAttach ();
2516
2517public:
2518    //------------------------------------------------------------------
2519    /// Get the exit status for a process.
2520    ///
2521    /// @return
2522    ///     The process's return code, or -1 if the current process
2523    ///     state is not eStateExited.
2524    //------------------------------------------------------------------
2525    int
2526    GetExitStatus ();
2527
2528    //------------------------------------------------------------------
2529    /// Get a textual description of what the process exited.
2530    ///
2531    /// @return
2532    ///     The textual description of why the process exited, or NULL
2533    ///     if there is no description available.
2534    //------------------------------------------------------------------
2535    const char *
2536    GetExitDescription ();
2537
2538
2539    virtual void
2540    DidExit ()
2541    {
2542    }
2543
2544    //------------------------------------------------------------------
2545    /// Get the Modification ID of the process.
2546    ///
2547    /// @return
2548    ///     The modification ID of the process.
2549    //------------------------------------------------------------------
2550    ProcessModID
2551    GetModID () const
2552    {
2553        return m_mod_id;
2554    }
2555
2556    const ProcessModID &
2557    GetModIDRef () const
2558    {
2559        return m_mod_id;
2560    }
2561
2562    uint32_t
2563    GetStopID () const
2564    {
2565        return m_mod_id.GetStopID();
2566    }
2567
2568    uint32_t
2569    GetResumeID () const
2570    {
2571        return m_mod_id.GetResumeID();
2572    }
2573
2574    uint32_t
2575    GetLastUserExpressionResumeID () const
2576    {
2577        return m_mod_id.GetLastUserExpressionResumeID();
2578    }
2579
2580    uint32_t
2581    GetLastNaturalStopID()
2582    {
2583        return m_mod_id.GetLastNaturalStopID();
2584    }
2585
2586    //------------------------------------------------------------------
2587    /// Set accessor for the process exit status (return code).
2588    ///
2589    /// Sometimes a child exits and the exit can be detected by global
2590    /// functions (signal handler for SIGCHLD for example). This
2591    /// accessor allows the exit status to be set from an external
2592    /// source.
2593    ///
2594    /// Setting this will cause a eStateExited event to be posted to
2595    /// the process event queue.
2596    ///
2597    /// @param[in] exit_status
2598    ///     The value for the process's return code.
2599    ///
2600    /// @see lldb::StateType
2601    //------------------------------------------------------------------
2602    virtual bool
2603    SetExitStatus (int exit_status, const char *cstr);
2604
2605    //------------------------------------------------------------------
2606    /// Check if a process is still alive.
2607    ///
2608    /// @return
2609    ///     Returns \b true if the process is still valid, \b false
2610    ///     otherwise.
2611    //------------------------------------------------------------------
2612    virtual bool
2613    IsAlive () = 0;
2614
2615    //------------------------------------------------------------------
2616    /// Actually do the reading of memory from a process.
2617    ///
2618    /// Subclasses must override this function and can return fewer
2619    /// bytes than requested when memory requests are too large. This
2620    /// class will break up the memory requests and keep advancing the
2621    /// arguments along as needed.
2622    ///
2623    /// @param[in] vm_addr
2624    ///     A virtual load address that indicates where to start reading
2625    ///     memory from.
2626    ///
2627    /// @param[in] size
2628    ///     The number of bytes to read.
2629    ///
2630    /// @param[out] buf
2631    ///     A byte buffer that is at least \a size bytes long that
2632    ///     will receive the memory bytes.
2633    ///
2634    /// @return
2635    ///     The number of bytes that were actually read into \a buf.
2636    //------------------------------------------------------------------
2637    virtual size_t
2638    DoReadMemory (lldb::addr_t vm_addr,
2639                  void *buf,
2640                  size_t size,
2641                  Error &error) = 0;
2642
2643    //------------------------------------------------------------------
2644    /// Read of memory from a process.
2645    ///
2646    /// This function will read memory from the current process's
2647    /// address space and remove any traps that may have been inserted
2648    /// into the memory.
2649    ///
2650    /// This function is not meant to be overridden by Process
2651    /// subclasses, the subclasses should implement
2652    /// Process::DoReadMemory (lldb::addr_t, size_t, void *).
2653    ///
2654    /// @param[in] vm_addr
2655    ///     A virtual load address that indicates where to start reading
2656    ///     memory from.
2657    ///
2658    /// @param[out] buf
2659    ///     A byte buffer that is at least \a size bytes long that
2660    ///     will receive the memory bytes.
2661    ///
2662    /// @param[in] size
2663    ///     The number of bytes to read.
2664    ///
2665    /// @return
2666    ///     The number of bytes that were actually read into \a buf. If
2667    ///     the returned number is greater than zero, yet less than \a
2668    ///     size, then this function will get called again with \a
2669    ///     vm_addr, \a buf, and \a size updated appropriately. Zero is
2670    ///     returned to indicate an error.
2671    //------------------------------------------------------------------
2672    virtual size_t
2673    ReadMemory (lldb::addr_t vm_addr,
2674                void *buf,
2675                size_t size,
2676                Error &error);
2677
2678    //------------------------------------------------------------------
2679    /// Read a NULL terminated C string from memory
2680    ///
2681    /// This function will read a cache page at a time until the NULL
2682    /// C string terminator is found. It will stop reading if the NULL
2683    /// termination byte isn't found before reading \a cstr_max_len
2684    /// bytes, and the results are always guaranteed to be NULL
2685    /// terminated (at most cstr_max_len - 1 bytes will be read).
2686    //------------------------------------------------------------------
2687    size_t
2688    ReadCStringFromMemory (lldb::addr_t vm_addr,
2689                           char *cstr,
2690                           size_t cstr_max_len,
2691                           Error &error);
2692
2693    size_t
2694    ReadCStringFromMemory (lldb::addr_t vm_addr,
2695                           std::string &out_str,
2696                           Error &error);
2697
2698    size_t
2699    ReadMemoryFromInferior (lldb::addr_t vm_addr,
2700                            void *buf,
2701                            size_t size,
2702                            Error &error);
2703
2704    //------------------------------------------------------------------
2705    /// Reads an unsigned integer of the specified byte size from
2706    /// process memory.
2707    ///
2708    /// @param[in] load_addr
2709    ///     A load address of the integer to read.
2710    ///
2711    /// @param[in] byte_size
2712    ///     The size in byte of the integer to read.
2713    ///
2714    /// @param[in] fail_value
2715    ///     The value to return if we fail to read an integer.
2716    ///
2717    /// @param[out] error
2718    ///     An error that indicates the success or failure of this
2719    ///     operation. If error indicates success (error.Success()),
2720    ///     then the value returned can be trusted, otherwise zero
2721    ///     will be returned.
2722    ///
2723    /// @return
2724    ///     The unsigned integer that was read from the process memory
2725    ///     space. If the integer was smaller than a uint64_t, any
2726    ///     unused upper bytes will be zero filled. If the process
2727    ///     byte order differs from the host byte order, the integer
2728    ///     value will be appropriately byte swapped into host byte
2729    ///     order.
2730    //------------------------------------------------------------------
2731    uint64_t
2732    ReadUnsignedIntegerFromMemory (lldb::addr_t load_addr,
2733                                   size_t byte_size,
2734                                   uint64_t fail_value,
2735                                   Error &error);
2736
2737    lldb::addr_t
2738    ReadPointerFromMemory (lldb::addr_t vm_addr,
2739                           Error &error);
2740
2741    bool
2742    WritePointerToMemory (lldb::addr_t vm_addr,
2743                          lldb::addr_t ptr_value,
2744                          Error &error);
2745
2746    //------------------------------------------------------------------
2747    /// Actually do the writing of memory to a process.
2748    ///
2749    /// @param[in] vm_addr
2750    ///     A virtual load address that indicates where to start writing
2751    ///     memory to.
2752    ///
2753    /// @param[in] buf
2754    ///     A byte buffer that is at least \a size bytes long that
2755    ///     contains the data to write.
2756    ///
2757    /// @param[in] size
2758    ///     The number of bytes to write.
2759    ///
2760    /// @param[out] error
2761    ///     An error value in case the memory write fails.
2762    ///
2763    /// @return
2764    ///     The number of bytes that were actually written.
2765    //------------------------------------------------------------------
2766    virtual size_t
2767    DoWriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error)
2768    {
2769        error.SetErrorStringWithFormat("error: %s does not support writing to processes", GetShortPluginName());
2770        return 0;
2771    }
2772
2773
2774    //------------------------------------------------------------------
2775    /// Write all or part of a scalar value to memory.
2776    ///
2777    /// The value contained in \a scalar will be swapped to match the
2778    /// byte order of the process that is being debugged. If \a size is
2779    /// less than the size of scalar, the least significate \a size bytes
2780    /// from scalar will be written. If \a size is larger than the byte
2781    /// size of scalar, then the extra space will be padded with zeros
2782    /// and the scalar value will be placed in the least significant
2783    /// bytes in memory.
2784    ///
2785    /// @param[in] vm_addr
2786    ///     A virtual load address that indicates where to start writing
2787    ///     memory to.
2788    ///
2789    /// @param[in] scalar
2790    ///     The scalar to write to the debugged process.
2791    ///
2792    /// @param[in] size
2793    ///     This value can be smaller or larger than the scalar value
2794    ///     itself. If \a size is smaller than the size of \a scalar,
2795    ///     the least significant bytes in \a scalar will be used. If
2796    ///     \a size is larger than the byte size of \a scalar, then
2797    ///     the extra space will be padded with zeros. If \a size is
2798    ///     set to UINT32_MAX, then the size of \a scalar will be used.
2799    ///
2800    /// @param[out] error
2801    ///     An error value in case the memory write fails.
2802    ///
2803    /// @return
2804    ///     The number of bytes that were actually written.
2805    //------------------------------------------------------------------
2806    size_t
2807    WriteScalarToMemory (lldb::addr_t vm_addr,
2808                         const Scalar &scalar,
2809                         size_t size,
2810                         Error &error);
2811
2812    size_t
2813    ReadScalarIntegerFromMemory (lldb::addr_t addr,
2814                                 uint32_t byte_size,
2815                                 bool is_signed,
2816                                 Scalar &scalar,
2817                                 Error &error);
2818
2819    //------------------------------------------------------------------
2820    /// Write memory to a process.
2821    ///
2822    /// This function will write memory to the current process's
2823    /// address space and maintain any traps that might be present due
2824    /// to software breakpoints.
2825    ///
2826    /// This function is not meant to be overridden by Process
2827    /// subclasses, the subclasses should implement
2828    /// Process::DoWriteMemory (lldb::addr_t, size_t, void *).
2829    ///
2830    /// @param[in] vm_addr
2831    ///     A virtual load address that indicates where to start writing
2832    ///     memory to.
2833    ///
2834    /// @param[in] buf
2835    ///     A byte buffer that is at least \a size bytes long that
2836    ///     contains the data to write.
2837    ///
2838    /// @param[in] size
2839    ///     The number of bytes to write.
2840    ///
2841    /// @return
2842    ///     The number of bytes that were actually written.
2843    //------------------------------------------------------------------
2844    size_t
2845    WriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error);
2846
2847
2848    //------------------------------------------------------------------
2849    /// Actually allocate memory in the process.
2850    ///
2851    /// This function will allocate memory in the process's address
2852    /// space.  This can't rely on the generic function calling mechanism,
2853    /// since that requires this function.
2854    ///
2855    /// @param[in] size
2856    ///     The size of the allocation requested.
2857    ///
2858    /// @return
2859    ///     The address of the allocated buffer in the process, or
2860    ///     LLDB_INVALID_ADDRESS if the allocation failed.
2861    //------------------------------------------------------------------
2862
2863    virtual lldb::addr_t
2864    DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2865    {
2866        error.SetErrorStringWithFormat("error: %s does not support allocating in the debug process", GetShortPluginName());
2867        return LLDB_INVALID_ADDRESS;
2868    }
2869
2870
2871    //------------------------------------------------------------------
2872    /// The public interface to allocating memory in the process.
2873    ///
2874    /// This function will allocate memory in the process's address
2875    /// space.  This can't rely on the generic function calling mechanism,
2876    /// since that requires this function.
2877    ///
2878    /// @param[in] size
2879    ///     The size of the allocation requested.
2880    ///
2881    /// @param[in] permissions
2882    ///     Or together any of the lldb::Permissions bits.  The permissions on
2883    ///     a given memory allocation can't be changed after allocation.  Note
2884    ///     that a block that isn't set writable can still be written on from lldb,
2885    ///     just not by the process itself.
2886    ///
2887    /// @param[in/out] error
2888    ///     An error object to fill in if things go wrong.
2889    /// @return
2890    ///     The address of the allocated buffer in the process, or
2891    ///     LLDB_INVALID_ADDRESS if the allocation failed.
2892    //------------------------------------------------------------------
2893
2894    lldb::addr_t
2895    AllocateMemory (size_t size, uint32_t permissions, Error &error);
2896
2897
2898    //------------------------------------------------------------------
2899    /// Resolve dynamically loaded indirect functions.
2900    ///
2901    /// @param[in] address
2902    ///     The load address of the indirect function to resolve.
2903    ///
2904    /// @param[out] error
2905    ///     An error value in case the resolve fails.
2906    ///
2907    /// @return
2908    ///     The address of the resolved function.
2909    ///     LLDB_INVALID_ADDRESS if the resolution failed.
2910    //------------------------------------------------------------------
2911
2912    virtual lldb::addr_t
2913    ResolveIndirectFunction(const Address *address, Error &error)
2914    {
2915        error.SetErrorStringWithFormat("error: %s does not support indirect functions in the debug process", GetShortPluginName());
2916        return LLDB_INVALID_ADDRESS;
2917    }
2918
2919    virtual Error
2920    GetMemoryRegionInfo (lldb::addr_t load_addr,
2921                        MemoryRegionInfo &range_info)
2922    {
2923        Error error;
2924        error.SetErrorString ("Process::GetMemoryRegionInfo() not supported");
2925        return error;
2926    }
2927
2928    virtual Error
2929    GetWatchpointSupportInfo (uint32_t &num)
2930    {
2931        Error error;
2932        error.SetErrorString ("Process::GetWatchpointSupportInfo() not supported");
2933        return error;
2934    }
2935
2936    virtual Error
2937    GetWatchpointSupportInfo (uint32_t &num, bool& after)
2938    {
2939        Error error;
2940        error.SetErrorString ("Process::GetWatchpointSupportInfo() not supported");
2941        return error;
2942    }
2943
2944    lldb::ModuleSP
2945    ReadModuleFromMemory (const FileSpec& file_spec,
2946                          lldb::addr_t header_addr);
2947
2948    //------------------------------------------------------------------
2949    /// Attempt to get the attributes for a region of memory in the process.
2950    ///
2951    /// It may be possible for the remote debug server to inspect attributes
2952    /// for a region of memory in the process, such as whether there is a
2953    /// valid page of memory at a given address or whether that page is
2954    /// readable/writable/executable by the process.
2955    ///
2956    /// @param[in] load_addr
2957    ///     The address of interest in the process.
2958    ///
2959    /// @param[out] permissions
2960    ///     If this call returns successfully, this bitmask will have
2961    ///     its Permissions bits set to indicate whether the region is
2962    ///     readable/writable/executable.  If this call fails, the
2963    ///     bitmask values are undefined.
2964    ///
2965    /// @return
2966    ///     Returns true if it was able to determine the attributes of the
2967    ///     memory region.  False if not.
2968    //------------------------------------------------------------------
2969
2970    virtual bool
2971    GetLoadAddressPermissions (lldb::addr_t load_addr, uint32_t &permissions)
2972    {
2973        MemoryRegionInfo range_info;
2974        permissions = 0;
2975        Error error (GetMemoryRegionInfo (load_addr, range_info));
2976        if (!error.Success())
2977            return false;
2978        if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow
2979            || range_info.GetWritable() == MemoryRegionInfo::eDontKnow
2980            || range_info.GetExecutable() == MemoryRegionInfo::eDontKnow)
2981        {
2982            return false;
2983        }
2984
2985        if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2986            permissions |= lldb::ePermissionsReadable;
2987
2988        if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2989            permissions |= lldb::ePermissionsWritable;
2990
2991        if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2992            permissions |= lldb::ePermissionsExecutable;
2993
2994        return true;
2995    }
2996
2997    //------------------------------------------------------------------
2998    /// Determines whether executing JIT-compiled code in this process
2999    /// is possible.
3000    ///
3001    /// @return
3002    ///     True if execution of JIT code is possible; false otherwise.
3003    //------------------------------------------------------------------
3004    bool CanJIT ();
3005
3006    //------------------------------------------------------------------
3007    /// Sets whether executing JIT-compiled code in this process
3008    /// is possible.
3009    ///
3010    /// @param[in] can_jit
3011    ///     True if execution of JIT code is possible; false otherwise.
3012    //------------------------------------------------------------------
3013    void SetCanJIT (bool can_jit);
3014
3015    //------------------------------------------------------------------
3016    /// Actually deallocate memory in the process.
3017    ///
3018    /// This function will deallocate memory in the process's address
3019    /// space that was allocated with AllocateMemory.
3020    ///
3021    /// @param[in] ptr
3022    ///     A return value from AllocateMemory, pointing to the memory you
3023    ///     want to deallocate.
3024    ///
3025    /// @return
3026    ///     \btrue if the memory was deallocated, \bfalse otherwise.
3027    //------------------------------------------------------------------
3028
3029    virtual Error
3030    DoDeallocateMemory (lldb::addr_t ptr)
3031    {
3032        Error error;
3033        error.SetErrorStringWithFormat("error: %s does not support deallocating in the debug process", GetShortPluginName());
3034        return error;
3035    }
3036
3037
3038    //------------------------------------------------------------------
3039    /// The public interface to deallocating memory in the process.
3040    ///
3041    /// This function will deallocate memory in the process's address
3042    /// space that was allocated with AllocateMemory.
3043    ///
3044    /// @param[in] ptr
3045    ///     A return value from AllocateMemory, pointing to the memory you
3046    ///     want to deallocate.
3047    ///
3048    /// @return
3049    ///     \btrue if the memory was deallocated, \bfalse otherwise.
3050    //------------------------------------------------------------------
3051
3052    Error
3053    DeallocateMemory (lldb::addr_t ptr);
3054
3055    //------------------------------------------------------------------
3056    /// Get any available STDOUT.
3057    ///
3058    /// If the process was launched without supplying valid file paths
3059    /// for stdin, stdout, and stderr, then the Process class might
3060    /// try to cache the STDOUT for the process if it is able. Events
3061    /// will be queued indicating that there is STDOUT available that
3062    /// can be retrieved using this function.
3063    ///
3064    /// @param[out] buf
3065    ///     A buffer that will receive any STDOUT bytes that are
3066    ///     currently available.
3067    ///
3068    /// @param[out] buf_size
3069    ///     The size in bytes for the buffer \a buf.
3070    ///
3071    /// @return
3072    ///     The number of bytes written into \a buf. If this value is
3073    ///     equal to \a buf_size, another call to this function should
3074    ///     be made to retrieve more STDOUT data.
3075    //------------------------------------------------------------------
3076    virtual size_t
3077    GetSTDOUT (char *buf, size_t buf_size, Error &error);
3078
3079    //------------------------------------------------------------------
3080    /// Get any available STDERR.
3081    ///
3082    /// If the process was launched without supplying valid file paths
3083    /// for stdin, stdout, and stderr, then the Process class might
3084    /// try to cache the STDERR for the process if it is able. Events
3085    /// will be queued indicating that there is STDERR available that
3086    /// can be retrieved using this function.
3087    ///
3088    /// @param[out] buf
3089    ///     A buffer that will receive any STDERR bytes that are
3090    ///     currently available.
3091    ///
3092    /// @param[out] buf_size
3093    ///     The size in bytes for the buffer \a buf.
3094    ///
3095    /// @return
3096    ///     The number of bytes written into \a buf. If this value is
3097    ///     equal to \a buf_size, another call to this function should
3098    ///     be made to retrieve more STDERR data.
3099    //------------------------------------------------------------------
3100    virtual size_t
3101    GetSTDERR (char *buf, size_t buf_size, Error &error);
3102
3103    virtual size_t
3104    PutSTDIN (const char *buf, size_t buf_size, Error &error)
3105    {
3106        error.SetErrorString("stdin unsupported");
3107        return 0;
3108    }
3109
3110    //------------------------------------------------------------------
3111    /// Get any available profile data.
3112    ///
3113    /// @param[out] buf
3114    ///     A buffer that will receive any profile data bytes that are
3115    ///     currently available.
3116    ///
3117    /// @param[out] buf_size
3118    ///     The size in bytes for the buffer \a buf.
3119    ///
3120    /// @return
3121    ///     The number of bytes written into \a buf. If this value is
3122    ///     equal to \a buf_size, another call to this function should
3123    ///     be made to retrieve more profile data.
3124    //------------------------------------------------------------------
3125    virtual size_t
3126    GetAsyncProfileData (char *buf, size_t buf_size, Error &error);
3127
3128    //----------------------------------------------------------------------
3129    // Process Breakpoints
3130    //----------------------------------------------------------------------
3131    size_t
3132    GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site);
3133
3134    virtual Error
3135    EnableBreakpointSite (BreakpointSite *bp_site)
3136    {
3137        Error error;
3138        error.SetErrorStringWithFormat("error: %s does not support enabling breakpoints", GetShortPluginName());
3139        return error;
3140    }
3141
3142
3143    virtual Error
3144    DisableBreakpointSite (BreakpointSite *bp_site)
3145    {
3146        Error error;
3147        error.SetErrorStringWithFormat("error: %s does not support disabling breakpoints", GetShortPluginName());
3148        return error;
3149    }
3150
3151
3152    // This is implemented completely using the lldb::Process API. Subclasses
3153    // don't need to implement this function unless the standard flow of
3154    // read existing opcode, write breakpoint opcode, verify breakpoint opcode
3155    // doesn't work for a specific process plug-in.
3156    virtual Error
3157    EnableSoftwareBreakpoint (BreakpointSite *bp_site);
3158
3159    // This is implemented completely using the lldb::Process API. Subclasses
3160    // don't need to implement this function unless the standard flow of
3161    // restoring original opcode in memory and verifying the restored opcode
3162    // doesn't work for a specific process plug-in.
3163    virtual Error
3164    DisableSoftwareBreakpoint (BreakpointSite *bp_site);
3165
3166    BreakpointSiteList &
3167    GetBreakpointSiteList();
3168
3169    const BreakpointSiteList &
3170    GetBreakpointSiteList() const;
3171
3172    void
3173    DisableAllBreakpointSites ();
3174
3175    Error
3176    ClearBreakpointSiteByID (lldb::user_id_t break_id);
3177
3178    lldb::break_id_t
3179    CreateBreakpointSite (const lldb::BreakpointLocationSP &owner,
3180                          bool use_hardware);
3181
3182    Error
3183    DisableBreakpointSiteByID (lldb::user_id_t break_id);
3184
3185    Error
3186    EnableBreakpointSiteByID (lldb::user_id_t break_id);
3187
3188
3189    // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove
3190    // themselves from the owner's list of this breakpoint sites.  This has to
3191    // be a static function because you can't be sure that removing the
3192    // breakpoint from it's containing map won't delete the breakpoint site,
3193    // and doing that in an instance method isn't copasetic.
3194    void
3195    RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id,
3196                                   lldb::user_id_t owner_loc_id,
3197                                   lldb::BreakpointSiteSP &bp_site_sp);
3198
3199    //----------------------------------------------------------------------
3200    // Process Watchpoints (optional)
3201    //----------------------------------------------------------------------
3202    virtual Error
3203    EnableWatchpoint (Watchpoint *wp, bool notify = true);
3204
3205    virtual Error
3206    DisableWatchpoint (Watchpoint *wp, bool notify = true);
3207
3208    //------------------------------------------------------------------
3209    // Thread Queries
3210    //------------------------------------------------------------------
3211    virtual bool
3212    UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list) = 0;
3213
3214    void
3215    UpdateThreadListIfNeeded ();
3216
3217    ThreadList &
3218    GetThreadList ()
3219    {
3220        return m_thread_list;
3221    }
3222
3223    // This is obsoleted and will be removed very soon.
3224    uint32_t
3225    GetNextThreadIndexID ();
3226
3227    uint32_t
3228    GetNextThreadIndexID (uint64_t thread_id);
3229
3230    lldb::ThreadSP
3231    CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context);
3232
3233    // Returns true if an index id has been assigned to a thread.
3234    bool
3235    HasAssignedIndexIDToThread(uint64_t sb_thread_id);
3236
3237    // Given a thread_id, it will assign a more reasonable index id for display to the user.
3238    // If the thread_id has previously been assigned, the same index id will be used.
3239    uint32_t
3240    AssignIndexIDToThread(uint64_t thread_id);
3241
3242    //------------------------------------------------------------------
3243    // Event Handling
3244    //------------------------------------------------------------------
3245    lldb::StateType
3246    GetNextEvent (lldb::EventSP &event_sp);
3247
3248    lldb::StateType
3249    WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr = NULL);
3250
3251    lldb::StateType
3252    WaitForStateChangedEvents (const TimeValue *timeout, lldb::EventSP &event_sp);
3253
3254    Event *
3255    PeekAtStateChangedEvents ();
3256
3257
3258    class
3259    ProcessEventHijacker
3260    {
3261    public:
3262        ProcessEventHijacker (Process &process, Listener *listener) :
3263            m_process (process)
3264        {
3265            m_process.HijackProcessEvents (listener);
3266        }
3267        ~ProcessEventHijacker ()
3268        {
3269            m_process.RestoreProcessEvents();
3270        }
3271
3272    private:
3273        Process &m_process;
3274    };
3275    friend class ProcessEventHijacker;
3276    //------------------------------------------------------------------
3277    /// If you need to ensure that you and only you will hear about some public
3278    /// event, then make a new listener, set to listen to process events, and
3279    /// then call this with that listener.  Then you will have to wait on that
3280    /// listener explicitly for events (rather than using the GetNextEvent & WaitFor*
3281    /// calls above.  Be sure to call RestoreProcessEvents when you are done.
3282    ///
3283    /// @param[in] listener
3284    ///     This is the new listener to whom all process events will be delivered.
3285    ///
3286    /// @return
3287    ///     Returns \b true if the new listener could be installed,
3288    ///     \b false otherwise.
3289    //------------------------------------------------------------------
3290    bool
3291    HijackProcessEvents (Listener *listener);
3292
3293    //------------------------------------------------------------------
3294    /// Restores the process event broadcasting to its normal state.
3295    ///
3296    //------------------------------------------------------------------
3297    void
3298    RestoreProcessEvents ();
3299
3300protected:
3301    //------------------------------------------------------------------
3302    /// This is the part of the event handling that for a process event.
3303    /// It decides what to do with the event and returns true if the
3304    /// event needs to be propagated to the user, and false otherwise.
3305    /// If the event is not propagated, this call will most likely set
3306    /// the target to executing again.
3307    ///
3308    /// @param[in] event_ptr
3309    ///     This is the event we are handling.
3310    ///
3311    /// @return
3312    ///     Returns \b true if the event should be reported to the
3313    ///     user, \b false otherwise.
3314    //------------------------------------------------------------------
3315    bool
3316    ShouldBroadcastEvent (Event *event_ptr);
3317
3318public:
3319    const lldb::ABISP &
3320    GetABI ();
3321
3322    OperatingSystem *
3323    GetOperatingSystem ()
3324    {
3325        return m_os_ap.get();
3326    }
3327
3328
3329    virtual LanguageRuntime *
3330    GetLanguageRuntime (lldb::LanguageType language, bool retry_if_null = true);
3331
3332    virtual CPPLanguageRuntime *
3333    GetCPPLanguageRuntime (bool retry_if_null = true);
3334
3335    virtual ObjCLanguageRuntime *
3336    GetObjCLanguageRuntime (bool retry_if_null = true);
3337
3338    bool
3339    IsPossibleDynamicValue (ValueObject& in_value);
3340
3341    bool
3342    IsRunning () const;
3343
3344    DynamicCheckerFunctions *GetDynamicCheckers()
3345    {
3346        return m_dynamic_checkers_ap.get();
3347    }
3348
3349    void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
3350    {
3351        m_dynamic_checkers_ap.reset(dynamic_checkers);
3352    }
3353
3354    //------------------------------------------------------------------
3355    /// Call this to set the lldb in the mode where it breaks on new thread
3356    /// creations, and then auto-restarts.  This is useful when you are trying
3357    /// to run only one thread, but either that thread or the kernel is creating
3358    /// new threads in the process.  If you stop when the thread is created, you
3359    /// can immediately suspend it, and keep executing only the one thread you intend.
3360    ///
3361    /// @return
3362    ///     Returns \b true if we were able to start up the notification
3363    ///     \b false otherwise.
3364    //------------------------------------------------------------------
3365    virtual bool
3366    StartNoticingNewThreads()
3367    {
3368        return true;
3369    }
3370
3371    //------------------------------------------------------------------
3372    /// Call this to turn off the stop & notice new threads mode.
3373    ///
3374    /// @return
3375    ///     Returns \b true if we were able to start up the notification
3376    ///     \b false otherwise.
3377    //------------------------------------------------------------------
3378    virtual bool
3379    StopNoticingNewThreads()
3380    {
3381        return true;
3382    }
3383
3384    void
3385    SetRunningUserExpression (bool on);
3386
3387    //------------------------------------------------------------------
3388    // lldb::ExecutionContextScope pure virtual functions
3389    //------------------------------------------------------------------
3390    virtual lldb::TargetSP
3391    CalculateTarget ();
3392
3393    virtual lldb::ProcessSP
3394    CalculateProcess ()
3395    {
3396        return shared_from_this();
3397    }
3398
3399    virtual lldb::ThreadSP
3400    CalculateThread ()
3401    {
3402        return lldb::ThreadSP();
3403    }
3404
3405    virtual lldb::StackFrameSP
3406    CalculateStackFrame ()
3407    {
3408        return lldb::StackFrameSP();
3409    }
3410
3411    virtual void
3412    CalculateExecutionContext (ExecutionContext &exe_ctx);
3413
3414    void
3415    SetSTDIOFileDescriptor (int file_descriptor);
3416
3417    //------------------------------------------------------------------
3418    // Add a permanent region of memory that should never be read or
3419    // written to. This can be used to ensure that memory reads or writes
3420    // to certain areas of memory never end up being sent to the
3421    // DoReadMemory or DoWriteMemory functions which can improve
3422    // performance.
3423    //------------------------------------------------------------------
3424    void
3425    AddInvalidMemoryRegion (const LoadRange &region);
3426
3427    //------------------------------------------------------------------
3428    // Remove a permanent region of memory that should never be read or
3429    // written to that was previously added with AddInvalidMemoryRegion.
3430    //------------------------------------------------------------------
3431    bool
3432    RemoveInvalidMemoryRange (const LoadRange &region);
3433
3434    //------------------------------------------------------------------
3435    // If the setup code of a thread plan needs to do work that might involve
3436    // calling a function in the target, it should not do that work directly
3437    // in one of the thread plan functions (DidPush/WillResume) because
3438    // such work needs to be handled carefully.  Instead, put that work in
3439    // a PreResumeAction callback, and register it with the process.  It will
3440    // get done before the actual "DoResume" gets called.
3441    //------------------------------------------------------------------
3442
3443    typedef bool (PreResumeActionCallback)(void *);
3444
3445    void
3446    AddPreResumeAction (PreResumeActionCallback callback, void *baton);
3447
3448    bool
3449    RunPreResumeActions ();
3450
3451    void
3452    ClearPreResumeActions ();
3453
3454    ReadWriteLock &
3455    GetRunLock ()
3456    {
3457        return m_run_lock;
3458    }
3459
3460protected:
3461    //------------------------------------------------------------------
3462    // NextEventAction provides a way to register an action on the next
3463    // event that is delivered to this process.  There is currently only
3464    // one next event action allowed in the process at one time.  If a
3465    // new "NextEventAction" is added while one is already present, the
3466    // old action will be discarded (with HandleBeingUnshipped called
3467    // after it is discarded.)
3468    //------------------------------------------------------------------
3469    class NextEventAction
3470    {
3471    public:
3472        typedef enum EventActionResult
3473        {
3474            eEventActionSuccess,
3475            eEventActionRetry,
3476            eEventActionExit
3477        } EventActionResult;
3478
3479        NextEventAction (Process *process) :
3480            m_process(process)
3481        {
3482        }
3483
3484        virtual
3485        ~NextEventAction()
3486        {
3487        }
3488
3489        virtual EventActionResult PerformAction (lldb::EventSP &event_sp) = 0;
3490        virtual void HandleBeingUnshipped () {}
3491        virtual EventActionResult HandleBeingInterrupted () = 0;
3492        virtual const char *GetExitString() = 0;
3493    protected:
3494        Process *m_process;
3495    };
3496
3497    void SetNextEventAction (Process::NextEventAction *next_event_action)
3498    {
3499        if (m_next_event_action_ap.get())
3500            m_next_event_action_ap->HandleBeingUnshipped();
3501
3502        m_next_event_action_ap.reset(next_event_action);
3503    }
3504
3505    // This is the completer for Attaching:
3506    class AttachCompletionHandler : public NextEventAction
3507    {
3508    public:
3509        AttachCompletionHandler (Process *process, uint32_t exec_count) :
3510            NextEventAction (process),
3511            m_exec_count (exec_count)
3512        {
3513        }
3514
3515        virtual
3516        ~AttachCompletionHandler()
3517        {
3518        }
3519
3520        virtual EventActionResult PerformAction (lldb::EventSP &event_sp);
3521        virtual EventActionResult HandleBeingInterrupted ();
3522        virtual const char *GetExitString();
3523    private:
3524        uint32_t m_exec_count;
3525        std::string m_exit_string;
3526    };
3527
3528    bool
3529    HijackPrivateProcessEvents (Listener *listener);
3530
3531    void
3532    RestorePrivateProcessEvents ();
3533
3534    bool
3535    PrivateStateThreadIsValid () const
3536    {
3537        return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3538    }
3539
3540    //------------------------------------------------------------------
3541    // Type definitions
3542    //------------------------------------------------------------------
3543    typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP> LanguageRuntimeCollection;
3544
3545    struct PreResumeCallbackAndBaton
3546    {
3547        bool (*callback) (void *);
3548        void *baton;
3549        PreResumeCallbackAndBaton (PreResumeActionCallback in_callback, void *in_baton) :
3550            callback (in_callback),
3551            baton (in_baton)
3552        {
3553        }
3554    };
3555
3556    //------------------------------------------------------------------
3557    // Member variables
3558    //------------------------------------------------------------------
3559    Target &                    m_target;               ///< The target that owns this process.
3560    ThreadSafeValue<lldb::StateType>  m_public_state;
3561    ThreadSafeValue<lldb::StateType>  m_private_state; // The actual state of our process
3562    Broadcaster                 m_private_state_broadcaster;  // This broadcaster feeds state changed events into the private state thread's listener.
3563    Broadcaster                 m_private_state_control_broadcaster; // This is the control broadcaster, used to pause, resume & stop the private state thread.
3564    Listener                    m_private_state_listener;     // This is the listener for the private state thread.
3565    Predicate<bool>             m_private_state_control_wait; /// This Predicate is used to signal that a control operation is complete.
3566    lldb::thread_t              m_private_state_thread;  // Thread ID for the thread that watches interal state events
3567    ProcessModID                m_mod_id;               ///< Tracks the state of the process over stops and other alterations.
3568    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
3569    uint32_t                    m_thread_index_id;      ///< Each thread is created with a 1 based index that won't get re-used.
3570    std::map<uint64_t, uint32_t> m_thread_id_to_index_id_map;
3571    int                         m_exit_status;          ///< The exit status of the process, or -1 if not set.
3572    std::string                 m_exit_string;          ///< A textual description of why a process exited.
3573    ThreadList                  m_thread_list;          ///< The threads for this process.
3574    std::vector<Notifications>  m_notifications;        ///< The list of notifications that this process can deliver.
3575    std::vector<lldb::addr_t>   m_image_tokens;
3576    Listener                    &m_listener;
3577    BreakpointSiteList          m_breakpoint_site_list; ///< This is the list of breakpoint locations we intend to insert in the target.
3578    std::auto_ptr<DynamicLoader> m_dyld_ap;
3579    std::auto_ptr<DynamicCheckerFunctions> m_dynamic_checkers_ap; ///< The functions used by the expression parser to validate data that expressions use.
3580    std::auto_ptr<OperatingSystem> m_os_ap;
3581    UnixSignals                 m_unix_signals;         /// This is the current signal set for this process.
3582    lldb::ABISP                 m_abi_sp;
3583    lldb::InputReaderSP         m_process_input_reader;
3584    Communication               m_stdio_communication;
3585    Mutex                       m_stdio_communication_mutex;
3586    std::string                 m_stdout_data;
3587    std::string                 m_stderr_data;
3588    Mutex                       m_profile_data_comm_mutex;
3589    std::vector<std::string>    m_profile_data;
3590    MemoryCache                 m_memory_cache;
3591    AllocatedMemoryCache        m_allocated_memory_cache;
3592    bool                        m_should_detach;   /// Should we detach if the process object goes away with an explicit call to Kill or Detach?
3593    LanguageRuntimeCollection   m_language_runtimes;
3594    std::auto_ptr<NextEventAction> m_next_event_action_ap;
3595    std::vector<PreResumeCallbackAndBaton> m_pre_resume_actions;
3596    ReadWriteLock               m_run_lock;
3597    Predicate<bool>             m_currently_handling_event;
3598    bool                        m_finalize_called;
3599    lldb::StateType             m_last_broadcast_state;   /// This helps with the Public event coalescing in ShouldBroadcastEvent.
3600
3601    enum {
3602        eCanJITDontKnow= 0,
3603        eCanJITYes,
3604        eCanJITNo
3605    } m_can_jit;
3606
3607    size_t
3608    RemoveBreakpointOpcodesFromBuffer (lldb::addr_t addr, size_t size, uint8_t *buf) const;
3609
3610    void
3611    SynchronouslyNotifyStateChanged (lldb::StateType state);
3612
3613    void
3614    SetPublicState (lldb::StateType new_state);
3615
3616    void
3617    SetPrivateState (lldb::StateType state);
3618
3619    bool
3620    StartPrivateStateThread (bool force = false);
3621
3622    void
3623    StopPrivateStateThread ();
3624
3625    void
3626    PausePrivateStateThread ();
3627
3628    void
3629    ResumePrivateStateThread ();
3630
3631    static void *
3632    PrivateStateThread (void *arg);
3633
3634    void *
3635    RunPrivateStateThread ();
3636
3637    void
3638    HandlePrivateEvent (lldb::EventSP &event_sp);
3639
3640    lldb::StateType
3641    WaitForProcessStopPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
3642
3643    // This waits for both the state change broadcaster, and the control broadcaster.
3644    // If control_only, it only waits for the control broadcaster.
3645
3646    bool
3647    WaitForEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp, bool control_only);
3648
3649    lldb::StateType
3650    WaitForStateChangedEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
3651
3652    lldb::StateType
3653    WaitForState (const TimeValue *timeout,
3654                  const lldb::StateType *match_states,
3655                  const uint32_t num_match_states);
3656
3657    size_t
3658    WriteMemoryPrivate (lldb::addr_t addr, const void *buf, size_t size, Error &error);
3659
3660    void
3661    AppendSTDOUT (const char *s, size_t len);
3662
3663    void
3664    AppendSTDERR (const char *s, size_t len);
3665
3666    void
3667    BroadcastAsyncProfileData(const char *s, size_t len);
3668
3669    static void
3670    STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len);
3671
3672    void
3673    PushProcessInputReader ();
3674
3675    void
3676    PopProcessInputReader ();
3677
3678    void
3679    ResetProcessInputReader ();
3680
3681    static size_t
3682    ProcessInputReaderCallback (void *baton,
3683                                InputReader &reader,
3684                                lldb::InputReaderAction notification,
3685                                const char *bytes,
3686                                size_t bytes_len);
3687
3688
3689private:
3690    //------------------------------------------------------------------
3691    // For Process only
3692    //------------------------------------------------------------------
3693    void ControlPrivateStateThread (uint32_t signal);
3694
3695    DISALLOW_COPY_AND_ASSIGN (Process);
3696
3697};
3698
3699} // namespace lldb_private
3700
3701#endif  // liblldb_Process_h_
3702