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