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