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