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