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