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