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