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 //===----------------------------------------------------------------------===//
15 // Other libraries and framework includes
16 #include "llvm/Support/ScopedPrinter.h"
17 #include "llvm/Support/Threading.h"
20 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
21 #include "lldb/Breakpoint/BreakpointLocation.h"
22 #include "lldb/Breakpoint/StoppointCallbackContext.h"
23 #include "lldb/Core/Debugger.h"
24 #include "lldb/Core/Event.h"
25 #include "lldb/Core/Module.h"
26 #include "lldb/Core/ModuleSpec.h"
27 #include "lldb/Core/PluginManager.h"
28 #include "lldb/Core/State.h"
29 #include "lldb/Core/StreamFile.h"
30 #include "lldb/Expression/DiagnosticManager.h"
31 #include "lldb/Expression/IRDynamicChecks.h"
32 #include "lldb/Expression/UserExpression.h"
33 #include "lldb/Host/ConnectionFileDescriptor.h"
34 #include "lldb/Host/FileSystem.h"
35 #include "lldb/Host/Host.h"
36 #include "lldb/Host/HostInfo.h"
37 #include "lldb/Host/OptionParser.h"
38 #include "lldb/Host/Pipe.h"
39 #include "lldb/Host/Terminal.h"
40 #include "lldb/Host/ThreadLauncher.h"
41 #include "lldb/Interpreter/CommandInterpreter.h"
42 #include "lldb/Interpreter/OptionValueProperties.h"
43 #include "lldb/Symbol/Function.h"
44 #include "lldb/Symbol/Symbol.h"
45 #include "lldb/Target/ABI.h"
46 #include "lldb/Target/CPPLanguageRuntime.h"
47 #include "lldb/Target/DynamicLoader.h"
48 #include "lldb/Target/InstrumentationRuntime.h"
49 #include "lldb/Target/JITLoader.h"
50 #include "lldb/Target/JITLoaderList.h"
51 #include "lldb/Target/LanguageRuntime.h"
52 #include "lldb/Target/MemoryHistory.h"
53 #include "lldb/Target/MemoryRegionInfo.h"
54 #include "lldb/Target/ObjCLanguageRuntime.h"
55 #include "lldb/Target/OperatingSystem.h"
56 #include "lldb/Target/Platform.h"
57 #include "lldb/Target/Process.h"
58 #include "lldb/Target/RegisterContext.h"
59 #include "lldb/Target/StopInfo.h"
60 #include "lldb/Target/StructuredDataPlugin.h"
61 #include "lldb/Target/SystemRuntime.h"
62 #include "lldb/Target/Target.h"
63 #include "lldb/Target/TargetList.h"
64 #include "lldb/Target/Thread.h"
65 #include "lldb/Target/ThreadPlan.h"
66 #include "lldb/Target/ThreadPlanBase.h"
67 #include "lldb/Target/UnixSignals.h"
68 #include "lldb/Utility/Log.h"
69 #include "lldb/Utility/NameMatches.h"
70 #include "lldb/Utility/SelectHelper.h"
73 using namespace lldb_private;
74 using namespace std::chrono;
76 // Comment out line below to disable memory caching, overriding the process
77 // setting target.process.disable-memory-cache
78 #define ENABLE_MEMORY_CACHING
80 #ifdef ENABLE_MEMORY_CACHING
81 #define DISABLE_MEM_CACHE_DEFAULT false
83 #define DISABLE_MEM_CACHE_DEFAULT true
86 class ProcessOptionValueProperties : public OptionValueProperties {
88 ProcessOptionValueProperties(const ConstString &name)
89 : OptionValueProperties(name) {}
91 // This constructor is used when creating ProcessOptionValueProperties when it
92 // is part of a new lldb_private::Process instance. It will copy all current
93 // global property values as needed
94 ProcessOptionValueProperties(ProcessProperties *global_properties)
95 : OptionValueProperties(*global_properties->GetValueProperties()) {}
97 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
99 uint32_t idx) const override {
100 // When getting the value for a key from the process options, we will always
101 // try and grab the setting from the current process if there is one. Else
103 // use the one from this instance.
105 Process *process = exe_ctx->GetProcessPtr();
107 ProcessOptionValueProperties *instance_properties =
108 static_cast<ProcessOptionValueProperties *>(
109 process->GetValueProperties().get());
110 if (this != instance_properties)
111 return instance_properties->ProtectedGetPropertyAtIndex(idx);
114 return ProtectedGetPropertyAtIndex(idx);
118 static PropertyDefinition g_properties[] = {
119 {"disable-memory-cache", OptionValue::eTypeBoolean, false,
120 DISABLE_MEM_CACHE_DEFAULT, nullptr, nullptr,
121 "Disable reading and caching of memory in fixed-size units."},
122 {"extra-startup-command", OptionValue::eTypeArray, false,
123 OptionValue::eTypeString, nullptr, nullptr,
124 "A list containing extra commands understood by the particular process "
126 "For instance, to turn on debugserver logging set this to "
127 "\"QSetLogging:bitmask=LOG_DEFAULT;\""},
128 {"ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true,
130 "If true, breakpoints will be ignored during expression evaluation."},
131 {"unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true,
132 nullptr, nullptr, "If true, errors in expression evaluation will unwind "
133 "the stack back to the state before the call."},
134 {"python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, nullptr,
135 nullptr, "A path to a python OS plug-in module file that contains a "
136 "OperatingSystemPlugIn class."},
137 {"stop-on-sharedlibrary-events", OptionValue::eTypeBoolean, true, false,
139 "If true, stop when a shared library is loaded or unloaded."},
140 {"detach-keeps-stopped", OptionValue::eTypeBoolean, true, false, nullptr,
141 nullptr, "If true, detach will attempt to keep the process stopped."},
142 {"memory-cache-line-size", OptionValue::eTypeUInt64, false, 512, nullptr,
143 nullptr, "The memory cache line size"},
144 {"optimization-warnings", OptionValue::eTypeBoolean, false, true, nullptr,
145 nullptr, "If true, warn when stopped in code that is optimized where "
146 "stepping and variable availability may not behave as expected."},
147 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
150 ePropertyDisableMemCache,
151 ePropertyExtraStartCommand,
152 ePropertyIgnoreBreakpointsInExpressions,
153 ePropertyUnwindOnErrorInExpressions,
154 ePropertyPythonOSPluginPath,
155 ePropertyStopOnSharedLibraryEvents,
156 ePropertyDetachKeepsStopped,
157 ePropertyMemCacheLineSize,
158 ePropertyWarningOptimization
161 ProcessProperties::ProcessProperties(lldb_private::Process *process)
163 m_process(process) // Can be nullptr for global ProcessProperties
165 if (process == nullptr) {
166 // Global process properties, set them up one time
167 m_collection_sp.reset(
168 new ProcessOptionValueProperties(ConstString("process")));
169 m_collection_sp->Initialize(g_properties);
170 m_collection_sp->AppendProperty(
171 ConstString("thread"), ConstString("Settings specific to threads."),
172 true, Thread::GetGlobalProperties()->GetValueProperties());
174 m_collection_sp.reset(
175 new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
176 m_collection_sp->SetValueChangedCallback(
177 ePropertyPythonOSPluginPath,
178 ProcessProperties::OptionValueChangedCallback, this);
182 ProcessProperties::~ProcessProperties() = default;
184 void ProcessProperties::OptionValueChangedCallback(void *baton,
185 OptionValue *option_value) {
186 ProcessProperties *properties = (ProcessProperties *)baton;
187 if (properties->m_process)
188 properties->m_process->LoadOperatingSystemPlugin(true);
191 bool ProcessProperties::GetDisableMemoryCache() const {
192 const uint32_t idx = ePropertyDisableMemCache;
193 return m_collection_sp->GetPropertyAtIndexAsBoolean(
194 nullptr, idx, g_properties[idx].default_uint_value != 0);
197 uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
198 const uint32_t idx = ePropertyMemCacheLineSize;
199 return m_collection_sp->GetPropertyAtIndexAsUInt64(
200 nullptr, idx, g_properties[idx].default_uint_value);
203 Args ProcessProperties::GetExtraStartupCommands() const {
205 const uint32_t idx = ePropertyExtraStartCommand;
206 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
210 void ProcessProperties::SetExtraStartupCommands(const Args &args) {
211 const uint32_t idx = ePropertyExtraStartCommand;
212 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
215 FileSpec ProcessProperties::GetPythonOSPluginPath() const {
216 const uint32_t idx = ePropertyPythonOSPluginPath;
217 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
220 void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
221 const uint32_t idx = ePropertyPythonOSPluginPath;
222 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
225 bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
226 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
227 return m_collection_sp->GetPropertyAtIndexAsBoolean(
228 nullptr, idx, g_properties[idx].default_uint_value != 0);
231 void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
232 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
233 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
236 bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
237 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
238 return m_collection_sp->GetPropertyAtIndexAsBoolean(
239 nullptr, idx, g_properties[idx].default_uint_value != 0);
242 void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
243 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
244 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
247 bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
248 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
249 return m_collection_sp->GetPropertyAtIndexAsBoolean(
250 nullptr, idx, g_properties[idx].default_uint_value != 0);
253 void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
254 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
255 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
258 bool ProcessProperties::GetDetachKeepsStopped() const {
259 const uint32_t idx = ePropertyDetachKeepsStopped;
260 return m_collection_sp->GetPropertyAtIndexAsBoolean(
261 nullptr, idx, g_properties[idx].default_uint_value != 0);
264 void ProcessProperties::SetDetachKeepsStopped(bool stop) {
265 const uint32_t idx = ePropertyDetachKeepsStopped;
266 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
269 bool ProcessProperties::GetWarningsOptimization() const {
270 const uint32_t idx = ePropertyWarningOptimization;
271 return m_collection_sp->GetPropertyAtIndexAsBoolean(
272 nullptr, idx, g_properties[idx].default_uint_value != 0);
275 void ProcessInstanceInfo::Dump(Stream &s, Platform *platform) const {
277 if (m_pid != LLDB_INVALID_PROCESS_ID)
278 s.Printf(" pid = %" PRIu64 "\n", m_pid);
280 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
281 s.Printf(" parent = %" PRIu64 "\n", m_parent_pid);
284 s.Printf(" name = %s\n", m_executable.GetFilename().GetCString());
285 s.PutCString(" file = ");
286 m_executable.Dump(&s);
289 const uint32_t argc = m_arguments.GetArgumentCount();
291 for (uint32_t i = 0; i < argc; i++) {
292 const char *arg = m_arguments.GetArgumentAtIndex(i);
294 s.Printf(" arg[%u] = %s\n", i, arg);
296 s.Printf("arg[%u] = %s\n", i, arg);
300 const uint32_t envc = m_environment.GetArgumentCount();
302 for (uint32_t i = 0; i < envc; i++) {
303 const char *env = m_environment.GetArgumentAtIndex(i);
305 s.Printf(" env[%u] = %s\n", i, env);
307 s.Printf("env[%u] = %s\n", i, env);
311 if (m_arch.IsValid()) {
312 s.Printf(" arch = ");
313 m_arch.DumpTriple(s);
317 if (m_uid != UINT32_MAX) {
318 cstr = platform->GetUserName(m_uid);
319 s.Printf(" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
321 if (m_gid != UINT32_MAX) {
322 cstr = platform->GetGroupName(m_gid);
323 s.Printf(" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
325 if (m_euid != UINT32_MAX) {
326 cstr = platform->GetUserName(m_euid);
327 s.Printf(" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
329 if (m_egid != UINT32_MAX) {
330 cstr = platform->GetGroupName(m_egid);
331 s.Printf(" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
335 void ProcessInstanceInfo::DumpTableHeader(Stream &s, Platform *platform,
336 bool show_args, bool verbose) {
338 if (show_args || verbose)
344 s.Printf("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE "
347 s.PutCString("====== ====== ========== ========== ========== ========== "
348 "======================== ============================\n");
350 s.Printf("PID PARENT USER TRIPLE %s\n", label);
351 s.PutCString("====== ====== ========== ======================== "
352 "============================\n");
356 void ProcessInstanceInfo::DumpAsTableRow(Stream &s, Platform *platform,
357 bool show_args, bool verbose) const {
358 if (m_pid != LLDB_INVALID_PROCESS_ID) {
360 s.Printf("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
362 StreamString arch_strm;
363 if (m_arch.IsValid())
364 m_arch.DumpTriple(arch_strm);
367 cstr = platform->GetUserName(m_uid);
369 cstr[0]) // Watch for empty string that indicates lookup failed
370 s.Printf("%-10s ", cstr);
372 s.Printf("%-10u ", m_uid);
374 cstr = platform->GetGroupName(m_gid);
376 cstr[0]) // Watch for empty string that indicates lookup failed
377 s.Printf("%-10s ", cstr);
379 s.Printf("%-10u ", m_gid);
381 cstr = platform->GetUserName(m_euid);
383 cstr[0]) // Watch for empty string that indicates lookup failed
384 s.Printf("%-10s ", cstr);
386 s.Printf("%-10u ", m_euid);
388 cstr = platform->GetGroupName(m_egid);
390 cstr[0]) // Watch for empty string that indicates lookup failed
391 s.Printf("%-10s ", cstr);
393 s.Printf("%-10u ", m_egid);
395 s.Printf("%-24s ", arch_strm.GetData());
397 s.Printf("%-10s %-24s ", platform->GetUserName(m_euid),
398 arch_strm.GetData());
401 if (verbose || show_args) {
402 const uint32_t argc = m_arguments.GetArgumentCount();
404 for (uint32_t i = 0; i < argc; i++) {
407 s.PutCString(m_arguments.GetArgumentAtIndex(i));
411 s.PutCString(GetName());
418 Status ProcessLaunchCommandOptions::SetOptionValue(
419 uint32_t option_idx, llvm::StringRef option_arg,
420 ExecutionContext *execution_context) {
422 const int short_option = m_getopt_table[option_idx].val;
424 switch (short_option) {
425 case 's': // Stop at program entry point
426 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
429 case 'i': // STDIN for read only
432 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
433 launch_info.AppendFileAction(action);
437 case 'o': // Open STDOUT for write only
440 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
441 launch_info.AppendFileAction(action);
445 case 'e': // STDERR for write only
448 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
449 launch_info.AppendFileAction(action);
453 case 'p': // Process plug-in name
454 launch_info.SetProcessPluginName(option_arg);
457 case 'n': // Disable STDIO
460 const FileSpec dev_null{FileSystem::DEV_NULL, false};
461 if (action.Open(STDIN_FILENO, dev_null, true, false))
462 launch_info.AppendFileAction(action);
463 if (action.Open(STDOUT_FILENO, dev_null, false, true))
464 launch_info.AppendFileAction(action);
465 if (action.Open(STDERR_FILENO, dev_null, false, true))
466 launch_info.AppendFileAction(action);
471 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
474 case 't': // Open process in new terminal window
475 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
480 execution_context ? execution_context->GetTargetSP() : TargetSP();
481 PlatformSP platform_sp =
482 target_sp ? target_sp->GetPlatform() : PlatformSP();
483 if (!launch_info.GetArchitecture().SetTriple(option_arg, platform_sp.get()))
484 launch_info.GetArchitecture().SetTriple(option_arg);
487 case 'A': // Disable ASLR.
490 const bool disable_aslr_arg =
491 Args::StringToBoolean(option_arg, true, &success);
493 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
495 error.SetErrorStringWithFormat(
496 "Invalid boolean value for disable-aslr option: '%s'",
497 option_arg.empty() ? "<null>" : option_arg.str().c_str());
501 case 'X': // shell expand args.
504 const bool expand_args = Args::StringToBoolean(option_arg, true, &success);
506 launch_info.SetShellExpandArguments(expand_args);
508 error.SetErrorStringWithFormat(
509 "Invalid boolean value for shell-expand-args option: '%s'",
510 option_arg.empty() ? "<null>" : option_arg.str().c_str());
515 if (!option_arg.empty())
516 launch_info.SetShell(FileSpec(option_arg, false));
518 launch_info.SetShell(HostInfo::GetDefaultShell());
522 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
526 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
533 static OptionDefinition g_process_launch_options[] = {
534 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
535 nullptr, nullptr, 0, eArgTypeNone,
536 "Stop at the entry point of the program when launching a process."},
537 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
538 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
539 "Set whether to disable address space layout randomization when launching "
541 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
542 nullptr, nullptr, 0, eArgTypePlugin,
543 "Name of the process plugin you want to use."},
544 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
545 OptionParser::eRequiredArgument, nullptr, nullptr, 0,
546 eArgTypeDirectoryName,
547 "Set the current working directory to <path> when running the inferior."},
548 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
549 nullptr, nullptr, 0, eArgTypeArchitecture,
550 "Set the architecture for the process to launch when ambiguous."},
551 {LLDB_OPT_SET_ALL, false, "environment", 'v',
552 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone,
553 "Specify an environment variable name/value string (--environment "
554 "NAME=VALUE). Can be specified multiple times for subsequent environment "
556 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
557 OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeFilename,
558 "Run the process in a shell (not supported on all platforms)."},
560 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
561 nullptr, nullptr, 0, eArgTypeFilename,
562 "Redirect stdin for the process to <filename>."},
563 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
564 nullptr, nullptr, 0, eArgTypeFilename,
565 "Redirect stdout for the process to <filename>."},
566 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
567 nullptr, nullptr, 0, eArgTypeFilename,
568 "Redirect stderr for the process to <filename>."},
570 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
571 nullptr, 0, eArgTypeNone,
572 "Start the process in a terminal (not supported on all platforms)."},
574 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
575 nullptr, 0, eArgTypeNone,
576 "Do not set up for terminal I/O to go to running process."},
577 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
578 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
579 "Set whether to shell expand arguments to the process when launching."},
582 llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
583 return llvm::makeArrayRef(g_process_launch_options);
586 bool ProcessInstanceInfoMatch::NameMatches(const char *process_name) const {
587 if (m_name_match_type == NameMatch::Ignore || process_name == nullptr)
589 const char *match_name = m_match_info.GetName();
593 return lldb_private::NameMatches(process_name, m_name_match_type, match_name);
596 bool ProcessInstanceInfoMatch::Matches(
597 const ProcessInstanceInfo &proc_info) const {
598 if (!NameMatches(proc_info.GetName()))
601 if (m_match_info.ProcessIDIsValid() &&
602 m_match_info.GetProcessID() != proc_info.GetProcessID())
605 if (m_match_info.ParentProcessIDIsValid() &&
606 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
609 if (m_match_info.UserIDIsValid() &&
610 m_match_info.GetUserID() != proc_info.GetUserID())
613 if (m_match_info.GroupIDIsValid() &&
614 m_match_info.GetGroupID() != proc_info.GetGroupID())
617 if (m_match_info.EffectiveUserIDIsValid() &&
618 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
621 if (m_match_info.EffectiveGroupIDIsValid() &&
622 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
625 if (m_match_info.GetArchitecture().IsValid() &&
626 !m_match_info.GetArchitecture().IsCompatibleMatch(
627 proc_info.GetArchitecture()))
632 bool ProcessInstanceInfoMatch::MatchAllProcesses() const {
633 if (m_name_match_type != NameMatch::Ignore)
636 if (m_match_info.ProcessIDIsValid())
639 if (m_match_info.ParentProcessIDIsValid())
642 if (m_match_info.UserIDIsValid())
645 if (m_match_info.GroupIDIsValid())
648 if (m_match_info.EffectiveUserIDIsValid())
651 if (m_match_info.EffectiveGroupIDIsValid())
654 if (m_match_info.GetArchitecture().IsValid())
657 if (m_match_all_users)
663 void ProcessInstanceInfoMatch::Clear() {
664 m_match_info.Clear();
665 m_name_match_type = NameMatch::Ignore;
666 m_match_all_users = false;
669 ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
670 llvm::StringRef plugin_name,
671 ListenerSP listener_sp,
672 const FileSpec *crash_file_path) {
673 static uint32_t g_process_unique_id = 0;
675 ProcessSP process_sp;
676 ProcessCreateInstance create_callback = nullptr;
677 if (!plugin_name.empty()) {
678 ConstString const_plugin_name(plugin_name);
680 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
681 if (create_callback) {
682 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
684 if (process_sp->CanDebug(target_sp, true)) {
685 process_sp->m_process_unique_id = ++g_process_unique_id;
691 for (uint32_t idx = 0;
693 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
695 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
697 if (process_sp->CanDebug(target_sp, false)) {
698 process_sp->m_process_unique_id = ++g_process_unique_id;
708 ConstString &Process::GetStaticBroadcasterClass() {
709 static ConstString class_name("lldb.process");
713 Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
714 : Process(target_sp, listener_sp,
715 UnixSignals::Create(HostInfo::GetArchitecture())) {
716 // This constructor just delegates to the full Process constructor,
717 // defaulting to using the Host's UnixSignals.
720 Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
721 const UnixSignalsSP &unix_signals_sp)
722 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
723 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
724 Process::GetStaticBroadcasterClass().AsCString()),
725 m_target_sp(target_sp), m_public_state(eStateUnloaded),
726 m_private_state(eStateUnloaded),
727 m_private_state_broadcaster(nullptr,
728 "lldb.process.internal_state_broadcaster"),
729 m_private_state_control_broadcaster(
730 nullptr, "lldb.process.internal_state_control_broadcaster"),
731 m_private_state_listener_sp(
732 Listener::MakeListener("lldb.process.internal_state_listener")),
733 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
734 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
735 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
736 m_thread_list(this), m_extended_thread_list(this),
737 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
738 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
739 m_breakpoint_site_list(), m_dynamic_checkers_ap(),
740 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
741 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
742 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
743 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
744 m_memory_cache(*this), m_allocated_memory_cache(*this),
745 m_should_detach(false), m_next_event_action_ap(), m_public_run_lock(),
746 m_private_run_lock(), m_stop_info_override_callback(nullptr),
747 m_finalizing(false), m_finalize_called(false),
748 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
749 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
750 m_can_interpret_function_calls(false), m_warnings_issued(),
751 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
752 CheckInWithManager();
754 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
756 log->Printf("%p Process::Process()", static_cast<void *>(this));
758 if (!m_unix_signals_sp)
759 m_unix_signals_sp = std::make_shared<UnixSignals>();
761 SetEventName(eBroadcastBitStateChanged, "state-changed");
762 SetEventName(eBroadcastBitInterrupt, "interrupt");
763 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
764 SetEventName(eBroadcastBitSTDERR, "stderr-available");
765 SetEventName(eBroadcastBitProfileData, "profile-data-available");
766 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
768 m_private_state_control_broadcaster.SetEventName(
769 eBroadcastInternalStateControlStop, "control-stop");
770 m_private_state_control_broadcaster.SetEventName(
771 eBroadcastInternalStateControlPause, "control-pause");
772 m_private_state_control_broadcaster.SetEventName(
773 eBroadcastInternalStateControlResume, "control-resume");
775 m_listener_sp->StartListeningForEvents(
776 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
777 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
778 eBroadcastBitProfileData | eBroadcastBitStructuredData);
780 m_private_state_listener_sp->StartListeningForEvents(
781 &m_private_state_broadcaster,
782 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
784 m_private_state_listener_sp->StartListeningForEvents(
785 &m_private_state_control_broadcaster,
786 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
787 eBroadcastInternalStateControlResume);
788 // We need something valid here, even if just the default UnixSignalsSP.
789 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
791 // Allow the platform to override the default cache line size
792 OptionValueSP value_sp =
794 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
796 uint32_t platform_cache_line_size =
797 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
798 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
799 value_sp->SetUInt64Value(platform_cache_line_size);
802 Process::~Process() {
803 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
805 log->Printf("%p Process::~Process()", static_cast<void *>(this));
806 StopPrivateStateThread();
808 // ThreadList::Clear() will try to acquire this process's mutex, so
809 // explicitly clear the thread list here to ensure that the mutex
810 // is not destroyed before the thread list.
811 m_thread_list.Clear();
814 const ProcessPropertiesSP &Process::GetGlobalProperties() {
815 // NOTE: intentional leak so we don't crash if global destructor chain gets
816 // called as other threads still use the result of this function
817 static ProcessPropertiesSP *g_settings_sp_ptr =
818 new ProcessPropertiesSP(new ProcessProperties(nullptr));
819 return *g_settings_sp_ptr;
822 void Process::Finalize() {
825 // Destroy this process if needed
826 switch (GetPrivateState()) {
827 case eStateConnected:
828 case eStateAttaching:
829 case eStateLaunching:
834 case eStateSuspended:
845 // Clear our broadcaster before we proceed with destroying
846 Broadcaster::Clear();
848 // Do any cleanup needed prior to being destructed... Subclasses
849 // that override this method should call this superclass method as well.
851 // We need to destroy the loader before the derived Process class gets
853 // since it is very likely that undoing the loader will require access to the
855 m_dynamic_checkers_ap.reset();
858 m_system_runtime_ap.reset();
860 m_jit_loaders_ap.reset();
861 m_thread_list_real.Destroy();
862 m_thread_list.Destroy();
863 m_extended_thread_list.Destroy();
864 m_queue_list.Clear();
865 m_queue_list_stop_id = 0;
866 std::vector<Notifications> empty_notifications;
867 m_notifications.swap(empty_notifications);
868 m_image_tokens.clear();
869 m_memory_cache.Clear();
870 m_allocated_memory_cache.Clear();
871 m_language_runtimes.clear();
872 m_instrumentation_runtimes.clear();
873 m_next_event_action_ap.reset();
874 m_stop_info_override_callback = nullptr;
875 // Clear the last natural stop ID since it has a strong
876 // reference to this process
877 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
878 //#ifdef LLDB_CONFIGURATION_DEBUG
879 // StreamFile s(stdout, false);
881 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
883 // event_sp->Dump (&s);
887 // We have to be very careful here as the m_private_state_listener might
888 // contain events that have ProcessSP values in them which can keep this
889 // process around forever. These events need to be cleared out.
890 m_private_state_listener_sp->Clear();
891 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
892 m_public_run_lock.SetStopped();
893 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
894 m_private_run_lock.SetStopped();
895 m_structured_data_plugin_map.clear();
896 m_finalize_called = true;
899 void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
900 m_notifications.push_back(callbacks);
901 if (callbacks.initialize != nullptr)
902 callbacks.initialize(callbacks.baton, this);
905 bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
906 std::vector<Notifications>::iterator pos, end = m_notifications.end();
907 for (pos = m_notifications.begin(); pos != end; ++pos) {
908 if (pos->baton == callbacks.baton &&
909 pos->initialize == callbacks.initialize &&
910 pos->process_state_changed == callbacks.process_state_changed) {
911 m_notifications.erase(pos);
918 void Process::SynchronouslyNotifyStateChanged(StateType state) {
919 std::vector<Notifications>::iterator notification_pos,
920 notification_end = m_notifications.end();
921 for (notification_pos = m_notifications.begin();
922 notification_pos != notification_end; ++notification_pos) {
923 if (notification_pos->process_state_changed)
924 notification_pos->process_state_changed(notification_pos->baton, this,
929 // FIXME: We need to do some work on events before the general Listener sees
931 // For instance if we are continuing from a breakpoint, we need to ensure that
933 // the little "insert real insn, step & stop" trick. But we can't do that when
935 // event is delivered by the broadcaster - since that is done on the thread that
937 // waiting for new events, so if we needed more than one event for our handling,
939 // stall. So instead we do it when we fetch the event off of the queue.
942 StateType Process::GetNextEvent(EventSP &event_sp) {
943 StateType state = eStateInvalid;
945 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
946 std::chrono::seconds(0)) &&
948 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
953 void Process::SyncIOHandler(uint32_t iohandler_id, uint64_t timeout_msec) {
954 // don't sync (potentially context switch) in case where there is no process
956 if (!m_process_input_reader)
959 uint32_t new_iohandler_id = 0;
960 m_iohandler_sync.WaitForValueNotEqualTo(
961 iohandler_id, new_iohandler_id, std::chrono::milliseconds(timeout_msec));
963 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
965 log->Printf("Process::%s waited for m_iohandler_sync to change from %u, "
967 __FUNCTION__, iohandler_id, new_iohandler_id);
970 StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
971 EventSP *event_sp_ptr, bool wait_always,
972 ListenerSP hijack_listener_sp,
973 Stream *stream, bool use_run_lock) {
974 // We can't just wait for a "stopped" event, because the stopped event may
975 // have restarted the target.
976 // We have to actually check each event, and in the case of a stopped event
977 // check the restarted flag
980 event_sp_ptr->reset();
981 StateType state = GetState();
982 // If we are exited or detached, we won't ever get back to any
983 // other valid state...
984 if (state == eStateDetached || state == eStateExited)
987 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
988 LLDB_LOG(log, "timeout = {0}", timeout);
990 if (!wait_always && StateIsStoppedState(state, true) &&
991 StateIsStoppedState(GetPrivateState(), true)) {
993 log->Printf("Process::%s returning without waiting for events; process "
994 "private and public states are already 'stopped'.",
996 // We need to toggle the run lock as this won't get done in
997 // SetPublicState() if the process is hijacked.
998 if (hijack_listener_sp && use_run_lock)
999 m_public_run_lock.SetStopped();
1003 while (state != eStateInvalid) {
1005 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
1006 if (event_sp_ptr && event_sp)
1007 *event_sp_ptr = event_sp;
1009 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
1010 Process::HandleProcessStateChangedEvent(event_sp, stream,
1011 pop_process_io_handler);
1015 case eStateDetached:
1017 case eStateUnloaded:
1018 // We need to toggle the run lock as this won't get done in
1019 // SetPublicState() if the process is hijacked.
1020 if (hijack_listener_sp && use_run_lock)
1021 m_public_run_lock.SetStopped();
1024 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1027 // We need to toggle the run lock as this won't get done in
1028 // SetPublicState() if the process is hijacked.
1029 if (hijack_listener_sp && use_run_lock)
1030 m_public_run_lock.SetStopped();
1040 bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
1042 bool &pop_process_io_handler) {
1043 const bool handle_pop = pop_process_io_handler;
1045 pop_process_io_handler = false;
1046 ProcessSP process_sp =
1047 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1052 StateType event_state =
1053 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1054 if (event_state == eStateInvalid)
1057 switch (event_state) {
1059 case eStateUnloaded:
1060 case eStateAttaching:
1061 case eStateLaunching:
1062 case eStateStepping:
1063 case eStateDetached:
1065 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
1066 StateAsCString(event_state));
1067 if (event_state == eStateDetached)
1068 pop_process_io_handler = true;
1071 case eStateConnected:
1073 // Don't be chatty when we run...
1078 process_sp->GetStatus(*stream);
1079 pop_process_io_handler = true;
1084 case eStateSuspended:
1085 // Make sure the program hasn't been auto-restarted:
1086 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
1088 size_t num_reasons =
1089 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1090 if (num_reasons > 0) {
1091 // FIXME: Do we want to report this, or would that just be annoyingly
1093 if (num_reasons == 1) {
1094 const char *reason =
1095 Process::ProcessEventData::GetRestartedReasonAtIndex(
1097 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
1098 process_sp->GetID(),
1099 reason ? reason : "<UNKNOWN REASON>");
1101 stream->Printf("Process %" PRIu64
1102 " stopped and restarted, reasons:\n",
1103 process_sp->GetID());
1105 for (size_t i = 0; i < num_reasons; i++) {
1106 const char *reason =
1107 Process::ProcessEventData::GetRestartedReasonAtIndex(
1109 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1115 StopInfoSP curr_thread_stop_info_sp;
1116 // Lock the thread list so it doesn't change on us, this is the scope for
1119 ThreadList &thread_list = process_sp->GetThreadList();
1120 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
1122 ThreadSP curr_thread(thread_list.GetSelectedThread());
1124 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1126 curr_thread_stop_reason = curr_thread->GetStopReason();
1127 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
1129 if (!curr_thread || !curr_thread->IsValid() ||
1130 curr_thread_stop_reason == eStopReasonInvalid ||
1131 curr_thread_stop_reason == eStopReasonNone) {
1132 // Prefer a thread that has just completed its plan over another
1133 // thread as current thread.
1134 ThreadSP plan_thread;
1135 ThreadSP other_thread;
1137 const size_t num_threads = thread_list.GetSize();
1139 for (i = 0; i < num_threads; ++i) {
1140 thread = thread_list.GetThreadAtIndex(i);
1141 StopReason thread_stop_reason = thread->GetStopReason();
1142 switch (thread_stop_reason) {
1143 case eStopReasonInvalid:
1144 case eStopReasonNone:
1147 case eStopReasonSignal: {
1148 // Don't select a signal thread if we weren't going to stop at
1150 // signal. We have to have had another reason for stopping here,
1152 // the user doesn't want to see this thread.
1153 uint64_t signo = thread->GetStopInfo()->GetValue();
1154 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
1156 other_thread = thread;
1160 case eStopReasonTrace:
1161 case eStopReasonBreakpoint:
1162 case eStopReasonWatchpoint:
1163 case eStopReasonException:
1164 case eStopReasonExec:
1165 case eStopReasonThreadExiting:
1166 case eStopReasonInstrumentation:
1168 other_thread = thread;
1170 case eStopReasonPlanComplete:
1172 plan_thread = thread;
1177 thread_list.SetSelectedThreadByID(plan_thread->GetID());
1178 else if (other_thread)
1179 thread_list.SetSelectedThreadByID(other_thread->GetID());
1181 if (curr_thread && curr_thread->IsValid())
1182 thread = curr_thread;
1184 thread = thread_list.GetThreadAtIndex(0);
1187 thread_list.SetSelectedThreadByID(thread->GetID());
1191 // Drop the ThreadList mutex by here, since GetThreadStatus below might
1192 // have to run code,
1193 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the
1194 // process is going to
1195 // have a hard time restarting the process.
1197 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1198 if (debugger.GetTargetList().GetSelectedTarget().get() ==
1199 &process_sp->GetTarget()) {
1200 const bool only_threads_with_stop_reason = true;
1201 const uint32_t start_frame = 0;
1202 const uint32_t num_frames = 1;
1203 const uint32_t num_frames_with_source = 1;
1204 const bool stop_format = true;
1205 process_sp->GetStatus(*stream);
1206 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
1207 start_frame, num_frames,
1208 num_frames_with_source,
1210 if (curr_thread_stop_info_sp) {
1211 lldb::addr_t crashing_address;
1212 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1213 curr_thread_stop_info_sp, &crashing_address);
1215 const bool qualify_cxx_base_classes = false;
1217 const ValueObject::GetExpressionPathFormat format =
1218 ValueObject::GetExpressionPathFormat::
1219 eGetExpressionPathFormatHonorPointers;
1220 stream->PutCString("Likely cause: ");
1221 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
1223 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1227 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1228 process_sp->GetTarget().shared_from_this());
1229 if (target_idx != UINT32_MAX)
1230 stream->Printf("Target %d: (", target_idx);
1232 stream->Printf("Target <unknown index>: (");
1233 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1234 stream->Printf(") stopped.\n");
1238 // Pop the process IO handler
1239 pop_process_io_handler = true;
1244 if (handle_pop && pop_process_io_handler)
1245 process_sp->PopProcessIOHandler();
1250 bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1252 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1253 eBroadcastBitInterrupt);
1258 void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
1260 StateType Process::GetStateChangedEvents(EventSP &event_sp,
1261 const Timeout<std::micro> &timeout,
1262 ListenerSP hijack_listener_sp) {
1263 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1264 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1266 ListenerSP listener_sp = hijack_listener_sp;
1268 listener_sp = m_listener_sp;
1270 StateType state = eStateInvalid;
1271 if (listener_sp->GetEventForBroadcasterWithType(
1272 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
1274 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1275 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1277 LLDB_LOG(log, "got no event or was interrupted.");
1280 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
1284 Event *Process::PeekAtStateChangedEvents() {
1285 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1288 log->Printf("Process::%s...", __FUNCTION__);
1291 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1292 this, eBroadcastBitStateChanged);
1296 "Process::%s (event_ptr) => %s", __FUNCTION__,
1297 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
1299 log->Printf("Process::%s no events found", __FUNCTION__);
1306 Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1307 const Timeout<std::micro> &timeout) {
1308 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1309 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1311 StateType state = eStateInvalid;
1312 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1313 &m_private_state_broadcaster,
1314 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
1316 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1317 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1319 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1320 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
1324 bool Process::GetEventsPrivate(EventSP &event_sp,
1325 const Timeout<std::micro> &timeout,
1326 bool control_only) {
1327 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1328 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1331 return m_private_state_listener_sp->GetEventForBroadcaster(
1332 &m_private_state_control_broadcaster, event_sp, timeout);
1334 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
1337 bool Process::IsRunning() const {
1338 return StateIsRunningState(m_public_state.GetValue());
1341 int Process::GetExitStatus() {
1342 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1344 if (m_public_state.GetValue() == eStateExited)
1345 return m_exit_status;
1349 const char *Process::GetExitDescription() {
1350 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1352 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1353 return m_exit_string.c_str();
1357 bool Process::SetExitStatus(int status, const char *cstr) {
1358 // Use a mutex to protect setting the exit status.
1359 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1361 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1362 LIBLLDB_LOG_PROCESS));
1365 "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1366 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL",
1369 // We were already in the exited state
1370 if (m_private_state.GetValue() == eStateExited) {
1372 log->Printf("Process::SetExitStatus () ignoring exit status because "
1373 "state was already set to eStateExited");
1377 m_exit_status = status;
1379 m_exit_string = cstr;
1381 m_exit_string.clear();
1383 // Clear the last natural stop ID since it has a strong
1384 // reference to this process
1385 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1387 SetPrivateState(eStateExited);
1389 // Allow subclasses to do some cleanup
1395 bool Process::IsAlive() {
1396 switch (m_private_state.GetValue()) {
1397 case eStateConnected:
1398 case eStateAttaching:
1399 case eStateLaunching:
1402 case eStateStepping:
1404 case eStateSuspended:
1411 // This static callback can be used to watch for local child processes on
1412 // the current host. The child process exits, the process will be
1413 // found in the global target list (we want to be completely sure that the
1414 // lldb_private::Process doesn't go away before we can deliver the signal.
1415 bool Process::SetProcessExitStatus(
1416 lldb::pid_t pid, bool exited,
1417 int signo, // Zero for no signal
1418 int exit_status // Exit value of process if signal is zero
1420 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1422 log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64
1423 ", exited=%i, signal=%i, exit_status=%i)\n",
1424 pid, exited, signo, exit_status);
1427 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1429 ProcessSP process_sp(target_sp->GetProcessSP());
1431 const char *signal_cstr = nullptr;
1433 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1435 process_sp->SetExitStatus(exit_status, signal_cstr);
1443 void Process::UpdateThreadListIfNeeded() {
1444 const uint32_t stop_id = GetStopID();
1445 if (m_thread_list.GetSize(false) == 0 ||
1446 stop_id != m_thread_list.GetStopID()) {
1447 const StateType state = GetPrivateState();
1448 if (StateIsStoppedState(state, true)) {
1449 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
1450 // m_thread_list does have its own mutex, but we need to
1451 // hold onto the mutex between the call to UpdateThreadList(...)
1452 // and the os->UpdateThreadList(...) so it doesn't change on us
1453 ThreadList &old_thread_list = m_thread_list;
1454 ThreadList real_thread_list(this);
1455 ThreadList new_thread_list(this);
1456 // Always update the thread list with the protocol specific
1457 // thread list, but only update if "true" is returned
1458 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1459 // Don't call into the OperatingSystem to update the thread list if we
1460 // are shutting down, since
1461 // that may call back into the SBAPI's, requiring the API lock which is
1462 // already held by whoever is
1463 // shutting us down, causing a deadlock.
1464 OperatingSystem *os = GetOperatingSystem();
1465 if (os && !m_destroy_in_process) {
1466 // Clear any old backing threads where memory threads might have been
1467 // backed by actual threads from the lldb_private::Process subclass
1468 size_t num_old_threads = old_thread_list.GetSize(false);
1469 for (size_t i = 0; i < num_old_threads; ++i)
1470 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1472 // Turn off dynamic types to ensure we don't run any expressions.
1474 // can run an expression to determine if a SBValue is a dynamic type
1476 // and we need to avoid this. OperatingSystem plug-ins can't run
1478 // that require running code...
1480 Target &target = GetTarget();
1481 const lldb::DynamicValueType saved_prefer_dynamic =
1482 target.GetPreferDynamicValue();
1483 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1484 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1486 // Now let the OperatingSystem plug-in update the thread list
1488 os->UpdateThreadList(
1489 old_thread_list, // Old list full of threads created by OS plug-in
1490 real_thread_list, // The actual thread list full of threads
1491 // created by each lldb_private::Process
1493 new_thread_list); // The new thread list that we will show to the
1494 // user that gets filled in
1496 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1497 target.SetPreferDynamicValue(saved_prefer_dynamic);
1499 // No OS plug-in, the new thread list is the same as the real thread
1501 new_thread_list = real_thread_list;
1504 m_thread_list_real.Update(real_thread_list);
1505 m_thread_list.Update(new_thread_list);
1506 m_thread_list.SetStopID(stop_id);
1508 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1509 // Clear any extended threads that we may have accumulated previously
1510 m_extended_thread_list.Clear();
1511 m_extended_thread_stop_id = GetLastNaturalStopID();
1513 m_queue_list.Clear();
1514 m_queue_list_stop_id = GetLastNaturalStopID();
1521 void Process::UpdateQueueListIfNeeded() {
1522 if (m_system_runtime_ap) {
1523 if (m_queue_list.GetSize() == 0 ||
1524 m_queue_list_stop_id != GetLastNaturalStopID()) {
1525 const StateType state = GetPrivateState();
1526 if (StateIsStoppedState(state, true)) {
1527 m_system_runtime_ap->PopulateQueueList(m_queue_list);
1528 m_queue_list_stop_id = GetLastNaturalStopID();
1534 ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1535 OperatingSystem *os = GetOperatingSystem();
1537 return os->CreateThread(tid, context);
1541 uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1542 return AssignIndexIDToThread(thread_id);
1545 bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1546 return (m_thread_id_to_index_id_map.find(thread_id) !=
1547 m_thread_id_to_index_id_map.end());
1550 uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1551 uint32_t result = 0;
1552 std::map<uint64_t, uint32_t>::iterator iterator =
1553 m_thread_id_to_index_id_map.find(thread_id);
1554 if (iterator == m_thread_id_to_index_id_map.end()) {
1555 result = ++m_thread_index_id;
1556 m_thread_id_to_index_id_map[thread_id] = result;
1558 result = iterator->second;
1564 StateType Process::GetState() {
1565 // If any other threads access this we will need a mutex for it
1566 return m_public_state.GetValue();
1569 bool Process::StateChangedIsExternallyHijacked() {
1570 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1571 const char *hijacking_name = GetHijackingListenerName();
1572 if (hijacking_name &&
1573 strcmp(hijacking_name, "lldb.Process.ResumeSynchronous.hijack"))
1579 void Process::SetPublicState(StateType new_state, bool restarted) {
1580 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1581 LIBLLDB_LOG_PROCESS));
1583 log->Printf("Process::SetPublicState (state = %s, restarted = %i)",
1584 StateAsCString(new_state), restarted);
1585 const StateType old_state = m_public_state.GetValue();
1586 m_public_state.SetValue(new_state);
1588 // On the transition from Run to Stopped, we unlock the writer end of the
1589 // run lock. The lock gets locked in Resume, which is the public API
1590 // to tell the program to run.
1591 if (!StateChangedIsExternallyHijacked()) {
1592 if (new_state == eStateDetached) {
1595 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1596 StateAsCString(new_state));
1597 m_public_run_lock.SetStopped();
1599 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1600 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1601 if ((old_state_is_stopped != new_state_is_stopped)) {
1602 if (new_state_is_stopped && !restarted) {
1604 log->Printf("Process::SetPublicState (%s) -- unlocking run lock",
1605 StateAsCString(new_state));
1606 m_public_run_lock.SetStopped();
1613 Status Process::Resume() {
1614 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1615 LIBLLDB_LOG_PROCESS));
1617 log->Printf("Process::Resume -- locking run lock");
1618 if (!m_public_run_lock.TrySetRunning()) {
1619 Status error("Resume request failed - process still running.");
1621 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1624 return PrivateResume();
1627 Status Process::ResumeSynchronous(Stream *stream) {
1628 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1629 LIBLLDB_LOG_PROCESS));
1631 log->Printf("Process::ResumeSynchronous -- locking run lock");
1632 if (!m_public_run_lock.TrySetRunning()) {
1633 Status error("Resume request failed - process still running.");
1635 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1639 ListenerSP listener_sp(
1640 Listener::MakeListener("lldb.Process.ResumeSynchronous.hijack"));
1641 HijackProcessEvents(listener_sp);
1643 Status error = PrivateResume();
1644 if (error.Success()) {
1646 WaitForProcessToStop(llvm::None, NULL, true, listener_sp, stream);
1647 const bool must_be_alive =
1648 false; // eStateExited is ok, so this must be false
1649 if (!StateIsStoppedState(state, must_be_alive))
1650 error.SetErrorStringWithFormat(
1651 "process not in stopped state after synchronous resume: %s",
1652 StateAsCString(state));
1655 // Undo the hijacking of process events...
1656 RestoreProcessEvents();
1661 StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
1663 void Process::SetPrivateState(StateType new_state) {
1664 if (m_finalize_called)
1667 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1668 LIBLLDB_LOG_PROCESS));
1669 bool state_changed = false;
1672 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1674 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1675 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1677 const StateType old_state = m_private_state.GetValueNoLock();
1678 state_changed = old_state != new_state;
1680 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1681 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1682 if (old_state_is_stopped != new_state_is_stopped) {
1683 if (new_state_is_stopped)
1684 m_private_run_lock.SetStopped();
1686 m_private_run_lock.SetRunning();
1689 if (state_changed) {
1690 m_private_state.SetValueNoLock(new_state);
1692 new Event(eBroadcastBitStateChanged,
1693 new ProcessEventData(shared_from_this(), new_state)));
1694 if (StateIsStoppedState(new_state, false)) {
1695 // Note, this currently assumes that all threads in the list
1696 // stop when the process stops. In the future we will want to
1697 // support a debugging model where some threads continue to run
1698 // while others are stopped. When that happens we will either need
1699 // a way for the thread list to identify which threads are stopping
1700 // or create a special thread list containing only threads which
1701 // actually stopped.
1703 // The process plugin is responsible for managing the actual
1704 // behavior of the threads and should have stopped any threads
1705 // that are going to stop before we get here.
1706 m_thread_list.DidStop();
1708 m_mod_id.BumpStopID();
1709 if (!m_mod_id.IsLastResumeForUserExpression())
1710 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1711 m_memory_cache.Clear();
1713 log->Printf("Process::SetPrivateState (%s) stop_id = %u",
1714 StateAsCString(new_state), m_mod_id.GetStopID());
1717 // Use our target to get a shared pointer to ourselves...
1718 if (m_finalize_called && !PrivateStateThreadIsValid())
1719 BroadcastEvent(event_sp);
1721 m_private_state_broadcaster.BroadcastEvent(event_sp);
1725 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1726 StateAsCString(new_state));
1730 void Process::SetRunningUserExpression(bool on) {
1731 m_mod_id.SetRunningUserExpression(on);
1734 addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1736 const lldb::ABISP &Process::GetABI() {
1738 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
1742 LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language,
1743 bool retry_if_null) {
1747 LanguageRuntimeCollection::iterator pos;
1748 pos = m_language_runtimes.find(language);
1749 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) {
1750 lldb::LanguageRuntimeSP runtime_sp(
1751 LanguageRuntime::FindPlugin(this, language));
1753 m_language_runtimes[language] = runtime_sp;
1754 return runtime_sp.get();
1756 return (*pos).second.get();
1759 CPPLanguageRuntime *Process::GetCPPLanguageRuntime(bool retry_if_null) {
1760 LanguageRuntime *runtime =
1761 GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1762 if (runtime != nullptr &&
1763 runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1764 return static_cast<CPPLanguageRuntime *>(runtime);
1768 ObjCLanguageRuntime *Process::GetObjCLanguageRuntime(bool retry_if_null) {
1769 LanguageRuntime *runtime =
1770 GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1771 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC)
1772 return static_cast<ObjCLanguageRuntime *>(runtime);
1776 bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1780 if (in_value.IsDynamic())
1782 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1784 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1785 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1786 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1789 LanguageRuntime *cpp_runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1790 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1793 LanguageRuntime *objc_runtime = GetLanguageRuntime(eLanguageTypeObjC);
1794 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1797 void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
1798 m_dynamic_checkers_ap.reset(dynamic_checkers);
1801 BreakpointSiteList &Process::GetBreakpointSiteList() {
1802 return m_breakpoint_site_list;
1805 const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1806 return m_breakpoint_site_list;
1809 void Process::DisableAllBreakpointSites() {
1810 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1811 // bp_site->SetEnabled(true);
1812 DisableBreakpointSite(bp_site);
1816 Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1817 Status error(DisableBreakpointSiteByID(break_id));
1819 if (error.Success())
1820 m_breakpoint_site_list.Remove(break_id);
1825 Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1827 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1829 if (bp_site_sp->IsEnabled())
1830 error = DisableBreakpointSite(bp_site_sp.get());
1832 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1839 Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1841 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1843 if (!bp_site_sp->IsEnabled())
1844 error = EnableBreakpointSite(bp_site_sp.get());
1846 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1853 Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1854 bool use_hardware) {
1855 addr_t load_addr = LLDB_INVALID_ADDRESS;
1857 bool show_error = true;
1858 switch (GetState()) {
1860 case eStateUnloaded:
1861 case eStateConnected:
1862 case eStateAttaching:
1863 case eStateLaunching:
1864 case eStateDetached:
1871 case eStateStepping:
1873 case eStateSuspended:
1874 show_error = IsAlive();
1878 // Reset the IsIndirect flag here, in case the location changes from
1879 // pointing to a indirect symbol to a regular symbol.
1880 owner->SetIsIndirect(false);
1882 if (owner->ShouldResolveIndirectFunctions()) {
1883 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1884 if (symbol && symbol->IsIndirect()) {
1886 Address symbol_address = symbol->GetAddress();
1887 load_addr = ResolveIndirectFunction(&symbol_address, error);
1888 if (!error.Success() && show_error) {
1889 GetTarget().GetDebugger().GetErrorFile()->Printf(
1890 "warning: failed to resolve indirect function at 0x%" PRIx64
1891 " for breakpoint %i.%i: %s\n",
1892 symbol->GetLoadAddress(&GetTarget()),
1893 owner->GetBreakpoint().GetID(), owner->GetID(),
1894 error.AsCString() ? error.AsCString() : "unknown error");
1895 return LLDB_INVALID_BREAK_ID;
1897 Address resolved_address(load_addr);
1898 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1899 owner->SetIsIndirect(true);
1901 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1903 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1905 if (load_addr != LLDB_INVALID_ADDRESS) {
1906 BreakpointSiteSP bp_site_sp;
1908 // Look up this breakpoint site. If it exists, then add this new owner,
1910 // create a new breakpoint site and add it.
1912 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1915 bp_site_sp->AddOwner(owner);
1916 owner->SetBreakpointSite(bp_site_sp);
1917 return bp_site_sp->GetID();
1919 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1920 load_addr, use_hardware));
1922 Status error = EnableBreakpointSite(bp_site_sp.get());
1923 if (error.Success()) {
1924 owner->SetBreakpointSite(bp_site_sp);
1925 return m_breakpoint_site_list.Add(bp_site_sp);
1928 // Report error for setting breakpoint...
1929 GetTarget().GetDebugger().GetErrorFile()->Printf(
1930 "warning: failed to set breakpoint site at 0x%" PRIx64
1931 " for breakpoint %i.%i: %s\n",
1932 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1933 error.AsCString() ? error.AsCString() : "unknown error");
1939 // We failed to enable the breakpoint
1940 return LLDB_INVALID_BREAK_ID;
1943 void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1944 lldb::user_id_t owner_loc_id,
1945 BreakpointSiteSP &bp_site_sp) {
1946 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1947 if (num_owners == 0) {
1948 // Don't try to disable the site if we don't have a live process anymore.
1950 DisableBreakpointSite(bp_site_sp.get());
1951 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1955 size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1956 uint8_t *buf) const {
1957 size_t bytes_removed = 0;
1958 BreakpointSiteList bp_sites_in_range;
1960 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1961 bp_sites_in_range)) {
1962 bp_sites_in_range.ForEach([bp_addr, size,
1963 buf](BreakpointSite *bp_site) -> void {
1964 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1965 addr_t intersect_addr;
1966 size_t intersect_size;
1967 size_t opcode_offset;
1968 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1969 &intersect_size, &opcode_offset)) {
1970 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1971 assert(bp_addr < intersect_addr + intersect_size &&
1972 intersect_addr + intersect_size <= bp_addr + size);
1973 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1974 size_t buf_offset = intersect_addr - bp_addr;
1975 ::memcpy(buf + buf_offset,
1976 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1982 return bytes_removed;
1985 size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1986 PlatformSP platform_sp(GetTarget().GetPlatform());
1988 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1992 Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1994 assert(bp_site != nullptr);
1995 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1996 const addr_t bp_addr = bp_site->GetLoadAddress();
1999 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
2000 bp_site->GetID(), (uint64_t)bp_addr);
2001 if (bp_site->IsEnabled()) {
2004 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2005 " -- already enabled",
2006 bp_site->GetID(), (uint64_t)bp_addr);
2010 if (bp_addr == LLDB_INVALID_ADDRESS) {
2011 error.SetErrorString("BreakpointSite contains an invalid load address.");
2014 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2015 // trap for the breakpoint site
2016 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2018 if (bp_opcode_size == 0) {
2019 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
2020 "returned zero, unable to get breakpoint "
2021 "trap for address 0x%" PRIx64,
2024 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2026 if (bp_opcode_bytes == nullptr) {
2027 error.SetErrorString(
2028 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2032 // Save the original opcode by reading it
2033 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
2034 error) == bp_opcode_size) {
2035 // Write a software breakpoint in place of the original opcode
2036 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
2038 uint8_t verify_bp_opcode_bytes[64];
2039 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
2040 error) == bp_opcode_size) {
2041 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
2042 bp_opcode_size) == 0) {
2043 bp_site->SetEnabled(true);
2044 bp_site->SetType(BreakpointSite::eSoftware);
2046 log->Printf("Process::EnableSoftwareBreakpoint (site_id = %d) "
2047 "addr = 0x%" PRIx64 " -- SUCCESS",
2048 bp_site->GetID(), (uint64_t)bp_addr);
2050 error.SetErrorString(
2051 "failed to verify the breakpoint trap in memory.");
2053 error.SetErrorString(
2054 "Unable to read memory to verify breakpoint trap.");
2056 error.SetErrorString("Unable to write breakpoint trap to memory.");
2058 error.SetErrorString("Unable to read memory at breakpoint address.");
2060 if (log && error.Fail())
2062 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2064 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2068 Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
2070 assert(bp_site != nullptr);
2071 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2072 addr_t bp_addr = bp_site->GetLoadAddress();
2073 lldb::user_id_t breakID = bp_site->GetID();
2075 log->Printf("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
2076 ") addr = 0x%" PRIx64,
2077 breakID, (uint64_t)bp_addr);
2079 if (bp_site->IsHardware()) {
2080 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2081 } else if (bp_site->IsEnabled()) {
2082 const size_t break_op_size = bp_site->GetByteSize();
2083 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
2084 if (break_op_size > 0) {
2085 // Clear a software breakpoint instruction
2086 uint8_t curr_break_op[8];
2087 assert(break_op_size <= sizeof(curr_break_op));
2088 bool break_op_found = false;
2090 // Read the breakpoint opcode
2091 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
2093 bool verify = false;
2094 // Make sure the breakpoint opcode exists at this address
2095 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
2096 break_op_found = true;
2097 // We found a valid breakpoint opcode at this address, now restore
2098 // the saved opcode.
2099 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
2100 break_op_size, error) == break_op_size) {
2103 error.SetErrorString(
2104 "Memory write failed when restoring original opcode.");
2106 error.SetErrorString(
2107 "Original breakpoint trap is no longer in memory.");
2108 // Set verify to true and so we can check if the original opcode has
2109 // already been restored
2114 uint8_t verify_opcode[8];
2115 assert(break_op_size < sizeof(verify_opcode));
2116 // Verify that our original opcode made it back to the inferior
2117 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
2119 // compare the memory we just read with the original opcode
2120 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
2121 break_op_size) == 0) {
2123 bp_site->SetEnabled(false);
2125 log->Printf("Process::DisableSoftwareBreakpoint (site_id = %d) "
2126 "addr = 0x%" PRIx64 " -- SUCCESS",
2127 bp_site->GetID(), (uint64_t)bp_addr);
2131 error.SetErrorString("Failed to restore original opcode.");
2134 error.SetErrorString("Failed to read memory to verify that "
2135 "breakpoint trap was restored.");
2138 error.SetErrorString(
2139 "Unable to read memory that should contain the breakpoint trap.");
2144 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2145 " -- already disabled",
2146 bp_site->GetID(), (uint64_t)bp_addr);
2152 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2154 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2158 // Uncomment to verify memory caching works after making changes to caching code
2159 //#define VERIFY_MEMORY_READS
2161 size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
2163 if (!GetDisableMemoryCache()) {
2164 #if defined(VERIFY_MEMORY_READS)
2165 // Memory caching is enabled, with debug verification
2168 // Uncomment the line below to make sure memory caching is working.
2169 // I ran this through the test suite and got no assertions, so I am
2170 // pretty confident this is working well. If any changes are made to
2171 // memory caching, uncomment the line below and test your changes!
2173 // Verify all memory reads by using the cache first, then redundantly
2174 // reading the same memory from the inferior and comparing to make sure
2175 // everything is exactly the same.
2176 std::string verify_buf(size, '\0');
2177 assert(verify_buf.size() == size);
2178 const size_t cache_bytes_read =
2179 m_memory_cache.Read(this, addr, buf, size, error);
2180 Status verify_error;
2181 const size_t verify_bytes_read =
2182 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2183 verify_buf.size(), verify_error);
2184 assert(cache_bytes_read == verify_bytes_read);
2185 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2186 assert(verify_error.Success() == error.Success());
2187 return cache_bytes_read;
2190 #else // !defined(VERIFY_MEMORY_READS)
2191 // Memory caching is enabled, without debug verification
2193 return m_memory_cache.Read(addr, buf, size, error);
2194 #endif // defined (VERIFY_MEMORY_READS)
2196 // Memory caching is disabled
2198 return ReadMemoryFromInferior(addr, buf, size, error);
2202 size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
2206 addr_t curr_addr = addr;
2208 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2211 out_str.append(buf, length);
2212 // If we got "length - 1" bytes, we didn't get the whole C string, we
2213 // need to read some more characters
2214 if (length == sizeof(buf) - 1)
2215 curr_addr += length;
2219 return out_str.size();
2222 size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
2223 Status &error, size_t type_width) {
2224 size_t total_bytes_read = 0;
2225 if (dst && max_bytes && type_width && max_bytes >= type_width) {
2226 // Ensure a null terminator independent of the number of bytes that is read.
2227 memset(dst, 0, max_bytes);
2228 size_t bytes_left = max_bytes - type_width;
2230 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2231 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2232 "string with more than 4 bytes "
2235 addr_t curr_addr = addr;
2236 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2237 char *curr_dst = dst;
2240 while (bytes_left > 0 && error.Success()) {
2241 addr_t cache_line_bytes_left =
2242 cache_line_size - (curr_addr % cache_line_size);
2243 addr_t bytes_to_read =
2244 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2245 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
2247 if (bytes_read == 0)
2250 // Search for a null terminator of correct size and alignment in
2252 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2253 for (size_t i = aligned_start;
2254 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2255 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2260 total_bytes_read += bytes_read;
2261 curr_dst += bytes_read;
2262 curr_addr += bytes_read;
2263 bytes_left -= bytes_read;
2267 error.SetErrorString("invalid arguments");
2269 return total_bytes_read;
2272 // Deprecated in favor of ReadStringFromMemory which has wchar support and
2273 // correct code to find
2274 // null terminators.
2275 size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
2277 Status &result_error) {
2278 size_t total_cstr_len = 0;
2279 if (dst && dst_max_len) {
2280 result_error.Clear();
2281 // NULL out everything just to be safe
2282 memset(dst, 0, dst_max_len);
2284 addr_t curr_addr = addr;
2285 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2286 size_t bytes_left = dst_max_len - 1;
2287 char *curr_dst = dst;
2289 while (bytes_left > 0) {
2290 addr_t cache_line_bytes_left =
2291 cache_line_size - (curr_addr % cache_line_size);
2292 addr_t bytes_to_read =
2293 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2294 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
2296 if (bytes_read == 0) {
2297 result_error = error;
2298 dst[total_cstr_len] = '\0';
2301 const size_t len = strlen(curr_dst);
2303 total_cstr_len += len;
2305 if (len < bytes_to_read)
2308 curr_dst += bytes_read;
2309 curr_addr += bytes_read;
2310 bytes_left -= bytes_read;
2314 result_error.SetErrorString("invalid arguments");
2316 result_error.Clear();
2318 return total_cstr_len;
2321 size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
2323 if (buf == nullptr || size == 0)
2326 size_t bytes_read = 0;
2327 uint8_t *bytes = (uint8_t *)buf;
2329 while (bytes_read < size) {
2330 const size_t curr_size = size - bytes_read;
2331 const size_t curr_bytes_read =
2332 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2333 bytes_read += curr_bytes_read;
2334 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2338 // Replace any software breakpoint opcodes that fall into this range back
2339 // into "buf" before we return
2341 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2345 uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2346 size_t integer_byte_size,
2347 uint64_t fail_value,
2350 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2352 return scalar.ULongLong(fail_value);
2356 int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2357 size_t integer_byte_size,
2361 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2363 return scalar.SLongLong(fail_value);
2367 addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
2369 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2371 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2372 return LLDB_INVALID_ADDRESS;
2375 bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
2378 const uint32_t addr_byte_size = GetAddressByteSize();
2379 if (addr_byte_size <= 4)
2380 scalar = (uint32_t)ptr_value;
2383 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2387 size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
2389 size_t bytes_written = 0;
2390 const uint8_t *bytes = (const uint8_t *)buf;
2392 while (bytes_written < size) {
2393 const size_t curr_size = size - bytes_written;
2394 const size_t curr_bytes_written = DoWriteMemory(
2395 addr + bytes_written, bytes + bytes_written, curr_size, error);
2396 bytes_written += curr_bytes_written;
2397 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2400 return bytes_written;
2403 size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
2405 #if defined(ENABLE_MEMORY_CACHING)
2406 m_memory_cache.Flush(addr, size);
2409 if (buf == nullptr || size == 0)
2412 m_mod_id.BumpMemoryID();
2414 // We need to write any data that would go where any current software traps
2415 // (enabled software breakpoints) any software traps (breakpoints) that we
2416 // may have placed in our tasks memory.
2418 BreakpointSiteList bp_sites_in_range;
2420 if (m_breakpoint_site_list.FindInRange(addr, addr + size,
2421 bp_sites_in_range)) {
2422 // No breakpoint sites overlap
2423 if (bp_sites_in_range.IsEmpty())
2424 return WriteMemoryPrivate(addr, buf, size, error);
2426 const uint8_t *ubuf = (const uint8_t *)buf;
2427 uint64_t bytes_written = 0;
2429 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2430 &error](BreakpointSite *bp) -> void {
2432 if (error.Success()) {
2433 addr_t intersect_addr;
2434 size_t intersect_size;
2435 size_t opcode_offset;
2436 const bool intersects = bp->IntersectsRange(
2437 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2438 UNUSED_IF_ASSERT_DISABLED(intersects);
2440 assert(addr <= intersect_addr && intersect_addr < addr + size);
2441 assert(addr < intersect_addr + intersect_size &&
2442 intersect_addr + intersect_size <= addr + size);
2443 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2445 // Check for bytes before this breakpoint
2446 const addr_t curr_addr = addr + bytes_written;
2447 if (intersect_addr > curr_addr) {
2448 // There are some bytes before this breakpoint that we need to
2449 // just write to memory
2450 size_t curr_size = intersect_addr - curr_addr;
2451 size_t curr_bytes_written = WriteMemoryPrivate(
2452 curr_addr, ubuf + bytes_written, curr_size, error);
2453 bytes_written += curr_bytes_written;
2454 if (curr_bytes_written != curr_size) {
2455 // We weren't able to write all of the requested bytes, we
2456 // are done looping and will return the number of bytes that
2457 // we have written so far.
2458 if (error.Success())
2459 error.SetErrorToGenericError();
2462 // Now write any bytes that would cover up any software breakpoints
2463 // directly into the breakpoint opcode buffer
2464 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset,
2465 ubuf + bytes_written, intersect_size);
2466 bytes_written += intersect_size;
2470 if (bytes_written < size)
2471 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2472 size - bytes_written, error);
2475 return WriteMemoryPrivate(addr, buf, size, error);
2478 // Write any remaining bytes after the last breakpoint if we have any left
2479 return 0; // bytes_written;
2482 size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2483 size_t byte_size, Status &error) {
2484 if (byte_size == UINT32_MAX)
2485 byte_size = scalar.GetByteSize();
2486 if (byte_size > 0) {
2488 const size_t mem_size =
2489 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2491 return WriteMemory(addr, buf, mem_size, error);
2493 error.SetErrorString("failed to get scalar as memory data");
2495 error.SetErrorString("invalid scalar value");
2500 size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2501 bool is_signed, Scalar &scalar,
2504 if (byte_size == 0) {
2505 error.SetErrorString("byte size is zero");
2506 } else if (byte_size & (byte_size - 1)) {
2507 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2509 } else if (byte_size <= sizeof(uval)) {
2510 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2511 if (bytes_read == byte_size) {
2512 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2513 GetAddressByteSize());
2514 lldb::offset_t offset = 0;
2516 scalar = data.GetMaxU32(&offset, byte_size);
2518 scalar = data.GetMaxU64(&offset, byte_size);
2520 scalar.SignExtend(byte_size * 8);
2524 error.SetErrorStringWithFormat(
2525 "byte size of %u is too large for integer scalar type", byte_size);
2530 #define USE_ALLOCATE_MEMORY_CACHE 1
2531 addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2533 if (GetPrivateState() != eStateStopped)
2534 return LLDB_INVALID_ADDRESS;
2536 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2537 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2539 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2540 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2542 log->Printf("Process::AllocateMemory(size=%" PRIu64
2543 ", permissions=%s) => 0x%16.16" PRIx64
2544 " (m_stop_id = %u m_memory_id = %u)",
2545 (uint64_t)size, GetPermissionsAsCString(permissions),
2546 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2547 m_mod_id.GetMemoryID());
2548 return allocated_addr;
2552 addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2554 addr_t return_addr = AllocateMemory(size, permissions, error);
2555 if (error.Success()) {
2556 std::string buffer(size, 0);
2557 WriteMemory(return_addr, buffer.c_str(), size, error);
2562 bool Process::CanJIT() {
2563 if (m_can_jit == eCanJITDontKnow) {
2564 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2567 uint64_t allocated_memory = AllocateMemory(
2568 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2571 if (err.Success()) {
2572 m_can_jit = eCanJITYes;
2574 log->Printf("Process::%s pid %" PRIu64
2575 " allocation test passed, CanJIT () is true",
2576 __FUNCTION__, GetID());
2578 m_can_jit = eCanJITNo;
2580 log->Printf("Process::%s pid %" PRIu64
2581 " allocation test failed, CanJIT () is false: %s",
2582 __FUNCTION__, GetID(), err.AsCString());
2585 DeallocateMemory(allocated_memory);
2588 return m_can_jit == eCanJITYes;
2591 void Process::SetCanJIT(bool can_jit) {
2592 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2595 void Process::SetCanRunCode(bool can_run_code) {
2596 SetCanJIT(can_run_code);
2597 m_can_interpret_function_calls = can_run_code;
2600 Status Process::DeallocateMemory(addr_t ptr) {
2602 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2603 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2604 error.SetErrorStringWithFormat(
2605 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2608 error = DoDeallocateMemory(ptr);
2610 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2612 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64
2613 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2614 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2615 m_mod_id.GetMemoryID());
2620 ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2621 lldb::addr_t header_addr,
2622 size_t size_to_read) {
2623 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2625 log->Printf("Process::ReadModuleFromMemory reading %s binary from memory",
2626 file_spec.GetPath().c_str());
2628 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2631 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2632 shared_from_this(), header_addr, error, size_to_read);
2639 bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2640 uint32_t &permissions) {
2641 MemoryRegionInfo range_info;
2643 Status error(GetMemoryRegionInfo(load_addr, range_info));
2644 if (!error.Success())
2646 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2647 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2648 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2652 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2653 permissions |= lldb::ePermissionsReadable;
2655 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2656 permissions |= lldb::ePermissionsWritable;
2658 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2659 permissions |= lldb::ePermissionsExecutable;
2664 Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2666 error.SetErrorString("watchpoints are not supported");
2670 Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2672 error.SetErrorString("watchpoints are not supported");
2677 Process::WaitForProcessStopPrivate(EventSP &event_sp,
2678 const Timeout<std::micro> &timeout) {
2680 // Now wait for the process to launch and return control to us, and then
2684 state = GetStateChangedEventsPrivate(event_sp, timeout);
2686 if (StateIsStoppedState(state, false))
2689 // If state is invalid, then we timed out
2690 if (state == eStateInvalid)
2694 HandlePrivateEvent(event_sp);
2699 void Process::LoadOperatingSystemPlugin(bool flush) {
2701 m_thread_list.Clear();
2702 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
2707 Status Process::Launch(ProcessLaunchInfo &launch_info) {
2711 m_jit_loaders_ap.reset();
2712 m_system_runtime_ap.reset();
2714 m_process_input_reader.reset();
2715 m_stop_info_override_callback = nullptr;
2717 Module *exe_module = GetTarget().GetExecutableModulePointer();
2719 char local_exec_file_path[PATH_MAX];
2720 char platform_exec_file_path[PATH_MAX];
2721 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2722 sizeof(local_exec_file_path));
2723 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2724 sizeof(platform_exec_file_path));
2725 if (exe_module->GetFileSpec().Exists()) {
2726 // Install anything that might need to be installed prior to launching.
2727 // For host systems, this will do nothing, but if we are connected to a
2728 // remote platform it will install any needed binaries
2729 error = GetTarget().Install(&launch_info);
2733 if (PrivateStateThreadIsValid())
2734 PausePrivateStateThread();
2736 error = WillLaunch(exe_module);
2737 if (error.Success()) {
2738 const bool restarted = false;
2739 SetPublicState(eStateLaunching, restarted);
2740 m_should_detach = false;
2742 if (m_public_run_lock.TrySetRunning()) {
2743 // Now launch using these arguments.
2744 error = DoLaunch(exe_module, launch_info);
2746 // This shouldn't happen
2747 error.SetErrorString("failed to acquire process run lock");
2751 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2752 SetID(LLDB_INVALID_PROCESS_ID);
2753 const char *error_string = error.AsCString();
2754 if (error_string == nullptr)
2755 error_string = "launch failed";
2756 SetExitStatus(-1, error_string);
2760 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
2762 if (state == eStateInvalid || !event_sp) {
2763 // We were able to launch the process, but we failed to
2764 // catch the initial stop.
2765 error.SetErrorString("failed to catch stop after launch");
2766 SetExitStatus(0, "failed to catch stop after launch");
2768 } else if (state == eStateStopped || state == eStateCrashed) {
2771 DynamicLoader *dyld = GetDynamicLoader();
2775 GetJITLoaders().DidLaunch();
2777 SystemRuntime *system_runtime = GetSystemRuntime();
2779 system_runtime->DidLaunch();
2782 LoadOperatingSystemPlugin(false);
2784 // We successfully launched the process and stopped,
2785 // now it the right time to set up signal filters before resuming.
2786 UpdateAutomaticSignalFiltering();
2788 // Note, the stop event was consumed above, but not handled. This
2790 // to give DidLaunch a chance to run. The target is either stopped
2792 // Directly set the state. This is done to prevent a stop message
2794 // of spurious output on thread status, as well as not pop a
2795 // ProcessIOHandler.
2796 SetPublicState(state, false);
2798 if (PrivateStateThreadIsValid())
2799 ResumePrivateStateThread();
2801 StartPrivateStateThread();
2803 m_stop_info_override_callback =
2804 GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
2806 // Target was stopped at entry as was intended. Need to notify the
2809 if (state == eStateStopped &&
2810 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2811 HandlePrivateEvent(event_sp);
2812 } else if (state == eStateExited) {
2813 // We exited while trying to launch somehow. Don't call DidLaunch
2815 // not likely to work, and return an invalid pid.
2816 HandlePrivateEvent(event_sp);
2821 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2822 local_exec_file_path);
2828 Status Process::LoadCore() {
2829 Status error = DoLoadCore();
2830 if (error.Success()) {
2831 ListenerSP listener_sp(
2832 Listener::MakeListener("lldb.process.load_core_listener"));
2833 HijackProcessEvents(listener_sp);
2835 if (PrivateStateThreadIsValid())
2836 ResumePrivateStateThread();
2838 StartPrivateStateThread();
2840 DynamicLoader *dyld = GetDynamicLoader();
2844 GetJITLoaders().DidAttach();
2846 SystemRuntime *system_runtime = GetSystemRuntime();
2848 system_runtime->DidAttach();
2851 LoadOperatingSystemPlugin(false);
2853 // We successfully loaded a core file, now pretend we stopped so we can
2854 // show all of the threads in the core file and explore the crashed
2856 SetPrivateState(eStateStopped);
2858 // Wait indefinitely for a stopped event since we just posted one above...
2859 lldb::EventSP event_sp;
2860 listener_sp->GetEvent(event_sp, llvm::None);
2861 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2863 if (!StateIsStoppedState(state, false)) {
2864 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2866 log->Printf("Process::Halt() failed to stop, state is: %s",
2867 StateAsCString(state));
2868 error.SetErrorString(
2869 "Did not get stopped event after loading the core file.");
2871 RestoreProcessEvents();
2876 DynamicLoader *Process::GetDynamicLoader() {
2878 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, nullptr));
2879 return m_dyld_ap.get();
2882 const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); }
2884 JITLoaderList &Process::GetJITLoaders() {
2885 if (!m_jit_loaders_ap) {
2886 m_jit_loaders_ap.reset(new JITLoaderList());
2887 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2889 return *m_jit_loaders_ap;
2892 SystemRuntime *Process::GetSystemRuntime() {
2893 if (!m_system_runtime_ap)
2894 m_system_runtime_ap.reset(SystemRuntime::FindPlugin(this));
2895 return m_system_runtime_ap.get();
2898 Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2899 uint32_t exec_count)
2900 : NextEventAction(process), m_exec_count(exec_count) {
2901 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2904 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2905 __FUNCTION__, static_cast<void *>(process), exec_count);
2908 Process::NextEventAction::EventActionResult
2909 Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2910 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2912 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2915 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2916 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2919 case eStateAttaching:
2920 return eEventActionSuccess;
2923 case eStateConnected:
2924 return eEventActionRetry;
2928 // During attach, prior to sending the eStateStopped event,
2929 // lldb_private::Process subclasses must set the new process ID.
2930 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2931 // We don't want these events to be reported, so go set the ShouldReportStop
2933 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2935 if (m_exec_count > 0) {
2939 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2940 "remaining exec count to %" PRIu32 ", requesting resume",
2941 __FUNCTION__, StateAsCString(state), m_exec_count);
2944 return eEventActionRetry;
2947 log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2948 "execs expected to start, continuing with attach",
2949 __FUNCTION__, StateAsCString(state));
2951 m_process->CompleteAttach();
2952 return eEventActionSuccess;
2962 m_exit_string.assign("No valid Process");
2963 return eEventActionExit;
2966 Process::NextEventAction::EventActionResult
2967 Process::AttachCompletionHandler::HandleBeingInterrupted() {
2968 return eEventActionSuccess;
2971 const char *Process::AttachCompletionHandler::GetExitString() {
2972 return m_exit_string.c_str();
2975 ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2977 return m_listener_sp;
2979 return debugger.GetListener();
2982 Status Process::Attach(ProcessAttachInfo &attach_info) {
2984 m_process_input_reader.reset();
2986 m_jit_loaders_ap.reset();
2987 m_system_runtime_ap.reset();
2989 m_stop_info_override_callback = nullptr;
2991 lldb::pid_t attach_pid = attach_info.GetProcessID();
2993 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2994 char process_name[PATH_MAX];
2996 if (attach_info.GetExecutableFile().GetPath(process_name,
2997 sizeof(process_name))) {
2998 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3000 if (wait_for_launch) {
3001 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3002 if (error.Success()) {
3003 if (m_public_run_lock.TrySetRunning()) {
3004 m_should_detach = true;
3005 const bool restarted = false;
3006 SetPublicState(eStateAttaching, restarted);
3007 // Now attach using these arguments.
3008 error = DoAttachToProcessWithName(process_name, attach_info);
3010 // This shouldn't happen
3011 error.SetErrorString("failed to acquire process run lock");
3015 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3016 SetID(LLDB_INVALID_PROCESS_ID);
3017 if (error.AsCString() == nullptr)
3018 error.SetErrorString("attach failed");
3020 SetExitStatus(-1, error.AsCString());
3023 SetNextEventAction(new Process::AttachCompletionHandler(
3024 this, attach_info.GetResumeCount()));
3025 StartPrivateStateThread();
3030 ProcessInstanceInfoList process_infos;
3031 PlatformSP platform_sp(GetTarget().GetPlatform());
3034 ProcessInstanceInfoMatch match_info;
3035 match_info.GetProcessInfo() = attach_info;
3036 match_info.SetNameMatchType(NameMatch::Equals);
3037 platform_sp->FindProcesses(match_info, process_infos);
3038 const uint32_t num_matches = process_infos.GetSize();
3039 if (num_matches == 1) {
3040 attach_pid = process_infos.GetProcessIDAtIndex(0);
3041 // Fall through and attach using the above process ID
3043 match_info.GetProcessInfo().GetExecutableFile().GetPath(
3044 process_name, sizeof(process_name));
3045 if (num_matches > 1) {
3047 ProcessInstanceInfo::DumpTableHeader(s, platform_sp.get(), true,
3049 for (size_t i = 0; i < num_matches; i++) {
3050 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
3051 s, platform_sp.get(), true, false);
3053 error.SetErrorStringWithFormat(
3054 "more than one process named %s:\n%s", process_name,
3057 error.SetErrorStringWithFormat(
3058 "could not find a process named %s", process_name);
3061 error.SetErrorString(
3062 "invalid platform, can't find processes by name");
3067 error.SetErrorString("invalid process name");
3071 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
3072 error = WillAttachToProcessWithID(attach_pid);
3073 if (error.Success()) {
3075 if (m_public_run_lock.TrySetRunning()) {
3076 // Now attach using these arguments.
3077 m_should_detach = true;
3078 const bool restarted = false;
3079 SetPublicState(eStateAttaching, restarted);
3080 error = DoAttachToProcessWithID(attach_pid, attach_info);
3082 // This shouldn't happen
3083 error.SetErrorString("failed to acquire process run lock");
3086 if (error.Success()) {
3087 SetNextEventAction(new Process::AttachCompletionHandler(
3088 this, attach_info.GetResumeCount()));
3089 StartPrivateStateThread();
3091 if (GetID() != LLDB_INVALID_PROCESS_ID)
3092 SetID(LLDB_INVALID_PROCESS_ID);
3094 const char *error_string = error.AsCString();
3095 if (error_string == nullptr)
3096 error_string = "attach failed";
3098 SetExitStatus(-1, error_string);
3105 void Process::CompleteAttach() {
3106 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3107 LIBLLDB_LOG_TARGET));
3109 log->Printf("Process::%s()", __FUNCTION__);
3111 // Let the process subclass figure out at much as it can about the process
3112 // before we go looking for a dynamic loader plug-in.
3113 ArchSpec process_arch;
3114 DidAttach(process_arch);
3116 if (process_arch.IsValid()) {
3117 GetTarget().SetArchitecture(process_arch);
3119 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
3120 log->Printf("Process::%s replacing process architecture with DidAttach() "
3122 __FUNCTION__, triple_str ? triple_str : "<null>");
3126 // We just attached. If we have a platform, ask it for the process
3127 // architecture, and if it isn't
3128 // the same as the one we've already set, switch architectures.
3129 PlatformSP platform_sp(GetTarget().GetPlatform());
3130 assert(platform_sp);
3132 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3133 if (target_arch.IsValid() &&
3134 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
3135 ArchSpec platform_arch;
3137 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
3139 GetTarget().SetPlatform(platform_sp);
3140 GetTarget().SetArchitecture(platform_arch);
3142 log->Printf("Process::%s switching platform to %s and architecture "
3143 "to %s based on info from attach",
3144 __FUNCTION__, platform_sp->GetName().AsCString(""),
3145 platform_arch.GetTriple().getTriple().c_str());
3147 } else if (!process_arch.IsValid()) {
3148 ProcessInstanceInfo process_info;
3149 GetProcessInfo(process_info);
3150 const ArchSpec &process_arch = process_info.GetArchitecture();
3151 if (process_arch.IsValid() &&
3152 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
3153 GetTarget().SetArchitecture(process_arch);
3155 log->Printf("Process::%s switching architecture to %s based on info "
3156 "the platform retrieved for pid %" PRIu64,
3158 process_arch.GetTriple().getTriple().c_str(), GetID());
3163 // We have completed the attach, now it is time to find the dynamic loader
3165 DynamicLoader *dyld = GetDynamicLoader();
3169 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3170 log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
3171 "executable is %s (using %s plugin)",
3173 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3175 dyld->GetPluginName().AsCString("<unnamed>"));
3179 GetJITLoaders().DidAttach();
3181 SystemRuntime *system_runtime = GetSystemRuntime();
3182 if (system_runtime) {
3183 system_runtime->DidAttach();
3185 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3186 log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
3187 "executable is %s (using %s plugin)",
3189 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3191 system_runtime->GetPluginName().AsCString("<unnamed>"));
3196 LoadOperatingSystemPlugin(false);
3197 // Figure out which one is the executable, and set that in our target:
3198 const ModuleList &target_modules = GetTarget().GetImages();
3199 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3200 size_t num_modules = target_modules.GetSize();
3201 ModuleSP new_executable_module_sp;
3203 for (size_t i = 0; i < num_modules; i++) {
3204 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3205 if (module_sp && module_sp->IsExecutable()) {
3206 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3207 new_executable_module_sp = module_sp;
3211 if (new_executable_module_sp) {
3212 GetTarget().SetExecutableModule(new_executable_module_sp, false);
3214 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3216 "Process::%s after looping through modules, target executable is %s",
3218 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3223 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
3226 Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
3228 m_process_input_reader.reset();
3230 // Find the process and its architecture. Make sure it matches the
3231 // architecture of the current Target, and if not adjust it.
3233 Status error(DoConnectRemote(strm, remote_url));
3234 if (error.Success()) {
3235 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3237 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
3239 if (state == eStateStopped || state == eStateCrashed) {
3240 // If we attached and actually have a process on the other end, then
3241 // this ended up being the equivalent of an attach.
3244 // This delays passing the stopped event to listeners till
3245 // CompleteAttach gets a chance to complete...
3246 HandlePrivateEvent(event_sp);
3250 if (PrivateStateThreadIsValid())
3251 ResumePrivateStateThread();
3253 StartPrivateStateThread();
3258 Status Process::PrivateResume() {
3259 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3262 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3263 "private state: %s",
3264 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3265 StateAsCString(m_private_state.GetValue()));
3267 // If signals handing status changed we might want to update
3268 // our signal filters before resuming.
3269 UpdateAutomaticSignalFiltering();
3271 Status error(WillResume());
3272 // Tell the process it is about to resume before the thread list
3273 if (error.Success()) {
3274 // Now let the thread list know we are about to resume so it
3275 // can let all of our threads know that they are about to be
3276 // resumed. Threads will each be called with
3277 // Thread::WillResume(StateType) where StateType contains the state
3278 // that they are supposed to have when the process is resumed
3279 // (suspended/running/stepping). Threads should also check
3280 // their resume signal in lldb::Thread::GetResumeSignal()
3281 // to see if they are supposed to start back up with a signal.
3282 if (m_thread_list.WillResume()) {
3283 // Last thing, do the PreResumeActions.
3284 if (!RunPreResumeActions()) {
3285 error.SetErrorStringWithFormat(
3286 "Process::PrivateResume PreResumeActions failed, not resuming.");
3288 m_mod_id.BumpResumeID();
3290 if (error.Success()) {
3292 m_thread_list.DidResume();
3294 log->Printf("Process thinks the process has resumed.");
3298 // Somebody wanted to run without running (e.g. we were faking a step from
3299 // one frame of a set of inlined
3300 // frames that share the same PC to another.) So generate a continue & a
3302 // and let the world handle them.
3305 "Process::PrivateResume() asked to simulate a start & stop.");
3307 SetPrivateState(eStateRunning);
3308 SetPrivateState(eStateStopped);
3311 log->Printf("Process::PrivateResume() got an error \"%s\".",
3312 error.AsCString("<unknown error>"));
3316 Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3317 if (!StateIsRunningState(m_public_state.GetValue()))
3318 return Status("Process is not running.");
3320 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3321 // in case it was already set and some thread plan logic calls halt on its
3323 m_clear_thread_plans_on_stop |= clear_thread_plans;
3325 ListenerSP halt_listener_sp(
3326 Listener::MakeListener("lldb.process.halt_listener"));
3327 HijackProcessEvents(halt_listener_sp);
3331 SendAsyncInterrupt();
3333 if (m_public_state.GetValue() == eStateAttaching) {
3334 // Don't hijack and eat the eStateExited as the code that was doing
3335 // the attach will be waiting for this event...
3336 RestoreProcessEvents();
3337 SetExitStatus(SIGKILL, "Cancelled async attach.");
3342 // Wait for 10 second for the process to stop.
3343 StateType state = WaitForProcessToStop(
3344 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
3345 RestoreProcessEvents();
3347 if (state == eStateInvalid || !event_sp) {
3348 // We timed out and didn't get a stop event...
3349 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
3352 BroadcastEvent(event_sp);
3357 Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3360 // Check both the public & private states here. If we're hung evaluating an
3361 // expression, for instance, then
3362 // the public state will be stopped, but we still need to interrupt.
3363 if (m_public_state.GetValue() == eStateRunning ||
3364 m_private_state.GetValue() == eStateRunning) {
3365 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3367 log->Printf("Process::%s() About to stop.", __FUNCTION__);
3369 ListenerSP listener_sp(
3370 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3371 HijackProcessEvents(listener_sp);
3373 SendAsyncInterrupt();
3375 // Consume the interrupt event.
3377 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
3379 RestoreProcessEvents();
3381 // If the process exited while we were waiting for it to stop, put the
3382 // exited event into
3383 // the shared pointer passed in and return. Our caller doesn't need to do
3384 // anything else, since
3385 // they don't have a process anymore...
3387 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3389 log->Printf("Process::%s() Process exited while waiting to stop.",
3393 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3395 if (state != eStateStopped) {
3397 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__,
3398 StateAsCString(state));
3399 // If we really couldn't stop the process then we should just error out
3401 // lower levels just bobbled sending the event and we really are stopped,
3402 // then continue on.
3403 StateType private_state = m_private_state.GetValue();
3404 if (private_state != eStateStopped) {
3406 "Attempt to stop the target in order to detach timed out. "
3408 StateAsCString(GetState()));
3415 Status Process::Detach(bool keep_stopped) {
3416 EventSP exit_event_sp;
3418 m_destroy_in_process = true;
3420 error = WillDetach();
3422 if (error.Success()) {
3423 if (DetachRequiresHalt()) {
3424 error = StopForDestroyOrDetach(exit_event_sp);
3425 if (!error.Success()) {
3426 m_destroy_in_process = false;
3428 } else if (exit_event_sp) {
3429 // We shouldn't need to do anything else here. There's no process left
3430 // to detach from...
3431 StopPrivateStateThread();
3432 m_destroy_in_process = false;
3437 m_thread_list.DiscardThreadPlans();
3438 DisableAllBreakpointSites();
3440 error = DoDetach(keep_stopped);
3441 if (error.Success()) {
3443 StopPrivateStateThread();
3448 m_destroy_in_process = false;
3450 // If we exited when we were waiting for a process to stop, then
3451 // forward the event here so we don't lose the event
3452 if (exit_event_sp) {
3453 // Directly broadcast our exited event because we shut down our
3454 // private state thread above
3455 BroadcastEvent(exit_event_sp);
3458 // If we have been interrupted (to kill us) in the middle of running, we may
3459 // not end up propagating
3460 // the last events through the event system, in which case we might strand the
3461 // write lock. Unlock
3462 // it here so when we do to tear down the process we don't get an error
3463 // destroying the lock.
3465 m_public_run_lock.SetStopped();
3469 Status Process::Destroy(bool force_kill) {
3471 // Tell ourselves we are in the process of destroying the process, so that we
3472 // don't do any unnecessary work
3473 // that might hinder the destruction. Remember to set this back to false when
3474 // we are done. That way if the attempt
3475 // failed and the process stays around for some reason it won't be in a
3479 m_should_detach = false;
3481 if (GetShouldDetach()) {
3482 // FIXME: This will have to be a process setting:
3483 bool keep_stopped = false;
3484 Detach(keep_stopped);
3487 m_destroy_in_process = true;
3489 Status error(WillDestroy());
3490 if (error.Success()) {
3491 EventSP exit_event_sp;
3492 if (DestroyRequiresHalt()) {
3493 error = StopForDestroyOrDetach(exit_event_sp);
3496 if (m_public_state.GetValue() != eStateRunning) {
3497 // Ditch all thread plans, and remove all our breakpoints: in case we have
3498 // to restart the target to
3499 // kill it, we don't want it hitting a breakpoint...
3500 // Only do this if we've stopped, however, since if we didn't manage to
3501 // halt it above, then
3502 // we're not going to have much luck doing this now.
3503 m_thread_list.DiscardThreadPlans();
3504 DisableAllBreakpointSites();
3507 error = DoDestroy();
3508 if (error.Success()) {
3510 StopPrivateStateThread();
3512 m_stdio_communication.Disconnect();
3513 m_stdio_communication.StopReadThread();
3514 m_stdin_forward = false;
3516 if (m_process_input_reader) {
3517 m_process_input_reader->SetIsDone(true);
3518 m_process_input_reader->Cancel();
3519 m_process_input_reader.reset();
3522 // If we exited when we were waiting for a process to stop, then
3523 // forward the event here so we don't lose the event
3524 if (exit_event_sp) {
3525 // Directly broadcast our exited event because we shut down our
3526 // private state thread above
3527 BroadcastEvent(exit_event_sp);
3530 // If we have been interrupted (to kill us) in the middle of running, we may
3531 // not end up propagating
3532 // the last events through the event system, in which case we might strand
3533 // the write lock. Unlock
3534 // it here so when we do to tear down the process we don't get an error
3535 // destroying the lock.
3536 m_public_run_lock.SetStopped();
3539 m_destroy_in_process = false;
3544 Status Process::Signal(int signal) {
3545 Status error(WillSignal());
3546 if (error.Success()) {
3547 error = DoSignal(signal);
3548 if (error.Success())
3554 void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3555 assert(signals_sp && "null signals_sp");
3556 m_unix_signals_sp = signals_sp;
3559 const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3560 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3561 return m_unix_signals_sp;
3564 lldb::ByteOrder Process::GetByteOrder() const {
3565 return GetTarget().GetArchitecture().GetByteOrder();
3568 uint32_t Process::GetAddressByteSize() const {
3569 return GetTarget().GetArchitecture().GetAddressByteSize();
3572 bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3573 const StateType state =
3574 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3575 bool return_value = true;
3576 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3577 LIBLLDB_LOG_PROCESS));
3580 case eStateDetached:
3582 case eStateUnloaded:
3583 m_stdio_communication.SynchronizeWithReadThread();
3584 m_stdio_communication.Disconnect();
3585 m_stdio_communication.StopReadThread();
3586 m_stdin_forward = false;
3589 case eStateConnected:
3590 case eStateAttaching:
3591 case eStateLaunching:
3592 // These events indicate changes in the state of the debugging session,
3593 // always report them.
3594 return_value = true;
3597 // We stopped for no apparent reason, don't report it.
3598 return_value = false;
3601 case eStateStepping:
3602 // If we've started the target running, we handle the cases where we
3603 // are already running and where there is a transition from stopped to
3604 // running differently.
3605 // running -> running: Automatically suppress extra running events
3606 // stopped -> running: Report except when there is one or more no votes
3607 // and no yes votes.
3608 SynchronouslyNotifyStateChanged(state);
3609 if (m_force_next_event_delivery)
3610 return_value = true;
3612 switch (m_last_broadcast_state) {
3614 case eStateStepping:
3615 // We always suppress multiple runnings with no PUBLIC stop in between.
3616 return_value = false;
3619 // TODO: make this work correctly. For now always report
3620 // run if we aren't running so we don't miss any running
3621 // events. If I run the lldb/test/thread/a.out file and
3622 // break at main.cpp:58, run and hit the breakpoints on
3623 // multiple threads, then somehow during the stepping over
3624 // of all breakpoints no run gets reported.
3626 // This is a transition from stop to run.
3627 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3629 case eVoteNoOpinion:
3630 return_value = true;
3633 return_value = false;
3642 case eStateSuspended:
3643 // We've stopped. First see if we're going to restart the target.
3644 // If we are going to stop, then we always broadcast the event.
3645 // If we aren't going to stop, let the thread plans decide if we're going to
3646 // report this event.
3647 // If no thread has an opinion, we don't report it.
3649 m_stdio_communication.SynchronizeWithReadThread();
3650 RefreshStateAfterStop();
3651 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3653 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3654 "interrupt, state: %s",
3655 static_cast<void *>(event_ptr), StateAsCString(state));
3656 // Even though we know we are going to stop, we should let the threads
3657 // have a look at the stop,
3658 // so they can properly set their state.
3659 m_thread_list.ShouldStop(event_ptr);
3660 return_value = true;
3662 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3663 bool should_resume = false;
3665 // It makes no sense to ask "ShouldStop" if we've already been
3667 // Asking the thread list is also not likely to go well, since we are
3669 // So in that case just report the event.
3672 should_resume = !m_thread_list.ShouldStop(event_ptr);
3674 if (was_restarted || should_resume || m_resume_requested) {
3675 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3677 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3678 "%s was_restarted: %i stop_vote: %d.",
3679 should_resume, StateAsCString(state), was_restarted,
3682 switch (stop_vote) {
3684 return_value = true;
3686 case eVoteNoOpinion:
3688 return_value = false;
3692 if (!was_restarted) {
3694 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3696 static_cast<void *>(event_ptr), StateAsCString(state));
3697 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3701 return_value = true;
3702 SynchronouslyNotifyStateChanged(state);
3708 // Forcing the next event delivery is a one shot deal. So reset it here.
3709 m_force_next_event_delivery = false;
3711 // We do some coalescing of events (for instance two consecutive running
3712 // events get coalesced.)
3713 // But we only coalesce against events we actually broadcast. So we use
3714 // m_last_broadcast_state
3715 // to track that. NB - you can't use "m_public_state.GetValue()" for that
3716 // purpose, as was originally done,
3717 // because the PublicState reflects the last event pulled off the queue, and
3718 // there may be several
3719 // events stacked up on the queue unserviced. So the PublicState may not
3720 // reflect the last broadcasted event
3721 // yet. m_last_broadcast_state gets updated here.
3724 m_last_broadcast_state = state;
3727 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3728 "broadcast state: %s - %s",
3729 static_cast<void *>(event_ptr), StateAsCString(state),
3730 StateAsCString(m_last_broadcast_state),
3731 return_value ? "YES" : "NO");
3732 return return_value;
3735 bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3736 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3738 bool already_running = PrivateStateThreadIsValid();
3740 log->Printf("Process::%s()%s ", __FUNCTION__,
3741 already_running ? " already running"
3742 : " starting private state thread");
3744 if (!is_secondary_thread && already_running)
3747 // Create a thread that watches our internal state and controls which
3748 // events make it to clients (into the DCProcess event queue).
3749 char thread_name[1024];
3750 uint32_t max_len = llvm::get_max_thread_name_length();
3751 if (max_len > 0 && max_len <= 30) {
3752 // On platforms with abbreviated thread name lengths, choose thread names
3753 // that fit within the limit.
3754 if (already_running)
3755 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3757 snprintf(thread_name, sizeof(thread_name), "intern-state");
3759 if (already_running)
3760 snprintf(thread_name, sizeof(thread_name),
3761 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3764 snprintf(thread_name, sizeof(thread_name),
3765 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3768 // Create the private state thread, and start it running.
3769 PrivateStateThreadArgs *args_ptr =
3770 new PrivateStateThreadArgs(this, is_secondary_thread);
3771 m_private_state_thread =
3772 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3773 (void *)args_ptr, nullptr, 8 * 1024 * 1024);
3774 if (m_private_state_thread.IsJoinable()) {
3775 ResumePrivateStateThread();
3781 void Process::PausePrivateStateThread() {
3782 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3785 void Process::ResumePrivateStateThread() {
3786 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3789 void Process::StopPrivateStateThread() {
3790 if (m_private_state_thread.IsJoinable())
3791 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3793 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3796 "Went to stop the private state thread, but it was already invalid.");
3800 void Process::ControlPrivateStateThread(uint32_t signal) {
3801 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3803 assert(signal == eBroadcastInternalStateControlStop ||
3804 signal == eBroadcastInternalStateControlPause ||
3805 signal == eBroadcastInternalStateControlResume);
3808 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3810 // Signal the private state thread
3811 if (m_private_state_thread.IsJoinable()) {
3812 // Broadcast the event.
3813 // It is important to do this outside of the if below, because
3814 // it's possible that the thread state is invalid but that the
3815 // thread is waiting on a control event instead of simply being
3816 // on its way out (this should not happen, but it apparently can).
3818 log->Printf("Sending control event of type: %d.", signal);
3819 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3820 m_private_state_control_broadcaster.BroadcastEvent(signal,
3823 // Wait for the event receipt or for the private state thread to exit
3824 bool receipt_received = false;
3825 if (PrivateStateThreadIsValid()) {
3826 while (!receipt_received) {
3827 bool timed_out = false;
3828 // Check for a receipt for 2 seconds and then check if the private state
3829 // thread is still around.
3830 receipt_received = event_receipt_sp->WaitForEventReceived(
3831 std::chrono::seconds(2), &timed_out);
3832 if (!receipt_received) {
3833 // Check if the private state thread is still around. If it isn't then
3834 // we are done waiting
3835 if (!PrivateStateThreadIsValid())
3836 break; // Private state thread exited or is exiting, we are done
3841 if (signal == eBroadcastInternalStateControlStop) {
3842 thread_result_t result = NULL;
3843 m_private_state_thread.Join(&result);
3844 m_private_state_thread.Reset();
3849 "Private state thread already dead, no need to signal it to stop.");
3853 void Process::SendAsyncInterrupt() {
3854 if (PrivateStateThreadIsValid())
3855 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3858 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3861 void Process::HandlePrivateEvent(EventSP &event_sp) {
3862 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3863 m_resume_requested = false;
3865 const StateType new_state =
3866 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3868 // First check to see if anybody wants a shot at this event:
3869 if (m_next_event_action_ap) {
3870 NextEventAction::EventActionResult action_result =
3871 m_next_event_action_ap->PerformAction(event_sp);
3873 log->Printf("Ran next event action, result was %d.", action_result);
3875 switch (action_result) {
3876 case NextEventAction::eEventActionSuccess:
3877 SetNextEventAction(nullptr);
3880 case NextEventAction::eEventActionRetry:
3883 case NextEventAction::eEventActionExit:
3884 // Handle Exiting Here. If we already got an exited event,
3885 // we should just propagate it. Otherwise, swallow this event,
3886 // and set our state to exit so the next event will kill us.
3887 if (new_state != eStateExited) {
3888 // FIXME: should cons up an exited event, and discard this one.
3889 SetExitStatus(0, m_next_event_action_ap->GetExitString());
3890 SetNextEventAction(nullptr);
3893 SetNextEventAction(nullptr);
3898 // See if we should broadcast this state to external clients?
3899 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3901 if (should_broadcast) {
3902 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3904 log->Printf("Process::%s (pid = %" PRIu64
3905 ") broadcasting new state %s (old state %s) to %s",
3906 __FUNCTION__, GetID(), StateAsCString(new_state),
3907 StateAsCString(GetState()),
3908 is_hijacked ? "hijacked" : "public");
3910 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3911 if (StateIsRunningState(new_state)) {
3912 // Only push the input handler if we aren't fowarding events,
3913 // as this means the curses GUI is in use...
3914 // Or don't push it if we are launching since it will come up stopped.
3915 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3916 new_state != eStateLaunching && new_state != eStateAttaching) {
3917 PushProcessIOHandler();
3918 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3921 log->Printf("Process::%s updated m_iohandler_sync to %d",
3922 __FUNCTION__, m_iohandler_sync.GetValue());
3924 } else if (StateIsStoppedState(new_state, false)) {
3925 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
3926 // If the lldb_private::Debugger is handling the events, we don't
3927 // want to pop the process IOHandler here, we want to do it when
3928 // we receive the stopped event so we can carefully control when
3929 // the process IOHandler is popped because when we stop we want to
3930 // display some text stating how and why we stopped, then maybe some
3931 // process/thread/frame info, and then we want the "(lldb) " prompt
3932 // to show up. If we pop the process IOHandler here, then we will
3933 // cause the command interpreter to become the top IOHandler after
3934 // the process pops off and it will update its prompt right away...
3935 // See the Debugger.cpp file where it calls the function as
3936 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3937 // Otherwise we end up getting overlapping "(lldb) " prompts and
3940 // If we aren't handling the events in the debugger (which is indicated
3941 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
3942 // are hijacked, then we always pop the process IO handler manually.
3943 // Hijacking happens when the internal process state thread is running
3944 // thread plans, or when commands want to run in synchronous mode
3945 // and they call "process->WaitForProcessToStop()". An example of
3947 // that will hijack the events is a simple expression:
3949 // (lldb) expr (int)puts("hello")
3951 // This will cause the internal process state thread to resume and halt
3952 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3953 // events) and we do need the IO handler to be pushed and popped
3956 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3957 PopProcessIOHandler();
3961 BroadcastEvent(event_sp);
3965 "Process::%s (pid = %" PRIu64
3966 ") suppressing state %s (old state %s): should_broadcast == false",
3967 __FUNCTION__, GetID(), StateAsCString(new_state),
3968 StateAsCString(GetState()));
3973 Status Process::HaltPrivate() {
3975 Status error(WillHalt());
3979 // Ask the process subclass to actually halt our process
3981 error = DoHalt(caused_stop);
3987 thread_result_t Process::PrivateStateThread(void *arg) {
3988 std::unique_ptr<PrivateStateThreadArgs> args_up(
3989 static_cast<PrivateStateThreadArgs *>(arg));
3990 thread_result_t result =
3991 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3995 thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3996 bool control_only = true;
3998 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4000 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4001 __FUNCTION__, static_cast<void *>(this), GetID());
4003 bool exit_now = false;
4004 bool interrupt_requested = false;
4007 GetEventsPrivate(event_sp, llvm::None, control_only);
4008 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
4010 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4011 ") got a control event: %d",
4012 __FUNCTION__, static_cast<void *>(this), GetID(),
4013 event_sp->GetType());
4015 switch (event_sp->GetType()) {
4016 case eBroadcastInternalStateControlStop:
4018 break; // doing any internal state management below
4020 case eBroadcastInternalStateControlPause:
4021 control_only = true;
4024 case eBroadcastInternalStateControlResume:
4025 control_only = false;
4030 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
4031 if (m_public_state.GetValue() == eStateAttaching) {
4033 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4034 ") woke up with an interrupt while attaching - "
4035 "forwarding interrupt.",
4036 __FUNCTION__, static_cast<void *>(this), GetID());
4037 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
4038 } else if (StateIsRunningState(m_last_broadcast_state)) {
4040 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4041 ") woke up with an interrupt - Halting.",
4042 __FUNCTION__, static_cast<void *>(this), GetID());
4043 Status error = HaltPrivate();
4044 if (error.Fail() && log)
4045 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4046 ") failed to halt the process: %s",
4047 __FUNCTION__, static_cast<void *>(this), GetID(),
4049 // Halt should generate a stopped event. Make a note of the fact that we
4051 // doing the interrupt, so we can set the interrupted flag after we
4053 // event. We deliberately set this to true even if HaltPrivate failed,
4055 // can interrupt on the next natural stop.
4056 interrupt_requested = true;
4058 // This can happen when someone (e.g. Process::Halt) sees that we are
4060 // sends an interrupt request, but the process actually stops before we
4062 // it. In that case, we can just ignore the request. We use
4063 // m_last_broadcast_state, because the Stopped event may not have been
4065 // the event queue yet, which is when the public state gets updated.
4068 "Process::%s ignoring interrupt as we have already stopped.",
4074 const StateType internal_state =
4075 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4077 if (internal_state != eStateInvalid) {
4078 if (m_clear_thread_plans_on_stop &&
4079 StateIsStoppedState(internal_state, true)) {
4080 m_clear_thread_plans_on_stop = false;
4081 m_thread_list.DiscardThreadPlans();
4084 if (interrupt_requested) {
4085 if (StateIsStoppedState(internal_state, true)) {
4086 // We requested the interrupt, so mark this as such in the stop event
4088 // clients can tell an interrupted process from a natural stop
4089 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
4090 interrupt_requested = false;
4092 log->Printf("Process::%s interrupt_requested, but a non-stopped "
4093 "state '%s' received.",
4094 __FUNCTION__, StateAsCString(internal_state));
4098 HandlePrivateEvent(event_sp);
4101 if (internal_state == eStateInvalid || internal_state == eStateExited ||
4102 internal_state == eStateDetached) {
4104 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4105 ") about to exit with internal state %s...",
4106 __FUNCTION__, static_cast<void *>(this), GetID(),
4107 StateAsCString(internal_state));
4113 // Verify log is still enabled before attempting to write to it...
4115 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4116 __FUNCTION__, static_cast<void *>(this), GetID());
4118 // If we are a secondary thread, then the primary thread we are working for
4119 // will have already
4120 // acquired the public_run_lock, and isn't done with what it was doing yet, so
4122 // try to change it on the way out.
4123 if (!is_secondary_thread)
4124 m_public_run_lock.SetStopped();
4128 //------------------------------------------------------------------
4129 // Process Event Data
4130 //------------------------------------------------------------------
4132 Process::ProcessEventData::ProcessEventData()
4133 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
4134 m_update_state(0), m_interrupted(false) {}
4136 Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
4138 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
4139 m_update_state(0), m_interrupted(false) {
4141 m_process_wp = process_sp;
4144 Process::ProcessEventData::~ProcessEventData() = default;
4146 const ConstString &Process::ProcessEventData::GetFlavorString() {
4147 static ConstString g_flavor("Process::ProcessEventData");
4151 const ConstString &Process::ProcessEventData::GetFlavor() const {
4152 return ProcessEventData::GetFlavorString();
4155 void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
4156 ProcessSP process_sp(m_process_wp.lock());
4161 // This function gets called twice for each event, once when the event gets
4163 // off of the private process event queue, and then any number of times, first
4164 // when it gets pulled off of
4165 // the public event queue, then other times when we're pretending that this is
4166 // where we stopped at the
4167 // end of expression evaluation. m_update_state is used to distinguish these
4168 // three cases; it is 0 when we're just pulling it off for private handling,
4169 // and > 1 for expression evaluation, and we don't want to do the breakpoint
4170 // command handling then.
4171 if (m_update_state != 1)
4174 process_sp->SetPublicState(
4175 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4177 if (m_state == eStateStopped && !m_restarted) {
4178 // Let process subclasses know we are about to do a public stop and
4179 // do anything they might need to in order to speed up register and
4181 process_sp->WillPublicStop();
4184 // If this is a halt event, even if the halt stopped with some reason other
4185 // than a plain interrupt (e.g. we had
4186 // already stopped for a breakpoint when the halt request came through) don't
4187 // do the StopInfo actions, as they may
4188 // end up restarting the process.
4192 // If we're stopped and haven't restarted, then do the StopInfo actions here:
4193 if (m_state == eStateStopped && !m_restarted) {
4194 ThreadList &curr_thread_list = process_sp->GetThreadList();
4195 uint32_t num_threads = curr_thread_list.GetSize();
4198 // The actions might change one of the thread's stop_info's opinions about
4199 // whether we should
4200 // stop the process, so we need to query that as we go.
4202 // One other complication here, is that we try to catch any case where the
4203 // target has run (except for expressions)
4204 // and immediately exit, but if we get that wrong (which is possible) then
4205 // the thread list might have changed, and
4206 // that would cause our iteration here to crash. We could make a copy of
4207 // the thread list, but we'd really like
4208 // to also know if it has changed at all, so we make up a vector of the
4209 // thread ID's and check what we get back
4210 // against this list & bag out if anything differs.
4211 std::vector<uint32_t> thread_index_array(num_threads);
4212 for (idx = 0; idx < num_threads; ++idx)
4213 thread_index_array[idx] =
4214 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4216 // Use this to track whether we should continue from here. We will only
4217 // continue the target running if
4218 // no thread says we should stop. Of course if some thread's PerformAction
4219 // actually sets the target running,
4220 // then it doesn't matter what the other threads say...
4222 bool still_should_stop = false;
4224 // Sometimes - for instance if we have a bug in the stub we are talking to,
4225 // we stop but no thread has a
4226 // valid stop reason. In that case we should just stop, because we have no
4227 // way of telling what the right
4228 // thing to do is, and it's better to let the user decide than continue
4229 // behind their backs.
4231 bool does_anybody_have_an_opinion = false;
4233 for (idx = 0; idx < num_threads; ++idx) {
4234 curr_thread_list = process_sp->GetThreadList();
4235 if (curr_thread_list.GetSize() != num_threads) {
4236 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4237 LIBLLDB_LOG_PROCESS));
4240 "Number of threads changed from %u to %u while processing event.",
4241 num_threads, curr_thread_list.GetSize());
4245 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4247 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4248 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4249 LIBLLDB_LOG_PROCESS));
4251 log->Printf("The thread at position %u changed from %u to %u while "
4252 "processing event.",
4253 idx, thread_index_array[idx], thread_sp->GetIndexID());
4257 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4258 if (stop_info_sp && stop_info_sp->IsValid()) {
4259 does_anybody_have_an_opinion = true;
4260 bool this_thread_wants_to_stop;
4261 if (stop_info_sp->GetOverrideShouldStop()) {
4262 this_thread_wants_to_stop =
4263 stop_info_sp->GetOverriddenShouldStopValue();
4265 stop_info_sp->PerformAction(event_ptr);
4266 // The stop action might restart the target. If it does, then we want
4267 // to mark that in the
4268 // event so that whoever is receiving it will know to wait for the
4269 // running event and reflect
4270 // that state appropriately.
4271 // We also need to stop processing actions, since they aren't
4272 // expecting the target to be running.
4274 // FIXME: we might have run.
4275 if (stop_info_sp->HasTargetRunSinceMe()) {
4280 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4283 if (!still_should_stop)
4284 still_should_stop = this_thread_wants_to_stop;
4288 if (!GetRestarted()) {
4289 if (!still_should_stop && does_anybody_have_an_opinion) {
4290 // We've been asked to continue, so do that here.
4292 // Use the public resume method here, since this is just
4293 // extending a public resume.
4294 process_sp->PrivateResume();
4296 // If we didn't restart, run the Stop Hooks here:
4297 // They might also restart the target, so watch for that.
4298 process_sp->GetTarget().RunStopHooks();
4299 if (process_sp->GetPrivateState() == eStateRunning)
4306 void Process::ProcessEventData::Dump(Stream *s) const {
4307 ProcessSP process_sp(m_process_wp.lock());
4310 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4311 static_cast<void *>(process_sp.get()), process_sp->GetID());
4313 s->PutCString(" process = NULL, ");
4315 s->Printf("state = %s", StateAsCString(GetState()));
4318 const Process::ProcessEventData *
4319 Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4321 const EventData *event_data = event_ptr->GetData();
4323 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4324 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4330 Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4331 ProcessSP process_sp;
4332 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4334 process_sp = data->GetProcessSP();
4338 StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4339 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4340 if (data == nullptr)
4341 return eStateInvalid;
4343 return data->GetState();
4346 bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4347 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4348 if (data == nullptr)
4351 return data->GetRestarted();
4354 void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4356 ProcessEventData *data =
4357 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4358 if (data != nullptr)
4359 data->SetRestarted(new_value);
4363 Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4364 ProcessEventData *data =
4365 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4366 if (data != nullptr)
4367 return data->GetNumRestartedReasons();
4373 Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4375 ProcessEventData *data =
4376 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4377 if (data != nullptr)
4378 return data->GetRestartedReasonAtIndex(idx);
4383 void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4384 const char *reason) {
4385 ProcessEventData *data =
4386 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4387 if (data != nullptr)
4388 data->AddRestartedReason(reason);
4391 bool Process::ProcessEventData::GetInterruptedFromEvent(
4392 const Event *event_ptr) {
4393 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4394 if (data == nullptr)
4397 return data->GetInterrupted();
4400 void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4402 ProcessEventData *data =
4403 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4404 if (data != nullptr)
4405 data->SetInterrupted(new_value);
4408 bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4409 ProcessEventData *data =
4410 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4412 data->SetUpdateStateOnRemoval();
4418 lldb::TargetSP Process::CalculateTarget() { return m_target_sp.lock(); }
4420 void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4421 exe_ctx.SetTargetPtr(&GetTarget());
4422 exe_ctx.SetProcessPtr(this);
4423 exe_ctx.SetThreadPtr(nullptr);
4424 exe_ctx.SetFramePtr(nullptr);
4428 // Process::ListProcessesMatchingName (const char *name, StringList &matches,
4429 // std::vector<lldb::pid_t> &pids)
4435 // Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4437 // return Host::GetArchSpecForExistingProcess (pid);
4441 // Process::GetArchSpecForExistingProcess (const char *process_name)
4443 // return Host::GetArchSpecForExistingProcess (process_name);
4446 void Process::AppendSTDOUT(const char *s, size_t len) {
4447 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4448 m_stdout_data.append(s, len);
4449 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4450 new ProcessEventData(shared_from_this(), GetState()));
4453 void Process::AppendSTDERR(const char *s, size_t len) {
4454 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4455 m_stderr_data.append(s, len);
4456 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4457 new ProcessEventData(shared_from_this(), GetState()));
4460 void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4461 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4462 m_profile_data.push_back(one_profile_data);
4463 BroadcastEventIfUnique(eBroadcastBitProfileData,
4464 new ProcessEventData(shared_from_this(), GetState()));
4467 void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4468 const StructuredDataPluginSP &plugin_sp) {
4470 eBroadcastBitStructuredData,
4471 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
4474 StructuredDataPluginSP
4475 Process::GetStructuredDataPlugin(const ConstString &type_name) const {
4476 auto find_it = m_structured_data_plugin_map.find(type_name);
4477 if (find_it != m_structured_data_plugin_map.end())
4478 return find_it->second;
4480 return StructuredDataPluginSP();
4483 size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
4484 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4485 if (m_profile_data.empty())
4488 std::string &one_profile_data = m_profile_data.front();
4489 size_t bytes_available = one_profile_data.size();
4490 if (bytes_available > 0) {
4491 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4493 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4494 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4495 if (bytes_available > buf_size) {
4496 memcpy(buf, one_profile_data.c_str(), buf_size);
4497 one_profile_data.erase(0, buf_size);
4498 bytes_available = buf_size;
4500 memcpy(buf, one_profile_data.c_str(), bytes_available);
4501 m_profile_data.erase(m_profile_data.begin());
4504 return bytes_available;
4507 //------------------------------------------------------------------
4509 //------------------------------------------------------------------
4511 size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
4512 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4513 size_t bytes_available = m_stdout_data.size();
4514 if (bytes_available > 0) {
4515 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4517 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4518 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4519 if (bytes_available > buf_size) {
4520 memcpy(buf, m_stdout_data.c_str(), buf_size);
4521 m_stdout_data.erase(0, buf_size);
4522 bytes_available = buf_size;
4524 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4525 m_stdout_data.clear();
4528 return bytes_available;
4531 size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
4532 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4533 size_t bytes_available = m_stderr_data.size();
4534 if (bytes_available > 0) {
4535 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4537 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4538 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4539 if (bytes_available > buf_size) {
4540 memcpy(buf, m_stderr_data.c_str(), buf_size);
4541 m_stderr_data.erase(0, buf_size);
4542 bytes_available = buf_size;
4544 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4545 m_stderr_data.clear();
4548 return bytes_available;
4551 void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4553 Process *process = (Process *)baton;
4554 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
4557 class IOHandlerProcessSTDIO : public IOHandler {
4559 IOHandlerProcessSTDIO(Process *process, int write_fd)
4560 : IOHandler(process->GetTarget().GetDebugger(),
4561 IOHandler::Type::ProcessIO),
4562 m_process(process), m_write_file(write_fd, false) {
4563 m_pipe.CreateNew(false);
4564 m_read_file.SetDescriptor(GetInputFD(), false);
4567 ~IOHandlerProcessSTDIO() override = default;
4569 // Each IOHandler gets to run until it is done. It should read data
4570 // from the "in" and place output into "out" and "err and return
4572 void Run() override {
4573 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4574 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4580 const int read_fd = m_read_file.GetDescriptor();
4581 TerminalState terminal_state;
4582 terminal_state.Save(read_fd, false);
4583 Terminal terminal(read_fd);
4584 terminal.SetCanonical(false);
4585 terminal.SetEcho(false);
4586 // FD_ZERO, FD_SET are not supported on windows
4588 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4589 m_is_running = true;
4590 while (!GetIsDone()) {
4591 SelectHelper select_helper;
4592 select_helper.FDSetRead(read_fd);
4593 select_helper.FDSetRead(pipe_read_fd);
4594 Status error = select_helper.Select();
4601 if (select_helper.FDIsSetRead(read_fd)) {
4603 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4604 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4609 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4611 // Consume the interrupt byte
4612 Status error = m_pipe.Read(&ch, 1, bytes_read);
4613 if (error.Success()) {
4619 if (StateIsRunningState(m_process->GetState()))
4620 m_process->SendAsyncInterrupt();
4627 m_is_running = false;
4629 terminal_state.Restore();
4632 void Cancel() override {
4634 // Only write to our pipe to cancel if we are in
4635 // IOHandlerProcessSTDIO::Run().
4636 // We can end up with a python command that is being run from the command
4639 // (lldb) step_process_thousands_of_times
4641 // In this case the command interpreter will be in the middle of handling
4642 // the command and if the process pushes and pops the IOHandler thousands
4643 // of times, we can end up writing to m_pipe without ever consuming the
4644 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4645 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4647 char ch = 'q'; // Send 'q' for quit
4648 size_t bytes_written = 0;
4649 m_pipe.Write(&ch, 1, bytes_written);
4653 bool Interrupt() override {
4654 // Do only things that are safe to do in an interrupt context (like in
4655 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4656 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4657 // that was written to the pipe and then call
4658 // m_process->SendAsyncInterrupt()
4659 // from a much safer location in code.
4661 char ch = 'i'; // Send 'i' for interrupt
4662 size_t bytes_written = 0;
4663 Status result = m_pipe.Write(&ch, 1, bytes_written);
4664 return result.Success();
4666 // This IOHandler might be pushed on the stack, but not being run
4668 // so do the right thing if we aren't actively watching for STDIN by
4670 // the interrupt to the process. Otherwise the write to the pipe above
4672 // do nothing. This can happen when the command interpreter is running and
4673 // gets a "expression ...". It will be on the IOHandler thread and sending
4674 // the input is complete to the delegate which will cause the expression
4676 // run, which will push the process IO handler, but not run it.
4678 if (StateIsRunningState(m_process->GetState())) {
4679 m_process->SendAsyncInterrupt();
4686 void GotEOF() override {}
4690 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4691 File m_write_file; // Write to this file (usually the master pty for getting
4694 std::atomic<bool> m_is_running{false};
4697 void Process::SetSTDIOFileDescriptor(int fd) {
4698 // First set up the Read Thread for reading/handling process I/O
4700 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
4701 new ConnectionFileDescriptor(fd, true));
4704 m_stdio_communication.SetConnection(conn_ap.release());
4705 if (m_stdio_communication.IsConnected()) {
4706 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4707 STDIOReadThreadBytesReceived, this);
4708 m_stdio_communication.StartReadThread();
4710 // Now read thread is set up, set up input reader.
4712 if (!m_process_input_reader)
4713 m_process_input_reader.reset(new IOHandlerProcessSTDIO(this, fd));
4718 bool Process::ProcessIOHandlerIsActive() {
4719 IOHandlerSP io_handler_sp(m_process_input_reader);
4721 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4724 bool Process::PushProcessIOHandler() {
4725 IOHandlerSP io_handler_sp(m_process_input_reader);
4726 if (io_handler_sp) {
4727 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4729 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
4731 io_handler_sp->SetIsDone(false);
4732 GetTarget().GetDebugger().PushIOHandler(io_handler_sp);
4738 bool Process::PopProcessIOHandler() {
4739 IOHandlerSP io_handler_sp(m_process_input_reader);
4741 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4745 // The process needs to know about installed plug-ins
4746 void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
4748 void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
4751 // RestorePlanState is used to record the "is private", "is master" and "okay to
4752 // discard" fields of
4753 // the plan we are running, and reset it on Clean or on destruction.
4754 // It will only reset the state once, so you can call Clean and then monkey with
4756 // won't get reset on you again.
4758 class RestorePlanState {
4760 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4761 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4762 if (m_thread_plan_sp) {
4763 m_private = m_thread_plan_sp->GetPrivate();
4764 m_is_master = m_thread_plan_sp->IsMasterPlan();
4765 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4769 ~RestorePlanState() { Clean(); }
4772 if (!m_already_reset && m_thread_plan_sp) {
4773 m_already_reset = true;
4774 m_thread_plan_sp->SetPrivate(m_private);
4775 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4776 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4781 lldb::ThreadPlanSP m_thread_plan_sp;
4782 bool m_already_reset;
4785 bool m_okay_to_discard;
4787 } // anonymous namespace
4790 GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4791 const milliseconds default_one_thread_timeout(250);
4793 // If the overall wait is forever, then we don't need to worry about it.
4794 if (!options.GetTimeout()) {
4795 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4796 : default_one_thread_timeout;
4799 // If the one thread timeout is set, use it.
4800 if (options.GetOneThreadTimeout())
4801 return *options.GetOneThreadTimeout();
4803 // Otherwise use half the total timeout, bounded by the
4804 // default_one_thread_timeout.
4805 return std::min<microseconds>(default_one_thread_timeout,
4806 *options.GetTimeout() / 2);
4809 static Timeout<std::micro>
4810 GetExpressionTimeout(const EvaluateExpressionOptions &options,
4811 bool before_first_timeout) {
4812 // If we are going to run all threads the whole time, or if we are only
4813 // going to run one thread, we can just return the overall timeout.
4814 if (!options.GetStopOthers() || !options.GetTryAllThreads())
4815 return options.GetTimeout();
4817 if (before_first_timeout)
4818 return GetOneThreadExpressionTimeout(options);
4820 if (!options.GetTimeout())
4823 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
4826 static llvm::Optional<ExpressionResults>
4827 HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
4828 RestorePlanState &restorer, const EventSP &event_sp,
4829 EventSP &event_to_broadcast_sp,
4830 const EvaluateExpressionOptions &options, bool handle_interrupts) {
4831 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4833 ThreadPlanSP plan = thread.GetCompletedPlan();
4834 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4835 LLDB_LOG(log, "execution completed successfully");
4837 // Restore the plan state so it will get reported as intended when we are
4840 return eExpressionCompleted;
4843 StopInfoSP stop_info_sp = thread.GetStopInfo();
4844 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4845 stop_info_sp->ShouldNotify(event_sp.get())) {
4846 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4847 if (!options.DoesIgnoreBreakpoints()) {
4848 // Restore the plan state and then force Private to false. We are going
4849 // to stop because of this plan so we need it to become a public plan or
4850 // it won't report correctly when we continue to its termination later on.
4852 thread_plan_sp->SetPrivate(false);
4853 event_to_broadcast_sp = event_sp;
4855 return eExpressionHitBreakpoint;
4858 if (!handle_interrupts &&
4859 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4862 LLDB_LOG(log, "thread plan did not successfully complete");
4863 if (!options.DoesUnwindOnError())
4864 event_to_broadcast_sp = event_sp;
4865 return eExpressionInterrupted;
4869 Process::RunThreadPlan(ExecutionContext &exe_ctx,
4870 lldb::ThreadPlanSP &thread_plan_sp,
4871 const EvaluateExpressionOptions &options,
4872 DiagnosticManager &diagnostic_manager) {
4873 ExpressionResults return_value = eExpressionSetupError;
4875 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4877 if (!thread_plan_sp) {
4878 diagnostic_manager.PutString(
4879 eDiagnosticSeverityError,
4880 "RunThreadPlan called with empty thread plan.");
4881 return eExpressionSetupError;
4884 if (!thread_plan_sp->ValidatePlan(nullptr)) {
4885 diagnostic_manager.PutString(
4886 eDiagnosticSeverityError,
4887 "RunThreadPlan called with an invalid thread plan.");
4888 return eExpressionSetupError;
4891 if (exe_ctx.GetProcessPtr() != this) {
4892 diagnostic_manager.PutString(eDiagnosticSeverityError,
4893 "RunThreadPlan called on wrong process.");
4894 return eExpressionSetupError;
4897 Thread *thread = exe_ctx.GetThreadPtr();
4898 if (thread == nullptr) {
4899 diagnostic_manager.PutString(eDiagnosticSeverityError,
4900 "RunThreadPlan called with invalid thread.");
4901 return eExpressionSetupError;
4904 // We need to change some of the thread plan attributes for the thread plan
4905 // runner. This will restore them
4906 // when we are done:
4908 RestorePlanState thread_plan_restorer(thread_plan_sp);
4910 // We rely on the thread plan we are running returning "PlanCompleted" if when
4911 // it successfully completes.
4912 // For that to be true the plan can't be private - since private plans
4913 // suppress themselves in the
4914 // GetCompletedPlan call.
4916 thread_plan_sp->SetPrivate(false);
4918 // The plans run with RunThreadPlan also need to be terminal master plans or
4919 // when they are done we will end
4920 // up asking the plan above us whether we should stop, which may give the
4923 thread_plan_sp->SetIsMasterPlan(true);
4924 thread_plan_sp->SetOkayToDiscard(false);
4926 if (m_private_state.GetValue() != eStateStopped) {
4927 diagnostic_manager.PutString(
4928 eDiagnosticSeverityError,
4929 "RunThreadPlan called while the private state was not stopped.");
4930 return eExpressionSetupError;
4933 // Save the thread & frame from the exe_ctx for restoration after we run
4934 const uint32_t thread_idx_id = thread->GetIndexID();
4935 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4936 if (!selected_frame_sp) {
4937 thread->SetSelectedFrame(nullptr);
4938 selected_frame_sp = thread->GetSelectedFrame();
4939 if (!selected_frame_sp) {
4940 diagnostic_manager.Printf(
4941 eDiagnosticSeverityError,
4942 "RunThreadPlan called without a selected frame on thread %d",
4944 return eExpressionSetupError;
4948 // Make sure the timeout values make sense. The one thread timeout needs to be
4949 // smaller than the overall timeout.
4950 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4951 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
4952 diagnostic_manager.PutString(eDiagnosticSeverityError,
4953 "RunThreadPlan called with one thread "
4954 "timeout greater than total timeout");
4955 return eExpressionSetupError;
4958 StackID ctx_frame_id = selected_frame_sp->GetStackID();
4960 // N.B. Running the target may unset the currently selected thread and frame.
4961 // We don't want to do that either,
4962 // so we should arrange to reset them as well.
4964 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
4966 uint32_t selected_tid;
4967 StackID selected_stack_id;
4968 if (selected_thread_sp) {
4969 selected_tid = selected_thread_sp->GetIndexID();
4970 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4972 selected_tid = LLDB_INVALID_THREAD_ID;
4975 HostThread backup_private_state_thread;
4976 lldb::StateType old_state = eStateInvalid;
4977 lldb::ThreadPlanSP stopper_base_plan_sp;
4979 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4980 LIBLLDB_LOG_PROCESS));
4981 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4982 // Yikes, we are running on the private state thread! So we can't wait for
4983 // public events on this thread, since
4984 // we are the thread that is generating public events.
4985 // The simplest thing to do is to spin up a temporary thread to handle
4986 // private state thread events while
4987 // we are fielding public events here.
4989 log->Printf("Running thread plan on private state thread, spinning up "
4990 "another state thread to handle the events.");
4992 backup_private_state_thread = m_private_state_thread;
4994 // One other bit of business: we want to run just this thread plan and
4995 // anything it pushes, and then stop,
4996 // returning control here.
4997 // But in the normal course of things, the plan above us on the stack would
4998 // be given a shot at the stop
4999 // event before deciding to stop, and we don't want that. So we insert a
5000 // "stopper" base plan on the stack
5001 // before the plan we want to run. Since base plans always stop and return
5002 // control to the user, that will
5003 // do just what we want.
5004 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
5005 thread->QueueThreadPlan(stopper_base_plan_sp, false);
5006 // Have to make sure our public state is stopped, since otherwise the
5007 // reporting logic below doesn't work correctly.
5008 old_state = m_public_state.GetValue();
5009 m_public_state.SetValueNoLock(eStateStopped);
5011 // Now spin up the private state thread:
5012 StartPrivateStateThread(true);
5015 thread->QueueThreadPlan(
5016 thread_plan_sp, false); // This used to pass "true" does that make sense?
5018 if (options.GetDebug()) {
5019 // In this case, we aren't actually going to run, we just want to stop right
5021 // Flush this thread so we will refetch the stacks and show the correct
5023 // FIXME: To make this prettier we should invent some stop reason for this,
5025 // is only cosmetic, and this functionality is only of use to lldb
5026 // developers who can
5027 // live with not pretty...
5029 return eExpressionStoppedForDebug;
5032 ListenerSP listener_sp(
5033 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
5035 lldb::EventSP event_to_broadcast_sp;
5038 // This process event hijacker Hijacks the Public events and its destructor
5039 // makes sure that the process events get
5040 // restored on exit to the function.
5042 // If the event needs to propagate beyond the hijacker (e.g., the process
5043 // exits during execution), then the event
5044 // is put into event_to_broadcast_sp for rebroadcasting.
5046 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
5050 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
5051 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
5052 " to run thread plan \"%s\".",
5053 thread->GetIndexID(), thread->GetID(), s.GetData());
5057 lldb::EventSP event_sp;
5058 lldb::StateType stop_state = lldb::eStateInvalid;
5060 bool before_first_timeout = true; // This is set to false the first time
5061 // that we have to halt the target.
5062 bool do_resume = true;
5063 bool handle_running_event = true;
5065 // This is just for accounting:
5066 uint32_t num_resumes = 0;
5068 // If we are going to run all threads the whole time, or if we are only
5069 // going to run one thread, then we don't need the first timeout. So we
5070 // pretend we are after the first timeout already.
5071 if (!options.GetStopOthers() || !options.GetTryAllThreads())
5072 before_first_timeout = false;
5075 log->Printf("Stop others: %u, try all: %u, before_first: %u.\n",
5076 options.GetStopOthers(), options.GetTryAllThreads(),
5077 before_first_timeout);
5079 // This isn't going to work if there are unfetched events on the queue.
5080 // Are there cases where we might want to run the remaining events here, and
5082 // call the function? That's probably being too tricky for our own good.
5084 Event *other_events = listener_sp->PeekAtNextEvent();
5085 if (other_events != nullptr) {
5086 diagnostic_manager.PutString(
5087 eDiagnosticSeverityError,
5088 "RunThreadPlan called with pending events on the queue.");
5089 return eExpressionSetupError;
5092 // We also need to make sure that the next event is delivered. We might be
5093 // calling a function as part of
5094 // a thread plan, in which case the last delivered event could be the
5095 // running event, and we don't want
5096 // event coalescing to cause us to lose OUR running event...
5097 ForceNextEventDelivery();
5099 // This while loop must exit out the bottom, there's cleanup that we need to do
5100 // when we are done.
5101 // So don't call return anywhere within it.
5103 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5104 // It's pretty much impossible to write test cases for things like:
5105 // One thread timeout expires, I go to halt, but the process already stopped
5106 // on the function call stop breakpoint. Turning on this define will make
5108 // fetch the first event till after the halt. So if you run a quick
5109 // function, it will have
5110 // completed, and the completion event will be waiting, when you interrupt
5112 // The expression evaluation should still succeed.
5113 bool miss_first_event = true;
5116 // We usually want to resume the process if we get to the top of the loop.
5117 // The only exception is if we get two running events with no intervening
5118 // stop, which can happen, we will just wait for then next stop event.
5120 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
5121 "before_first_timeout: %i.",
5122 do_resume, handle_running_event, before_first_timeout);
5124 if (do_resume || handle_running_event) {
5125 // Do the initial resume and wait for the running event before going
5130 Status resume_error = PrivateResume();
5131 if (!resume_error.Success()) {
5132 diagnostic_manager.Printf(
5133 eDiagnosticSeverityError,
5134 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5135 resume_error.AsCString());
5136 return_value = eExpressionSetupError;
5142 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
5145 log->Printf("Process::RunThreadPlan(): didn't get any event after "
5146 "resume %" PRIu32 ", exiting.",
5149 diagnostic_manager.Printf(eDiagnosticSeverityError,
5150 "didn't get any event after resume %" PRIu32
5153 return_value = eExpressionSetupError;
5158 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5160 if (stop_state != eStateRunning) {
5161 bool restarted = false;
5163 if (stop_state == eStateStopped) {
5164 restarted = Process::ProcessEventData::GetRestartedFromEvent(
5168 "Process::RunThreadPlan(): didn't get running event after "
5169 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5170 "handle_running_event: %i).",
5171 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5172 handle_running_event);
5176 // This is probably an overabundance of caution, I don't think I
5177 // should ever get a stopped & restarted
5178 // event here. But if I do, the best thing is to Halt and then get
5180 const bool clear_thread_plans = false;
5181 const bool use_run_lock = false;
5182 Halt(clear_thread_plans, use_run_lock);
5185 diagnostic_manager.Printf(
5186 eDiagnosticSeverityError,
5187 "didn't get running event after initial resume, got %s instead.",
5188 StateAsCString(stop_state));
5189 return_value = eExpressionSetupError;
5194 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
5195 // We need to call the function synchronously, so spin waiting for it to
5197 // If we get interrupted while executing, we're going to lose our
5199 // won't be able to gather the result at this point.
5200 // We set the timeout AFTER the resume, since the resume takes some time
5202 // don't want to charge that to the timeout.
5205 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5209 handle_running_event = true;
5211 // Now wait for the process to stop again:
5214 Timeout<std::micro> timeout =
5215 GetExpressionTimeout(options, before_first_timeout);
5218 auto now = system_clock::now();
5219 log->Printf("Process::RunThreadPlan(): about to wait - now is %s - "
5221 llvm::to_string(now).c_str(),
5222 llvm::to_string(now + *timeout).c_str());
5224 log->Printf("Process::RunThreadPlan(): about to wait forever.");
5228 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5229 // See comment above...
5230 if (miss_first_event) {
5232 miss_first_event = false;
5236 got_event = listener_sp->GetEvent(event_sp, timeout);
5240 bool keep_going = false;
5241 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5242 const bool clear_thread_plans = false;
5243 const bool use_run_lock = false;
5244 Halt(clear_thread_plans, use_run_lock);
5245 return_value = eExpressionInterrupted;
5246 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5247 "execution halted by user interrupt.");
5249 log->Printf("Process::RunThreadPlan(): Got interrupted by "
5250 "eBroadcastBitInterrupted, exiting.");
5254 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5257 "Process::RunThreadPlan(): in while loop, got event: %s.",
5258 StateAsCString(stop_state));
5260 switch (stop_state) {
5261 case lldb::eStateStopped: {
5262 // We stopped, figure out what we are going to do now.
5263 ThreadSP thread_sp =
5264 GetThreadList().FindThreadByIndexID(thread_idx_id);
5266 // Ooh, our thread has vanished. Unlikely that this was
5267 // successful execution...
5269 log->Printf("Process::RunThreadPlan(): execution completed "
5270 "but our thread (index-id=%u) has vanished.",
5272 return_value = eExpressionInterrupted;
5273 } else if (Process::ProcessEventData::GetRestartedFromEvent(
5275 // If we were restarted, we just need to go back up to fetch
5278 log->Printf("Process::RunThreadPlan(): Got a stop and "
5279 "restart, so we'll continue waiting.");
5283 handle_running_event = true;
5285 const bool handle_interrupts = true;
5286 return_value = *HandleStoppedEvent(
5287 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5288 event_to_broadcast_sp, options, handle_interrupts);
5292 case lldb::eStateRunning:
5293 // This shouldn't really happen, but sometimes we do get two
5294 // running events without an
5295 // intervening stop, and in that case we should just go back to
5296 // waiting for the stop.
5299 handle_running_event = false;
5304 log->Printf("Process::RunThreadPlan(): execution stopped with "
5305 "unexpected state: %s.",
5306 StateAsCString(stop_state));
5308 if (stop_state == eStateExited)
5309 event_to_broadcast_sp = event_sp;
5311 diagnostic_manager.PutString(
5312 eDiagnosticSeverityError,
5313 "execution stopped with unexpected state.");
5314 return_value = eExpressionInterrupted;
5325 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5326 "the event pointer was null. How odd...");
5327 return_value = eExpressionInterrupted;
5331 // If we didn't get an event that means we've timed out...
5332 // We will interrupt the process here. Depending on what we were asked
5334 // either exit, or try with all threads running for the same timeout.
5337 if (options.GetTryAllThreads()) {
5338 if (before_first_timeout) {
5340 "Running function with one thread timeout timed out.");
5342 LLDB_LOG(log, "Restarting function with all threads enabled and "
5343 "timeout: {0} timed out, abandoning execution.",
5346 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5347 "abandoning execution.",
5351 // It is possible that between the time we issued the Halt, and we get
5352 // around to calling Halt the target
5353 // could have stopped. That's fine, Halt will figure that out and send
5354 // the appropriate Stopped event.
5355 // BUT it is also possible that we stopped & restarted (e.g. hit a
5356 // signal with "stop" set to false.) In
5357 // that case, we'll get the stopped & restarted event, and we should go
5358 // back to waiting for the Halt's
5359 // stopped event. That's what this while loop does.
5361 bool back_to_top = true;
5362 uint32_t try_halt_again = 0;
5363 bool do_halt = true;
5364 const uint32_t num_retries = 5;
5365 while (try_halt_again < num_retries) {
5369 log->Printf("Process::RunThreadPlan(): Running Halt.");
5370 const bool clear_thread_plans = false;
5371 const bool use_run_lock = false;
5372 Halt(clear_thread_plans, use_run_lock);
5374 if (halt_error.Success()) {
5376 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5379 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
5383 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5385 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5386 StateAsCString(stop_state));
5387 if (stop_state == lldb::eStateStopped &&
5388 Process::ProcessEventData::GetInterruptedFromEvent(
5390 log->PutCString(" Event was the Halt interruption event.");
5393 if (stop_state == lldb::eStateStopped) {
5394 if (Process::ProcessEventData::GetRestartedFromEvent(
5397 log->PutCString("Process::RunThreadPlan(): Went to halt "
5398 "but got a restarted event, there must be "
5399 "an un-restarted stopped event so try "
5401 "Exiting wait loop.");
5407 // Between the time we initiated the Halt and the time we
5408 // delivered it, the process could have
5409 // already finished its job. Check that here:
5410 const bool handle_interrupts = false;
5411 if (auto result = HandleStoppedEvent(
5412 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5413 event_to_broadcast_sp, options, handle_interrupts)) {
5414 return_value = *result;
5415 back_to_top = false;
5419 if (!options.GetTryAllThreads()) {
5421 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5422 "was false, we stopped so now we're "
5424 return_value = eExpressionInterrupted;
5425 back_to_top = false;
5429 if (before_first_timeout) {
5430 // Set all the other threads to run, and return to the top of
5431 // the loop, which will continue;
5432 before_first_timeout = false;
5433 thread_plan_sp->SetStopOthers(false);
5436 "Process::RunThreadPlan(): about to resume.");
5441 // Running all threads failed, so return Interrupted.
5443 log->PutCString("Process::RunThreadPlan(): running all "
5444 "threads timed out.");
5445 return_value = eExpressionInterrupted;
5446 back_to_top = false;
5452 log->PutCString("Process::RunThreadPlan(): halt said it "
5453 "succeeded, but I got no event. "
5454 "I'm getting out of here passing Interrupted.");
5455 return_value = eExpressionInterrupted;
5456 back_to_top = false;
5465 if (!back_to_top || try_halt_again > num_retries)
5472 // If we had to start up a temporary private state thread to run this thread
5473 // plan, shut it down now.
5474 if (backup_private_state_thread.IsJoinable()) {
5475 StopPrivateStateThread();
5477 m_private_state_thread = backup_private_state_thread;
5478 if (stopper_base_plan_sp) {
5479 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5481 if (old_state != eStateInvalid)
5482 m_public_state.SetValueNoLock(old_state);
5485 if (return_value != eExpressionCompleted && log) {
5486 // Print a backtrace into the log so we can figure out where we are:
5488 s.PutCString("Thread state after unsuccessful completion: \n");
5489 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
5490 log->PutString(s.GetString());
5492 // Restore the thread state if we are going to discard the plan execution.
5493 // There are three cases where this
5495 // 1) The execution successfully completed
5496 // 2) We hit a breakpoint, and ignore_breakpoints was true
5497 // 3) We got some other error, and discard_on_error was true
5498 bool should_unwind = (return_value == eExpressionInterrupted &&
5499 options.DoesUnwindOnError()) ||
5500 (return_value == eExpressionHitBreakpoint &&
5501 options.DoesIgnoreBreakpoints());
5503 if (return_value == eExpressionCompleted || should_unwind) {
5504 thread_plan_sp->RestoreThreadState();
5507 // Now do some processing on the results of the run:
5508 if (return_value == eExpressionInterrupted ||
5509 return_value == eExpressionHitBreakpoint) {
5515 log->PutCString("Process::RunThreadPlan(): Stop event that "
5516 "interrupted us is NULL.");
5521 const char *event_explanation = nullptr;
5525 event_explanation = "<no event>";
5527 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5528 event_explanation = "<user interrupt>";
5531 const Process::ProcessEventData *event_data =
5532 Process::ProcessEventData::GetEventDataFromEvent(
5536 event_explanation = "<no event data>";
5540 Process *process = event_data->GetProcessSP().get();
5543 event_explanation = "<no process>";
5547 ThreadList &thread_list = process->GetThreadList();
5549 uint32_t num_threads = thread_list.GetSize();
5550 uint32_t thread_index;
5552 ts.Printf("<%u threads> ", num_threads);
5554 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5555 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5562 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5563 RegisterContext *register_context =
5564 thread->GetRegisterContext().get();
5566 if (register_context)
5567 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5569 ts.Printf("[ip unknown] ");
5571 // Show the private stop info here, the public stop info will be
5572 // from the last natural stop.
5573 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5575 const char *stop_desc = stop_info_sp->GetDescription();
5577 ts.PutCString(stop_desc);
5582 event_explanation = ts.GetData();
5586 if (event_explanation)
5587 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5588 s.GetData(), event_explanation);
5590 log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5594 if (should_unwind) {
5596 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5597 "discarding thread plans up to %p.",
5598 static_cast<void *>(thread_plan_sp.get()));
5599 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5602 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5603 "plan: %p not discarding.",
5604 static_cast<void *>(thread_plan_sp.get()));
5606 } else if (return_value == eExpressionSetupError) {
5608 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5610 if (options.DoesUnwindOnError()) {
5611 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5614 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5616 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5617 return_value = eExpressionCompleted;
5618 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5621 "Process::RunThreadPlan(): thread plan was discarded");
5622 return_value = eExpressionDiscarded;
5626 "Process::RunThreadPlan(): thread plan stopped in mid course");
5627 if (options.DoesUnwindOnError() && thread_plan_sp) {
5629 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5630 "'cause unwind_on_error is set.");
5631 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5636 // Thread we ran the function in may have gone away because we ran the
5638 // Check that it's still there, and if it is put it back in the context.
5640 // frame in the context if it is still present.
5641 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5643 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5646 // Also restore the current process'es selected frame & thread, since this
5647 // function calling may
5648 // be done behind the user's back.
5650 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5651 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5652 selected_stack_id.IsValid()) {
5653 // We were able to restore the selected thread, now restore the frame:
5654 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5655 StackFrameSP old_frame_sp =
5656 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5659 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5660 old_frame_sp.get());
5665 // If the process exited during the run of the thread plan, notify everyone.
5667 if (event_to_broadcast_sp) {
5669 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5670 BroadcastEvent(event_to_broadcast_sp);
5673 return return_value;
5676 const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5677 const char *result_name;
5680 case eExpressionCompleted:
5681 result_name = "eExpressionCompleted";
5683 case eExpressionDiscarded:
5684 result_name = "eExpressionDiscarded";
5686 case eExpressionInterrupted:
5687 result_name = "eExpressionInterrupted";
5689 case eExpressionHitBreakpoint:
5690 result_name = "eExpressionHitBreakpoint";
5692 case eExpressionSetupError:
5693 result_name = "eExpressionSetupError";
5695 case eExpressionParseError:
5696 result_name = "eExpressionParseError";
5698 case eExpressionResultUnavailable:
5699 result_name = "eExpressionResultUnavailable";
5701 case eExpressionTimedOut:
5702 result_name = "eExpressionTimedOut";
5704 case eExpressionStoppedForDebug:
5705 result_name = "eExpressionStoppedForDebug";
5711 void Process::GetStatus(Stream &strm) {
5712 const StateType state = GetState();
5713 if (StateIsStoppedState(state, false)) {
5714 if (state == eStateExited) {
5715 int exit_status = GetExitStatus();
5716 const char *exit_description = GetExitDescription();
5717 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5718 GetID(), exit_status, exit_status,
5719 exit_description ? exit_description : "");
5721 if (state == eStateConnected)
5722 strm.Printf("Connected to remote target.\n");
5724 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5727 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5731 size_t Process::GetThreadStatus(Stream &strm,
5732 bool only_threads_with_stop_reason,
5733 uint32_t start_frame, uint32_t num_frames,
5734 uint32_t num_frames_with_source,
5736 size_t num_thread_infos_dumped = 0;
5738 // You can't hold the thread list lock while calling Thread::GetStatus. That
5739 // very well might run code (e.g. if we need it
5740 // to get return values or arguments.) For that to work the process has to be
5741 // able to acquire it. So instead copy the thread
5742 // ID's, and look them up one by one:
5744 uint32_t num_threads;
5745 std::vector<lldb::tid_t> thread_id_array;
5746 // Scope for thread list locker;
5748 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5749 ThreadList &curr_thread_list = GetThreadList();
5750 num_threads = curr_thread_list.GetSize();
5752 thread_id_array.resize(num_threads);
5753 for (idx = 0; idx < num_threads; ++idx)
5754 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5757 for (uint32_t i = 0; i < num_threads; i++) {
5758 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5760 if (only_threads_with_stop_reason) {
5761 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5762 if (!stop_info_sp || !stop_info_sp->IsValid())
5765 thread_sp->GetStatus(strm, start_frame, num_frames,
5766 num_frames_with_source,
5768 ++num_thread_infos_dumped;
5770 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5772 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5773 " vanished while running Thread::GetStatus.");
5776 return num_thread_infos_dumped;
5779 void Process::AddInvalidMemoryRegion(const LoadRange ®ion) {
5780 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5783 bool Process::RemoveInvalidMemoryRange(const LoadRange ®ion) {
5784 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5785 region.GetByteSize());
5788 void Process::AddPreResumeAction(PreResumeActionCallback callback,
5790 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5793 bool Process::RunPreResumeActions() {
5795 while (!m_pre_resume_actions.empty()) {
5796 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5797 m_pre_resume_actions.pop_back();
5798 bool this_result = action.callback(action.baton);
5800 result = this_result;
5805 void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5807 void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5809 PreResumeCallbackAndBaton element(callback, baton);
5810 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5811 if (found_iter != m_pre_resume_actions.end())
5813 m_pre_resume_actions.erase(found_iter);
5817 ProcessRunLock &Process::GetRunLock() {
5818 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5819 return m_private_run_lock;
5821 return m_public_run_lock;
5824 void Process::Flush() {
5825 m_thread_list.Flush();
5826 m_extended_thread_list.Flush();
5827 m_extended_thread_stop_id = 0;
5828 m_queue_list.Clear();
5829 m_queue_list_stop_id = 0;
5832 void Process::DidExec() {
5833 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5835 log->Printf("Process::%s()", __FUNCTION__);
5837 Target &target = GetTarget();
5838 target.CleanupProcess();
5839 target.ClearModules(false);
5840 m_dynamic_checkers_ap.reset();
5842 m_system_runtime_ap.reset();
5845 m_jit_loaders_ap.reset();
5846 m_image_tokens.clear();
5847 m_allocated_memory_cache.Clear();
5848 m_language_runtimes.clear();
5849 m_instrumentation_runtimes.clear();
5850 m_thread_list.DiscardThreadPlans();
5851 m_memory_cache.Clear(true);
5852 m_stop_info_override_callback = nullptr;
5855 // Flush the process (threads and all stack frames) after running
5857 // in case the dynamic loader loaded things in new locations.
5860 // After we figure out what was loaded/unloaded in CompleteAttach,
5861 // we need to let the target know so it can do any cleanup it needs to.
5865 addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
5866 if (address == nullptr) {
5867 error.SetErrorString("Invalid address argument");
5868 return LLDB_INVALID_ADDRESS;
5871 addr_t function_addr = LLDB_INVALID_ADDRESS;
5873 addr_t addr = address->GetLoadAddress(&GetTarget());
5874 std::map<addr_t, addr_t>::const_iterator iter =
5875 m_resolved_indirect_addresses.find(addr);
5876 if (iter != m_resolved_indirect_addresses.end()) {
5877 function_addr = (*iter).second;
5879 if (!InferiorCall(this, address, function_addr)) {
5880 Symbol *symbol = address->CalculateSymbolContextSymbol();
5881 error.SetErrorStringWithFormat(
5882 "Unable to call resolver for indirect function %s",
5883 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5884 function_addr = LLDB_INVALID_ADDRESS;
5886 m_resolved_indirect_addresses.insert(
5887 std::pair<addr_t, addr_t>(addr, function_addr));
5890 return function_addr;
5893 void Process::ModulesDidLoad(ModuleList &module_list) {
5894 SystemRuntime *sys_runtime = GetSystemRuntime();
5896 sys_runtime->ModulesDidLoad(module_list);
5899 GetJITLoaders().ModulesDidLoad(module_list);
5901 // Give runtimes a chance to be created.
5902 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5903 m_instrumentation_runtimes);
5905 // Tell runtimes about new modules.
5906 for (auto pos = m_instrumentation_runtimes.begin();
5907 pos != m_instrumentation_runtimes.end(); ++pos) {
5908 InstrumentationRuntimeSP runtime = pos->second;
5909 runtime->ModulesDidLoad(module_list);
5912 // Let any language runtimes we have already created know
5913 // about the modules that loaded.
5915 // Iterate over a copy of this language runtime list in case
5916 // the language runtime ModulesDidLoad somehow causes the language
5917 // riuntime to be unloaded.
5918 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5919 for (const auto &pair : language_runtimes) {
5920 // We must check language_runtime_sp to make sure it is not
5921 // nullptr as we might cache the fact that we didn't have a
5922 // language runtime for a language.
5923 LanguageRuntimeSP language_runtime_sp = pair.second;
5924 if (language_runtime_sp)
5925 language_runtime_sp->ModulesDidLoad(module_list);
5928 // If we don't have an operating system plug-in, try to load one since
5929 // loading shared libraries might cause a new one to try and load
5931 LoadOperatingSystemPlugin(false);
5933 // Give structured-data plugins a chance to see the modified modules.
5934 for (auto pair : m_structured_data_plugin_map) {
5936 pair.second->ModulesDidLoad(*this, module_list);
5940 void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5941 const char *fmt, ...) {
5942 bool print_warning = true;
5944 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5947 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5951 if (repeat_key != nullptr) {
5952 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5953 if (it == m_warnings_issued.end()) {
5954 m_warnings_issued[warning_type] = WarningsPointerSet();
5955 m_warnings_issued[warning_type].insert(repeat_key);
5957 if (it->second.find(repeat_key) != it->second.end()) {
5958 print_warning = false;
5960 it->second.insert(repeat_key);
5965 if (print_warning) {
5967 va_start(args, fmt);
5968 stream_sp->PrintfVarArg(fmt, args);
5973 void Process::PrintWarningOptimization(const SymbolContext &sc) {
5974 if (GetWarningsOptimization() && sc.module_sp &&
5975 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5976 sc.function->GetIsOptimized()) {
5977 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5978 "%s was compiled with optimization - stepping may behave "
5979 "oddly; variables may not be available.\n",
5980 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5984 bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5987 PlatformSP platform_sp = GetTarget().GetPlatform();
5991 return platform_sp->GetProcessInfo(GetID(), info);
5994 ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5995 ThreadCollectionSP threads;
5997 const MemoryHistorySP &memory_history =
5998 MemoryHistory::FindPlugin(shared_from_this());
6000 if (!memory_history) {
6004 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6009 InstrumentationRuntimeSP
6010 Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
6011 InstrumentationRuntimeCollection::iterator pos;
6012 pos = m_instrumentation_runtimes.find(type);
6013 if (pos == m_instrumentation_runtimes.end()) {
6014 return InstrumentationRuntimeSP();
6016 return (*pos).second;
6019 bool Process::GetModuleSpec(const FileSpec &module_file_spec,
6020 const ArchSpec &arch, ModuleSpec &module_spec) {
6021 module_spec.Clear();
6025 size_t Process::AddImageToken(lldb::addr_t image_ptr) {
6026 m_image_tokens.push_back(image_ptr);
6027 return m_image_tokens.size() - 1;
6030 lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
6031 if (token < m_image_tokens.size())
6032 return m_image_tokens[token];
6033 return LLDB_INVALID_IMAGE_TOKEN;
6036 void Process::ResetImageToken(size_t token) {
6037 if (token < m_image_tokens.size())
6038 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
6042 Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
6043 AddressRange range_bounds) {
6044 Target &target = GetTarget();
6045 DisassemblerSP disassembler_sp;
6046 InstructionList *insn_list = nullptr;
6048 Address retval = default_stop_addr;
6050 if (!target.GetUseFastStepping())
6052 if (!default_stop_addr.IsValid())
6055 ExecutionContext exe_ctx(this);
6056 const char *plugin_name = nullptr;
6057 const char *flavor = nullptr;
6058 const bool prefer_file_cache = true;
6059 disassembler_sp = Disassembler::DisassembleRange(
6060 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
6062 if (disassembler_sp)
6063 insn_list = &disassembler_sp->GetInstructionList();
6065 if (insn_list == nullptr) {
6069 size_t insn_offset =
6070 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
6071 if (insn_offset == UINT32_MAX) {
6075 uint32_t branch_index =
6076 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target);
6077 if (branch_index == UINT32_MAX) {
6081 if (branch_index > insn_offset) {
6082 Address next_branch_insn_address =
6083 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
6084 if (next_branch_insn_address.IsValid() &&
6085 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
6086 retval = next_branch_insn_address;
6094 Process::GetMemoryRegions(std::vector<lldb::MemoryRegionInfoSP> ®ion_list) {
6098 lldb::addr_t range_end = 0;
6100 region_list.clear();
6102 lldb::MemoryRegionInfoSP region_info(new lldb_private::MemoryRegionInfo());
6103 error = GetMemoryRegionInfo(range_end, *region_info);
6104 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6106 region_list.clear();
6110 range_end = region_info->GetRange().GetRangeEnd();
6111 if (region_info->GetMapped() == MemoryRegionInfo::eYes) {
6112 region_list.push_back(region_info);
6114 } while (range_end != LLDB_INVALID_ADDRESS);
6120 Process::ConfigureStructuredData(const ConstString &type_name,
6121 const StructuredData::ObjectSP &config_sp) {
6122 // If you get this, the Process-derived class needs to implement a method
6123 // to enable an already-reported asynchronous structured data feature.
6124 // See ProcessGDBRemote for an example implementation over gdb-remote.
6125 return Status("unimplemented");
6128 void Process::MapSupportedStructuredDataPlugins(
6129 const StructuredData::Array &supported_type_names) {
6130 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
6132 // Bail out early if there are no type names to map.
6133 if (supported_type_names.GetSize() == 0) {
6135 log->Printf("Process::%s(): no structured data types supported",
6140 // Convert StructuredData type names to ConstString instances.
6141 std::set<ConstString> const_type_names;
6144 log->Printf("Process::%s(): the process supports the following async "
6145 "structured data types:",
6148 supported_type_names.ForEach(
6149 [&const_type_names, &log](StructuredData::Object *object) {
6151 // Invalid - shouldn't be null objects in the array.
6155 auto type_name = object->GetAsString();
6157 // Invalid format - all type names should be strings.
6161 const_type_names.insert(ConstString(type_name->GetValue()));
6162 LLDB_LOG(log, "- {0}", type_name->GetValue());
6166 // For each StructuredDataPlugin, if the plugin handles any of the
6167 // types in the supported_type_names, map that type name to that plugin.
6168 uint32_t plugin_index = 0;
6169 for (auto create_instance =
6170 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
6172 create_instance && !const_type_names.empty(); ++plugin_index) {
6173 // Create the plugin.
6174 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
6176 // This plugin doesn't think it can work with the process.
6177 // Move on to the next.
6181 // For any of the remaining type names, map any that this plugin
6183 std::vector<ConstString> names_to_remove;
6184 for (auto &type_name : const_type_names) {
6185 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6186 m_structured_data_plugin_map.insert(
6187 std::make_pair(type_name, plugin_sp));
6188 names_to_remove.push_back(type_name);
6190 log->Printf("Process::%s(): using plugin %s for type name "
6192 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
6193 type_name.GetCString());
6197 // Remove the type names that were consumed by this plugin.
6198 for (auto &type_name : names_to_remove)
6199 const_type_names.erase(type_name);
6203 bool Process::RouteAsyncStructuredData(
6204 const StructuredData::ObjectSP object_sp) {
6205 // Nothing to do if there's no data.
6209 // The contract is this must be a dictionary, so we can look up the
6210 // routing key via the top-level 'type' string value within the dictionary.
6211 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6215 // Grab the async structured type name (i.e. the feature/plugin name).
6216 ConstString type_name;
6217 if (!dictionary->GetValueForKeyAsString("type", type_name))
6220 // Check if there's a plugin registered for this type name.
6221 auto find_it = m_structured_data_plugin_map.find(type_name);
6222 if (find_it == m_structured_data_plugin_map.end()) {
6223 // We don't have a mapping for this structured data type.
6227 // Route the structured data to the plugin.
6228 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6232 Status Process::UpdateAutomaticSignalFiltering() {
6233 // Default implementation does nothign.
6234 // No automatic signal filtering to speak of.