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