1 //===-- Process.cpp ---------------------------------------------*- 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 #include "lldb/lldb-python.h"
12 #include "lldb/Target/Process.h"
14 #include "lldb/lldb-private-log.h"
16 #include "lldb/Breakpoint/StoppointCallbackContext.h"
17 #include "lldb/Breakpoint/BreakpointLocation.h"
18 #include "lldb/Core/Event.h"
19 #include "lldb/Core/ConnectionFileDescriptor.h"
20 #include "lldb/Core/Debugger.h"
21 #include "lldb/Core/InputReader.h"
22 #include "lldb/Core/Log.h"
23 #include "lldb/Core/Module.h"
24 #include "lldb/Core/PluginManager.h"
25 #include "lldb/Core/State.h"
26 #include "lldb/Expression/ClangUserExpression.h"
27 #include "lldb/Interpreter/CommandInterpreter.h"
28 #include "lldb/Host/Host.h"
29 #include "lldb/Target/ABI.h"
30 #include "lldb/Target/DynamicLoader.h"
31 #include "lldb/Target/OperatingSystem.h"
32 #include "lldb/Target/LanguageRuntime.h"
33 #include "lldb/Target/CPPLanguageRuntime.h"
34 #include "lldb/Target/ObjCLanguageRuntime.h"
35 #include "lldb/Target/Platform.h"
36 #include "lldb/Target/RegisterContext.h"
37 #include "lldb/Target/StopInfo.h"
38 #include "lldb/Target/Target.h"
39 #include "lldb/Target/TargetList.h"
40 #include "lldb/Target/Thread.h"
41 #include "lldb/Target/ThreadPlan.h"
42 #include "lldb/Target/ThreadPlanBase.h"
45 using namespace lldb_private;
48 // Comment out line below to disable memory caching, overriding the process setting
49 // target.process.disable-memory-cache
50 #define ENABLE_MEMORY_CACHING
52 #ifdef ENABLE_MEMORY_CACHING
53 #define DISABLE_MEM_CACHE_DEFAULT false
55 #define DISABLE_MEM_CACHE_DEFAULT true
58 class ProcessOptionValueProperties : public OptionValueProperties
61 ProcessOptionValueProperties (const ConstString &name) :
62 OptionValueProperties (name)
66 // This constructor is used when creating ProcessOptionValueProperties when it
67 // is part of a new lldb_private::Process instance. It will copy all current
68 // global property values as needed
69 ProcessOptionValueProperties (ProcessProperties *global_properties) :
70 OptionValueProperties(*global_properties->GetValueProperties())
74 virtual const Property *
75 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
77 // When gettings the value for a key from the process options, we will always
78 // try and grab the setting from the current process if there is one. Else we just
79 // use the one from this instance.
82 Process *process = exe_ctx->GetProcessPtr();
85 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
86 if (this != instance_properties)
87 return instance_properties->ProtectedGetPropertyAtIndex (idx);
90 return ProtectedGetPropertyAtIndex (idx);
94 static PropertyDefinition
97 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." },
98 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
99 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
100 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
101 { "unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, errors in expression evaluation will unwind the stack back to the state before the call." },
102 { "python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, NULL, NULL, "A path to a python OS plug-in module file that contains a OperatingSystemPlugIn class." },
103 { "stop-on-sharedlibrary-events" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, stop when a shared library is loaded or unloaded." },
104 { "detach-keeps-stopped" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, detach will attempt to keep the process stopped." },
105 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
109 ePropertyDisableMemCache,
110 ePropertyExtraStartCommand,
111 ePropertyIgnoreBreakpointsInExpressions,
112 ePropertyUnwindOnErrorInExpressions,
113 ePropertyPythonOSPluginPath,
114 ePropertyStopOnSharedLibraryEvents,
115 ePropertyDetachKeepsStopped
118 ProcessProperties::ProcessProperties (bool is_global) :
123 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
124 m_collection_sp->Initialize(g_properties);
125 m_collection_sp->AppendProperty(ConstString("thread"),
126 ConstString("Settings specific to threads."),
128 Thread::GetGlobalProperties()->GetValueProperties());
131 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
134 ProcessProperties::~ProcessProperties()
139 ProcessProperties::GetDisableMemoryCache() const
141 const uint32_t idx = ePropertyDisableMemCache;
142 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
146 ProcessProperties::GetExtraStartupCommands () const
149 const uint32_t idx = ePropertyExtraStartCommand;
150 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
155 ProcessProperties::SetExtraStartupCommands (const Args &args)
157 const uint32_t idx = ePropertyExtraStartCommand;
158 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
162 ProcessProperties::GetPythonOSPluginPath () const
164 const uint32_t idx = ePropertyPythonOSPluginPath;
165 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
169 ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
171 const uint32_t idx = ePropertyPythonOSPluginPath;
172 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
177 ProcessProperties::GetIgnoreBreakpointsInExpressions () const
179 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
180 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
184 ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
186 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
187 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
191 ProcessProperties::GetUnwindOnErrorInExpressions () const
193 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
194 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
198 ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
200 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
201 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
205 ProcessProperties::GetStopOnSharedLibraryEvents () const
207 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
208 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
212 ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
214 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
215 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
219 ProcessProperties::GetDetachKeepsStopped () const
221 const uint32_t idx = ePropertyDetachKeepsStopped;
222 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
226 ProcessProperties::SetDetachKeepsStopped (bool stop)
228 const uint32_t idx = ePropertyDetachKeepsStopped;
229 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
233 ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
236 if (m_pid != LLDB_INVALID_PROCESS_ID)
237 s.Printf (" pid = %" PRIu64 "\n", m_pid);
239 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
240 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
244 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
245 s.PutCString (" file = ");
246 m_executable.Dump(&s);
249 const uint32_t argc = m_arguments.GetArgumentCount();
252 for (uint32_t i=0; i<argc; i++)
254 const char *arg = m_arguments.GetArgumentAtIndex(i);
256 s.Printf (" arg[%u] = %s\n", i, arg);
258 s.Printf ("arg[%u] = %s\n", i, arg);
262 const uint32_t envc = m_environment.GetArgumentCount();
265 for (uint32_t i=0; i<envc; i++)
267 const char *env = m_environment.GetArgumentAtIndex(i);
269 s.Printf (" env[%u] = %s\n", i, env);
271 s.Printf ("env[%u] = %s\n", i, env);
275 if (m_arch.IsValid())
276 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
278 if (m_uid != UINT32_MAX)
280 cstr = platform->GetUserName (m_uid);
281 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
283 if (m_gid != UINT32_MAX)
285 cstr = platform->GetGroupName (m_gid);
286 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
288 if (m_euid != UINT32_MAX)
290 cstr = platform->GetUserName (m_euid);
291 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
293 if (m_egid != UINT32_MAX)
295 cstr = platform->GetGroupName (m_egid);
296 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
301 ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
304 if (show_args || verbose)
311 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
312 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
316 s.Printf ("PID PARENT USER ARCH %s\n", label);
317 s.PutCString ("====== ====== ========== ======= ============================\n");
322 ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
324 if (m_pid != LLDB_INVALID_PROCESS_ID)
327 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
332 cstr = platform->GetUserName (m_uid);
333 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
334 s.Printf ("%-10s ", cstr);
336 s.Printf ("%-10u ", m_uid);
338 cstr = platform->GetGroupName (m_gid);
339 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
340 s.Printf ("%-10s ", cstr);
342 s.Printf ("%-10u ", m_gid);
344 cstr = platform->GetUserName (m_euid);
345 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
346 s.Printf ("%-10s ", cstr);
348 s.Printf ("%-10u ", m_euid);
350 cstr = platform->GetGroupName (m_egid);
351 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
352 s.Printf ("%-10s ", cstr);
354 s.Printf ("%-10u ", m_egid);
355 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
359 s.Printf ("%-10s %-7d %s ",
360 platform->GetUserName (m_euid),
361 (int)m_arch.GetTriple().getArchName().size(),
362 m_arch.GetTriple().getArchName().data());
365 if (verbose || show_args)
367 const uint32_t argc = m_arguments.GetArgumentCount();
370 for (uint32_t i=0; i<argc; i++)
374 s.PutCString (m_arguments.GetArgumentAtIndex(i));
380 s.PutCString (GetName());
389 ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
391 m_arguments.SetArguments (argv);
393 // Is the first argument the executable?
394 if (first_arg_is_executable)
396 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
399 // Yes the first argument is an executable, set it as the executable
400 // in the launch options. Don't resolve the file path as the path
401 // could be a remote platform path
402 const bool resolve = false;
403 m_executable.SetFile(first_arg, resolve);
408 ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
410 // Copy all arguments
413 // Is the first argument the executable?
414 if (first_arg_is_executable)
416 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
419 // Yes the first argument is an executable, set it as the executable
420 // in the launch options. Don't resolve the file path as the path
421 // could be a remote platform path
422 const bool resolve = false;
423 m_executable.SetFile(first_arg, resolve);
429 ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
431 // If notthing was specified, then check the process for any default
432 // settings that were set with "settings set"
433 if (m_file_actions.empty())
435 if (m_flags.Test(eLaunchFlagDisableSTDIO))
437 AppendSuppressFileAction (STDIN_FILENO , true, false);
438 AppendSuppressFileAction (STDOUT_FILENO, false, true);
439 AppendSuppressFileAction (STDERR_FILENO, false, true);
443 // Check for any values that might have gotten set with any of:
444 // (lldb) settings set target.input-path
445 // (lldb) settings set target.output-path
446 // (lldb) settings set target.error-path
452 in_path = target->GetStandardInputPath();
453 out_path = target->GetStandardOutputPath();
454 err_path = target->GetStandardErrorPath();
457 if (in_path || out_path || err_path)
460 if (in_path && in_path.GetPath(path, sizeof(path)))
461 AppendOpenFileAction(STDIN_FILENO, path, true, false);
463 if (out_path && out_path.GetPath(path, sizeof(path)))
464 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
466 if (err_path && err_path.GetPath(path, sizeof(path)))
467 AppendOpenFileAction(STDERR_FILENO, path, false, true);
469 else if (default_to_use_pty)
471 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
473 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
474 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
475 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
476 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
485 ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
488 bool first_arg_is_full_shell_command)
492 if (GetFlags().Test (eLaunchFlagLaunchInShell))
494 const char *shell_executable = GetShell();
495 if (shell_executable)
497 char shell_resolved_path[PATH_MAX];
501 FileSpec shell_filespec (shell_executable, true);
503 if (!shell_filespec.Exists())
505 // Resolve the path in case we just got "bash", "sh" or "tcsh"
506 if (!shell_filespec.ResolveExecutableLocation ())
508 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
512 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
513 shell_executable = shell_resolved_path;
516 const char **argv = GetArguments().GetConstArgumentVector ();
517 if (argv == NULL || argv[0] == NULL)
519 Args shell_arguments;
520 std::string safe_arg;
521 shell_arguments.AppendArgument (shell_executable);
522 shell_arguments.AppendArgument ("-c");
523 StreamString shell_command;
526 // Add a modified PATH environment variable in case argv[0]
527 // is a relative path
528 const char *argv0 = argv[0];
529 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
531 // We have a relative path to our executable which may not work if
532 // we just try to run "a.out" (without it being converted to "./a.out")
533 const char *working_dir = GetWorkingDirectory();
534 // Be sure to put quotes around PATH's value in case any paths have spaces...
535 std::string new_path("PATH=\"");
536 const size_t empty_path_len = new_path.size();
538 if (working_dir && working_dir[0])
540 new_path += working_dir;
544 char current_working_dir[PATH_MAX];
545 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
549 const char *curr_path = getenv("PATH");
552 if (new_path.size() > empty_path_len)
554 new_path += curr_path;
557 shell_command.PutCString(new_path.c_str());
560 shell_command.PutCString ("exec");
562 // Only Apple supports /usr/bin/arch being able to specify the architecture
563 if (GetArchitecture().IsValid())
565 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
566 // Set the resume count to 2:
568 // 2 - stop in /usr/bin/arch
569 // 3 - then we will stop in our program
574 // Set the resume count to 1:
576 // 2 - then we will stop in our program
581 if (first_arg_is_full_shell_command)
583 // There should only be one argument that is the shell command itself to be used as is
584 if (argv[0] && !argv[1])
585 shell_command.Printf("%s", argv[0]);
591 for (size_t i=0; argv[i] != NULL; ++i)
593 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
594 shell_command.Printf(" %s", arg);
597 shell_arguments.AppendArgument (shell_command.GetString().c_str());
598 m_executable.SetFile(shell_executable, false);
599 m_arguments = shell_arguments;
604 error.SetErrorString ("invalid shell path");
609 error.SetErrorString ("not launching in shell");
616 ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
618 if ((read || write) && fd >= 0 && path && path[0])
620 m_action = eFileActionOpen;
623 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
625 m_arg = O_NOCTTY | O_RDONLY;
627 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
628 m_path.assign (path);
639 ProcessLaunchInfo::FileAction::Close (int fd)
644 m_action = eFileActionClose;
652 ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
655 if (fd >= 0 && dup_fd >= 0)
657 m_action = eFileActionDuplicate;
667 ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
668 const FileAction *info,
675 switch (info->m_action)
677 case eFileActionNone:
681 case eFileActionClose:
682 if (info->m_fd == -1)
683 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
686 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
688 if (log && (error.Fail() || log))
689 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
690 file_actions, info->m_fd);
694 case eFileActionDuplicate:
695 if (info->m_fd == -1)
696 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
697 else if (info->m_arg == -1)
698 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
701 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
703 if (log && (error.Fail() || log))
704 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
705 file_actions, info->m_fd, info->m_arg);
709 case eFileActionOpen:
710 if (info->m_fd == -1)
711 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
714 int oflag = info->m_arg;
721 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
723 info->m_path.c_str(),
727 if (error.Fail() || log)
729 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
730 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
734 return error.Success();
738 ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
741 const int short_option = m_getopt_table[option_idx].val;
743 switch (short_option)
745 case 's': // Stop at program entry point
746 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
749 case 'i': // STDIN for read only
751 ProcessLaunchInfo::FileAction action;
752 if (action.Open (STDIN_FILENO, option_arg, true, false))
753 launch_info.AppendFileAction (action);
757 case 'o': // Open STDOUT for write only
759 ProcessLaunchInfo::FileAction action;
760 if (action.Open (STDOUT_FILENO, option_arg, false, true))
761 launch_info.AppendFileAction (action);
765 case 'e': // STDERR for write only
767 ProcessLaunchInfo::FileAction action;
768 if (action.Open (STDERR_FILENO, option_arg, false, true))
769 launch_info.AppendFileAction (action);
774 case 'p': // Process plug-in name
775 launch_info.SetProcessPluginName (option_arg);
778 case 'n': // Disable STDIO
780 ProcessLaunchInfo::FileAction action;
781 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
782 launch_info.AppendFileAction (action);
783 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
784 launch_info.AppendFileAction (action);
785 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
786 launch_info.AppendFileAction (action);
791 launch_info.SetWorkingDirectory (option_arg);
794 case 't': // Open process in new terminal window
795 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
799 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
800 launch_info.GetArchitecture().SetTriple (option_arg);
804 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
808 if (option_arg && option_arg[0])
809 launch_info.SetShell (option_arg);
811 launch_info.SetShell ("/bin/bash");
815 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
819 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
827 ProcessLaunchCommandOptions::g_option_table[] =
829 { LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', no_argument, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."},
830 { LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
831 { LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
832 { LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
833 { LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
834 { LLDB_OPT_SET_ALL, false, "environment", 'v', required_argument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value stirng (--environement NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
835 { LLDB_OPT_SET_ALL, false, "shell", 'c', optional_argument, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
837 { LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
838 { LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
839 { LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
841 { LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
843 { LLDB_OPT_SET_3 , false, "no-stdio", 'n', no_argument, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."},
845 { 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
851 ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
853 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
855 const char *match_name = m_match_info.GetName();
859 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
863 ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
865 if (!NameMatches (proc_info.GetName()))
868 if (m_match_info.ProcessIDIsValid() &&
869 m_match_info.GetProcessID() != proc_info.GetProcessID())
872 if (m_match_info.ParentProcessIDIsValid() &&
873 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
876 if (m_match_info.UserIDIsValid () &&
877 m_match_info.GetUserID() != proc_info.GetUserID())
880 if (m_match_info.GroupIDIsValid () &&
881 m_match_info.GetGroupID() != proc_info.GetGroupID())
884 if (m_match_info.EffectiveUserIDIsValid () &&
885 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
888 if (m_match_info.EffectiveGroupIDIsValid () &&
889 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
892 if (m_match_info.GetArchitecture().IsValid() &&
893 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
899 ProcessInstanceInfoMatch::MatchAllProcesses () const
901 if (m_name_match_type != eNameMatchIgnore)
904 if (m_match_info.ProcessIDIsValid())
907 if (m_match_info.ParentProcessIDIsValid())
910 if (m_match_info.UserIDIsValid ())
913 if (m_match_info.GroupIDIsValid ())
916 if (m_match_info.EffectiveUserIDIsValid ())
919 if (m_match_info.EffectiveGroupIDIsValid ())
922 if (m_match_info.GetArchitecture().IsValid())
925 if (m_match_all_users)
933 ProcessInstanceInfoMatch::Clear()
935 m_match_info.Clear();
936 m_name_match_type = eNameMatchIgnore;
937 m_match_all_users = false;
941 Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
943 static uint32_t g_process_unique_id = 0;
945 ProcessSP process_sp;
946 ProcessCreateInstance create_callback = NULL;
949 ConstString const_plugin_name(plugin_name);
950 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
953 process_sp = create_callback(target, listener, crash_file_path);
956 if (process_sp->CanDebug(target, true))
958 process_sp->m_process_unique_id = ++g_process_unique_id;
967 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
969 process_sp = create_callback(target, listener, crash_file_path);
972 if (process_sp->CanDebug(target, false))
974 process_sp->m_process_unique_id = ++g_process_unique_id;
986 Process::GetStaticBroadcasterClass ()
988 static ConstString class_name ("lldb.process");
992 //----------------------------------------------------------------------
993 // Process constructor
994 //----------------------------------------------------------------------
995 Process::Process(Target &target, Listener &listener) :
996 ProcessProperties (false),
997 UserID (LLDB_INVALID_PROCESS_ID),
998 Broadcaster (&(target.GetDebugger()), "lldb.process"),
1000 m_public_state (eStateUnloaded),
1001 m_private_state (eStateUnloaded),
1002 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
1003 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
1004 m_private_state_listener ("lldb.process.internal_state_listener"),
1005 m_private_state_control_wait(),
1006 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
1008 m_process_unique_id(0),
1009 m_thread_index_id (0),
1010 m_thread_id_to_index_id_map (),
1013 m_thread_mutex (Mutex::eMutexTypeRecursive),
1014 m_thread_list_real (this),
1015 m_thread_list (this),
1018 m_listener (listener),
1019 m_breakpoint_site_list (),
1020 m_dynamic_checkers_ap (),
1023 m_process_input_reader (),
1024 m_stdio_communication ("process.stdio"),
1025 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
1028 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1030 m_memory_cache (*this),
1031 m_allocated_memory_cache (*this),
1032 m_should_detach (false),
1033 m_next_event_action_ap(),
1034 m_public_run_lock (),
1035 m_private_run_lock (),
1036 m_currently_handling_event(false),
1037 m_finalize_called(false),
1038 m_clear_thread_plans_on_stop (false),
1039 m_last_broadcast_state (eStateInvalid),
1040 m_destroy_in_process (false),
1041 m_can_jit(eCanJITDontKnow)
1043 CheckInWithManager ();
1045 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
1047 log->Printf ("%p Process::Process()", this);
1049 SetEventName (eBroadcastBitStateChanged, "state-changed");
1050 SetEventName (eBroadcastBitInterrupt, "interrupt");
1051 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1052 SetEventName (eBroadcastBitSTDERR, "stderr-available");
1053 SetEventName (eBroadcastBitProfileData, "profile-data-available");
1055 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1056 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1057 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1059 listener.StartListeningForEvents (this,
1060 eBroadcastBitStateChanged |
1061 eBroadcastBitInterrupt |
1062 eBroadcastBitSTDOUT |
1063 eBroadcastBitSTDERR |
1064 eBroadcastBitProfileData);
1066 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
1067 eBroadcastBitStateChanged |
1068 eBroadcastBitInterrupt);
1070 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1071 eBroadcastInternalStateControlStop |
1072 eBroadcastInternalStateControlPause |
1073 eBroadcastInternalStateControlResume);
1076 //----------------------------------------------------------------------
1078 //----------------------------------------------------------------------
1081 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
1083 log->Printf ("%p Process::~Process()", this);
1084 StopPrivateStateThread();
1087 const ProcessPropertiesSP &
1088 Process::GetGlobalProperties()
1090 static ProcessPropertiesSP g_settings_sp;
1092 g_settings_sp.reset (new ProcessProperties (true));
1093 return g_settings_sp;
1099 switch (GetPrivateState())
1101 case eStateConnected:
1102 case eStateAttaching:
1103 case eStateLaunching:
1106 case eStateStepping:
1108 case eStateSuspended:
1109 if (GetShouldDetach())
1111 // FIXME: This will have to be a process setting:
1112 bool keep_stopped = false;
1113 Detach(keep_stopped);
1120 case eStateUnloaded:
1121 case eStateDetached:
1126 // Clear our broadcaster before we proceed with destroying
1127 Broadcaster::Clear();
1129 // Do any cleanup needed prior to being destructed... Subclasses
1130 // that override this method should call this superclass method as well.
1132 // We need to destroy the loader before the derived Process class gets destroyed
1133 // since it is very likely that undoing the loader will require access to the real process.
1134 m_dynamic_checkers_ap.reset();
1138 m_thread_list_real.Destroy();
1139 m_thread_list.Destroy();
1140 std::vector<Notifications> empty_notifications;
1141 m_notifications.swap(empty_notifications);
1142 m_image_tokens.clear();
1143 m_memory_cache.Clear();
1144 m_allocated_memory_cache.Clear();
1145 m_language_runtimes.clear();
1146 m_next_event_action_ap.reset();
1147 //#ifdef LLDB_CONFIGURATION_DEBUG
1148 // StreamFile s(stdout, false);
1149 // EventSP event_sp;
1150 // while (m_private_state_listener.GetNextEvent(event_sp))
1152 // event_sp->Dump (&s);
1156 // We have to be very careful here as the m_private_state_listener might
1157 // contain events that have ProcessSP values in them which can keep this
1158 // process around forever. These events need to be cleared out.
1159 m_private_state_listener.Clear();
1160 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
1161 m_public_run_lock.SetStopped();
1162 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
1163 m_private_run_lock.SetStopped();
1164 m_finalize_called = true;
1168 Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1170 m_notifications.push_back(callbacks);
1171 if (callbacks.initialize != NULL)
1172 callbacks.initialize (callbacks.baton, this);
1176 Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1178 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1179 for (pos = m_notifications.begin(); pos != end; ++pos)
1181 if (pos->baton == callbacks.baton &&
1182 pos->initialize == callbacks.initialize &&
1183 pos->process_state_changed == callbacks.process_state_changed)
1185 m_notifications.erase(pos);
1193 Process::SynchronouslyNotifyStateChanged (StateType state)
1195 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1196 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1198 if (notification_pos->process_state_changed)
1199 notification_pos->process_state_changed (notification_pos->baton, this, state);
1203 // FIXME: We need to do some work on events before the general Listener sees them.
1204 // For instance if we are continuing from a breakpoint, we need to ensure that we do
1205 // the little "insert real insn, step & stop" trick. But we can't do that when the
1206 // event is delivered by the broadcaster - since that is done on the thread that is
1207 // waiting for new events, so if we needed more than one event for our handling, we would
1208 // stall. So instead we do it when we fetch the event off of the queue.
1212 Process::GetNextEvent (EventSP &event_sp)
1214 StateType state = eStateInvalid;
1216 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1217 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1224 Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
1226 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1227 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1230 event_sp_ptr->reset();
1231 StateType state = GetState();
1232 // If we are exited or detached, we won't ever get back to any
1233 // other valid state...
1234 if (state == eStateDetached || state == eStateExited)
1237 while (state != eStateInvalid)
1240 state = WaitForStateChangedEvents (timeout, event_sp);
1241 if (event_sp_ptr && event_sp)
1242 *event_sp_ptr = event_sp;
1247 case eStateDetached:
1249 case eStateUnloaded:
1252 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1265 Process::WaitForState
1267 const TimeValue *timeout,
1268 const StateType *match_states, const uint32_t num_match_states
1273 StateType state = GetState();
1274 while (state != eStateInvalid)
1276 // If we are exited or detached, we won't ever get back to any
1277 // other valid state...
1278 if (state == eStateDetached || state == eStateExited)
1281 state = WaitForStateChangedEvents (timeout, event_sp);
1283 for (i=0; i<num_match_states; ++i)
1285 if (match_states[i] == state)
1293 Process::HijackProcessEvents (Listener *listener)
1295 if (listener != NULL)
1297 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
1304 Process::RestoreProcessEvents ()
1306 RestoreBroadcaster();
1310 Process::HijackPrivateProcessEvents (Listener *listener)
1312 if (listener != NULL)
1314 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
1321 Process::RestorePrivateProcessEvents ()
1323 m_private_state_broadcaster.RestoreBroadcaster();
1327 Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1329 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1332 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1334 StateType state = eStateInvalid;
1335 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1337 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1340 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1341 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1343 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1347 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1350 StateAsCString(state));
1355 Process::PeekAtStateChangedEvents ()
1357 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1360 log->Printf ("Process::%s...", __FUNCTION__);
1363 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1364 eBroadcastBitStateChanged);
1369 log->Printf ("Process::%s (event_ptr) => %s",
1371 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1375 log->Printf ("Process::%s no events found",
1383 Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1385 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1388 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1390 StateType state = eStateInvalid;
1391 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1392 &m_private_state_broadcaster,
1393 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1395 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1396 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1398 // This is a bit of a hack, but when we wait here we could very well return
1399 // to the command-line, and that could disable the log, which would render the
1400 // log we got above invalid.
1403 if (state == eStateInvalid)
1404 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1406 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1412 Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1414 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1417 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1420 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1422 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1426 Process::IsRunning () const
1428 return StateIsRunningState (m_public_state.GetValue());
1432 Process::GetExitStatus ()
1434 if (m_public_state.GetValue() == eStateExited)
1435 return m_exit_status;
1441 Process::GetExitDescription ()
1443 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1444 return m_exit_string.c_str();
1449 Process::SetExitStatus (int status, const char *cstr)
1451 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1453 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1456 cstr ? cstr : "NULL",
1459 // We were already in the exited state
1460 if (m_private_state.GetValue() == eStateExited)
1463 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
1467 m_exit_status = status;
1469 m_exit_string = cstr;
1471 m_exit_string.clear();
1475 SetPrivateState (eStateExited);
1479 // This static callback can be used to watch for local child processes on
1480 // the current host. The the child process exits, the process will be
1481 // found in the global target list (we want to be completely sure that the
1482 // lldb_private::Process doesn't go away before we can deliver the signal.
1484 Process::SetProcessExitStatus (void *callback_baton,
1487 int signo, // Zero for no signal
1488 int exit_status // Exit value of process if signal is zero
1491 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1493 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
1502 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
1505 ProcessSP process_sp (target_sp->GetProcessSP());
1508 const char *signal_cstr = NULL;
1510 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1512 process_sp->SetExitStatus (exit_status, signal_cstr);
1522 Process::UpdateThreadListIfNeeded ()
1524 const uint32_t stop_id = GetStopID();
1525 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1527 const StateType state = GetPrivateState();
1528 if (StateIsStoppedState (state, true))
1530 Mutex::Locker locker (m_thread_list.GetMutex ());
1531 // m_thread_list does have its own mutex, but we need to
1532 // hold onto the mutex between the call to UpdateThreadList(...)
1533 // and the os->UpdateThreadList(...) so it doesn't change on us
1534 ThreadList &old_thread_list = m_thread_list;
1535 ThreadList real_thread_list(this);
1536 ThreadList new_thread_list(this);
1537 // Always update the thread list with the protocol specific
1538 // thread list, but only update if "true" is returned
1539 if (UpdateThreadList (m_thread_list_real, real_thread_list))
1541 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1542 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1543 // shutting us down, causing a deadlock.
1544 if (!m_destroy_in_process)
1546 OperatingSystem *os = GetOperatingSystem ();
1549 // Clear any old backing threads where memory threads might have been
1550 // backed by actual threads from the lldb_private::Process subclass
1551 size_t num_old_threads = old_thread_list.GetSize(false);
1552 for (size_t i=0; i<num_old_threads; ++i)
1553 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1555 // Now let the OperatingSystem plug-in update the thread list
1556 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1557 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1558 new_thread_list); // The new thread list that we will show to the user that gets filled in
1562 // No OS plug-in, the new thread list is the same as the real thread list
1563 new_thread_list = real_thread_list;
1567 m_thread_list_real.Update(real_thread_list);
1568 m_thread_list.Update (new_thread_list);
1569 m_thread_list.SetStopID (stop_id);
1576 Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1578 OperatingSystem *os = GetOperatingSystem ();
1580 return os->CreateThread(tid, context);
1585 Process::GetNextThreadIndexID (uint64_t thread_id)
1587 return AssignIndexIDToThread(thread_id);
1591 Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1593 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1594 if (iterator == m_thread_id_to_index_id_map.end())
1605 Process::AssignIndexIDToThread(uint64_t thread_id)
1607 uint32_t result = 0;
1608 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1609 if (iterator == m_thread_id_to_index_id_map.end())
1611 result = ++m_thread_index_id;
1612 m_thread_id_to_index_id_map[thread_id] = result;
1616 result = iterator->second;
1625 // If any other threads access this we will need a mutex for it
1626 return m_public_state.GetValue ();
1630 Process::SetPublicState (StateType new_state, bool restarted)
1632 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1634 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
1635 const StateType old_state = m_public_state.GetValue();
1636 m_public_state.SetValue (new_state);
1638 // On the transition from Run to Stopped, we unlock the writer end of the
1639 // run lock. The lock gets locked in Resume, which is the public API
1640 // to tell the program to run.
1641 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1643 if (new_state == eStateDetached)
1646 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1647 m_public_run_lock.SetStopped();
1651 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1652 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1653 if ((old_state_is_stopped != new_state_is_stopped))
1655 if (new_state_is_stopped && !restarted)
1658 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1659 m_public_run_lock.SetStopped();
1669 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1671 log->Printf("Process::Resume -- locking run lock");
1672 if (!m_public_run_lock.TrySetRunning())
1674 Error error("Resume request failed - process still running.");
1676 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
1679 return PrivateResume();
1683 Process::GetPrivateState ()
1685 return m_private_state.GetValue();
1689 Process::SetPrivateState (StateType new_state)
1691 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1692 bool state_changed = false;
1695 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1697 Mutex::Locker thread_locker(m_thread_list.GetMutex());
1698 Mutex::Locker locker(m_private_state.GetMutex());
1700 const StateType old_state = m_private_state.GetValueNoLock ();
1701 state_changed = old_state != new_state;
1703 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1704 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1705 if (old_state_is_stopped != new_state_is_stopped)
1707 if (new_state_is_stopped)
1708 m_private_run_lock.SetStopped();
1710 m_private_run_lock.SetRunning();
1715 m_private_state.SetValueNoLock (new_state);
1716 if (StateIsStoppedState(new_state, false))
1718 // Note, this currently assumes that all threads in the list
1719 // stop when the process stops. In the future we will want to
1720 // support a debugging model where some threads continue to run
1721 // while others are stopped. When that happens we will either need
1722 // a way for the thread list to identify which threads are stopping
1723 // or create a special thread list containing only threads which
1724 // actually stopped.
1726 // The process plugin is responsible for managing the actual
1727 // behavior of the threads and should have stopped any threads
1728 // that are going to stop before we get here.
1729 m_thread_list.DidStop();
1731 m_mod_id.BumpStopID();
1732 m_memory_cache.Clear();
1734 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
1736 // Use our target to get a shared pointer to ourselves...
1737 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1738 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1740 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1745 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
1750 Process::SetRunningUserExpression (bool on)
1752 m_mod_id.SetRunningUserExpression (on);
1756 Process::GetImageInfoAddress()
1758 return LLDB_INVALID_ADDRESS;
1761 //----------------------------------------------------------------------
1764 // This function provides a default implementation that works for most
1765 // unix variants. Any Process subclasses that need to do shared library
1766 // loading differently should override LoadImage and UnloadImage and
1767 // do what is needed.
1768 //----------------------------------------------------------------------
1770 Process::LoadImage (const FileSpec &image_spec, Error &error)
1772 char path[PATH_MAX];
1773 image_spec.GetPath(path, sizeof(path));
1775 DynamicLoader *loader = GetDynamicLoader();
1778 error = loader->CanLoadImage();
1780 return LLDB_INVALID_IMAGE_TOKEN;
1783 if (error.Success())
1785 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
1789 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1793 ExecutionContext exe_ctx;
1794 frame_sp->CalculateExecutionContext (exe_ctx);
1795 const bool unwind_on_error = true;
1796 const bool ignore_breakpoints = true;
1798 expr.Printf("dlopen (\"%s\", 2)", path);
1799 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
1800 lldb::ValueObjectSP result_valobj_sp;
1801 ClangUserExpression::Evaluate (exe_ctx,
1802 eExecutionPolicyAlways,
1803 lldb::eLanguageTypeUnknown,
1804 ClangUserExpression::eResultTypeAny,
1811 ClangUserExpression::kDefaultTimeout);
1812 error = result_valobj_sp->GetError();
1813 if (error.Success())
1816 if (result_valobj_sp->ResolveValue (scalar))
1818 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1819 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1821 uint32_t image_token = m_image_tokens.size();
1822 m_image_tokens.push_back (image_ptr);
1830 if (!error.AsCString())
1831 error.SetErrorStringWithFormat("unable to load '%s'", path);
1832 return LLDB_INVALID_IMAGE_TOKEN;
1835 //----------------------------------------------------------------------
1838 // This function provides a default implementation that works for most
1839 // unix variants. Any Process subclasses that need to do shared library
1840 // loading differently should override LoadImage and UnloadImage and
1841 // do what is needed.
1842 //----------------------------------------------------------------------
1844 Process::UnloadImage (uint32_t image_token)
1847 if (image_token < m_image_tokens.size())
1849 const addr_t image_addr = m_image_tokens[image_token];
1850 if (image_addr == LLDB_INVALID_ADDRESS)
1852 error.SetErrorString("image already unloaded");
1856 DynamicLoader *loader = GetDynamicLoader();
1858 error = loader->CanLoadImage();
1860 if (error.Success())
1862 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
1866 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1870 ExecutionContext exe_ctx;
1871 frame_sp->CalculateExecutionContext (exe_ctx);
1872 const bool unwind_on_error = true;
1873 const bool ignore_breakpoints = true;
1875 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
1876 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
1877 lldb::ValueObjectSP result_valobj_sp;
1878 ClangUserExpression::Evaluate (exe_ctx,
1879 eExecutionPolicyAlways,
1880 lldb::eLanguageTypeUnknown,
1881 ClangUserExpression::eResultTypeAny,
1888 ClangUserExpression::kDefaultTimeout);
1889 if (result_valobj_sp->GetError().Success())
1892 if (result_valobj_sp->ResolveValue (scalar))
1896 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1900 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1906 error = result_valobj_sp->GetError();
1915 error.SetErrorString("invalid image token");
1924 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1929 Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
1931 LanguageRuntimeCollection::iterator pos;
1932 pos = m_language_runtimes.find (language);
1933 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
1935 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
1937 m_language_runtimes[language] = runtime_sp;
1938 return runtime_sp.get();
1941 return (*pos).second.get();
1944 CPPLanguageRuntime *
1945 Process::GetCPPLanguageRuntime (bool retry_if_null)
1947 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1948 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1949 return static_cast<CPPLanguageRuntime *> (runtime);
1953 ObjCLanguageRuntime *
1954 Process::GetObjCLanguageRuntime (bool retry_if_null)
1956 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1957 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1958 return static_cast<ObjCLanguageRuntime *> (runtime);
1963 Process::IsPossibleDynamicValue (ValueObject& in_value)
1965 if (in_value.IsDynamic())
1967 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1969 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1971 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1972 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1975 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1976 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1979 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1980 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1983 BreakpointSiteList &
1984 Process::GetBreakpointSiteList()
1986 return m_breakpoint_site_list;
1989 const BreakpointSiteList &
1990 Process::GetBreakpointSiteList() const
1992 return m_breakpoint_site_list;
1997 Process::DisableAllBreakpointSites ()
1999 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2000 // bp_site->SetEnabled(true);
2001 DisableBreakpointSite(bp_site);
2006 Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2008 Error error (DisableBreakpointSiteByID (break_id));
2010 if (error.Success())
2011 m_breakpoint_site_list.Remove(break_id);
2017 Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2020 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2023 if (bp_site_sp->IsEnabled())
2024 error = DisableBreakpointSite (bp_site_sp.get());
2028 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
2035 Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2038 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2041 if (!bp_site_sp->IsEnabled())
2042 error = EnableBreakpointSite (bp_site_sp.get());
2046 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
2052 Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
2054 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2055 if (load_addr != LLDB_INVALID_ADDRESS)
2057 BreakpointSiteSP bp_site_sp;
2059 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2060 // create a new breakpoint site and add it.
2062 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2066 bp_site_sp->AddOwner (owner);
2067 owner->SetBreakpointSite (bp_site_sp);
2068 return bp_site_sp->GetID();
2072 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
2075 if (EnableBreakpointSite (bp_site_sp.get()).Success())
2077 owner->SetBreakpointSite (bp_site_sp);
2078 return m_breakpoint_site_list.Add (bp_site_sp);
2083 // We failed to enable the breakpoint
2084 return LLDB_INVALID_BREAK_ID;
2089 Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2091 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2092 if (num_owners == 0)
2094 // Don't try to disable the site if we don't have a live process anymore.
2096 DisableBreakpointSite (bp_site_sp.get());
2097 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2103 Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2105 size_t bytes_removed = 0;
2106 BreakpointSiteList bp_sites_in_range;
2108 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
2110 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2111 if (bp_site->GetType() == BreakpointSite::eSoftware)
2113 addr_t intersect_addr;
2114 size_t intersect_size;
2115 size_t opcode_offset;
2116 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
2118 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2119 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
2120 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
2121 size_t buf_offset = intersect_addr - bp_addr;
2122 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
2127 return bytes_removed;
2133 Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2135 PlatformSP platform_sp (m_target.GetPlatform());
2137 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2142 Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2145 assert (bp_site != NULL);
2146 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2147 const addr_t bp_addr = bp_site->GetLoadAddress();
2149 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
2150 if (bp_site->IsEnabled())
2153 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
2157 if (bp_addr == LLDB_INVALID_ADDRESS)
2159 error.SetErrorString("BreakpointSite contains an invalid load address.");
2162 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2163 // trap for the breakpoint site
2164 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2166 if (bp_opcode_size == 0)
2168 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
2172 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2174 if (bp_opcode_bytes == NULL)
2176 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2180 // Save the original opcode by reading it
2181 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2183 // Write a software breakpoint in place of the original opcode
2184 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2186 uint8_t verify_bp_opcode_bytes[64];
2187 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2189 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2191 bp_site->SetEnabled(true);
2192 bp_site->SetType (BreakpointSite::eSoftware);
2194 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
2199 error.SetErrorString("failed to verify the breakpoint trap in memory.");
2202 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2205 error.SetErrorString("Unable to write breakpoint trap to memory.");
2208 error.SetErrorString("Unable to read memory at breakpoint address.");
2210 if (log && error.Fail())
2211 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
2219 Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2222 assert (bp_site != NULL);
2223 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2224 addr_t bp_addr = bp_site->GetLoadAddress();
2225 lldb::user_id_t breakID = bp_site->GetID();
2227 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
2229 if (bp_site->IsHardware())
2231 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2233 else if (bp_site->IsEnabled())
2235 const size_t break_op_size = bp_site->GetByteSize();
2236 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2237 if (break_op_size > 0)
2239 // Clear a software breakoint instruction
2240 uint8_t curr_break_op[8];
2241 assert (break_op_size <= sizeof(curr_break_op));
2242 bool break_op_found = false;
2244 // Read the breakpoint opcode
2245 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2247 bool verify = false;
2248 // Make sure we have the a breakpoint opcode exists at this address
2249 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2251 break_op_found = true;
2252 // We found a valid breakpoint opcode at this address, now restore
2253 // the saved opcode.
2254 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2259 error.SetErrorString("Memory write failed when restoring original opcode.");
2263 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2264 // Set verify to true and so we can check if the original opcode has already been restored
2270 uint8_t verify_opcode[8];
2271 assert (break_op_size < sizeof(verify_opcode));
2272 // Verify that our original opcode made it back to the inferior
2273 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2275 // compare the memory we just read with the original opcode
2276 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2279 bp_site->SetEnabled(false);
2281 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
2287 error.SetErrorString("Failed to restore original opcode.");
2291 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2295 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2301 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
2306 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
2314 // Uncomment to verify memory caching works after making changes to caching code
2315 //#define VERIFY_MEMORY_READS
2318 Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2320 if (!GetDisableMemoryCache())
2322 #if defined (VERIFY_MEMORY_READS)
2323 // Memory caching is enabled, with debug verification
2327 // Uncomment the line below to make sure memory caching is working.
2328 // I ran this through the test suite and got no assertions, so I am
2329 // pretty confident this is working well. If any changes are made to
2330 // memory caching, uncomment the line below and test your changes!
2332 // Verify all memory reads by using the cache first, then redundantly
2333 // reading the same memory from the inferior and comparing to make sure
2334 // everything is exactly the same.
2335 std::string verify_buf (size, '\0');
2336 assert (verify_buf.size() == size);
2337 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2339 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2340 assert (cache_bytes_read == verify_bytes_read);
2341 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2342 assert (verify_error.Success() == error.Success());
2343 return cache_bytes_read;
2346 #else // !defined(VERIFY_MEMORY_READS)
2347 // Memory caching is enabled, without debug verification
2349 return m_memory_cache.Read (addr, buf, size, error);
2350 #endif // defined (VERIFY_MEMORY_READS)
2354 // Memory caching is disabled
2356 return ReadMemoryFromInferior (addr, buf, size, error);
2361 Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2365 addr_t curr_addr = addr;
2368 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2371 out_str.append(buf, length);
2372 // If we got "length - 1" bytes, we didn't get the whole C string, we
2373 // need to read some more characters
2374 if (length == sizeof(buf) - 1)
2375 curr_addr += length;
2379 return out_str.size();
2384 Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2387 size_t total_bytes_read = 0;
2388 if (dst && max_bytes && type_width && max_bytes >= type_width)
2390 // Ensure a null terminator independent of the number of bytes that is read.
2391 memset (dst, 0, max_bytes);
2392 size_t bytes_left = max_bytes - type_width;
2394 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2395 assert(sizeof(terminator) >= type_width &&
2396 "Attempting to validate a string with more than 4 bytes per character!");
2398 addr_t curr_addr = addr;
2399 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2400 char *curr_dst = dst;
2403 while (bytes_left > 0 && error.Success())
2405 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2406 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2407 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2409 if (bytes_read == 0)
2412 // Search for a null terminator of correct size and alignment in bytes_read
2413 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2414 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2415 if (::strncmp(&dst[i], terminator, type_width) == 0)
2421 total_bytes_read += bytes_read;
2422 curr_dst += bytes_read;
2423 curr_addr += bytes_read;
2424 bytes_left -= bytes_read;
2430 error.SetErrorString("invalid arguments");
2432 return total_bytes_read;
2435 // Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2436 // null terminators.
2438 Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
2440 size_t total_cstr_len = 0;
2441 if (dst && dst_max_len)
2443 result_error.Clear();
2444 // NULL out everything just to be safe
2445 memset (dst, 0, dst_max_len);
2447 addr_t curr_addr = addr;
2448 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2449 size_t bytes_left = dst_max_len - 1;
2450 char *curr_dst = dst;
2452 while (bytes_left > 0)
2454 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2455 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2456 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2458 if (bytes_read == 0)
2460 result_error = error;
2461 dst[total_cstr_len] = '\0';
2464 const size_t len = strlen(curr_dst);
2466 total_cstr_len += len;
2468 if (len < bytes_to_read)
2471 curr_dst += bytes_read;
2472 curr_addr += bytes_read;
2473 bytes_left -= bytes_read;
2479 result_error.SetErrorString("invalid arguments");
2481 result_error.Clear();
2483 return total_cstr_len;
2487 Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2489 if (buf == NULL || size == 0)
2492 size_t bytes_read = 0;
2493 uint8_t *bytes = (uint8_t *)buf;
2495 while (bytes_read < size)
2497 const size_t curr_size = size - bytes_read;
2498 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2502 bytes_read += curr_bytes_read;
2503 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2507 // Replace any software breakpoint opcodes that fall into this range back
2508 // into "buf" before we return
2510 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2515 Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
2518 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2519 return scalar.ULongLong(fail_value);
2524 Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2527 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2528 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2529 return LLDB_INVALID_ADDRESS;
2534 Process::WritePointerToMemory (lldb::addr_t vm_addr,
2535 lldb::addr_t ptr_value,
2539 const uint32_t addr_byte_size = GetAddressByteSize();
2540 if (addr_byte_size <= 4)
2541 scalar = (uint32_t)ptr_value;
2544 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
2548 Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2550 size_t bytes_written = 0;
2551 const uint8_t *bytes = (const uint8_t *)buf;
2553 while (bytes_written < size)
2555 const size_t curr_size = size - bytes_written;
2556 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2557 bytes + bytes_written,
2560 bytes_written += curr_bytes_written;
2561 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2564 return bytes_written;
2568 Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2570 #if defined (ENABLE_MEMORY_CACHING)
2571 m_memory_cache.Flush (addr, size);
2574 if (buf == NULL || size == 0)
2577 m_mod_id.BumpMemoryID();
2579 // We need to write any data that would go where any current software traps
2580 // (enabled software breakpoints) any software traps (breakpoints) that we
2581 // may have placed in our tasks memory.
2583 BreakpointSiteList bp_sites_in_range;
2585 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
2587 // No breakpoint sites overlap
2588 if (bp_sites_in_range.IsEmpty())
2589 return WriteMemoryPrivate (addr, buf, size, error);
2592 const uint8_t *ubuf = (const uint8_t *)buf;
2593 uint64_t bytes_written = 0;
2595 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2597 if (error.Success())
2599 addr_t intersect_addr;
2600 size_t intersect_size;
2601 size_t opcode_offset;
2602 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2604 assert(addr <= intersect_addr && intersect_addr < addr + size);
2605 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2606 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2608 // Check for bytes before this breakpoint
2609 const addr_t curr_addr = addr + bytes_written;
2610 if (intersect_addr > curr_addr)
2612 // There are some bytes before this breakpoint that we need to
2613 // just write to memory
2614 size_t curr_size = intersect_addr - curr_addr;
2615 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2616 ubuf + bytes_written,
2619 bytes_written += curr_bytes_written;
2620 if (curr_bytes_written != curr_size)
2622 // We weren't able to write all of the requested bytes, we
2623 // are done looping and will return the number of bytes that
2624 // we have written so far.
2625 if (error.Success())
2626 error.SetErrorToGenericError();
2629 // Now write any bytes that would cover up any software breakpoints
2630 // directly into the breakpoint opcode buffer
2631 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2632 bytes_written += intersect_size;
2636 if (bytes_written < size)
2637 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2638 ubuf + bytes_written,
2639 size - bytes_written,
2645 return WriteMemoryPrivate (addr, buf, size, error);
2648 // Write any remaining bytes after the last breakpoint if we have any left
2649 return 0; //bytes_written;
2653 Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
2655 if (byte_size == UINT32_MAX)
2656 byte_size = scalar.GetByteSize();
2660 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2662 return WriteMemory(addr, buf, mem_size, error);
2664 error.SetErrorString ("failed to get scalar as memory data");
2668 error.SetErrorString ("invalid scalar value");
2674 Process::ReadScalarIntegerFromMemory (addr_t addr,
2683 error.SetErrorString ("byte size is zero");
2685 else if (byte_size & (byte_size - 1))
2687 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2689 else if (byte_size <= sizeof(uval))
2691 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2692 if (bytes_read == byte_size)
2694 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2695 lldb::offset_t offset = 0;
2697 scalar = data.GetMaxU32 (&offset, byte_size);
2699 scalar = data.GetMaxU64 (&offset, byte_size);
2701 scalar.SignExtend(byte_size * 8);
2707 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2712 #define USE_ALLOCATE_MEMORY_CACHE 1
2714 Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2716 if (GetPrivateState() != eStateStopped)
2717 return LLDB_INVALID_ADDRESS;
2719 #if defined (USE_ALLOCATE_MEMORY_CACHE)
2720 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2722 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2723 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2725 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16" PRIx64 " (m_stop_id = %u m_memory_id = %u)",
2727 GetPermissionsAsCString (permissions),
2728 (uint64_t)allocated_addr,
2729 m_mod_id.GetStopID(),
2730 m_mod_id.GetMemoryID());
2731 return allocated_addr;
2738 if (m_can_jit == eCanJITDontKnow)
2742 uint64_t allocated_memory = AllocateMemory(8,
2743 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2747 m_can_jit = eCanJITYes;
2749 m_can_jit = eCanJITNo;
2751 DeallocateMemory (allocated_memory);
2754 return m_can_jit == eCanJITYes;
2758 Process::SetCanJIT (bool can_jit)
2760 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2764 Process::DeallocateMemory (addr_t ptr)
2767 #if defined (USE_ALLOCATE_MEMORY_CACHE)
2768 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2770 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2773 error = DoDeallocateMemory (ptr);
2775 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2777 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2779 error.AsCString("SUCCESS"),
2780 m_mod_id.GetStopID(),
2781 m_mod_id.GetMemoryID());
2788 Process::ReadModuleFromMemory (const FileSpec& file_spec,
2789 lldb::addr_t header_addr)
2791 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
2795 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2803 Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
2806 error.SetErrorString("watchpoints are not supported");
2811 Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
2814 error.SetErrorString("watchpoints are not supported");
2819 Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2822 // Now wait for the process to launch and return control to us, and then
2827 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2829 if (StateIsStoppedState(state, false))
2832 // If state is invalid, then we timed out
2833 if (state == eStateInvalid)
2837 HandlePrivateEvent (event_sp);
2843 Process::Launch (const ProcessLaunchInfo &launch_info)
2849 m_process_input_reader.reset();
2851 Module *exe_module = m_target.GetExecutableModulePointer();
2854 char local_exec_file_path[PATH_MAX];
2855 char platform_exec_file_path[PATH_MAX];
2856 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2857 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
2858 if (exe_module->GetFileSpec().Exists())
2860 if (PrivateStateThreadIsValid ())
2861 PausePrivateStateThread ();
2863 error = WillLaunch (exe_module);
2864 if (error.Success())
2866 const bool restarted = false;
2867 SetPublicState (eStateLaunching, restarted);
2868 m_should_detach = false;
2870 if (m_public_run_lock.TrySetRunning())
2872 // Now launch using these arguments.
2873 error = DoLaunch (exe_module, launch_info);
2877 // This shouldn't happen
2878 error.SetErrorString("failed to acquire process run lock");
2883 if (GetID() != LLDB_INVALID_PROCESS_ID)
2885 SetID (LLDB_INVALID_PROCESS_ID);
2886 const char *error_string = error.AsCString();
2887 if (error_string == NULL)
2888 error_string = "launch failed";
2889 SetExitStatus (-1, error_string);
2895 TimeValue timeout_time;
2896 timeout_time = TimeValue::Now();
2897 timeout_time.OffsetWithSeconds(10);
2898 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
2900 if (state == eStateInvalid || event_sp.get() == NULL)
2902 // We were able to launch the process, but we failed to
2903 // catch the initial stop.
2904 SetExitStatus (0, "failed to catch stop after launch");
2907 else if (state == eStateStopped || state == eStateCrashed)
2912 DynamicLoader *dyld = GetDynamicLoader ();
2916 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
2917 // This delays passing the stopped event to listeners till DidLaunch gets
2918 // a chance to complete...
2919 HandlePrivateEvent (event_sp);
2921 if (PrivateStateThreadIsValid ())
2922 ResumePrivateStateThread ();
2924 StartPrivateStateThread ();
2926 else if (state == eStateExited)
2928 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2929 // not likely to work, and return an invalid pid.
2930 HandlePrivateEvent (event_sp);
2937 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
2945 Process::LoadCore ()
2947 Error error = DoLoadCore();
2948 if (error.Success())
2950 if (PrivateStateThreadIsValid ())
2951 ResumePrivateStateThread ();
2953 StartPrivateStateThread ();
2955 DynamicLoader *dyld = GetDynamicLoader ();
2959 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
2960 // We successfully loaded a core file, now pretend we stopped so we can
2961 // show all of the threads in the core file and explore the crashed
2963 SetPrivateState (eStateStopped);
2970 Process::GetDynamicLoader ()
2972 if (m_dyld_ap.get() == NULL)
2973 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2974 return m_dyld_ap.get();
2978 Process::NextEventAction::EventActionResult
2979 Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
2981 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2985 case eStateConnected:
2986 return eEventActionRetry;
2991 // During attach, prior to sending the eStateStopped event,
2992 // lldb_private::Process subclasses must set the new process ID.
2993 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2994 // We don't want these events to be reported, so go set the ShouldReportStop here:
2995 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
2997 if (m_exec_count > 0)
3001 return eEventActionRetry;
3005 m_process->CompleteAttach ();
3006 return eEventActionSuccess;
3017 m_exit_string.assign ("No valid Process");
3018 return eEventActionExit;
3021 Process::NextEventAction::EventActionResult
3022 Process::AttachCompletionHandler::HandleBeingInterrupted()
3024 return eEventActionSuccess;
3028 Process::AttachCompletionHandler::GetExitString ()
3030 return m_exit_string.c_str();
3034 Process::Attach (ProcessAttachInfo &attach_info)
3037 m_process_input_reader.reset();
3041 lldb::pid_t attach_pid = attach_info.GetProcessID();
3043 if (attach_pid == LLDB_INVALID_PROCESS_ID)
3045 char process_name[PATH_MAX];
3047 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
3049 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3051 if (wait_for_launch)
3053 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3054 if (error.Success())
3056 if (m_public_run_lock.TrySetRunning())
3058 m_should_detach = true;
3059 const bool restarted = false;
3060 SetPublicState (eStateAttaching, restarted);
3061 // Now attach using these arguments.
3062 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
3066 // This shouldn't happen
3067 error.SetErrorString("failed to acquire process run lock");
3072 if (GetID() != LLDB_INVALID_PROCESS_ID)
3074 SetID (LLDB_INVALID_PROCESS_ID);
3075 if (error.AsCString() == NULL)
3076 error.SetErrorString("attach failed");
3078 SetExitStatus(-1, error.AsCString());
3083 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3084 StartPrivateStateThread();
3091 ProcessInstanceInfoList process_infos;
3092 PlatformSP platform_sp (m_target.GetPlatform ());
3096 ProcessInstanceInfoMatch match_info;
3097 match_info.GetProcessInfo() = attach_info;
3098 match_info.SetNameMatchType (eNameMatchEquals);
3099 platform_sp->FindProcesses (match_info, process_infos);
3100 const uint32_t num_matches = process_infos.GetSize();
3101 if (num_matches == 1)
3103 attach_pid = process_infos.GetProcessIDAtIndex(0);
3104 // Fall through and attach using the above process ID
3108 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3109 if (num_matches > 1)
3110 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3112 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3117 error.SetErrorString ("invalid platform, can't find processes by name");
3124 error.SetErrorString ("invalid process name");
3128 if (attach_pid != LLDB_INVALID_PROCESS_ID)
3130 error = WillAttachToProcessWithID(attach_pid);
3131 if (error.Success())
3134 if (m_public_run_lock.TrySetRunning())
3136 // Now attach using these arguments.
3137 m_should_detach = true;
3138 const bool restarted = false;
3139 SetPublicState (eStateAttaching, restarted);
3140 error = DoAttachToProcessWithID (attach_pid, attach_info);
3144 // This shouldn't happen
3145 error.SetErrorString("failed to acquire process run lock");
3148 if (error.Success())
3151 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3152 StartPrivateStateThread();
3156 if (GetID() != LLDB_INVALID_PROCESS_ID)
3158 SetID (LLDB_INVALID_PROCESS_ID);
3159 const char *error_string = error.AsCString();
3160 if (error_string == NULL)
3161 error_string = "attach failed";
3163 SetExitStatus(-1, error_string);
3172 Process::CompleteAttach ()
3174 // Let the process subclass figure out at much as it can about the process
3175 // before we go looking for a dynamic loader plug-in.
3178 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3179 // the same as the one we've already set, switch architectures.
3180 PlatformSP platform_sp (m_target.GetPlatform ());
3181 assert (platform_sp.get());
3184 const ArchSpec &target_arch = m_target.GetArchitecture();
3185 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
3187 ArchSpec platform_arch;
3188 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3191 m_target.SetPlatform (platform_sp);
3192 m_target.SetArchitecture(platform_arch);
3197 ProcessInstanceInfo process_info;
3198 platform_sp->GetProcessInfo (GetID(), process_info);
3199 const ArchSpec &process_arch = process_info.GetArchitecture();
3200 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
3201 m_target.SetArchitecture (process_arch);
3205 // We have completed the attach, now it is time to find the dynamic loader
3207 DynamicLoader *dyld = GetDynamicLoader ();
3211 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
3212 // Figure out which one is the executable, and set that in our target:
3213 const ModuleList &target_modules = m_target.GetImages();
3214 Mutex::Locker modules_locker(target_modules.GetMutex());
3215 size_t num_modules = target_modules.GetSize();
3216 ModuleSP new_executable_module_sp;
3218 for (size_t i = 0; i < num_modules; i++)
3220 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
3221 if (module_sp && module_sp->IsExecutable())
3223 if (m_target.GetExecutableModulePointer() != module_sp.get())
3224 new_executable_module_sp = module_sp;
3228 if (new_executable_module_sp)
3229 m_target.SetExecutableModule (new_executable_module_sp, false);
3233 Process::ConnectRemote (Stream *strm, const char *remote_url)
3236 m_process_input_reader.reset();
3238 // Find the process and its architecture. Make sure it matches the architecture
3239 // of the current Target, and if not adjust it.
3241 Error error (DoConnectRemote (strm, remote_url));
3242 if (error.Success())
3244 if (GetID() != LLDB_INVALID_PROCESS_ID)
3247 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3249 if (state == eStateStopped || state == eStateCrashed)
3251 // If we attached and actually have a process on the other end, then
3252 // this ended up being the equivalent of an attach.
3255 // This delays passing the stopped event to listeners till
3256 // CompleteAttach gets a chance to complete...
3257 HandlePrivateEvent (event_sp);
3262 if (PrivateStateThreadIsValid ())
3263 ResumePrivateStateThread ();
3265 StartPrivateStateThread ();
3272 Process::PrivateResume ()
3274 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
3276 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
3277 m_mod_id.GetStopID(),
3278 StateAsCString(m_public_state.GetValue()),
3279 StateAsCString(m_private_state.GetValue()));
3281 Error error (WillResume());
3282 // Tell the process it is about to resume before the thread list
3283 if (error.Success())
3285 // Now let the thread list know we are about to resume so it
3286 // can let all of our threads know that they are about to be
3287 // resumed. Threads will each be called with
3288 // Thread::WillResume(StateType) where StateType contains the state
3289 // that they are supposed to have when the process is resumed
3290 // (suspended/running/stepping). Threads should also check
3291 // their resume signal in lldb::Thread::GetResumeSignal()
3292 // to see if they are supposed to start back up with a signal.
3293 if (m_thread_list.WillResume())
3295 // Last thing, do the PreResumeActions.
3296 if (!RunPreResumeActions())
3298 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
3302 m_mod_id.BumpResumeID();
3304 if (error.Success())
3307 m_thread_list.DidResume();
3309 log->Printf ("Process thinks the process has resumed.");
3315 // Somebody wanted to run without running. So generate a continue & a stopped event,
3316 // and let the world handle them.
3318 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3320 SetPrivateState(eStateRunning);
3321 SetPrivateState(eStateStopped);
3325 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
3330 Process::Halt (bool clear_thread_plans)
3332 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3333 // in case it was already set and some thread plan logic calls halt on its
3335 m_clear_thread_plans_on_stop |= clear_thread_plans;
3337 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3338 // we could just straightaway get another event. It just narrows the window...
3339 m_currently_handling_event.WaitForValueEqualTo(false);
3342 // Pause our private state thread so we can ensure no one else eats
3343 // the stop event out from under us.
3344 Listener halt_listener ("lldb.process.halt_listener");
3345 HijackPrivateProcessEvents(&halt_listener);
3348 Error error (WillHalt());
3350 if (error.Success())
3353 bool caused_stop = false;
3355 // Ask the process subclass to actually halt our process
3356 error = DoHalt(caused_stop);
3357 if (error.Success())
3359 if (m_public_state.GetValue() == eStateAttaching)
3361 SetExitStatus(SIGKILL, "Cancelled async attach.");
3366 // If "caused_stop" is true, then DoHalt stopped the process. If
3367 // "caused_stop" is false, the process was already stopped.
3368 // If the DoHalt caused the process to stop, then we want to catch
3369 // this event and set the interrupted bool to true before we pass
3370 // this along so clients know that the process was interrupted by
3374 // Wait for 1 second for the process to stop.
3375 TimeValue timeout_time;
3376 timeout_time = TimeValue::Now();
3377 timeout_time.OffsetWithSeconds(1);
3378 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3379 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
3381 if (!got_event || state == eStateInvalid)
3383 // We timeout out and didn't get a stop event...
3384 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
3388 if (StateIsStoppedState (state, false))
3390 // We caused the process to interrupt itself, so mark this
3391 // as such in the stop event so clients can tell an interrupted
3392 // process from a natural stop
3393 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3397 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3399 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3400 error.SetErrorString ("Did not get stopped event after halt.");
3408 // Resume our private state thread before we post the event (if any)
3409 RestorePrivateProcessEvents();
3411 // Post any event we might have consumed. If all goes well, we will have
3412 // stopped the process, intercepted the event and set the interrupted
3413 // bool in the event. Post it to the private event queue and that will end up
3414 // correctly setting the state.
3416 m_private_state_broadcaster.BroadcastEvent(event_sp);
3422 Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3425 if (m_public_state.GetValue() == eStateRunning)
3427 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3429 log->Printf("Process::Destroy() About to halt.");
3431 if (error.Success())
3433 // Consume the halt event.
3434 TimeValue timeout (TimeValue::Now());
3435 timeout.OffsetWithSeconds(1);
3436 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3438 // If the process exited while we were waiting for it to stop, put the exited event into
3439 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3440 // they don't have a process anymore...
3442 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3445 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3449 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3451 if (state != eStateStopped)
3454 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3455 // If we really couldn't stop the process then we should just error out here, but if the
3456 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3457 StateType private_state = m_private_state.GetValue();
3458 if (private_state != eStateStopped)
3467 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3474 Process::Detach (bool keep_stopped)
3476 EventSP exit_event_sp;
3478 m_destroy_in_process = true;
3480 error = WillDetach();
3482 if (error.Success())
3484 if (DetachRequiresHalt())
3486 error = HaltForDestroyOrDetach (exit_event_sp);
3487 if (!error.Success())
3489 m_destroy_in_process = false;
3492 else if (exit_event_sp)
3494 // We shouldn't need to do anything else here. There's no process left to detach from...
3495 StopPrivateStateThread();
3496 m_destroy_in_process = false;
3501 error = DoDetach(keep_stopped);
3502 if (error.Success())
3505 StopPrivateStateThread();
3512 m_destroy_in_process = false;
3514 // If we exited when we were waiting for a process to stop, then
3515 // forward the event here so we don't lose the event
3518 // Directly broadcast our exited event because we shut down our
3519 // private state thread above
3520 BroadcastEvent(exit_event_sp);
3523 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3524 // the last events through the event system, in which case we might strand the write lock. Unlock
3525 // it here so when we do to tear down the process we don't get an error destroying the lock.
3527 m_public_run_lock.SetStopped();
3535 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3536 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3537 // failed and the process stays around for some reason it won't be in a confused state.
3539 m_destroy_in_process = true;
3541 Error error (WillDestroy());
3542 if (error.Success())
3544 EventSP exit_event_sp;
3545 if (DestroyRequiresHalt())
3547 error = HaltForDestroyOrDetach(exit_event_sp);
3550 if (m_public_state.GetValue() != eStateRunning)
3552 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3553 // kill it, we don't want it hitting a breakpoint...
3554 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3555 // we're not going to have much luck doing this now.
3556 m_thread_list.DiscardThreadPlans();
3557 DisableAllBreakpointSites();
3560 error = DoDestroy();
3561 if (error.Success())
3564 StopPrivateStateThread();
3566 m_stdio_communication.StopReadThread();
3567 m_stdio_communication.Disconnect();
3568 if (m_process_input_reader && m_process_input_reader->IsActive())
3569 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3570 if (m_process_input_reader)
3571 m_process_input_reader.reset();
3573 // If we exited when we were waiting for a process to stop, then
3574 // forward the event here so we don't lose the event
3577 // Directly broadcast our exited event because we shut down our
3578 // private state thread above
3579 BroadcastEvent(exit_event_sp);
3582 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3583 // the last events through the event system, in which case we might strand the write lock. Unlock
3584 // it here so when we do to tear down the process we don't get an error destroying the lock.
3585 m_public_run_lock.SetStopped();
3588 m_destroy_in_process = false;
3594 Process::Signal (int signal)
3596 Error error (WillSignal());
3597 if (error.Success())
3599 error = DoSignal(signal);
3600 if (error.Success())
3607 Process::GetByteOrder () const
3609 return m_target.GetArchitecture().GetByteOrder();
3613 Process::GetAddressByteSize () const
3615 return m_target.GetArchitecture().GetAddressByteSize();
3620 Process::ShouldBroadcastEvent (Event *event_ptr)
3622 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3623 bool return_value = true;
3624 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
3628 case eStateConnected:
3629 case eStateAttaching:
3630 case eStateLaunching:
3631 case eStateDetached:
3633 case eStateUnloaded:
3634 // These events indicate changes in the state of the debugging session, always report them.
3635 return_value = true;
3638 // We stopped for no apparent reason, don't report it.
3639 return_value = false;
3642 case eStateStepping:
3643 // If we've started the target running, we handle the cases where we
3644 // are already running and where there is a transition from stopped to
3645 // running differently.
3646 // running -> running: Automatically suppress extra running events
3647 // stopped -> running: Report except when there is one or more no votes
3648 // and no yes votes.
3649 SynchronouslyNotifyStateChanged (state);
3650 switch (m_last_broadcast_state)
3653 case eStateStepping:
3654 // We always suppress multiple runnings with no PUBLIC stop in between.
3655 return_value = false;
3658 // TODO: make this work correctly. For now always report
3659 // run if we aren't running so we don't miss any runnning
3660 // events. If I run the lldb/test/thread/a.out file and
3661 // break at main.cpp:58, run and hit the breakpoints on
3662 // multiple threads, then somehow during the stepping over
3663 // of all breakpoints no run gets reported.
3665 // This is a transition from stop to run.
3666 switch (m_thread_list.ShouldReportRun (event_ptr))
3669 case eVoteNoOpinion:
3670 return_value = true;
3673 return_value = false;
3681 case eStateSuspended:
3683 // We've stopped. First see if we're going to restart the target.
3684 // If we are going to stop, then we always broadcast the event.
3685 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
3686 // If no thread has an opinion, we don't report it.
3688 RefreshStateAfterStop ();
3689 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
3692 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3694 StateAsCString(state));
3695 return_value = true;
3699 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3700 bool should_resume = false;
3702 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3703 // Asking the thread list is also not likely to go well, since we are running again.
3704 // So in that case just report the event.
3707 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
3709 if (was_restarted || should_resume || m_resume_requested)
3711 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3713 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3715 StateAsCString(state),
3722 return_value = true;
3724 case eVoteNoOpinion:
3726 return_value = false;
3733 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3734 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3741 return_value = true;
3742 SynchronouslyNotifyStateChanged (state);
3749 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3750 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3751 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3752 // because the PublicState reflects the last event pulled off the queue, and there may be several
3753 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3754 // yet. m_last_broadcast_state gets updated here.
3757 m_last_broadcast_state = state;
3760 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3762 StateAsCString(state),
3763 StateAsCString(m_last_broadcast_state),
3764 return_value ? "YES" : "NO");
3765 return return_value;
3770 Process::StartPrivateStateThread (bool force)
3772 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3774 bool already_running = PrivateStateThreadIsValid ();
3776 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3778 if (!force && already_running)
3781 // Create a thread that watches our internal state and controls which
3782 // events make it to clients (into the DCProcess event queue).
3783 char thread_name[1024];
3784 if (already_running)
3785 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
3787 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3789 // Create the private state thread, and start it running.
3790 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
3791 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3794 ResumePrivateStateThread();
3802 Process::PausePrivateStateThread ()
3804 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3808 Process::ResumePrivateStateThread ()
3810 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3814 Process::StopPrivateStateThread ()
3816 if (PrivateStateThreadIsValid ())
3817 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
3820 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3822 log->Printf ("Went to stop the private state thread, but it was already invalid.");
3827 Process::ControlPrivateStateThread (uint32_t signal)
3829 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3831 assert (signal == eBroadcastInternalStateControlStop ||
3832 signal == eBroadcastInternalStateControlPause ||
3833 signal == eBroadcastInternalStateControlResume);
3836 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
3838 // Signal the private state thread. First we should copy this is case the
3839 // thread starts exiting since the private state thread will NULL this out
3841 const lldb::thread_t private_state_thread = m_private_state_thread;
3842 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
3844 TimeValue timeout_time;
3847 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3849 timeout_time = TimeValue::Now();
3850 timeout_time.OffsetWithSeconds(2);
3852 log->Printf ("Sending control event of type: %d.", signal);
3853 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3854 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3856 if (signal == eBroadcastInternalStateControlStop)
3861 Host::ThreadCancel (private_state_thread, &error);
3863 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3868 log->Printf ("The control event killed the private state thread without having to cancel.");
3871 thread_result_t result = NULL;
3872 Host::ThreadJoin (private_state_thread, &result, NULL);
3873 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
3879 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3884 Process::SendAsyncInterrupt ()
3886 if (PrivateStateThreadIsValid())
3887 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3889 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3893 Process::HandlePrivateEvent (EventSP &event_sp)
3895 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3896 m_resume_requested = false;
3898 m_currently_handling_event.SetValue(true, eBroadcastNever);
3900 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3902 // First check to see if anybody wants a shot at this event:
3903 if (m_next_event_action_ap.get() != NULL)
3905 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
3907 log->Printf ("Ran next event action, result was %d.", action_result);
3909 switch (action_result)
3911 case NextEventAction::eEventActionSuccess:
3912 SetNextEventAction(NULL);
3915 case NextEventAction::eEventActionRetry:
3918 case NextEventAction::eEventActionExit:
3919 // Handle Exiting Here. If we already got an exited event,
3920 // we should just propagate it. Otherwise, swallow this event,
3921 // and set our state to exit so the next event will kill us.
3922 if (new_state != eStateExited)
3924 // FIXME: should cons up an exited event, and discard this one.
3925 SetExitStatus(0, m_next_event_action_ap->GetExitString());
3926 m_currently_handling_event.SetValue(false, eBroadcastAlways);
3927 SetNextEventAction(NULL);
3930 SetNextEventAction(NULL);
3935 // See if we should broadcast this state to external clients?
3936 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
3938 if (should_broadcast)
3942 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
3945 StateAsCString(new_state),
3946 StateAsCString (GetState ()),
3947 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
3949 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3950 if (StateIsRunningState (new_state))
3951 PushProcessInputReader ();
3952 else if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
3953 PopProcessInputReader ();
3955 BroadcastEvent (event_sp);
3961 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
3964 StateAsCString(new_state),
3965 StateAsCString (GetState ()));
3968 m_currently_handling_event.SetValue(false, eBroadcastAlways);
3972 Process::PrivateStateThread (void *arg)
3974 Process *proc = static_cast<Process*> (arg);
3975 void *result = proc->RunPrivateStateThread ();
3980 Process::RunPrivateStateThread ()
3982 bool control_only = true;
3983 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3985 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3987 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
3989 bool exit_now = false;
3993 WaitForEventsPrivate (NULL, event_sp, control_only);
3994 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3997 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
3999 switch (event_sp->GetType())
4001 case eBroadcastInternalStateControlStop:
4003 break; // doing any internal state managment below
4005 case eBroadcastInternalStateControlPause:
4006 control_only = true;
4009 case eBroadcastInternalStateControlResume:
4010 control_only = false;
4014 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4017 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4019 if (m_public_state.GetValue() == eStateAttaching)
4022 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
4023 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4028 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
4034 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4036 if (internal_state != eStateInvalid)
4038 if (m_clear_thread_plans_on_stop &&
4039 StateIsStoppedState(internal_state, true))
4041 m_clear_thread_plans_on_stop = false;
4042 m_thread_list.DiscardThreadPlans();
4044 HandlePrivateEvent (event_sp);
4047 if (internal_state == eStateInvalid ||
4048 internal_state == eStateExited ||
4049 internal_state == eStateDetached )
4052 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
4058 // Verify log is still enabled before attempting to write to it...
4060 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
4062 m_public_run_lock.SetStopped();
4063 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4064 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
4068 //------------------------------------------------------------------
4069 // Process Event Data
4070 //------------------------------------------------------------------
4072 Process::ProcessEventData::ProcessEventData () :
4075 m_state (eStateInvalid),
4076 m_restarted (false),
4078 m_interrupted (false)
4082 Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4084 m_process_sp (process_sp),
4086 m_restarted (false),
4088 m_interrupted (false)
4092 Process::ProcessEventData::~ProcessEventData()
4097 Process::ProcessEventData::GetFlavorString ()
4099 static ConstString g_flavor ("Process::ProcessEventData");
4104 Process::ProcessEventData::GetFlavor () const
4106 return ProcessEventData::GetFlavorString ();
4110 Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4112 // This function gets called twice for each event, once when the event gets pulled
4113 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4114 // the public event queue, then other times when we're pretending that this is where we stopped at the
4115 // end of expression evaluation. m_update_state is used to distinguish these
4116 // three cases; it is 0 when we're just pulling it off for private handling,
4117 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
4118 if (m_update_state != 1)
4121 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4123 // If we're stopped and haven't restarted, then do the breakpoint commands here:
4124 if (m_state == eStateStopped && ! m_restarted)
4126 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
4127 uint32_t num_threads = curr_thread_list.GetSize();
4130 // The actions might change one of the thread's stop_info's opinions about whether we should
4131 // stop the process, so we need to query that as we go.
4133 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4134 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4135 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4136 // to also know if it has changed at all, so we make up a vector of the thread ID's and check what we get back
4137 // against this list & bag out if anything differs.
4138 std::vector<uint32_t> thread_index_array(num_threads);
4139 for (idx = 0; idx < num_threads; ++idx)
4140 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4142 // Use this to track whether we should continue from here. We will only continue the target running if
4143 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4144 // then it doesn't matter what the other threads say...
4146 bool still_should_stop = false;
4148 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4149 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4150 // thing to do is, and it's better to let the user decide than continue behind their backs.
4152 bool does_anybody_have_an_opinion = false;
4154 for (idx = 0; idx < num_threads; ++idx)
4156 curr_thread_list = m_process_sp->GetThreadList();
4157 if (curr_thread_list.GetSize() != num_threads)
4159 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
4161 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
4165 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4167 if (thread_sp->GetIndexID() != thread_index_array[idx])
4169 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
4171 log->Printf("The thread at position %u changed from %u to %u while processing event.",
4173 thread_index_array[idx],
4174 thread_sp->GetIndexID());
4178 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
4179 if (stop_info_sp && stop_info_sp->IsValid())
4181 does_anybody_have_an_opinion = true;
4182 bool this_thread_wants_to_stop;
4183 if (stop_info_sp->GetOverrideShouldStop())
4185 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4189 stop_info_sp->PerformAction(event_ptr);
4190 // The stop action might restart the target. If it does, then we want to mark that in the
4191 // event so that whoever is receiving it will know to wait for the running event and reflect
4192 // that state appropriately.
4193 // We also need to stop processing actions, since they aren't expecting the target to be running.
4195 // FIXME: we might have run.
4196 if (stop_info_sp->HasTargetRunSinceMe())
4198 SetRestarted (true);
4202 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4205 if (still_should_stop == false)
4206 still_should_stop = this_thread_wants_to_stop;
4211 if (!GetRestarted())
4213 if (!still_should_stop && does_anybody_have_an_opinion)
4215 // We've been asked to continue, so do that here.
4217 // Use the public resume method here, since this is just
4218 // extending a public resume.
4219 m_process_sp->PrivateResume();
4223 // If we didn't restart, run the Stop Hooks here:
4224 // They might also restart the target, so watch for that.
4225 m_process_sp->GetTarget().RunStopHooks();
4226 if (m_process_sp->GetPrivateState() == eStateRunning)
4234 Process::ProcessEventData::Dump (Stream *s) const
4237 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
4239 s->Printf("state = %s", StateAsCString(GetState()));
4242 const Process::ProcessEventData *
4243 Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4247 const EventData *event_data = event_ptr->GetData();
4248 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4249 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4255 Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4257 ProcessSP process_sp;
4258 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4260 process_sp = data->GetProcessSP();
4265 Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4267 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4269 return eStateInvalid;
4271 return data->GetState();
4275 Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4277 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4281 return data->GetRestarted();
4285 Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4287 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4289 data->SetRestarted(new_value);
4293 Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4295 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4297 return data->GetNumRestartedReasons();
4303 Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4305 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4307 return data->GetRestartedReasonAtIndex(idx);
4313 Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4315 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4317 data->AddRestartedReason(reason);
4321 Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4323 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4327 return data->GetInterrupted ();
4331 Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4333 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4335 data->SetInterrupted(new_value);
4339 Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4341 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4344 data->SetUpdateStateOnRemoval();
4351 Process::CalculateTarget ()
4353 return m_target.shared_from_this();
4357 Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
4359 exe_ctx.SetTargetPtr (&m_target);
4360 exe_ctx.SetProcessPtr (this);
4361 exe_ctx.SetThreadPtr(NULL);
4362 exe_ctx.SetFramePtr (NULL);
4366 //Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4372 //Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4374 // return Host::GetArchSpecForExistingProcess (pid);
4378 //Process::GetArchSpecForExistingProcess (const char *process_name)
4380 // return Host::GetArchSpecForExistingProcess (process_name);
4384 Process::AppendSTDOUT (const char * s, size_t len)
4386 Mutex::Locker locker (m_stdio_communication_mutex);
4387 m_stdout_data.append (s, len);
4388 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
4392 Process::AppendSTDERR (const char * s, size_t len)
4394 Mutex::Locker locker (m_stdio_communication_mutex);
4395 m_stderr_data.append (s, len);
4396 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
4400 Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
4402 Mutex::Locker locker (m_profile_data_comm_mutex);
4403 m_profile_data.push_back(one_profile_data);
4404 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4408 Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4410 Mutex::Locker locker(m_profile_data_comm_mutex);
4411 if (m_profile_data.empty())
4414 std::string &one_profile_data = m_profile_data.front();
4415 size_t bytes_available = one_profile_data.size();
4416 if (bytes_available > 0)
4418 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4420 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
4421 if (bytes_available > buf_size)
4423 memcpy(buf, one_profile_data.c_str(), buf_size);
4424 one_profile_data.erase(0, buf_size);
4425 bytes_available = buf_size;
4429 memcpy(buf, one_profile_data.c_str(), bytes_available);
4430 m_profile_data.erase(m_profile_data.begin());
4433 return bytes_available;
4437 //------------------------------------------------------------------
4439 //------------------------------------------------------------------
4442 Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4444 Mutex::Locker locker(m_stdio_communication_mutex);
4445 size_t bytes_available = m_stdout_data.size();
4446 if (bytes_available > 0)
4448 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4450 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
4451 if (bytes_available > buf_size)
4453 memcpy(buf, m_stdout_data.c_str(), buf_size);
4454 m_stdout_data.erase(0, buf_size);
4455 bytes_available = buf_size;
4459 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4460 m_stdout_data.clear();
4463 return bytes_available;
4468 Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4470 Mutex::Locker locker(m_stdio_communication_mutex);
4471 size_t bytes_available = m_stderr_data.size();
4472 if (bytes_available > 0)
4474 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4476 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
4477 if (bytes_available > buf_size)
4479 memcpy(buf, m_stderr_data.c_str(), buf_size);
4480 m_stderr_data.erase(0, buf_size);
4481 bytes_available = buf_size;
4485 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4486 m_stderr_data.clear();
4489 return bytes_available;
4493 Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4495 Process *process = (Process *) baton;
4496 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4500 Process::ProcessInputReaderCallback (void *baton,
4501 InputReader &reader,
4502 lldb::InputReaderAction notification,
4506 Process *process = (Process *) baton;
4508 switch (notification)
4510 case eInputReaderActivate:
4513 case eInputReaderDeactivate:
4516 case eInputReaderReactivate:
4519 case eInputReaderAsynchronousOutputWritten:
4522 case eInputReaderGotToken:
4525 process->PutSTDIN (bytes, bytes_len, error);
4529 case eInputReaderInterrupt:
4530 process->SendAsyncInterrupt();
4533 case eInputReaderEndOfFile:
4534 process->AppendSTDOUT ("^D", 2);
4537 case eInputReaderDone:
4546 Process::ResetProcessInputReader ()
4548 m_process_input_reader.reset();
4552 Process::SetSTDIOFileDescriptor (int file_descriptor)
4554 // First set up the Read Thread for reading/handling process I/O
4556 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4560 m_stdio_communication.SetConnection (conn_ap.release());
4561 if (m_stdio_communication.IsConnected())
4563 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4564 m_stdio_communication.StartReadThread();
4566 // Now read thread is set up, set up input reader.
4568 if (!m_process_input_reader.get())
4570 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4571 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4573 eInputReaderGranularityByte,
4579 m_process_input_reader.reset();
4586 Process::PushProcessInputReader ()
4588 if (m_process_input_reader && !m_process_input_reader->IsActive())
4589 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4593 Process::PopProcessInputReader ()
4595 if (m_process_input_reader && m_process_input_reader->IsActive())
4596 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4599 // The process needs to know about installed plug-ins
4601 Process::SettingsInitialize ()
4603 // static std::vector<OptionEnumValueElement> g_plugins;
4606 // const char *name;
4607 // OptionEnumValueElement option_enum;
4608 // while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4612 // option_enum.value = i;
4613 // option_enum.string_value = name;
4614 // option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4615 // g_plugins.push_back (option_enum);
4619 // option_enum.value = 0;
4620 // option_enum.string_value = NULL;
4621 // option_enum.usage = NULL;
4622 // g_plugins.push_back (option_enum);
4624 // for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4626 // if (::strcmp (name, "plugin") == 0)
4628 // SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4633 Thread::SettingsInitialize ();
4637 Process::SettingsTerminate ()
4639 Thread::SettingsTerminate ();
4643 Process::RunThreadPlan (ExecutionContext &exe_ctx,
4644 lldb::ThreadPlanSP &thread_plan_sp,
4647 bool unwind_on_error,
4648 bool ignore_breakpoints,
4649 uint32_t timeout_usec,
4652 ExecutionResults return_value = eExecutionSetupError;
4654 if (thread_plan_sp.get() == NULL)
4656 errors.Printf("RunThreadPlan called with empty thread plan.");
4657 return eExecutionSetupError;
4660 if (!thread_plan_sp->ValidatePlan(NULL))
4662 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4663 return eExecutionSetupError;
4666 if (exe_ctx.GetProcessPtr() != this)
4668 errors.Printf("RunThreadPlan called on wrong process.");
4669 return eExecutionSetupError;
4672 Thread *thread = exe_ctx.GetThreadPtr();
4675 errors.Printf("RunThreadPlan called with invalid thread.");
4676 return eExecutionSetupError;
4679 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4680 // For that to be true the plan can't be private - since private plans suppress themselves in the
4681 // GetCompletedPlan call.
4683 bool orig_plan_private = thread_plan_sp->GetPrivate();
4684 thread_plan_sp->SetPrivate(false);
4686 if (m_private_state.GetValue() != eStateStopped)
4688 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
4689 return eExecutionSetupError;
4692 // Save the thread & frame from the exe_ctx for restoration after we run
4693 const uint32_t thread_idx_id = thread->GetIndexID();
4694 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4695 if (!selected_frame_sp)
4697 thread->SetSelectedFrame(0);
4698 selected_frame_sp = thread->GetSelectedFrame();
4699 if (!selected_frame_sp)
4701 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
4702 return eExecutionSetupError;
4706 StackID ctx_frame_id = selected_frame_sp->GetStackID();
4708 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4709 // so we should arrange to reset them as well.
4711 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
4713 uint32_t selected_tid;
4714 StackID selected_stack_id;
4715 if (selected_thread_sp)
4717 selected_tid = selected_thread_sp->GetIndexID();
4718 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4722 selected_tid = LLDB_INVALID_THREAD_ID;
4725 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
4726 lldb::StateType old_state;
4727 lldb::ThreadPlanSP stopper_base_plan_sp;
4729 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
4730 if (Host::GetCurrentThread() == m_private_state_thread)
4732 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4733 // we are the thread that is generating public events.
4734 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
4735 // we are fielding public events here.
4737 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
4740 backup_private_state_thread = m_private_state_thread;
4742 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4743 // returning control here.
4744 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4745 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4746 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4747 // do just what we want.
4748 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4749 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4750 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4751 old_state = m_public_state.GetValue();
4752 m_public_state.SetValueNoLock(eStateStopped);
4754 // Now spin up the private state thread:
4755 StartPrivateStateThread(true);
4758 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
4760 Listener listener("lldb.process.listener.run-thread-plan");
4762 lldb::EventSP event_to_broadcast_sp;
4765 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4766 // restored on exit to the function.
4768 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4769 // is put into event_to_broadcast_sp for rebroadcasting.
4771 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
4776 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4777 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
4778 thread->GetIndexID(),
4784 lldb::EventSP event_sp;
4785 lldb::StateType stop_state = lldb::eStateInvalid;
4787 TimeValue* timeout_ptr = NULL;
4788 TimeValue real_timeout;
4790 bool before_first_timeout = true; // This is set to false the first time that we have to halt the target.
4791 bool do_resume = true;
4792 bool handle_running_event = true;
4793 const uint64_t default_one_thread_timeout_usec = 250000;
4795 // This is just for accounting:
4796 uint32_t num_resumes = 0;
4798 TimeValue one_thread_timeout = TimeValue::Now();
4799 TimeValue final_timeout = one_thread_timeout;
4803 // If we are running all threads then we take half the time to run all threads, bounded by
4805 if (timeout_usec == 0)
4806 one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
4809 uint64_t computed_timeout = timeout_usec / 2;
4810 if (computed_timeout > default_one_thread_timeout_usec)
4811 computed_timeout = default_one_thread_timeout_usec;
4812 one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
4814 final_timeout.OffsetWithMicroSeconds (timeout_usec);
4818 if (timeout_usec != 0)
4819 final_timeout.OffsetWithMicroSeconds(timeout_usec);
4822 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4823 // So don't call return anywhere within it.
4827 // We usually want to resume the process if we get to the top of the loop.
4828 // The only exception is if we get two running events with no intervening
4829 // stop, which can happen, we will just wait for then next stop event.
4831 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
4833 handle_running_event,
4834 before_first_timeout);
4836 if (do_resume || handle_running_event)
4838 // Do the initial resume and wait for the running event before going further.
4843 Error resume_error = PrivateResume ();
4844 if (!resume_error.Success())
4846 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
4848 resume_error.AsCString());
4849 return_value = eExecutionSetupError;
4854 TimeValue resume_timeout = TimeValue::Now();
4855 resume_timeout.OffsetWithMicroSeconds(500000);
4857 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
4861 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
4864 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
4865 return_value = eExecutionSetupError;
4869 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4871 if (stop_state != eStateRunning)
4873 bool restarted = false;
4875 if (stop_state == eStateStopped)
4877 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
4879 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4880 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
4882 StateAsCString(stop_state),
4885 handle_running_event);
4890 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
4891 // event here. But if I do, the best thing is to Halt and then get out of here.
4895 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4896 StateAsCString(stop_state));
4897 return_value = eExecutionSetupError;
4902 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4903 // We need to call the function synchronously, so spin waiting for it to return.
4904 // If we get interrupted while executing, we're going to lose our context, and
4905 // won't be able to gather the result at this point.
4906 // We set the timeout AFTER the resume, since the resume takes some time and we
4907 // don't want to charge that to the timeout.
4912 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
4915 if (before_first_timeout)
4918 timeout_ptr = &one_thread_timeout;
4921 if (timeout_usec == 0)
4924 timeout_ptr = &final_timeout;
4929 if (timeout_usec == 0)
4932 timeout_ptr = &final_timeout;
4936 handle_running_event = true;
4938 // Now wait for the process to stop again:
4945 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
4946 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
4947 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
4951 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4955 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4961 bool keep_going = false;
4962 if (event_sp->GetType() == eBroadcastBitInterrupt)
4965 return_value = eExecutionInterrupted;
4966 errors.Printf ("Execution halted by user interrupt.");
4968 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
4973 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4975 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4979 case lldb::eStateStopped:
4981 // We stopped, figure out what we are going to do now.
4982 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4985 // Ooh, our thread has vanished. Unlikely that this was successful execution...
4987 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4988 return_value = eExecutionInterrupted;
4992 // If we were restarted, we just need to go back up to fetch another event.
4993 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4997 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5001 handle_running_event = true;
5007 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5008 StopReason stop_reason = eStopReasonInvalid;
5010 stop_reason = stop_info_sp->GetStopReason();
5013 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5014 // it is OUR plan that is complete?
5015 if (stop_reason == eStopReasonPlanComplete)
5018 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5019 // Now mark this plan as private so it doesn't get reported as the stop reason
5020 // after this point.
5022 thread_plan_sp->SetPrivate (orig_plan_private);
5023 return_value = eExecutionCompleted;
5027 // Something restarted the target, so just wait for it to stop for real.
5028 if (stop_reason == eStopReasonBreakpoint)
5031 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
5032 return_value = eExecutionHitBreakpoint;
5033 if (!ignore_breakpoints)
5035 event_to_broadcast_sp = event_sp;
5041 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
5042 if (!unwind_on_error)
5043 event_to_broadcast_sp = event_sp;
5044 return_value = eExecutionInterrupted;
5052 case lldb::eStateRunning:
5053 // This shouldn't really happen, but sometimes we do get two running events without an
5054 // intervening stop, and in that case we should just go back to waiting for the stop.
5057 handle_running_event = false;
5062 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
5064 if (stop_state == eStateExited)
5065 event_to_broadcast_sp = event_sp;
5067 errors.Printf ("Execution stopped with unexpected state.\n");
5068 return_value = eExecutionInterrupted;
5081 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
5082 return_value = eExecutionInterrupted;
5088 // If we didn't get an event that means we've timed out...
5089 // We will interrupt the process here. Depending on what we were asked to do we will
5090 // either exit, or try with all threads running for the same timeout.
5095 uint64_t remaining_time = final_timeout - TimeValue::Now();
5096 if (before_first_timeout)
5097 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
5098 "running till for %" PRId64 " usec with all threads enabled.",
5101 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
5102 "and timeout: %d timed out, abandoning execution.",
5106 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
5107 "abandoning execution.",
5111 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5112 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5113 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5114 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5115 // stopped event. That's what this while loop does.
5117 bool back_to_top = true;
5118 uint32_t try_halt_again = 0;
5119 bool do_halt = true;
5120 const uint32_t num_retries = 5;
5121 while (try_halt_again < num_retries)
5127 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5128 halt_error = Halt();
5130 if (halt_error.Success())
5133 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
5135 real_timeout = TimeValue::Now();
5136 real_timeout.OffsetWithMicroSeconds(500000);
5138 got_event = listener.WaitForEvent(&real_timeout, event_sp);
5142 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5145 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5146 if (stop_state == lldb::eStateStopped
5147 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5148 log->PutCString (" Event was the Halt interruption event.");
5151 if (stop_state == lldb::eStateStopped)
5153 // Between the time we initiated the Halt and the time we delivered it, the process could have
5154 // already finished its job. Check that here:
5156 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5159 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5160 "Exiting wait loop.");
5161 return_value = eExecutionCompleted;
5162 back_to_top = false;
5166 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5169 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5170 "Exiting wait loop.");
5179 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5180 return_value = eExecutionInterrupted;
5181 back_to_top = false;
5185 if (before_first_timeout)
5187 // Set all the other threads to run, and return to the top of the loop, which will continue;
5188 before_first_timeout = false;
5189 thread_plan_sp->SetStopOthers (false);
5191 log->PutCString ("Process::RunThreadPlan(): about to resume.");
5198 // Running all threads failed, so return Interrupted.
5200 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5201 return_value = eExecutionInterrupted;
5202 back_to_top = false;
5209 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5210 "I'm getting out of here passing Interrupted.");
5211 return_value = eExecutionInterrupted;
5212 back_to_top = false;
5223 if (!back_to_top || try_halt_again > num_retries)
5230 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5231 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5233 StopPrivateStateThread();
5235 m_private_state_thread = backup_private_state_thread;
5236 if (stopper_base_plan_sp)
5238 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5240 m_public_state.SetValueNoLock(old_state);
5244 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5246 // 1) The execution successfully completed
5247 // 2) We hit a breakpoint, and ignore_breakpoints was true
5248 // 3) We got some other error, and discard_on_error was true
5249 bool should_unwind = (return_value == eExecutionInterrupted && unwind_on_error)
5250 || (return_value == eExecutionHitBreakpoint && ignore_breakpoints);
5252 if (return_value == eExecutionCompleted
5255 thread_plan_sp->RestoreThreadState();
5258 // Now do some processing on the results of the run:
5259 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
5265 event_sp->Dump (&s);
5268 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5273 const char *event_explanation = NULL;
5279 event_explanation = "<no event>";
5282 else if (event_sp->GetType() == eBroadcastBitInterrupt)
5284 event_explanation = "<user interrupt>";
5289 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5293 event_explanation = "<no event data>";
5297 Process *process = event_data->GetProcessSP().get();
5301 event_explanation = "<no process>";
5305 ThreadList &thread_list = process->GetThreadList();
5307 uint32_t num_threads = thread_list.GetSize();
5308 uint32_t thread_index;
5310 ts.Printf("<%u threads> ", num_threads);
5312 for (thread_index = 0;
5313 thread_index < num_threads;
5316 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5324 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5325 RegisterContext *register_context = thread->GetRegisterContext().get();
5327 if (register_context)
5328 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5330 ts.Printf("[ip unknown] ");
5332 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5335 const char *stop_desc = stop_info_sp->GetDescription();
5337 ts.PutCString (stop_desc);
5342 event_explanation = ts.GetData();
5346 if (event_explanation)
5347 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
5349 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5352 if (should_unwind && thread_plan_sp)
5355 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5356 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5357 thread_plan_sp->SetPrivate (orig_plan_private);
5362 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
5365 else if (return_value == eExecutionSetupError)
5368 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5370 if (unwind_on_error && thread_plan_sp)
5372 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5373 thread_plan_sp->SetPrivate (orig_plan_private);
5378 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5381 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5382 return_value = eExecutionCompleted;
5384 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5387 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5388 return_value = eExecutionDiscarded;
5393 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
5394 if (unwind_on_error && thread_plan_sp)
5397 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
5398 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5399 thread_plan_sp->SetPrivate (orig_plan_private);
5404 // Thread we ran the function in may have gone away because we ran the target
5405 // Check that it's still there, and if it is put it back in the context. Also restore the
5406 // frame in the context if it is still present.
5407 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5410 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5413 // Also restore the current process'es selected frame & thread, since this function calling may
5414 // be done behind the user's back.
5416 if (selected_tid != LLDB_INVALID_THREAD_ID)
5418 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5420 // We were able to restore the selected thread, now restore the frame:
5421 Mutex::Locker lock(GetThreadList().GetMutex());
5422 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
5424 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
5429 // If the process exited during the run of the thread plan, notify everyone.
5431 if (event_to_broadcast_sp)
5434 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5435 BroadcastEvent(event_to_broadcast_sp);
5438 return return_value;
5442 Process::ExecutionResultAsCString (ExecutionResults result)
5444 const char *result_name;
5448 case eExecutionCompleted:
5449 result_name = "eExecutionCompleted";
5451 case eExecutionDiscarded:
5452 result_name = "eExecutionDiscarded";
5454 case eExecutionInterrupted:
5455 result_name = "eExecutionInterrupted";
5457 case eExecutionHitBreakpoint:
5458 result_name = "eExecutionHitBreakpoint";
5460 case eExecutionSetupError:
5461 result_name = "eExecutionSetupError";
5463 case eExecutionTimedOut:
5464 result_name = "eExecutionTimedOut";
5471 Process::GetStatus (Stream &strm)
5473 const StateType state = GetState();
5474 if (StateIsStoppedState(state, false))
5476 if (state == eStateExited)
5478 int exit_status = GetExitStatus();
5479 const char *exit_description = GetExitDescription();
5480 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5484 exit_description ? exit_description : "");
5488 if (state == eStateConnected)
5489 strm.Printf ("Connected to remote target.\n");
5491 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
5496 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
5501 Process::GetThreadStatus (Stream &strm,
5502 bool only_threads_with_stop_reason,
5503 uint32_t start_frame,
5504 uint32_t num_frames,
5505 uint32_t num_frames_with_source)
5507 size_t num_thread_infos_dumped = 0;
5509 Mutex::Locker locker (GetThreadList().GetMutex());
5510 const size_t num_threads = GetThreadList().GetSize();
5511 for (uint32_t i = 0; i < num_threads; i++)
5513 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5516 if (only_threads_with_stop_reason)
5518 StopInfoSP stop_info_sp = thread->GetStopInfo();
5519 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
5522 thread->GetStatus (strm,
5525 num_frames_with_source);
5526 ++num_thread_infos_dumped;
5529 return num_thread_infos_dumped;
5533 Process::AddInvalidMemoryRegion (const LoadRange ®ion)
5535 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5539 Process::RemoveInvalidMemoryRange (const LoadRange ®ion)
5541 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5545 Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5547 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5551 Process::RunPreResumeActions ()
5554 while (!m_pre_resume_actions.empty())
5556 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5557 m_pre_resume_actions.pop_back();
5558 bool this_result = action.callback (action.baton);
5559 if (result == true) result = this_result;
5565 Process::ClearPreResumeActions ()
5567 m_pre_resume_actions.clear();
5573 m_thread_list.Flush();
5579 Target &target = GetTarget();
5580 target.CleanupProcess ();
5581 ModuleList unloaded_modules (target.GetImages());
5582 target.ModulesDidUnload (unloaded_modules);
5583 target.GetSectionLoadList().Clear();
5584 m_dynamic_checkers_ap.reset();
5588 m_image_tokens.clear();
5589 m_allocated_memory_cache.Clear();
5590 m_language_runtimes.clear();
5591 m_thread_list.DiscardThreadPlans();
5592 m_memory_cache.Clear(true);