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