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