Process.h revision 1f9c39c3c146f3c057575f53707e97019f402c46
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 (UserSettingsController &owner, 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 ReferenceCountedBaseVirtual<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
2378    size_t
2379    ReadMemoryFromInferior (lldb::addr_t vm_addr,
2380                            void *buf,
2381                            size_t size,
2382                            Error &error);
2383
2384    //------------------------------------------------------------------
2385    /// Reads an unsigned integer of the specified byte size from
2386    /// process memory.
2387    ///
2388    /// @param[in] load_addr
2389    ///     A load address of the integer to read.
2390    ///
2391    /// @param[in] byte_size
2392    ///     The size in byte of the integer to read.
2393    ///
2394    /// @param[in] fail_value
2395    ///     The value to return if we fail to read an integer.
2396    ///
2397    /// @param[out] error
2398    ///     An error that indicates the success or failure of this
2399    ///     operation. If error indicates success (error.Success()),
2400    ///     then the value returned can be trusted, otherwise zero
2401    ///     will be returned.
2402    ///
2403    /// @return
2404    ///     The unsigned integer that was read from the process memory
2405    ///     space. If the integer was smaller than a uint64_t, any
2406    ///     unused upper bytes will be zero filled. If the process
2407    ///     byte order differs from the host byte order, the integer
2408    ///     value will be appropriately byte swapped into host byte
2409    ///     order.
2410    //------------------------------------------------------------------
2411    uint64_t
2412    ReadUnsignedIntegerFromMemory (lldb::addr_t load_addr,
2413                                   size_t byte_size,
2414                                   uint64_t fail_value,
2415                                   Error &error);
2416
2417    lldb::addr_t
2418    ReadPointerFromMemory (lldb::addr_t vm_addr,
2419                           Error &error);
2420
2421    bool
2422    WritePointerToMemory (lldb::addr_t vm_addr,
2423                          lldb::addr_t ptr_value,
2424                          Error &error);
2425
2426    //------------------------------------------------------------------
2427    /// Actually do the writing of memory to a process.
2428    ///
2429    /// @param[in] vm_addr
2430    ///     A virtual load address that indicates where to start writing
2431    ///     memory to.
2432    ///
2433    /// @param[in] buf
2434    ///     A byte buffer that is at least \a size bytes long that
2435    ///     contains the data to write.
2436    ///
2437    /// @param[in] size
2438    ///     The number of bytes to write.
2439    ///
2440    /// @param[out] error
2441    ///     An error value in case the memory write fails.
2442    ///
2443    /// @return
2444    ///     The number of bytes that were actually written.
2445    //------------------------------------------------------------------
2446    virtual size_t
2447    DoWriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error) = 0;
2448
2449    //------------------------------------------------------------------
2450    /// Write all or part of a scalar value to memory.
2451    ///
2452    /// The value contained in \a scalar will be swapped to match the
2453    /// byte order of the process that is being debugged. If \a size is
2454    /// less than the size of scalar, the least significate \a size bytes
2455    /// from scalar will be written. If \a size is larger than the byte
2456    /// size of scalar, then the extra space will be padded with zeros
2457    /// and the scalar value will be placed in the least significant
2458    /// bytes in memory.
2459    ///
2460    /// @param[in] vm_addr
2461    ///     A virtual load address that indicates where to start writing
2462    ///     memory to.
2463    ///
2464    /// @param[in] scalar
2465    ///     The scalar to write to the debugged process.
2466    ///
2467    /// @param[in] size
2468    ///     This value can be smaller or larger than the scalar value
2469    ///     itself. If \a size is smaller than the size of \a scalar,
2470    ///     the least significant bytes in \a scalar will be used. If
2471    ///     \a size is larger than the byte size of \a scalar, then
2472    ///     the extra space will be padded with zeros. If \a size is
2473    ///     set to UINT32_MAX, then the size of \a scalar will be used.
2474    ///
2475    /// @param[out] error
2476    ///     An error value in case the memory write fails.
2477    ///
2478    /// @return
2479    ///     The number of bytes that were actually written.
2480    //------------------------------------------------------------------
2481    size_t
2482    WriteScalarToMemory (lldb::addr_t vm_addr,
2483                         const Scalar &scalar,
2484                         uint32_t size,
2485                         Error &error);
2486
2487    size_t
2488    ReadScalarIntegerFromMemory (lldb::addr_t addr,
2489                                 uint32_t byte_size,
2490                                 bool is_signed,
2491                                 Scalar &scalar,
2492                                 Error &error);
2493
2494    //------------------------------------------------------------------
2495    /// Write memory to a process.
2496    ///
2497    /// This function will write memory to the current process's
2498    /// address space and maintain any traps that might be present due
2499    /// to software breakpoints.
2500    ///
2501    /// This function is not meant to be overridden by Process
2502    /// subclasses, the subclasses should implement
2503    /// Process::DoWriteMemory (lldb::addr_t, size_t, void *).
2504    ///
2505    /// @param[in] vm_addr
2506    ///     A virtual load address that indicates where to start writing
2507    ///     memory to.
2508    ///
2509    /// @param[in] buf
2510    ///     A byte buffer that is at least \a size bytes long that
2511    ///     contains the data to write.
2512    ///
2513    /// @param[in] size
2514    ///     The number of bytes to write.
2515    ///
2516    /// @return
2517    ///     The number of bytes that were actually written.
2518    //------------------------------------------------------------------
2519    size_t
2520    WriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error);
2521
2522
2523    //------------------------------------------------------------------
2524    /// Actually allocate memory in the process.
2525    ///
2526    /// This function will allocate memory in the process's address
2527    /// space.  This can't rely on the generic function calling mechanism,
2528    /// since that requires this function.
2529    ///
2530    /// @param[in] size
2531    ///     The size of the allocation requested.
2532    ///
2533    /// @return
2534    ///     The address of the allocated buffer in the process, or
2535    ///     LLDB_INVALID_ADDRESS if the allocation failed.
2536    //------------------------------------------------------------------
2537
2538    virtual lldb::addr_t
2539    DoAllocateMemory (size_t size, uint32_t permissions, Error &error) = 0;
2540
2541    //------------------------------------------------------------------
2542    /// The public interface to allocating memory in the process.
2543    ///
2544    /// This function will allocate memory in the process's address
2545    /// space.  This can't rely on the generic function calling mechanism,
2546    /// since that requires this function.
2547    ///
2548    /// @param[in] size
2549    ///     The size of the allocation requested.
2550    ///
2551    /// @param[in] permissions
2552    ///     Or together any of the lldb::Permissions bits.  The permissions on
2553    ///     a given memory allocation can't be changed after allocation.  Note
2554    ///     that a block that isn't set writable can still be written on from lldb,
2555    ///     just not by the process itself.
2556    ///
2557    /// @param[in/out] error
2558    ///     An error object to fill in if things go wrong.
2559    /// @return
2560    ///     The address of the allocated buffer in the process, or
2561    ///     LLDB_INVALID_ADDRESS if the allocation failed.
2562    //------------------------------------------------------------------
2563
2564    lldb::addr_t
2565    AllocateMemory (size_t size, uint32_t permissions, Error &error);
2566
2567    virtual Error
2568    GetMemoryRegionInfo (lldb::addr_t load_addr,
2569                        MemoryRegionInfo &range_info)
2570    {
2571        Error error;
2572        error.SetErrorString ("Process::GetMemoryRegionInfo() not supported");
2573        return error;
2574    }
2575
2576    //------------------------------------------------------------------
2577    /// Attempt to get the attributes for a region of memory in the process.
2578    ///
2579    /// It may be possible for the remote debug server to inspect attributes
2580    /// for a region of memory in the process, such as whether there is a
2581    /// valid page of memory at a given address or whether that page is
2582    /// readable/writable/executable by the process.
2583    ///
2584    /// @param[in] load_addr
2585    ///     The address of interest in the process.
2586    ///
2587    /// @param[out] permissions
2588    ///     If this call returns successfully, this bitmask will have
2589    ///     its Permissions bits set to indicate whether the region is
2590    ///     readable/writable/executable.  If this call fails, the
2591    ///     bitmask values are undefined.
2592    ///
2593    /// @return
2594    ///     Returns true if it was able to determine the attributes of the
2595    ///     memory region.  False if not.
2596    //------------------------------------------------------------------
2597
2598    virtual bool
2599    GetLoadAddressPermissions (lldb::addr_t load_addr, uint32_t &permissions)
2600    {
2601        MemoryRegionInfo range_info;
2602        permissions = 0;
2603        Error error (GetMemoryRegionInfo (load_addr, range_info));
2604        if (!error.Success())
2605            return false;
2606        if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow
2607            || range_info.GetWritable() == MemoryRegionInfo::eDontKnow
2608            || range_info.GetExecutable() == MemoryRegionInfo::eDontKnow)
2609        {
2610            return false;
2611        }
2612
2613        if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2614            permissions |= lldb::ePermissionsReadable;
2615
2616        if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2617            permissions |= lldb::ePermissionsWritable;
2618
2619        if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2620            permissions |= lldb::ePermissionsExecutable;
2621
2622        return true;
2623    }
2624
2625    //------------------------------------------------------------------
2626    /// Determines whether executing JIT-compiled code in this process
2627    /// is possible.
2628    ///
2629    /// @return
2630    ///     True if execution of JIT code is possible; false otherwise.
2631    //------------------------------------------------------------------
2632    bool CanJIT ();
2633
2634    //------------------------------------------------------------------
2635    /// Sets whether executing JIT-compiled code in this process
2636    /// is possible.
2637    ///
2638    /// @param[in] can_jit
2639    ///     True if execution of JIT code is possible; false otherwise.
2640    //------------------------------------------------------------------
2641    void SetCanJIT (bool can_jit);
2642
2643    //------------------------------------------------------------------
2644    /// Actually deallocate memory in the process.
2645    ///
2646    /// This function will deallocate memory in the process's address
2647    /// space that was allocated with AllocateMemory.
2648    ///
2649    /// @param[in] ptr
2650    ///     A return value from AllocateMemory, pointing to the memory you
2651    ///     want to deallocate.
2652    ///
2653    /// @return
2654    ///     \btrue if the memory was deallocated, \bfalse otherwise.
2655    //------------------------------------------------------------------
2656
2657    virtual Error
2658    DoDeallocateMemory (lldb::addr_t ptr) = 0;
2659
2660    //------------------------------------------------------------------
2661    /// The public interface to deallocating memory in the process.
2662    ///
2663    /// This function will deallocate memory in the process's address
2664    /// space that was allocated with AllocateMemory.
2665    ///
2666    /// @param[in] ptr
2667    ///     A return value from AllocateMemory, pointing to the memory you
2668    ///     want to deallocate.
2669    ///
2670    /// @return
2671    ///     \btrue if the memory was deallocated, \bfalse otherwise.
2672    //------------------------------------------------------------------
2673
2674    Error
2675    DeallocateMemory (lldb::addr_t ptr);
2676
2677    //------------------------------------------------------------------
2678    /// Get any available STDOUT.
2679    ///
2680    /// If the process was launched without supplying valid file paths
2681    /// for stdin, stdout, and stderr, then the Process class might
2682    /// try to cache the STDOUT for the process if it is able. Events
2683    /// will be queued indicating that there is STDOUT available that
2684    /// can be retrieved using this function.
2685    ///
2686    /// @param[out] buf
2687    ///     A buffer that will receive any STDOUT bytes that are
2688    ///     currently available.
2689    ///
2690    /// @param[out] buf_size
2691    ///     The size in bytes for the buffer \a buf.
2692    ///
2693    /// @return
2694    ///     The number of bytes written into \a buf. If this value is
2695    ///     equal to \a buf_size, another call to this function should
2696    ///     be made to retrieve more STDOUT data.
2697    //------------------------------------------------------------------
2698    virtual size_t
2699    GetSTDOUT (char *buf, size_t buf_size, Error &error);
2700
2701    //------------------------------------------------------------------
2702    /// Get any available STDERR.
2703    ///
2704    /// If the process was launched without supplying valid file paths
2705    /// for stdin, stdout, and stderr, then the Process class might
2706    /// try to cache the STDERR for the process if it is able. Events
2707    /// will be queued indicating that there is STDERR available that
2708    /// can be retrieved using this function.
2709    ///
2710    /// @param[out] buf
2711    ///     A buffer that will receive any STDERR bytes that are
2712    ///     currently available.
2713    ///
2714    /// @param[out] buf_size
2715    ///     The size in bytes for the buffer \a buf.
2716    ///
2717    /// @return
2718    ///     The number of bytes written into \a buf. If this value is
2719    ///     equal to \a buf_size, another call to this function should
2720    ///     be made to retrieve more STDERR data.
2721    //------------------------------------------------------------------
2722    virtual size_t
2723    GetSTDERR (char *buf, size_t buf_size, Error &error);
2724
2725    virtual size_t
2726    PutSTDIN (const char *buf, size_t buf_size, Error &error)
2727    {
2728        error.SetErrorString("stdin unsupported");
2729        return 0;
2730    }
2731
2732    //----------------------------------------------------------------------
2733    // Process Breakpoints
2734    //----------------------------------------------------------------------
2735    size_t
2736    GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site);
2737
2738    virtual Error
2739    EnableBreakpoint (BreakpointSite *bp_site) = 0;
2740
2741    virtual Error
2742    DisableBreakpoint (BreakpointSite *bp_site) = 0;
2743
2744    // This is implemented completely using the lldb::Process API. Subclasses
2745    // don't need to implement this function unless the standard flow of
2746    // read existing opcode, write breakpoint opcode, verify breakpoint opcode
2747    // doesn't work for a specific process plug-in.
2748    virtual Error
2749    EnableSoftwareBreakpoint (BreakpointSite *bp_site);
2750
2751    // This is implemented completely using the lldb::Process API. Subclasses
2752    // don't need to implement this function unless the standard flow of
2753    // restoring original opcode in memory and verifying the restored opcode
2754    // doesn't work for a specific process plug-in.
2755    virtual Error
2756    DisableSoftwareBreakpoint (BreakpointSite *bp_site);
2757
2758    BreakpointSiteList &
2759    GetBreakpointSiteList();
2760
2761    const BreakpointSiteList &
2762    GetBreakpointSiteList() const;
2763
2764    void
2765    DisableAllBreakpointSites ();
2766
2767    Error
2768    ClearBreakpointSiteByID (lldb::user_id_t break_id);
2769
2770    lldb::break_id_t
2771    CreateBreakpointSite (lldb::BreakpointLocationSP &owner,
2772                          bool use_hardware);
2773
2774    Error
2775    DisableBreakpointSiteByID (lldb::user_id_t break_id);
2776
2777    Error
2778    EnableBreakpointSiteByID (lldb::user_id_t break_id);
2779
2780
2781    // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove
2782    // themselves from the owner's list of this breakpoint sites.  This has to
2783    // be a static function because you can't be sure that removing the
2784    // breakpoint from it's containing map won't delete the breakpoint site,
2785    // and doing that in an instance method isn't copasetic.
2786    void
2787    RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id,
2788                                   lldb::user_id_t owner_loc_id,
2789                                   lldb::BreakpointSiteSP &bp_site_sp);
2790
2791    //----------------------------------------------------------------------
2792    // Process Watchpoints (optional)
2793    //----------------------------------------------------------------------
2794    virtual Error
2795    EnableWatchpoint (Watchpoint *wp);
2796
2797    virtual Error
2798    DisableWatchpoint (Watchpoint *wp);
2799
2800    //------------------------------------------------------------------
2801    // Thread Queries
2802    //------------------------------------------------------------------
2803    virtual uint32_t
2804    UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list) = 0;
2805
2806    void
2807    UpdateThreadListIfNeeded ();
2808
2809    ThreadList &
2810    GetThreadList ()
2811    {
2812        return m_thread_list;
2813    }
2814
2815
2816    uint32_t
2817    GetNextThreadIndexID ();
2818
2819    //------------------------------------------------------------------
2820    // Event Handling
2821    //------------------------------------------------------------------
2822    lldb::StateType
2823    GetNextEvent (lldb::EventSP &event_sp);
2824
2825    lldb::StateType
2826    WaitForProcessToStop (const TimeValue *timeout);
2827
2828    lldb::StateType
2829    WaitForStateChangedEvents (const TimeValue *timeout, lldb::EventSP &event_sp);
2830
2831    Event *
2832    PeekAtStateChangedEvents ();
2833
2834
2835    class
2836    ProcessEventHijacker
2837    {
2838    public:
2839        ProcessEventHijacker (Process &process, Listener *listener) :
2840            m_process (process),
2841            m_listener (listener)
2842        {
2843            m_process.HijackProcessEvents (listener);
2844        }
2845        ~ProcessEventHijacker ()
2846        {
2847            m_process.RestoreProcessEvents();
2848        }
2849
2850    private:
2851        Process &m_process;
2852        Listener *m_listener;
2853    };
2854    friend class ProcessEventHijacker;
2855    //------------------------------------------------------------------
2856    /// If you need to ensure that you and only you will hear about some public
2857    /// event, then make a new listener, set to listen to process events, and
2858    /// then call this with that listener.  Then you will have to wait on that
2859    /// listener explicitly for events (rather than using the GetNextEvent & WaitFor*
2860    /// calls above.  Be sure to call RestoreProcessEvents when you are done.
2861    ///
2862    /// @param[in] listener
2863    ///     This is the new listener to whom all process events will be delivered.
2864    ///
2865    /// @return
2866    ///     Returns \b true if the new listener could be installed,
2867    ///     \b false otherwise.
2868    //------------------------------------------------------------------
2869    bool
2870    HijackProcessEvents (Listener *listener);
2871
2872    //------------------------------------------------------------------
2873    /// Restores the process event broadcasting to its normal state.
2874    ///
2875    //------------------------------------------------------------------
2876    void
2877    RestoreProcessEvents ();
2878
2879protected:
2880    //------------------------------------------------------------------
2881    /// This is the part of the event handling that for a process event.
2882    /// It decides what to do with the event and returns true if the
2883    /// event needs to be propagated to the user, and false otherwise.
2884    /// If the event is not propagated, this call will most likely set
2885    /// the target to executing again.
2886    ///
2887    /// @param[in] event_ptr
2888    ///     This is the event we are handling.
2889    ///
2890    /// @return
2891    ///     Returns \b true if the event should be reported to the
2892    ///     user, \b false otherwise.
2893    //------------------------------------------------------------------
2894    bool
2895    ShouldBroadcastEvent (Event *event_ptr);
2896
2897public:
2898    const lldb::ABISP &
2899    GetABI ();
2900
2901    DynamicLoader *
2902    GetDynamicLoader ()
2903    {
2904        return m_dyld_ap.get();
2905    }
2906
2907    OperatingSystem *
2908    GetOperatingSystem ()
2909    {
2910        return m_os_ap.get();
2911    }
2912
2913
2914    virtual LanguageRuntime *
2915    GetLanguageRuntime (lldb::LanguageType language);
2916
2917    virtual CPPLanguageRuntime *
2918    GetCPPLanguageRuntime ();
2919
2920    virtual ObjCLanguageRuntime *
2921    GetObjCLanguageRuntime ();
2922
2923    bool
2924    IsRunning () const;
2925
2926    DynamicCheckerFunctions *GetDynamicCheckers()
2927    {
2928        return m_dynamic_checkers_ap.get();
2929    }
2930
2931    void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
2932    {
2933        m_dynamic_checkers_ap.reset(dynamic_checkers);
2934    }
2935
2936    //------------------------------------------------------------------
2937    /// Call this to set the lldb in the mode where it breaks on new thread
2938    /// creations, and then auto-restarts.  This is useful when you are trying
2939    /// to run only one thread, but either that thread or the kernel is creating
2940    /// new threads in the process.  If you stop when the thread is created, you
2941    /// can immediately suspend it, and keep executing only the one thread you intend.
2942    ///
2943    /// @return
2944    ///     Returns \b true if we were able to start up the notification
2945    ///     \b false otherwise.
2946    //------------------------------------------------------------------
2947    virtual bool
2948    StartNoticingNewThreads()
2949    {
2950        return true;
2951    }
2952
2953    //------------------------------------------------------------------
2954    /// Call this to turn off the stop & notice new threads mode.
2955    ///
2956    /// @return
2957    ///     Returns \b true if we were able to start up the notification
2958    ///     \b false otherwise.
2959    //------------------------------------------------------------------
2960    virtual bool
2961    StopNoticingNewThreads()
2962    {
2963        return true;
2964    }
2965
2966    void
2967    SetRunningUserExpression (bool on);
2968
2969    //------------------------------------------------------------------
2970    // lldb::ExecutionContextScope pure virtual functions
2971    //------------------------------------------------------------------
2972    virtual Target *
2973    CalculateTarget ()
2974    {
2975        return &m_target;
2976    }
2977
2978    virtual Process *
2979    CalculateProcess ()
2980    {
2981        return this;
2982    }
2983
2984    virtual Thread *
2985    CalculateThread ()
2986    {
2987        return NULL;
2988    }
2989
2990    virtual StackFrame *
2991    CalculateStackFrame ()
2992    {
2993        return NULL;
2994    }
2995
2996    virtual void
2997    CalculateExecutionContext (ExecutionContext &exe_ctx);
2998
2999    lldb::ProcessSP
3000    GetSP ();
3001
3002    void
3003    SetSTDIOFileDescriptor (int file_descriptor);
3004
3005protected:
3006    //------------------------------------------------------------------
3007    // NextEventAction provides a way to register an action on the next
3008    // event that is delivered to this process.  There is currently only
3009    // one next event action allowed in the process at one time.  If a
3010    // new "NextEventAction" is added while one is already present, the
3011    // old action will be discarded (with HandleBeingUnshipped called
3012    // after it is discarded.)
3013    //------------------------------------------------------------------
3014    class NextEventAction
3015    {
3016    public:
3017        typedef enum EventActionResult
3018        {
3019            eEventActionSuccess,
3020            eEventActionRetry,
3021            eEventActionExit
3022        } EventActionResult;
3023
3024        NextEventAction (Process *process) :
3025            m_process(process)
3026        {
3027        }
3028
3029        virtual
3030        ~NextEventAction()
3031        {
3032        }
3033
3034        virtual EventActionResult PerformAction (lldb::EventSP &event_sp) = 0;
3035        virtual void HandleBeingUnshipped () {};
3036        virtual EventActionResult HandleBeingInterrupted () = 0;
3037        virtual const char *GetExitString() = 0;
3038    protected:
3039        Process *m_process;
3040    };
3041
3042    void SetNextEventAction (Process::NextEventAction *next_event_action)
3043    {
3044        if (m_next_event_action_ap.get())
3045            m_next_event_action_ap->HandleBeingUnshipped();
3046
3047        m_next_event_action_ap.reset(next_event_action);
3048    }
3049
3050    // This is the completer for Attaching:
3051    class AttachCompletionHandler : public NextEventAction
3052    {
3053    public:
3054        AttachCompletionHandler (Process *process, uint32_t exec_count) :
3055            NextEventAction (process),
3056            m_exec_count (exec_count)
3057        {
3058        }
3059
3060        virtual
3061        ~AttachCompletionHandler()
3062        {
3063        }
3064
3065        virtual EventActionResult PerformAction (lldb::EventSP &event_sp);
3066        virtual EventActionResult HandleBeingInterrupted ();
3067        virtual const char *GetExitString();
3068    private:
3069        uint32_t m_exec_count;
3070        std::string m_exit_string;
3071    };
3072
3073    bool
3074    HijackPrivateProcessEvents (Listener *listener);
3075
3076    void
3077    RestorePrivateProcessEvents ();
3078
3079    bool
3080    PrivateStateThreadIsValid () const
3081    {
3082        return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
3083    }
3084
3085    //------------------------------------------------------------------
3086    // Member variables
3087    //------------------------------------------------------------------
3088    Target &                    m_target;               ///< The target that owns this process.
3089    ThreadSafeValue<lldb::StateType>  m_public_state;
3090    ThreadSafeValue<lldb::StateType>  m_private_state; // The actual state of our process
3091    Broadcaster                 m_private_state_broadcaster;  // This broadcaster feeds state changed events into the private state thread's listener.
3092    Broadcaster                 m_private_state_control_broadcaster; // This is the control broadcaster, used to pause, resume & stop the private state thread.
3093    Listener                    m_private_state_listener;     // This is the listener for the private state thread.
3094    Predicate<bool>             m_private_state_control_wait; /// This Predicate is used to signal that a control operation is complete.
3095    lldb::thread_t              m_private_state_thread;  // Thread ID for the thread that watches interal state events
3096    ProcessModID                m_mod_id;              ///< Tracks the state of the process over stops and other alterations.
3097    uint32_t                    m_thread_index_id;      ///< Each thread is created with a 1 based index that won't get re-used.
3098    int                         m_exit_status;          ///< The exit status of the process, or -1 if not set.
3099    std::string                 m_exit_string;          ///< A textual description of why a process exited.
3100    ThreadList                  m_thread_list;          ///< The threads for this process.
3101    std::vector<Notifications>  m_notifications;        ///< The list of notifications that this process can deliver.
3102    std::vector<lldb::addr_t>   m_image_tokens;
3103    Listener                    &m_listener;
3104    BreakpointSiteList          m_breakpoint_site_list; ///< This is the list of breakpoint locations we intend
3105                                                        ///< to insert in the target.
3106    std::auto_ptr<DynamicLoader> m_dyld_ap;
3107    std::auto_ptr<DynamicCheckerFunctions>  m_dynamic_checkers_ap; ///< The functions used by the expression parser to validate data that expressions use.
3108    std::auto_ptr<OperatingSystem>     m_os_ap;
3109    UnixSignals                 m_unix_signals;         /// This is the current signal set for this process.
3110    lldb::ABISP                 m_abi_sp;
3111    lldb::InputReaderSP         m_process_input_reader;
3112    lldb_private::Communication m_stdio_communication;
3113    lldb_private::Mutex         m_stdio_communication_mutex;
3114    std::string                 m_stdout_data;
3115    std::string                 m_stderr_data;
3116    MemoryCache                 m_memory_cache;
3117    AllocatedMemoryCache        m_allocated_memory_cache;
3118    bool                        m_should_detach;   /// Should we detach if the process object goes away with an explicit call to Kill or Detach?
3119
3120    typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP> LanguageRuntimeCollection;
3121    LanguageRuntimeCollection m_language_runtimes;
3122    std::auto_ptr<NextEventAction> m_next_event_action_ap;
3123
3124    enum {
3125        eCanJITDontKnow= 0,
3126        eCanJITYes,
3127        eCanJITNo
3128    } m_can_jit;
3129
3130    size_t
3131    RemoveBreakpointOpcodesFromBuffer (lldb::addr_t addr, size_t size, uint8_t *buf) const;
3132
3133    void
3134    SynchronouslyNotifyStateChanged (lldb::StateType state);
3135
3136    void
3137    SetPublicState (lldb::StateType new_state);
3138
3139    void
3140    SetPrivateState (lldb::StateType state);
3141
3142    bool
3143    StartPrivateStateThread ();
3144
3145    void
3146    StopPrivateStateThread ();
3147
3148    void
3149    PausePrivateStateThread ();
3150
3151    void
3152    ResumePrivateStateThread ();
3153
3154    static void *
3155    PrivateStateThread (void *arg);
3156
3157    void *
3158    RunPrivateStateThread ();
3159
3160    void
3161    HandlePrivateEvent (lldb::EventSP &event_sp);
3162
3163    lldb::StateType
3164    WaitForProcessStopPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
3165
3166    // This waits for both the state change broadcaster, and the control broadcaster.
3167    // If control_only, it only waits for the control broadcaster.
3168
3169    bool
3170    WaitForEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp, bool control_only);
3171
3172    lldb::StateType
3173    WaitForStateChangedEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
3174
3175    lldb::StateType
3176    WaitForState (const TimeValue *timeout,
3177                  const lldb::StateType *match_states,
3178                  const uint32_t num_match_states);
3179
3180    size_t
3181    WriteMemoryPrivate (lldb::addr_t addr, const void *buf, size_t size, Error &error);
3182
3183    void
3184    AppendSTDOUT (const char *s, size_t len);
3185
3186    void
3187    AppendSTDERR (const char *s, size_t len);
3188
3189    static void
3190    STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len);
3191
3192    void
3193    PushProcessInputReader ();
3194
3195    void
3196    PopProcessInputReader ();
3197
3198    void
3199    ResetProcessInputReader ();
3200
3201    static size_t
3202    ProcessInputReaderCallback (void *baton,
3203                                InputReader &reader,
3204                                lldb::InputReaderAction notification,
3205                                const char *bytes,
3206                                size_t bytes_len);
3207
3208
3209private:
3210    //------------------------------------------------------------------
3211    // For Process only
3212    //------------------------------------------------------------------
3213    void ControlPrivateStateThread (uint32_t signal);
3214
3215    DISALLOW_COPY_AND_ASSIGN (Process);
3216
3217};
3218
3219} // namespace lldb_private
3220
3221#endif  // liblldb_Process_h_
3222