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