1 //===-- Process.h -----------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef liblldb_Process_h_
11 #define liblldb_Process_h_
13 #include "lldb/Host/Config.h"
23 // Other libraries and framework includes
25 #include "lldb/lldb-private.h"
26 #include "lldb/Core/ArchSpec.h"
27 #include "lldb/Core/Broadcaster.h"
28 #include "lldb/Core/Communication.h"
29 #include "lldb/Core/Error.h"
30 #include "lldb/Core/Event.h"
31 #include "lldb/Core/RangeMap.h"
32 #include "lldb/Core/StringList.h"
33 #include "lldb/Core/ThreadSafeValue.h"
34 #include "lldb/Core/PluginInterface.h"
35 #include "lldb/Core/UserSettingsController.h"
36 #include "lldb/Breakpoint/BreakpointSiteList.h"
37 #include "lldb/Expression/ClangPersistentVariables.h"
38 #include "lldb/Expression/IRDynamicChecks.h"
39 #include "lldb/Host/FileSpec.h"
40 #include "lldb/Host/Host.h"
41 #include "lldb/Host/ProcessRunLock.h"
42 #include "lldb/Interpreter/Args.h"
43 #include "lldb/Interpreter/Options.h"
44 #include "lldb/Target/ExecutionContextScope.h"
45 #include "lldb/Target/Memory.h"
46 #include "lldb/Target/QueueList.h"
47 #include "lldb/Target/ThreadList.h"
48 #include "lldb/Target/UnixSignals.h"
49 #include "lldb/Utility/PseudoTerminal.h"
51 namespace lldb_private {
53 //----------------------------------------------------------------------
55 //----------------------------------------------------------------------
56 class ProcessProperties : public Properties
59 ProcessProperties(bool is_global);
65 GetDisableMemoryCache() const;
68 GetExtraStartupCommands () const;
71 SetExtraStartupCommands (const Args &args);
74 GetPythonOSPluginPath () const;
77 SetPythonOSPluginPath (const FileSpec &file);
80 GetIgnoreBreakpointsInExpressions () const;
83 SetIgnoreBreakpointsInExpressions (bool ignore);
86 GetUnwindOnErrorInExpressions () const;
89 SetUnwindOnErrorInExpressions (bool ignore);
92 GetStopOnSharedLibraryEvents () const;
95 SetStopOnSharedLibraryEvents (bool stop);
98 GetDetachKeepsStopped () const;
101 SetDetachKeepsStopped (bool keep_stopped);
104 typedef std::shared_ptr<ProcessProperties> ProcessPropertiesSP;
106 //----------------------------------------------------------------------
109 // A base class for information for a process. This can be used to fill
110 // out information for a process prior to launching it, or it can be
111 // used for an instance of a process and can be filled in with the
112 // existing values for that process.
113 //----------------------------------------------------------------------
124 m_pid (LLDB_INVALID_PROCESS_ID)
128 ProcessInfo (const char *name,
129 const ArchSpec &arch,
131 m_executable (name, false),
144 m_executable.Clear();
146 m_environment.Clear();
150 m_pid = LLDB_INVALID_PROCESS_ID;
156 return m_executable.GetFilename().GetCString();
160 GetNameLength() const
162 return m_executable.GetFilename().GetLength();
172 SetExecutableFile (const FileSpec &exe_file, bool add_exe_file_as_first_arg)
176 m_executable = exe_file;
177 if (add_exe_file_as_first_arg)
179 char filename[PATH_MAX];
180 if (exe_file.GetPath(filename, sizeof(filename)))
181 m_arguments.InsertArgumentAtIndex (0, filename);
186 m_executable.Clear();
191 GetExecutableFile () const
209 UserIDIsValid () const
211 return m_uid != UINT32_MAX;
215 GroupIDIsValid () const
217 return m_gid != UINT32_MAX;
221 SetUserID (uint32_t uid)
227 SetGroupID (uint32_t gid)
239 GetArchitecture () const
245 SetArchitecture (ArchSpec arch)
251 GetProcessID () const
257 SetProcessID (lldb::pid_t pid)
263 ProcessIDIsValid() const
265 return m_pid != LLDB_INVALID_PROCESS_ID;
269 Dump (Stream &s, Platform *platform) const;
278 GetArguments () const
288 return m_arg0.c_str();
292 SetArg0 (const char *arg)
301 SetArguments (const Args& args, bool first_arg_is_executable);
304 SetArguments (char const **argv, bool first_arg_is_executable);
307 GetEnvironmentEntries ()
309 return m_environment;
313 GetEnvironmentEntries () const
315 return m_environment;
319 FileSpec m_executable;
320 std::string m_arg0; // argv[0] if supported. If empty, then use m_executable.
321 // Not all process plug-ins support specifying an argv[0]
322 // that differs from the resolved platform executable
323 // (which is in m_executable)
324 Args m_arguments; // All program arguments except argv[0]
332 //----------------------------------------------------------------------
333 // ProcessInstanceInfo
335 // Describes an existing process and any discoverable information that
336 // pertains to that process.
337 //----------------------------------------------------------------------
338 class ProcessInstanceInfo : public ProcessInfo
341 ProcessInstanceInfo () :
345 m_parent_pid (LLDB_INVALID_PROCESS_ID)
349 ProcessInstanceInfo (const char *name,
350 const ArchSpec &arch,
352 ProcessInfo (name, arch, pid),
355 m_parent_pid (LLDB_INVALID_PROCESS_ID)
362 ProcessInfo::Clear();
365 m_parent_pid = LLDB_INVALID_PROCESS_ID;
369 GetEffectiveUserID() const
375 GetEffectiveGroupID() const
381 EffectiveUserIDIsValid () const
383 return m_euid != UINT32_MAX;
387 EffectiveGroupIDIsValid () const
389 return m_egid != UINT32_MAX;
393 SetEffectiveUserID (uint32_t uid)
399 SetEffectiveGroupID (uint32_t gid)
405 GetParentProcessID () const
411 SetParentProcessID (lldb::pid_t pid)
417 ParentProcessIDIsValid() const
419 return m_parent_pid != LLDB_INVALID_PROCESS_ID;
423 Dump (Stream &s, Platform *platform) const;
426 DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose);
429 DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const;
434 lldb::pid_t m_parent_pid;
438 //----------------------------------------------------------------------
441 // Describes any information that is required to launch a process.
442 //----------------------------------------------------------------------
444 class ProcessLaunchInfo : public ProcessInfo
455 eFileActionDuplicate,
461 m_action (eFileActionNone),
471 m_action = eFileActionNone;
481 Duplicate (int fd, int dup_fd);
484 Open (int fd, const char *path, bool read, bool write);
486 #ifndef LLDB_DISABLE_POSIX
488 AddPosixSpawnFileAction (void *file_actions,
489 const FileAction *info,
507 GetActionArgument () const
517 return m_path.c_str();
521 Action m_action; // The action for this file
522 int m_fd; // An existing file descriptor
523 int m_arg; // oflag for eFileActionOpen*, dup_fd for eFileActionDuplicate
524 std::string m_path; // A file path to use for opening after fork or posix_spawn
527 ProcessLaunchInfo () :
536 m_monitor_callback (NULL),
537 m_monitor_callback_baton (NULL),
538 m_monitor_signals (false),
539 m_hijack_listener_sp ()
543 ProcessLaunchInfo (const char *stdin_path,
544 const char *stdout_path,
545 const char *stderr_path,
546 const char *working_directory,
547 uint32_t launch_flags) :
552 m_flags (launch_flags),
556 m_monitor_callback (NULL),
557 m_monitor_callback_baton (NULL),
558 m_monitor_signals (false),
559 m_hijack_listener_sp ()
563 ProcessLaunchInfo::FileAction file_action;
564 const bool read = true;
565 const bool write = false;
566 if (file_action.Open(STDIN_FILENO, stdin_path, read, write))
567 AppendFileAction (file_action);
571 ProcessLaunchInfo::FileAction file_action;
572 const bool read = false;
573 const bool write = true;
574 if (file_action.Open(STDOUT_FILENO, stdout_path, read, write))
575 AppendFileAction (file_action);
579 ProcessLaunchInfo::FileAction file_action;
580 const bool read = false;
581 const bool write = true;
582 if (file_action.Open(STDERR_FILENO, stderr_path, read, write))
583 AppendFileAction (file_action);
585 if (working_directory)
586 SetWorkingDirectory(working_directory);
590 AppendFileAction (const FileAction &info)
592 m_file_actions.push_back(info);
596 AppendCloseFileAction (int fd)
598 FileAction file_action;
599 if (file_action.Close (fd))
601 AppendFileAction (file_action);
608 AppendDuplicateFileAction (int fd, int dup_fd)
610 FileAction file_action;
611 if (file_action.Duplicate (fd, dup_fd))
613 AppendFileAction (file_action);
620 AppendOpenFileAction (int fd, const char *path, bool read, bool write)
622 FileAction file_action;
623 if (file_action.Open (fd, path, read, write))
625 AppendFileAction (file_action);
632 AppendSuppressFileAction (int fd, bool read, bool write)
634 FileAction file_action;
635 if (file_action.Open (fd, "/dev/null", read, write))
637 AppendFileAction (file_action);
644 FinalizeFileActions (Target *target,
645 bool default_to_use_pty);
648 GetNumFileActions () const
650 return m_file_actions.size();
654 GetFileActionAtIndex (size_t idx) const
656 if (idx < m_file_actions.size())
657 return &m_file_actions[idx];
662 GetFileActionForFD (int fd) const
664 for (size_t idx=0, count=m_file_actions.size(); idx < count; ++idx)
666 if (m_file_actions[idx].GetFD () == fd)
667 return &m_file_actions[idx];
685 GetWorkingDirectory () const
687 if (m_working_dir.empty())
689 return m_working_dir.c_str();
693 SetWorkingDirectory (const char *working_dir)
695 if (working_dir && working_dir[0])
696 m_working_dir.assign (working_dir);
698 m_working_dir.clear();
702 SwapWorkingDirectory (std::string &working_dir)
704 m_working_dir.swap (working_dir);
709 GetProcessPluginName () const
711 if (m_plugin_name.empty())
713 return m_plugin_name.c_str();
717 SetProcessPluginName (const char *plugin)
719 if (plugin && plugin[0])
720 m_plugin_name.assign (plugin);
722 m_plugin_name.clear();
730 return m_shell.c_str();
734 SetShell (const char * path)
738 m_shell.assign (path);
739 m_flags.Set (lldb::eLaunchFlagLaunchInShell);
744 m_flags.Clear (lldb::eLaunchFlagLaunchInShell);
749 GetResumeCount () const
751 return m_resume_count;
755 SetResumeCount (uint32_t c)
761 GetLaunchInSeparateProcessGroup ()
763 return m_flags.Test(lldb::eLaunchFlagLaunchInSeparateProcessGroup);
767 SetLaunchInSeparateProcessGroup (bool separate)
770 m_flags.Set(lldb::eLaunchFlagLaunchInSeparateProcessGroup);
772 m_flags.Clear (lldb::eLaunchFlagLaunchInSeparateProcessGroup);
779 ProcessInfo::Clear();
780 m_working_dir.clear();
781 m_plugin_name.clear();
784 m_file_actions.clear();
786 m_hijack_listener_sp.reset();
790 ConvertArgumentsForLaunchingInShell (Error &error,
793 bool first_arg_is_full_shell_command,
794 int32_t num_resumes);
797 SetMonitorProcessCallback (Host::MonitorChildProcessCallback callback,
799 bool monitor_signals)
801 m_monitor_callback = callback;
802 m_monitor_callback_baton = baton;
803 m_monitor_signals = monitor_signals;
806 Host::MonitorChildProcessCallback
807 GetMonitorProcessCallback ()
809 return m_monitor_callback;
813 GetMonitorProcessBaton () const
815 return m_monitor_callback_baton;
818 // If the LaunchInfo has a monitor callback, then arrange to monitor the process.
819 // Return true if the LaunchInfo has taken care of monitoring the process, and false if the
820 // caller might want to monitor the process themselves.
823 MonitorProcess () const
825 if (GetFlags().Test(lldb::eLaunchFlagsDontMonitorProcess))
828 if (m_monitor_callback && ProcessIDIsValid())
830 Host::StartMonitoringChildProcess (m_monitor_callback,
831 m_monitor_callback_baton,
839 lldb_utility::PseudoTerminal &
846 GetHijackListener () const
848 return m_hijack_listener_sp;
852 SetHijackListener (const lldb::ListenerSP &listener_sp)
854 m_hijack_listener_sp = listener_sp;
859 std::string m_working_dir;
860 std::string m_plugin_name;
862 Flags m_flags; // Bitwise OR of bits from lldb::LaunchFlags
863 std::vector<FileAction> m_file_actions; // File actions for any other files
864 lldb_utility::PseudoTerminal m_pty;
865 uint32_t m_resume_count; // How many times do we resume after launching
866 Host::MonitorChildProcessCallback m_monitor_callback;
867 void *m_monitor_callback_baton;
868 bool m_monitor_signals;
869 lldb::ListenerSP m_hijack_listener_sp;
872 //----------------------------------------------------------------------
875 // Describes any information that is required to launch a process.
876 //----------------------------------------------------------------------
878 class ProcessAttachInfo : public ProcessInstanceInfo
881 ProcessAttachInfo() :
882 ProcessInstanceInfo(),
885 m_wait_for_launch (false),
886 m_ignore_existing (true),
887 m_continue_once_attached (false)
891 ProcessAttachInfo (const ProcessLaunchInfo &launch_info) :
892 ProcessInstanceInfo(),
895 m_wait_for_launch (false),
896 m_ignore_existing (true),
897 m_continue_once_attached (false)
899 ProcessInfo::operator= (launch_info);
900 SetProcessPluginName (launch_info.GetProcessPluginName());
901 SetResumeCount (launch_info.GetResumeCount());
902 SetHijackListener(launch_info.GetHijackListener());
906 GetWaitForLaunch () const
908 return m_wait_for_launch;
912 SetWaitForLaunch (bool b)
914 m_wait_for_launch = b;
918 GetIgnoreExisting () const
920 return m_ignore_existing;
924 SetIgnoreExisting (bool b)
926 m_ignore_existing = b;
930 GetContinueOnceAttached () const
932 return m_continue_once_attached;
936 SetContinueOnceAttached (bool b)
938 m_continue_once_attached = b;
942 GetResumeCount () const
944 return m_resume_count;
948 SetResumeCount (uint32_t c)
954 GetProcessPluginName () const
956 if (m_plugin_name.empty())
958 return m_plugin_name.c_str();
962 SetProcessPluginName (const char *plugin)
964 if (plugin && plugin[0])
965 m_plugin_name.assign (plugin);
967 m_plugin_name.clear();
973 ProcessInstanceInfo::Clear();
974 m_plugin_name.clear();
976 m_wait_for_launch = false;
977 m_ignore_existing = true;
978 m_continue_once_attached = false;
982 ProcessInfoSpecified () const
984 if (GetExecutableFile())
986 if (GetProcessID() != LLDB_INVALID_PROCESS_ID)
988 if (GetParentProcessID() != LLDB_INVALID_PROCESS_ID)
994 GetHijackListener () const
996 return m_hijack_listener_sp;
1000 SetHijackListener (const lldb::ListenerSP &listener_sp)
1002 m_hijack_listener_sp = listener_sp;
1007 lldb::ListenerSP m_hijack_listener_sp;
1008 std::string m_plugin_name;
1009 uint32_t m_resume_count; // How many times do we resume after launching
1010 bool m_wait_for_launch;
1011 bool m_ignore_existing;
1012 bool m_continue_once_attached; // Supports the use-case scenario of immediately continuing the process once attached.
1015 class ProcessLaunchCommandOptions : public Options
1019 ProcessLaunchCommandOptions (CommandInterpreter &interpreter) :
1020 Options(interpreter)
1022 // Keep default values of all options in one place: OptionParsingStarting ()
1023 OptionParsingStarting ();
1026 ~ProcessLaunchCommandOptions ()
1031 SetOptionValue (uint32_t option_idx, const char *option_arg);
1034 OptionParsingStarting ()
1036 launch_info.Clear();
1039 const OptionDefinition*
1042 return g_option_table;
1045 // Options table: Required for subclasses of Options.
1047 static OptionDefinition g_option_table[];
1049 // Instance variables to hold the values for command options.
1051 ProcessLaunchInfo launch_info;
1054 //----------------------------------------------------------------------
1055 // ProcessInstanceInfoMatch
1057 // A class to help matching one ProcessInstanceInfo to another.
1058 //----------------------------------------------------------------------
1060 class ProcessInstanceInfoMatch
1063 ProcessInstanceInfoMatch () :
1065 m_name_match_type (eNameMatchIgnore),
1066 m_match_all_users (false)
1070 ProcessInstanceInfoMatch (const char *process_name,
1071 NameMatchType process_name_match_type) :
1073 m_name_match_type (process_name_match_type),
1074 m_match_all_users (false)
1076 m_match_info.GetExecutableFile().SetFile(process_name, false);
1079 ProcessInstanceInfo &
1082 return m_match_info;
1085 const ProcessInstanceInfo &
1086 GetProcessInfo () const
1088 return m_match_info;
1092 GetMatchAllUsers () const
1094 return m_match_all_users;
1098 SetMatchAllUsers (bool b)
1100 m_match_all_users = b;
1104 GetNameMatchType () const
1106 return m_name_match_type;
1110 SetNameMatchType (NameMatchType name_match_type)
1112 m_name_match_type = name_match_type;
1116 NameMatches (const char *process_name) const;
1119 Matches (const ProcessInstanceInfo &proc_info) const;
1122 MatchAllProcesses () const;
1127 ProcessInstanceInfo m_match_info;
1128 NameMatchType m_name_match_type;
1129 bool m_match_all_users;
1132 class ProcessInstanceInfoList
1135 ProcessInstanceInfoList () :
1149 return m_infos.size();
1153 Append (const ProcessInstanceInfo &info)
1155 m_infos.push_back (info);
1159 GetProcessNameAtIndex (size_t idx)
1161 if (idx < m_infos.size())
1162 return m_infos[idx].GetName();
1167 GetProcessNameLengthAtIndex (size_t idx)
1169 if (idx < m_infos.size())
1170 return m_infos[idx].GetNameLength();
1175 GetProcessIDAtIndex (size_t idx)
1177 if (idx < m_infos.size())
1178 return m_infos[idx].GetProcessID();
1183 GetInfoAtIndex (size_t idx, ProcessInstanceInfo &info)
1185 if (idx < m_infos.size())
1187 info = m_infos[idx];
1193 // You must ensure "idx" is valid before calling this function
1194 const ProcessInstanceInfo &
1195 GetProcessInfoAtIndex (size_t idx) const
1197 assert (idx < m_infos.size());
1198 return m_infos[idx];
1202 typedef std::vector<ProcessInstanceInfo> collection;
1207 // This class tracks the Modification state of the process. Things that can currently modify
1208 // the program are running the program (which will up the StopID) and writing memory (which
1209 // will up the MemoryID.)
1210 // FIXME: Should we also include modification of register states?
1214 friend bool operator== (const ProcessModID &lhs, const ProcessModID &rhs);
1218 m_last_natural_stop_id(0),
1221 m_last_user_expression_resume (0),
1222 m_running_user_expression (false)
1225 ProcessModID (const ProcessModID &rhs) :
1226 m_stop_id (rhs.m_stop_id),
1227 m_memory_id (rhs.m_memory_id)
1230 const ProcessModID & operator= (const ProcessModID &rhs)
1234 m_stop_id = rhs.m_stop_id;
1235 m_memory_id = rhs.m_memory_id;
1242 void BumpStopID () {
1244 if (!IsLastResumeForUserExpression())
1245 m_last_natural_stop_id++;
1248 void BumpMemoryID () { m_memory_id++; }
1250 void BumpResumeID () {
1252 if (m_running_user_expression > 0)
1253 m_last_user_expression_resume = m_resume_id;
1256 uint32_t GetStopID() const { return m_stop_id; }
1257 uint32_t GetLastNaturalStopID() const { return m_last_natural_stop_id; }
1258 uint32_t GetMemoryID () const { return m_memory_id; }
1259 uint32_t GetResumeID () const { return m_resume_id; }
1260 uint32_t GetLastUserExpressionResumeID () const { return m_last_user_expression_resume; }
1262 bool MemoryIDEqual (const ProcessModID &compare) const
1264 return m_memory_id == compare.m_memory_id;
1267 bool StopIDEqual (const ProcessModID &compare) const
1269 return m_stop_id == compare.m_stop_id;
1274 m_stop_id = UINT32_MAX;
1277 bool IsValid () const
1279 return m_stop_id != UINT32_MAX;
1283 IsLastResumeForUserExpression () const
1285 return m_resume_id == m_last_user_expression_resume;
1289 SetRunningUserExpression (bool on)
1291 // REMOVEME printf ("Setting running user expression %s at resume id %d - value: %d.\n", on ? "on" : "off", m_resume_id, m_running_user_expression);
1293 m_running_user_expression++;
1295 m_running_user_expression--;
1300 uint32_t m_last_natural_stop_id;
1301 uint32_t m_resume_id;
1302 uint32_t m_memory_id;
1303 uint32_t m_last_user_expression_resume;
1304 uint32_t m_running_user_expression;
1306 inline bool operator== (const ProcessModID &lhs, const ProcessModID &rhs)
1308 if (lhs.StopIDEqual (rhs)
1309 && lhs.MemoryIDEqual (rhs))
1315 inline bool operator!= (const ProcessModID &lhs, const ProcessModID &rhs)
1317 if (!lhs.StopIDEqual (rhs)
1318 || !lhs.MemoryIDEqual (rhs))
1324 class MemoryRegionInfo
1327 typedef Range<lldb::addr_t, lldb::addr_t> RangeType;
1335 MemoryRegionInfo () :
1338 m_write (eDontKnow),
1339 m_execute (eDontKnow)
1343 ~MemoryRegionInfo ()
1357 m_read = m_write = m_execute = eDontKnow;
1367 GetReadable () const
1373 GetWritable () const
1379 GetExecutable () const
1385 SetReadable (OptionalBool val)
1391 SetWritable (OptionalBool val)
1397 SetExecutable (OptionalBool val)
1404 OptionalBool m_read;
1405 OptionalBool m_write;
1406 OptionalBool m_execute;
1409 //----------------------------------------------------------------------
1410 /// @class Process Process.h "lldb/Target/Process.h"
1411 /// @brief A plug-in interface definition class for debugging a process.
1412 //----------------------------------------------------------------------
1414 public std::enable_shared_from_this<Process>,
1415 public ProcessProperties,
1418 public ExecutionContextScope,
1419 public PluginInterface
1421 friend class ClangFunction; // For WaitForStateChangeEventsPrivate
1422 friend class ProcessEventData;
1423 friend class StopInfo;
1424 friend class Target;
1425 friend class ThreadList;
1429 //------------------------------------------------------------------
1430 /// Broadcaster event bits definitions.
1431 //------------------------------------------------------------------
1434 eBroadcastBitStateChanged = (1 << 0),
1435 eBroadcastBitInterrupt = (1 << 1),
1436 eBroadcastBitSTDOUT = (1 << 2),
1437 eBroadcastBitSTDERR = (1 << 3),
1438 eBroadcastBitProfileData = (1 << 4)
1443 eBroadcastInternalStateControlStop = (1<<0),
1444 eBroadcastInternalStateControlPause = (1<<1),
1445 eBroadcastInternalStateControlResume = (1<<2)
1448 typedef Range<lldb::addr_t, lldb::addr_t> LoadRange;
1449 // We use a read/write lock to allow on or more clients to
1450 // access the process state while the process is stopped (reader).
1451 // We lock the write lock to control access to the process
1452 // while it is running (readers, or clients that want the process
1453 // stopped can block waiting for the process to stop, or just
1454 // try to lock it to see if they can immediately access the stopped
1455 // process. If the try read lock fails, then the process is running.
1456 typedef ProcessRunLock::ProcessRunLocker StopLocker;
1458 // These two functions fill out the Broadcaster interface:
1460 static ConstString &GetStaticBroadcasterClass ();
1462 virtual ConstString &GetBroadcasterClass() const
1464 return GetStaticBroadcasterClass();
1468 //------------------------------------------------------------------
1469 /// A notification structure that can be used by clients to listen
1470 /// for changes in a process's lifetime.
1472 /// @see RegisterNotificationCallbacks (const Notifications&)
1473 /// @see UnregisterNotificationCallbacks (const Notifications&)
1474 //------------------------------------------------------------------
1479 void (*initialize)(void *baton, Process *process);
1480 void (*process_state_changed) (void *baton, Process *process, lldb::StateType state);
1483 class ProcessEventData :
1486 friend class Process;
1489 ProcessEventData ();
1490 ProcessEventData (const lldb::ProcessSP &process, lldb::StateType state);
1492 virtual ~ProcessEventData();
1494 static const ConstString &
1497 virtual const ConstString &
1500 const lldb::ProcessSP &
1501 GetProcessSP() const
1503 return m_process_sp;
1511 GetRestarted () const
1517 GetNumRestartedReasons ()
1519 return m_restarted_reasons.size();
1523 GetRestartedReasonAtIndex(size_t idx)
1525 if (idx > m_restarted_reasons.size())
1528 return m_restarted_reasons[idx].c_str();
1532 GetInterrupted () const
1534 return m_interrupted;
1538 Dump (Stream *s) const;
1541 DoOnRemoval (Event *event_ptr);
1543 static const Process::ProcessEventData *
1544 GetEventDataFromEvent (const Event *event_ptr);
1546 static lldb::ProcessSP
1547 GetProcessFromEvent (const Event *event_ptr);
1549 static lldb::StateType
1550 GetStateFromEvent (const Event *event_ptr);
1553 GetRestartedFromEvent (const Event *event_ptr);
1556 GetNumRestartedReasons(const Event *event_ptr);
1559 GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx);
1562 AddRestartedReason (Event *event_ptr, const char *reason);
1565 SetRestartedInEvent (Event *event_ptr, bool new_value);
1568 GetInterruptedFromEvent (const Event *event_ptr);
1571 SetInterruptedInEvent (Event *event_ptr, bool new_value);
1574 SetUpdateStateOnRemoval (Event *event_ptr);
1579 SetUpdateStateOnRemoval()
1584 SetRestarted (bool new_value)
1586 m_restarted = new_value;
1589 SetInterrupted (bool new_value)
1591 m_interrupted = new_value;
1594 AddRestartedReason (const char *reason)
1596 m_restarted_reasons.push_back(reason);
1599 lldb::ProcessSP m_process_sp;
1600 lldb::StateType m_state;
1601 std::vector<std::string> m_restarted_reasons;
1602 bool m_restarted; // For "eStateStopped" events, this is true if the target was automatically restarted.
1605 DISALLOW_COPY_AND_ASSIGN (ProcessEventData);
1612 SettingsInitialize ();
1615 SettingsTerminate ();
1617 static const ProcessPropertiesSP &
1618 GetGlobalProperties();
1620 //------------------------------------------------------------------
1621 /// Construct with a shared pointer to a target, and the Process listener.
1622 //------------------------------------------------------------------
1623 Process(Target &target, Listener &listener);
1625 //------------------------------------------------------------------
1628 /// The destructor is virtual since this class is designed to be
1629 /// inherited from by the plug-in instance.
1630 //------------------------------------------------------------------
1634 //------------------------------------------------------------------
1635 /// Find a Process plug-in that can debug \a module using the
1636 /// currently selected architecture.
1638 /// Scans all loaded plug-in interfaces that implement versions of
1639 /// the Process plug-in interface and returns the first instance
1640 /// that can debug the file.
1642 /// @param[in] module_sp
1643 /// The module shared pointer that this process will debug.
1645 /// @param[in] plugin_name
1646 /// If NULL, select the best plug-in for the binary. If non-NULL
1647 /// then look for a plugin whose PluginInfo's name matches
1650 /// @see Process::CanDebug ()
1651 //------------------------------------------------------------------
1652 static lldb::ProcessSP
1653 FindPlugin (Target &target,
1654 const char *plugin_name,
1656 const FileSpec *crash_file_path);
1660 //------------------------------------------------------------------
1661 /// Static function that can be used with the \b host function
1662 /// Host::StartMonitoringChildProcess ().
1664 /// This function can be used by lldb_private::Process subclasses
1665 /// when they want to watch for a local process and have its exit
1666 /// status automatically set when the host child process exits.
1667 /// Subclasses should call Host::StartMonitoringChildProcess ()
1669 /// callback = Process::SetHostProcessExitStatus
1670 /// callback_baton = NULL
1671 /// pid = Process::GetID()
1672 /// monitor_signals = false
1673 //------------------------------------------------------------------
1675 SetProcessExitStatus (void *callback_baton, // The callback baton which should be set to NULL
1676 lldb::pid_t pid, // The process ID we want to monitor
1678 int signo, // Zero for no signal
1679 int status); // Exit value of process if signal is zero
1682 GetByteOrder () const;
1685 GetAddressByteSize () const;
1690 return m_process_unique_id;
1692 //------------------------------------------------------------------
1693 /// Check if a plug-in instance can debug the file in \a module.
1695 /// Each plug-in is given a chance to say whether it can debug
1696 /// the file in \a module. If the Process plug-in instance can
1697 /// debug a file on the current system, it should return \b true.
1700 /// Returns \b true if this Process plug-in instance can
1701 /// debug the executable, \b false otherwise.
1702 //------------------------------------------------------------------
1704 CanDebug (Target &target,
1705 bool plugin_specified_by_name) = 0;
1708 //------------------------------------------------------------------
1709 /// This object is about to be destroyed, do any necessary cleanup.
1711 /// Subclasses that override this method should always call this
1712 /// superclass method.
1713 //------------------------------------------------------------------
1718 //------------------------------------------------------------------
1719 /// Return whether this object is valid (i.e. has not been finalized.)
1722 /// Returns \b true if this Process has not been finalized
1723 /// and \b false otherwise.
1724 //------------------------------------------------------------------
1728 return !m_finalize_called;
1731 //------------------------------------------------------------------
1732 /// Return a multi-word command object that can be used to expose
1733 /// plug-in specific commands.
1735 /// This object will be used to resolve plug-in commands and can be
1736 /// triggered by a call to:
1738 /// (lldb) process commmand <args>
1741 /// A CommandObject which can be one of the concrete subclasses
1742 /// of CommandObject like CommandObjectRaw, CommandObjectParsed,
1743 /// or CommandObjectMultiword.
1744 //------------------------------------------------------------------
1745 virtual CommandObject *
1746 GetPluginCommandObject()
1751 //------------------------------------------------------------------
1752 /// Launch a new process.
1754 /// Launch a new process by spawning a new process using the
1755 /// target object's executable module's file as the file to launch.
1756 /// Arguments are given in \a argv, and the environment variables
1757 /// are in \a envp. Standard input and output files can be
1758 /// optionally re-directed to \a stdin_path, \a stdout_path, and
1761 /// This function is not meant to be overridden by Process
1762 /// subclasses. It will first call Process::WillLaunch (Module *)
1763 /// and if that returns \b true, Process::DoLaunch (Module*,
1764 /// char const *[],char const *[],const char *,const char *,
1765 /// const char *) will be called to actually do the launching. If
1766 /// DoLaunch returns \b true, then Process::DidLaunch() will be
1770 /// The argument array.
1773 /// The environment array.
1775 /// @param[in] launch_flags
1776 /// Flags to modify the launch (@see lldb::LaunchFlags)
1778 /// @param[in] stdin_path
1779 /// The path to use when re-directing the STDIN of the new
1780 /// process. If all stdXX_path arguments are NULL, a pseudo
1781 /// terminal will be used.
1783 /// @param[in] stdout_path
1784 /// The path to use when re-directing the STDOUT of the new
1785 /// process. If all stdXX_path arguments are NULL, a pseudo
1786 /// terminal will be used.
1788 /// @param[in] stderr_path
1789 /// The path to use when re-directing the STDERR of the new
1790 /// process. If all stdXX_path arguments are NULL, a pseudo
1791 /// terminal will be used.
1793 /// @param[in] working_directory
1794 /// The working directory to have the child process run in
1797 /// An error object. Call GetID() to get the process ID if
1798 /// the error object is success.
1799 //------------------------------------------------------------------
1801 Launch (ProcessLaunchInfo &launch_info);
1810 error.SetErrorStringWithFormat("error: %s does not support loading core files.", GetPluginName().GetCString());
1814 //------------------------------------------------------------------
1815 /// Get the dynamic loader plug-in for this process.
1817 /// The default action is to let the DynamicLoader plug-ins check
1818 /// the main executable and the DynamicLoader will select itself
1819 /// automatically. Subclasses can override this if inspecting the
1820 /// executable is not desired, or if Process subclasses can only
1821 /// use a specific DynamicLoader plug-in.
1822 //------------------------------------------------------------------
1823 virtual DynamicLoader *
1824 GetDynamicLoader ();
1826 //------------------------------------------------------------------
1827 /// Get the system runtime plug-in for this process.
1830 /// Returns a pointer to the SystemRuntime plugin for this Process
1831 /// if one is available. Else returns NULL.
1832 //------------------------------------------------------------------
1833 virtual SystemRuntime *
1834 GetSystemRuntime ();
1836 //------------------------------------------------------------------
1837 /// Attach to an existing process using the process attach info.
1839 /// This function is not meant to be overridden by Process
1840 /// subclasses. It will first call WillAttach (lldb::pid_t)
1841 /// or WillAttach (const char *), and if that returns \b
1842 /// true, DoAttach (lldb::pid_t) or DoAttach (const char *) will
1843 /// be called to actually do the attach. If DoAttach returns \b
1844 /// true, then Process::DidAttach() will be called.
1847 /// The process ID that we should attempt to attach to.
1850 /// Returns \a pid if attaching was successful, or
1851 /// LLDB_INVALID_PROCESS_ID if attaching fails.
1852 //------------------------------------------------------------------
1854 Attach (ProcessAttachInfo &attach_info);
1856 //------------------------------------------------------------------
1857 /// Attach to a remote system via a URL
1860 /// A stream where output intended for the user
1861 /// (if the driver has a way to display that) generated during
1862 /// the connection. This may be NULL if no output is needed.A
1864 /// @param[in] remote_url
1865 /// The URL format that we are connecting to.
1868 /// Returns an error object.
1869 //------------------------------------------------------------------
1871 ConnectRemote (Stream *strm, const char *remote_url);
1874 GetShouldDetach () const
1876 return m_should_detach;
1880 SetShouldDetach (bool b)
1882 m_should_detach = b;
1885 //------------------------------------------------------------------
1886 /// Get the image information address for the current process.
1888 /// Some runtimes have system functions that can help dynamic
1889 /// loaders locate the dynamic loader information needed to observe
1890 /// shared libraries being loaded or unloaded. This function is
1891 /// in the Process interface (as opposed to the DynamicLoader
1892 /// interface) to ensure that remote debugging can take advantage of
1893 /// this functionality.
1896 /// The address of the dynamic loader information, or
1897 /// LLDB_INVALID_ADDRESS if this is not supported by this
1899 //------------------------------------------------------------------
1900 virtual lldb::addr_t
1901 GetImageInfoAddress ();
1903 //------------------------------------------------------------------
1904 /// Load a shared library into this process.
1906 /// Try and load a shared library into the current process. This
1907 /// call might fail in the dynamic loader plug-in says it isn't safe
1908 /// to try and load shared libraries at the moment.
1910 /// @param[in] image_spec
1911 /// The image file spec that points to the shared library that
1912 /// you want to load.
1914 /// @param[out] error
1915 /// An error object that gets filled in with any errors that
1916 /// might occur when trying to load the shared library.
1919 /// A token that represents the shared library that can be
1920 /// later used to unload the shared library. A value of
1921 /// LLDB_INVALID_IMAGE_TOKEN will be returned if the shared
1922 /// library can't be opened.
1923 //------------------------------------------------------------------
1925 LoadImage (const FileSpec &image_spec, Error &error);
1928 UnloadImage (uint32_t image_token);
1930 //------------------------------------------------------------------
1931 /// Register for process and thread notifications.
1933 /// Clients can register nofication callbacks by filling out a
1934 /// Process::Notifications structure and calling this function.
1936 /// @param[in] callbacks
1937 /// A structure that contains the notification baton and
1938 /// callback functions.
1940 /// @see Process::Notifications
1941 //------------------------------------------------------------------
1944 RegisterNotificationCallbacks (const Process::Notifications& callbacks);
1946 //------------------------------------------------------------------
1947 /// Unregister for process and thread notifications.
1949 /// Clients can unregister nofication callbacks by passing a copy of
1950 /// the original baton and callbacks in \a callbacks.
1952 /// @param[in] callbacks
1953 /// A structure that contains the notification baton and
1954 /// callback functions.
1957 /// Returns \b true if the notification callbacks were
1958 /// successfully removed from the process, \b false otherwise.
1960 /// @see Process::Notifications
1961 //------------------------------------------------------------------
1964 UnregisterNotificationCallbacks (const Process::Notifications& callbacks);
1966 //==================================================================
1967 // Built in Process Control functions
1968 //==================================================================
1969 //------------------------------------------------------------------
1970 /// Resumes all of a process's threads as configured using the
1971 /// Thread run control functions.
1973 /// Threads for a process should be updated with one of the run
1974 /// control actions (resume, step, or suspend) that they should take
1975 /// when the process is resumed. If no run control action is given
1976 /// to a thread it will be resumed by default.
1978 /// This function is not meant to be overridden by Process
1979 /// subclasses. This function will take care of disabling any
1980 /// breakpoints that threads may be stopped at, single stepping, and
1981 /// re-enabling breakpoints, and enabling the basic flow control
1982 /// that the plug-in instances need not worry about.
1984 /// N.B. This function also sets the Write side of the Run Lock,
1985 /// which is unset when the corresponding stop event is pulled off
1986 /// the Public Event Queue. If you need to resume the process without
1987 /// setting the Run Lock, use PrivateResume (though you should only do
1988 /// that from inside the Process class.
1991 /// Returns an error object.
1993 /// @see Thread:Resume()
1994 /// @see Thread:Step()
1995 /// @see Thread:Suspend()
1996 //------------------------------------------------------------------
2000 //------------------------------------------------------------------
2001 /// Halts a running process.
2003 /// This function is not meant to be overridden by Process
2005 /// If the process is successfully halted, a eStateStopped
2006 /// process event with GetInterrupted will be broadcast. If false, we will
2007 /// halt the process with no events generated by the halt.
2009 /// @param[in] clear_thread_plans
2010 /// If true, when the process stops, clear all thread plans.
2013 /// Returns an error object. If the error is empty, the process is halted.
2014 /// otherwise the halt has failed.
2015 //------------------------------------------------------------------
2017 Halt (bool clear_thread_plans = false);
2019 //------------------------------------------------------------------
2020 /// Detaches from a running or stopped process.
2022 /// This function is not meant to be overridden by Process
2025 /// @param[in] keep_stopped
2026 /// If true, don't resume the process on detach.
2029 /// Returns an error object.
2030 //------------------------------------------------------------------
2032 Detach (bool keep_stopped);
2034 //------------------------------------------------------------------
2035 /// Kills the process and shuts down all threads that were spawned
2036 /// to track and monitor the process.
2038 /// This function is not meant to be overridden by Process
2042 /// Returns an error object.
2043 //------------------------------------------------------------------
2047 //------------------------------------------------------------------
2048 /// Sends a process a UNIX signal \a signal.
2050 /// This function is not meant to be overridden by Process
2054 /// Returns an error object.
2055 //------------------------------------------------------------------
2057 Signal (int signal);
2059 virtual UnixSignals &
2062 return m_unix_signals;
2065 //==================================================================
2066 // Plug-in Process Control Overrides
2067 //==================================================================
2069 //------------------------------------------------------------------
2070 /// Called before attaching to a process.
2072 /// Allow Process plug-ins to execute some code before attaching a
2076 /// Returns an error object.
2077 //------------------------------------------------------------------
2079 WillAttachToProcessWithID (lldb::pid_t pid)
2084 //------------------------------------------------------------------
2085 /// Called before attaching to a process.
2087 /// Allow Process plug-ins to execute some code before attaching a
2091 /// Returns an error object.
2092 //------------------------------------------------------------------
2094 WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
2099 //------------------------------------------------------------------
2100 /// Attach to a remote system via a URL
2103 /// A stream where output intended for the user
2104 /// (if the driver has a way to display that) generated during
2105 /// the connection. This may be NULL if no output is needed.A
2107 /// @param[in] remote_url
2108 /// The URL format that we are connecting to.
2111 /// Returns an error object.
2112 //------------------------------------------------------------------
2114 DoConnectRemote (Stream *strm, const char *remote_url)
2117 error.SetErrorString ("remote connections are not supported");
2121 //------------------------------------------------------------------
2122 /// Attach to an existing process using a process ID.
2125 /// The process ID that we should attempt to attach to.
2128 /// Returns \a pid if attaching was successful, or
2129 /// LLDB_INVALID_PROCESS_ID if attaching fails.
2130 //------------------------------------------------------------------
2132 DoAttachToProcessWithID (lldb::pid_t pid)
2135 error.SetErrorStringWithFormat("error: %s does not support attaching to a process by pid", GetPluginName().GetCString());
2139 //------------------------------------------------------------------
2140 /// Attach to an existing process using a process ID.
2143 /// The process ID that we should attempt to attach to.
2145 /// @param[in] attach_info
2146 /// Information on how to do the attach. For example, GetUserID()
2147 /// will return the uid to attach as.
2150 /// Returns \a pid if attaching was successful, or
2151 /// LLDB_INVALID_PROCESS_ID if attaching fails.
2152 /// hanming : need flag
2153 //------------------------------------------------------------------
2155 DoAttachToProcessWithID (lldb::pid_t pid, const ProcessAttachInfo &attach_info)
2158 error.SetErrorStringWithFormat("error: %s does not support attaching to a process by pid", GetPluginName().GetCString());
2162 //------------------------------------------------------------------
2163 /// Attach to an existing process using a partial process name.
2165 /// @param[in] process_name
2166 /// The name of the process to attach to.
2168 /// @param[in] attach_info
2169 /// Information on how to do the attach. For example, GetUserID()
2170 /// will return the uid to attach as.
2173 /// Returns an error object.
2174 //------------------------------------------------------------------
2176 DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
2179 error.SetErrorString("attach by name is not supported");
2183 //------------------------------------------------------------------
2184 /// Called after attaching a process.
2186 /// Allow Process plug-ins to execute some code after attaching to
2188 //------------------------------------------------------------------
2193 //------------------------------------------------------------------
2194 /// Called after a process re-execs itself.
2196 /// Allow Process plug-ins to execute some code after a process has
2197 /// exec'ed itself. Subclasses typically should override DoDidExec()
2198 /// as the lldb_private::Process class needs to remove its dynamic
2199 /// loader, runtime, ABI and other plug-ins, as well as unload all
2200 /// shared libraries.
2201 //------------------------------------------------------------------
2205 //------------------------------------------------------------------
2206 /// Subclasses of Process should implement this function if they
2207 /// need to do anything after a process exec's itself.
2208 //------------------------------------------------------------------
2214 //------------------------------------------------------------------
2215 /// Called before launching to a process.
2217 /// Allow Process plug-ins to execute some code before launching a
2221 /// Returns an error object.
2222 //------------------------------------------------------------------
2224 WillLaunch (Module* module)
2229 //------------------------------------------------------------------
2230 /// Launch a new process.
2232 /// Launch a new process by spawning a new process using \a module's
2233 /// file as the file to launch. Arguments are given in \a argv,
2234 /// and the environment variables are in \a envp. Standard input
2235 /// and output files can be optionally re-directed to \a stdin_path,
2236 /// \a stdout_path, and \a stderr_path.
2238 /// @param[in] module
2239 /// The module from which to extract the file specification and
2243 /// The argument array.
2246 /// The environment array.
2248 /// @param[in] launch_flags
2249 /// Flags to modify the launch (@see lldb::LaunchFlags)
2251 /// @param[in] stdin_path
2252 /// The path to use when re-directing the STDIN of the new
2253 /// process. If all stdXX_path arguments are NULL, a pseudo
2254 /// terminal will be used.
2256 /// @param[in] stdout_path
2257 /// The path to use when re-directing the STDOUT of the new
2258 /// process. If all stdXX_path arguments are NULL, a pseudo
2259 /// terminal will be used.
2261 /// @param[in] stderr_path
2262 /// The path to use when re-directing the STDERR of the new
2263 /// process. If all stdXX_path arguments are NULL, a pseudo
2264 /// terminal will be used.
2266 /// @param[in] working_directory
2267 /// The working directory to have the child process run in
2270 /// A new valid process ID, or LLDB_INVALID_PROCESS_ID if
2271 /// launching fails.
2272 //------------------------------------------------------------------
2274 DoLaunch (Module *exe_module,
2275 ProcessLaunchInfo &launch_info)
2278 error.SetErrorStringWithFormat("error: %s does not support launching processes", GetPluginName().GetCString());
2283 //------------------------------------------------------------------
2284 /// Called after launching a process.
2286 /// Allow Process plug-ins to execute some code after launching
2288 //------------------------------------------------------------------
2294 //------------------------------------------------------------------
2295 /// Called before resuming to a process.
2297 /// Allow Process plug-ins to execute some code before resuming a
2301 /// Returns an error object.
2302 //------------------------------------------------------------------
2304 WillResume () { return Error(); }
2306 //------------------------------------------------------------------
2307 /// Resumes all of a process's threads as configured using the
2308 /// Thread run control functions.
2310 /// Threads for a process should be updated with one of the run
2311 /// control actions (resume, step, or suspend) that they should take
2312 /// when the process is resumed. If no run control action is given
2313 /// to a thread it will be resumed by default.
2316 /// Returns \b true if the process successfully resumes using
2317 /// the thread run control actions, \b false otherwise.
2319 /// @see Thread:Resume()
2320 /// @see Thread:Step()
2321 /// @see Thread:Suspend()
2322 //------------------------------------------------------------------
2327 error.SetErrorStringWithFormat("error: %s does not support resuming processes", GetPluginName().GetCString());
2332 //------------------------------------------------------------------
2333 /// Called after resuming a process.
2335 /// Allow Process plug-ins to execute some code after resuming
2337 //------------------------------------------------------------------
2342 //------------------------------------------------------------------
2343 /// Called before halting to a process.
2345 /// Allow Process plug-ins to execute some code before halting a
2349 /// Returns an error object.
2350 //------------------------------------------------------------------
2352 WillHalt () { return Error(); }
2354 //------------------------------------------------------------------
2355 /// Halts a running process.
2357 /// DoHalt must produce one and only one stop StateChanged event if it actually
2358 /// stops the process. If the stop happens through some natural event (for
2359 /// instance a SIGSTOP), then forwarding that event will do. Otherwise, you must
2360 /// generate the event manually. Note also, the private event thread is stopped when
2361 /// DoHalt is run to prevent the events generated while halting to trigger
2362 /// other state changes before the halt is complete.
2364 /// @param[out] caused_stop
2365 /// If true, then this Halt caused the stop, otherwise, the
2366 /// process was already stopped.
2369 /// Returns \b true if the process successfully halts, \b false
2371 //------------------------------------------------------------------
2373 DoHalt (bool &caused_stop)
2376 error.SetErrorStringWithFormat("error: %s does not support halting processes", GetPluginName().GetCString());
2381 //------------------------------------------------------------------
2382 /// Called after halting a process.
2384 /// Allow Process plug-ins to execute some code after halting
2386 //------------------------------------------------------------------
2390 //------------------------------------------------------------------
2391 /// Called before detaching from a process.
2393 /// Allow Process plug-ins to execute some code before detaching
2397 /// Returns an error object.
2398 //------------------------------------------------------------------
2405 //------------------------------------------------------------------
2406 /// Detaches from a running or stopped process.
2409 /// Returns \b true if the process successfully detaches, \b
2410 /// false otherwise.
2411 //------------------------------------------------------------------
2413 DoDetach (bool keep_stopped)
2416 error.SetErrorStringWithFormat("error: %s does not support detaching from processes", GetPluginName().GetCString());
2421 //------------------------------------------------------------------
2422 /// Called after detaching from a process.
2424 /// Allow Process plug-ins to execute some code after detaching
2426 //------------------------------------------------------------------
2431 DetachRequiresHalt() { return false; }
2433 //------------------------------------------------------------------
2434 /// Called before sending a signal to a process.
2436 /// Allow Process plug-ins to execute some code before sending a
2437 /// signal to a process.
2440 /// Returns no error if it is safe to proceed with a call to
2441 /// Process::DoSignal(int), otherwise an error describing what
2442 /// prevents the signal from being sent.
2443 //------------------------------------------------------------------
2445 WillSignal () { return Error(); }
2447 //------------------------------------------------------------------
2448 /// Sends a process a UNIX signal \a signal.
2451 /// Returns an error object.
2452 //------------------------------------------------------------------
2454 DoSignal (int signal)
2457 error.SetErrorStringWithFormat("error: %s does not support senging signals to processes", GetPluginName().GetCString());
2462 WillDestroy () { return Error(); }
2471 DestroyRequiresHalt() { return true; }
2474 //------------------------------------------------------------------
2475 /// Called after sending a signal to a process.
2477 /// Allow Process plug-ins to execute some code after sending a
2478 /// signal to a process.
2479 //------------------------------------------------------------------
2483 //------------------------------------------------------------------
2484 /// Currently called as part of ShouldStop.
2485 /// FIXME: Should really happen when the target stops before the
2486 /// event is taken from the queue...
2488 /// This callback is called as the event
2489 /// is about to be queued up to allow Process plug-ins to execute
2490 /// some code prior to clients being notified that a process was
2491 /// stopped. Common operations include updating the thread list,
2492 /// invalidating any thread state (registers, stack, etc) prior to
2493 /// letting the notification go out.
2495 //------------------------------------------------------------------
2497 RefreshStateAfterStop () = 0;
2499 //------------------------------------------------------------------
2500 /// Get the target object pointer for this module.
2503 /// A Target object pointer to the target that owns this
2505 //------------------------------------------------------------------
2512 //------------------------------------------------------------------
2513 /// Get the const target object pointer for this module.
2516 /// A const Target object pointer to the target that owns this
2518 //------------------------------------------------------------------
2525 //------------------------------------------------------------------
2526 /// Flush all data in the process.
2528 /// Flush the memory caches, all threads, and any other cached data
2531 /// This function can be called after a world changing event like
2532 /// adding a new symbol file, or after the process makes a large
2533 /// context switch (from boot ROM to booted into an OS).
2534 //------------------------------------------------------------------
2538 //------------------------------------------------------------------
2539 /// Get accessor for the current process state.
2542 /// The current state of the process.
2544 /// @see lldb::StateType
2545 //------------------------------------------------------------------
2550 RunThreadPlan (ExecutionContext &exe_ctx,
2551 lldb::ThreadPlanSP &thread_plan_sp,
2552 const EvaluateExpressionOptions &options,
2556 ExecutionResultAsCString (ExecutionResults result);
2559 GetStatus (Stream &ostrm);
2562 GetThreadStatus (Stream &ostrm,
2563 bool only_threads_with_stop_reason,
2564 uint32_t start_frame,
2565 uint32_t num_frames,
2566 uint32_t num_frames_with_source);
2569 SendAsyncInterrupt ();
2574 SetState (lldb::EventSP &event_sp);
2579 //------------------------------------------------------------------
2580 /// The "private" side of resuming a process. This doesn't alter the
2581 /// state of m_run_lock, but just causes the process to resume.
2584 /// An Error object describing the success or failure of the resume.
2585 //------------------------------------------------------------------
2589 //------------------------------------------------------------------
2590 // Called internally
2591 //------------------------------------------------------------------
2596 //------------------------------------------------------------------
2597 /// Get the exit status for a process.
2600 /// The process's return code, or -1 if the current process
2601 /// state is not eStateExited.
2602 //------------------------------------------------------------------
2606 //------------------------------------------------------------------
2607 /// Get a textual description of what the process exited.
2610 /// The textual description of why the process exited, or NULL
2611 /// if there is no description available.
2612 //------------------------------------------------------------------
2614 GetExitDescription ();
2622 //------------------------------------------------------------------
2623 /// Get the Modification ID of the process.
2626 /// The modification ID of the process.
2627 //------------------------------------------------------------------
2634 const ProcessModID &
2635 GetModIDRef () const
2643 return m_mod_id.GetStopID();
2647 GetResumeID () const
2649 return m_mod_id.GetResumeID();
2653 GetLastUserExpressionResumeID () const
2655 return m_mod_id.GetLastUserExpressionResumeID();
2659 GetLastNaturalStopID()
2661 return m_mod_id.GetLastNaturalStopID();
2664 //------------------------------------------------------------------
2665 /// Set accessor for the process exit status (return code).
2667 /// Sometimes a child exits and the exit can be detected by global
2668 /// functions (signal handler for SIGCHLD for example). This
2669 /// accessor allows the exit status to be set from an external
2672 /// Setting this will cause a eStateExited event to be posted to
2673 /// the process event queue.
2675 /// @param[in] exit_status
2676 /// The value for the process's return code.
2678 /// @see lldb::StateType
2679 //------------------------------------------------------------------
2681 SetExitStatus (int exit_status, const char *cstr);
2683 //------------------------------------------------------------------
2684 /// Check if a process is still alive.
2687 /// Returns \b true if the process is still valid, \b false
2689 //------------------------------------------------------------------
2693 //------------------------------------------------------------------
2694 /// Before lldb detaches from a process, it warns the user that they are about to lose their debug session.
2695 /// In some cases, this warning doesn't need to be emitted -- for instance, with core file debugging where
2696 /// the user can reconstruct the "state" by simply re-running the debugger on the core file.
2699 // true if the user should be warned about detaching from this process.
2700 //------------------------------------------------------------------
2702 WarnBeforeDetach () const
2707 //------------------------------------------------------------------
2708 /// Actually do the reading of memory from a process.
2710 /// Subclasses must override this function and can return fewer
2711 /// bytes than requested when memory requests are too large. This
2712 /// class will break up the memory requests and keep advancing the
2713 /// arguments along as needed.
2715 /// @param[in] vm_addr
2716 /// A virtual load address that indicates where to start reading
2720 /// The number of bytes to read.
2723 /// A byte buffer that is at least \a size bytes long that
2724 /// will receive the memory bytes.
2727 /// The number of bytes that were actually read into \a buf.
2728 //------------------------------------------------------------------
2730 DoReadMemory (lldb::addr_t vm_addr,
2735 //------------------------------------------------------------------
2736 /// Read of memory from a process.
2738 /// This function will read memory from the current process's
2739 /// address space and remove any traps that may have been inserted
2740 /// into the memory.
2742 /// This function is not meant to be overridden by Process
2743 /// subclasses, the subclasses should implement
2744 /// Process::DoReadMemory (lldb::addr_t, size_t, void *).
2746 /// @param[in] vm_addr
2747 /// A virtual load address that indicates where to start reading
2751 /// A byte buffer that is at least \a size bytes long that
2752 /// will receive the memory bytes.
2755 /// The number of bytes to read.
2758 /// The number of bytes that were actually read into \a buf. If
2759 /// the returned number is greater than zero, yet less than \a
2760 /// size, then this function will get called again with \a
2761 /// vm_addr, \a buf, and \a size updated appropriately. Zero is
2762 /// returned to indicate an error.
2763 //------------------------------------------------------------------
2765 ReadMemory (lldb::addr_t vm_addr,
2770 //------------------------------------------------------------------
2771 /// Read a NULL terminated string from memory
2773 /// This function will read a cache page at a time until a NULL
2774 /// string terminator is found. It will stop reading if an aligned
2775 /// sequence of NULL termination \a type_width bytes is not found
2776 /// before reading \a cstr_max_len bytes. The results are always
2777 /// guaranteed to be NULL terminated, and that no more than
2778 /// (max_bytes - type_width) bytes will be read.
2780 /// @param[in] vm_addr
2781 /// The virtual load address to start the memory read.
2784 /// A character buffer containing at least max_bytes.
2786 /// @param[in] max_bytes
2787 /// The maximum number of bytes to read.
2789 /// @param[in] error
2790 /// The error status of the read operation.
2792 /// @param[in] type_width
2793 /// The size of the null terminator (1 to 4 bytes per
2794 /// character). Defaults to 1.
2797 /// The error status or the number of bytes prior to the null terminator.
2798 //------------------------------------------------------------------
2800 ReadStringFromMemory (lldb::addr_t vm_addr,
2804 size_t type_width = 1);
2806 //------------------------------------------------------------------
2807 /// Read a NULL terminated C string from memory
2809 /// This function will read a cache page at a time until the NULL
2810 /// C string terminator is found. It will stop reading if the NULL
2811 /// termination byte isn't found before reading \a cstr_max_len
2812 /// bytes, and the results are always guaranteed to be NULL
2813 /// terminated (at most cstr_max_len - 1 bytes will be read).
2814 //------------------------------------------------------------------
2816 ReadCStringFromMemory (lldb::addr_t vm_addr,
2818 size_t cstr_max_len,
2822 ReadCStringFromMemory (lldb::addr_t vm_addr,
2823 std::string &out_str,
2827 ReadMemoryFromInferior (lldb::addr_t vm_addr,
2832 //------------------------------------------------------------------
2833 /// Reads an unsigned integer of the specified byte size from
2836 /// @param[in] load_addr
2837 /// A load address of the integer to read.
2839 /// @param[in] byte_size
2840 /// The size in byte of the integer to read.
2842 /// @param[in] fail_value
2843 /// The value to return if we fail to read an integer.
2845 /// @param[out] error
2846 /// An error that indicates the success or failure of this
2847 /// operation. If error indicates success (error.Success()),
2848 /// then the value returned can be trusted, otherwise zero
2849 /// will be returned.
2852 /// The unsigned integer that was read from the process memory
2853 /// space. If the integer was smaller than a uint64_t, any
2854 /// unused upper bytes will be zero filled. If the process
2855 /// byte order differs from the host byte order, the integer
2856 /// value will be appropriately byte swapped into host byte
2858 //------------------------------------------------------------------
2860 ReadUnsignedIntegerFromMemory (lldb::addr_t load_addr,
2862 uint64_t fail_value,
2866 ReadPointerFromMemory (lldb::addr_t vm_addr,
2870 WritePointerToMemory (lldb::addr_t vm_addr,
2871 lldb::addr_t ptr_value,
2874 //------------------------------------------------------------------
2875 /// Actually do the writing of memory to a process.
2877 /// @param[in] vm_addr
2878 /// A virtual load address that indicates where to start writing
2882 /// A byte buffer that is at least \a size bytes long that
2883 /// contains the data to write.
2886 /// The number of bytes to write.
2888 /// @param[out] error
2889 /// An error value in case the memory write fails.
2892 /// The number of bytes that were actually written.
2893 //------------------------------------------------------------------
2895 DoWriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error)
2897 error.SetErrorStringWithFormat("error: %s does not support writing to processes", GetPluginName().GetCString());
2902 //------------------------------------------------------------------
2903 /// Write all or part of a scalar value to memory.
2905 /// The value contained in \a scalar will be swapped to match the
2906 /// byte order of the process that is being debugged. If \a size is
2907 /// less than the size of scalar, the least significate \a size bytes
2908 /// from scalar will be written. If \a size is larger than the byte
2909 /// size of scalar, then the extra space will be padded with zeros
2910 /// and the scalar value will be placed in the least significant
2911 /// bytes in memory.
2913 /// @param[in] vm_addr
2914 /// A virtual load address that indicates where to start writing
2917 /// @param[in] scalar
2918 /// The scalar to write to the debugged process.
2921 /// This value can be smaller or larger than the scalar value
2922 /// itself. If \a size is smaller than the size of \a scalar,
2923 /// the least significant bytes in \a scalar will be used. If
2924 /// \a size is larger than the byte size of \a scalar, then
2925 /// the extra space will be padded with zeros. If \a size is
2926 /// set to UINT32_MAX, then the size of \a scalar will be used.
2928 /// @param[out] error
2929 /// An error value in case the memory write fails.
2932 /// The number of bytes that were actually written.
2933 //------------------------------------------------------------------
2935 WriteScalarToMemory (lldb::addr_t vm_addr,
2936 const Scalar &scalar,
2941 ReadScalarIntegerFromMemory (lldb::addr_t addr,
2947 //------------------------------------------------------------------
2948 /// Write memory to a process.
2950 /// This function will write memory to the current process's
2951 /// address space and maintain any traps that might be present due
2952 /// to software breakpoints.
2954 /// This function is not meant to be overridden by Process
2955 /// subclasses, the subclasses should implement
2956 /// Process::DoWriteMemory (lldb::addr_t, size_t, void *).
2958 /// @param[in] vm_addr
2959 /// A virtual load address that indicates where to start writing
2963 /// A byte buffer that is at least \a size bytes long that
2964 /// contains the data to write.
2967 /// The number of bytes to write.
2970 /// The number of bytes that were actually written.
2971 //------------------------------------------------------------------
2973 WriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error);
2976 //------------------------------------------------------------------
2977 /// Actually allocate memory in the process.
2979 /// This function will allocate memory in the process's address
2980 /// space. This can't rely on the generic function calling mechanism,
2981 /// since that requires this function.
2984 /// The size of the allocation requested.
2987 /// The address of the allocated buffer in the process, or
2988 /// LLDB_INVALID_ADDRESS if the allocation failed.
2989 //------------------------------------------------------------------
2991 virtual lldb::addr_t
2992 DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2994 error.SetErrorStringWithFormat("error: %s does not support allocating in the debug process", GetPluginName().GetCString());
2995 return LLDB_INVALID_ADDRESS;
2999 //------------------------------------------------------------------
3000 /// The public interface to allocating memory in the process.
3002 /// This function will allocate memory in the process's address
3003 /// space. This can't rely on the generic function calling mechanism,
3004 /// since that requires this function.
3007 /// The size of the allocation requested.
3009 /// @param[in] permissions
3010 /// Or together any of the lldb::Permissions bits. The permissions on
3011 /// a given memory allocation can't be changed after allocation. Note
3012 /// that a block that isn't set writable can still be written on from lldb,
3013 /// just not by the process itself.
3015 /// @param[in/out] error
3016 /// An error object to fill in if things go wrong.
3018 /// The address of the allocated buffer in the process, or
3019 /// LLDB_INVALID_ADDRESS if the allocation failed.
3020 //------------------------------------------------------------------
3023 AllocateMemory (size_t size, uint32_t permissions, Error &error);
3026 //------------------------------------------------------------------
3027 /// Resolve dynamically loaded indirect functions.
3029 /// @param[in] address
3030 /// The load address of the indirect function to resolve.
3032 /// @param[out] error
3033 /// An error value in case the resolve fails.
3036 /// The address of the resolved function.
3037 /// LLDB_INVALID_ADDRESS if the resolution failed.
3038 //------------------------------------------------------------------
3040 virtual lldb::addr_t
3041 ResolveIndirectFunction(const Address *address, Error &error);
3044 GetMemoryRegionInfo (lldb::addr_t load_addr,
3045 MemoryRegionInfo &range_info)
3048 error.SetErrorString ("Process::GetMemoryRegionInfo() not supported");
3053 GetWatchpointSupportInfo (uint32_t &num)
3057 error.SetErrorString ("Process::GetWatchpointSupportInfo() not supported");
3062 GetWatchpointSupportInfo (uint32_t &num, bool& after)
3067 error.SetErrorString ("Process::GetWatchpointSupportInfo() not supported");
3072 ReadModuleFromMemory (const FileSpec& file_spec,
3073 lldb::addr_t header_addr);
3075 //------------------------------------------------------------------
3076 /// Attempt to get the attributes for a region of memory in the process.
3078 /// It may be possible for the remote debug server to inspect attributes
3079 /// for a region of memory in the process, such as whether there is a
3080 /// valid page of memory at a given address or whether that page is
3081 /// readable/writable/executable by the process.
3083 /// @param[in] load_addr
3084 /// The address of interest in the process.
3086 /// @param[out] permissions
3087 /// If this call returns successfully, this bitmask will have
3088 /// its Permissions bits set to indicate whether the region is
3089 /// readable/writable/executable. If this call fails, the
3090 /// bitmask values are undefined.
3093 /// Returns true if it was able to determine the attributes of the
3094 /// memory region. False if not.
3095 //------------------------------------------------------------------
3098 GetLoadAddressPermissions (lldb::addr_t load_addr, uint32_t &permissions)
3100 MemoryRegionInfo range_info;
3102 Error error (GetMemoryRegionInfo (load_addr, range_info));
3103 if (!error.Success())
3105 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow
3106 || range_info.GetWritable() == MemoryRegionInfo::eDontKnow
3107 || range_info.GetExecutable() == MemoryRegionInfo::eDontKnow)
3112 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
3113 permissions |= lldb::ePermissionsReadable;
3115 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
3116 permissions |= lldb::ePermissionsWritable;
3118 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
3119 permissions |= lldb::ePermissionsExecutable;
3124 //------------------------------------------------------------------
3125 /// Determines whether executing JIT-compiled code in this process
3129 /// True if execution of JIT code is possible; false otherwise.
3130 //------------------------------------------------------------------
3133 //------------------------------------------------------------------
3134 /// Sets whether executing JIT-compiled code in this process
3137 /// @param[in] can_jit
3138 /// True if execution of JIT code is possible; false otherwise.
3139 //------------------------------------------------------------------
3140 void SetCanJIT (bool can_jit);
3142 //------------------------------------------------------------------
3143 /// Actually deallocate memory in the process.
3145 /// This function will deallocate memory in the process's address
3146 /// space that was allocated with AllocateMemory.
3149 /// A return value from AllocateMemory, pointing to the memory you
3150 /// want to deallocate.
3153 /// \btrue if the memory was deallocated, \bfalse otherwise.
3154 //------------------------------------------------------------------
3157 DoDeallocateMemory (lldb::addr_t ptr)
3160 error.SetErrorStringWithFormat("error: %s does not support deallocating in the debug process", GetPluginName().GetCString());
3165 //------------------------------------------------------------------
3166 /// The public interface to deallocating memory in the process.
3168 /// This function will deallocate memory in the process's address
3169 /// space that was allocated with AllocateMemory.
3172 /// A return value from AllocateMemory, pointing to the memory you
3173 /// want to deallocate.
3176 /// \btrue if the memory was deallocated, \bfalse otherwise.
3177 //------------------------------------------------------------------
3180 DeallocateMemory (lldb::addr_t ptr);
3182 //------------------------------------------------------------------
3183 /// Get any available STDOUT.
3185 /// If the process was launched without supplying valid file paths
3186 /// for stdin, stdout, and stderr, then the Process class might
3187 /// try to cache the STDOUT for the process if it is able. Events
3188 /// will be queued indicating that there is STDOUT available that
3189 /// can be retrieved using this function.
3192 /// A buffer that will receive any STDOUT bytes that are
3193 /// currently available.
3195 /// @param[out] buf_size
3196 /// The size in bytes for the buffer \a buf.
3199 /// The number of bytes written into \a buf. If this value is
3200 /// equal to \a buf_size, another call to this function should
3201 /// be made to retrieve more STDOUT data.
3202 //------------------------------------------------------------------
3204 GetSTDOUT (char *buf, size_t buf_size, Error &error);
3206 //------------------------------------------------------------------
3207 /// Get any available STDERR.
3209 /// If the process was launched without supplying valid file paths
3210 /// for stdin, stdout, and stderr, then the Process class might
3211 /// try to cache the STDERR for the process if it is able. Events
3212 /// will be queued indicating that there is STDERR available that
3213 /// can be retrieved using this function.
3216 /// A buffer that will receive any STDERR bytes that are
3217 /// currently available.
3219 /// @param[out] buf_size
3220 /// The size in bytes for the buffer \a buf.
3223 /// The number of bytes written into \a buf. If this value is
3224 /// equal to \a buf_size, another call to this function should
3225 /// be made to retrieve more STDERR data.
3226 //------------------------------------------------------------------
3228 GetSTDERR (char *buf, size_t buf_size, Error &error);
3231 PutSTDIN (const char *buf, size_t buf_size, Error &error)
3233 error.SetErrorString("stdin unsupported");
3237 //------------------------------------------------------------------
3238 /// Get any available profile data.
3241 /// A buffer that will receive any profile data bytes that are
3242 /// currently available.
3244 /// @param[out] buf_size
3245 /// The size in bytes for the buffer \a buf.
3248 /// The number of bytes written into \a buf. If this value is
3249 /// equal to \a buf_size, another call to this function should
3250 /// be made to retrieve more profile data.
3251 //------------------------------------------------------------------
3253 GetAsyncProfileData (char *buf, size_t buf_size, Error &error);
3255 //----------------------------------------------------------------------
3256 // Process Breakpoints
3257 //----------------------------------------------------------------------
3259 GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site);
3262 EnableBreakpointSite (BreakpointSite *bp_site)
3265 error.SetErrorStringWithFormat("error: %s does not support enabling breakpoints", GetPluginName().GetCString());
3271 DisableBreakpointSite (BreakpointSite *bp_site)
3274 error.SetErrorStringWithFormat("error: %s does not support disabling breakpoints", GetPluginName().GetCString());
3279 // This is implemented completely using the lldb::Process API. Subclasses
3280 // don't need to implement this function unless the standard flow of
3281 // read existing opcode, write breakpoint opcode, verify breakpoint opcode
3282 // doesn't work for a specific process plug-in.
3284 EnableSoftwareBreakpoint (BreakpointSite *bp_site);
3286 // This is implemented completely using the lldb::Process API. Subclasses
3287 // don't need to implement this function unless the standard flow of
3288 // restoring original opcode in memory and verifying the restored opcode
3289 // doesn't work for a specific process plug-in.
3291 DisableSoftwareBreakpoint (BreakpointSite *bp_site);
3293 BreakpointSiteList &
3294 GetBreakpointSiteList();
3296 const BreakpointSiteList &
3297 GetBreakpointSiteList() const;
3300 DisableAllBreakpointSites ();
3303 ClearBreakpointSiteByID (lldb::user_id_t break_id);
3306 CreateBreakpointSite (const lldb::BreakpointLocationSP &owner,
3310 DisableBreakpointSiteByID (lldb::user_id_t break_id);
3313 EnableBreakpointSiteByID (lldb::user_id_t break_id);
3316 // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove
3317 // themselves from the owner's list of this breakpoint sites.
3319 RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id,
3320 lldb::user_id_t owner_loc_id,
3321 lldb::BreakpointSiteSP &bp_site_sp);
3323 //----------------------------------------------------------------------
3324 // Process Watchpoints (optional)
3325 //----------------------------------------------------------------------
3327 EnableWatchpoint (Watchpoint *wp, bool notify = true);
3330 DisableWatchpoint (Watchpoint *wp, bool notify = true);
3332 //------------------------------------------------------------------
3334 //------------------------------------------------------------------
3336 UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list) = 0;
3339 UpdateThreadListIfNeeded ();
3344 return m_thread_list;
3347 // When ExtendedBacktraces are requested, the HistoryThreads that are
3348 // created need an owner -- they're saved here in the Process. The
3349 // threads in this list are not iterated over - driver programs need to
3350 // request the extended backtrace calls starting from a root concrete
3351 // thread one by one.
3353 GetExtendedThreadList ()
3355 return m_extended_thread_list;
3358 ThreadList::ThreadIterable
3361 return m_thread_list.Threads();
3365 GetNextThreadIndexID (uint64_t thread_id);
3368 CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context);
3370 // Returns true if an index id has been assigned to a thread.
3372 HasAssignedIndexIDToThread(uint64_t sb_thread_id);
3374 // Given a thread_id, it will assign a more reasonable index id for display to the user.
3375 // If the thread_id has previously been assigned, the same index id will be used.
3377 AssignIndexIDToThread(uint64_t thread_id);
3379 //------------------------------------------------------------------
3381 //------------------------------------------------------------------
3384 UpdateQueueListIfNeeded ();
3389 UpdateQueueListIfNeeded();
3390 return m_queue_list;
3393 QueueList::QueueIterable
3396 UpdateQueueListIfNeeded();
3397 return m_queue_list.Queues();
3400 //------------------------------------------------------------------
3402 //------------------------------------------------------------------
3404 GetNextEvent (lldb::EventSP &event_sp);
3406 // Returns the process state when it is stopped. If specified, event_sp_ptr
3407 // is set to the event which triggered the stop. If wait_always = false,
3408 // and the process is already stopped, this function returns immediately.
3410 WaitForProcessToStop (const TimeValue *timeout,
3411 lldb::EventSP *event_sp_ptr = NULL,
3412 bool wait_always = true,
3413 Listener *hijack_listener = NULL);
3416 WaitForStateChangedEvents (const TimeValue *timeout,
3417 lldb::EventSP &event_sp,
3418 Listener *hijack_listener); // Pass NULL to use builtin listener
3421 PeekAtStateChangedEvents ();
3425 ProcessEventHijacker
3428 ProcessEventHijacker (Process &process, Listener *listener) :
3431 m_process.HijackProcessEvents (listener);
3433 ~ProcessEventHijacker ()
3435 m_process.RestoreProcessEvents();
3441 friend class ProcessEventHijacker;
3442 //------------------------------------------------------------------
3443 /// If you need to ensure that you and only you will hear about some public
3444 /// event, then make a new listener, set to listen to process events, and
3445 /// then call this with that listener. Then you will have to wait on that
3446 /// listener explicitly for events (rather than using the GetNextEvent & WaitFor*
3447 /// calls above. Be sure to call RestoreProcessEvents when you are done.
3449 /// @param[in] listener
3450 /// This is the new listener to whom all process events will be delivered.
3453 /// Returns \b true if the new listener could be installed,
3454 /// \b false otherwise.
3455 //------------------------------------------------------------------
3457 HijackProcessEvents (Listener *listener);
3459 //------------------------------------------------------------------
3460 /// Restores the process event broadcasting to its normal state.
3462 //------------------------------------------------------------------
3464 RestoreProcessEvents ();
3467 //------------------------------------------------------------------
3468 /// This is the part of the event handling that for a process event.
3469 /// It decides what to do with the event and returns true if the
3470 /// event needs to be propagated to the user, and false otherwise.
3471 /// If the event is not propagated, this call will most likely set
3472 /// the target to executing again.
3473 /// There is only one place where this call should be called, HandlePrivateEvent.
3474 /// Don't call it from anywhere else...
3476 /// @param[in] event_ptr
3477 /// This is the event we are handling.
3480 /// Returns \b true if the event should be reported to the
3481 /// user, \b false otherwise.
3482 //------------------------------------------------------------------
3484 ShouldBroadcastEvent (Event *event_ptr);
3491 GetOperatingSystem ()
3493 return m_os_ap.get();
3497 virtual LanguageRuntime *
3498 GetLanguageRuntime (lldb::LanguageType language, bool retry_if_null = true);
3500 virtual CPPLanguageRuntime *
3501 GetCPPLanguageRuntime (bool retry_if_null = true);
3503 virtual ObjCLanguageRuntime *
3504 GetObjCLanguageRuntime (bool retry_if_null = true);
3507 IsPossibleDynamicValue (ValueObject& in_value);
3512 DynamicCheckerFunctions *GetDynamicCheckers()
3514 return m_dynamic_checkers_ap.get();
3517 void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
3519 m_dynamic_checkers_ap.reset(dynamic_checkers);
3522 //------------------------------------------------------------------
3523 /// Call this to set the lldb in the mode where it breaks on new thread
3524 /// creations, and then auto-restarts. This is useful when you are trying
3525 /// to run only one thread, but either that thread or the kernel is creating
3526 /// new threads in the process. If you stop when the thread is created, you
3527 /// can immediately suspend it, and keep executing only the one thread you intend.
3530 /// Returns \b true if we were able to start up the notification
3531 /// \b false otherwise.
3532 //------------------------------------------------------------------
3534 StartNoticingNewThreads()
3539 //------------------------------------------------------------------
3540 /// Call this to turn off the stop & notice new threads mode.
3543 /// Returns \b true if we were able to start up the notification
3544 /// \b false otherwise.
3545 //------------------------------------------------------------------
3547 StopNoticingNewThreads()
3553 SetRunningUserExpression (bool on);
3555 //------------------------------------------------------------------
3556 // lldb::ExecutionContextScope pure virtual functions
3557 //------------------------------------------------------------------
3558 virtual lldb::TargetSP
3561 virtual lldb::ProcessSP
3564 return shared_from_this();
3567 virtual lldb::ThreadSP
3570 return lldb::ThreadSP();
3573 virtual lldb::StackFrameSP
3574 CalculateStackFrame ()
3576 return lldb::StackFrameSP();
3580 CalculateExecutionContext (ExecutionContext &exe_ctx);
3583 SetSTDIOFileDescriptor (int file_descriptor);
3586 WatchForSTDIN (IOHandler &io_handler);
3589 CancelWatchForSTDIN (bool exited);
3591 //------------------------------------------------------------------
3592 // Add a permanent region of memory that should never be read or
3593 // written to. This can be used to ensure that memory reads or writes
3594 // to certain areas of memory never end up being sent to the
3595 // DoReadMemory or DoWriteMemory functions which can improve
3597 //------------------------------------------------------------------
3599 AddInvalidMemoryRegion (const LoadRange ®ion);
3601 //------------------------------------------------------------------
3602 // Remove a permanent region of memory that should never be read or
3603 // written to that was previously added with AddInvalidMemoryRegion.
3604 //------------------------------------------------------------------
3606 RemoveInvalidMemoryRange (const LoadRange ®ion);
3608 //------------------------------------------------------------------
3609 // If the setup code of a thread plan needs to do work that might involve
3610 // calling a function in the target, it should not do that work directly
3611 // in one of the thread plan functions (DidPush/WillResume) because
3612 // such work needs to be handled carefully. Instead, put that work in
3613 // a PreResumeAction callback, and register it with the process. It will
3614 // get done before the actual "DoResume" gets called.
3615 //------------------------------------------------------------------
3617 typedef bool (PreResumeActionCallback)(void *);
3620 AddPreResumeAction (PreResumeActionCallback callback, void *baton);
3623 RunPreResumeActions ();
3626 ClearPreResumeActions ();
3631 if (Host::GetCurrentThread() == m_private_state_thread)
3632 return m_private_run_lock;
3634 return m_public_run_lock;
3638 //------------------------------------------------------------------
3639 // NextEventAction provides a way to register an action on the next
3640 // event that is delivered to this process. There is currently only
3641 // one next event action allowed in the process at one time. If a
3642 // new "NextEventAction" is added while one is already present, the
3643 // old action will be discarded (with HandleBeingUnshipped called
3644 // after it is discarded.)
3646 // If you want to resume the process as a result of a resume action,
3647 // call RequestResume, don't call Resume directly.
3648 //------------------------------------------------------------------
3649 class NextEventAction
3652 typedef enum EventActionResult
3654 eEventActionSuccess,
3657 } EventActionResult;
3659 NextEventAction (Process *process) :
3669 virtual EventActionResult PerformAction (lldb::EventSP &event_sp) = 0;
3670 virtual void HandleBeingUnshipped () {}
3671 virtual EventActionResult HandleBeingInterrupted () = 0;
3672 virtual const char *GetExitString() = 0;
3673 void RequestResume()
3675 m_process->m_resume_requested = true;
3681 void SetNextEventAction (Process::NextEventAction *next_event_action)
3683 if (m_next_event_action_ap.get())
3684 m_next_event_action_ap->HandleBeingUnshipped();
3686 m_next_event_action_ap.reset(next_event_action);
3689 // This is the completer for Attaching:
3690 class AttachCompletionHandler : public NextEventAction
3693 AttachCompletionHandler (Process *process, uint32_t exec_count) :
3694 NextEventAction (process),
3695 m_exec_count (exec_count)
3700 ~AttachCompletionHandler()
3704 virtual EventActionResult PerformAction (lldb::EventSP &event_sp);
3705 virtual EventActionResult HandleBeingInterrupted ();
3706 virtual const char *GetExitString();
3708 uint32_t m_exec_count;
3709 std::string m_exit_string;
3713 HijackPrivateProcessEvents (Listener *listener);
3716 RestorePrivateProcessEvents ();
3719 PrivateStateThreadIsValid () const
3721 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3725 ForceNextEventDelivery()
3727 m_force_next_event_delivery = true;
3730 //------------------------------------------------------------------
3732 //------------------------------------------------------------------
3733 typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP> LanguageRuntimeCollection;
3735 struct PreResumeCallbackAndBaton
3737 bool (*callback) (void *);
3739 PreResumeCallbackAndBaton (PreResumeActionCallback in_callback, void *in_baton) :
3740 callback (in_callback),
3746 //------------------------------------------------------------------
3748 //------------------------------------------------------------------
3749 Target & m_target; ///< The target that owns this process.
3750 ThreadSafeValue<lldb::StateType> m_public_state;
3751 ThreadSafeValue<lldb::StateType> m_private_state; // The actual state of our process
3752 Broadcaster m_private_state_broadcaster; // This broadcaster feeds state changed events into the private state thread's listener.
3753 Broadcaster m_private_state_control_broadcaster; // This is the control broadcaster, used to pause, resume & stop the private state thread.
3754 Listener m_private_state_listener; // This is the listener for the private state thread.
3755 Predicate<bool> m_private_state_control_wait; /// This Predicate is used to signal that a control operation is complete.
3756 lldb::thread_t m_private_state_thread; // Thread ID for the thread that watches interal state events
3757 ProcessModID m_mod_id; ///< Tracks the state of the process over stops and other alterations.
3758 uint32_t m_process_unique_id; ///< Each lldb_private::Process class that is created gets a unique integer ID that increments with each new instance
3759 uint32_t m_thread_index_id; ///< Each thread is created with a 1 based index that won't get re-used.
3760 std::map<uint64_t, uint32_t> m_thread_id_to_index_id_map;
3761 int m_exit_status; ///< The exit status of the process, or -1 if not set.
3762 std::string m_exit_string; ///< A textual description of why a process exited.
3763 Mutex m_thread_mutex;
3764 ThreadList m_thread_list_real; ///< The threads for this process as are known to the protocol we are debugging with
3765 ThreadList m_thread_list; ///< The threads for this process as the user will see them. This is usually the same as
3766 ///< m_thread_list_real, but might be different if there is an OS plug-in creating memory threads
3767 ThreadList m_extended_thread_list; ///< Owner for extended threads that may be generated, cleared on natural stops
3768 uint32_t m_extended_thread_stop_id; ///< The natural stop id when extended_thread_list was last updated
3769 QueueList m_queue_list; ///< The list of libdispatch queues at a given stop point
3770 uint32_t m_queue_list_stop_id; ///< The natural stop id when queue list was last fetched
3771 std::vector<Notifications> m_notifications; ///< The list of notifications that this process can deliver.
3772 std::vector<lldb::addr_t> m_image_tokens;
3773 Listener &m_listener;
3774 BreakpointSiteList m_breakpoint_site_list; ///< This is the list of breakpoint locations we intend to insert in the target.
3775 std::unique_ptr<DynamicLoader> m_dyld_ap;
3776 std::unique_ptr<DynamicCheckerFunctions> m_dynamic_checkers_ap; ///< The functions used by the expression parser to validate data that expressions use.
3777 std::unique_ptr<OperatingSystem> m_os_ap;
3778 std::unique_ptr<SystemRuntime> m_system_runtime_ap;
3779 UnixSignals m_unix_signals; /// This is the current signal set for this process.
3780 lldb::ABISP m_abi_sp;
3781 lldb::IOHandlerSP m_process_input_reader;
3782 Communication m_stdio_communication;
3783 Mutex m_stdio_communication_mutex;
3784 std::string m_stdout_data;
3785 std::string m_stderr_data;
3786 Mutex m_profile_data_comm_mutex;
3787 std::vector<std::string> m_profile_data;
3788 MemoryCache m_memory_cache;
3789 AllocatedMemoryCache m_allocated_memory_cache;
3790 bool m_should_detach; /// Should we detach if the process object goes away with an explicit call to Kill or Detach?
3791 LanguageRuntimeCollection m_language_runtimes;
3792 std::unique_ptr<NextEventAction> m_next_event_action_ap;
3793 std::vector<PreResumeCallbackAndBaton> m_pre_resume_actions;
3794 ProcessRunLock m_public_run_lock;
3795 ProcessRunLock m_private_run_lock;
3796 Predicate<bool> m_currently_handling_event; // This predicate is set in HandlePrivateEvent while all its business is being done.
3797 bool m_currently_handling_do_on_removals;
3798 bool m_resume_requested; // If m_currently_handling_event or m_currently_handling_do_on_removals are true, Resume will only request a resume, using this flag to check.
3799 bool m_finalize_called;
3800 bool m_clear_thread_plans_on_stop;
3801 bool m_force_next_event_delivery;
3802 lldb::StateType m_last_broadcast_state; /// This helps with the Public event coalescing in ShouldBroadcastEvent.
3803 std::map<lldb::addr_t,lldb::addr_t> m_resolved_indirect_addresses;
3804 bool m_destroy_in_process;
3813 RemoveBreakpointOpcodesFromBuffer (lldb::addr_t addr, size_t size, uint8_t *buf) const;
3816 SynchronouslyNotifyStateChanged (lldb::StateType state);
3819 SetPublicState (lldb::StateType new_state, bool restarted);
3822 SetPrivateState (lldb::StateType state);
3825 StartPrivateStateThread (bool force = false);
3828 StopPrivateStateThread ();
3831 PausePrivateStateThread ();
3834 ResumePrivateStateThread ();
3836 static lldb::thread_result_t
3837 PrivateStateThread (void *arg);
3839 lldb::thread_result_t
3840 RunPrivateStateThread ();
3843 HandlePrivateEvent (lldb::EventSP &event_sp);
3846 WaitForProcessStopPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
3848 // This waits for both the state change broadcaster, and the control broadcaster.
3849 // If control_only, it only waits for the control broadcaster.
3852 WaitForEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp, bool control_only);
3855 WaitForStateChangedEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp);
3858 WaitForState (const TimeValue *timeout,
3859 const lldb::StateType *match_states,
3860 const uint32_t num_match_states);
3863 WriteMemoryPrivate (lldb::addr_t addr, const void *buf, size_t size, Error &error);
3866 AppendSTDOUT (const char *s, size_t len);
3869 AppendSTDERR (const char *s, size_t len);
3872 BroadcastAsyncProfileData(const std::string &one_profile_data);
3875 STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len);
3878 PushProcessIOHandler ();
3881 PopProcessIOHandler ();
3884 ResetProcessIOHandler ();
3887 HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp);
3890 //------------------------------------------------------------------
3892 //------------------------------------------------------------------
3893 void ControlPrivateStateThread (uint32_t signal);
3895 DISALLOW_COPY_AND_ASSIGN (Process);
3899 } // namespace lldb_private
3901 #endif // liblldb_Process_h_