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