Process.h revision fac2e62f08719ba800a440b7ad0d5a55a26dc620
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    /// Launch a new process.
1583    ///
1584    /// Launch a new process by spawning a new process using the
1585    /// target object's executable module's file as the file to launch.
1586    /// Arguments are given in \a argv, and the environment variables
1587    /// are in \a envp. Standard input and output files can be
1588    /// optionally re-directed to \a stdin_path, \a stdout_path, and
1589    /// \a stderr_path.
1590    ///
1591    /// This function is not meant to be overridden by Process
1592    /// subclasses. It will first call Process::WillLaunch (Module *)
1593    /// and if that returns \b true, Process::DoLaunch (Module*,
1594    /// char const *[],char const *[],const char *,const char *,
1595    /// const char *) will be called to actually do the launching. If
1596    /// DoLaunch returns \b true, then Process::DidLaunch() will be
1597    /// called.
1598    ///
1599    /// @param[in] argv
1600    ///     The argument array.
1601    ///
1602    /// @param[in] envp
1603    ///     The environment array.
1604    ///
1605    /// @param[in] launch_flags
1606    ///     Flags to modify the launch (@see lldb::LaunchFlags)
1607    ///
1608    /// @param[in] stdin_path
1609    ///     The path to use when re-directing the STDIN of the new
1610    ///     process. If all stdXX_path arguments are NULL, a pseudo
1611    ///     terminal will be used.
1612    ///
1613    /// @param[in] stdout_path
1614    ///     The path to use when re-directing the STDOUT of the new
1615    ///     process. If all stdXX_path arguments are NULL, a pseudo
1616    ///     terminal will be used.
1617    ///
1618    /// @param[in] stderr_path
1619    ///     The path to use when re-directing the STDERR of the new
1620    ///     process. If all stdXX_path arguments are NULL, a pseudo
1621    ///     terminal will be used.
1622    ///
1623    /// @param[in] working_directory
1624    ///     The working directory to have the child process run in
1625    ///
1626    /// @return
1627    ///     An error object. Call GetID() to get the process ID if
1628    ///     the error object is success.
1629    //------------------------------------------------------------------
1630    virtual Error
1631    Launch (const ProcessLaunchInfo &launch_info);
1632
1633    virtual Error
1634    LoadCore ();
1635
1636    virtual Error
1637    DoLoadCore ()
1638    {
1639        Error error;
1640        error.SetErrorStringWithFormat("error: %s does not support loading core files.", GetShortPluginName());
1641        return error;
1642    }
1643
1644    //------------------------------------------------------------------
1645    /// Get the dynamic loader plug-in for this process.
1646    ///
1647    /// The default action is to let the DynamicLoader plug-ins check
1648    /// the main executable and the DynamicLoader will select itself
1649    /// automatically. Subclasses can override this if inspecting the
1650    /// executable is not desired, or if Process subclasses can only
1651    /// use a specific DynamicLoader plug-in.
1652    //------------------------------------------------------------------
1653    virtual DynamicLoader *
1654    GetDynamicLoader ();
1655
1656    //------------------------------------------------------------------
1657    /// Attach to an existing process using the process attach info.
1658    ///
1659    /// This function is not meant to be overridden by Process
1660    /// subclasses. It will first call WillAttach (lldb::pid_t)
1661    /// or WillAttach (const char *), and if that returns \b
1662    /// true, DoAttach (lldb::pid_t) or DoAttach (const char *) will
1663    /// be called to actually do the attach. If DoAttach returns \b
1664    /// true, then Process::DidAttach() will be called.
1665    ///
1666    /// @param[in] pid
1667    ///     The process ID that we should attempt to attach to.
1668    ///
1669    /// @return
1670    ///     Returns \a pid if attaching was successful, or
1671    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
1672    //------------------------------------------------------------------
1673    virtual Error
1674    Attach (ProcessAttachInfo &attach_info);
1675
1676    //------------------------------------------------------------------
1677    /// Attach to a remote system via a URL
1678    ///
1679    /// @param[in] strm
1680    ///     A stream where output intended for the user
1681    ///     (if the driver has a way to display that) generated during
1682    ///     the connection.  This may be NULL if no output is needed.A
1683    ///
1684    /// @param[in] remote_url
1685    ///     The URL format that we are connecting to.
1686    ///
1687    /// @return
1688    ///     Returns an error object.
1689    //------------------------------------------------------------------
1690    virtual Error
1691    ConnectRemote (Stream *strm, const char *remote_url);
1692
1693    bool
1694    GetShouldDetach () const
1695    {
1696        return m_should_detach;
1697    }
1698
1699    void
1700    SetShouldDetach (bool b)
1701    {
1702        m_should_detach = b;
1703    }
1704
1705    //------------------------------------------------------------------
1706    /// Get the image information address for the current process.
1707    ///
1708    /// Some runtimes have system functions that can help dynamic
1709    /// loaders locate the dynamic loader information needed to observe
1710    /// shared libraries being loaded or unloaded. This function is
1711    /// in the Process interface (as opposed to the DynamicLoader
1712    /// interface) to ensure that remote debugging can take advantage of
1713    /// this functionality.
1714    ///
1715    /// @return
1716    ///     The address of the dynamic loader information, or
1717    ///     LLDB_INVALID_ADDRESS if this is not supported by this
1718    ///     interface.
1719    //------------------------------------------------------------------
1720    virtual lldb::addr_t
1721    GetImageInfoAddress ();
1722
1723    //------------------------------------------------------------------
1724    /// Load a shared library into this process.
1725    ///
1726    /// Try and load a shared library into the current process. This
1727    /// call might fail in the dynamic loader plug-in says it isn't safe
1728    /// to try and load shared libraries at the moment.
1729    ///
1730    /// @param[in] image_spec
1731    ///     The image file spec that points to the shared library that
1732    ///     you want to load.
1733    ///
1734    /// @param[out] error
1735    ///     An error object that gets filled in with any errors that
1736    ///     might occur when trying to load the shared library.
1737    ///
1738    /// @return
1739    ///     A token that represents the shared library that can be
1740    ///     later used to unload the shared library. A value of
1741    ///     LLDB_INVALID_IMAGE_TOKEN will be returned if the shared
1742    ///     library can't be opened.
1743    //------------------------------------------------------------------
1744    virtual uint32_t
1745    LoadImage (const FileSpec &image_spec, Error &error);
1746
1747    virtual Error
1748    UnloadImage (uint32_t image_token);
1749
1750    //------------------------------------------------------------------
1751    /// Register for process and thread notifications.
1752    ///
1753    /// Clients can register nofication callbacks by filling out a
1754    /// Process::Notifications structure and calling this function.
1755    ///
1756    /// @param[in] callbacks
1757    ///     A structure that contains the notification baton and
1758    ///     callback functions.
1759    ///
1760    /// @see Process::Notifications
1761    //------------------------------------------------------------------
1762#ifndef SWIG
1763    void
1764    RegisterNotificationCallbacks (const Process::Notifications& callbacks);
1765#endif
1766    //------------------------------------------------------------------
1767    /// Unregister for process and thread notifications.
1768    ///
1769    /// Clients can unregister nofication callbacks by passing a copy of
1770    /// the original baton and callbacks in \a callbacks.
1771    ///
1772    /// @param[in] callbacks
1773    ///     A structure that contains the notification baton and
1774    ///     callback functions.
1775    ///
1776    /// @return
1777    ///     Returns \b true if the notification callbacks were
1778    ///     successfully removed from the process, \b false otherwise.
1779    ///
1780    /// @see Process::Notifications
1781    //------------------------------------------------------------------
1782#ifndef SWIG
1783    bool
1784    UnregisterNotificationCallbacks (const Process::Notifications& callbacks);
1785#endif
1786    //==================================================================
1787    // Built in Process Control functions
1788    //==================================================================
1789    //------------------------------------------------------------------
1790    /// Resumes all of a process's threads as configured using the
1791    /// Thread run control functions.
1792    ///
1793    /// Threads for a process should be updated with one of the run
1794    /// control actions (resume, step, or suspend) that they should take
1795    /// when the process is resumed. If no run control action is given
1796    /// to a thread it will be resumed by default.
1797    ///
1798    /// This function is not meant to be overridden by Process
1799    /// subclasses. This function will take care of disabling any
1800    /// breakpoints that threads may be stopped at, single stepping, and
1801    /// re-enabling breakpoints, and enabling the basic flow control
1802    /// that the plug-in instances need not worry about.
1803    ///
1804    /// N.B. This function also sets the Write side of the Run Lock,
1805    /// which is unset when the corresponding stop event is pulled off
1806    /// the Public Event Queue.  If you need to resume the process without
1807    /// setting the Run Lock, use PrivateResume (though you should only do
1808    /// that from inside the Process class.
1809    ///
1810    /// @return
1811    ///     Returns an error object.
1812    ///
1813    /// @see Thread:Resume()
1814    /// @see Thread:Step()
1815    /// @see Thread:Suspend()
1816    //------------------------------------------------------------------
1817    Error
1818    Resume();
1819
1820    //------------------------------------------------------------------
1821    /// Halts a running process.
1822    ///
1823    /// This function is not meant to be overridden by Process
1824    /// subclasses.
1825    /// If the process is successfully halted, a eStateStopped
1826    /// process event with GetInterrupted will be broadcast.  If false, we will
1827    /// halt the process with no events generated by the halt.
1828    ///
1829    /// @return
1830    ///     Returns an error object.  If the error is empty, the process is halted.
1831    ///     otherwise the halt has failed.
1832    //------------------------------------------------------------------
1833    Error
1834    Halt ();
1835
1836    //------------------------------------------------------------------
1837    /// Detaches from a running or stopped process.
1838    ///
1839    /// This function is not meant to be overridden by Process
1840    /// subclasses.
1841    ///
1842    /// @return
1843    ///     Returns an error object.
1844    //------------------------------------------------------------------
1845    Error
1846    Detach ();
1847
1848    //------------------------------------------------------------------
1849    /// Kills the process and shuts down all threads that were spawned
1850    /// to track and monitor the process.
1851    ///
1852    /// This function is not meant to be overridden by Process
1853    /// subclasses.
1854    ///
1855    /// @return
1856    ///     Returns an error object.
1857    //------------------------------------------------------------------
1858    Error
1859    Destroy();
1860
1861    //------------------------------------------------------------------
1862    /// Sends a process a UNIX signal \a signal.
1863    ///
1864    /// This function is not meant to be overridden by Process
1865    /// subclasses.
1866    ///
1867    /// @return
1868    ///     Returns an error object.
1869    //------------------------------------------------------------------
1870    Error
1871    Signal (int signal);
1872
1873    virtual UnixSignals &
1874    GetUnixSignals ()
1875    {
1876        return m_unix_signals;
1877    }
1878
1879    //==================================================================
1880    // Plug-in Process Control Overrides
1881    //==================================================================
1882
1883    //------------------------------------------------------------------
1884    /// Called before attaching to a process.
1885    ///
1886    /// Allow Process plug-ins to execute some code before attaching a
1887    /// process.
1888    ///
1889    /// @return
1890    ///     Returns an error object.
1891    //------------------------------------------------------------------
1892    virtual Error
1893    WillAttachToProcessWithID (lldb::pid_t pid)
1894    {
1895        return Error();
1896    }
1897
1898    //------------------------------------------------------------------
1899    /// Called before attaching to a process.
1900    ///
1901    /// Allow Process plug-ins to execute some code before attaching a
1902    /// process.
1903    ///
1904    /// @return
1905    ///     Returns an error object.
1906    //------------------------------------------------------------------
1907    virtual Error
1908    WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
1909    {
1910        return Error();
1911    }
1912
1913    //------------------------------------------------------------------
1914    /// Attach to a remote system via a URL
1915    ///
1916    /// @param[in] strm
1917    ///     A stream where output intended for the user
1918    ///     (if the driver has a way to display that) generated during
1919    ///     the connection.  This may be NULL if no output is needed.A
1920    ///
1921    /// @param[in] remote_url
1922    ///     The URL format that we are connecting to.
1923    ///
1924    /// @return
1925    ///     Returns an error object.
1926    //------------------------------------------------------------------
1927    virtual Error
1928    DoConnectRemote (Stream *strm, const char *remote_url)
1929    {
1930        Error error;
1931        error.SetErrorString ("remote connections are not supported");
1932        return error;
1933    }
1934
1935    //------------------------------------------------------------------
1936    /// Attach to an existing process using a process ID.
1937    ///
1938    /// @param[in] pid
1939    ///     The process ID that we should attempt to attach to.
1940    ///
1941    /// @return
1942    ///     Returns \a pid if attaching was successful, or
1943    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
1944    //------------------------------------------------------------------
1945    virtual Error
1946    DoAttachToProcessWithID (lldb::pid_t pid)
1947    {
1948        Error error;
1949        error.SetErrorStringWithFormat("error: %s does not support attaching to a process by pid", GetShortPluginName());
1950        return error;
1951    }
1952
1953    //------------------------------------------------------------------
1954    /// Attach to an existing process using a process ID.
1955    ///
1956    /// @param[in] pid
1957    ///     The process ID that we should attempt to attach to.
1958    ///
1959    /// @param[in] attach_info
1960    ///     Information on how to do the attach. For example, GetUserID()
1961    ///     will return the uid to attach as.
1962    ///
1963    /// @return
1964    ///     Returns \a pid if attaching was successful, or
1965    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
1966    /// hanming : need flag
1967    //------------------------------------------------------------------
1968    virtual Error
1969    DoAttachToProcessWithID (lldb::pid_t pid,  const ProcessAttachInfo &attach_info)
1970    {
1971        Error error;
1972        error.SetErrorStringWithFormat("error: %s does not support attaching to a process by pid", GetShortPluginName());
1973        return error;
1974    }
1975
1976    //------------------------------------------------------------------
1977    /// Attach to an existing process using a partial process name.
1978    ///
1979    /// @param[in] process_name
1980    ///     The name of the process to attach to.
1981    ///
1982    /// @param[in] wait_for_launch
1983    ///     If \b true, wait for the process to be launched and attach
1984    ///     as soon as possible after it does launch. If \b false, then
1985    ///     search for a matching process the currently exists.
1986    ///
1987    /// @param[in] attach_info
1988    ///     Information on how to do the attach. For example, GetUserID()
1989    ///     will return the uid to attach as.
1990    ///
1991    /// @return
1992    ///     Returns \a pid if attaching was successful, or
1993    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
1994    //------------------------------------------------------------------
1995    virtual Error
1996    DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
1997    {
1998        Error error;
1999        error.SetErrorString("attach by name is not supported");
2000        return error;
2001    }
2002
2003    //------------------------------------------------------------------
2004    /// Called after attaching a process.
2005    ///
2006    /// Allow Process plug-ins to execute some code after attaching to
2007    /// a process.
2008    //------------------------------------------------------------------
2009    virtual void
2010    DidAttach () {}
2011
2012
2013    //------------------------------------------------------------------
2014    /// Called before launching to a process.
2015    ///
2016    /// Allow Process plug-ins to execute some code before launching a
2017    /// process.
2018    ///
2019    /// @return
2020    ///     Returns an error object.
2021    //------------------------------------------------------------------
2022    virtual Error
2023    WillLaunch (Module* module)
2024    {
2025        return Error();
2026    }
2027
2028    //------------------------------------------------------------------
2029    /// Launch a new process.
2030    ///
2031    /// Launch a new process by spawning a new process using \a module's
2032    /// file as the file to launch. Arguments are given in \a argv,
2033    /// and the environment variables are in \a envp. Standard input
2034    /// and output files can be optionally re-directed to \a stdin_path,
2035    /// \a stdout_path, and \a stderr_path.
2036    ///
2037    /// @param[in] module
2038    ///     The module from which to extract the file specification and
2039    ///     launch.
2040    ///
2041    /// @param[in] argv
2042    ///     The argument array.
2043    ///
2044    /// @param[in] envp
2045    ///     The environment array.
2046    ///
2047    /// @param[in] launch_flags
2048    ///     Flags to modify the launch (@see lldb::LaunchFlags)
2049    ///
2050    /// @param[in] stdin_path
2051    ///     The path to use when re-directing the STDIN of the new
2052    ///     process. If all stdXX_path arguments are NULL, a pseudo
2053    ///     terminal will be used.
2054    ///
2055    /// @param[in] stdout_path
2056    ///     The path to use when re-directing the STDOUT of the new
2057    ///     process. If all stdXX_path arguments are NULL, a pseudo
2058    ///     terminal will be used.
2059    ///
2060    /// @param[in] stderr_path
2061    ///     The path to use when re-directing the STDERR of the new
2062    ///     process. If all stdXX_path arguments are NULL, a pseudo
2063    ///     terminal will be used.
2064    ///
2065    /// @param[in] working_directory
2066    ///     The working directory to have the child process run in
2067    ///
2068    /// @return
2069    ///     A new valid process ID, or LLDB_INVALID_PROCESS_ID if
2070    ///     launching fails.
2071    //------------------------------------------------------------------
2072    virtual Error
2073    DoLaunch (Module *exe_module,
2074              const ProcessLaunchInfo &launch_info)
2075    {
2076        Error error;
2077        error.SetErrorStringWithFormat("error: %s does not support launching processes", GetShortPluginName());
2078        return error;
2079    }
2080
2081
2082    //------------------------------------------------------------------
2083    /// Called after launching a process.
2084    ///
2085    /// Allow Process plug-ins to execute some code after launching
2086    /// a process.
2087    //------------------------------------------------------------------
2088    virtual void
2089    DidLaunch () {}
2090
2091
2092
2093    //------------------------------------------------------------------
2094    /// Called before resuming to a process.
2095    ///
2096    /// Allow Process plug-ins to execute some code before resuming a
2097    /// process.
2098    ///
2099    /// @return
2100    ///     Returns an error object.
2101    //------------------------------------------------------------------
2102    virtual Error
2103    WillResume () { return Error(); }
2104
2105    //------------------------------------------------------------------
2106    /// Resumes all of a process's threads as configured using the
2107    /// Thread run control functions.
2108    ///
2109    /// Threads for a process should be updated with one of the run
2110    /// control actions (resume, step, or suspend) that they should take
2111    /// when the process is resumed. If no run control action is given
2112    /// to a thread it will be resumed by default.
2113    ///
2114    /// @return
2115    ///     Returns \b true if the process successfully resumes using
2116    ///     the thread run control actions, \b false otherwise.
2117    ///
2118    /// @see Thread:Resume()
2119    /// @see Thread:Step()
2120    /// @see Thread:Suspend()
2121    //------------------------------------------------------------------
2122    virtual Error
2123    DoResume ()
2124    {
2125        Error error;
2126        error.SetErrorStringWithFormat("error: %s does not support resuming processes", GetShortPluginName());
2127        return error;
2128    }
2129
2130
2131    //------------------------------------------------------------------
2132    /// Called after resuming a process.
2133    ///
2134    /// Allow Process plug-ins to execute some code after resuming
2135    /// a process.
2136    //------------------------------------------------------------------
2137    virtual void
2138    DidResume () {}
2139
2140
2141    //------------------------------------------------------------------
2142    /// Called before halting to a process.
2143    ///
2144    /// Allow Process plug-ins to execute some code before halting a
2145    /// process.
2146    ///
2147    /// @return
2148    ///     Returns an error object.
2149    //------------------------------------------------------------------
2150    virtual Error
2151    WillHalt () { return Error(); }
2152
2153    //------------------------------------------------------------------
2154    /// Halts a running process.
2155    ///
2156    /// DoHalt must produce one and only one stop StateChanged event if it actually
2157    /// stops the process.  If the stop happens through some natural event (for
2158    /// instance a SIGSTOP), then forwarding that event will do.  Otherwise, you must
2159    /// generate the event manually.  Note also, the private event thread is stopped when
2160    /// DoHalt is run to prevent the events generated while halting to trigger
2161    /// other state changes before the halt is complete.
2162    ///
2163    /// @param[out] caused_stop
2164    ///     If true, then this Halt caused the stop, otherwise, the
2165    ///     process was already stopped.
2166    ///
2167    /// @return
2168    ///     Returns \b true if the process successfully halts, \b false
2169    ///     otherwise.
2170    //------------------------------------------------------------------
2171    virtual Error
2172    DoHalt (bool &caused_stop)
2173    {
2174        Error error;
2175        error.SetErrorStringWithFormat("error: %s does not support halting processes", GetShortPluginName());
2176        return error;
2177    }
2178
2179
2180    //------------------------------------------------------------------
2181    /// Called after halting a process.
2182    ///
2183    /// Allow Process plug-ins to execute some code after halting
2184    /// a process.
2185    //------------------------------------------------------------------
2186    virtual void
2187    DidHalt () {}
2188
2189    //------------------------------------------------------------------
2190    /// Called before detaching from a process.
2191    ///
2192    /// Allow Process plug-ins to execute some code before detaching
2193    /// from a process.
2194    ///
2195    /// @return
2196    ///     Returns an error object.
2197    //------------------------------------------------------------------
2198    virtual Error
2199    WillDetach ()
2200    {
2201        return Error();
2202    }
2203
2204    //------------------------------------------------------------------
2205    /// Detaches from a running or stopped process.
2206    ///
2207    /// @return
2208    ///     Returns \b true if the process successfully detaches, \b
2209    ///     false otherwise.
2210    //------------------------------------------------------------------
2211    virtual Error
2212    DoDetach ()
2213    {
2214        Error error;
2215        error.SetErrorStringWithFormat("error: %s does not support detaching from processes", GetShortPluginName());
2216        return error;
2217    }
2218
2219
2220    //------------------------------------------------------------------
2221    /// Called after detaching from a process.
2222    ///
2223    /// Allow Process plug-ins to execute some code after detaching
2224    /// from a process.
2225    //------------------------------------------------------------------
2226    virtual void
2227    DidDetach () {}
2228
2229    //------------------------------------------------------------------
2230    /// Called before sending a signal to a process.
2231    ///
2232    /// Allow Process plug-ins to execute some code before sending a
2233    /// signal to a process.
2234    ///
2235    /// @return
2236    ///     Returns no error if it is safe to proceed with a call to
2237    ///     Process::DoSignal(int), otherwise an error describing what
2238    ///     prevents the signal from being sent.
2239    //------------------------------------------------------------------
2240    virtual Error
2241    WillSignal () { return Error(); }
2242
2243    //------------------------------------------------------------------
2244    /// Sends a process a UNIX signal \a signal.
2245    ///
2246    /// @return
2247    ///     Returns an error object.
2248    //------------------------------------------------------------------
2249    virtual Error
2250    DoSignal (int signal)
2251    {
2252        Error error;
2253        error.SetErrorStringWithFormat("error: %s does not support senging signals to processes", GetShortPluginName());
2254        return error;
2255    }
2256
2257    virtual Error
2258    WillDestroy () { return Error(); }
2259
2260    virtual Error
2261    DoDestroy () = 0;
2262
2263    virtual void
2264    DidDestroy () { }
2265
2266
2267    //------------------------------------------------------------------
2268    /// Called after sending a signal to a process.
2269    ///
2270    /// Allow Process plug-ins to execute some code after sending a
2271    /// signal to a process.
2272    //------------------------------------------------------------------
2273    virtual void
2274    DidSignal () {}
2275
2276    //------------------------------------------------------------------
2277    /// Currently called as part of ShouldStop.
2278    /// FIXME: Should really happen when the target stops before the
2279    /// event is taken from the queue...
2280    ///
2281    /// This callback is called as the event
2282    /// is about to be queued up to allow Process plug-ins to execute
2283    /// some code prior to clients being notified that a process was
2284    /// stopped. Common operations include updating the thread list,
2285    /// invalidating any thread state (registers, stack, etc) prior to
2286    /// letting the notification go out.
2287    ///
2288    //------------------------------------------------------------------
2289    virtual void
2290    RefreshStateAfterStop () = 0;
2291
2292    //------------------------------------------------------------------
2293    /// Get the target object pointer for this module.
2294    ///
2295    /// @return
2296    ///     A Target object pointer to the target that owns this
2297    ///     module.
2298    //------------------------------------------------------------------
2299    Target &
2300    GetTarget ()
2301    {
2302        return m_target;
2303    }
2304
2305    //------------------------------------------------------------------
2306    /// Get the const target object pointer for this module.
2307    ///
2308    /// @return
2309    ///     A const Target object pointer to the target that owns this
2310    ///     module.
2311    //------------------------------------------------------------------
2312    const Target &
2313    GetTarget () const
2314    {
2315        return m_target;
2316    }
2317
2318    //------------------------------------------------------------------
2319    /// Flush all data in the process.
2320    ///
2321    /// Flush the memory caches, all threads, and any other cached data
2322    /// in the process.
2323    ///
2324    /// This function can be called after a world changing event like
2325    /// adding a new symbol file, or after the process makes a large
2326    /// context switch (from boot ROM to booted into an OS).
2327    //------------------------------------------------------------------
2328    void
2329    Flush ();
2330
2331    //------------------------------------------------------------------
2332    /// Get accessor for the current process state.
2333    ///
2334    /// @return
2335    ///     The current state of the process.
2336    ///
2337    /// @see lldb::StateType
2338    //------------------------------------------------------------------
2339    lldb::StateType
2340    GetState ();
2341
2342    ExecutionResults
2343    RunThreadPlan (ExecutionContext &exe_ctx,
2344                    lldb::ThreadPlanSP &thread_plan_sp,
2345                    bool stop_others,
2346                    bool try_all_threads,
2347                    bool discard_on_error,
2348                    uint32_t single_thread_timeout_usec,
2349                    Stream &errors);
2350
2351    static const char *
2352    ExecutionResultAsCString (ExecutionResults result);
2353
2354    void
2355    GetStatus (Stream &ostrm);
2356
2357    size_t
2358    GetThreadStatus (Stream &ostrm,
2359                     bool only_threads_with_stop_reason,
2360                     uint32_t start_frame,
2361                     uint32_t num_frames,
2362                     uint32_t num_frames_with_source);
2363
2364    void
2365    SendAsyncInterrupt ();
2366
2367protected:
2368
2369    void
2370    SetState (lldb::EventSP &event_sp);
2371
2372    lldb::StateType
2373    GetPrivateState ();
2374
2375    //------------------------------------------------------------------
2376    /// The "private" side of resuming a process.  This doesn't alter the
2377    /// state of m_run_lock, but just causes the process to resume.
2378    ///
2379    /// @return
2380    ///     An Error object describing the success or failure of the resume.
2381    //------------------------------------------------------------------
2382    Error
2383    PrivateResume ();
2384
2385    //------------------------------------------------------------------
2386    // Called internally
2387    //------------------------------------------------------------------
2388    void
2389    CompleteAttach ();
2390
2391public:
2392    //------------------------------------------------------------------
2393    /// Get the exit status for a process.
2394    ///
2395    /// @return
2396    ///     The process's return code, or -1 if the current process
2397    ///     state is not eStateExited.
2398    //------------------------------------------------------------------
2399    int
2400    GetExitStatus ();
2401
2402    //------------------------------------------------------------------
2403    /// Get a textual description of what the process exited.
2404    ///
2405    /// @return
2406    ///     The textual description of why the process exited, or NULL
2407    ///     if there is no description available.
2408    //------------------------------------------------------------------
2409    const char *
2410    GetExitDescription ();
2411
2412
2413    virtual void
2414    DidExit ()
2415    {
2416    }
2417
2418    //------------------------------------------------------------------
2419    /// Get the Modification ID of the process.
2420    ///
2421    /// @return
2422    ///     The modification ID of the process.
2423    //------------------------------------------------------------------
2424    ProcessModID
2425    GetModID () const
2426    {
2427        return m_mod_id;
2428    }
2429
2430    const ProcessModID &
2431    GetModIDRef () const
2432    {
2433        return m_mod_id;
2434    }
2435
2436    uint32_t
2437    GetStopID () const
2438    {
2439        return m_mod_id.GetStopID();
2440    }
2441
2442    uint32_t
2443    GetResumeID () const
2444    {
2445        return m_mod_id.GetResumeID();
2446    }
2447
2448    uint32_t
2449    GetLastUserExpressionResumeID () const
2450    {
2451        return m_mod_id.GetLastUserExpressionResumeID();
2452    }
2453
2454    //------------------------------------------------------------------
2455    /// Set accessor for the process exit status (return code).
2456    ///
2457    /// Sometimes a child exits and the exit can be detected by global
2458    /// functions (signal handler for SIGCHLD for example). This
2459    /// accessor allows the exit status to be set from an external
2460    /// source.
2461    ///
2462    /// Setting this will cause a eStateExited event to be posted to
2463    /// the process event queue.
2464    ///
2465    /// @param[in] exit_status
2466    ///     The value for the process's return code.
2467    ///
2468    /// @see lldb::StateType
2469    //------------------------------------------------------------------
2470    virtual bool
2471    SetExitStatus (int exit_status, const char *cstr);
2472
2473    //------------------------------------------------------------------
2474    /// Check if a process is still alive.
2475    ///
2476    /// @return
2477    ///     Returns \b true if the process is still valid, \b false
2478    ///     otherwise.
2479    //------------------------------------------------------------------
2480    virtual bool
2481    IsAlive () = 0;
2482
2483    //------------------------------------------------------------------
2484    /// Actually do the reading of memory from a process.
2485    ///
2486    /// Subclasses must override this function and can return fewer
2487    /// bytes than requested when memory requests are too large. This
2488    /// class will break up the memory requests and keep advancing the
2489    /// arguments along as needed.
2490    ///
2491    /// @param[in] vm_addr
2492    ///     A virtual load address that indicates where to start reading
2493    ///     memory from.
2494    ///
2495    /// @param[in] size
2496    ///     The number of bytes to read.
2497    ///
2498    /// @param[out] buf
2499    ///     A byte buffer that is at least \a size bytes long that
2500    ///     will receive the memory bytes.
2501    ///
2502    /// @return
2503    ///     The number of bytes that were actually read into \a buf.
2504    //------------------------------------------------------------------
2505    virtual size_t
2506    DoReadMemory (lldb::addr_t vm_addr,
2507                  void *buf,
2508                  size_t size,
2509                  Error &error) = 0;
2510
2511    //------------------------------------------------------------------
2512    /// Read of memory from a process.
2513    ///
2514    /// This function will read memory from the current process's
2515    /// address space and remove any traps that may have been inserted
2516    /// into the memory.
2517    ///
2518    /// This function is not meant to be overridden by Process
2519    /// subclasses, the subclasses should implement
2520    /// Process::DoReadMemory (lldb::addr_t, size_t, void *).
2521    ///
2522    /// @param[in] vm_addr
2523    ///     A virtual load address that indicates where to start reading
2524    ///     memory from.
2525    ///
2526    /// @param[out] buf
2527    ///     A byte buffer that is at least \a size bytes long that
2528    ///     will receive the memory bytes.
2529    ///
2530    /// @param[in] size
2531    ///     The number of bytes to read.
2532    ///
2533    /// @return
2534    ///     The number of bytes that were actually read into \a buf. If
2535    ///     the returned number is greater than zero, yet less than \a
2536    ///     size, then this function will get called again with \a
2537    ///     vm_addr, \a buf, and \a size updated appropriately. Zero is
2538    ///     returned to indicate an error.
2539    //------------------------------------------------------------------
2540    virtual size_t
2541    ReadMemory (lldb::addr_t vm_addr,
2542                void *buf,
2543                size_t size,
2544                Error &error);
2545
2546    //------------------------------------------------------------------
2547    /// Read a NULL terminated C string from memory
2548    ///
2549    /// This function will read a cache page at a time until the NULL
2550    /// C stirng terminator is found. It will stop reading if the NULL
2551    /// termination byte isn't found before reading \a cstr_max_len
2552    /// bytes, and the results are always guaranteed to be NULL
2553    /// terminated (at most cstr_max_len - 1 bytes will be read).
2554    //------------------------------------------------------------------
2555    size_t
2556    ReadCStringFromMemory (lldb::addr_t vm_addr,
2557                           char *cstr,
2558                           size_t cstr_max_len,
2559                           Error &error);
2560
2561    size_t
2562    ReadCStringFromMemory (lldb::addr_t vm_addr,
2563                           std::string &out_str,
2564                           Error &error);
2565
2566    size_t
2567    ReadMemoryFromInferior (lldb::addr_t vm_addr,
2568                            void *buf,
2569                            size_t size,
2570                            Error &error);
2571
2572    //------------------------------------------------------------------
2573    /// Reads an unsigned integer of the specified byte size from
2574    /// process memory.
2575    ///
2576    /// @param[in] load_addr
2577    ///     A load address of the integer to read.
2578    ///
2579    /// @param[in] byte_size
2580    ///     The size in byte of the integer to read.
2581    ///
2582    /// @param[in] fail_value
2583    ///     The value to return if we fail to read an integer.
2584    ///
2585    /// @param[out] error
2586    ///     An error that indicates the success or failure of this
2587    ///     operation. If error indicates success (error.Success()),
2588    ///     then the value returned can be trusted, otherwise zero
2589    ///     will be returned.
2590    ///
2591    /// @return
2592    ///     The unsigned integer that was read from the process memory
2593    ///     space. If the integer was smaller than a uint64_t, any
2594    ///     unused upper bytes will be zero filled. If the process
2595    ///     byte order differs from the host byte order, the integer
2596    ///     value will be appropriately byte swapped into host byte
2597    ///     order.
2598    //------------------------------------------------------------------
2599    uint64_t
2600    ReadUnsignedIntegerFromMemory (lldb::addr_t load_addr,
2601                                   size_t byte_size,
2602                                   uint64_t fail_value,
2603                                   Error &error);
2604
2605    lldb::addr_t
2606    ReadPointerFromMemory (lldb::addr_t vm_addr,
2607                           Error &error);
2608
2609    bool
2610    WritePointerToMemory (lldb::addr_t vm_addr,
2611                          lldb::addr_t ptr_value,
2612                          Error &error);
2613
2614    //------------------------------------------------------------------
2615    /// Actually do the writing of memory to a process.
2616    ///
2617    /// @param[in] vm_addr
2618    ///     A virtual load address that indicates where to start writing
2619    ///     memory to.
2620    ///
2621    /// @param[in] buf
2622    ///     A byte buffer that is at least \a size bytes long that
2623    ///     contains the data to write.
2624    ///
2625    /// @param[in] size
2626    ///     The number of bytes to write.
2627    ///
2628    /// @param[out] error
2629    ///     An error value in case the memory write fails.
2630    ///
2631    /// @return
2632    ///     The number of bytes that were actually written.
2633    //------------------------------------------------------------------
2634    virtual size_t
2635    DoWriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error)
2636    {
2637        error.SetErrorStringWithFormat("error: %s does not support writing to processes", GetShortPluginName());
2638        return 0;
2639    }
2640
2641
2642    //------------------------------------------------------------------
2643    /// Write all or part of a scalar value to memory.
2644    ///
2645    /// The value contained in \a scalar will be swapped to match the
2646    /// byte order of the process that is being debugged. If \a size is
2647    /// less than the size of scalar, the least significate \a size bytes
2648    /// from scalar will be written. If \a size is larger than the byte
2649    /// size of scalar, then the extra space will be padded with zeros
2650    /// and the scalar value will be placed in the least significant
2651    /// bytes in memory.
2652    ///
2653    /// @param[in] vm_addr
2654    ///     A virtual load address that indicates where to start writing
2655    ///     memory to.
2656    ///
2657    /// @param[in] scalar
2658    ///     The scalar to write to the debugged process.
2659    ///
2660    /// @param[in] size
2661    ///     This value can be smaller or larger than the scalar value
2662    ///     itself. If \a size is smaller than the size of \a scalar,
2663    ///     the least significant bytes in \a scalar will be used. If
2664    ///     \a size is larger than the byte size of \a scalar, then
2665    ///     the extra space will be padded with zeros. If \a size is
2666    ///     set to UINT32_MAX, then the size of \a scalar will be used.
2667    ///
2668    /// @param[out] error
2669    ///     An error value in case the memory write fails.
2670    ///
2671    /// @return
2672    ///     The number of bytes that were actually written.
2673    //------------------------------------------------------------------
2674    size_t
2675    WriteScalarToMemory (lldb::addr_t vm_addr,
2676                         const Scalar &scalar,
2677                         uint32_t size,
2678                         Error &error);
2679
2680    size_t
2681    ReadScalarIntegerFromMemory (lldb::addr_t addr,
2682                                 uint32_t byte_size,
2683                                 bool is_signed,
2684                                 Scalar &scalar,
2685                                 Error &error);
2686
2687    //------------------------------------------------------------------
2688    /// Write memory to a process.
2689    ///
2690    /// This function will write memory to the current process's
2691    /// address space and maintain any traps that might be present due
2692    /// to software breakpoints.
2693    ///
2694    /// This function is not meant to be overridden by Process
2695    /// subclasses, the subclasses should implement
2696    /// Process::DoWriteMemory (lldb::addr_t, size_t, void *).
2697    ///
2698    /// @param[in] vm_addr
2699    ///     A virtual load address that indicates where to start writing
2700    ///     memory to.
2701    ///
2702    /// @param[in] buf
2703    ///     A byte buffer that is at least \a size bytes long that
2704    ///     contains the data to write.
2705    ///
2706    /// @param[in] size
2707    ///     The number of bytes to write.
2708    ///
2709    /// @return
2710    ///     The number of bytes that were actually written.
2711    //------------------------------------------------------------------
2712    size_t
2713    WriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error);
2714
2715
2716    //------------------------------------------------------------------
2717    /// Actually allocate memory in the process.
2718    ///
2719    /// This function will allocate memory in the process's address
2720    /// space.  This can't rely on the generic function calling mechanism,
2721    /// since that requires this function.
2722    ///
2723    /// @param[in] size
2724    ///     The size of the allocation requested.
2725    ///
2726    /// @return
2727    ///     The address of the allocated buffer in the process, or
2728    ///     LLDB_INVALID_ADDRESS if the allocation failed.
2729    //------------------------------------------------------------------
2730
2731    virtual lldb::addr_t
2732    DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2733    {
2734        error.SetErrorStringWithFormat("error: %s does not support allocating in the debug process", GetShortPluginName());
2735        return LLDB_INVALID_ADDRESS;
2736    }
2737
2738
2739    //------------------------------------------------------------------
2740    /// The public interface to allocating memory in the process.
2741    ///
2742    /// This function will allocate memory in the process's address
2743    /// space.  This can't rely on the generic function calling mechanism,
2744    /// since that requires this function.
2745    ///
2746    /// @param[in] size
2747    ///     The size of the allocation requested.
2748    ///
2749    /// @param[in] permissions
2750    ///     Or together any of the lldb::Permissions bits.  The permissions on
2751    ///     a given memory allocation can't be changed after allocation.  Note
2752    ///     that a block that isn't set writable can still be written on from lldb,
2753    ///     just not by the process itself.
2754    ///
2755    /// @param[in/out] error
2756    ///     An error object to fill in if things go wrong.
2757    /// @return
2758    ///     The address of the allocated buffer in the process, or
2759    ///     LLDB_INVALID_ADDRESS if the allocation failed.
2760    //------------------------------------------------------------------
2761
2762    lldb::addr_t
2763    AllocateMemory (size_t size, uint32_t permissions, Error &error);
2764
2765    virtual Error
2766    GetMemoryRegionInfo (lldb::addr_t load_addr,
2767                        MemoryRegionInfo &range_info)
2768    {
2769        Error error;
2770        error.SetErrorString ("Process::GetMemoryRegionInfo() not supported");
2771        return error;
2772    }
2773
2774    virtual Error
2775    GetWatchpointSupportInfo (uint32_t &num)
2776    {
2777        Error error;
2778        error.SetErrorString ("Process::GetWatchpointSupportInfo() not supported");
2779        return error;
2780    }
2781
2782    virtual Error
2783    GetWatchpointSupportInfo (uint32_t &num, bool& after)
2784    {
2785        Error error;
2786        error.SetErrorString ("Process::GetWatchpointSupportInfo() not supported");
2787        return error;
2788    }
2789
2790    lldb::ModuleSP
2791    ReadModuleFromMemory (const FileSpec& file_spec,
2792                          lldb::addr_t header_addr,
2793                          bool add_image_to_target,
2794                          bool load_sections_in_target);
2795
2796    //------------------------------------------------------------------
2797    /// Attempt to get the attributes for a region of memory in the process.
2798    ///
2799    /// It may be possible for the remote debug server to inspect attributes
2800    /// for a region of memory in the process, such as whether there is a
2801    /// valid page of memory at a given address or whether that page is
2802    /// readable/writable/executable by the process.
2803    ///
2804    /// @param[in] load_addr
2805    ///     The address of interest in the process.
2806    ///
2807    /// @param[out] permissions
2808    ///     If this call returns successfully, this bitmask will have
2809    ///     its Permissions bits set to indicate whether the region is
2810    ///     readable/writable/executable.  If this call fails, the
2811    ///     bitmask values are undefined.
2812    ///
2813    /// @return
2814    ///     Returns true if it was able to determine the attributes of the
2815    ///     memory region.  False if not.
2816    //------------------------------------------------------------------
2817
2818    virtual bool
2819    GetLoadAddressPermissions (lldb::addr_t load_addr, uint32_t &permissions)
2820    {
2821        MemoryRegionInfo range_info;
2822        permissions = 0;
2823        Error error (GetMemoryRegionInfo (load_addr, range_info));
2824        if (!error.Success())
2825            return false;
2826        if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow
2827            || range_info.GetWritable() == MemoryRegionInfo::eDontKnow
2828            || range_info.GetExecutable() == MemoryRegionInfo::eDontKnow)
2829        {
2830            return false;
2831        }
2832
2833        if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2834            permissions |= lldb::ePermissionsReadable;
2835
2836        if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2837            permissions |= lldb::ePermissionsWritable;
2838
2839        if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2840            permissions |= lldb::ePermissionsExecutable;
2841
2842        return true;
2843    }
2844
2845    //------------------------------------------------------------------
2846    /// Determines whether executing JIT-compiled code in this process
2847    /// is possible.
2848    ///
2849    /// @return
2850    ///     True if execution of JIT code is possible; false otherwise.
2851    //------------------------------------------------------------------
2852    bool CanJIT ();
2853
2854    //------------------------------------------------------------------
2855    /// Sets whether executing JIT-compiled code in this process
2856    /// is possible.
2857    ///
2858    /// @param[in] can_jit
2859    ///     True if execution of JIT code is possible; false otherwise.
2860    //------------------------------------------------------------------
2861    void SetCanJIT (bool can_jit);
2862
2863    //------------------------------------------------------------------
2864    /// Actually deallocate memory in the process.
2865    ///
2866    /// This function will deallocate memory in the process's address
2867    /// space that was allocated with AllocateMemory.
2868    ///
2869    /// @param[in] ptr
2870    ///     A return value from AllocateMemory, pointing to the memory you
2871    ///     want to deallocate.
2872    ///
2873    /// @return
2874    ///     \btrue if the memory was deallocated, \bfalse otherwise.
2875    //------------------------------------------------------------------
2876
2877    virtual Error
2878    DoDeallocateMemory (lldb::addr_t ptr)
2879    {
2880        Error error;
2881        error.SetErrorStringWithFormat("error: %s does not support deallocating in the debug process", GetShortPluginName());
2882        return error;
2883    }
2884
2885
2886    //------------------------------------------------------------------
2887    /// The public interface to deallocating memory in the process.
2888    ///
2889    /// This function will deallocate memory in the process's address
2890    /// space that was allocated with AllocateMemory.
2891    ///
2892    /// @param[in] ptr
2893    ///     A return value from AllocateMemory, pointing to the memory you
2894    ///     want to deallocate.
2895    ///
2896    /// @return
2897    ///     \btrue if the memory was deallocated, \bfalse otherwise.
2898    //------------------------------------------------------------------
2899
2900    Error
2901    DeallocateMemory (lldb::addr_t ptr);
2902
2903    //------------------------------------------------------------------
2904    /// Get any available STDOUT.
2905    ///
2906    /// If the process was launched without supplying valid file paths
2907    /// for stdin, stdout, and stderr, then the Process class might
2908    /// try to cache the STDOUT for the process if it is able. Events
2909    /// will be queued indicating that there is STDOUT available that
2910    /// can be retrieved using this function.
2911    ///
2912    /// @param[out] buf
2913    ///     A buffer that will receive any STDOUT bytes that are
2914    ///     currently available.
2915    ///
2916    /// @param[out] buf_size
2917    ///     The size in bytes for the buffer \a buf.
2918    ///
2919    /// @return
2920    ///     The number of bytes written into \a buf. If this value is
2921    ///     equal to \a buf_size, another call to this function should
2922    ///     be made to retrieve more STDOUT data.
2923    //------------------------------------------------------------------
2924    virtual size_t
2925    GetSTDOUT (char *buf, size_t buf_size, Error &error);
2926
2927    //------------------------------------------------------------------
2928    /// Get any available STDERR.
2929    ///
2930    /// If the process was launched without supplying valid file paths
2931    /// for stdin, stdout, and stderr, then the Process class might
2932    /// try to cache the STDERR for the process if it is able. Events
2933    /// will be queued indicating that there is STDERR available that
2934    /// can be retrieved using this function.
2935    ///
2936    /// @param[out] buf
2937    ///     A buffer that will receive any STDERR bytes that are
2938    ///     currently available.
2939    ///
2940    /// @param[out] buf_size
2941    ///     The size in bytes for the buffer \a buf.
2942    ///
2943    /// @return
2944    ///     The number of bytes written into \a buf. If this value is
2945    ///     equal to \a buf_size, another call to this function should
2946    ///     be made to retrieve more STDERR data.
2947    //------------------------------------------------------------------
2948    virtual size_t
2949    GetSTDERR (char *buf, size_t buf_size, Error &error);
2950
2951    virtual size_t
2952    PutSTDIN (const char *buf, size_t buf_size, Error &error)
2953    {
2954        error.SetErrorString("stdin unsupported");
2955        return 0;
2956    }
2957
2958    //----------------------------------------------------------------------
2959    // Process Breakpoints
2960    //----------------------------------------------------------------------
2961    size_t
2962    GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site);
2963
2964    virtual Error
2965    EnableBreakpoint (BreakpointSite *bp_site)
2966    {
2967        Error error;
2968        error.SetErrorStringWithFormat("error: %s does not support enabling breakpoints", GetShortPluginName());
2969        return error;
2970    }
2971
2972
2973    virtual Error
2974    DisableBreakpoint (BreakpointSite *bp_site)
2975    {
2976        Error error;
2977        error.SetErrorStringWithFormat("error: %s does not support disabling breakpoints", GetShortPluginName());
2978        return error;
2979    }
2980
2981
2982    // This is implemented completely using the lldb::Process API. Subclasses
2983    // don't need to implement this function unless the standard flow of
2984    // read existing opcode, write breakpoint opcode, verify breakpoint opcode
2985    // doesn't work for a specific process plug-in.
2986    virtual Error
2987    EnableSoftwareBreakpoint (BreakpointSite *bp_site);
2988
2989    // This is implemented completely using the lldb::Process API. Subclasses
2990    // don't need to implement this function unless the standard flow of
2991    // restoring original opcode in memory and verifying the restored opcode
2992    // doesn't work for a specific process plug-in.
2993    virtual Error
2994    DisableSoftwareBreakpoint (BreakpointSite *bp_site);
2995
2996    BreakpointSiteList &
2997    GetBreakpointSiteList();
2998
2999    const BreakpointSiteList &
3000    GetBreakpointSiteList() const;
3001
3002    void
3003    DisableAllBreakpointSites ();
3004
3005    Error
3006    ClearBreakpointSiteByID (lldb::user_id_t break_id);
3007
3008    lldb::break_id_t
3009    CreateBreakpointSite (const lldb::BreakpointLocationSP &owner,
3010                          bool use_hardware);
3011
3012    Error
3013    DisableBreakpointSiteByID (lldb::user_id_t break_id);
3014
3015    Error
3016    EnableBreakpointSiteByID (lldb::user_id_t break_id);
3017
3018
3019    // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove
3020    // themselves from the owner's list of this breakpoint sites.  This has to
3021    // be a static function because you can't be sure that removing the
3022    // breakpoint from it's containing map won't delete the breakpoint site,
3023    // and doing that in an instance method isn't copasetic.
3024    void
3025    RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id,
3026                                   lldb::user_id_t owner_loc_id,
3027                                   lldb::BreakpointSiteSP &bp_site_sp);
3028
3029    //----------------------------------------------------------------------
3030    // Process Watchpoints (optional)
3031    //----------------------------------------------------------------------
3032    virtual Error
3033    EnableWatchpoint (Watchpoint *wp);
3034
3035    virtual Error
3036    DisableWatchpoint (Watchpoint *wp);
3037
3038    //------------------------------------------------------------------
3039    // Thread Queries
3040    //------------------------------------------------------------------
3041    virtual bool
3042    UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list) = 0;
3043
3044    void
3045    UpdateThreadListIfNeeded ();
3046
3047    ThreadList &
3048    GetThreadList ()
3049    {
3050        return m_thread_list;
3051    }
3052
3053
3054    uint32_t
3055    GetNextThreadIndexID ();
3056
3057    //------------------------------------------------------------------
3058    // Event Handling
3059    //------------------------------------------------------------------
3060    lldb::StateType
3061    GetNextEvent (lldb::EventSP &event_sp);
3062
3063    lldb::StateType
3064    WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr = NULL);
3065
3066    lldb::StateType
3067    WaitForStateChangedEvents (const TimeValue *timeout, lldb::EventSP &event_sp);
3068
3069    Event *
3070    PeekAtStateChangedEvents ();
3071
3072
3073    class
3074    ProcessEventHijacker
3075    {
3076    public:
3077        ProcessEventHijacker (Process &process, Listener *listener) :
3078            m_process (process),
3079            m_listener (listener)
3080        {
3081            m_process.HijackProcessEvents (listener);
3082        }
3083        ~ProcessEventHijacker ()
3084        {
3085            m_process.RestoreProcessEvents();
3086        }
3087
3088    private:
3089        Process &m_process;
3090        Listener *m_listener;
3091    };
3092    friend class ProcessEventHijacker;
3093    //------------------------------------------------------------------
3094    /// If you need to ensure that you and only you will hear about some public
3095    /// event, then make a new listener, set to listen to process events, and
3096    /// then call this with that listener.  Then you will have to wait on that
3097    /// listener explicitly for events (rather than using the GetNextEvent & WaitFor*
3098    /// calls above.  Be sure to call RestoreProcessEvents when you are done.
3099    ///
3100    /// @param[in] listener
3101    ///     This is the new listener to whom all process events will be delivered.
3102    ///
3103    /// @return
3104    ///     Returns \b true if the new listener could be installed,
3105    ///     \b false otherwise.
3106    //------------------------------------------------------------------
3107    bool
3108    HijackProcessEvents (Listener *listener);
3109
3110    //------------------------------------------------------------------
3111    /// Restores the process event broadcasting to its normal state.
3112    ///
3113    //------------------------------------------------------------------
3114    void
3115    RestoreProcessEvents ();
3116
3117protected:
3118    //------------------------------------------------------------------
3119    /// This is the part of the event handling that for a process event.
3120    /// It decides what to do with the event and returns true if the
3121    /// event needs to be propagated to the user, and false otherwise.
3122    /// If the event is not propagated, this call will most likely set
3123    /// the target to executing again.
3124    ///
3125    /// @param[in] event_ptr
3126    ///     This is the event we are handling.
3127    ///
3128    /// @return
3129    ///     Returns \b true if the event should be reported to the
3130    ///     user, \b false otherwise.
3131    //------------------------------------------------------------------
3132    bool
3133    ShouldBroadcastEvent (Event *event_ptr);
3134
3135public:
3136    const lldb::ABISP &
3137    GetABI ();
3138
3139    OperatingSystem *
3140    GetOperatingSystem ()
3141    {
3142        return m_os_ap.get();
3143    }
3144
3145
3146    virtual LanguageRuntime *
3147    GetLanguageRuntime (lldb::LanguageType language, bool retry_if_null = true);
3148
3149    virtual CPPLanguageRuntime *
3150    GetCPPLanguageRuntime (bool retry_if_null = true);
3151
3152    virtual ObjCLanguageRuntime *
3153    GetObjCLanguageRuntime (bool retry_if_null = true);
3154
3155    bool
3156    IsPossibleDynamicValue (ValueObject& in_value);
3157
3158    bool
3159    IsRunning () const;
3160
3161    DynamicCheckerFunctions *GetDynamicCheckers()
3162    {
3163        return m_dynamic_checkers_ap.get();
3164    }
3165
3166    void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
3167    {
3168        m_dynamic_checkers_ap.reset(dynamic_checkers);
3169    }
3170
3171    //------------------------------------------------------------------
3172    /// Call this to set the lldb in the mode where it breaks on new thread
3173    /// creations, and then auto-restarts.  This is useful when you are trying
3174    /// to run only one thread, but either that thread or the kernel is creating
3175    /// new threads in the process.  If you stop when the thread is created, you
3176    /// can immediately suspend it, and keep executing only the one thread you intend.
3177    ///
3178    /// @return
3179    ///     Returns \b true if we were able to start up the notification
3180    ///     \b false otherwise.
3181    //------------------------------------------------------------------
3182    virtual bool
3183    StartNoticingNewThreads()
3184    {
3185        return true;
3186    }
3187
3188    //------------------------------------------------------------------
3189    /// Call this to turn off the stop & notice new threads mode.
3190    ///
3191    /// @return
3192    ///     Returns \b true if we were able to start up the notification
3193    ///     \b false otherwise.
3194    //------------------------------------------------------------------
3195    virtual bool
3196    StopNoticingNewThreads()
3197    {
3198        return true;
3199    }
3200
3201    void
3202    SetRunningUserExpression (bool on);
3203
3204    //------------------------------------------------------------------
3205    // lldb::ExecutionContextScope pure virtual functions
3206    //------------------------------------------------------------------
3207    virtual lldb::TargetSP
3208    CalculateTarget ();
3209
3210    virtual lldb::ProcessSP
3211    CalculateProcess ()
3212    {
3213        return shared_from_this();
3214    }
3215
3216    virtual lldb::ThreadSP
3217    CalculateThread ()
3218    {
3219        return lldb::ThreadSP();
3220    }
3221
3222    virtual lldb::StackFrameSP
3223    CalculateStackFrame ()
3224    {
3225        return lldb::StackFrameSP();
3226    }
3227
3228    virtual void
3229    CalculateExecutionContext (ExecutionContext &exe_ctx);
3230
3231    void
3232    SetSTDIOFileDescriptor (int file_descriptor);
3233
3234    //------------------------------------------------------------------
3235    // Add a permanent region of memory that should never be read or
3236    // written to. This can be used to ensure that memory reads or writes
3237    // to certain areas of memory never end up being sent to the
3238    // DoReadMemory or DoWriteMemory functions which can improve
3239    // performance.
3240    //------------------------------------------------------------------
3241    void
3242    AddInvalidMemoryRegion (const LoadRange &region);
3243
3244    //------------------------------------------------------------------
3245    // Remove a permanent region of memory that should never be read or
3246    // written to that was previously added with AddInvalidMemoryRegion.
3247    //------------------------------------------------------------------
3248    bool
3249    RemoveInvalidMemoryRange (const LoadRange &region);
3250
3251    //------------------------------------------------------------------
3252    // If the setup code of a thread plan needs to do work that might involve
3253    // calling a function in the target, it should not do that work directly
3254    // in one of the thread plan functions (DidPush/WillResume) because
3255    // such work needs to be handled carefully.  Instead, put that work in
3256    // a PreResumeAction callback, and register it with the process.  It will
3257    // get done before the actual "DoResume" gets called.
3258    //------------------------------------------------------------------
3259
3260    typedef bool (PreResumeActionCallback)(void *);
3261
3262    void
3263    AddPreResumeAction (PreResumeActionCallback callback, void *baton);
3264
3265    bool
3266    RunPreResumeActions ();
3267
3268    void
3269    ClearPreResumeActions ();
3270
3271    ReadWriteLock &
3272    GetRunLock ()
3273    {
3274        return m_run_lock;
3275    }
3276
3277protected:
3278    //------------------------------------------------------------------
3279    // NextEventAction provides a way to register an action on the next
3280    // event that is delivered to this process.  There is currently only
3281    // one next event action allowed in the process at one time.  If a
3282    // new "NextEventAction" is added while one is already present, the
3283    // old action will be discarded (with HandleBeingUnshipped called
3284    // after it is discarded.)
3285    //------------------------------------------------------------------
3286    class NextEventAction
3287    {
3288    public:
3289        typedef enum EventActionResult
3290        {
3291            eEventActionSuccess,
3292            eEventActionRetry,
3293            eEventActionExit
3294        } EventActionResult;
3295
3296        NextEventAction (Process *process) :
3297            m_process(process)
3298        {
3299        }
3300
3301        virtual
3302        ~NextEventAction()
3303        {
3304        }
3305
3306        virtual EventActionResult PerformAction (lldb::EventSP &event_sp) = 0;
3307        virtual void HandleBeingUnshipped () {}
3308        virtual EventActionResult HandleBeingInterrupted () = 0;
3309        virtual const char *GetExitString() = 0;
3310    protected:
3311        Process *m_process;
3312    };
3313
3314    void SetNextEventAction (Process::NextEventAction *next_event_action)
3315    {
3316        if (m_next_event_action_ap.get())
3317            m_next_event_action_ap->HandleBeingUnshipped();
3318
3319        m_next_event_action_ap.reset(next_event_action);
3320    }
3321
3322    // This is the completer for Attaching:
3323    class AttachCompletionHandler : public NextEventAction
3324    {
3325    public:
3326        AttachCompletionHandler (Process *process, uint32_t exec_count) :
3327            NextEventAction (process),
3328            m_exec_count (exec_count)
3329        {
3330        }
3331
3332        virtual
3333        ~AttachCompletionHandler()
3334        {
3335        }
3336
3337        virtual EventActionResult PerformAction (lldb::EventSP &event_sp);
3338        virtual EventActionResult HandleBeingInterrupted ();
3339        virtual const char *GetExitString();
3340    private:
3341        uint32_t m_exec_count;
3342        std::string m_exit_string;
3343    };
3344
3345    bool
3346    HijackPrivateProcessEvents (Listener *listener);
3347
3348    void
3349    RestorePrivateProcessEvents ();
3350
3351    bool
3352    PrivateStateThreadIsValid () const
3353    {
3354        return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3355    }
3356
3357    //------------------------------------------------------------------
3358    // Type definitions
3359    //------------------------------------------------------------------
3360    typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP> LanguageRuntimeCollection;
3361
3362    struct PreResumeCallbackAndBaton
3363    {
3364        bool (*callback) (void *);
3365        void *baton;
3366        PreResumeCallbackAndBaton (PreResumeActionCallback in_callback, void *in_baton) :
3367            callback (in_callback),
3368            baton (in_baton)
3369        {
3370        }
3371    };
3372
3373    //------------------------------------------------------------------
3374    // Member variables
3375    //------------------------------------------------------------------
3376    Target &                    m_target;               ///< The target that owns this process.
3377    ThreadSafeValue<lldb::StateType>  m_public_state;
3378    ThreadSafeValue<lldb::StateType>  m_private_state; // The actual state of our process
3379    Broadcaster                 m_private_state_broadcaster;  // This broadcaster feeds state changed events into the private state thread's listener.
3380    Broadcaster                 m_private_state_control_broadcaster; // This is the control broadcaster, used to pause, resume & stop the private state thread.
3381    Listener                    m_private_state_listener;     // This is the listener for the private state thread.
3382    Predicate<bool>             m_private_state_control_wait; /// This Predicate is used to signal that a control operation is complete.
3383    lldb::thread_t              m_private_state_thread;  // Thread ID for the thread that watches interal state events
3384    ProcessModID                m_mod_id;               ///< Tracks the state of the process over stops and other alterations.
3385    uint32_t                    m_thread_index_id;      ///< Each thread is created with a 1 based index that won't get re-used.
3386    int                         m_exit_status;          ///< The exit status of the process, or -1 if not set.
3387    std::string                 m_exit_string;          ///< A textual description of why a process exited.
3388    ThreadList                  m_thread_list;          ///< The threads for this process.
3389    std::vector<Notifications>  m_notifications;        ///< The list of notifications that this process can deliver.
3390    std::vector<lldb::addr_t>   m_image_tokens;
3391    Listener                    &m_listener;
3392    BreakpointSiteList          m_breakpoint_site_list; ///< This is the list of breakpoint locations we intend to insert in the target.
3393    std::auto_ptr<DynamicLoader> m_dyld_ap;
3394    std::auto_ptr<DynamicCheckerFunctions> m_dynamic_checkers_ap; ///< The functions used by the expression parser to validate data that expressions use.
3395    std::auto_ptr<OperatingSystem> m_os_ap;
3396    UnixSignals                 m_unix_signals;         /// This is the current signal set for this process.
3397    lldb::ABISP                 m_abi_sp;
3398    lldb::InputReaderSP         m_process_input_reader;
3399    Communication 				m_stdio_communication;
3400    Mutex        				m_stdio_communication_mutex;
3401    std::string                 m_stdout_data;
3402    std::string                 m_stderr_data;
3403    MemoryCache                 m_memory_cache;
3404    AllocatedMemoryCache        m_allocated_memory_cache;
3405    bool                        m_should_detach;   /// Should we detach if the process object goes away with an explicit call to Kill or Detach?
3406    LanguageRuntimeCollection 	m_language_runtimes;
3407    std::auto_ptr<NextEventAction> m_next_event_action_ap;
3408    std::vector<PreResumeCallbackAndBaton> m_pre_resume_actions;
3409    ReadWriteLock               m_run_lock;
3410    Predicate<bool>             m_currently_handling_event;
3411    bool                        m_finalize_called;
3412
3413    enum {
3414        eCanJITDontKnow= 0,
3415        eCanJITYes,
3416        eCanJITNo
3417    } m_can_jit;
3418
3419    size_t
3420    RemoveBreakpointOpcodesFromBuffer (lldb::addr_t addr, size_t size, uint8_t *buf) const;
3421
3422    void
3423    SynchronouslyNotifyStateChanged (lldb::StateType state);
3424
3425    void
3426    SetPublicState (lldb::StateType new_state);
3427
3428    void
3429    SetPrivateState (lldb::StateType state);
3430
3431    bool
3432    StartPrivateStateThread (bool force = false);
3433
3434    void
3435    StopPrivateStateThread ();
3436
3437    void
3438    PausePrivateStateThread ();
3439
3440    void
3441    ResumePrivateStateThread ();
3442
3443    static void *
3444    PrivateStateThread (void *arg);
3445
3446    void *
3447    RunPrivateStateThread ();
3448
3449    void
3450    HandlePrivateEvent (lldb::EventSP &event_sp);
3451
3452    lldb::StateType
3453    WaitForProcessStopPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
3454
3455    // This waits for both the state change broadcaster, and the control broadcaster.
3456    // If control_only, it only waits for the control broadcaster.
3457
3458    bool
3459    WaitForEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp, bool control_only);
3460
3461    lldb::StateType
3462    WaitForStateChangedEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
3463
3464    lldb::StateType
3465    WaitForState (const TimeValue *timeout,
3466                  const lldb::StateType *match_states,
3467                  const uint32_t num_match_states);
3468
3469    size_t
3470    WriteMemoryPrivate (lldb::addr_t addr, const void *buf, size_t size, Error &error);
3471
3472    void
3473    AppendSTDOUT (const char *s, size_t len);
3474
3475    void
3476    AppendSTDERR (const char *s, size_t len);
3477
3478    static void
3479    STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len);
3480
3481    void
3482    PushProcessInputReader ();
3483
3484    void
3485    PopProcessInputReader ();
3486
3487    void
3488    ResetProcessInputReader ();
3489
3490    static size_t
3491    ProcessInputReaderCallback (void *baton,
3492                                InputReader &reader,
3493                                lldb::InputReaderAction notification,
3494                                const char *bytes,
3495                                size_t bytes_len);
3496
3497
3498private:
3499    //------------------------------------------------------------------
3500    // For Process only
3501    //------------------------------------------------------------------
3502    void ControlPrivateStateThread (uint32_t signal);
3503
3504    DISALLOW_COPY_AND_ASSIGN (Process);
3505
3506};
3507
3508} // namespace lldb_private
3509
3510#endif  // liblldb_Process_h_
3511