Process.h revision 21f37ad875d4f50d1b4b3d307e120f6d27103730
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    /// List the processes matching the given partial name.
1369    ///
1370    /// FIXME: Is it too heavyweight to create an entire process object to do this?
1371    /// The problem is for remote processes we're going to have to set up the same transport
1372    /// to get this data as to actually attach.  So we need to factor out transport
1373    /// and process before we can do this separately from the process.
1374    ///
1375    /// @param[in] name
1376    ///     A partial name to match against the current process list.
1377    ///
1378    /// @param[out] matches
1379    ///     The list of process names matching \a name.
1380    ///
1381    /// @param[in] pids
1382    ///     A vector filled with the pids that correspond to the names in \a matches.
1383    ///
1384    /// @return
1385    ///     Returns the number of matching processes.
1386    //------------------------------------------------------------------
1387
1388//    virtual uint32_t
1389//    ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids);
1390
1391    //------------------------------------------------------------------
1392    /// Find the architecture of a process by pid.
1393    ///
1394    /// FIXME: See comment for ListProcessesMatchingName.
1395    ///
1396    /// @param[in] pid
1397    ///     A pid to inspect.
1398    ///
1399    /// @return
1400    ///     Returns the architecture of the process or an invalid architecture if the process can't be found.
1401    //------------------------------------------------------------------
1402//    virtual ArchSpec
1403//    GetArchSpecForExistingProcess (lldb::pid_t pid);
1404
1405    //------------------------------------------------------------------
1406    /// Find the architecture of a process by name.
1407    ///
1408    /// FIXME: See comment for ListProcessesMatchingName.
1409    ///
1410    /// @param[in] process_name
1411    ///     The process name to inspect.
1412    ///
1413    /// @return
1414    ///     Returns the architecture of the process or an invalid architecture if the process can't be found.
1415    //------------------------------------------------------------------
1416//    virtual ArchSpec
1417//    GetArchSpecForExistingProcess (const char *process_name);
1418
1419    //------------------------------------------------------------------
1420    /// Get the image information address for the current process.
1421    ///
1422    /// Some runtimes have system functions that can help dynamic
1423    /// loaders locate the dynamic loader information needed to observe
1424    /// shared libraries being loaded or unloaded. This function is
1425    /// in the Process interface (as opposed to the DynamicLoader
1426    /// interface) to ensure that remote debugging can take advantage of
1427    /// this functionality.
1428    ///
1429    /// @return
1430    ///     The address of the dynamic loader information, or
1431    ///     LLDB_INVALID_ADDRESS if this is not supported by this
1432    ///     interface.
1433    //------------------------------------------------------------------
1434    virtual lldb::addr_t
1435    GetImageInfoAddress ();
1436
1437    //------------------------------------------------------------------
1438    /// Load a shared library into this process.
1439    ///
1440    /// Try and load a shared library into the current process. This
1441    /// call might fail in the dynamic loader plug-in says it isn't safe
1442    /// to try and load shared libraries at the moment.
1443    ///
1444    /// @param[in] image_spec
1445    ///     The image file spec that points to the shared library that
1446    ///     you want to load.
1447    ///
1448    /// @param[out] error
1449    ///     An error object that gets filled in with any errors that
1450    ///     might occur when trying to load the shared library.
1451    ///
1452    /// @return
1453    ///     A token that represents the shared library that can be
1454    ///     later used to unload the shared library. A value of
1455    ///     LLDB_INVALID_IMAGE_TOKEN will be returned if the shared
1456    ///     library can't be opened.
1457    //------------------------------------------------------------------
1458    virtual uint32_t
1459    LoadImage (const FileSpec &image_spec, Error &error);
1460
1461    virtual Error
1462    UnloadImage (uint32_t image_token);
1463
1464    //------------------------------------------------------------------
1465    /// Register for process and thread notifications.
1466    ///
1467    /// Clients can register nofication callbacks by filling out a
1468    /// Process::Notifications structure and calling this function.
1469    ///
1470    /// @param[in] callbacks
1471    ///     A structure that contains the notification baton and
1472    ///     callback functions.
1473    ///
1474    /// @see Process::Notifications
1475    //------------------------------------------------------------------
1476#ifndef SWIG
1477    void
1478    RegisterNotificationCallbacks (const Process::Notifications& callbacks);
1479#endif
1480    //------------------------------------------------------------------
1481    /// Unregister for process and thread notifications.
1482    ///
1483    /// Clients can unregister nofication callbacks by passing a copy of
1484    /// the original baton and callbacks in \a callbacks.
1485    ///
1486    /// @param[in] callbacks
1487    ///     A structure that contains the notification baton and
1488    ///     callback functions.
1489    ///
1490    /// @return
1491    ///     Returns \b true if the notification callbacks were
1492    ///     successfully removed from the process, \b false otherwise.
1493    ///
1494    /// @see Process::Notifications
1495    //------------------------------------------------------------------
1496#ifndef SWIG
1497    bool
1498    UnregisterNotificationCallbacks (const Process::Notifications& callbacks);
1499#endif
1500    //==================================================================
1501    // Built in Process Control functions
1502    //==================================================================
1503    //------------------------------------------------------------------
1504    /// Resumes all of a process's threads as configured using the
1505    /// Thread run control functions.
1506    ///
1507    /// Threads for a process should be updated with one of the run
1508    /// control actions (resume, step, or suspend) that they should take
1509    /// when the process is resumed. If no run control action is given
1510    /// to a thread it will be resumed by default.
1511    ///
1512    /// This function is not meant to be overridden by Process
1513    /// subclasses. This function will take care of disabling any
1514    /// breakpoints that threads may be stopped at, single stepping, and
1515    /// re-enabling breakpoints, and enabling the basic flow control
1516    /// that the plug-in instances need not worry about.
1517    ///
1518    /// @return
1519    ///     Returns an error object.
1520    ///
1521    /// @see Thread:Resume()
1522    /// @see Thread:Step()
1523    /// @see Thread:Suspend()
1524    //------------------------------------------------------------------
1525    Error
1526    Resume ();
1527
1528    //------------------------------------------------------------------
1529    /// Halts a running process.
1530    ///
1531    /// This function is not meant to be overridden by Process
1532    /// subclasses.
1533    /// If the process is successfully halted, a eStateStopped
1534    /// process event with GetInterrupted will be broadcast.  If false, we will
1535    /// halt the process with no events generated by the halt.
1536    ///
1537    /// @return
1538    ///     Returns an error object.  If the error is empty, the process is halted.
1539    ///     otherwise the halt has failed.
1540    //------------------------------------------------------------------
1541    Error
1542    Halt ();
1543
1544    //------------------------------------------------------------------
1545    /// Detaches from a running or stopped process.
1546    ///
1547    /// This function is not meant to be overridden by Process
1548    /// subclasses.
1549    ///
1550    /// @return
1551    ///     Returns an error object.
1552    //------------------------------------------------------------------
1553    Error
1554    Detach ();
1555
1556    //------------------------------------------------------------------
1557    /// Kills the process and shuts down all threads that were spawned
1558    /// to track and monitor the process.
1559    ///
1560    /// This function is not meant to be overridden by Process
1561    /// subclasses.
1562    ///
1563    /// @return
1564    ///     Returns an error object.
1565    //------------------------------------------------------------------
1566    Error
1567    Destroy();
1568
1569    //------------------------------------------------------------------
1570    /// Sends a process a UNIX signal \a signal.
1571    ///
1572    /// This function is not meant to be overridden by Process
1573    /// subclasses.
1574    ///
1575    /// @return
1576    ///     Returns an error object.
1577    //------------------------------------------------------------------
1578    Error
1579    Signal (int signal);
1580
1581    virtual UnixSignals &
1582    GetUnixSignals ()
1583    {
1584        return m_unix_signals;
1585    }
1586
1587    //==================================================================
1588    // Plug-in Process Control Overrides
1589    //==================================================================
1590
1591    //------------------------------------------------------------------
1592    /// Called before attaching to a process.
1593    ///
1594    /// Allow Process plug-ins to execute some code before attaching a
1595    /// process.
1596    ///
1597    /// @return
1598    ///     Returns an error object.
1599    //------------------------------------------------------------------
1600    virtual Error
1601    WillAttachToProcessWithID (lldb::pid_t pid)
1602    {
1603        return Error();
1604    }
1605
1606    //------------------------------------------------------------------
1607    /// Called before attaching to a process.
1608    ///
1609    /// Allow Process plug-ins to execute some code before attaching a
1610    /// process.
1611    ///
1612    /// @return
1613    ///     Returns an error object.
1614    //------------------------------------------------------------------
1615    virtual Error
1616    WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
1617    {
1618        return Error();
1619    }
1620
1621    virtual Error
1622    DoConnectRemote (const char *remote_url)
1623    {
1624        Error error;
1625        error.SetErrorString ("remote connections are not supported");
1626        return error;
1627    }
1628
1629    //------------------------------------------------------------------
1630    /// Attach to an existing process using a process ID.
1631    ///
1632    /// @param[in] pid
1633    ///     The process ID that we should attempt to attach to.
1634    ///
1635    /// @return
1636    ///     Returns \a pid if attaching was successful, or
1637    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
1638    //------------------------------------------------------------------
1639    virtual Error
1640    DoAttachToProcessWithID (lldb::pid_t pid) = 0;
1641
1642    //------------------------------------------------------------------
1643    /// Attach to an existing process using a partial process name.
1644    ///
1645    /// @param[in] process_name
1646    ///     The name of the process to attach to.
1647    ///
1648    /// @param[in] wait_for_launch
1649    ///     If \b true, wait for the process to be launched and attach
1650    ///     as soon as possible after it does launch. If \b false, then
1651    ///     search for a matching process the currently exists.
1652    ///
1653    /// @return
1654    ///     Returns \a pid if attaching was successful, or
1655    ///     LLDB_INVALID_PROCESS_ID if attaching fails.
1656    //------------------------------------------------------------------
1657    virtual Error
1658    DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
1659    {
1660        Error error;
1661        error.SetErrorString("attach by name is not supported");
1662        return error;
1663    }
1664
1665    //------------------------------------------------------------------
1666    /// Called after attaching a process.
1667    ///
1668    /// Allow Process plug-ins to execute some code after attaching to
1669    /// a process.
1670    //------------------------------------------------------------------
1671    virtual void
1672    DidAttach () {}
1673
1674
1675    //------------------------------------------------------------------
1676    /// Called before launching to a process.
1677    ///
1678    /// Allow Process plug-ins to execute some code before launching a
1679    /// process.
1680    ///
1681    /// @return
1682    ///     Returns an error object.
1683    //------------------------------------------------------------------
1684    virtual Error
1685    WillLaunch (Module* module)
1686    {
1687        return Error();
1688    }
1689
1690    //------------------------------------------------------------------
1691    /// Launch a new process.
1692    ///
1693    /// Launch a new process by spawning a new process using \a module's
1694    /// file as the file to launch. Arguments are given in \a argv,
1695    /// and the environment variables are in \a envp. Standard input
1696    /// and output files can be optionally re-directed to \a stdin_path,
1697    /// \a stdout_path, and \a stderr_path.
1698    ///
1699    /// @param[in] module
1700    ///     The module from which to extract the file specification and
1701    ///     launch.
1702    ///
1703    /// @param[in] argv
1704    ///     The argument array.
1705    ///
1706    /// @param[in] envp
1707    ///     The environment array.
1708    ///
1709    /// @param[in] launch_flags
1710    ///     Flags to modify the launch (@see lldb::LaunchFlags)
1711    ///
1712    /// @param[in] stdin_path
1713    ///     The path to use when re-directing the STDIN of the new
1714    ///     process. If all stdXX_path arguments are NULL, a pseudo
1715    ///     terminal will be used.
1716    ///
1717    /// @param[in] stdout_path
1718    ///     The path to use when re-directing the STDOUT of the new
1719    ///     process. If all stdXX_path arguments are NULL, a pseudo
1720    ///     terminal will be used.
1721    ///
1722    /// @param[in] stderr_path
1723    ///     The path to use when re-directing the STDERR of the new
1724    ///     process. If all stdXX_path arguments are NULL, a pseudo
1725    ///     terminal will be used.
1726    ///
1727    /// @param[in] working_directory
1728    ///     The working directory to have the child process run in
1729    ///
1730    /// @return
1731    ///     A new valid process ID, or LLDB_INVALID_PROCESS_ID if
1732    ///     launching fails.
1733    //------------------------------------------------------------------
1734    virtual Error
1735    DoLaunch (Module* module,
1736              char const *argv[],
1737              char const *envp[],
1738              uint32_t launch_flags,
1739              const char *stdin_path,
1740              const char *stdout_path,
1741              const char *stderr_path,
1742              const char *working_directory) = 0;
1743
1744    //------------------------------------------------------------------
1745    /// Called after launching a process.
1746    ///
1747    /// Allow Process plug-ins to execute some code after launching
1748    /// a process.
1749    //------------------------------------------------------------------
1750    virtual void
1751    DidLaunch () {}
1752
1753
1754
1755    //------------------------------------------------------------------
1756    /// Called before resuming to a process.
1757    ///
1758    /// Allow Process plug-ins to execute some code before resuming a
1759    /// process.
1760    ///
1761    /// @return
1762    ///     Returns an error object.
1763    //------------------------------------------------------------------
1764    virtual Error
1765    WillResume () { return Error(); }
1766
1767    //------------------------------------------------------------------
1768    /// Resumes all of a process's threads as configured using the
1769    /// Thread run control functions.
1770    ///
1771    /// Threads for a process should be updated with one of the run
1772    /// control actions (resume, step, or suspend) that they should take
1773    /// when the process is resumed. If no run control action is given
1774    /// to a thread it will be resumed by default.
1775    ///
1776    /// @return
1777    ///     Returns \b true if the process successfully resumes using
1778    ///     the thread run control actions, \b false otherwise.
1779    ///
1780    /// @see Thread:Resume()
1781    /// @see Thread:Step()
1782    /// @see Thread:Suspend()
1783    //------------------------------------------------------------------
1784    virtual Error
1785    DoResume () = 0;
1786
1787    //------------------------------------------------------------------
1788    /// Called after resuming a process.
1789    ///
1790    /// Allow Process plug-ins to execute some code after resuming
1791    /// a process.
1792    //------------------------------------------------------------------
1793    virtual void
1794    DidResume () {}
1795
1796
1797    //------------------------------------------------------------------
1798    /// Called before halting to a process.
1799    ///
1800    /// Allow Process plug-ins to execute some code before halting a
1801    /// process.
1802    ///
1803    /// @return
1804    ///     Returns an error object.
1805    //------------------------------------------------------------------
1806    virtual Error
1807    WillHalt () { return Error(); }
1808
1809    //------------------------------------------------------------------
1810    /// Halts a running process.
1811    ///
1812    /// DoHalt must produce one and only one stop StateChanged event if it actually
1813    /// stops the process.  If the stop happens through some natural event (for
1814    /// instance a SIGSTOP), then forwarding that event will do.  Otherwise, you must
1815    /// generate the event manually.  Note also, the private event thread is stopped when
1816    /// DoHalt is run to prevent the events generated while halting to trigger
1817    /// other state changes before the halt is complete.
1818    ///
1819    /// @param[out] caused_stop
1820    ///     If true, then this Halt caused the stop, otherwise, the
1821    ///     process was already stopped.
1822    ///
1823    /// @return
1824    ///     Returns \b true if the process successfully halts, \b false
1825    ///     otherwise.
1826    //------------------------------------------------------------------
1827    virtual Error
1828    DoHalt (bool &caused_stop) = 0;
1829
1830    //------------------------------------------------------------------
1831    /// Called after halting a process.
1832    ///
1833    /// Allow Process plug-ins to execute some code after halting
1834    /// a process.
1835    //------------------------------------------------------------------
1836    virtual void
1837    DidHalt () {}
1838
1839    //------------------------------------------------------------------
1840    /// Called before detaching from a process.
1841    ///
1842    /// Allow Process plug-ins to execute some code before detaching
1843    /// from a process.
1844    ///
1845    /// @return
1846    ///     Returns an error object.
1847    //------------------------------------------------------------------
1848    virtual Error
1849    WillDetach ()
1850    {
1851        return Error();
1852    }
1853
1854    //------------------------------------------------------------------
1855    /// Detaches from a running or stopped process.
1856    ///
1857    /// @return
1858    ///     Returns \b true if the process successfully detaches, \b
1859    ///     false otherwise.
1860    //------------------------------------------------------------------
1861    virtual Error
1862    DoDetach () = 0;
1863
1864    //------------------------------------------------------------------
1865    /// Called after detaching from a process.
1866    ///
1867    /// Allow Process plug-ins to execute some code after detaching
1868    /// from a process.
1869    //------------------------------------------------------------------
1870    virtual void
1871    DidDetach () {}
1872
1873    //------------------------------------------------------------------
1874    /// Called before sending a signal to a process.
1875    ///
1876    /// Allow Process plug-ins to execute some code before sending a
1877    /// signal to a process.
1878    ///
1879    /// @return
1880    ///     Returns no error if it is safe to proceed with a call to
1881    ///     Process::DoSignal(int), otherwise an error describing what
1882    ///     prevents the signal from being sent.
1883    //------------------------------------------------------------------
1884    virtual Error
1885    WillSignal () { return Error(); }
1886
1887    //------------------------------------------------------------------
1888    /// Sends a process a UNIX signal \a signal.
1889    ///
1890    /// @return
1891    ///     Returns an error object.
1892    //------------------------------------------------------------------
1893    virtual Error
1894    DoSignal (int signal) = 0;
1895
1896
1897
1898    virtual Error
1899    WillDestroy () { return Error(); }
1900
1901    virtual Error
1902    DoDestroy () = 0;
1903
1904    virtual void
1905    DidDestroy () { }
1906
1907
1908    //------------------------------------------------------------------
1909    /// Called after sending a signal to a process.
1910    ///
1911    /// Allow Process plug-ins to execute some code after sending a
1912    /// signal to a process.
1913    //------------------------------------------------------------------
1914    virtual void
1915    DidSignal () {}
1916
1917
1918    //------------------------------------------------------------------
1919    /// Currently called as part of ShouldStop.
1920    /// FIXME: Should really happen when the target stops before the
1921    /// event is taken from the queue...
1922    ///
1923    /// This callback is called as the event
1924    /// is about to be queued up to allow Process plug-ins to execute
1925    /// some code prior to clients being notified that a process was
1926    /// stopped. Common operations include updating the thread list,
1927    /// invalidating any thread state (registers, stack, etc) prior to
1928    /// letting the notification go out.
1929    ///
1930    //------------------------------------------------------------------
1931    virtual void
1932    RefreshStateAfterStop () = 0;
1933
1934    //------------------------------------------------------------------
1935    /// Get the target object pointer for this module.
1936    ///
1937    /// @return
1938    ///     A Target object pointer to the target that owns this
1939    ///     module.
1940    //------------------------------------------------------------------
1941    Target &
1942    GetTarget ()
1943    {
1944        return m_target;
1945    }
1946
1947    //------------------------------------------------------------------
1948    /// Get the const target object pointer for this module.
1949    ///
1950    /// @return
1951    ///     A const Target object pointer to the target that owns this
1952    ///     module.
1953    //------------------------------------------------------------------
1954    const Target &
1955    GetTarget () const
1956    {
1957        return m_target;
1958    }
1959
1960
1961    //------------------------------------------------------------------
1962    /// Get accessor for the current process state.
1963    ///
1964    /// @return
1965    ///     The current state of the process.
1966    ///
1967    /// @see lldb::StateType
1968    //------------------------------------------------------------------
1969    lldb::StateType
1970    GetState ();
1971
1972    ExecutionResults
1973    RunThreadPlan (ExecutionContext &exe_ctx,
1974                    lldb::ThreadPlanSP &thread_plan_sp,
1975                    bool stop_others,
1976                    bool try_all_threads,
1977                    bool discard_on_error,
1978                    uint32_t single_thread_timeout_usec,
1979                    Stream &errors);
1980
1981    static const char *
1982    ExecutionResultAsCString (ExecutionResults result);
1983
1984    void
1985    GetStatus (Stream &ostrm);
1986
1987    size_t
1988    GetThreadStatus (Stream &ostrm,
1989                     bool only_threads_with_stop_reason,
1990                     uint32_t start_frame,
1991                     uint32_t num_frames,
1992                     uint32_t num_frames_with_source);
1993
1994protected:
1995
1996    void
1997    SetState (lldb::EventSP &event_sp);
1998
1999    lldb::StateType
2000    GetPrivateState ();
2001
2002    //------------------------------------------------------------------
2003    // Called internally
2004    //------------------------------------------------------------------
2005    void
2006    CompleteAttach ();
2007
2008public:
2009    //------------------------------------------------------------------
2010    /// Get the exit status for a process.
2011    ///
2012    /// @return
2013    ///     The process's return code, or -1 if the current process
2014    ///     state is not eStateExited.
2015    //------------------------------------------------------------------
2016    int
2017    GetExitStatus ();
2018
2019    //------------------------------------------------------------------
2020    /// Get a textual description of what the process exited.
2021    ///
2022    /// @return
2023    ///     The textual description of why the process exited, or NULL
2024    ///     if there is no description available.
2025    //------------------------------------------------------------------
2026    const char *
2027    GetExitDescription ();
2028
2029
2030    virtual void
2031    DidExit ()
2032    {
2033    }
2034
2035    //------------------------------------------------------------------
2036    /// Get the Modification ID of the process.
2037    ///
2038    /// @return
2039    ///     The modification ID of the process.
2040    //------------------------------------------------------------------
2041    ProcessModID
2042    GetModID () const
2043    {
2044        return m_mod_id;
2045    }
2046
2047    uint32_t
2048    GetStopID () const
2049    {
2050        return m_mod_id.GetStopID();
2051    }
2052
2053    //------------------------------------------------------------------
2054    /// Set accessor for the process exit status (return code).
2055    ///
2056    /// Sometimes a child exits and the exit can be detected by global
2057    /// functions (signal handler for SIGCHLD for example). This
2058    /// accessor allows the exit status to be set from an external
2059    /// source.
2060    ///
2061    /// Setting this will cause a eStateExited event to be posted to
2062    /// the process event queue.
2063    ///
2064    /// @param[in] exit_status
2065    ///     The value for the process's return code.
2066    ///
2067    /// @see lldb::StateType
2068    //------------------------------------------------------------------
2069    virtual bool
2070    SetExitStatus (int exit_status, const char *cstr);
2071
2072    //------------------------------------------------------------------
2073    /// Check if a process is still alive.
2074    ///
2075    /// @return
2076    ///     Returns \b true if the process is still valid, \b false
2077    ///     otherwise.
2078    //------------------------------------------------------------------
2079    virtual bool
2080    IsAlive () = 0;
2081
2082    //------------------------------------------------------------------
2083    /// Actually do the reading of memory from a process.
2084    ///
2085    /// Subclasses must override this function and can return fewer
2086    /// bytes than requested when memory requests are too large. This
2087    /// class will break up the memory requests and keep advancing the
2088    /// arguments along as needed.
2089    ///
2090    /// @param[in] vm_addr
2091    ///     A virtual load address that indicates where to start reading
2092    ///     memory from.
2093    ///
2094    /// @param[in] size
2095    ///     The number of bytes to read.
2096    ///
2097    /// @param[out] buf
2098    ///     A byte buffer that is at least \a size bytes long that
2099    ///     will receive the memory bytes.
2100    ///
2101    /// @return
2102    ///     The number of bytes that were actually read into \a buf.
2103    //------------------------------------------------------------------
2104    virtual size_t
2105    DoReadMemory (lldb::addr_t vm_addr,
2106                  void *buf,
2107                  size_t size,
2108                  Error &error) = 0;
2109
2110    //------------------------------------------------------------------
2111    /// Read of memory from a process.
2112    ///
2113    /// This function will read memory from the current process's
2114    /// address space and remove any traps that may have been inserted
2115    /// into the memory.
2116    ///
2117    /// This function is not meant to be overridden by Process
2118    /// subclasses, the subclasses should implement
2119    /// Process::DoReadMemory (lldb::addr_t, size_t, void *).
2120    ///
2121    /// @param[in] vm_addr
2122    ///     A virtual load address that indicates where to start reading
2123    ///     memory from.
2124    ///
2125    /// @param[out] buf
2126    ///     A byte buffer that is at least \a size bytes long that
2127    ///     will receive the memory bytes.
2128    ///
2129    /// @param[in] size
2130    ///     The number of bytes to read.
2131    ///
2132    /// @return
2133    ///     The number of bytes that were actually read into \a buf. If
2134    ///     the returned number is greater than zero, yet less than \a
2135    ///     size, then this function will get called again with \a
2136    ///     vm_addr, \a buf, and \a size updated appropriately. Zero is
2137    ///     returned to indicate an error.
2138    //------------------------------------------------------------------
2139    size_t
2140    ReadMemory (lldb::addr_t vm_addr,
2141                void *buf,
2142                size_t size,
2143                Error &error);
2144
2145    //------------------------------------------------------------------
2146    /// Read a NULL terminated C string from memory
2147    ///
2148    /// This function will read a cache page at a time until the NULL
2149    /// C stirng terminator is found. It will stop reading if the NULL
2150    /// termination byte isn't found before reading \a cstr_max_len
2151    /// bytes, and the results are always guaranteed to be NULL
2152    /// terminated (at most cstr_max_len - 1 bytes will be read).
2153    //------------------------------------------------------------------
2154    size_t
2155    ReadCStringFromMemory (lldb::addr_t vm_addr,
2156                           char *cstr,
2157                           size_t cstr_max_len);
2158
2159    size_t
2160    ReadMemoryFromInferior (lldb::addr_t vm_addr,
2161                            void *buf,
2162                            size_t size,
2163                            Error &error);
2164
2165    //------------------------------------------------------------------
2166    /// Reads an unsigned integer of the specified byte size from
2167    /// process memory.
2168    ///
2169    /// @param[in] load_addr
2170    ///     A load address of the integer to read.
2171    ///
2172    /// @param[in] byte_size
2173    ///     The size in byte of the integer to read.
2174    ///
2175    /// @param[in] fail_value
2176    ///     The value to return if we fail to read an integer.
2177    ///
2178    /// @param[out] error
2179    ///     An error that indicates the success or failure of this
2180    ///     operation. If error indicates success (error.Success()),
2181    ///     then the value returned can be trusted, otherwise zero
2182    ///     will be returned.
2183    ///
2184    /// @return
2185    ///     The unsigned integer that was read from the process memory
2186    ///     space. If the integer was smaller than a uint64_t, any
2187    ///     unused upper bytes will be zero filled. If the process
2188    ///     byte order differs from the host byte order, the integer
2189    ///     value will be appropriately byte swapped into host byte
2190    ///     order.
2191    //------------------------------------------------------------------
2192    uint64_t
2193    ReadUnsignedIntegerFromMemory (lldb::addr_t load_addr,
2194                                   size_t byte_size,
2195                                   uint64_t fail_value,
2196                                   Error &error);
2197
2198    lldb::addr_t
2199    ReadPointerFromMemory (lldb::addr_t vm_addr,
2200                           Error &error);
2201
2202    bool
2203    WritePointerToMemory (lldb::addr_t vm_addr,
2204                          lldb::addr_t ptr_value,
2205                          Error &error);
2206
2207    //------------------------------------------------------------------
2208    /// Actually do the writing of memory to a process.
2209    ///
2210    /// @param[in] vm_addr
2211    ///     A virtual load address that indicates where to start writing
2212    ///     memory to.
2213    ///
2214    /// @param[in] buf
2215    ///     A byte buffer that is at least \a size bytes long that
2216    ///     contains the data to write.
2217    ///
2218    /// @param[in] size
2219    ///     The number of bytes to write.
2220    ///
2221    /// @param[out] error
2222    ///     An error value in case the memory write fails.
2223    ///
2224    /// @return
2225    ///     The number of bytes that were actually written.
2226    //------------------------------------------------------------------
2227    virtual size_t
2228    DoWriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error) = 0;
2229
2230    //------------------------------------------------------------------
2231    /// Write all or part of a scalar value to memory.
2232    ///
2233    /// The value contained in \a scalar will be swapped to match the
2234    /// byte order of the process that is being debugged. If \a size is
2235    /// less than the size of scalar, the least significate \a size bytes
2236    /// from scalar will be written. If \a size is larger than the byte
2237    /// size of scalar, then the extra space will be padded with zeros
2238    /// and the scalar value will be placed in the least significant
2239    /// bytes in memory.
2240    ///
2241    /// @param[in] vm_addr
2242    ///     A virtual load address that indicates where to start writing
2243    ///     memory to.
2244    ///
2245    /// @param[in] scalar
2246    ///     The scalar to write to the debugged process.
2247    ///
2248    /// @param[in] size
2249    ///     This value can be smaller or larger than the scalar value
2250    ///     itself. If \a size is smaller than the size of \a scalar,
2251    ///     the least significant bytes in \a scalar will be used. If
2252    ///     \a size is larger than the byte size of \a scalar, then
2253    ///     the extra space will be padded with zeros. If \a size is
2254    ///     set to UINT32_MAX, then the size of \a scalar will be used.
2255    ///
2256    /// @param[out] error
2257    ///     An error value in case the memory write fails.
2258    ///
2259    /// @return
2260    ///     The number of bytes that were actually written.
2261    //------------------------------------------------------------------
2262    size_t
2263    WriteScalarToMemory (lldb::addr_t vm_addr,
2264                         const Scalar &scalar,
2265                         uint32_t size,
2266                         Error &error);
2267
2268    size_t
2269    ReadScalarIntegerFromMemory (lldb::addr_t addr,
2270                                 uint32_t byte_size,
2271                                 bool is_signed,
2272                                 Scalar &scalar,
2273                                 Error &error);
2274
2275    //------------------------------------------------------------------
2276    /// Write memory to a process.
2277    ///
2278    /// This function will write memory to the current process's
2279    /// address space and maintain any traps that might be present due
2280    /// to software breakpoints.
2281    ///
2282    /// This function is not meant to be overridden by Process
2283    /// subclasses, the subclasses should implement
2284    /// Process::DoWriteMemory (lldb::addr_t, size_t, void *).
2285    ///
2286    /// @param[in] vm_addr
2287    ///     A virtual load address that indicates where to start writing
2288    ///     memory to.
2289    ///
2290    /// @param[in] buf
2291    ///     A byte buffer that is at least \a size bytes long that
2292    ///     contains the data to write.
2293    ///
2294    /// @param[in] size
2295    ///     The number of bytes to write.
2296    ///
2297    /// @return
2298    ///     The number of bytes that were actually written.
2299    //------------------------------------------------------------------
2300    size_t
2301    WriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error);
2302
2303
2304    //------------------------------------------------------------------
2305    /// Actually allocate memory in the process.
2306    ///
2307    /// This function will allocate memory in the process's address
2308    /// space.  This can't rely on the generic function calling mechanism,
2309    /// since that requires this function.
2310    ///
2311    /// @param[in] size
2312    ///     The size of the allocation requested.
2313    ///
2314    /// @return
2315    ///     The address of the allocated buffer in the process, or
2316    ///     LLDB_INVALID_ADDRESS if the allocation failed.
2317    //------------------------------------------------------------------
2318
2319    virtual lldb::addr_t
2320    DoAllocateMemory (size_t size, uint32_t permissions, Error &error) = 0;
2321
2322    //------------------------------------------------------------------
2323    /// The public interface to allocating memory in the process.
2324    ///
2325    /// This function will allocate memory in the process's address
2326    /// space.  This can't rely on the generic function calling mechanism,
2327    /// since that requires this function.
2328    ///
2329    /// @param[in] size
2330    ///     The size of the allocation requested.
2331    ///
2332    /// @param[in] permissions
2333    ///     Or together any of the lldb::Permissions bits.  The permissions on
2334    ///     a given memory allocation can't be changed after allocation.  Note
2335    ///     that a block that isn't set writable can still be written on from lldb,
2336    ///     just not by the process itself.
2337    ///
2338    /// @param[in/out] error
2339    ///     An error object to fill in if things go wrong.
2340    /// @return
2341    ///     The address of the allocated buffer in the process, or
2342    ///     LLDB_INVALID_ADDRESS if the allocation failed.
2343    //------------------------------------------------------------------
2344
2345    lldb::addr_t
2346    AllocateMemory (size_t size, uint32_t permissions, Error &error);
2347
2348    //------------------------------------------------------------------
2349    /// Actually deallocate memory in the process.
2350    ///
2351    /// This function will deallocate memory in the process's address
2352    /// space that was allocated with AllocateMemory.
2353    ///
2354    /// @param[in] ptr
2355    ///     A return value from AllocateMemory, pointing to the memory you
2356    ///     want to deallocate.
2357    ///
2358    /// @return
2359    ///     \btrue if the memory was deallocated, \bfalse otherwise.
2360    //------------------------------------------------------------------
2361
2362    virtual Error
2363    DoDeallocateMemory (lldb::addr_t ptr) = 0;
2364
2365    //------------------------------------------------------------------
2366    /// The public interface to deallocating memory in the process.
2367    ///
2368    /// This function will deallocate memory in the process's address
2369    /// space that was allocated with AllocateMemory.
2370    ///
2371    /// @param[in] ptr
2372    ///     A return value from AllocateMemory, pointing to the memory you
2373    ///     want to deallocate.
2374    ///
2375    /// @return
2376    ///     \btrue if the memory was deallocated, \bfalse otherwise.
2377    //------------------------------------------------------------------
2378
2379    Error
2380    DeallocateMemory (lldb::addr_t ptr);
2381
2382    //------------------------------------------------------------------
2383    /// Get any available STDOUT.
2384    ///
2385    /// If the process was launched without supplying valid file paths
2386    /// for stdin, stdout, and stderr, then the Process class might
2387    /// try to cache the STDOUT for the process if it is able. Events
2388    /// will be queued indicating that there is STDOUT available that
2389    /// can be retrieved using this function.
2390    ///
2391    /// @param[out] buf
2392    ///     A buffer that will receive any STDOUT bytes that are
2393    ///     currently available.
2394    ///
2395    /// @param[out] buf_size
2396    ///     The size in bytes for the buffer \a buf.
2397    ///
2398    /// @return
2399    ///     The number of bytes written into \a buf. If this value is
2400    ///     equal to \a buf_size, another call to this function should
2401    ///     be made to retrieve more STDOUT data.
2402    //------------------------------------------------------------------
2403    virtual size_t
2404    GetSTDOUT (char *buf, size_t buf_size, Error &error)
2405    {
2406        error.SetErrorString("stdout unsupported");
2407        return 0;
2408    }
2409
2410
2411    //------------------------------------------------------------------
2412    /// Get any available STDERR.
2413    ///
2414    /// If the process was launched without supplying valid file paths
2415    /// for stdin, stdout, and stderr, then the Process class might
2416    /// try to cache the STDERR for the process if it is able. Events
2417    /// will be queued indicating that there is STDERR available that
2418    /// can be retrieved using this function.
2419    ///
2420    /// @param[out] buf
2421    ///     A buffer that will receive any STDERR bytes that are
2422    ///     currently available.
2423    ///
2424    /// @param[out] buf_size
2425    ///     The size in bytes for the buffer \a buf.
2426    ///
2427    /// @return
2428    ///     The number of bytes written into \a buf. If this value is
2429    ///     equal to \a buf_size, another call to this function should
2430    ///     be made to retrieve more STDERR data.
2431    //------------------------------------------------------------------
2432    virtual size_t
2433    GetSTDERR (char *buf, size_t buf_size, Error &error)
2434    {
2435        error.SetErrorString("stderr unsupported");
2436        return 0;
2437    }
2438
2439    virtual size_t
2440    PutSTDIN (const char *buf, size_t buf_size, Error &error)
2441    {
2442        error.SetErrorString("stdin unsupported");
2443        return 0;
2444    }
2445
2446    //----------------------------------------------------------------------
2447    // Process Breakpoints
2448    //----------------------------------------------------------------------
2449    size_t
2450    GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site);
2451
2452    virtual Error
2453    EnableBreakpoint (BreakpointSite *bp_site) = 0;
2454
2455    virtual Error
2456    DisableBreakpoint (BreakpointSite *bp_site) = 0;
2457
2458    // This is implemented completely using the lldb::Process API. Subclasses
2459    // don't need to implement this function unless the standard flow of
2460    // read existing opcode, write breakpoint opcode, verify breakpoint opcode
2461    // doesn't work for a specific process plug-in.
2462    virtual Error
2463    EnableSoftwareBreakpoint (BreakpointSite *bp_site);
2464
2465    // This is implemented completely using the lldb::Process API. Subclasses
2466    // don't need to implement this function unless the standard flow of
2467    // restoring original opcode in memory and verifying the restored opcode
2468    // doesn't work for a specific process plug-in.
2469    virtual Error
2470    DisableSoftwareBreakpoint (BreakpointSite *bp_site);
2471
2472    BreakpointSiteList &
2473    GetBreakpointSiteList();
2474
2475    const BreakpointSiteList &
2476    GetBreakpointSiteList() const;
2477
2478    void
2479    DisableAllBreakpointSites ();
2480
2481    Error
2482    ClearBreakpointSiteByID (lldb::user_id_t break_id);
2483
2484    lldb::break_id_t
2485    CreateBreakpointSite (lldb::BreakpointLocationSP &owner,
2486                          bool use_hardware);
2487
2488    Error
2489    DisableBreakpointSiteByID (lldb::user_id_t break_id);
2490
2491    Error
2492    EnableBreakpointSiteByID (lldb::user_id_t break_id);
2493
2494
2495    // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove
2496    // themselves from the owner's list of this breakpoint sites.  This has to
2497    // be a static function because you can't be sure that removing the
2498    // breakpoint from it's containing map won't delete the breakpoint site,
2499    // and doing that in an instance method isn't copasetic.
2500    void
2501    RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id,
2502                                   lldb::user_id_t owner_loc_id,
2503                                   lldb::BreakpointSiteSP &bp_site_sp);
2504
2505    //----------------------------------------------------------------------
2506    // Process Watchpoints (optional)
2507    //----------------------------------------------------------------------
2508    virtual Error
2509    EnableWatchpoint (WatchpointLocation *bp_loc);
2510
2511    virtual Error
2512    DisableWatchpoint (WatchpointLocation *bp_loc);
2513
2514    //------------------------------------------------------------------
2515    // Thread Queries
2516    //------------------------------------------------------------------
2517    virtual uint32_t
2518    UpdateThreadListIfNeeded () = 0;
2519
2520    ThreadList &
2521    GetThreadList ()
2522    {
2523        return m_thread_list;
2524    }
2525
2526    const ThreadList &
2527    GetThreadList () const
2528    {
2529        return m_thread_list;
2530    }
2531
2532    uint32_t
2533    GetNextThreadIndexID ();
2534
2535    //------------------------------------------------------------------
2536    // Event Handling
2537    //------------------------------------------------------------------
2538    lldb::StateType
2539    GetNextEvent (lldb::EventSP &event_sp);
2540
2541    lldb::StateType
2542    WaitForProcessToStop (const TimeValue *timeout);
2543
2544    lldb::StateType
2545    WaitForStateChangedEvents (const TimeValue *timeout, lldb::EventSP &event_sp);
2546
2547    Event *
2548    PeekAtStateChangedEvents ();
2549
2550
2551    class
2552    ProcessEventHijacker
2553    {
2554    public:
2555        ProcessEventHijacker (Process &process, Listener *listener) :
2556            m_process (process),
2557            m_listener (listener)
2558        {
2559            m_process.HijackProcessEvents (listener);
2560        }
2561        ~ProcessEventHijacker ()
2562        {
2563            m_process.RestoreProcessEvents();
2564        }
2565
2566    private:
2567        Process &m_process;
2568        Listener *m_listener;
2569    };
2570    friend class ProcessEventHijacker;
2571    //------------------------------------------------------------------
2572    /// If you need to ensure that you and only you will hear about some public
2573    /// event, then make a new listener, set to listen to process events, and
2574    /// then call this with that listener.  Then you will have to wait on that
2575    /// listener explicitly for events (rather than using the GetNextEvent & WaitFor*
2576    /// calls above.  Be sure to call RestoreProcessEvents when you are done.
2577    ///
2578    /// @param[in] listener
2579    ///     This is the new listener to whom all process events will be delivered.
2580    ///
2581    /// @return
2582    ///     Returns \b true if the new listener could be installed,
2583    ///     \b false otherwise.
2584    //------------------------------------------------------------------
2585    bool
2586    HijackProcessEvents (Listener *listener);
2587
2588    //------------------------------------------------------------------
2589    /// Restores the process event broadcasting to its normal state.
2590    ///
2591    //------------------------------------------------------------------
2592    void
2593    RestoreProcessEvents ();
2594
2595protected:
2596    //------------------------------------------------------------------
2597    /// This is the part of the event handling that for a process event.
2598    /// It decides what to do with the event and returns true if the
2599    /// event needs to be propagated to the user, and false otherwise.
2600    /// If the event is not propagated, this call will most likely set
2601    /// the target to executing again.
2602    ///
2603    /// @param[in] event_ptr
2604    ///     This is the event we are handling.
2605    ///
2606    /// @return
2607    ///     Returns \b true if the event should be reported to the
2608    ///     user, \b false otherwise.
2609    //------------------------------------------------------------------
2610    bool
2611    ShouldBroadcastEvent (Event *event_ptr);
2612
2613public:
2614    const lldb::ABISP &
2615    GetABI ();
2616
2617    DynamicLoader *
2618    GetDynamicLoader ()
2619    {
2620        return m_dyld_ap.get();
2621    }
2622
2623    virtual LanguageRuntime *
2624    GetLanguageRuntime (lldb::LanguageType language);
2625
2626    virtual CPPLanguageRuntime *
2627    GetCPPLanguageRuntime ();
2628
2629    virtual ObjCLanguageRuntime *
2630    GetObjCLanguageRuntime ();
2631
2632    bool
2633    IsRunning () const;
2634
2635    DynamicCheckerFunctions *GetDynamicCheckers()
2636    {
2637        return m_dynamic_checkers_ap.get();
2638    }
2639
2640    void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
2641    {
2642        m_dynamic_checkers_ap.reset(dynamic_checkers);
2643    }
2644
2645    //------------------------------------------------------------------
2646    /// Call this to set the lldb in the mode where it breaks on new thread
2647    /// creations, and then auto-restarts.  This is useful when you are trying
2648    /// to run only one thread, but either that thread or the kernel is creating
2649    /// new threads in the process.  If you stop when the thread is created, you
2650    /// can immediately suspend it, and keep executing only the one thread you intend.
2651    ///
2652    /// @return
2653    ///     Returns \b true if we were able to start up the notification
2654    ///     \b false otherwise.
2655    //------------------------------------------------------------------
2656    virtual bool
2657    StartNoticingNewThreads()
2658    {
2659        return true;
2660    }
2661
2662    //------------------------------------------------------------------
2663    /// Call this to turn off the stop & notice new threads mode.
2664    ///
2665    /// @return
2666    ///     Returns \b true if we were able to start up the notification
2667    ///     \b false otherwise.
2668    //------------------------------------------------------------------
2669    virtual bool
2670    StopNoticingNewThreads()
2671    {
2672        return true;
2673    }
2674
2675    //------------------------------------------------------------------
2676    // lldb::ExecutionContextScope pure virtual functions
2677    //------------------------------------------------------------------
2678    virtual Target *
2679    CalculateTarget ()
2680    {
2681        return &m_target;
2682    }
2683
2684    virtual Process *
2685    CalculateProcess ()
2686    {
2687        return this;
2688    }
2689
2690    virtual Thread *
2691    CalculateThread ()
2692    {
2693        return NULL;
2694    }
2695
2696    virtual StackFrame *
2697    CalculateStackFrame ()
2698    {
2699        return NULL;
2700    }
2701
2702    virtual void
2703    CalculateExecutionContext (ExecutionContext &exe_ctx);
2704
2705    lldb::ProcessSP
2706    GetSP ();
2707
2708protected:
2709    //------------------------------------------------------------------
2710    // NextEventAction provides a way to register an action on the next
2711    // event that is delivered to this process.  There is currently only
2712    // one next event action allowed in the process at one time.  If a
2713    // new "NextEventAction" is added while one is already present, the
2714    // old action will be discarded (with HandleBeingUnshipped called
2715    // after it is discarded.)
2716    //------------------------------------------------------------------
2717    class NextEventAction
2718    {
2719    public:
2720        typedef enum EventActionResult
2721        {
2722            eEventActionSuccess,
2723            eEventActionRetry,
2724            eEventActionExit
2725        } EventActionResult;
2726
2727        NextEventAction (Process *process) :
2728            m_process(process)
2729        {}
2730        virtual ~NextEventAction() {}
2731
2732        virtual EventActionResult PerformAction (lldb::EventSP &event_sp) = 0;
2733        virtual void HandleBeingUnshipped () {};
2734        virtual EventActionResult HandleBeingInterrupted () = 0;
2735        virtual const char *GetExitString() = 0;
2736    protected:
2737        Process *m_process;
2738    };
2739
2740    void SetNextEventAction (Process::NextEventAction *next_event_action)
2741    {
2742        if (m_next_event_action_ap.get())
2743            m_next_event_action_ap->HandleBeingUnshipped();
2744
2745        m_next_event_action_ap.reset(next_event_action);
2746    }
2747
2748    // This is the completer for Attaching:
2749    class AttachCompletionHandler : public NextEventAction
2750    {
2751    public:
2752        AttachCompletionHandler (Process *process) :
2753            NextEventAction(process)
2754        {}
2755        virtual ~AttachCompletionHandler() {}
2756
2757        virtual EventActionResult PerformAction (lldb::EventSP &event_sp);
2758        virtual EventActionResult HandleBeingInterrupted ();
2759        virtual const char *GetExitString();
2760    private:
2761        std::string m_exit_string;
2762    };
2763
2764    bool
2765    HijackPrivateProcessEvents (Listener *listener);
2766
2767    void
2768    RestorePrivateProcessEvents ();
2769
2770    bool
2771    PrivateStateThreadIsValid () const
2772    {
2773        return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
2774    }
2775
2776    //------------------------------------------------------------------
2777    // Member variables
2778    //------------------------------------------------------------------
2779    Target &                    m_target;               ///< The target that owns this process.
2780    ThreadSafeValue<lldb::StateType>  m_public_state;
2781    ThreadSafeValue<lldb::StateType>  m_private_state; // The actual state of our process
2782    Broadcaster                 m_private_state_broadcaster;  // This broadcaster feeds state changed events into the private state thread's listener.
2783    Broadcaster                 m_private_state_control_broadcaster; // This is the control broadcaster, used to pause, resume & stop the private state thread.
2784    Listener                    m_private_state_listener;     // This is the listener for the private state thread.
2785    Predicate<bool>             m_private_state_control_wait; /// This Predicate is used to signal that a control operation is complete.
2786    lldb::thread_t              m_private_state_thread;  // Thread ID for the thread that watches interal state events
2787    ProcessModID                m_mod_id;              ///< Tracks the state of the process over stops and other alterations.
2788    uint32_t                    m_thread_index_id;      ///< Each thread is created with a 1 based index that won't get re-used.
2789    int                         m_exit_status;          ///< The exit status of the process, or -1 if not set.
2790    std::string                 m_exit_string;          ///< A textual description of why a process exited.
2791    ThreadList                  m_thread_list;          ///< The threads for this process.
2792    std::vector<Notifications>  m_notifications;        ///< The list of notifications that this process can deliver.
2793    std::vector<lldb::addr_t>   m_image_tokens;
2794    Listener                    &m_listener;
2795    BreakpointSiteList          m_breakpoint_site_list; ///< This is the list of breakpoint locations we intend
2796                                                        ///< to insert in the target.
2797    std::auto_ptr<DynamicLoader> m_dyld_ap;
2798    std::auto_ptr<DynamicCheckerFunctions>  m_dynamic_checkers_ap; ///< The functions used by the expression parser to validate data that expressions use.
2799    UnixSignals                 m_unix_signals;         /// This is the current signal set for this process.
2800    lldb::ABISP                 m_abi_sp;
2801    lldb::InputReaderSP         m_process_input_reader;
2802    lldb_private::Communication m_stdio_communication;
2803    lldb_private::Mutex         m_stdio_communication_mutex;
2804    std::string                 m_stdout_data;
2805    MemoryCache                 m_memory_cache;
2806    AllocatedMemoryCache        m_allocated_memory_cache;
2807
2808    typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP> LanguageRuntimeCollection;
2809    LanguageRuntimeCollection m_language_runtimes;
2810    std::auto_ptr<NextEventAction> m_next_event_action_ap;
2811
2812    size_t
2813    RemoveBreakpointOpcodesFromBuffer (lldb::addr_t addr, size_t size, uint8_t *buf) const;
2814
2815    void
2816    SynchronouslyNotifyStateChanged (lldb::StateType state);
2817
2818    void
2819    SetPublicState (lldb::StateType new_state);
2820
2821    void
2822    SetPrivateState (lldb::StateType state);
2823
2824    bool
2825    StartPrivateStateThread ();
2826
2827    void
2828    StopPrivateStateThread ();
2829
2830    void
2831    PausePrivateStateThread ();
2832
2833    void
2834    ResumePrivateStateThread ();
2835
2836    static void *
2837    PrivateStateThread (void *arg);
2838
2839    void *
2840    RunPrivateStateThread ();
2841
2842    void
2843    HandlePrivateEvent (lldb::EventSP &event_sp);
2844
2845    lldb::StateType
2846    WaitForProcessStopPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
2847
2848    // This waits for both the state change broadcaster, and the control broadcaster.
2849    // If control_only, it only waits for the control broadcaster.
2850
2851    bool
2852    WaitForEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp, bool control_only);
2853
2854    lldb::StateType
2855    WaitForStateChangedEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
2856
2857    lldb::StateType
2858    WaitForState (const TimeValue *timeout,
2859                  const lldb::StateType *match_states,
2860                  const uint32_t num_match_states);
2861
2862    size_t
2863    WriteMemoryPrivate (lldb::addr_t addr, const void *buf, size_t size, Error &error);
2864
2865    void
2866    AppendSTDOUT (const char *s, size_t len);
2867
2868    static void
2869    STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len);
2870
2871    void
2872    PushProcessInputReader ();
2873
2874    void
2875    PopProcessInputReader ();
2876
2877    void
2878    ResetProcessInputReader ();
2879
2880    void
2881    SetUpProcessInputReader (int file_descriptor);
2882
2883    static size_t
2884    ProcessInputReaderCallback (void *baton,
2885                                InputReader &reader,
2886                                lldb::InputReaderAction notification,
2887                                const char *bytes,
2888                                size_t bytes_len);
2889
2890
2891private:
2892    //------------------------------------------------------------------
2893    // For Process only
2894    //------------------------------------------------------------------
2895    void ControlPrivateStateThread (uint32_t signal);
2896
2897    DISALLOW_COPY_AND_ASSIGN (Process);
2898
2899};
2900
2901} // namespace lldb_private
2902
2903#endif  // liblldb_Process_h_
2904