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