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/Log.h"
22 #include "lldb/Core/Module.h"
23 #include "lldb/Symbol/Symbol.h"
24 #include "lldb/Core/PluginManager.h"
25 #include "lldb/Core/State.h"
26 #include "lldb/Core/StreamFile.h"
27 #include "lldb/Expression/ClangUserExpression.h"
28 #include "lldb/Interpreter/CommandInterpreter.h"
29 #include "lldb/Host/Host.h"
30 #include "lldb/Host/Terminal.h"
31 #include "lldb/Target/ABI.h"
32 #include "lldb/Target/DynamicLoader.h"
33 #include "lldb/Target/OperatingSystem.h"
34 #include "lldb/Target/LanguageRuntime.h"
35 #include "lldb/Target/CPPLanguageRuntime.h"
36 #include "lldb/Target/ObjCLanguageRuntime.h"
37 #include "lldb/Target/Platform.h"
38 #include "lldb/Target/RegisterContext.h"
39 #include "lldb/Target/StopInfo.h"
40 #include "lldb/Target/SystemRuntime.h"
41 #include "lldb/Target/Target.h"
42 #include "lldb/Target/TargetList.h"
43 #include "lldb/Target/Thread.h"
44 #include "lldb/Target/ThreadPlan.h"
45 #include "lldb/Target/ThreadPlanBase.h"
46 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
48 #ifndef LLDB_DISABLE_POSIX
53 using namespace lldb_private;
56 // Comment out line below to disable memory caching, overriding the process setting
57 // target.process.disable-memory-cache
58 #define ENABLE_MEMORY_CACHING
60 #ifdef ENABLE_MEMORY_CACHING
61 #define DISABLE_MEM_CACHE_DEFAULT false
63 #define DISABLE_MEM_CACHE_DEFAULT true
66 class ProcessOptionValueProperties : public OptionValueProperties
69 ProcessOptionValueProperties (const ConstString &name) :
70 OptionValueProperties (name)
74 // This constructor is used when creating ProcessOptionValueProperties when it
75 // is part of a new lldb_private::Process instance. It will copy all current
76 // global property values as needed
77 ProcessOptionValueProperties (ProcessProperties *global_properties) :
78 OptionValueProperties(*global_properties->GetValueProperties())
82 virtual const Property *
83 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
85 // When gettings the value for a key from the process options, we will always
86 // try and grab the setting from the current process if there is one. Else we just
87 // use the one from this instance.
90 Process *process = exe_ctx->GetProcessPtr();
93 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
94 if (this != instance_properties)
95 return instance_properties->ProtectedGetPropertyAtIndex (idx);
98 return ProtectedGetPropertyAtIndex (idx);
102 static PropertyDefinition
105 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." },
106 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
107 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
108 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
109 { "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." },
110 { "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." },
111 { "stop-on-sharedlibrary-events" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, stop when a shared library is loaded or unloaded." },
112 { "detach-keeps-stopped" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, detach will attempt to keep the process stopped." },
113 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
117 ePropertyDisableMemCache,
118 ePropertyExtraStartCommand,
119 ePropertyIgnoreBreakpointsInExpressions,
120 ePropertyUnwindOnErrorInExpressions,
121 ePropertyPythonOSPluginPath,
122 ePropertyStopOnSharedLibraryEvents,
123 ePropertyDetachKeepsStopped
126 ProcessProperties::ProcessProperties (bool is_global) :
131 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
132 m_collection_sp->Initialize(g_properties);
133 m_collection_sp->AppendProperty(ConstString("thread"),
134 ConstString("Settings specific to threads."),
136 Thread::GetGlobalProperties()->GetValueProperties());
139 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
142 ProcessProperties::~ProcessProperties()
147 ProcessProperties::GetDisableMemoryCache() const
149 const uint32_t idx = ePropertyDisableMemCache;
150 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
154 ProcessProperties::GetExtraStartupCommands () const
157 const uint32_t idx = ePropertyExtraStartCommand;
158 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
163 ProcessProperties::SetExtraStartupCommands (const Args &args)
165 const uint32_t idx = ePropertyExtraStartCommand;
166 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
170 ProcessProperties::GetPythonOSPluginPath () const
172 const uint32_t idx = ePropertyPythonOSPluginPath;
173 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
177 ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
179 const uint32_t idx = ePropertyPythonOSPluginPath;
180 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
185 ProcessProperties::GetIgnoreBreakpointsInExpressions () const
187 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
188 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
192 ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
194 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
195 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
199 ProcessProperties::GetUnwindOnErrorInExpressions () const
201 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
202 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
206 ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
208 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
209 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
213 ProcessProperties::GetStopOnSharedLibraryEvents () const
215 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
216 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
220 ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
222 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
223 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
227 ProcessProperties::GetDetachKeepsStopped () const
229 const uint32_t idx = ePropertyDetachKeepsStopped;
230 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
234 ProcessProperties::SetDetachKeepsStopped (bool stop)
236 const uint32_t idx = ePropertyDetachKeepsStopped;
237 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
241 ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
244 if (m_pid != LLDB_INVALID_PROCESS_ID)
245 s.Printf (" pid = %" PRIu64 "\n", m_pid);
247 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
248 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
252 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
253 s.PutCString (" file = ");
254 m_executable.Dump(&s);
257 const uint32_t argc = m_arguments.GetArgumentCount();
260 for (uint32_t i=0; i<argc; i++)
262 const char *arg = m_arguments.GetArgumentAtIndex(i);
264 s.Printf (" arg[%u] = %s\n", i, arg);
266 s.Printf ("arg[%u] = %s\n", i, arg);
270 const uint32_t envc = m_environment.GetArgumentCount();
273 for (uint32_t i=0; i<envc; i++)
275 const char *env = m_environment.GetArgumentAtIndex(i);
277 s.Printf (" env[%u] = %s\n", i, env);
279 s.Printf ("env[%u] = %s\n", i, env);
283 if (m_arch.IsValid())
284 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
286 if (m_uid != UINT32_MAX)
288 cstr = platform->GetUserName (m_uid);
289 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
291 if (m_gid != UINT32_MAX)
293 cstr = platform->GetGroupName (m_gid);
294 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
296 if (m_euid != UINT32_MAX)
298 cstr = platform->GetUserName (m_euid);
299 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
301 if (m_egid != UINT32_MAX)
303 cstr = platform->GetGroupName (m_egid);
304 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
309 ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
312 if (show_args || verbose)
319 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
320 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
324 s.Printf ("PID PARENT USER ARCH %s\n", label);
325 s.PutCString ("====== ====== ========== ======= ============================\n");
330 ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
332 if (m_pid != LLDB_INVALID_PROCESS_ID)
335 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
340 cstr = platform->GetUserName (m_uid);
341 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
342 s.Printf ("%-10s ", cstr);
344 s.Printf ("%-10u ", m_uid);
346 cstr = platform->GetGroupName (m_gid);
347 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
348 s.Printf ("%-10s ", cstr);
350 s.Printf ("%-10u ", m_gid);
352 cstr = platform->GetUserName (m_euid);
353 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
354 s.Printf ("%-10s ", cstr);
356 s.Printf ("%-10u ", m_euid);
358 cstr = platform->GetGroupName (m_egid);
359 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
360 s.Printf ("%-10s ", cstr);
362 s.Printf ("%-10u ", m_egid);
363 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
367 s.Printf ("%-10s %-7d %s ",
368 platform->GetUserName (m_euid),
369 (int)m_arch.GetTriple().getArchName().size(),
370 m_arch.GetTriple().getArchName().data());
373 if (verbose || show_args)
375 const uint32_t argc = m_arguments.GetArgumentCount();
378 for (uint32_t i=0; i<argc; i++)
382 s.PutCString (m_arguments.GetArgumentAtIndex(i));
388 s.PutCString (GetName());
397 ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
399 m_arguments.SetArguments (argv);
401 // Is the first argument the executable?
402 if (first_arg_is_executable)
404 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
407 // Yes the first argument is an executable, set it as the executable
408 // in the launch options. Don't resolve the file path as the path
409 // could be a remote platform path
410 const bool resolve = false;
411 m_executable.SetFile(first_arg, resolve);
416 ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
418 // Copy all arguments
421 // Is the first argument the executable?
422 if (first_arg_is_executable)
424 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
427 // Yes the first argument is an executable, set it as the executable
428 // in the launch options. Don't resolve the file path as the path
429 // could be a remote platform path
430 const bool resolve = false;
431 m_executable.SetFile(first_arg, resolve);
437 ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
439 // If notthing was specified, then check the process for any default
440 // settings that were set with "settings set"
441 if (m_file_actions.empty())
443 if (m_flags.Test(eLaunchFlagDisableSTDIO))
445 AppendSuppressFileAction (STDIN_FILENO , true, false);
446 AppendSuppressFileAction (STDOUT_FILENO, false, true);
447 AppendSuppressFileAction (STDERR_FILENO, false, true);
451 // Check for any values that might have gotten set with any of:
452 // (lldb) settings set target.input-path
453 // (lldb) settings set target.output-path
454 // (lldb) settings set target.error-path
460 in_path = target->GetStandardInputPath();
461 out_path = target->GetStandardOutputPath();
462 err_path = target->GetStandardErrorPath();
465 if (in_path || out_path || err_path)
468 if (in_path && in_path.GetPath(path, sizeof(path)))
469 AppendOpenFileAction(STDIN_FILENO, path, true, false);
471 if (out_path && out_path.GetPath(path, sizeof(path)))
472 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
474 if (err_path && err_path.GetPath(path, sizeof(path)))
475 AppendOpenFileAction(STDERR_FILENO, path, false, true);
477 else if (default_to_use_pty)
479 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
481 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
482 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
483 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
484 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
493 ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
496 bool first_arg_is_full_shell_command,
501 if (GetFlags().Test (eLaunchFlagLaunchInShell))
503 const char *shell_executable = GetShell();
504 if (shell_executable)
506 char shell_resolved_path[PATH_MAX];
510 FileSpec shell_filespec (shell_executable, true);
512 if (!shell_filespec.Exists())
514 // Resolve the path in case we just got "bash", "sh" or "tcsh"
515 if (!shell_filespec.ResolveExecutableLocation ())
517 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
521 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
522 shell_executable = shell_resolved_path;
525 const char **argv = GetArguments().GetConstArgumentVector ();
526 if (argv == NULL || argv[0] == NULL)
528 Args shell_arguments;
529 std::string safe_arg;
530 shell_arguments.AppendArgument (shell_executable);
531 shell_arguments.AppendArgument ("-c");
532 StreamString shell_command;
535 // Add a modified PATH environment variable in case argv[0]
536 // is a relative path
537 const char *argv0 = argv[0];
538 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
540 // We have a relative path to our executable which may not work if
541 // we just try to run "a.out" (without it being converted to "./a.out")
542 const char *working_dir = GetWorkingDirectory();
543 // Be sure to put quotes around PATH's value in case any paths have spaces...
544 std::string new_path("PATH=\"");
545 const size_t empty_path_len = new_path.size();
547 if (working_dir && working_dir[0])
549 new_path += working_dir;
553 char current_working_dir[PATH_MAX];
554 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
558 const char *curr_path = getenv("PATH");
561 if (new_path.size() > empty_path_len)
563 new_path += curr_path;
566 shell_command.PutCString(new_path.c_str());
569 shell_command.PutCString ("exec");
571 // Only Apple supports /usr/bin/arch being able to specify the architecture
572 if (GetArchitecture().IsValid())
574 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
575 // Set the resume count to 2:
577 // 2 - stop in /usr/bin/arch
578 // 3 - then we will stop in our program
579 SetResumeCount(num_resumes + 1);
583 // Set the resume count to 1:
585 // 2 - then we will stop in our program
586 SetResumeCount(num_resumes);
590 if (first_arg_is_full_shell_command)
592 // There should only be one argument that is the shell command itself to be used as is
593 if (argv[0] && !argv[1])
594 shell_command.Printf("%s", argv[0]);
600 for (size_t i=0; argv[i] != NULL; ++i)
602 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
603 shell_command.Printf(" %s", arg);
606 shell_arguments.AppendArgument (shell_command.GetString().c_str());
607 m_executable.SetFile(shell_executable, false);
608 m_arguments = shell_arguments;
613 error.SetErrorString ("invalid shell path");
618 error.SetErrorString ("not launching in shell");
625 ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
627 if ((read || write) && fd >= 0 && path && path[0])
629 m_action = eFileActionOpen;
632 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
634 m_arg = O_NOCTTY | O_RDONLY;
636 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
637 m_path.assign (path);
648 ProcessLaunchInfo::FileAction::Close (int fd)
653 m_action = eFileActionClose;
661 ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
664 if (fd >= 0 && dup_fd >= 0)
666 m_action = eFileActionDuplicate;
675 #ifndef LLDB_DISABLE_POSIX
677 ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (void *_file_actions,
678 const FileAction *info,
685 posix_spawn_file_actions_t *file_actions = reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions);
687 switch (info->m_action)
689 case eFileActionNone:
693 case eFileActionClose:
694 if (info->m_fd == -1)
695 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
698 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
700 if (log && (error.Fail() || log))
701 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
702 file_actions, info->m_fd);
706 case eFileActionDuplicate:
707 if (info->m_fd == -1)
708 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
709 else if (info->m_arg == -1)
710 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
713 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
715 if (log && (error.Fail() || log))
716 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
717 file_actions, info->m_fd, info->m_arg);
721 case eFileActionOpen:
722 if (info->m_fd == -1)
723 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
726 int oflag = info->m_arg;
733 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
735 info->m_path.c_str(),
739 if (error.Fail() || log)
741 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
742 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
746 return error.Success();
751 ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
754 const int short_option = m_getopt_table[option_idx].val;
756 switch (short_option)
758 case 's': // Stop at program entry point
759 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
762 case 'i': // STDIN for read only
764 ProcessLaunchInfo::FileAction action;
765 if (action.Open (STDIN_FILENO, option_arg, true, false))
766 launch_info.AppendFileAction (action);
770 case 'o': // Open STDOUT for write only
772 ProcessLaunchInfo::FileAction action;
773 if (action.Open (STDOUT_FILENO, option_arg, false, true))
774 launch_info.AppendFileAction (action);
778 case 'e': // STDERR for write only
780 ProcessLaunchInfo::FileAction action;
781 if (action.Open (STDERR_FILENO, option_arg, false, true))
782 launch_info.AppendFileAction (action);
787 case 'p': // Process plug-in name
788 launch_info.SetProcessPluginName (option_arg);
791 case 'n': // Disable STDIO
793 ProcessLaunchInfo::FileAction action;
794 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
795 launch_info.AppendFileAction (action);
796 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
797 launch_info.AppendFileAction (action);
798 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
799 launch_info.AppendFileAction (action);
804 launch_info.SetWorkingDirectory (option_arg);
807 case 't': // Open process in new terminal window
808 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
812 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
813 launch_info.GetArchitecture().SetTriple (option_arg);
817 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
821 if (option_arg && option_arg[0])
822 launch_info.SetShell (option_arg);
824 launch_info.SetShell (LLDB_DEFAULT_SHELL);
828 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
832 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
840 ProcessLaunchCommandOptions::g_option_table[] =
842 { LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."},
843 { LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
844 { LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
845 { LLDB_OPT_SET_ALL, false, "working-dir", 'w', OptionParser::eRequiredArgument, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
846 { LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
847 { LLDB_OPT_SET_ALL, false, "environment", 'v', OptionParser::eRequiredArgument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value string (--environment NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
848 { LLDB_OPT_SET_ALL, false, "shell", 'c', OptionParser::eOptionalArgument, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
850 { LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
851 { LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
852 { LLDB_OPT_SET_1 , false, "stderr", 'e', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
854 { LLDB_OPT_SET_2 , false, "tty", 't', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
856 { LLDB_OPT_SET_3 , false, "no-stdio", 'n', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."},
858 { 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
864 ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
866 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
868 const char *match_name = m_match_info.GetName();
872 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
876 ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
878 if (!NameMatches (proc_info.GetName()))
881 if (m_match_info.ProcessIDIsValid() &&
882 m_match_info.GetProcessID() != proc_info.GetProcessID())
885 if (m_match_info.ParentProcessIDIsValid() &&
886 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
889 if (m_match_info.UserIDIsValid () &&
890 m_match_info.GetUserID() != proc_info.GetUserID())
893 if (m_match_info.GroupIDIsValid () &&
894 m_match_info.GetGroupID() != proc_info.GetGroupID())
897 if (m_match_info.EffectiveUserIDIsValid () &&
898 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
901 if (m_match_info.EffectiveGroupIDIsValid () &&
902 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
905 if (m_match_info.GetArchitecture().IsValid() &&
906 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
912 ProcessInstanceInfoMatch::MatchAllProcesses () const
914 if (m_name_match_type != eNameMatchIgnore)
917 if (m_match_info.ProcessIDIsValid())
920 if (m_match_info.ParentProcessIDIsValid())
923 if (m_match_info.UserIDIsValid ())
926 if (m_match_info.GroupIDIsValid ())
929 if (m_match_info.EffectiveUserIDIsValid ())
932 if (m_match_info.EffectiveGroupIDIsValid ())
935 if (m_match_info.GetArchitecture().IsValid())
938 if (m_match_all_users)
946 ProcessInstanceInfoMatch::Clear()
948 m_match_info.Clear();
949 m_name_match_type = eNameMatchIgnore;
950 m_match_all_users = false;
954 Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
956 static uint32_t g_process_unique_id = 0;
958 ProcessSP process_sp;
959 ProcessCreateInstance create_callback = NULL;
962 ConstString const_plugin_name(plugin_name);
963 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
966 process_sp = create_callback(target, listener, crash_file_path);
969 if (process_sp->CanDebug(target, true))
971 process_sp->m_process_unique_id = ++g_process_unique_id;
980 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
982 process_sp = create_callback(target, listener, crash_file_path);
985 if (process_sp->CanDebug(target, false))
987 process_sp->m_process_unique_id = ++g_process_unique_id;
999 Process::GetStaticBroadcasterClass ()
1001 static ConstString class_name ("lldb.process");
1005 //----------------------------------------------------------------------
1006 // Process constructor
1007 //----------------------------------------------------------------------
1008 Process::Process(Target &target, Listener &listener) :
1009 ProcessProperties (false),
1010 UserID (LLDB_INVALID_PROCESS_ID),
1011 Broadcaster (&(target.GetDebugger()), "lldb.process"),
1013 m_public_state (eStateUnloaded),
1014 m_private_state (eStateUnloaded),
1015 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
1016 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
1017 m_private_state_listener ("lldb.process.internal_state_listener"),
1018 m_private_state_control_wait(),
1019 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
1021 m_process_unique_id(0),
1022 m_thread_index_id (0),
1023 m_thread_id_to_index_id_map (),
1026 m_thread_mutex (Mutex::eMutexTypeRecursive),
1027 m_thread_list_real (this),
1028 m_thread_list (this),
1029 m_extended_thread_list (this),
1030 m_extended_thread_stop_id (0),
1031 m_queue_list (this),
1032 m_queue_list_stop_id (0),
1035 m_listener (listener),
1036 m_breakpoint_site_list (),
1037 m_dynamic_checkers_ap (),
1040 m_process_input_reader (),
1041 m_stdio_communication ("process.stdio"),
1042 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
1045 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1047 m_memory_cache (*this),
1048 m_allocated_memory_cache (*this),
1049 m_should_detach (false),
1050 m_next_event_action_ap(),
1051 m_public_run_lock (),
1052 m_private_run_lock (),
1053 m_currently_handling_event(false),
1054 m_finalize_called(false),
1055 m_clear_thread_plans_on_stop (false),
1056 m_force_next_event_delivery(false),
1057 m_last_broadcast_state (eStateInvalid),
1058 m_destroy_in_process (false),
1059 m_can_jit(eCanJITDontKnow)
1061 CheckInWithManager ();
1063 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
1065 log->Printf ("%p Process::Process()", this);
1067 SetEventName (eBroadcastBitStateChanged, "state-changed");
1068 SetEventName (eBroadcastBitInterrupt, "interrupt");
1069 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1070 SetEventName (eBroadcastBitSTDERR, "stderr-available");
1071 SetEventName (eBroadcastBitProfileData, "profile-data-available");
1073 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1074 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1075 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1077 listener.StartListeningForEvents (this,
1078 eBroadcastBitStateChanged |
1079 eBroadcastBitInterrupt |
1080 eBroadcastBitSTDOUT |
1081 eBroadcastBitSTDERR |
1082 eBroadcastBitProfileData);
1084 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
1085 eBroadcastBitStateChanged |
1086 eBroadcastBitInterrupt);
1088 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1089 eBroadcastInternalStateControlStop |
1090 eBroadcastInternalStateControlPause |
1091 eBroadcastInternalStateControlResume);
1094 //----------------------------------------------------------------------
1096 //----------------------------------------------------------------------
1099 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
1101 log->Printf ("%p Process::~Process()", this);
1102 StopPrivateStateThread();
1105 const ProcessPropertiesSP &
1106 Process::GetGlobalProperties()
1108 static ProcessPropertiesSP g_settings_sp;
1110 g_settings_sp.reset (new ProcessProperties (true));
1111 return g_settings_sp;
1117 switch (GetPrivateState())
1119 case eStateConnected:
1120 case eStateAttaching:
1121 case eStateLaunching:
1124 case eStateStepping:
1126 case eStateSuspended:
1127 if (GetShouldDetach())
1129 // FIXME: This will have to be a process setting:
1130 bool keep_stopped = false;
1131 Detach(keep_stopped);
1138 case eStateUnloaded:
1139 case eStateDetached:
1144 // Clear our broadcaster before we proceed with destroying
1145 Broadcaster::Clear();
1147 // Do any cleanup needed prior to being destructed... Subclasses
1148 // that override this method should call this superclass method as well.
1150 // We need to destroy the loader before the derived Process class gets destroyed
1151 // since it is very likely that undoing the loader will require access to the real process.
1152 m_dynamic_checkers_ap.reset();
1155 m_system_runtime_ap.reset();
1157 m_thread_list_real.Destroy();
1158 m_thread_list.Destroy();
1159 m_extended_thread_list.Destroy();
1160 m_queue_list.Clear();
1161 m_queue_list_stop_id = 0;
1162 std::vector<Notifications> empty_notifications;
1163 m_notifications.swap(empty_notifications);
1164 m_image_tokens.clear();
1165 m_memory_cache.Clear();
1166 m_allocated_memory_cache.Clear();
1167 m_language_runtimes.clear();
1168 m_next_event_action_ap.reset();
1169 //#ifdef LLDB_CONFIGURATION_DEBUG
1170 // StreamFile s(stdout, false);
1171 // EventSP event_sp;
1172 // while (m_private_state_listener.GetNextEvent(event_sp))
1174 // event_sp->Dump (&s);
1178 // We have to be very careful here as the m_private_state_listener might
1179 // contain events that have ProcessSP values in them which can keep this
1180 // process around forever. These events need to be cleared out.
1181 m_private_state_listener.Clear();
1182 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
1183 m_public_run_lock.SetStopped();
1184 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
1185 m_private_run_lock.SetStopped();
1186 m_finalize_called = true;
1190 Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1192 m_notifications.push_back(callbacks);
1193 if (callbacks.initialize != NULL)
1194 callbacks.initialize (callbacks.baton, this);
1198 Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1200 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1201 for (pos = m_notifications.begin(); pos != end; ++pos)
1203 if (pos->baton == callbacks.baton &&
1204 pos->initialize == callbacks.initialize &&
1205 pos->process_state_changed == callbacks.process_state_changed)
1207 m_notifications.erase(pos);
1215 Process::SynchronouslyNotifyStateChanged (StateType state)
1217 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1218 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1220 if (notification_pos->process_state_changed)
1221 notification_pos->process_state_changed (notification_pos->baton, this, state);
1225 // FIXME: We need to do some work on events before the general Listener sees them.
1226 // For instance if we are continuing from a breakpoint, we need to ensure that we do
1227 // the little "insert real insn, step & stop" trick. But we can't do that when the
1228 // event is delivered by the broadcaster - since that is done on the thread that is
1229 // waiting for new events, so if we needed more than one event for our handling, we would
1230 // stall. So instead we do it when we fetch the event off of the queue.
1234 Process::GetNextEvent (EventSP &event_sp)
1236 StateType state = eStateInvalid;
1238 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1239 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1246 Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always, Listener *hijack_listener)
1248 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1249 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1252 event_sp_ptr->reset();
1253 StateType state = GetState();
1254 // If we are exited or detached, we won't ever get back to any
1255 // other valid state...
1256 if (state == eStateDetached || state == eStateExited)
1259 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1261 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__, timeout);
1264 StateIsStoppedState(state, true) &&
1265 StateIsStoppedState(GetPrivateState(), true)) {
1267 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
1272 while (state != eStateInvalid)
1275 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
1276 if (event_sp_ptr && event_sp)
1277 *event_sp_ptr = event_sp;
1282 case eStateDetached:
1284 case eStateUnloaded:
1285 // We need to toggle the run lock as this won't get done in
1286 // SetPublicState() if the process is hijacked.
1287 if (hijack_listener)
1288 m_public_run_lock.SetStopped();
1291 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1295 // We need to toggle the run lock as this won't get done in
1296 // SetPublicState() if the process is hijacked.
1297 if (hijack_listener)
1298 m_public_run_lock.SetStopped();
1310 Process::WaitForState
1312 const TimeValue *timeout,
1313 const StateType *match_states,
1314 const uint32_t num_match_states
1319 StateType state = GetState();
1320 while (state != eStateInvalid)
1322 // If we are exited or detached, we won't ever get back to any
1323 // other valid state...
1324 if (state == eStateDetached || state == eStateExited)
1327 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
1329 for (i=0; i<num_match_states; ++i)
1331 if (match_states[i] == state)
1339 Process::HijackProcessEvents (Listener *listener)
1341 if (listener != NULL)
1343 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
1350 Process::RestoreProcessEvents ()
1352 RestoreBroadcaster();
1356 Process::HijackPrivateProcessEvents (Listener *listener)
1358 if (listener != NULL)
1360 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
1367 Process::RestorePrivateProcessEvents ()
1369 m_private_state_broadcaster.RestoreBroadcaster();
1373 Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
1375 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1378 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1380 Listener *listener = hijack_listener;
1381 if (listener == NULL)
1382 listener = &m_listener;
1384 StateType state = eStateInvalid;
1385 if (listener->WaitForEventForBroadcasterWithType (timeout,
1387 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1390 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1391 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1393 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1397 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1400 StateAsCString(state));
1405 Process::PeekAtStateChangedEvents ()
1407 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1410 log->Printf ("Process::%s...", __FUNCTION__);
1413 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1414 eBroadcastBitStateChanged);
1419 log->Printf ("Process::%s (event_ptr) => %s",
1421 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1425 log->Printf ("Process::%s no events found",
1433 Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1435 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1438 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1440 StateType state = eStateInvalid;
1441 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1442 &m_private_state_broadcaster,
1443 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1445 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1446 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1448 // This is a bit of a hack, but when we wait here we could very well return
1449 // to the command-line, and that could disable the log, which would render the
1450 // log we got above invalid.
1453 if (state == eStateInvalid)
1454 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1456 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1462 Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1464 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1467 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1470 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1472 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1476 Process::IsRunning () const
1478 return StateIsRunningState (m_public_state.GetValue());
1482 Process::GetExitStatus ()
1484 if (m_public_state.GetValue() == eStateExited)
1485 return m_exit_status;
1491 Process::GetExitDescription ()
1493 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1494 return m_exit_string.c_str();
1499 Process::SetExitStatus (int status, const char *cstr)
1501 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1503 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1506 cstr ? cstr : "NULL",
1509 // We were already in the exited state
1510 if (m_private_state.GetValue() == eStateExited)
1513 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
1517 m_exit_status = status;
1519 m_exit_string = cstr;
1521 m_exit_string.clear();
1525 SetPrivateState (eStateExited);
1526 CancelWatchForSTDIN (true);
1530 // This static callback can be used to watch for local child processes on
1531 // the current host. The the child process exits, the process will be
1532 // found in the global target list (we want to be completely sure that the
1533 // lldb_private::Process doesn't go away before we can deliver the signal.
1535 Process::SetProcessExitStatus (void *callback_baton,
1538 int signo, // Zero for no signal
1539 int exit_status // Exit value of process if signal is zero
1542 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1544 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
1553 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
1556 ProcessSP process_sp (target_sp->GetProcessSP());
1559 const char *signal_cstr = NULL;
1561 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1563 process_sp->SetExitStatus (exit_status, signal_cstr);
1573 Process::UpdateThreadListIfNeeded ()
1575 const uint32_t stop_id = GetStopID();
1576 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1578 const StateType state = GetPrivateState();
1579 if (StateIsStoppedState (state, true))
1581 Mutex::Locker locker (m_thread_list.GetMutex ());
1582 // m_thread_list does have its own mutex, but we need to
1583 // hold onto the mutex between the call to UpdateThreadList(...)
1584 // and the os->UpdateThreadList(...) so it doesn't change on us
1585 ThreadList &old_thread_list = m_thread_list;
1586 ThreadList real_thread_list(this);
1587 ThreadList new_thread_list(this);
1588 // Always update the thread list with the protocol specific
1589 // thread list, but only update if "true" is returned
1590 if (UpdateThreadList (m_thread_list_real, real_thread_list))
1592 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1593 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1594 // shutting us down, causing a deadlock.
1595 if (!m_destroy_in_process)
1597 OperatingSystem *os = GetOperatingSystem ();
1600 // Clear any old backing threads where memory threads might have been
1601 // backed by actual threads from the lldb_private::Process subclass
1602 size_t num_old_threads = old_thread_list.GetSize(false);
1603 for (size_t i=0; i<num_old_threads; ++i)
1604 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1606 // Now let the OperatingSystem plug-in update the thread list
1607 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1608 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1609 new_thread_list); // The new thread list that we will show to the user that gets filled in
1613 // No OS plug-in, the new thread list is the same as the real thread list
1614 new_thread_list = real_thread_list;
1618 m_thread_list_real.Update(real_thread_list);
1619 m_thread_list.Update (new_thread_list);
1620 m_thread_list.SetStopID (stop_id);
1622 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1624 // Clear any extended threads that we may have accumulated previously
1625 m_extended_thread_list.Clear();
1626 m_extended_thread_stop_id = GetLastNaturalStopID ();
1628 m_queue_list.Clear();
1629 m_queue_list_stop_id = GetLastNaturalStopID ();
1637 Process::UpdateQueueListIfNeeded ()
1639 if (m_system_runtime_ap.get())
1641 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1643 const StateType state = GetPrivateState();
1644 if (StateIsStoppedState (state, true))
1646 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1647 m_queue_list_stop_id = GetLastNaturalStopID();
1654 Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1656 OperatingSystem *os = GetOperatingSystem ();
1658 return os->CreateThread(tid, context);
1663 Process::GetNextThreadIndexID (uint64_t thread_id)
1665 return AssignIndexIDToThread(thread_id);
1669 Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1671 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1672 if (iterator == m_thread_id_to_index_id_map.end())
1683 Process::AssignIndexIDToThread(uint64_t thread_id)
1685 uint32_t result = 0;
1686 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1687 if (iterator == m_thread_id_to_index_id_map.end())
1689 result = ++m_thread_index_id;
1690 m_thread_id_to_index_id_map[thread_id] = result;
1694 result = iterator->second;
1703 // If any other threads access this we will need a mutex for it
1704 return m_public_state.GetValue ();
1708 Process::SetPublicState (StateType new_state, bool restarted)
1710 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1712 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
1713 const StateType old_state = m_public_state.GetValue();
1714 m_public_state.SetValue (new_state);
1716 // On the transition from Run to Stopped, we unlock the writer end of the
1717 // run lock. The lock gets locked in Resume, which is the public API
1718 // to tell the program to run.
1719 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1721 if (new_state == eStateDetached)
1724 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1725 m_public_run_lock.SetStopped();
1729 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1730 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1731 if ((old_state_is_stopped != new_state_is_stopped))
1733 if (new_state_is_stopped && !restarted)
1736 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1737 m_public_run_lock.SetStopped();
1747 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1749 log->Printf("Process::Resume -- locking run lock");
1750 if (!m_public_run_lock.TrySetRunning())
1752 Error error("Resume request failed - process still running.");
1754 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
1757 return PrivateResume();
1761 Process::GetPrivateState ()
1763 return m_private_state.GetValue();
1767 Process::SetPrivateState (StateType new_state)
1769 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1770 bool state_changed = false;
1773 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1775 Mutex::Locker thread_locker(m_thread_list.GetMutex());
1776 Mutex::Locker locker(m_private_state.GetMutex());
1778 const StateType old_state = m_private_state.GetValueNoLock ();
1779 state_changed = old_state != new_state;
1781 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1782 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1783 if (old_state_is_stopped != new_state_is_stopped)
1785 if (new_state_is_stopped)
1786 m_private_run_lock.SetStopped();
1788 m_private_run_lock.SetRunning();
1793 m_private_state.SetValueNoLock (new_state);
1794 if (StateIsStoppedState(new_state, false))
1796 // Note, this currently assumes that all threads in the list
1797 // stop when the process stops. In the future we will want to
1798 // support a debugging model where some threads continue to run
1799 // while others are stopped. When that happens we will either need
1800 // a way for the thread list to identify which threads are stopping
1801 // or create a special thread list containing only threads which
1802 // actually stopped.
1804 // The process plugin is responsible for managing the actual
1805 // behavior of the threads and should have stopped any threads
1806 // that are going to stop before we get here.
1807 m_thread_list.DidStop();
1809 m_mod_id.BumpStopID();
1810 m_memory_cache.Clear();
1812 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
1814 // Use our target to get a shared pointer to ourselves...
1815 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1816 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1818 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1823 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
1828 Process::SetRunningUserExpression (bool on)
1830 m_mod_id.SetRunningUserExpression (on);
1834 Process::GetImageInfoAddress()
1836 return LLDB_INVALID_ADDRESS;
1839 //----------------------------------------------------------------------
1842 // This function provides a default implementation that works for most
1843 // unix variants. Any Process subclasses that need to do shared library
1844 // loading differently should override LoadImage and UnloadImage and
1845 // do what is needed.
1846 //----------------------------------------------------------------------
1848 Process::LoadImage (const FileSpec &image_spec, Error &error)
1850 char path[PATH_MAX];
1851 image_spec.GetPath(path, sizeof(path));
1853 DynamicLoader *loader = GetDynamicLoader();
1856 error = loader->CanLoadImage();
1858 return LLDB_INVALID_IMAGE_TOKEN;
1861 if (error.Success())
1863 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
1867 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1871 ExecutionContext exe_ctx;
1872 frame_sp->CalculateExecutionContext (exe_ctx);
1873 EvaluateExpressionOptions expr_options;
1874 expr_options.SetUnwindOnError(true);
1875 expr_options.SetIgnoreBreakpoints(true);
1876 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
1878 expr.Printf("dlopen (\"%s\", 2)", path);
1879 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
1880 lldb::ValueObjectSP result_valobj_sp;
1882 ClangUserExpression::Evaluate (exe_ctx,
1888 if (expr_error.Success())
1890 error = result_valobj_sp->GetError();
1891 if (error.Success())
1894 if (result_valobj_sp->ResolveValue (scalar))
1896 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1897 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1899 uint32_t image_token = m_image_tokens.size();
1900 m_image_tokens.push_back (image_ptr);
1909 if (!error.AsCString())
1910 error.SetErrorStringWithFormat("unable to load '%s'", path);
1911 return LLDB_INVALID_IMAGE_TOKEN;
1914 //----------------------------------------------------------------------
1917 // This function provides a default implementation that works for most
1918 // unix variants. Any Process subclasses that need to do shared library
1919 // loading differently should override LoadImage and UnloadImage and
1920 // do what is needed.
1921 //----------------------------------------------------------------------
1923 Process::UnloadImage (uint32_t image_token)
1926 if (image_token < m_image_tokens.size())
1928 const addr_t image_addr = m_image_tokens[image_token];
1929 if (image_addr == LLDB_INVALID_ADDRESS)
1931 error.SetErrorString("image already unloaded");
1935 DynamicLoader *loader = GetDynamicLoader();
1937 error = loader->CanLoadImage();
1939 if (error.Success())
1941 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
1945 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1949 ExecutionContext exe_ctx;
1950 frame_sp->CalculateExecutionContext (exe_ctx);
1951 EvaluateExpressionOptions expr_options;
1952 expr_options.SetUnwindOnError(true);
1953 expr_options.SetIgnoreBreakpoints(true);
1954 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
1956 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
1957 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
1958 lldb::ValueObjectSP result_valobj_sp;
1960 ClangUserExpression::Evaluate (exe_ctx,
1966 if (result_valobj_sp->GetError().Success())
1969 if (result_valobj_sp->ResolveValue (scalar))
1973 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1977 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1983 error = result_valobj_sp->GetError();
1992 error.SetErrorString("invalid image token");
2001 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
2006 Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
2008 LanguageRuntimeCollection::iterator pos;
2009 pos = m_language_runtimes.find (language);
2010 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
2012 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
2014 m_language_runtimes[language] = runtime_sp;
2015 return runtime_sp.get();
2018 return (*pos).second.get();
2021 CPPLanguageRuntime *
2022 Process::GetCPPLanguageRuntime (bool retry_if_null)
2024 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
2025 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
2026 return static_cast<CPPLanguageRuntime *> (runtime);
2030 ObjCLanguageRuntime *
2031 Process::GetObjCLanguageRuntime (bool retry_if_null)
2033 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
2034 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
2035 return static_cast<ObjCLanguageRuntime *> (runtime);
2040 Process::IsPossibleDynamicValue (ValueObject& in_value)
2042 if (in_value.IsDynamic())
2044 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2046 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2048 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2049 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2052 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2053 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2056 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2057 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2060 BreakpointSiteList &
2061 Process::GetBreakpointSiteList()
2063 return m_breakpoint_site_list;
2066 const BreakpointSiteList &
2067 Process::GetBreakpointSiteList() const
2069 return m_breakpoint_site_list;
2074 Process::DisableAllBreakpointSites ()
2076 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2077 // bp_site->SetEnabled(true);
2078 DisableBreakpointSite(bp_site);
2083 Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2085 Error error (DisableBreakpointSiteByID (break_id));
2087 if (error.Success())
2088 m_breakpoint_site_list.Remove(break_id);
2094 Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2097 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2100 if (bp_site_sp->IsEnabled())
2101 error = DisableBreakpointSite (bp_site_sp.get());
2105 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
2112 Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2115 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2118 if (!bp_site_sp->IsEnabled())
2119 error = EnableBreakpointSite (bp_site_sp.get());
2123 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
2129 Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
2131 addr_t load_addr = LLDB_INVALID_ADDRESS;
2133 bool show_error = true;
2137 case eStateUnloaded:
2138 case eStateConnected:
2139 case eStateAttaching:
2140 case eStateLaunching:
2141 case eStateDetached:
2148 case eStateStepping:
2150 case eStateSuspended:
2151 show_error = IsAlive();
2155 // Reset the IsIndirect flag here, in case the location changes from
2156 // pointing to a indirect symbol to a regular symbol.
2157 owner->SetIsIndirect (false);
2159 if (owner->ShouldResolveIndirectFunctions())
2161 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2162 if (symbol && symbol->IsIndirect())
2165 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
2166 if (!error.Success() && show_error)
2168 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2169 symbol->GetAddress().GetLoadAddress(&m_target),
2170 owner->GetBreakpoint().GetID(),
2172 error.AsCString() ? error.AsCString() : "unkown error");
2173 return LLDB_INVALID_BREAK_ID;
2175 Address resolved_address(load_addr);
2176 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
2177 owner->SetIsIndirect(true);
2180 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2183 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2185 if (load_addr != LLDB_INVALID_ADDRESS)
2187 BreakpointSiteSP bp_site_sp;
2189 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2190 // create a new breakpoint site and add it.
2192 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2196 bp_site_sp->AddOwner (owner);
2197 owner->SetBreakpointSite (bp_site_sp);
2198 return bp_site_sp->GetID();
2202 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
2205 Error error = EnableBreakpointSite (bp_site_sp.get());
2206 if (error.Success())
2208 owner->SetBreakpointSite (bp_site_sp);
2209 return m_breakpoint_site_list.Add (bp_site_sp);
2215 // Report error for setting breakpoint...
2216 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2218 owner->GetBreakpoint().GetID(),
2220 error.AsCString() ? error.AsCString() : "unkown error");
2226 // We failed to enable the breakpoint
2227 return LLDB_INVALID_BREAK_ID;
2232 Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2234 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2235 if (num_owners == 0)
2237 // Don't try to disable the site if we don't have a live process anymore.
2239 DisableBreakpointSite (bp_site_sp.get());
2240 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2246 Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2248 size_t bytes_removed = 0;
2249 BreakpointSiteList bp_sites_in_range;
2251 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
2253 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2254 if (bp_site->GetType() == BreakpointSite::eSoftware)
2256 addr_t intersect_addr;
2257 size_t intersect_size;
2258 size_t opcode_offset;
2259 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
2261 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2262 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
2263 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
2264 size_t buf_offset = intersect_addr - bp_addr;
2265 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
2270 return bytes_removed;
2276 Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2278 PlatformSP platform_sp (m_target.GetPlatform());
2280 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2285 Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2288 assert (bp_site != NULL);
2289 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2290 const addr_t bp_addr = bp_site->GetLoadAddress();
2292 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
2293 if (bp_site->IsEnabled())
2296 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
2300 if (bp_addr == LLDB_INVALID_ADDRESS)
2302 error.SetErrorString("BreakpointSite contains an invalid load address.");
2305 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2306 // trap for the breakpoint site
2307 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2309 if (bp_opcode_size == 0)
2311 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
2315 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2317 if (bp_opcode_bytes == NULL)
2319 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2323 // Save the original opcode by reading it
2324 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2326 // Write a software breakpoint in place of the original opcode
2327 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2329 uint8_t verify_bp_opcode_bytes[64];
2330 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2332 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2334 bp_site->SetEnabled(true);
2335 bp_site->SetType (BreakpointSite::eSoftware);
2337 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
2342 error.SetErrorString("failed to verify the breakpoint trap in memory.");
2345 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2348 error.SetErrorString("Unable to write breakpoint trap to memory.");
2351 error.SetErrorString("Unable to read memory at breakpoint address.");
2353 if (log && error.Fail())
2354 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
2362 Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2365 assert (bp_site != NULL);
2366 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2367 addr_t bp_addr = bp_site->GetLoadAddress();
2368 lldb::user_id_t breakID = bp_site->GetID();
2370 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
2372 if (bp_site->IsHardware())
2374 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2376 else if (bp_site->IsEnabled())
2378 const size_t break_op_size = bp_site->GetByteSize();
2379 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2380 if (break_op_size > 0)
2382 // Clear a software breakoint instruction
2383 uint8_t curr_break_op[8];
2384 assert (break_op_size <= sizeof(curr_break_op));
2385 bool break_op_found = false;
2387 // Read the breakpoint opcode
2388 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2390 bool verify = false;
2391 // Make sure we have the a breakpoint opcode exists at this address
2392 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2394 break_op_found = true;
2395 // We found a valid breakpoint opcode at this address, now restore
2396 // the saved opcode.
2397 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2402 error.SetErrorString("Memory write failed when restoring original opcode.");
2406 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2407 // Set verify to true and so we can check if the original opcode has already been restored
2413 uint8_t verify_opcode[8];
2414 assert (break_op_size < sizeof(verify_opcode));
2415 // Verify that our original opcode made it back to the inferior
2416 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2418 // compare the memory we just read with the original opcode
2419 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2422 bp_site->SetEnabled(false);
2424 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
2430 error.SetErrorString("Failed to restore original opcode.");
2434 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2438 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2444 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
2449 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
2457 // Uncomment to verify memory caching works after making changes to caching code
2458 //#define VERIFY_MEMORY_READS
2461 Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2464 if (!GetDisableMemoryCache())
2466 #if defined (VERIFY_MEMORY_READS)
2467 // Memory caching is enabled, with debug verification
2471 // Uncomment the line below to make sure memory caching is working.
2472 // I ran this through the test suite and got no assertions, so I am
2473 // pretty confident this is working well. If any changes are made to
2474 // memory caching, uncomment the line below and test your changes!
2476 // Verify all memory reads by using the cache first, then redundantly
2477 // reading the same memory from the inferior and comparing to make sure
2478 // everything is exactly the same.
2479 std::string verify_buf (size, '\0');
2480 assert (verify_buf.size() == size);
2481 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2483 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2484 assert (cache_bytes_read == verify_bytes_read);
2485 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2486 assert (verify_error.Success() == error.Success());
2487 return cache_bytes_read;
2490 #else // !defined(VERIFY_MEMORY_READS)
2491 // Memory caching is enabled, without debug verification
2493 return m_memory_cache.Read (addr, buf, size, error);
2494 #endif // defined (VERIFY_MEMORY_READS)
2498 // Memory caching is disabled
2500 return ReadMemoryFromInferior (addr, buf, size, error);
2505 Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2509 addr_t curr_addr = addr;
2512 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2515 out_str.append(buf, length);
2516 // If we got "length - 1" bytes, we didn't get the whole C string, we
2517 // need to read some more characters
2518 if (length == sizeof(buf) - 1)
2519 curr_addr += length;
2523 return out_str.size();
2528 Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2531 size_t total_bytes_read = 0;
2532 if (dst && max_bytes && type_width && max_bytes >= type_width)
2534 // Ensure a null terminator independent of the number of bytes that is read.
2535 memset (dst, 0, max_bytes);
2536 size_t bytes_left = max_bytes - type_width;
2538 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2539 assert(sizeof(terminator) >= type_width &&
2540 "Attempting to validate a string with more than 4 bytes per character!");
2542 addr_t curr_addr = addr;
2543 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2544 char *curr_dst = dst;
2547 while (bytes_left > 0 && error.Success())
2549 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2550 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2551 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2553 if (bytes_read == 0)
2556 // Search for a null terminator of correct size and alignment in bytes_read
2557 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2558 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2559 if (::strncmp(&dst[i], terminator, type_width) == 0)
2565 total_bytes_read += bytes_read;
2566 curr_dst += bytes_read;
2567 curr_addr += bytes_read;
2568 bytes_left -= bytes_read;
2574 error.SetErrorString("invalid arguments");
2576 return total_bytes_read;
2579 // Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2580 // null terminators.
2582 Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
2584 size_t total_cstr_len = 0;
2585 if (dst && dst_max_len)
2587 result_error.Clear();
2588 // NULL out everything just to be safe
2589 memset (dst, 0, dst_max_len);
2591 addr_t curr_addr = addr;
2592 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2593 size_t bytes_left = dst_max_len - 1;
2594 char *curr_dst = dst;
2596 while (bytes_left > 0)
2598 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2599 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2600 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2602 if (bytes_read == 0)
2604 result_error = error;
2605 dst[total_cstr_len] = '\0';
2608 const size_t len = strlen(curr_dst);
2610 total_cstr_len += len;
2612 if (len < bytes_to_read)
2615 curr_dst += bytes_read;
2616 curr_addr += bytes_read;
2617 bytes_left -= bytes_read;
2623 result_error.SetErrorString("invalid arguments");
2625 result_error.Clear();
2627 return total_cstr_len;
2631 Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2633 if (buf == NULL || size == 0)
2636 size_t bytes_read = 0;
2637 uint8_t *bytes = (uint8_t *)buf;
2639 while (bytes_read < size)
2641 const size_t curr_size = size - bytes_read;
2642 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2646 bytes_read += curr_bytes_read;
2647 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2651 // Replace any software breakpoint opcodes that fall into this range back
2652 // into "buf" before we return
2654 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2659 Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
2662 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2663 return scalar.ULongLong(fail_value);
2668 Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2671 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2672 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2673 return LLDB_INVALID_ADDRESS;
2678 Process::WritePointerToMemory (lldb::addr_t vm_addr,
2679 lldb::addr_t ptr_value,
2683 const uint32_t addr_byte_size = GetAddressByteSize();
2684 if (addr_byte_size <= 4)
2685 scalar = (uint32_t)ptr_value;
2688 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
2692 Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2694 size_t bytes_written = 0;
2695 const uint8_t *bytes = (const uint8_t *)buf;
2697 while (bytes_written < size)
2699 const size_t curr_size = size - bytes_written;
2700 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2701 bytes + bytes_written,
2704 bytes_written += curr_bytes_written;
2705 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2708 return bytes_written;
2712 Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2714 #if defined (ENABLE_MEMORY_CACHING)
2715 m_memory_cache.Flush (addr, size);
2718 if (buf == NULL || size == 0)
2721 m_mod_id.BumpMemoryID();
2723 // We need to write any data that would go where any current software traps
2724 // (enabled software breakpoints) any software traps (breakpoints) that we
2725 // may have placed in our tasks memory.
2727 BreakpointSiteList bp_sites_in_range;
2729 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
2731 // No breakpoint sites overlap
2732 if (bp_sites_in_range.IsEmpty())
2733 return WriteMemoryPrivate (addr, buf, size, error);
2736 const uint8_t *ubuf = (const uint8_t *)buf;
2737 uint64_t bytes_written = 0;
2739 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2741 if (error.Success())
2743 addr_t intersect_addr;
2744 size_t intersect_size;
2745 size_t opcode_offset;
2746 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2748 assert(addr <= intersect_addr && intersect_addr < addr + size);
2749 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2750 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2752 // Check for bytes before this breakpoint
2753 const addr_t curr_addr = addr + bytes_written;
2754 if (intersect_addr > curr_addr)
2756 // There are some bytes before this breakpoint that we need to
2757 // just write to memory
2758 size_t curr_size = intersect_addr - curr_addr;
2759 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2760 ubuf + bytes_written,
2763 bytes_written += curr_bytes_written;
2764 if (curr_bytes_written != curr_size)
2766 // We weren't able to write all of the requested bytes, we
2767 // are done looping and will return the number of bytes that
2768 // we have written so far.
2769 if (error.Success())
2770 error.SetErrorToGenericError();
2773 // Now write any bytes that would cover up any software breakpoints
2774 // directly into the breakpoint opcode buffer
2775 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2776 bytes_written += intersect_size;
2780 if (bytes_written < size)
2781 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2782 ubuf + bytes_written,
2783 size - bytes_written,
2789 return WriteMemoryPrivate (addr, buf, size, error);
2792 // Write any remaining bytes after the last breakpoint if we have any left
2793 return 0; //bytes_written;
2797 Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
2799 if (byte_size == UINT32_MAX)
2800 byte_size = scalar.GetByteSize();
2804 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2806 return WriteMemory(addr, buf, mem_size, error);
2808 error.SetErrorString ("failed to get scalar as memory data");
2812 error.SetErrorString ("invalid scalar value");
2818 Process::ReadScalarIntegerFromMemory (addr_t addr,
2827 error.SetErrorString ("byte size is zero");
2829 else if (byte_size & (byte_size - 1))
2831 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2833 else if (byte_size <= sizeof(uval))
2835 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2836 if (bytes_read == byte_size)
2838 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2839 lldb::offset_t offset = 0;
2841 scalar = data.GetMaxU32 (&offset, byte_size);
2843 scalar = data.GetMaxU64 (&offset, byte_size);
2845 scalar.SignExtend(byte_size * 8);
2851 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2856 #define USE_ALLOCATE_MEMORY_CACHE 1
2858 Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2860 if (GetPrivateState() != eStateStopped)
2861 return LLDB_INVALID_ADDRESS;
2863 #if defined (USE_ALLOCATE_MEMORY_CACHE)
2864 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2866 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2867 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2869 log->Printf("Process::AllocateMemory(size=%" PRIu64 ", permissions=%s) => 0x%16.16" PRIx64 " (m_stop_id = %u m_memory_id = %u)",
2871 GetPermissionsAsCString (permissions),
2872 (uint64_t)allocated_addr,
2873 m_mod_id.GetStopID(),
2874 m_mod_id.GetMemoryID());
2875 return allocated_addr;
2882 if (m_can_jit == eCanJITDontKnow)
2886 uint64_t allocated_memory = AllocateMemory(8,
2887 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2891 m_can_jit = eCanJITYes;
2893 m_can_jit = eCanJITNo;
2895 DeallocateMemory (allocated_memory);
2898 return m_can_jit == eCanJITYes;
2902 Process::SetCanJIT (bool can_jit)
2904 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2908 Process::DeallocateMemory (addr_t ptr)
2911 #if defined (USE_ALLOCATE_MEMORY_CACHE)
2912 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2914 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2917 error = DoDeallocateMemory (ptr);
2919 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2921 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2923 error.AsCString("SUCCESS"),
2924 m_mod_id.GetStopID(),
2925 m_mod_id.GetMemoryID());
2932 Process::ReadModuleFromMemory (const FileSpec& file_spec,
2933 lldb::addr_t header_addr)
2935 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
2939 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2947 Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
2950 error.SetErrorString("watchpoints are not supported");
2955 Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
2958 error.SetErrorString("watchpoints are not supported");
2963 Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2966 // Now wait for the process to launch and return control to us, and then
2971 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2973 if (StateIsStoppedState(state, false))
2976 // If state is invalid, then we timed out
2977 if (state == eStateInvalid)
2981 HandlePrivateEvent (event_sp);
2987 Process::Launch (ProcessLaunchInfo &launch_info)
2992 m_system_runtime_ap.reset();
2994 m_process_input_reader.reset();
2996 Module *exe_module = m_target.GetExecutableModulePointer();
2999 char local_exec_file_path[PATH_MAX];
3000 char platform_exec_file_path[PATH_MAX];
3001 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
3002 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
3003 if (exe_module->GetFileSpec().Exists())
3005 // Install anything that might need to be installed prior to launching.
3006 // For host systems, this will do nothing, but if we are connected to a
3007 // remote platform it will install any needed binaries
3008 error = GetTarget().Install(&launch_info);
3012 if (PrivateStateThreadIsValid ())
3013 PausePrivateStateThread ();
3015 error = WillLaunch (exe_module);
3016 if (error.Success())
3018 const bool restarted = false;
3019 SetPublicState (eStateLaunching, restarted);
3020 m_should_detach = false;
3022 if (m_public_run_lock.TrySetRunning())
3024 // Now launch using these arguments.
3025 error = DoLaunch (exe_module, launch_info);
3029 // This shouldn't happen
3030 error.SetErrorString("failed to acquire process run lock");
3035 if (GetID() != LLDB_INVALID_PROCESS_ID)
3037 SetID (LLDB_INVALID_PROCESS_ID);
3038 const char *error_string = error.AsCString();
3039 if (error_string == NULL)
3040 error_string = "launch failed";
3041 SetExitStatus (-1, error_string);
3047 TimeValue timeout_time;
3048 timeout_time = TimeValue::Now();
3049 timeout_time.OffsetWithSeconds(10);
3050 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
3052 if (state == eStateInvalid || event_sp.get() == NULL)
3054 // We were able to launch the process, but we failed to
3055 // catch the initial stop.
3056 SetExitStatus (0, "failed to catch stop after launch");
3059 else if (state == eStateStopped || state == eStateCrashed)
3064 DynamicLoader *dyld = GetDynamicLoader ();
3068 SystemRuntime *system_runtime = GetSystemRuntime ();
3070 system_runtime->DidLaunch();
3072 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
3073 // This delays passing the stopped event to listeners till DidLaunch gets
3074 // a chance to complete...
3075 HandlePrivateEvent (event_sp);
3077 if (PrivateStateThreadIsValid ())
3078 ResumePrivateStateThread ();
3080 StartPrivateStateThread ();
3082 else if (state == eStateExited)
3084 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3085 // not likely to work, and return an invalid pid.
3086 HandlePrivateEvent (event_sp);
3093 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
3101 Process::LoadCore ()
3103 Error error = DoLoadCore();
3104 if (error.Success())
3106 if (PrivateStateThreadIsValid ())
3107 ResumePrivateStateThread ();
3109 StartPrivateStateThread ();
3111 DynamicLoader *dyld = GetDynamicLoader ();
3115 SystemRuntime *system_runtime = GetSystemRuntime ();
3117 system_runtime->DidAttach();
3119 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
3120 // We successfully loaded a core file, now pretend we stopped so we can
3121 // show all of the threads in the core file and explore the crashed
3123 SetPrivateState (eStateStopped);
3130 Process::GetDynamicLoader ()
3132 if (m_dyld_ap.get() == NULL)
3133 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3134 return m_dyld_ap.get();
3138 Process::GetSystemRuntime ()
3140 if (m_system_runtime_ap.get() == NULL)
3141 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3142 return m_system_runtime_ap.get();
3146 Process::NextEventAction::EventActionResult
3147 Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
3149 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
3153 case eStateConnected:
3154 return eEventActionRetry;
3159 // During attach, prior to sending the eStateStopped event,
3160 // lldb_private::Process subclasses must set the new process ID.
3161 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
3162 // We don't want these events to be reported, so go set the ShouldReportStop here:
3163 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3165 if (m_exec_count > 0)
3169 return eEventActionRetry;
3173 m_process->CompleteAttach ();
3174 return eEventActionSuccess;
3185 m_exit_string.assign ("No valid Process");
3186 return eEventActionExit;
3189 Process::NextEventAction::EventActionResult
3190 Process::AttachCompletionHandler::HandleBeingInterrupted()
3192 return eEventActionSuccess;
3196 Process::AttachCompletionHandler::GetExitString ()
3198 return m_exit_string.c_str();
3202 Process::Attach (ProcessAttachInfo &attach_info)
3205 m_process_input_reader.reset();
3207 m_system_runtime_ap.reset();
3210 lldb::pid_t attach_pid = attach_info.GetProcessID();
3212 if (attach_pid == LLDB_INVALID_PROCESS_ID)
3214 char process_name[PATH_MAX];
3216 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
3218 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3220 if (wait_for_launch)
3222 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3223 if (error.Success())
3225 if (m_public_run_lock.TrySetRunning())
3227 m_should_detach = true;
3228 const bool restarted = false;
3229 SetPublicState (eStateAttaching, restarted);
3230 // Now attach using these arguments.
3231 error = DoAttachToProcessWithName (process_name, attach_info);
3235 // This shouldn't happen
3236 error.SetErrorString("failed to acquire process run lock");
3241 if (GetID() != LLDB_INVALID_PROCESS_ID)
3243 SetID (LLDB_INVALID_PROCESS_ID);
3244 if (error.AsCString() == NULL)
3245 error.SetErrorString("attach failed");
3247 SetExitStatus(-1, error.AsCString());
3252 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3253 StartPrivateStateThread();
3260 ProcessInstanceInfoList process_infos;
3261 PlatformSP platform_sp (m_target.GetPlatform ());
3265 ProcessInstanceInfoMatch match_info;
3266 match_info.GetProcessInfo() = attach_info;
3267 match_info.SetNameMatchType (eNameMatchEquals);
3268 platform_sp->FindProcesses (match_info, process_infos);
3269 const uint32_t num_matches = process_infos.GetSize();
3270 if (num_matches == 1)
3272 attach_pid = process_infos.GetProcessIDAtIndex(0);
3273 // Fall through and attach using the above process ID
3277 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3278 if (num_matches > 1)
3279 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3281 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3286 error.SetErrorString ("invalid platform, can't find processes by name");
3293 error.SetErrorString ("invalid process name");
3297 if (attach_pid != LLDB_INVALID_PROCESS_ID)
3299 error = WillAttachToProcessWithID(attach_pid);
3300 if (error.Success())
3303 if (m_public_run_lock.TrySetRunning())
3305 // Now attach using these arguments.
3306 m_should_detach = true;
3307 const bool restarted = false;
3308 SetPublicState (eStateAttaching, restarted);
3309 error = DoAttachToProcessWithID (attach_pid, attach_info);
3313 // This shouldn't happen
3314 error.SetErrorString("failed to acquire process run lock");
3317 if (error.Success())
3320 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3321 StartPrivateStateThread();
3325 if (GetID() != LLDB_INVALID_PROCESS_ID)
3327 SetID (LLDB_INVALID_PROCESS_ID);
3328 const char *error_string = error.AsCString();
3329 if (error_string == NULL)
3330 error_string = "attach failed";
3332 SetExitStatus(-1, error_string);
3341 Process::CompleteAttach ()
3343 // Let the process subclass figure out at much as it can about the process
3344 // before we go looking for a dynamic loader plug-in.
3347 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3348 // the same as the one we've already set, switch architectures.
3349 PlatformSP platform_sp (m_target.GetPlatform ());
3350 assert (platform_sp.get());
3353 const ArchSpec &target_arch = m_target.GetArchitecture();
3354 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
3356 ArchSpec platform_arch;
3357 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3360 m_target.SetPlatform (platform_sp);
3361 m_target.SetArchitecture(platform_arch);
3366 ProcessInstanceInfo process_info;
3367 platform_sp->GetProcessInfo (GetID(), process_info);
3368 const ArchSpec &process_arch = process_info.GetArchitecture();
3369 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
3370 m_target.SetArchitecture (process_arch);
3374 // We have completed the attach, now it is time to find the dynamic loader
3376 DynamicLoader *dyld = GetDynamicLoader ();
3380 SystemRuntime *system_runtime = GetSystemRuntime ();
3382 system_runtime->DidAttach();
3384 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
3385 // Figure out which one is the executable, and set that in our target:
3386 const ModuleList &target_modules = m_target.GetImages();
3387 Mutex::Locker modules_locker(target_modules.GetMutex());
3388 size_t num_modules = target_modules.GetSize();
3389 ModuleSP new_executable_module_sp;
3391 for (size_t i = 0; i < num_modules; i++)
3393 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
3394 if (module_sp && module_sp->IsExecutable())
3396 if (m_target.GetExecutableModulePointer() != module_sp.get())
3397 new_executable_module_sp = module_sp;
3401 if (new_executable_module_sp)
3402 m_target.SetExecutableModule (new_executable_module_sp, false);
3406 Process::ConnectRemote (Stream *strm, const char *remote_url)
3409 m_process_input_reader.reset();
3411 // Find the process and its architecture. Make sure it matches the architecture
3412 // of the current Target, and if not adjust it.
3414 Error error (DoConnectRemote (strm, remote_url));
3415 if (error.Success())
3417 if (GetID() != LLDB_INVALID_PROCESS_ID)
3420 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3422 if (state == eStateStopped || state == eStateCrashed)
3424 // If we attached and actually have a process on the other end, then
3425 // this ended up being the equivalent of an attach.
3428 // This delays passing the stopped event to listeners till
3429 // CompleteAttach gets a chance to complete...
3430 HandlePrivateEvent (event_sp);
3435 if (PrivateStateThreadIsValid ())
3436 ResumePrivateStateThread ();
3438 StartPrivateStateThread ();
3445 Process::PrivateResume ()
3447 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
3449 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
3450 m_mod_id.GetStopID(),
3451 StateAsCString(m_public_state.GetValue()),
3452 StateAsCString(m_private_state.GetValue()));
3454 Error error (WillResume());
3455 // Tell the process it is about to resume before the thread list
3456 if (error.Success())
3458 // Now let the thread list know we are about to resume so it
3459 // can let all of our threads know that they are about to be
3460 // resumed. Threads will each be called with
3461 // Thread::WillResume(StateType) where StateType contains the state
3462 // that they are supposed to have when the process is resumed
3463 // (suspended/running/stepping). Threads should also check
3464 // their resume signal in lldb::Thread::GetResumeSignal()
3465 // to see if they are supposed to start back up with a signal.
3466 if (m_thread_list.WillResume())
3468 // Last thing, do the PreResumeActions.
3469 if (!RunPreResumeActions())
3471 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
3475 m_mod_id.BumpResumeID();
3477 if (error.Success())
3480 m_thread_list.DidResume();
3482 log->Printf ("Process thinks the process has resumed.");
3488 // Somebody wanted to run without running. So generate a continue & a stopped event,
3489 // and let the world handle them.
3491 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3493 SetPrivateState(eStateRunning);
3494 SetPrivateState(eStateStopped);
3498 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
3503 Process::Halt (bool clear_thread_plans)
3505 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3506 // in case it was already set and some thread plan logic calls halt on its
3508 m_clear_thread_plans_on_stop |= clear_thread_plans;
3510 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3511 // we could just straightaway get another event. It just narrows the window...
3512 m_currently_handling_event.WaitForValueEqualTo(false);
3515 // Pause our private state thread so we can ensure no one else eats
3516 // the stop event out from under us.
3517 Listener halt_listener ("lldb.process.halt_listener");
3518 HijackPrivateProcessEvents(&halt_listener);
3521 Error error (WillHalt());
3523 if (error.Success())
3526 bool caused_stop = false;
3528 // Ask the process subclass to actually halt our process
3529 error = DoHalt(caused_stop);
3530 if (error.Success())
3532 if (m_public_state.GetValue() == eStateAttaching)
3534 SetExitStatus(SIGKILL, "Cancelled async attach.");
3539 // If "caused_stop" is true, then DoHalt stopped the process. If
3540 // "caused_stop" is false, the process was already stopped.
3541 // If the DoHalt caused the process to stop, then we want to catch
3542 // this event and set the interrupted bool to true before we pass
3543 // this along so clients know that the process was interrupted by
3547 // Wait for 1 second for the process to stop.
3548 TimeValue timeout_time;
3549 timeout_time = TimeValue::Now();
3550 timeout_time.OffsetWithSeconds(1);
3551 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3552 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
3554 if (!got_event || state == eStateInvalid)
3556 // We timeout out and didn't get a stop event...
3557 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
3561 if (StateIsStoppedState (state, false))
3563 // We caused the process to interrupt itself, so mark this
3564 // as such in the stop event so clients can tell an interrupted
3565 // process from a natural stop
3566 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3570 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3572 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3573 error.SetErrorString ("Did not get stopped event after halt.");
3581 // Resume our private state thread before we post the event (if any)
3582 RestorePrivateProcessEvents();
3584 // Post any event we might have consumed. If all goes well, we will have
3585 // stopped the process, intercepted the event and set the interrupted
3586 // bool in the event. Post it to the private event queue and that will end up
3587 // correctly setting the state.
3589 m_private_state_broadcaster.BroadcastEvent(event_sp);
3595 Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3598 if (m_public_state.GetValue() == eStateRunning)
3600 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3602 log->Printf("Process::Destroy() About to halt.");
3604 if (error.Success())
3606 // Consume the halt event.
3607 TimeValue timeout (TimeValue::Now());
3608 timeout.OffsetWithSeconds(1);
3609 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3611 // If the process exited while we were waiting for it to stop, put the exited event into
3612 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3613 // they don't have a process anymore...
3615 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3618 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3622 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3624 if (state != eStateStopped)
3627 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3628 // If we really couldn't stop the process then we should just error out here, but if the
3629 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3630 StateType private_state = m_private_state.GetValue();
3631 if (private_state != eStateStopped)
3640 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3647 Process::Detach (bool keep_stopped)
3649 EventSP exit_event_sp;
3651 m_destroy_in_process = true;
3653 error = WillDetach();
3655 if (error.Success())
3657 if (DetachRequiresHalt())
3659 error = HaltForDestroyOrDetach (exit_event_sp);
3660 if (!error.Success())
3662 m_destroy_in_process = false;
3665 else if (exit_event_sp)
3667 // We shouldn't need to do anything else here. There's no process left to detach from...
3668 StopPrivateStateThread();
3669 m_destroy_in_process = false;
3674 error = DoDetach(keep_stopped);
3675 if (error.Success())
3678 StopPrivateStateThread();
3685 m_destroy_in_process = false;
3687 // If we exited when we were waiting for a process to stop, then
3688 // forward the event here so we don't lose the event
3691 // Directly broadcast our exited event because we shut down our
3692 // private state thread above
3693 BroadcastEvent(exit_event_sp);
3696 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3697 // the last events through the event system, in which case we might strand the write lock. Unlock
3698 // it here so when we do to tear down the process we don't get an error destroying the lock.
3700 m_public_run_lock.SetStopped();
3708 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3709 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3710 // failed and the process stays around for some reason it won't be in a confused state.
3712 m_destroy_in_process = true;
3714 Error error (WillDestroy());
3715 if (error.Success())
3717 EventSP exit_event_sp;
3718 if (DestroyRequiresHalt())
3720 error = HaltForDestroyOrDetach(exit_event_sp);
3723 if (m_public_state.GetValue() != eStateRunning)
3725 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3726 // kill it, we don't want it hitting a breakpoint...
3727 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3728 // we're not going to have much luck doing this now.
3729 m_thread_list.DiscardThreadPlans();
3730 DisableAllBreakpointSites();
3733 error = DoDestroy();
3734 if (error.Success())
3737 StopPrivateStateThread();
3739 m_stdio_communication.StopReadThread();
3740 m_stdio_communication.Disconnect();
3741 if (m_process_input_reader)
3742 m_process_input_reader.reset();
3744 // If we exited when we were waiting for a process to stop, then
3745 // forward the event here so we don't lose the event
3748 // Directly broadcast our exited event because we shut down our
3749 // private state thread above
3750 BroadcastEvent(exit_event_sp);
3753 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3754 // the last events through the event system, in which case we might strand the write lock. Unlock
3755 // it here so when we do to tear down the process we don't get an error destroying the lock.
3756 m_public_run_lock.SetStopped();
3759 m_destroy_in_process = false;
3765 Process::Signal (int signal)
3767 Error error (WillSignal());
3768 if (error.Success())
3770 error = DoSignal(signal);
3771 if (error.Success())
3778 Process::GetByteOrder () const
3780 return m_target.GetArchitecture().GetByteOrder();
3784 Process::GetAddressByteSize () const
3786 return m_target.GetArchitecture().GetAddressByteSize();
3791 Process::ShouldBroadcastEvent (Event *event_ptr)
3793 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3794 bool return_value = true;
3795 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
3799 case eStateConnected:
3800 case eStateAttaching:
3801 case eStateLaunching:
3802 case eStateDetached:
3804 case eStateUnloaded:
3805 // These events indicate changes in the state of the debugging session, always report them.
3806 return_value = true;
3809 // We stopped for no apparent reason, don't report it.
3810 return_value = false;
3813 case eStateStepping:
3814 // If we've started the target running, we handle the cases where we
3815 // are already running and where there is a transition from stopped to
3816 // running differently.
3817 // running -> running: Automatically suppress extra running events
3818 // stopped -> running: Report except when there is one or more no votes
3819 // and no yes votes.
3820 SynchronouslyNotifyStateChanged (state);
3821 if (m_force_next_event_delivery)
3822 return_value = true;
3825 switch (m_last_broadcast_state)
3828 case eStateStepping:
3829 // We always suppress multiple runnings with no PUBLIC stop in between.
3830 return_value = false;
3833 // TODO: make this work correctly. For now always report
3834 // run if we aren't running so we don't miss any runnning
3835 // events. If I run the lldb/test/thread/a.out file and
3836 // break at main.cpp:58, run and hit the breakpoints on
3837 // multiple threads, then somehow during the stepping over
3838 // of all breakpoints no run gets reported.
3840 // This is a transition from stop to run.
3841 switch (m_thread_list.ShouldReportRun (event_ptr))
3844 case eVoteNoOpinion:
3845 return_value = true;
3848 return_value = false;
3857 case eStateSuspended:
3859 // We've stopped. First see if we're going to restart the target.
3860 // If we are going to stop, then we always broadcast the event.
3861 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
3862 // If no thread has an opinion, we don't report it.
3864 RefreshStateAfterStop ();
3865 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
3868 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3870 StateAsCString(state));
3871 return_value = true;
3875 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3876 bool should_resume = false;
3878 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3879 // Asking the thread list is also not likely to go well, since we are running again.
3880 // So in that case just report the event.
3883 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
3885 if (was_restarted || should_resume || m_resume_requested)
3887 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3889 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3891 StateAsCString(state),
3898 return_value = true;
3900 case eVoteNoOpinion:
3902 return_value = false;
3909 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3910 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3917 return_value = true;
3918 SynchronouslyNotifyStateChanged (state);
3925 // Forcing the next event delivery is a one shot deal. So reset it here.
3926 m_force_next_event_delivery = false;
3928 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3929 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3930 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3931 // because the PublicState reflects the last event pulled off the queue, and there may be several
3932 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3933 // yet. m_last_broadcast_state gets updated here.
3936 m_last_broadcast_state = state;
3939 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3941 StateAsCString(state),
3942 StateAsCString(m_last_broadcast_state),
3943 return_value ? "YES" : "NO");
3944 return return_value;
3949 Process::StartPrivateStateThread (bool force)
3951 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3953 bool already_running = PrivateStateThreadIsValid ();
3955 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3957 if (!force && already_running)
3960 // Create a thread that watches our internal state and controls which
3961 // events make it to clients (into the DCProcess event queue).
3962 char thread_name[1024];
3963 if (already_running)
3964 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
3966 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3968 // Create the private state thread, and start it running.
3969 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
3970 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3973 ResumePrivateStateThread();
3981 Process::PausePrivateStateThread ()
3983 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3987 Process::ResumePrivateStateThread ()
3989 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3993 Process::StopPrivateStateThread ()
3995 if (PrivateStateThreadIsValid ())
3996 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
3999 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4001 log->Printf ("Went to stop the private state thread, but it was already invalid.");
4006 Process::ControlPrivateStateThread (uint32_t signal)
4008 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4010 assert (signal == eBroadcastInternalStateControlStop ||
4011 signal == eBroadcastInternalStateControlPause ||
4012 signal == eBroadcastInternalStateControlResume);
4015 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
4017 // Signal the private state thread. First we should copy this is case the
4018 // thread starts exiting since the private state thread will NULL this out
4020 const lldb::thread_t private_state_thread = m_private_state_thread;
4021 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
4023 TimeValue timeout_time;
4026 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4028 timeout_time = TimeValue::Now();
4029 timeout_time.OffsetWithSeconds(2);
4031 log->Printf ("Sending control event of type: %d.", signal);
4032 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4033 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4035 if (signal == eBroadcastInternalStateControlStop)
4040 Host::ThreadCancel (private_state_thread, &error);
4042 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4047 log->Printf ("The control event killed the private state thread without having to cancel.");
4050 thread_result_t result = NULL;
4051 Host::ThreadJoin (private_state_thread, &result, NULL);
4052 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
4058 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4063 Process::SendAsyncInterrupt ()
4065 if (PrivateStateThreadIsValid())
4066 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4068 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4072 Process::HandlePrivateEvent (EventSP &event_sp)
4074 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4075 m_resume_requested = false;
4077 m_currently_handling_event.SetValue(true, eBroadcastNever);
4079 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4081 // First check to see if anybody wants a shot at this event:
4082 if (m_next_event_action_ap.get() != NULL)
4084 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
4086 log->Printf ("Ran next event action, result was %d.", action_result);
4088 switch (action_result)
4090 case NextEventAction::eEventActionSuccess:
4091 SetNextEventAction(NULL);
4094 case NextEventAction::eEventActionRetry:
4097 case NextEventAction::eEventActionExit:
4098 // Handle Exiting Here. If we already got an exited event,
4099 // we should just propagate it. Otherwise, swallow this event,
4100 // and set our state to exit so the next event will kill us.
4101 if (new_state != eStateExited)
4103 // FIXME: should cons up an exited event, and discard this one.
4104 SetExitStatus(0, m_next_event_action_ap->GetExitString());
4105 m_currently_handling_event.SetValue(false, eBroadcastAlways);
4106 SetNextEventAction(NULL);
4109 SetNextEventAction(NULL);
4114 // See if we should broadcast this state to external clients?
4115 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
4117 if (should_broadcast)
4121 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
4124 StateAsCString(new_state),
4125 StateAsCString (GetState ()),
4126 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
4128 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
4129 if (StateIsRunningState (new_state))
4131 // Only push the input handler if we aren't fowarding events,
4132 // as this means the curses GUI is in use...
4133 if (!GetTarget().GetDebugger().IsForwardingEvents())
4134 PushProcessIOHandler ();
4136 else if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4137 PopProcessIOHandler ();
4139 BroadcastEvent (event_sp);
4145 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
4148 StateAsCString(new_state),
4149 StateAsCString (GetState ()));
4152 m_currently_handling_event.SetValue(false, eBroadcastAlways);
4156 Process::PrivateStateThread (void *arg)
4158 Process *proc = static_cast<Process*> (arg);
4159 thread_result_t result = proc->RunPrivateStateThread();
4164 Process::RunPrivateStateThread ()
4166 bool control_only = true;
4167 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4169 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4171 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
4173 bool exit_now = false;
4177 WaitForEventsPrivate (NULL, event_sp, control_only);
4178 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4181 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
4183 switch (event_sp->GetType())
4185 case eBroadcastInternalStateControlStop:
4187 break; // doing any internal state managment below
4189 case eBroadcastInternalStateControlPause:
4190 control_only = true;
4193 case eBroadcastInternalStateControlResume:
4194 control_only = false;
4198 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4201 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4203 if (m_public_state.GetValue() == eStateAttaching)
4206 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
4207 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4212 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
4218 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4220 if (internal_state != eStateInvalid)
4222 if (m_clear_thread_plans_on_stop &&
4223 StateIsStoppedState(internal_state, true))
4225 m_clear_thread_plans_on_stop = false;
4226 m_thread_list.DiscardThreadPlans();
4228 HandlePrivateEvent (event_sp);
4231 if (internal_state == eStateInvalid ||
4232 internal_state == eStateExited ||
4233 internal_state == eStateDetached )
4236 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
4242 // Verify log is still enabled before attempting to write to it...
4244 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
4246 m_public_run_lock.SetStopped();
4247 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4248 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
4252 //------------------------------------------------------------------
4253 // Process Event Data
4254 //------------------------------------------------------------------
4256 Process::ProcessEventData::ProcessEventData () :
4259 m_state (eStateInvalid),
4260 m_restarted (false),
4262 m_interrupted (false)
4266 Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4268 m_process_sp (process_sp),
4270 m_restarted (false),
4272 m_interrupted (false)
4276 Process::ProcessEventData::~ProcessEventData()
4281 Process::ProcessEventData::GetFlavorString ()
4283 static ConstString g_flavor ("Process::ProcessEventData");
4288 Process::ProcessEventData::GetFlavor () const
4290 return ProcessEventData::GetFlavorString ();
4294 Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4296 // This function gets called twice for each event, once when the event gets pulled
4297 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4298 // the public event queue, then other times when we're pretending that this is where we stopped at the
4299 // end of expression evaluation. m_update_state is used to distinguish these
4300 // three cases; it is 0 when we're just pulling it off for private handling,
4301 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
4302 if (m_update_state != 1)
4305 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4307 // If we're stopped and haven't restarted, then do the breakpoint commands here:
4308 if (m_state == eStateStopped && ! m_restarted)
4310 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
4311 uint32_t num_threads = curr_thread_list.GetSize();
4314 // The actions might change one of the thread's stop_info's opinions about whether we should
4315 // stop the process, so we need to query that as we go.
4317 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4318 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4319 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4320 // 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
4321 // against this list & bag out if anything differs.
4322 std::vector<uint32_t> thread_index_array(num_threads);
4323 for (idx = 0; idx < num_threads; ++idx)
4324 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4326 // Use this to track whether we should continue from here. We will only continue the target running if
4327 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4328 // then it doesn't matter what the other threads say...
4330 bool still_should_stop = false;
4332 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4333 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4334 // thing to do is, and it's better to let the user decide than continue behind their backs.
4336 bool does_anybody_have_an_opinion = false;
4338 for (idx = 0; idx < num_threads; ++idx)
4340 curr_thread_list = m_process_sp->GetThreadList();
4341 if (curr_thread_list.GetSize() != num_threads)
4343 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
4345 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
4349 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4351 if (thread_sp->GetIndexID() != thread_index_array[idx])
4353 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
4355 log->Printf("The thread at position %u changed from %u to %u while processing event.",
4357 thread_index_array[idx],
4358 thread_sp->GetIndexID());
4362 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
4363 if (stop_info_sp && stop_info_sp->IsValid())
4365 does_anybody_have_an_opinion = true;
4366 bool this_thread_wants_to_stop;
4367 if (stop_info_sp->GetOverrideShouldStop())
4369 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4373 stop_info_sp->PerformAction(event_ptr);
4374 // The stop action might restart the target. If it does, then we want to mark that in the
4375 // event so that whoever is receiving it will know to wait for the running event and reflect
4376 // that state appropriately.
4377 // We also need to stop processing actions, since they aren't expecting the target to be running.
4379 // FIXME: we might have run.
4380 if (stop_info_sp->HasTargetRunSinceMe())
4382 SetRestarted (true);
4386 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4389 if (still_should_stop == false)
4390 still_should_stop = this_thread_wants_to_stop;
4395 if (!GetRestarted())
4397 if (!still_should_stop && does_anybody_have_an_opinion)
4399 // We've been asked to continue, so do that here.
4401 // Use the public resume method here, since this is just
4402 // extending a public resume.
4403 m_process_sp->PrivateResume();
4407 // If we didn't restart, run the Stop Hooks here:
4408 // They might also restart the target, so watch for that.
4409 m_process_sp->GetTarget().RunStopHooks();
4410 if (m_process_sp->GetPrivateState() == eStateRunning)
4418 Process::ProcessEventData::Dump (Stream *s) const
4421 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
4423 s->Printf("state = %s", StateAsCString(GetState()));
4426 const Process::ProcessEventData *
4427 Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4431 const EventData *event_data = event_ptr->GetData();
4432 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4433 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4439 Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4441 ProcessSP process_sp;
4442 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4444 process_sp = data->GetProcessSP();
4449 Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4451 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4453 return eStateInvalid;
4455 return data->GetState();
4459 Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4461 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4465 return data->GetRestarted();
4469 Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4471 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4473 data->SetRestarted(new_value);
4477 Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4479 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4481 return data->GetNumRestartedReasons();
4487 Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4489 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4491 return data->GetRestartedReasonAtIndex(idx);
4497 Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4499 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4501 data->AddRestartedReason(reason);
4505 Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4507 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4511 return data->GetInterrupted ();
4515 Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4517 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4519 data->SetInterrupted(new_value);
4523 Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4525 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4528 data->SetUpdateStateOnRemoval();
4535 Process::CalculateTarget ()
4537 return m_target.shared_from_this();
4541 Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
4543 exe_ctx.SetTargetPtr (&m_target);
4544 exe_ctx.SetProcessPtr (this);
4545 exe_ctx.SetThreadPtr(NULL);
4546 exe_ctx.SetFramePtr (NULL);
4550 //Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4556 //Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4558 // return Host::GetArchSpecForExistingProcess (pid);
4562 //Process::GetArchSpecForExistingProcess (const char *process_name)
4564 // return Host::GetArchSpecForExistingProcess (process_name);
4568 Process::AppendSTDOUT (const char * s, size_t len)
4570 Mutex::Locker locker (m_stdio_communication_mutex);
4571 m_stdout_data.append (s, len);
4572 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
4576 Process::AppendSTDERR (const char * s, size_t len)
4578 Mutex::Locker locker (m_stdio_communication_mutex);
4579 m_stderr_data.append (s, len);
4580 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
4584 Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
4586 Mutex::Locker locker (m_profile_data_comm_mutex);
4587 m_profile_data.push_back(one_profile_data);
4588 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4592 Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4594 Mutex::Locker locker(m_profile_data_comm_mutex);
4595 if (m_profile_data.empty())
4598 std::string &one_profile_data = m_profile_data.front();
4599 size_t bytes_available = one_profile_data.size();
4600 if (bytes_available > 0)
4602 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4604 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
4605 if (bytes_available > buf_size)
4607 memcpy(buf, one_profile_data.c_str(), buf_size);
4608 one_profile_data.erase(0, buf_size);
4609 bytes_available = buf_size;
4613 memcpy(buf, one_profile_data.c_str(), bytes_available);
4614 m_profile_data.erase(m_profile_data.begin());
4617 return bytes_available;
4621 //------------------------------------------------------------------
4623 //------------------------------------------------------------------
4626 Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4628 Mutex::Locker locker(m_stdio_communication_mutex);
4629 size_t bytes_available = m_stdout_data.size();
4630 if (bytes_available > 0)
4632 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4634 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
4635 if (bytes_available > buf_size)
4637 memcpy(buf, m_stdout_data.c_str(), buf_size);
4638 m_stdout_data.erase(0, buf_size);
4639 bytes_available = buf_size;
4643 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4644 m_stdout_data.clear();
4647 return bytes_available;
4652 Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4654 Mutex::Locker locker(m_stdio_communication_mutex);
4655 size_t bytes_available = m_stderr_data.size();
4656 if (bytes_available > 0)
4658 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4660 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
4661 if (bytes_available > buf_size)
4663 memcpy(buf, m_stderr_data.c_str(), buf_size);
4664 m_stderr_data.erase(0, buf_size);
4665 bytes_available = buf_size;
4669 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4670 m_stderr_data.clear();
4673 return bytes_available;
4677 Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4679 Process *process = (Process *) baton;
4680 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4684 Process::ResetProcessIOHandler ()
4686 m_process_input_reader.reset();
4690 class IOHandlerProcessSTDIO :
4694 IOHandlerProcessSTDIO (Process *process,
4696 IOHandler(process->GetTarget().GetDebugger()),
4697 m_process (process),
4699 m_write_file (write_fd, false),
4703 m_read_file.SetDescriptor(GetInputFD(), false);
4707 ~IOHandlerProcessSTDIO ()
4715 if (m_pipe_read.IsValid() && m_pipe_write.IsValid())
4720 // pipe is not supported on windows so default to a fail condition
4723 int err = pipe(fds);
4727 m_pipe_read.SetDescriptor(fds[0], true);
4728 m_pipe_write.SetDescriptor(fds[1], true);
4737 m_pipe_read.Close();
4738 m_pipe_write.Close();
4741 // Each IOHandler gets to run until it is done. It should read data
4742 // from the "in" and place output into "out" and "err and return
4747 if (m_read_file.IsValid() && m_write_file.IsValid())
4752 const int read_fd = m_read_file.GetDescriptor();
4753 const int pipe_read_fd = m_pipe_read.GetDescriptor();
4754 TerminalState terminal_state;
4755 terminal_state.Save (read_fd, false);
4756 Terminal terminal(read_fd);
4757 terminal.SetCanonical(false);
4758 terminal.SetEcho(false);
4759 // FD_ZERO, FD_SET are not supported on windows
4761 while (!GetIsDone())
4764 FD_ZERO (&read_fdset);
4765 FD_SET (read_fd, &read_fdset);
4766 FD_SET (pipe_read_fd, &read_fdset);
4767 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4768 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4769 if (num_set_fds < 0)
4771 const int select_errno = errno;
4773 if (select_errno != EINTR)
4776 else if (num_set_fds > 0)
4780 if (FD_ISSET (read_fd, &read_fdset))
4783 if (m_read_file.Read(&ch, n).Success() && n == 1)
4785 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4791 if (FD_ISSET (pipe_read_fd, &read_fdset))
4793 // Consume the interrupt byte
4795 m_pipe_read.Read (&ch, n);
4801 terminal_state.Restore();
4811 // Hide any characters that have been displayed so far so async
4812 // output can be displayed. Refresh() will be called after the
4813 // output has been displayed.
4819 // Called when the async output has been received in order to update
4820 // the input reader (refresh the prompt and redisplay any current
4821 // line(s) that are being edited
4833 m_pipe_write.Write (&ch, n);
4839 if (StateIsRunningState(m_process->GetState()))
4840 m_process->SendAsyncInterrupt();
4851 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4852 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
4859 Process::WatchForSTDIN (IOHandler &io_handler)
4864 Process::CancelWatchForSTDIN (bool exited)
4866 if (m_process_input_reader)
4869 m_process_input_reader->SetIsDone(true);
4870 m_process_input_reader->Cancel();
4875 Process::SetSTDIOFileDescriptor (int fd)
4877 // First set up the Read Thread for reading/handling process I/O
4879 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
4883 m_stdio_communication.SetConnection (conn_ap.release());
4884 if (m_stdio_communication.IsConnected())
4886 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4887 m_stdio_communication.StartReadThread();
4889 // Now read thread is set up, set up input reader.
4891 if (!m_process_input_reader.get())
4892 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
4898 Process::PushProcessIOHandler ()
4900 IOHandlerSP io_handler_sp (m_process_input_reader);
4903 io_handler_sp->SetIsDone(false);
4904 m_target.GetDebugger().PushIOHandler (io_handler_sp);
4909 Process::PopProcessIOHandler ()
4911 IOHandlerSP io_handler_sp (m_process_input_reader);
4914 io_handler_sp->Cancel();
4915 m_target.GetDebugger().PopIOHandler (io_handler_sp);
4919 // The process needs to know about installed plug-ins
4921 Process::SettingsInitialize ()
4923 Thread::SettingsInitialize ();
4927 Process::SettingsTerminate ()
4929 Thread::SettingsTerminate ();
4933 Process::RunThreadPlan (ExecutionContext &exe_ctx,
4934 lldb::ThreadPlanSP &thread_plan_sp,
4935 const EvaluateExpressionOptions &options,
4938 ExecutionResults return_value = eExecutionSetupError;
4940 if (thread_plan_sp.get() == NULL)
4942 errors.Printf("RunThreadPlan called with empty thread plan.");
4943 return eExecutionSetupError;
4946 if (!thread_plan_sp->ValidatePlan(NULL))
4948 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4949 return eExecutionSetupError;
4952 if (exe_ctx.GetProcessPtr() != this)
4954 errors.Printf("RunThreadPlan called on wrong process.");
4955 return eExecutionSetupError;
4958 Thread *thread = exe_ctx.GetThreadPtr();
4961 errors.Printf("RunThreadPlan called with invalid thread.");
4962 return eExecutionSetupError;
4965 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4966 // For that to be true the plan can't be private - since private plans suppress themselves in the
4967 // GetCompletedPlan call.
4969 bool orig_plan_private = thread_plan_sp->GetPrivate();
4970 thread_plan_sp->SetPrivate(false);
4972 if (m_private_state.GetValue() != eStateStopped)
4974 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
4975 return eExecutionSetupError;
4978 // Save the thread & frame from the exe_ctx for restoration after we run
4979 const uint32_t thread_idx_id = thread->GetIndexID();
4980 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4981 if (!selected_frame_sp)
4983 thread->SetSelectedFrame(0);
4984 selected_frame_sp = thread->GetSelectedFrame();
4985 if (!selected_frame_sp)
4987 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
4988 return eExecutionSetupError;
4992 StackID ctx_frame_id = selected_frame_sp->GetStackID();
4994 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4995 // so we should arrange to reset them as well.
4997 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
4999 uint32_t selected_tid;
5000 StackID selected_stack_id;
5001 if (selected_thread_sp)
5003 selected_tid = selected_thread_sp->GetIndexID();
5004 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
5008 selected_tid = LLDB_INVALID_THREAD_ID;
5011 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
5012 lldb::StateType old_state;
5013 lldb::ThreadPlanSP stopper_base_plan_sp;
5015 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
5016 if (Host::GetCurrentThread() == m_private_state_thread)
5018 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5019 // we are the thread that is generating public events.
5020 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
5021 // we are fielding public events here.
5023 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
5026 backup_private_state_thread = m_private_state_thread;
5028 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5029 // returning control here.
5030 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5031 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5032 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5033 // do just what we want.
5034 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5035 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5036 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5037 old_state = m_public_state.GetValue();
5038 m_public_state.SetValueNoLock(eStateStopped);
5040 // Now spin up the private state thread:
5041 StartPrivateStateThread(true);
5044 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
5046 if (options.GetDebug())
5048 // In this case, we aren't actually going to run, we just want to stop right away.
5049 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5050 // FIXME: To make this prettier we should invent some stop reason for this, but that
5051 // is only cosmetic, and this functionality is only of use to lldb developers who can
5052 // live with not pretty...
5054 return eExecutionStoppedForDebug;
5057 Listener listener("lldb.process.listener.run-thread-plan");
5059 lldb::EventSP event_to_broadcast_sp;
5062 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5063 // restored on exit to the function.
5065 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5066 // is put into event_to_broadcast_sp for rebroadcasting.
5068 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
5073 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
5074 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
5075 thread->GetIndexID(),
5081 lldb::EventSP event_sp;
5082 lldb::StateType stop_state = lldb::eStateInvalid;
5084 TimeValue* timeout_ptr = NULL;
5085 TimeValue real_timeout;
5087 bool before_first_timeout = true; // This is set to false the first time that we have to halt the target.
5088 bool do_resume = true;
5089 bool handle_running_event = true;
5090 const uint64_t default_one_thread_timeout_usec = 250000;
5092 // This is just for accounting:
5093 uint32_t num_resumes = 0;
5095 TimeValue one_thread_timeout = TimeValue::Now();
5096 TimeValue final_timeout = one_thread_timeout;
5098 uint32_t timeout_usec = options.GetTimeoutUsec();
5099 if (options.GetTryAllThreads())
5101 // If we are running all threads then we take half the time to run all threads, bounded by
5103 if (options.GetTimeoutUsec() == 0)
5104 one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
5107 uint64_t computed_timeout = timeout_usec / 2;
5108 if (computed_timeout > default_one_thread_timeout_usec)
5109 computed_timeout = default_one_thread_timeout_usec;
5110 one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
5112 final_timeout.OffsetWithMicroSeconds (timeout_usec);
5116 if (timeout_usec != 0)
5117 final_timeout.OffsetWithMicroSeconds(timeout_usec);
5120 // This isn't going to work if there are unfetched events on the queue.
5121 // Are there cases where we might want to run the remaining events here, and then try to
5122 // call the function? That's probably being too tricky for our own good.
5124 Event *other_events = listener.PeekAtNextEvent();
5125 if (other_events != NULL)
5127 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
5128 return eExecutionSetupError;
5131 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5132 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5133 // event coalescing to cause us to lose OUR running event...
5134 ForceNextEventDelivery();
5136 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5137 // So don't call return anywhere within it.
5141 // We usually want to resume the process if we get to the top of the loop.
5142 // The only exception is if we get two running events with no intervening
5143 // stop, which can happen, we will just wait for then next stop event.
5145 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5147 handle_running_event,
5148 before_first_timeout);
5150 if (do_resume || handle_running_event)
5152 // Do the initial resume and wait for the running event before going further.
5157 Error resume_error = PrivateResume ();
5158 if (!resume_error.Success())
5160 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5162 resume_error.AsCString());
5163 return_value = eExecutionSetupError;
5168 TimeValue resume_timeout = TimeValue::Now();
5169 resume_timeout.OffsetWithMicroSeconds(500000);
5171 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
5175 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5178 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
5179 return_value = eExecutionSetupError;
5183 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5185 if (stop_state != eStateRunning)
5187 bool restarted = false;
5189 if (stop_state == eStateStopped)
5191 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5193 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5194 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5196 StateAsCString(stop_state),
5199 handle_running_event);
5204 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5205 // event here. But if I do, the best thing is to Halt and then get out of here.
5209 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5210 StateAsCString(stop_state));
5211 return_value = eExecutionSetupError;
5216 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5217 // We need to call the function synchronously, so spin waiting for it to return.
5218 // If we get interrupted while executing, we're going to lose our context, and
5219 // won't be able to gather the result at this point.
5220 // We set the timeout AFTER the resume, since the resume takes some time and we
5221 // don't want to charge that to the timeout.
5226 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
5229 if (before_first_timeout)
5231 if (options.GetTryAllThreads())
5232 timeout_ptr = &one_thread_timeout;
5235 if (timeout_usec == 0)
5238 timeout_ptr = &final_timeout;
5243 if (timeout_usec == 0)
5246 timeout_ptr = &final_timeout;
5250 handle_running_event = true;
5252 // Now wait for the process to stop again:
5259 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
5260 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5261 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
5265 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5269 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
5275 bool keep_going = false;
5276 if (event_sp->GetType() == eBroadcastBitInterrupt)
5279 return_value = eExecutionInterrupted;
5280 errors.Printf ("Execution halted by user interrupt.");
5282 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
5287 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5289 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
5293 case lldb::eStateStopped:
5295 // We stopped, figure out what we are going to do now.
5296 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5299 // Ooh, our thread has vanished. Unlikely that this was successful execution...
5301 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
5302 return_value = eExecutionInterrupted;
5306 // If we were restarted, we just need to go back up to fetch another event.
5307 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5311 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5315 handle_running_event = true;
5321 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5322 StopReason stop_reason = eStopReasonInvalid;
5324 stop_reason = stop_info_sp->GetStopReason();
5327 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5328 // it is OUR plan that is complete?
5329 if (stop_reason == eStopReasonPlanComplete)
5332 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5333 // Now mark this plan as private so it doesn't get reported as the stop reason
5334 // after this point.
5336 thread_plan_sp->SetPrivate (orig_plan_private);
5337 return_value = eExecutionCompleted;
5341 // Something restarted the target, so just wait for it to stop for real.
5342 if (stop_reason == eStopReasonBreakpoint)
5345 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
5346 return_value = eExecutionHitBreakpoint;
5347 if (!options.DoesIgnoreBreakpoints())
5349 event_to_broadcast_sp = event_sp;
5355 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
5356 if (!options.DoesUnwindOnError())
5357 event_to_broadcast_sp = event_sp;
5358 return_value = eExecutionInterrupted;
5366 case lldb::eStateRunning:
5367 // This shouldn't really happen, but sometimes we do get two running events without an
5368 // intervening stop, and in that case we should just go back to waiting for the stop.
5371 handle_running_event = false;
5376 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
5378 if (stop_state == eStateExited)
5379 event_to_broadcast_sp = event_sp;
5381 errors.Printf ("Execution stopped with unexpected state.\n");
5382 return_value = eExecutionInterrupted;
5395 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
5396 return_value = eExecutionInterrupted;
5402 // If we didn't get an event that means we've timed out...
5403 // We will interrupt the process here. Depending on what we were asked to do we will
5404 // either exit, or try with all threads running for the same timeout.
5407 if (options.GetTryAllThreads())
5409 uint64_t remaining_time = final_timeout - TimeValue::Now();
5410 if (before_first_timeout)
5411 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
5412 "running till for %" PRIu64 " usec with all threads enabled.",
5415 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
5416 "and timeout: %u timed out, abandoning execution.",
5420 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
5421 "abandoning execution.",
5425 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5426 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5427 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5428 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5429 // stopped event. That's what this while loop does.
5431 bool back_to_top = true;
5432 uint32_t try_halt_again = 0;
5433 bool do_halt = true;
5434 const uint32_t num_retries = 5;
5435 while (try_halt_again < num_retries)
5441 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5442 halt_error = Halt();
5444 if (halt_error.Success())
5447 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
5449 real_timeout = TimeValue::Now();
5450 real_timeout.OffsetWithMicroSeconds(500000);
5452 got_event = listener.WaitForEvent(&real_timeout, event_sp);
5456 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5459 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5460 if (stop_state == lldb::eStateStopped
5461 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5462 log->PutCString (" Event was the Halt interruption event.");
5465 if (stop_state == lldb::eStateStopped)
5467 // Between the time we initiated the Halt and the time we delivered it, the process could have
5468 // already finished its job. Check that here:
5470 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5473 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5474 "Exiting wait loop.");
5475 return_value = eExecutionCompleted;
5476 back_to_top = false;
5480 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5483 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5484 "Exiting wait loop.");
5490 if (!options.GetTryAllThreads())
5493 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5494 return_value = eExecutionInterrupted;
5495 back_to_top = false;
5499 if (before_first_timeout)
5501 // Set all the other threads to run, and return to the top of the loop, which will continue;
5502 before_first_timeout = false;
5503 thread_plan_sp->SetStopOthers (false);
5505 log->PutCString ("Process::RunThreadPlan(): about to resume.");
5512 // Running all threads failed, so return Interrupted.
5514 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5515 return_value = eExecutionInterrupted;
5516 back_to_top = false;
5523 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5524 "I'm getting out of here passing Interrupted.");
5525 return_value = eExecutionInterrupted;
5526 back_to_top = false;
5537 if (!back_to_top || try_halt_again > num_retries)
5544 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5545 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5547 StopPrivateStateThread();
5549 m_private_state_thread = backup_private_state_thread;
5550 if (stopper_base_plan_sp)
5552 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5554 m_public_state.SetValueNoLock(old_state);
5558 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5560 // 1) The execution successfully completed
5561 // 2) We hit a breakpoint, and ignore_breakpoints was true
5562 // 3) We got some other error, and discard_on_error was true
5563 bool should_unwind = (return_value == eExecutionInterrupted && options.DoesUnwindOnError())
5564 || (return_value == eExecutionHitBreakpoint && options.DoesIgnoreBreakpoints());
5566 if (return_value == eExecutionCompleted
5569 thread_plan_sp->RestoreThreadState();
5572 // Now do some processing on the results of the run:
5573 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
5579 event_sp->Dump (&s);
5582 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5587 const char *event_explanation = NULL;
5593 event_explanation = "<no event>";
5596 else if (event_sp->GetType() == eBroadcastBitInterrupt)
5598 event_explanation = "<user interrupt>";
5603 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5607 event_explanation = "<no event data>";
5611 Process *process = event_data->GetProcessSP().get();
5615 event_explanation = "<no process>";
5619 ThreadList &thread_list = process->GetThreadList();
5621 uint32_t num_threads = thread_list.GetSize();
5622 uint32_t thread_index;
5624 ts.Printf("<%u threads> ", num_threads);
5626 for (thread_index = 0;
5627 thread_index < num_threads;
5630 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5638 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5639 RegisterContext *register_context = thread->GetRegisterContext().get();
5641 if (register_context)
5642 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5644 ts.Printf("[ip unknown] ");
5646 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5649 const char *stop_desc = stop_info_sp->GetDescription();
5651 ts.PutCString (stop_desc);
5656 event_explanation = ts.GetData();
5660 if (event_explanation)
5661 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
5663 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5669 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5670 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5671 thread_plan_sp->SetPrivate (orig_plan_private);
5676 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
5679 else if (return_value == eExecutionSetupError)
5682 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5684 if (options.DoesUnwindOnError())
5686 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5687 thread_plan_sp->SetPrivate (orig_plan_private);
5692 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5695 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5696 return_value = eExecutionCompleted;
5698 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5701 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5702 return_value = eExecutionDiscarded;
5707 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
5708 if (options.DoesUnwindOnError() && thread_plan_sp)
5711 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
5712 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5713 thread_plan_sp->SetPrivate (orig_plan_private);
5718 // Thread we ran the function in may have gone away because we ran the target
5719 // Check that it's still there, and if it is put it back in the context. Also restore the
5720 // frame in the context if it is still present.
5721 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5724 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5727 // Also restore the current process'es selected frame & thread, since this function calling may
5728 // be done behind the user's back.
5730 if (selected_tid != LLDB_INVALID_THREAD_ID)
5732 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5734 // We were able to restore the selected thread, now restore the frame:
5735 Mutex::Locker lock(GetThreadList().GetMutex());
5736 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
5738 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
5743 // If the process exited during the run of the thread plan, notify everyone.
5745 if (event_to_broadcast_sp)
5748 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5749 BroadcastEvent(event_to_broadcast_sp);
5752 return return_value;
5756 Process::ExecutionResultAsCString (ExecutionResults result)
5758 const char *result_name;
5762 case eExecutionCompleted:
5763 result_name = "eExecutionCompleted";
5765 case eExecutionDiscarded:
5766 result_name = "eExecutionDiscarded";
5768 case eExecutionInterrupted:
5769 result_name = "eExecutionInterrupted";
5771 case eExecutionHitBreakpoint:
5772 result_name = "eExecutionHitBreakpoint";
5774 case eExecutionSetupError:
5775 result_name = "eExecutionSetupError";
5777 case eExecutionTimedOut:
5778 result_name = "eExecutionTimedOut";
5780 case eExecutionStoppedForDebug:
5781 result_name = "eExecutionStoppedForDebug";
5788 Process::GetStatus (Stream &strm)
5790 const StateType state = GetState();
5791 if (StateIsStoppedState(state, false))
5793 if (state == eStateExited)
5795 int exit_status = GetExitStatus();
5796 const char *exit_description = GetExitDescription();
5797 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5801 exit_description ? exit_description : "");
5805 if (state == eStateConnected)
5806 strm.Printf ("Connected to remote target.\n");
5808 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
5813 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
5818 Process::GetThreadStatus (Stream &strm,
5819 bool only_threads_with_stop_reason,
5820 uint32_t start_frame,
5821 uint32_t num_frames,
5822 uint32_t num_frames_with_source)
5824 size_t num_thread_infos_dumped = 0;
5826 Mutex::Locker locker (GetThreadList().GetMutex());
5827 const size_t num_threads = GetThreadList().GetSize();
5828 for (uint32_t i = 0; i < num_threads; i++)
5830 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5833 if (only_threads_with_stop_reason)
5835 StopInfoSP stop_info_sp = thread->GetStopInfo();
5836 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
5839 thread->GetStatus (strm,
5842 num_frames_with_source);
5843 ++num_thread_infos_dumped;
5846 return num_thread_infos_dumped;
5850 Process::AddInvalidMemoryRegion (const LoadRange ®ion)
5852 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5856 Process::RemoveInvalidMemoryRange (const LoadRange ®ion)
5858 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5862 Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5864 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5868 Process::RunPreResumeActions ()
5871 while (!m_pre_resume_actions.empty())
5873 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5874 m_pre_resume_actions.pop_back();
5875 bool this_result = action.callback (action.baton);
5876 if (result == true) result = this_result;
5882 Process::ClearPreResumeActions ()
5884 m_pre_resume_actions.clear();
5890 m_thread_list.Flush();
5891 m_extended_thread_list.Flush();
5892 m_extended_thread_stop_id = 0;
5893 m_queue_list.Clear();
5894 m_queue_list_stop_id = 0;
5900 Target &target = GetTarget();
5901 target.CleanupProcess ();
5902 target.ClearModules(false);
5903 m_dynamic_checkers_ap.reset();
5905 m_system_runtime_ap.reset();
5908 m_image_tokens.clear();
5909 m_allocated_memory_cache.Clear();
5910 m_language_runtimes.clear();
5911 m_thread_list.DiscardThreadPlans();
5912 m_memory_cache.Clear(true);
5915 // Flush the process (threads and all stack frames) after running CompleteAttach()
5916 // in case the dynamic loader loaded things in new locations.
5919 // After we figure out what was loaded/unloaded in CompleteAttach,
5920 // we need to let the target know so it can do any cleanup it needs to.
5925 Process::ResolveIndirectFunction(const Address *address, Error &error)
5927 if (address == nullptr)
5929 error.SetErrorString("Invalid address argument");
5930 return LLDB_INVALID_ADDRESS;
5933 addr_t function_addr = LLDB_INVALID_ADDRESS;
5935 addr_t addr = address->GetLoadAddress(&GetTarget());
5936 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
5937 if (iter != m_resolved_indirect_addresses.end())
5939 function_addr = (*iter).second;
5943 if (!InferiorCall(this, address, function_addr))
5945 Symbol *symbol = address->CalculateSymbolContextSymbol();
5946 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
5947 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5948 function_addr = LLDB_INVALID_ADDRESS;
5952 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
5955 return function_addr;