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