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