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 {"stop-on-exec", OptionValue::eTypeBoolean, true, true,
149 "If true, stop when a shared library is loaded or unloaded."},
150 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
153 ePropertyDisableMemCache,
154 ePropertyExtraStartCommand,
155 ePropertyIgnoreBreakpointsInExpressions,
156 ePropertyUnwindOnErrorInExpressions,
157 ePropertyPythonOSPluginPath,
158 ePropertyStopOnSharedLibraryEvents,
159 ePropertyDetachKeepsStopped,
160 ePropertyMemCacheLineSize,
161 ePropertyWarningOptimization,
165 ProcessProperties::ProcessProperties(lldb_private::Process *process)
167 m_process(process) // Can be nullptr for global ProcessProperties
169 if (process == nullptr) {
170 // Global process properties, set them up one time
171 m_collection_sp.reset(
172 new ProcessOptionValueProperties(ConstString("process")));
173 m_collection_sp->Initialize(g_properties);
174 m_collection_sp->AppendProperty(
175 ConstString("thread"), ConstString("Settings specific to threads."),
176 true, Thread::GetGlobalProperties()->GetValueProperties());
178 m_collection_sp.reset(
179 new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
180 m_collection_sp->SetValueChangedCallback(
181 ePropertyPythonOSPluginPath,
182 ProcessProperties::OptionValueChangedCallback, this);
186 ProcessProperties::~ProcessProperties() = default;
188 void ProcessProperties::OptionValueChangedCallback(void *baton,
189 OptionValue *option_value) {
190 ProcessProperties *properties = (ProcessProperties *)baton;
191 if (properties->m_process)
192 properties->m_process->LoadOperatingSystemPlugin(true);
195 bool ProcessProperties::GetDisableMemoryCache() const {
196 const uint32_t idx = ePropertyDisableMemCache;
197 return m_collection_sp->GetPropertyAtIndexAsBoolean(
198 nullptr, idx, g_properties[idx].default_uint_value != 0);
201 uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
202 const uint32_t idx = ePropertyMemCacheLineSize;
203 return m_collection_sp->GetPropertyAtIndexAsUInt64(
204 nullptr, idx, g_properties[idx].default_uint_value);
207 Args ProcessProperties::GetExtraStartupCommands() const {
209 const uint32_t idx = ePropertyExtraStartCommand;
210 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
214 void ProcessProperties::SetExtraStartupCommands(const Args &args) {
215 const uint32_t idx = ePropertyExtraStartCommand;
216 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
219 FileSpec ProcessProperties::GetPythonOSPluginPath() const {
220 const uint32_t idx = ePropertyPythonOSPluginPath;
221 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
224 void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
225 const uint32_t idx = ePropertyPythonOSPluginPath;
226 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
229 bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
230 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
231 return m_collection_sp->GetPropertyAtIndexAsBoolean(
232 nullptr, idx, g_properties[idx].default_uint_value != 0);
235 void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
236 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
237 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
240 bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
241 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
242 return m_collection_sp->GetPropertyAtIndexAsBoolean(
243 nullptr, idx, g_properties[idx].default_uint_value != 0);
246 void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
247 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
248 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
251 bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
252 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
253 return m_collection_sp->GetPropertyAtIndexAsBoolean(
254 nullptr, idx, g_properties[idx].default_uint_value != 0);
257 void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
258 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
259 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
262 bool ProcessProperties::GetDetachKeepsStopped() const {
263 const uint32_t idx = ePropertyDetachKeepsStopped;
264 return m_collection_sp->GetPropertyAtIndexAsBoolean(
265 nullptr, idx, g_properties[idx].default_uint_value != 0);
268 void ProcessProperties::SetDetachKeepsStopped(bool stop) {
269 const uint32_t idx = ePropertyDetachKeepsStopped;
270 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
273 bool ProcessProperties::GetWarningsOptimization() const {
274 const uint32_t idx = ePropertyWarningOptimization;
275 return m_collection_sp->GetPropertyAtIndexAsBoolean(
276 nullptr, idx, g_properties[idx].default_uint_value != 0);
279 bool ProcessProperties::GetStopOnExec() const {
280 const uint32_t idx = ePropertyStopOnExec;
281 return m_collection_sp->GetPropertyAtIndexAsBoolean(
282 nullptr, idx, g_properties[idx].default_uint_value != 0);
285 void ProcessInstanceInfo::Dump(Stream &s, Platform *platform) const {
287 if (m_pid != LLDB_INVALID_PROCESS_ID)
288 s.Printf(" pid = %" PRIu64 "\n", m_pid);
290 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
291 s.Printf(" parent = %" PRIu64 "\n", m_parent_pid);
294 s.Printf(" name = %s\n", m_executable.GetFilename().GetCString());
295 s.PutCString(" file = ");
296 m_executable.Dump(&s);
299 const uint32_t argc = m_arguments.GetArgumentCount();
301 for (uint32_t i = 0; i < argc; i++) {
302 const char *arg = m_arguments.GetArgumentAtIndex(i);
304 s.Printf(" arg[%u] = %s\n", i, arg);
306 s.Printf("arg[%u] = %s\n", i, arg);
310 const uint32_t envc = m_environment.GetArgumentCount();
312 for (uint32_t i = 0; i < envc; i++) {
313 const char *env = m_environment.GetArgumentAtIndex(i);
315 s.Printf(" env[%u] = %s\n", i, env);
317 s.Printf("env[%u] = %s\n", i, env);
321 if (m_arch.IsValid()) {
322 s.Printf(" arch = ");
323 m_arch.DumpTriple(s);
327 if (m_uid != UINT32_MAX) {
328 cstr = platform->GetUserName(m_uid);
329 s.Printf(" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
331 if (m_gid != UINT32_MAX) {
332 cstr = platform->GetGroupName(m_gid);
333 s.Printf(" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
335 if (m_euid != UINT32_MAX) {
336 cstr = platform->GetUserName(m_euid);
337 s.Printf(" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
339 if (m_egid != UINT32_MAX) {
340 cstr = platform->GetGroupName(m_egid);
341 s.Printf(" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
345 void ProcessInstanceInfo::DumpTableHeader(Stream &s, Platform *platform,
346 bool show_args, bool verbose) {
348 if (show_args || verbose)
354 s.Printf("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE "
357 s.PutCString("====== ====== ========== ========== ========== ========== "
358 "======================== ============================\n");
360 s.Printf("PID PARENT USER TRIPLE %s\n", label);
361 s.PutCString("====== ====== ========== ======================== "
362 "============================\n");
366 void ProcessInstanceInfo::DumpAsTableRow(Stream &s, Platform *platform,
367 bool show_args, bool verbose) const {
368 if (m_pid != LLDB_INVALID_PROCESS_ID) {
370 s.Printf("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
372 StreamString arch_strm;
373 if (m_arch.IsValid())
374 m_arch.DumpTriple(arch_strm);
377 cstr = platform->GetUserName(m_uid);
379 cstr[0]) // Watch for empty string that indicates lookup failed
380 s.Printf("%-10s ", cstr);
382 s.Printf("%-10u ", m_uid);
384 cstr = platform->GetGroupName(m_gid);
386 cstr[0]) // Watch for empty string that indicates lookup failed
387 s.Printf("%-10s ", cstr);
389 s.Printf("%-10u ", m_gid);
391 cstr = platform->GetUserName(m_euid);
393 cstr[0]) // Watch for empty string that indicates lookup failed
394 s.Printf("%-10s ", cstr);
396 s.Printf("%-10u ", m_euid);
398 cstr = platform->GetGroupName(m_egid);
400 cstr[0]) // Watch for empty string that indicates lookup failed
401 s.Printf("%-10s ", cstr);
403 s.Printf("%-10u ", m_egid);
405 s.Printf("%-24s ", arch_strm.GetData());
407 s.Printf("%-10s %-24s ", platform->GetUserName(m_euid),
408 arch_strm.GetData());
411 if (verbose || show_args) {
412 const uint32_t argc = m_arguments.GetArgumentCount();
414 for (uint32_t i = 0; i < argc; i++) {
417 s.PutCString(m_arguments.GetArgumentAtIndex(i));
421 s.PutCString(GetName());
428 Status ProcessLaunchCommandOptions::SetOptionValue(
429 uint32_t option_idx, llvm::StringRef option_arg,
430 ExecutionContext *execution_context) {
432 const int short_option = m_getopt_table[option_idx].val;
434 switch (short_option) {
435 case 's': // Stop at program entry point
436 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
439 case 'i': // STDIN for read only
442 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
443 launch_info.AppendFileAction(action);
447 case 'o': // Open STDOUT for write only
450 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
451 launch_info.AppendFileAction(action);
455 case 'e': // STDERR for write only
458 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
459 launch_info.AppendFileAction(action);
463 case 'p': // Process plug-in name
464 launch_info.SetProcessPluginName(option_arg);
467 case 'n': // Disable STDIO
470 const FileSpec dev_null{FileSystem::DEV_NULL, false};
471 if (action.Open(STDIN_FILENO, dev_null, true, false))
472 launch_info.AppendFileAction(action);
473 if (action.Open(STDOUT_FILENO, dev_null, false, true))
474 launch_info.AppendFileAction(action);
475 if (action.Open(STDERR_FILENO, dev_null, false, true))
476 launch_info.AppendFileAction(action);
481 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
484 case 't': // Open process in new terminal window
485 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
490 execution_context ? execution_context->GetTargetSP() : TargetSP();
491 PlatformSP platform_sp =
492 target_sp ? target_sp->GetPlatform() : PlatformSP();
493 launch_info.GetArchitecture() =
494 Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
497 case 'A': // Disable ASLR.
500 const bool disable_aslr_arg =
501 Args::StringToBoolean(option_arg, true, &success);
503 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
505 error.SetErrorStringWithFormat(
506 "Invalid boolean value for disable-aslr option: '%s'",
507 option_arg.empty() ? "<null>" : option_arg.str().c_str());
511 case 'X': // shell expand args.
514 const bool expand_args = Args::StringToBoolean(option_arg, true, &success);
516 launch_info.SetShellExpandArguments(expand_args);
518 error.SetErrorStringWithFormat(
519 "Invalid boolean value for shell-expand-args option: '%s'",
520 option_arg.empty() ? "<null>" : option_arg.str().c_str());
525 if (!option_arg.empty())
526 launch_info.SetShell(FileSpec(option_arg, false));
528 launch_info.SetShell(HostInfo::GetDefaultShell());
532 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
536 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
543 static OptionDefinition g_process_launch_options[] = {
544 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
545 nullptr, nullptr, 0, eArgTypeNone,
546 "Stop at the entry point of the program when launching a process."},
547 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
548 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
549 "Set whether to disable address space layout randomization when launching "
551 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
552 nullptr, nullptr, 0, eArgTypePlugin,
553 "Name of the process plugin you want to use."},
554 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
555 OptionParser::eRequiredArgument, nullptr, nullptr, 0,
556 eArgTypeDirectoryName,
557 "Set the current working directory to <path> when running the inferior."},
558 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
559 nullptr, nullptr, 0, eArgTypeArchitecture,
560 "Set the architecture for the process to launch when ambiguous."},
561 {LLDB_OPT_SET_ALL, false, "environment", 'v',
562 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone,
563 "Specify an environment variable name/value string (--environment "
564 "NAME=VALUE). Can be specified multiple times for subsequent environment "
566 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
567 OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeFilename,
568 "Run the process in a shell (not supported on all platforms)."},
570 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
571 nullptr, nullptr, 0, eArgTypeFilename,
572 "Redirect stdin for the process to <filename>."},
573 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
574 nullptr, nullptr, 0, eArgTypeFilename,
575 "Redirect stdout for the process to <filename>."},
576 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
577 nullptr, nullptr, 0, eArgTypeFilename,
578 "Redirect stderr for the process to <filename>."},
580 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
581 nullptr, 0, eArgTypeNone,
582 "Start the process in a terminal (not supported on all platforms)."},
584 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
585 nullptr, 0, eArgTypeNone,
586 "Do not set up for terminal I/O to go to running process."},
587 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
588 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
589 "Set whether to shell expand arguments to the process when launching."},
592 llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
593 return llvm::makeArrayRef(g_process_launch_options);
596 bool ProcessInstanceInfoMatch::NameMatches(const char *process_name) const {
597 if (m_name_match_type == NameMatch::Ignore || process_name == nullptr)
599 const char *match_name = m_match_info.GetName();
603 return lldb_private::NameMatches(process_name, m_name_match_type, match_name);
606 bool ProcessInstanceInfoMatch::Matches(
607 const ProcessInstanceInfo &proc_info) const {
608 if (!NameMatches(proc_info.GetName()))
611 if (m_match_info.ProcessIDIsValid() &&
612 m_match_info.GetProcessID() != proc_info.GetProcessID())
615 if (m_match_info.ParentProcessIDIsValid() &&
616 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
619 if (m_match_info.UserIDIsValid() &&
620 m_match_info.GetUserID() != proc_info.GetUserID())
623 if (m_match_info.GroupIDIsValid() &&
624 m_match_info.GetGroupID() != proc_info.GetGroupID())
627 if (m_match_info.EffectiveUserIDIsValid() &&
628 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
631 if (m_match_info.EffectiveGroupIDIsValid() &&
632 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
635 if (m_match_info.GetArchitecture().IsValid() &&
636 !m_match_info.GetArchitecture().IsCompatibleMatch(
637 proc_info.GetArchitecture()))
642 bool ProcessInstanceInfoMatch::MatchAllProcesses() const {
643 if (m_name_match_type != NameMatch::Ignore)
646 if (m_match_info.ProcessIDIsValid())
649 if (m_match_info.ParentProcessIDIsValid())
652 if (m_match_info.UserIDIsValid())
655 if (m_match_info.GroupIDIsValid())
658 if (m_match_info.EffectiveUserIDIsValid())
661 if (m_match_info.EffectiveGroupIDIsValid())
664 if (m_match_info.GetArchitecture().IsValid())
667 if (m_match_all_users)
673 void ProcessInstanceInfoMatch::Clear() {
674 m_match_info.Clear();
675 m_name_match_type = NameMatch::Ignore;
676 m_match_all_users = false;
679 ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
680 llvm::StringRef plugin_name,
681 ListenerSP listener_sp,
682 const FileSpec *crash_file_path) {
683 static uint32_t g_process_unique_id = 0;
685 ProcessSP process_sp;
686 ProcessCreateInstance create_callback = nullptr;
687 if (!plugin_name.empty()) {
688 ConstString const_plugin_name(plugin_name);
690 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
691 if (create_callback) {
692 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
694 if (process_sp->CanDebug(target_sp, true)) {
695 process_sp->m_process_unique_id = ++g_process_unique_id;
701 for (uint32_t idx = 0;
703 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
705 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
707 if (process_sp->CanDebug(target_sp, false)) {
708 process_sp->m_process_unique_id = ++g_process_unique_id;
718 ConstString &Process::GetStaticBroadcasterClass() {
719 static ConstString class_name("lldb.process");
723 Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
724 : Process(target_sp, listener_sp,
725 UnixSignals::Create(HostInfo::GetArchitecture())) {
726 // This constructor just delegates to the full Process constructor,
727 // defaulting to using the Host's UnixSignals.
730 Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
731 const UnixSignalsSP &unix_signals_sp)
732 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
733 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
734 Process::GetStaticBroadcasterClass().AsCString()),
735 m_target_sp(target_sp), m_public_state(eStateUnloaded),
736 m_private_state(eStateUnloaded),
737 m_private_state_broadcaster(nullptr,
738 "lldb.process.internal_state_broadcaster"),
739 m_private_state_control_broadcaster(
740 nullptr, "lldb.process.internal_state_control_broadcaster"),
741 m_private_state_listener_sp(
742 Listener::MakeListener("lldb.process.internal_state_listener")),
743 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
744 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
745 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
746 m_thread_list(this), m_extended_thread_list(this),
747 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
748 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
749 m_breakpoint_site_list(), m_dynamic_checkers_ap(),
750 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
751 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
752 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
753 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
754 m_memory_cache(*this), m_allocated_memory_cache(*this),
755 m_should_detach(false), m_next_event_action_ap(), m_public_run_lock(),
756 m_private_run_lock(), m_finalizing(false), m_finalize_called(false),
757 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
758 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
759 m_can_interpret_function_calls(false), m_warnings_issued(),
760 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
761 CheckInWithManager();
763 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
765 log->Printf("%p Process::Process()", static_cast<void *>(this));
767 if (!m_unix_signals_sp)
768 m_unix_signals_sp = std::make_shared<UnixSignals>();
770 SetEventName(eBroadcastBitStateChanged, "state-changed");
771 SetEventName(eBroadcastBitInterrupt, "interrupt");
772 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
773 SetEventName(eBroadcastBitSTDERR, "stderr-available");
774 SetEventName(eBroadcastBitProfileData, "profile-data-available");
775 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
777 m_private_state_control_broadcaster.SetEventName(
778 eBroadcastInternalStateControlStop, "control-stop");
779 m_private_state_control_broadcaster.SetEventName(
780 eBroadcastInternalStateControlPause, "control-pause");
781 m_private_state_control_broadcaster.SetEventName(
782 eBroadcastInternalStateControlResume, "control-resume");
784 m_listener_sp->StartListeningForEvents(
785 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
786 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
787 eBroadcastBitProfileData | eBroadcastBitStructuredData);
789 m_private_state_listener_sp->StartListeningForEvents(
790 &m_private_state_broadcaster,
791 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
793 m_private_state_listener_sp->StartListeningForEvents(
794 &m_private_state_control_broadcaster,
795 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
796 eBroadcastInternalStateControlResume);
797 // We need something valid here, even if just the default UnixSignalsSP.
798 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
800 // Allow the platform to override the default cache line size
801 OptionValueSP value_sp =
803 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
805 uint32_t platform_cache_line_size =
806 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
807 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
808 value_sp->SetUInt64Value(platform_cache_line_size);
811 Process::~Process() {
812 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
814 log->Printf("%p Process::~Process()", static_cast<void *>(this));
815 StopPrivateStateThread();
817 // ThreadList::Clear() will try to acquire this process's mutex, so
818 // explicitly clear the thread list here to ensure that the mutex
819 // is not destroyed before the thread list.
820 m_thread_list.Clear();
823 const ProcessPropertiesSP &Process::GetGlobalProperties() {
824 // NOTE: intentional leak so we don't crash if global destructor chain gets
825 // called as other threads still use the result of this function
826 static ProcessPropertiesSP *g_settings_sp_ptr =
827 new ProcessPropertiesSP(new ProcessProperties(nullptr));
828 return *g_settings_sp_ptr;
831 void Process::Finalize() {
834 // Destroy this process if needed
835 switch (GetPrivateState()) {
836 case eStateConnected:
837 case eStateAttaching:
838 case eStateLaunching:
843 case eStateSuspended:
854 // Clear our broadcaster before we proceed with destroying
855 Broadcaster::Clear();
857 // Do any cleanup needed prior to being destructed... Subclasses
858 // that override this method should call this superclass method as well.
860 // We need to destroy the loader before the derived Process class gets
862 // since it is very likely that undoing the loader will require access to the
864 m_dynamic_checkers_ap.reset();
867 m_system_runtime_ap.reset();
869 m_jit_loaders_ap.reset();
870 m_thread_list_real.Destroy();
871 m_thread_list.Destroy();
872 m_extended_thread_list.Destroy();
873 m_queue_list.Clear();
874 m_queue_list_stop_id = 0;
875 std::vector<Notifications> empty_notifications;
876 m_notifications.swap(empty_notifications);
877 m_image_tokens.clear();
878 m_memory_cache.Clear();
879 m_allocated_memory_cache.Clear();
880 m_language_runtimes.clear();
881 m_instrumentation_runtimes.clear();
882 m_next_event_action_ap.reset();
883 // Clear the last natural stop ID since it has a strong
884 // reference to this process
885 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
886 //#ifdef LLDB_CONFIGURATION_DEBUG
887 // StreamFile s(stdout, false);
889 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
891 // event_sp->Dump (&s);
895 // We have to be very careful here as the m_private_state_listener might
896 // contain events that have ProcessSP values in them which can keep this
897 // process around forever. These events need to be cleared out.
898 m_private_state_listener_sp->Clear();
899 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
900 m_public_run_lock.SetStopped();
901 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
902 m_private_run_lock.SetStopped();
903 m_structured_data_plugin_map.clear();
904 m_finalize_called = true;
907 void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
908 m_notifications.push_back(callbacks);
909 if (callbacks.initialize != nullptr)
910 callbacks.initialize(callbacks.baton, this);
913 bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
914 std::vector<Notifications>::iterator pos, end = m_notifications.end();
915 for (pos = m_notifications.begin(); pos != end; ++pos) {
916 if (pos->baton == callbacks.baton &&
917 pos->initialize == callbacks.initialize &&
918 pos->process_state_changed == callbacks.process_state_changed) {
919 m_notifications.erase(pos);
926 void Process::SynchronouslyNotifyStateChanged(StateType state) {
927 std::vector<Notifications>::iterator notification_pos,
928 notification_end = m_notifications.end();
929 for (notification_pos = m_notifications.begin();
930 notification_pos != notification_end; ++notification_pos) {
931 if (notification_pos->process_state_changed)
932 notification_pos->process_state_changed(notification_pos->baton, this,
937 // FIXME: We need to do some work on events before the general Listener sees
939 // For instance if we are continuing from a breakpoint, we need to ensure that
941 // the little "insert real insn, step & stop" trick. But we can't do that when
943 // event is delivered by the broadcaster - since that is done on the thread that
945 // waiting for new events, so if we needed more than one event for our handling,
947 // stall. So instead we do it when we fetch the event off of the queue.
950 StateType Process::GetNextEvent(EventSP &event_sp) {
951 StateType state = eStateInvalid;
953 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
954 std::chrono::seconds(0)) &&
956 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
961 void Process::SyncIOHandler(uint32_t iohandler_id, uint64_t timeout_msec) {
962 // don't sync (potentially context switch) in case where there is no process
964 if (!m_process_input_reader)
967 uint32_t new_iohandler_id = 0;
968 m_iohandler_sync.WaitForValueNotEqualTo(
969 iohandler_id, new_iohandler_id, std::chrono::milliseconds(timeout_msec));
971 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
973 log->Printf("Process::%s waited for m_iohandler_sync to change from %u, "
975 __FUNCTION__, iohandler_id, new_iohandler_id);
978 StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
979 EventSP *event_sp_ptr, bool wait_always,
980 ListenerSP hijack_listener_sp,
981 Stream *stream, bool use_run_lock) {
982 // We can't just wait for a "stopped" event, because the stopped event may
983 // have restarted the target.
984 // We have to actually check each event, and in the case of a stopped event
985 // check the restarted flag
988 event_sp_ptr->reset();
989 StateType state = GetState();
990 // If we are exited or detached, we won't ever get back to any
991 // other valid state...
992 if (state == eStateDetached || state == eStateExited)
995 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
996 LLDB_LOG(log, "timeout = {0}", timeout);
998 if (!wait_always && StateIsStoppedState(state, true) &&
999 StateIsStoppedState(GetPrivateState(), true)) {
1001 log->Printf("Process::%s returning without waiting for events; process "
1002 "private and public states are already 'stopped'.",
1004 // We need to toggle the run lock as this won't get done in
1005 // SetPublicState() if the process is hijacked.
1006 if (hijack_listener_sp && use_run_lock)
1007 m_public_run_lock.SetStopped();
1011 while (state != eStateInvalid) {
1013 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
1014 if (event_sp_ptr && event_sp)
1015 *event_sp_ptr = event_sp;
1017 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
1018 Process::HandleProcessStateChangedEvent(event_sp, stream,
1019 pop_process_io_handler);
1023 case eStateDetached:
1025 case eStateUnloaded:
1026 // We need to toggle the run lock as this won't get done in
1027 // SetPublicState() if the process is hijacked.
1028 if (hijack_listener_sp && use_run_lock)
1029 m_public_run_lock.SetStopped();
1032 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1035 // We need to toggle the run lock as this won't get done in
1036 // SetPublicState() if the process is hijacked.
1037 if (hijack_listener_sp && use_run_lock)
1038 m_public_run_lock.SetStopped();
1048 bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
1050 bool &pop_process_io_handler) {
1051 const bool handle_pop = pop_process_io_handler;
1053 pop_process_io_handler = false;
1054 ProcessSP process_sp =
1055 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1060 StateType event_state =
1061 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1062 if (event_state == eStateInvalid)
1065 switch (event_state) {
1067 case eStateUnloaded:
1068 case eStateAttaching:
1069 case eStateLaunching:
1070 case eStateStepping:
1071 case eStateDetached:
1073 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
1074 StateAsCString(event_state));
1075 if (event_state == eStateDetached)
1076 pop_process_io_handler = true;
1079 case eStateConnected:
1081 // Don't be chatty when we run...
1086 process_sp->GetStatus(*stream);
1087 pop_process_io_handler = true;
1092 case eStateSuspended:
1093 // Make sure the program hasn't been auto-restarted:
1094 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
1096 size_t num_reasons =
1097 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1098 if (num_reasons > 0) {
1099 // FIXME: Do we want to report this, or would that just be annoyingly
1101 if (num_reasons == 1) {
1102 const char *reason =
1103 Process::ProcessEventData::GetRestartedReasonAtIndex(
1105 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
1106 process_sp->GetID(),
1107 reason ? reason : "<UNKNOWN REASON>");
1109 stream->Printf("Process %" PRIu64
1110 " stopped and restarted, reasons:\n",
1111 process_sp->GetID());
1113 for (size_t i = 0; i < num_reasons; i++) {
1114 const char *reason =
1115 Process::ProcessEventData::GetRestartedReasonAtIndex(
1117 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1123 StopInfoSP curr_thread_stop_info_sp;
1124 // Lock the thread list so it doesn't change on us, this is the scope for
1127 ThreadList &thread_list = process_sp->GetThreadList();
1128 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
1130 ThreadSP curr_thread(thread_list.GetSelectedThread());
1132 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1134 curr_thread_stop_reason = curr_thread->GetStopReason();
1135 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
1137 if (!curr_thread || !curr_thread->IsValid() ||
1138 curr_thread_stop_reason == eStopReasonInvalid ||
1139 curr_thread_stop_reason == eStopReasonNone) {
1140 // Prefer a thread that has just completed its plan over another
1141 // thread as current thread.
1142 ThreadSP plan_thread;
1143 ThreadSP other_thread;
1145 const size_t num_threads = thread_list.GetSize();
1147 for (i = 0; i < num_threads; ++i) {
1148 thread = thread_list.GetThreadAtIndex(i);
1149 StopReason thread_stop_reason = thread->GetStopReason();
1150 switch (thread_stop_reason) {
1151 case eStopReasonInvalid:
1152 case eStopReasonNone:
1155 case eStopReasonSignal: {
1156 // Don't select a signal thread if we weren't going to stop at
1158 // signal. We have to have had another reason for stopping here,
1160 // the user doesn't want to see this thread.
1161 uint64_t signo = thread->GetStopInfo()->GetValue();
1162 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
1164 other_thread = thread;
1168 case eStopReasonTrace:
1169 case eStopReasonBreakpoint:
1170 case eStopReasonWatchpoint:
1171 case eStopReasonException:
1172 case eStopReasonExec:
1173 case eStopReasonThreadExiting:
1174 case eStopReasonInstrumentation:
1176 other_thread = thread;
1178 case eStopReasonPlanComplete:
1180 plan_thread = thread;
1185 thread_list.SetSelectedThreadByID(plan_thread->GetID());
1186 else if (other_thread)
1187 thread_list.SetSelectedThreadByID(other_thread->GetID());
1189 if (curr_thread && curr_thread->IsValid())
1190 thread = curr_thread;
1192 thread = thread_list.GetThreadAtIndex(0);
1195 thread_list.SetSelectedThreadByID(thread->GetID());
1199 // Drop the ThreadList mutex by here, since GetThreadStatus below might
1200 // have to run code,
1201 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the
1202 // process is going to
1203 // have a hard time restarting the process.
1205 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1206 if (debugger.GetTargetList().GetSelectedTarget().get() ==
1207 &process_sp->GetTarget()) {
1208 const bool only_threads_with_stop_reason = true;
1209 const uint32_t start_frame = 0;
1210 const uint32_t num_frames = 1;
1211 const uint32_t num_frames_with_source = 1;
1212 const bool stop_format = true;
1213 process_sp->GetStatus(*stream);
1214 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
1215 start_frame, num_frames,
1216 num_frames_with_source,
1218 if (curr_thread_stop_info_sp) {
1219 lldb::addr_t crashing_address;
1220 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1221 curr_thread_stop_info_sp, &crashing_address);
1223 const bool qualify_cxx_base_classes = false;
1225 const ValueObject::GetExpressionPathFormat format =
1226 ValueObject::GetExpressionPathFormat::
1227 eGetExpressionPathFormatHonorPointers;
1228 stream->PutCString("Likely cause: ");
1229 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
1231 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1235 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1236 process_sp->GetTarget().shared_from_this());
1237 if (target_idx != UINT32_MAX)
1238 stream->Printf("Target %d: (", target_idx);
1240 stream->Printf("Target <unknown index>: (");
1241 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1242 stream->Printf(") stopped.\n");
1246 // Pop the process IO handler
1247 pop_process_io_handler = true;
1252 if (handle_pop && pop_process_io_handler)
1253 process_sp->PopProcessIOHandler();
1258 bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1260 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1261 eBroadcastBitInterrupt);
1266 void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
1268 StateType Process::GetStateChangedEvents(EventSP &event_sp,
1269 const Timeout<std::micro> &timeout,
1270 ListenerSP hijack_listener_sp) {
1271 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1272 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1274 ListenerSP listener_sp = hijack_listener_sp;
1276 listener_sp = m_listener_sp;
1278 StateType state = eStateInvalid;
1279 if (listener_sp->GetEventForBroadcasterWithType(
1280 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
1282 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1283 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1285 LLDB_LOG(log, "got no event or was interrupted.");
1288 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
1292 Event *Process::PeekAtStateChangedEvents() {
1293 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1296 log->Printf("Process::%s...", __FUNCTION__);
1299 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1300 this, eBroadcastBitStateChanged);
1304 "Process::%s (event_ptr) => %s", __FUNCTION__,
1305 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
1307 log->Printf("Process::%s no events found", __FUNCTION__);
1314 Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1315 const Timeout<std::micro> &timeout) {
1316 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1317 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1319 StateType state = eStateInvalid;
1320 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1321 &m_private_state_broadcaster,
1322 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
1324 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1325 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1327 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1328 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
1332 bool Process::GetEventsPrivate(EventSP &event_sp,
1333 const Timeout<std::micro> &timeout,
1334 bool control_only) {
1335 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1336 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1339 return m_private_state_listener_sp->GetEventForBroadcaster(
1340 &m_private_state_control_broadcaster, event_sp, timeout);
1342 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
1345 bool Process::IsRunning() const {
1346 return StateIsRunningState(m_public_state.GetValue());
1349 int Process::GetExitStatus() {
1350 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1352 if (m_public_state.GetValue() == eStateExited)
1353 return m_exit_status;
1357 const char *Process::GetExitDescription() {
1358 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1360 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1361 return m_exit_string.c_str();
1365 bool Process::SetExitStatus(int status, const char *cstr) {
1366 // Use a mutex to protect setting the exit status.
1367 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1369 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1370 LIBLLDB_LOG_PROCESS));
1373 "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1374 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL",
1377 // We were already in the exited state
1378 if (m_private_state.GetValue() == eStateExited) {
1380 log->Printf("Process::SetExitStatus () ignoring exit status because "
1381 "state was already set to eStateExited");
1385 m_exit_status = status;
1387 m_exit_string = cstr;
1389 m_exit_string.clear();
1391 // Clear the last natural stop ID since it has a strong
1392 // reference to this process
1393 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1395 SetPrivateState(eStateExited);
1397 // Allow subclasses to do some cleanup
1403 bool Process::IsAlive() {
1404 switch (m_private_state.GetValue()) {
1405 case eStateConnected:
1406 case eStateAttaching:
1407 case eStateLaunching:
1410 case eStateStepping:
1412 case eStateSuspended:
1419 // This static callback can be used to watch for local child processes on
1420 // the current host. The child process exits, the process will be
1421 // found in the global target list (we want to be completely sure that the
1422 // lldb_private::Process doesn't go away before we can deliver the signal.
1423 bool Process::SetProcessExitStatus(
1424 lldb::pid_t pid, bool exited,
1425 int signo, // Zero for no signal
1426 int exit_status // Exit value of process if signal is zero
1428 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1430 log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64
1431 ", exited=%i, signal=%i, exit_status=%i)\n",
1432 pid, exited, signo, exit_status);
1435 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1437 ProcessSP process_sp(target_sp->GetProcessSP());
1439 const char *signal_cstr = nullptr;
1441 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1443 process_sp->SetExitStatus(exit_status, signal_cstr);
1451 void Process::UpdateThreadListIfNeeded() {
1452 const uint32_t stop_id = GetStopID();
1453 if (m_thread_list.GetSize(false) == 0 ||
1454 stop_id != m_thread_list.GetStopID()) {
1455 const StateType state = GetPrivateState();
1456 if (StateIsStoppedState(state, true)) {
1457 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
1458 // m_thread_list does have its own mutex, but we need to
1459 // hold onto the mutex between the call to UpdateThreadList(...)
1460 // and the os->UpdateThreadList(...) so it doesn't change on us
1461 ThreadList &old_thread_list = m_thread_list;
1462 ThreadList real_thread_list(this);
1463 ThreadList new_thread_list(this);
1464 // Always update the thread list with the protocol specific
1465 // thread list, but only update if "true" is returned
1466 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1467 // Don't call into the OperatingSystem to update the thread list if we
1468 // are shutting down, since
1469 // that may call back into the SBAPI's, requiring the API lock which is
1470 // already held by whoever is
1471 // shutting us down, causing a deadlock.
1472 OperatingSystem *os = GetOperatingSystem();
1473 if (os && !m_destroy_in_process) {
1474 // Clear any old backing threads where memory threads might have been
1475 // backed by actual threads from the lldb_private::Process subclass
1476 size_t num_old_threads = old_thread_list.GetSize(false);
1477 for (size_t i = 0; i < num_old_threads; ++i)
1478 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1480 // Turn off dynamic types to ensure we don't run any expressions.
1482 // can run an expression to determine if a SBValue is a dynamic type
1484 // and we need to avoid this. OperatingSystem plug-ins can't run
1486 // that require running code...
1488 Target &target = GetTarget();
1489 const lldb::DynamicValueType saved_prefer_dynamic =
1490 target.GetPreferDynamicValue();
1491 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1492 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1494 // Now let the OperatingSystem plug-in update the thread list
1496 os->UpdateThreadList(
1497 old_thread_list, // Old list full of threads created by OS plug-in
1498 real_thread_list, // The actual thread list full of threads
1499 // created by each lldb_private::Process
1501 new_thread_list); // The new thread list that we will show to the
1502 // user that gets filled in
1504 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1505 target.SetPreferDynamicValue(saved_prefer_dynamic);
1507 // No OS plug-in, the new thread list is the same as the real thread
1509 new_thread_list = real_thread_list;
1512 m_thread_list_real.Update(real_thread_list);
1513 m_thread_list.Update(new_thread_list);
1514 m_thread_list.SetStopID(stop_id);
1516 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1517 // Clear any extended threads that we may have accumulated previously
1518 m_extended_thread_list.Clear();
1519 m_extended_thread_stop_id = GetLastNaturalStopID();
1521 m_queue_list.Clear();
1522 m_queue_list_stop_id = GetLastNaturalStopID();
1529 void Process::UpdateQueueListIfNeeded() {
1530 if (m_system_runtime_ap) {
1531 if (m_queue_list.GetSize() == 0 ||
1532 m_queue_list_stop_id != GetLastNaturalStopID()) {
1533 const StateType state = GetPrivateState();
1534 if (StateIsStoppedState(state, true)) {
1535 m_system_runtime_ap->PopulateQueueList(m_queue_list);
1536 m_queue_list_stop_id = GetLastNaturalStopID();
1542 ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1543 OperatingSystem *os = GetOperatingSystem();
1545 return os->CreateThread(tid, context);
1549 uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1550 return AssignIndexIDToThread(thread_id);
1553 bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1554 return (m_thread_id_to_index_id_map.find(thread_id) !=
1555 m_thread_id_to_index_id_map.end());
1558 uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1559 uint32_t result = 0;
1560 std::map<uint64_t, uint32_t>::iterator iterator =
1561 m_thread_id_to_index_id_map.find(thread_id);
1562 if (iterator == m_thread_id_to_index_id_map.end()) {
1563 result = ++m_thread_index_id;
1564 m_thread_id_to_index_id_map[thread_id] = result;
1566 result = iterator->second;
1572 StateType Process::GetState() {
1573 return m_public_state.GetValue();
1576 bool Process::StateChangedIsExternallyHijacked() {
1577 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1578 const char *hijacking_name = GetHijackingListenerName();
1579 if (hijacking_name &&
1580 strcmp(hijacking_name, "lldb.Process.ResumeSynchronous.hijack"))
1586 void Process::SetPublicState(StateType new_state, bool restarted) {
1587 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1588 LIBLLDB_LOG_PROCESS));
1590 log->Printf("Process::SetPublicState (state = %s, restarted = %i)",
1591 StateAsCString(new_state), restarted);
1592 const StateType old_state = m_public_state.GetValue();
1593 m_public_state.SetValue(new_state);
1595 // On the transition from Run to Stopped, we unlock the writer end of the
1596 // run lock. The lock gets locked in Resume, which is the public API
1597 // to tell the program to run.
1598 if (!StateChangedIsExternallyHijacked()) {
1599 if (new_state == eStateDetached) {
1602 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1603 StateAsCString(new_state));
1604 m_public_run_lock.SetStopped();
1606 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1607 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1608 if ((old_state_is_stopped != new_state_is_stopped)) {
1609 if (new_state_is_stopped && !restarted) {
1611 log->Printf("Process::SetPublicState (%s) -- unlocking run lock",
1612 StateAsCString(new_state));
1613 m_public_run_lock.SetStopped();
1620 Status Process::Resume() {
1621 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1622 LIBLLDB_LOG_PROCESS));
1624 log->Printf("Process::Resume -- locking run lock");
1625 if (!m_public_run_lock.TrySetRunning()) {
1626 Status error("Resume request failed - process still running.");
1628 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1631 Status error = PrivateResume();
1632 if (!error.Success()) {
1633 // Undo running state change
1634 m_public_run_lock.SetStopped();
1639 Status Process::ResumeSynchronous(Stream *stream) {
1640 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1641 LIBLLDB_LOG_PROCESS));
1643 log->Printf("Process::ResumeSynchronous -- locking run lock");
1644 if (!m_public_run_lock.TrySetRunning()) {
1645 Status error("Resume request failed - process still running.");
1647 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1651 ListenerSP listener_sp(
1652 Listener::MakeListener("lldb.Process.ResumeSynchronous.hijack"));
1653 HijackProcessEvents(listener_sp);
1655 Status error = PrivateResume();
1656 if (error.Success()) {
1658 WaitForProcessToStop(llvm::None, NULL, true, listener_sp, stream);
1659 const bool must_be_alive =
1660 false; // eStateExited is ok, so this must be false
1661 if (!StateIsStoppedState(state, must_be_alive))
1662 error.SetErrorStringWithFormat(
1663 "process not in stopped state after synchronous resume: %s",
1664 StateAsCString(state));
1666 // Undo running state change
1667 m_public_run_lock.SetStopped();
1670 // Undo the hijacking of process events...
1671 RestoreProcessEvents();
1676 StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
1678 void Process::SetPrivateState(StateType new_state) {
1679 if (m_finalize_called)
1682 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1683 LIBLLDB_LOG_PROCESS));
1684 bool state_changed = false;
1687 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1689 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1690 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1692 const StateType old_state = m_private_state.GetValueNoLock();
1693 state_changed = old_state != new_state;
1695 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1696 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1697 if (old_state_is_stopped != new_state_is_stopped) {
1698 if (new_state_is_stopped)
1699 m_private_run_lock.SetStopped();
1701 m_private_run_lock.SetRunning();
1704 if (state_changed) {
1705 m_private_state.SetValueNoLock(new_state);
1707 new Event(eBroadcastBitStateChanged,
1708 new ProcessEventData(shared_from_this(), new_state)));
1709 if (StateIsStoppedState(new_state, false)) {
1710 // Note, this currently assumes that all threads in the list
1711 // stop when the process stops. In the future we will want to
1712 // support a debugging model where some threads continue to run
1713 // while others are stopped. When that happens we will either need
1714 // a way for the thread list to identify which threads are stopping
1715 // or create a special thread list containing only threads which
1716 // actually stopped.
1718 // The process plugin is responsible for managing the actual
1719 // behavior of the threads and should have stopped any threads
1720 // that are going to stop before we get here.
1721 m_thread_list.DidStop();
1723 m_mod_id.BumpStopID();
1724 if (!m_mod_id.IsLastResumeForUserExpression())
1725 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1726 m_memory_cache.Clear();
1728 log->Printf("Process::SetPrivateState (%s) stop_id = %u",
1729 StateAsCString(new_state), m_mod_id.GetStopID());
1732 // Use our target to get a shared pointer to ourselves...
1733 if (m_finalize_called && !PrivateStateThreadIsValid())
1734 BroadcastEvent(event_sp);
1736 m_private_state_broadcaster.BroadcastEvent(event_sp);
1740 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1741 StateAsCString(new_state));
1745 void Process::SetRunningUserExpression(bool on) {
1746 m_mod_id.SetRunningUserExpression(on);
1749 addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1751 const lldb::ABISP &Process::GetABI() {
1753 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
1757 LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language,
1758 bool retry_if_null) {
1762 LanguageRuntimeCollection::iterator pos;
1763 pos = m_language_runtimes.find(language);
1764 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) {
1765 lldb::LanguageRuntimeSP runtime_sp(
1766 LanguageRuntime::FindPlugin(this, language));
1768 m_language_runtimes[language] = runtime_sp;
1769 return runtime_sp.get();
1771 return (*pos).second.get();
1774 CPPLanguageRuntime *Process::GetCPPLanguageRuntime(bool retry_if_null) {
1775 LanguageRuntime *runtime =
1776 GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1777 if (runtime != nullptr &&
1778 runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1779 return static_cast<CPPLanguageRuntime *>(runtime);
1783 ObjCLanguageRuntime *Process::GetObjCLanguageRuntime(bool retry_if_null) {
1784 LanguageRuntime *runtime =
1785 GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1786 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC)
1787 return static_cast<ObjCLanguageRuntime *>(runtime);
1791 bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1795 if (in_value.IsDynamic())
1797 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1799 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1800 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1801 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1804 LanguageRuntime *cpp_runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1805 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1808 LanguageRuntime *objc_runtime = GetLanguageRuntime(eLanguageTypeObjC);
1809 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1812 void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
1813 m_dynamic_checkers_ap.reset(dynamic_checkers);
1816 BreakpointSiteList &Process::GetBreakpointSiteList() {
1817 return m_breakpoint_site_list;
1820 const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1821 return m_breakpoint_site_list;
1824 void Process::DisableAllBreakpointSites() {
1825 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1826 // bp_site->SetEnabled(true);
1827 DisableBreakpointSite(bp_site);
1831 Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1832 Status error(DisableBreakpointSiteByID(break_id));
1834 if (error.Success())
1835 m_breakpoint_site_list.Remove(break_id);
1840 Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1842 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1844 if (bp_site_sp->IsEnabled())
1845 error = DisableBreakpointSite(bp_site_sp.get());
1847 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1854 Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1856 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1858 if (!bp_site_sp->IsEnabled())
1859 error = EnableBreakpointSite(bp_site_sp.get());
1861 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1868 Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1869 bool use_hardware) {
1870 addr_t load_addr = LLDB_INVALID_ADDRESS;
1872 bool show_error = true;
1873 switch (GetState()) {
1875 case eStateUnloaded:
1876 case eStateConnected:
1877 case eStateAttaching:
1878 case eStateLaunching:
1879 case eStateDetached:
1886 case eStateStepping:
1888 case eStateSuspended:
1889 show_error = IsAlive();
1893 // Reset the IsIndirect flag here, in case the location changes from
1894 // pointing to a indirect symbol to a regular symbol.
1895 owner->SetIsIndirect(false);
1897 if (owner->ShouldResolveIndirectFunctions()) {
1898 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1899 if (symbol && symbol->IsIndirect()) {
1901 Address symbol_address = symbol->GetAddress();
1902 load_addr = ResolveIndirectFunction(&symbol_address, error);
1903 if (!error.Success() && show_error) {
1904 GetTarget().GetDebugger().GetErrorFile()->Printf(
1905 "warning: failed to resolve indirect function at 0x%" PRIx64
1906 " for breakpoint %i.%i: %s\n",
1907 symbol->GetLoadAddress(&GetTarget()),
1908 owner->GetBreakpoint().GetID(), owner->GetID(),
1909 error.AsCString() ? error.AsCString() : "unknown error");
1910 return LLDB_INVALID_BREAK_ID;
1912 Address resolved_address(load_addr);
1913 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1914 owner->SetIsIndirect(true);
1916 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1918 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1920 if (load_addr != LLDB_INVALID_ADDRESS) {
1921 BreakpointSiteSP bp_site_sp;
1923 // Look up this breakpoint site. If it exists, then add this new owner,
1925 // create a new breakpoint site and add it.
1927 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1930 bp_site_sp->AddOwner(owner);
1931 owner->SetBreakpointSite(bp_site_sp);
1932 return bp_site_sp->GetID();
1934 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1935 load_addr, use_hardware));
1937 Status error = EnableBreakpointSite(bp_site_sp.get());
1938 if (error.Success()) {
1939 owner->SetBreakpointSite(bp_site_sp);
1940 return m_breakpoint_site_list.Add(bp_site_sp);
1943 // Report error for setting breakpoint...
1944 GetTarget().GetDebugger().GetErrorFile()->Printf(
1945 "warning: failed to set breakpoint site at 0x%" PRIx64
1946 " for breakpoint %i.%i: %s\n",
1947 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1948 error.AsCString() ? error.AsCString() : "unknown error");
1954 // We failed to enable the breakpoint
1955 return LLDB_INVALID_BREAK_ID;
1958 void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1959 lldb::user_id_t owner_loc_id,
1960 BreakpointSiteSP &bp_site_sp) {
1961 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1962 if (num_owners == 0) {
1963 // Don't try to disable the site if we don't have a live process anymore.
1965 DisableBreakpointSite(bp_site_sp.get());
1966 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1970 size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1971 uint8_t *buf) const {
1972 size_t bytes_removed = 0;
1973 BreakpointSiteList bp_sites_in_range;
1975 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1976 bp_sites_in_range)) {
1977 bp_sites_in_range.ForEach([bp_addr, size,
1978 buf](BreakpointSite *bp_site) -> void {
1979 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1980 addr_t intersect_addr;
1981 size_t intersect_size;
1982 size_t opcode_offset;
1983 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1984 &intersect_size, &opcode_offset)) {
1985 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1986 assert(bp_addr < intersect_addr + intersect_size &&
1987 intersect_addr + intersect_size <= bp_addr + size);
1988 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1989 size_t buf_offset = intersect_addr - bp_addr;
1990 ::memcpy(buf + buf_offset,
1991 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1997 return bytes_removed;
2000 size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
2001 PlatformSP platform_sp(GetTarget().GetPlatform());
2003 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
2007 Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
2009 assert(bp_site != nullptr);
2010 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2011 const addr_t bp_addr = bp_site->GetLoadAddress();
2014 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
2015 bp_site->GetID(), (uint64_t)bp_addr);
2016 if (bp_site->IsEnabled()) {
2019 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2020 " -- already enabled",
2021 bp_site->GetID(), (uint64_t)bp_addr);
2025 if (bp_addr == LLDB_INVALID_ADDRESS) {
2026 error.SetErrorString("BreakpointSite contains an invalid load address.");
2029 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2030 // trap for the breakpoint site
2031 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2033 if (bp_opcode_size == 0) {
2034 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
2035 "returned zero, unable to get breakpoint "
2036 "trap for address 0x%" PRIx64,
2039 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2041 if (bp_opcode_bytes == nullptr) {
2042 error.SetErrorString(
2043 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2047 // Save the original opcode by reading it
2048 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
2049 error) == bp_opcode_size) {
2050 // Write a software breakpoint in place of the original opcode
2051 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
2053 uint8_t verify_bp_opcode_bytes[64];
2054 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
2055 error) == bp_opcode_size) {
2056 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
2057 bp_opcode_size) == 0) {
2058 bp_site->SetEnabled(true);
2059 bp_site->SetType(BreakpointSite::eSoftware);
2061 log->Printf("Process::EnableSoftwareBreakpoint (site_id = %d) "
2062 "addr = 0x%" PRIx64 " -- SUCCESS",
2063 bp_site->GetID(), (uint64_t)bp_addr);
2065 error.SetErrorString(
2066 "failed to verify the breakpoint trap in memory.");
2068 error.SetErrorString(
2069 "Unable to read memory to verify breakpoint trap.");
2071 error.SetErrorString("Unable to write breakpoint trap to memory.");
2073 error.SetErrorString("Unable to read memory at breakpoint address.");
2075 if (log && error.Fail())
2077 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2079 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2083 Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
2085 assert(bp_site != nullptr);
2086 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2087 addr_t bp_addr = bp_site->GetLoadAddress();
2088 lldb::user_id_t breakID = bp_site->GetID();
2090 log->Printf("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
2091 ") addr = 0x%" PRIx64,
2092 breakID, (uint64_t)bp_addr);
2094 if (bp_site->IsHardware()) {
2095 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2096 } else if (bp_site->IsEnabled()) {
2097 const size_t break_op_size = bp_site->GetByteSize();
2098 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
2099 if (break_op_size > 0) {
2100 // Clear a software breakpoint instruction
2101 uint8_t curr_break_op[8];
2102 assert(break_op_size <= sizeof(curr_break_op));
2103 bool break_op_found = false;
2105 // Read the breakpoint opcode
2106 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
2108 bool verify = false;
2109 // Make sure the breakpoint opcode exists at this address
2110 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
2111 break_op_found = true;
2112 // We found a valid breakpoint opcode at this address, now restore
2113 // the saved opcode.
2114 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
2115 break_op_size, error) == break_op_size) {
2118 error.SetErrorString(
2119 "Memory write failed when restoring original opcode.");
2121 error.SetErrorString(
2122 "Original breakpoint trap is no longer in memory.");
2123 // Set verify to true and so we can check if the original opcode has
2124 // already been restored
2129 uint8_t verify_opcode[8];
2130 assert(break_op_size < sizeof(verify_opcode));
2131 // Verify that our original opcode made it back to the inferior
2132 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
2134 // compare the memory we just read with the original opcode
2135 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
2136 break_op_size) == 0) {
2138 bp_site->SetEnabled(false);
2140 log->Printf("Process::DisableSoftwareBreakpoint (site_id = %d) "
2141 "addr = 0x%" PRIx64 " -- SUCCESS",
2142 bp_site->GetID(), (uint64_t)bp_addr);
2146 error.SetErrorString("Failed to restore original opcode.");
2149 error.SetErrorString("Failed to read memory to verify that "
2150 "breakpoint trap was restored.");
2153 error.SetErrorString(
2154 "Unable to read memory that should contain the breakpoint trap.");
2159 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2160 " -- already disabled",
2161 bp_site->GetID(), (uint64_t)bp_addr);
2167 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2169 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2173 // Uncomment to verify memory caching works after making changes to caching code
2174 //#define VERIFY_MEMORY_READS
2176 size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
2178 if (!GetDisableMemoryCache()) {
2179 #if defined(VERIFY_MEMORY_READS)
2180 // Memory caching is enabled, with debug verification
2183 // Uncomment the line below to make sure memory caching is working.
2184 // I ran this through the test suite and got no assertions, so I am
2185 // pretty confident this is working well. If any changes are made to
2186 // memory caching, uncomment the line below and test your changes!
2188 // Verify all memory reads by using the cache first, then redundantly
2189 // reading the same memory from the inferior and comparing to make sure
2190 // everything is exactly the same.
2191 std::string verify_buf(size, '\0');
2192 assert(verify_buf.size() == size);
2193 const size_t cache_bytes_read =
2194 m_memory_cache.Read(this, addr, buf, size, error);
2195 Status verify_error;
2196 const size_t verify_bytes_read =
2197 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2198 verify_buf.size(), verify_error);
2199 assert(cache_bytes_read == verify_bytes_read);
2200 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2201 assert(verify_error.Success() == error.Success());
2202 return cache_bytes_read;
2205 #else // !defined(VERIFY_MEMORY_READS)
2206 // Memory caching is enabled, without debug verification
2208 return m_memory_cache.Read(addr, buf, size, error);
2209 #endif // defined (VERIFY_MEMORY_READS)
2211 // Memory caching is disabled
2213 return ReadMemoryFromInferior(addr, buf, size, error);
2217 size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
2221 addr_t curr_addr = addr;
2223 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2226 out_str.append(buf, length);
2227 // If we got "length - 1" bytes, we didn't get the whole C string, we
2228 // need to read some more characters
2229 if (length == sizeof(buf) - 1)
2230 curr_addr += length;
2234 return out_str.size();
2237 size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
2238 Status &error, size_t type_width) {
2239 size_t total_bytes_read = 0;
2240 if (dst && max_bytes && type_width && max_bytes >= type_width) {
2241 // Ensure a null terminator independent of the number of bytes that is read.
2242 memset(dst, 0, max_bytes);
2243 size_t bytes_left = max_bytes - type_width;
2245 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2246 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2247 "string with more than 4 bytes "
2250 addr_t curr_addr = addr;
2251 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2252 char *curr_dst = dst;
2255 while (bytes_left > 0 && error.Success()) {
2256 addr_t cache_line_bytes_left =
2257 cache_line_size - (curr_addr % cache_line_size);
2258 addr_t bytes_to_read =
2259 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2260 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
2262 if (bytes_read == 0)
2265 // Search for a null terminator of correct size and alignment in
2267 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2268 for (size_t i = aligned_start;
2269 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2270 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2275 total_bytes_read += bytes_read;
2276 curr_dst += bytes_read;
2277 curr_addr += bytes_read;
2278 bytes_left -= bytes_read;
2282 error.SetErrorString("invalid arguments");
2284 return total_bytes_read;
2287 // Deprecated in favor of ReadStringFromMemory which has wchar support and
2288 // correct code to find
2289 // null terminators.
2290 size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
2292 Status &result_error) {
2293 size_t total_cstr_len = 0;
2294 if (dst && dst_max_len) {
2295 result_error.Clear();
2296 // NULL out everything just to be safe
2297 memset(dst, 0, dst_max_len);
2299 addr_t curr_addr = addr;
2300 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2301 size_t bytes_left = dst_max_len - 1;
2302 char *curr_dst = dst;
2304 while (bytes_left > 0) {
2305 addr_t cache_line_bytes_left =
2306 cache_line_size - (curr_addr % cache_line_size);
2307 addr_t bytes_to_read =
2308 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2309 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
2311 if (bytes_read == 0) {
2312 result_error = error;
2313 dst[total_cstr_len] = '\0';
2316 const size_t len = strlen(curr_dst);
2318 total_cstr_len += len;
2320 if (len < bytes_to_read)
2323 curr_dst += bytes_read;
2324 curr_addr += bytes_read;
2325 bytes_left -= bytes_read;
2329 result_error.SetErrorString("invalid arguments");
2331 result_error.Clear();
2333 return total_cstr_len;
2336 size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
2338 if (buf == nullptr || size == 0)
2341 size_t bytes_read = 0;
2342 uint8_t *bytes = (uint8_t *)buf;
2344 while (bytes_read < size) {
2345 const size_t curr_size = size - bytes_read;
2346 const size_t curr_bytes_read =
2347 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2348 bytes_read += curr_bytes_read;
2349 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2353 // Replace any software breakpoint opcodes that fall into this range back
2354 // into "buf" before we return
2356 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2360 uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2361 size_t integer_byte_size,
2362 uint64_t fail_value,
2365 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2367 return scalar.ULongLong(fail_value);
2371 int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2372 size_t integer_byte_size,
2376 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2378 return scalar.SLongLong(fail_value);
2382 addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
2384 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2386 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2387 return LLDB_INVALID_ADDRESS;
2390 bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
2393 const uint32_t addr_byte_size = GetAddressByteSize();
2394 if (addr_byte_size <= 4)
2395 scalar = (uint32_t)ptr_value;
2398 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2402 size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
2404 size_t bytes_written = 0;
2405 const uint8_t *bytes = (const uint8_t *)buf;
2407 while (bytes_written < size) {
2408 const size_t curr_size = size - bytes_written;
2409 const size_t curr_bytes_written = DoWriteMemory(
2410 addr + bytes_written, bytes + bytes_written, curr_size, error);
2411 bytes_written += curr_bytes_written;
2412 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2415 return bytes_written;
2418 size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
2420 #if defined(ENABLE_MEMORY_CACHING)
2421 m_memory_cache.Flush(addr, size);
2424 if (buf == nullptr || size == 0)
2427 m_mod_id.BumpMemoryID();
2429 // We need to write any data that would go where any current software traps
2430 // (enabled software breakpoints) any software traps (breakpoints) that we
2431 // may have placed in our tasks memory.
2433 BreakpointSiteList bp_sites_in_range;
2435 if (m_breakpoint_site_list.FindInRange(addr, addr + size,
2436 bp_sites_in_range)) {
2437 // No breakpoint sites overlap
2438 if (bp_sites_in_range.IsEmpty())
2439 return WriteMemoryPrivate(addr, buf, size, error);
2441 const uint8_t *ubuf = (const uint8_t *)buf;
2442 uint64_t bytes_written = 0;
2444 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2445 &error](BreakpointSite *bp) -> void {
2447 if (error.Success()) {
2448 addr_t intersect_addr;
2449 size_t intersect_size;
2450 size_t opcode_offset;
2451 const bool intersects = bp->IntersectsRange(
2452 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2453 UNUSED_IF_ASSERT_DISABLED(intersects);
2455 assert(addr <= intersect_addr && intersect_addr < addr + size);
2456 assert(addr < intersect_addr + intersect_size &&
2457 intersect_addr + intersect_size <= addr + size);
2458 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2460 // Check for bytes before this breakpoint
2461 const addr_t curr_addr = addr + bytes_written;
2462 if (intersect_addr > curr_addr) {
2463 // There are some bytes before this breakpoint that we need to
2464 // just write to memory
2465 size_t curr_size = intersect_addr - curr_addr;
2466 size_t curr_bytes_written = WriteMemoryPrivate(
2467 curr_addr, ubuf + bytes_written, curr_size, error);
2468 bytes_written += curr_bytes_written;
2469 if (curr_bytes_written != curr_size) {
2470 // We weren't able to write all of the requested bytes, we
2471 // are done looping and will return the number of bytes that
2472 // we have written so far.
2473 if (error.Success())
2474 error.SetErrorToGenericError();
2477 // Now write any bytes that would cover up any software breakpoints
2478 // directly into the breakpoint opcode buffer
2479 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset,
2480 ubuf + bytes_written, intersect_size);
2481 bytes_written += intersect_size;
2485 if (bytes_written < size)
2486 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2487 size - bytes_written, error);
2490 return WriteMemoryPrivate(addr, buf, size, error);
2493 // Write any remaining bytes after the last breakpoint if we have any left
2494 return 0; // bytes_written;
2497 size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2498 size_t byte_size, Status &error) {
2499 if (byte_size == UINT32_MAX)
2500 byte_size = scalar.GetByteSize();
2501 if (byte_size > 0) {
2503 const size_t mem_size =
2504 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2506 return WriteMemory(addr, buf, mem_size, error);
2508 error.SetErrorString("failed to get scalar as memory data");
2510 error.SetErrorString("invalid scalar value");
2515 size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2516 bool is_signed, Scalar &scalar,
2519 if (byte_size == 0) {
2520 error.SetErrorString("byte size is zero");
2521 } else if (byte_size & (byte_size - 1)) {
2522 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2524 } else if (byte_size <= sizeof(uval)) {
2525 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2526 if (bytes_read == byte_size) {
2527 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2528 GetAddressByteSize());
2529 lldb::offset_t offset = 0;
2531 scalar = data.GetMaxU32(&offset, byte_size);
2533 scalar = data.GetMaxU64(&offset, byte_size);
2535 scalar.SignExtend(byte_size * 8);
2539 error.SetErrorStringWithFormat(
2540 "byte size of %u is too large for integer scalar type", byte_size);
2545 #define USE_ALLOCATE_MEMORY_CACHE 1
2546 addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2548 if (GetPrivateState() != eStateStopped)
2549 return LLDB_INVALID_ADDRESS;
2551 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2552 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2554 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2555 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2557 log->Printf("Process::AllocateMemory(size=%" PRIu64
2558 ", permissions=%s) => 0x%16.16" PRIx64
2559 " (m_stop_id = %u m_memory_id = %u)",
2560 (uint64_t)size, GetPermissionsAsCString(permissions),
2561 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2562 m_mod_id.GetMemoryID());
2563 return allocated_addr;
2567 addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2569 addr_t return_addr = AllocateMemory(size, permissions, error);
2570 if (error.Success()) {
2571 std::string buffer(size, 0);
2572 WriteMemory(return_addr, buffer.c_str(), size, error);
2577 bool Process::CanJIT() {
2578 if (m_can_jit == eCanJITDontKnow) {
2579 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2582 uint64_t allocated_memory = AllocateMemory(
2583 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2586 if (err.Success()) {
2587 m_can_jit = eCanJITYes;
2589 log->Printf("Process::%s pid %" PRIu64
2590 " allocation test passed, CanJIT () is true",
2591 __FUNCTION__, GetID());
2593 m_can_jit = eCanJITNo;
2595 log->Printf("Process::%s pid %" PRIu64
2596 " allocation test failed, CanJIT () is false: %s",
2597 __FUNCTION__, GetID(), err.AsCString());
2600 DeallocateMemory(allocated_memory);
2603 return m_can_jit == eCanJITYes;
2606 void Process::SetCanJIT(bool can_jit) {
2607 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2610 void Process::SetCanRunCode(bool can_run_code) {
2611 SetCanJIT(can_run_code);
2612 m_can_interpret_function_calls = can_run_code;
2615 Status Process::DeallocateMemory(addr_t ptr) {
2617 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2618 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2619 error.SetErrorStringWithFormat(
2620 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2623 error = DoDeallocateMemory(ptr);
2625 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2627 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64
2628 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2629 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2630 m_mod_id.GetMemoryID());
2635 ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2636 lldb::addr_t header_addr,
2637 size_t size_to_read) {
2638 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2640 log->Printf("Process::ReadModuleFromMemory reading %s binary from memory",
2641 file_spec.GetPath().c_str());
2643 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2646 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2647 shared_from_this(), header_addr, error, size_to_read);
2654 bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2655 uint32_t &permissions) {
2656 MemoryRegionInfo range_info;
2658 Status error(GetMemoryRegionInfo(load_addr, range_info));
2659 if (!error.Success())
2661 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2662 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2663 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2667 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2668 permissions |= lldb::ePermissionsReadable;
2670 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2671 permissions |= lldb::ePermissionsWritable;
2673 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2674 permissions |= lldb::ePermissionsExecutable;
2679 Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2681 error.SetErrorString("watchpoints are not supported");
2685 Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2687 error.SetErrorString("watchpoints are not supported");
2692 Process::WaitForProcessStopPrivate(EventSP &event_sp,
2693 const Timeout<std::micro> &timeout) {
2695 // Now wait for the process to launch and return control to us, and then
2699 state = GetStateChangedEventsPrivate(event_sp, timeout);
2701 if (StateIsStoppedState(state, false))
2704 // If state is invalid, then we timed out
2705 if (state == eStateInvalid)
2709 HandlePrivateEvent(event_sp);
2714 void Process::LoadOperatingSystemPlugin(bool flush) {
2716 m_thread_list.Clear();
2717 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
2722 Status Process::Launch(ProcessLaunchInfo &launch_info) {
2726 m_jit_loaders_ap.reset();
2727 m_system_runtime_ap.reset();
2729 m_process_input_reader.reset();
2731 Module *exe_module = GetTarget().GetExecutableModulePointer();
2733 char local_exec_file_path[PATH_MAX];
2734 char platform_exec_file_path[PATH_MAX];
2735 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2736 sizeof(local_exec_file_path));
2737 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2738 sizeof(platform_exec_file_path));
2739 if (exe_module->GetFileSpec().Exists()) {
2740 // Install anything that might need to be installed prior to launching.
2741 // For host systems, this will do nothing, but if we are connected to a
2742 // remote platform it will install any needed binaries
2743 error = GetTarget().Install(&launch_info);
2747 if (PrivateStateThreadIsValid())
2748 PausePrivateStateThread();
2750 error = WillLaunch(exe_module);
2751 if (error.Success()) {
2752 const bool restarted = false;
2753 SetPublicState(eStateLaunching, restarted);
2754 m_should_detach = false;
2756 if (m_public_run_lock.TrySetRunning()) {
2757 // Now launch using these arguments.
2758 error = DoLaunch(exe_module, launch_info);
2760 // This shouldn't happen
2761 error.SetErrorString("failed to acquire process run lock");
2765 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2766 SetID(LLDB_INVALID_PROCESS_ID);
2767 const char *error_string = error.AsCString();
2768 if (error_string == nullptr)
2769 error_string = "launch failed";
2770 SetExitStatus(-1, error_string);
2774 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
2776 if (state == eStateInvalid || !event_sp) {
2777 // We were able to launch the process, but we failed to
2778 // catch the initial stop.
2779 error.SetErrorString("failed to catch stop after launch");
2780 SetExitStatus(0, "failed to catch stop after launch");
2782 } else if (state == eStateStopped || state == eStateCrashed) {
2785 DynamicLoader *dyld = GetDynamicLoader();
2789 GetJITLoaders().DidLaunch();
2791 SystemRuntime *system_runtime = GetSystemRuntime();
2793 system_runtime->DidLaunch();
2796 LoadOperatingSystemPlugin(false);
2798 // We successfully launched the process and stopped,
2799 // now it the right time to set up signal filters before resuming.
2800 UpdateAutomaticSignalFiltering();
2802 // Note, the stop event was consumed above, but not handled. This
2804 // to give DidLaunch a chance to run. The target is either stopped
2806 // Directly set the state. This is done to prevent a stop message
2808 // of spurious output on thread status, as well as not pop a
2809 // ProcessIOHandler.
2810 SetPublicState(state, false);
2812 if (PrivateStateThreadIsValid())
2813 ResumePrivateStateThread();
2815 StartPrivateStateThread();
2817 // Target was stopped at entry as was intended. Need to notify the
2820 if (state == eStateStopped &&
2821 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2822 HandlePrivateEvent(event_sp);
2823 } else if (state == eStateExited) {
2824 // We exited while trying to launch somehow. Don't call DidLaunch
2826 // not likely to work, and return an invalid pid.
2827 HandlePrivateEvent(event_sp);
2832 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2833 local_exec_file_path);
2839 Status Process::LoadCore() {
2840 Status error = DoLoadCore();
2841 if (error.Success()) {
2842 ListenerSP listener_sp(
2843 Listener::MakeListener("lldb.process.load_core_listener"));
2844 HijackProcessEvents(listener_sp);
2846 if (PrivateStateThreadIsValid())
2847 ResumePrivateStateThread();
2849 StartPrivateStateThread();
2851 DynamicLoader *dyld = GetDynamicLoader();
2855 GetJITLoaders().DidAttach();
2857 SystemRuntime *system_runtime = GetSystemRuntime();
2859 system_runtime->DidAttach();
2862 LoadOperatingSystemPlugin(false);
2864 // We successfully loaded a core file, now pretend we stopped so we can
2865 // show all of the threads in the core file and explore the crashed
2867 SetPrivateState(eStateStopped);
2869 // Wait indefinitely for a stopped event since we just posted one above...
2870 lldb::EventSP event_sp;
2871 listener_sp->GetEvent(event_sp, llvm::None);
2872 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2874 if (!StateIsStoppedState(state, false)) {
2875 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2877 log->Printf("Process::Halt() failed to stop, state is: %s",
2878 StateAsCString(state));
2879 error.SetErrorString(
2880 "Did not get stopped event after loading the core file.");
2882 RestoreProcessEvents();
2887 DynamicLoader *Process::GetDynamicLoader() {
2889 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, nullptr));
2890 return m_dyld_ap.get();
2893 const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); }
2895 JITLoaderList &Process::GetJITLoaders() {
2896 if (!m_jit_loaders_ap) {
2897 m_jit_loaders_ap.reset(new JITLoaderList());
2898 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2900 return *m_jit_loaders_ap;
2903 SystemRuntime *Process::GetSystemRuntime() {
2904 if (!m_system_runtime_ap)
2905 m_system_runtime_ap.reset(SystemRuntime::FindPlugin(this));
2906 return m_system_runtime_ap.get();
2909 Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2910 uint32_t exec_count)
2911 : NextEventAction(process), m_exec_count(exec_count) {
2912 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2915 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2916 __FUNCTION__, static_cast<void *>(process), exec_count);
2919 Process::NextEventAction::EventActionResult
2920 Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2921 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2923 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2926 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2927 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2930 case eStateAttaching:
2931 return eEventActionSuccess;
2934 case eStateConnected:
2935 return eEventActionRetry;
2939 // During attach, prior to sending the eStateStopped event,
2940 // lldb_private::Process subclasses must set the new process ID.
2941 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2942 // We don't want these events to be reported, so go set the ShouldReportStop
2944 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2946 if (m_exec_count > 0) {
2950 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2951 "remaining exec count to %" PRIu32 ", requesting resume",
2952 __FUNCTION__, StateAsCString(state), m_exec_count);
2955 return eEventActionRetry;
2958 log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2959 "execs expected to start, continuing with attach",
2960 __FUNCTION__, StateAsCString(state));
2962 m_process->CompleteAttach();
2963 return eEventActionSuccess;
2973 m_exit_string.assign("No valid Process");
2974 return eEventActionExit;
2977 Process::NextEventAction::EventActionResult
2978 Process::AttachCompletionHandler::HandleBeingInterrupted() {
2979 return eEventActionSuccess;
2982 const char *Process::AttachCompletionHandler::GetExitString() {
2983 return m_exit_string.c_str();
2986 ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2988 return m_listener_sp;
2990 return debugger.GetListener();
2993 Status Process::Attach(ProcessAttachInfo &attach_info) {
2995 m_process_input_reader.reset();
2997 m_jit_loaders_ap.reset();
2998 m_system_runtime_ap.reset();
3001 lldb::pid_t attach_pid = attach_info.GetProcessID();
3003 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
3004 char process_name[PATH_MAX];
3006 if (attach_info.GetExecutableFile().GetPath(process_name,
3007 sizeof(process_name))) {
3008 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3010 if (wait_for_launch) {
3011 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3012 if (error.Success()) {
3013 if (m_public_run_lock.TrySetRunning()) {
3014 m_should_detach = true;
3015 const bool restarted = false;
3016 SetPublicState(eStateAttaching, restarted);
3017 // Now attach using these arguments.
3018 error = DoAttachToProcessWithName(process_name, attach_info);
3020 // This shouldn't happen
3021 error.SetErrorString("failed to acquire process run lock");
3025 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3026 SetID(LLDB_INVALID_PROCESS_ID);
3027 if (error.AsCString() == nullptr)
3028 error.SetErrorString("attach failed");
3030 SetExitStatus(-1, error.AsCString());
3033 SetNextEventAction(new Process::AttachCompletionHandler(
3034 this, attach_info.GetResumeCount()));
3035 StartPrivateStateThread();
3040 ProcessInstanceInfoList process_infos;
3041 PlatformSP platform_sp(GetTarget().GetPlatform());
3044 ProcessInstanceInfoMatch match_info;
3045 match_info.GetProcessInfo() = attach_info;
3046 match_info.SetNameMatchType(NameMatch::Equals);
3047 platform_sp->FindProcesses(match_info, process_infos);
3048 const uint32_t num_matches = process_infos.GetSize();
3049 if (num_matches == 1) {
3050 attach_pid = process_infos.GetProcessIDAtIndex(0);
3051 // Fall through and attach using the above process ID
3053 match_info.GetProcessInfo().GetExecutableFile().GetPath(
3054 process_name, sizeof(process_name));
3055 if (num_matches > 1) {
3057 ProcessInstanceInfo::DumpTableHeader(s, platform_sp.get(), true,
3059 for (size_t i = 0; i < num_matches; i++) {
3060 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
3061 s, platform_sp.get(), true, false);
3063 error.SetErrorStringWithFormat(
3064 "more than one process named %s:\n%s", process_name,
3067 error.SetErrorStringWithFormat(
3068 "could not find a process named %s", process_name);
3071 error.SetErrorString(
3072 "invalid platform, can't find processes by name");
3077 error.SetErrorString("invalid process name");
3081 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
3082 error = WillAttachToProcessWithID(attach_pid);
3083 if (error.Success()) {
3085 if (m_public_run_lock.TrySetRunning()) {
3086 // Now attach using these arguments.
3087 m_should_detach = true;
3088 const bool restarted = false;
3089 SetPublicState(eStateAttaching, restarted);
3090 error = DoAttachToProcessWithID(attach_pid, attach_info);
3092 // This shouldn't happen
3093 error.SetErrorString("failed to acquire process run lock");
3096 if (error.Success()) {
3097 SetNextEventAction(new Process::AttachCompletionHandler(
3098 this, attach_info.GetResumeCount()));
3099 StartPrivateStateThread();
3101 if (GetID() != LLDB_INVALID_PROCESS_ID)
3102 SetID(LLDB_INVALID_PROCESS_ID);
3104 const char *error_string = error.AsCString();
3105 if (error_string == nullptr)
3106 error_string = "attach failed";
3108 SetExitStatus(-1, error_string);
3115 void Process::CompleteAttach() {
3116 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3117 LIBLLDB_LOG_TARGET));
3119 log->Printf("Process::%s()", __FUNCTION__);
3121 // Let the process subclass figure out at much as it can about the process
3122 // before we go looking for a dynamic loader plug-in.
3123 ArchSpec process_arch;
3124 DidAttach(process_arch);
3126 if (process_arch.IsValid()) {
3127 GetTarget().SetArchitecture(process_arch);
3129 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
3130 log->Printf("Process::%s replacing process architecture with DidAttach() "
3132 __FUNCTION__, triple_str ? triple_str : "<null>");
3136 // We just attached. If we have a platform, ask it for the process
3137 // architecture, and if it isn't
3138 // the same as the one we've already set, switch architectures.
3139 PlatformSP platform_sp(GetTarget().GetPlatform());
3140 assert(platform_sp);
3142 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3143 if (target_arch.IsValid() &&
3144 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
3145 ArchSpec platform_arch;
3147 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
3149 GetTarget().SetPlatform(platform_sp);
3150 GetTarget().SetArchitecture(platform_arch);
3152 log->Printf("Process::%s switching platform to %s and architecture "
3153 "to %s based on info from attach",
3154 __FUNCTION__, platform_sp->GetName().AsCString(""),
3155 platform_arch.GetTriple().getTriple().c_str());
3157 } else if (!process_arch.IsValid()) {
3158 ProcessInstanceInfo process_info;
3159 GetProcessInfo(process_info);
3160 const ArchSpec &process_arch = process_info.GetArchitecture();
3161 if (process_arch.IsValid() &&
3162 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
3163 GetTarget().SetArchitecture(process_arch);
3165 log->Printf("Process::%s switching architecture to %s based on info "
3166 "the platform retrieved for pid %" PRIu64,
3168 process_arch.GetTriple().getTriple().c_str(), GetID());
3173 // We have completed the attach, now it is time to find the dynamic loader
3175 DynamicLoader *dyld = GetDynamicLoader();
3179 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3180 log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
3181 "executable is %s (using %s plugin)",
3183 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3185 dyld->GetPluginName().AsCString("<unnamed>"));
3189 GetJITLoaders().DidAttach();
3191 SystemRuntime *system_runtime = GetSystemRuntime();
3192 if (system_runtime) {
3193 system_runtime->DidAttach();
3195 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3196 log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
3197 "executable is %s (using %s plugin)",
3199 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3201 system_runtime->GetPluginName().AsCString("<unnamed>"));
3206 LoadOperatingSystemPlugin(false);
3207 // Figure out which one is the executable, and set that in our target:
3208 const ModuleList &target_modules = GetTarget().GetImages();
3209 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3210 size_t num_modules = target_modules.GetSize();
3211 ModuleSP new_executable_module_sp;
3213 for (size_t i = 0; i < num_modules; i++) {
3214 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3215 if (module_sp && module_sp->IsExecutable()) {
3216 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3217 new_executable_module_sp = module_sp;
3221 if (new_executable_module_sp) {
3222 GetTarget().SetExecutableModule(new_executable_module_sp, false);
3224 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3226 "Process::%s after looping through modules, target executable is %s",
3228 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3234 Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
3236 m_process_input_reader.reset();
3238 // Find the process and its architecture. Make sure it matches the
3239 // architecture of the current Target, and if not adjust it.
3241 Status error(DoConnectRemote(strm, remote_url));
3242 if (error.Success()) {
3243 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3245 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
3247 if (state == eStateStopped || state == eStateCrashed) {
3248 // If we attached and actually have a process on the other end, then
3249 // this ended up being the equivalent of an attach.
3252 // This delays passing the stopped event to listeners till
3253 // CompleteAttach gets a chance to complete...
3254 HandlePrivateEvent(event_sp);
3258 if (PrivateStateThreadIsValid())
3259 ResumePrivateStateThread();
3261 StartPrivateStateThread();
3266 Status Process::PrivateResume() {
3267 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3270 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3271 "private state: %s",
3272 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3273 StateAsCString(m_private_state.GetValue()));
3275 // If signals handing status changed we might want to update
3276 // our signal filters before resuming.
3277 UpdateAutomaticSignalFiltering();
3279 Status error(WillResume());
3280 // Tell the process it is about to resume before the thread list
3281 if (error.Success()) {
3282 // Now let the thread list know we are about to resume so it
3283 // can let all of our threads know that they are about to be
3284 // resumed. Threads will each be called with
3285 // Thread::WillResume(StateType) where StateType contains the state
3286 // that they are supposed to have when the process is resumed
3287 // (suspended/running/stepping). Threads should also check
3288 // their resume signal in lldb::Thread::GetResumeSignal()
3289 // to see if they are supposed to start back up with a signal.
3290 if (m_thread_list.WillResume()) {
3291 // Last thing, do the PreResumeActions.
3292 if (!RunPreResumeActions()) {
3293 error.SetErrorStringWithFormat(
3294 "Process::PrivateResume PreResumeActions failed, not resuming.");
3296 m_mod_id.BumpResumeID();
3298 if (error.Success()) {
3300 m_thread_list.DidResume();
3302 log->Printf("Process thinks the process has resumed.");
3306 // Somebody wanted to run without running (e.g. we were faking a step from
3307 // one frame of a set of inlined
3308 // frames that share the same PC to another.) So generate a continue & a
3310 // and let the world handle them.
3313 "Process::PrivateResume() asked to simulate a start & stop.");
3315 SetPrivateState(eStateRunning);
3316 SetPrivateState(eStateStopped);
3319 log->Printf("Process::PrivateResume() got an error \"%s\".",
3320 error.AsCString("<unknown error>"));
3324 Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3325 if (!StateIsRunningState(m_public_state.GetValue()))
3326 return Status("Process is not running.");
3328 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3329 // in case it was already set and some thread plan logic calls halt on its
3331 m_clear_thread_plans_on_stop |= clear_thread_plans;
3333 ListenerSP halt_listener_sp(
3334 Listener::MakeListener("lldb.process.halt_listener"));
3335 HijackProcessEvents(halt_listener_sp);
3339 SendAsyncInterrupt();
3341 if (m_public_state.GetValue() == eStateAttaching) {
3342 // Don't hijack and eat the eStateExited as the code that was doing
3343 // the attach will be waiting for this event...
3344 RestoreProcessEvents();
3345 SetExitStatus(SIGKILL, "Cancelled async attach.");
3350 // Wait for 10 second for the process to stop.
3351 StateType state = WaitForProcessToStop(
3352 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
3353 RestoreProcessEvents();
3355 if (state == eStateInvalid || !event_sp) {
3356 // We timed out and didn't get a stop event...
3357 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
3360 BroadcastEvent(event_sp);
3365 Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3368 // Check both the public & private states here. If we're hung evaluating an
3369 // expression, for instance, then
3370 // the public state will be stopped, but we still need to interrupt.
3371 if (m_public_state.GetValue() == eStateRunning ||
3372 m_private_state.GetValue() == eStateRunning) {
3373 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3375 log->Printf("Process::%s() About to stop.", __FUNCTION__);
3377 ListenerSP listener_sp(
3378 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3379 HijackProcessEvents(listener_sp);
3381 SendAsyncInterrupt();
3383 // Consume the interrupt event.
3385 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
3387 RestoreProcessEvents();
3389 // If the process exited while we were waiting for it to stop, put the
3390 // exited event into
3391 // the shared pointer passed in and return. Our caller doesn't need to do
3392 // anything else, since
3393 // they don't have a process anymore...
3395 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3397 log->Printf("Process::%s() Process exited while waiting to stop.",
3401 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3403 if (state != eStateStopped) {
3405 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__,
3406 StateAsCString(state));
3407 // If we really couldn't stop the process then we should just error out
3409 // lower levels just bobbled sending the event and we really are stopped,
3410 // then continue on.
3411 StateType private_state = m_private_state.GetValue();
3412 if (private_state != eStateStopped) {
3414 "Attempt to stop the target in order to detach timed out. "
3416 StateAsCString(GetState()));
3423 Status Process::Detach(bool keep_stopped) {
3424 EventSP exit_event_sp;
3426 m_destroy_in_process = true;
3428 error = WillDetach();
3430 if (error.Success()) {
3431 if (DetachRequiresHalt()) {
3432 error = StopForDestroyOrDetach(exit_event_sp);
3433 if (!error.Success()) {
3434 m_destroy_in_process = false;
3436 } else if (exit_event_sp) {
3437 // We shouldn't need to do anything else here. There's no process left
3438 // to detach from...
3439 StopPrivateStateThread();
3440 m_destroy_in_process = false;
3445 m_thread_list.DiscardThreadPlans();
3446 DisableAllBreakpointSites();
3448 error = DoDetach(keep_stopped);
3449 if (error.Success()) {
3451 StopPrivateStateThread();
3456 m_destroy_in_process = false;
3458 // If we exited when we were waiting for a process to stop, then
3459 // forward the event here so we don't lose the event
3460 if (exit_event_sp) {
3461 // Directly broadcast our exited event because we shut down our
3462 // private state thread above
3463 BroadcastEvent(exit_event_sp);
3466 // If we have been interrupted (to kill us) in the middle of running, we may
3467 // not end up propagating
3468 // the last events through the event system, in which case we might strand the
3469 // write lock. Unlock
3470 // it here so when we do to tear down the process we don't get an error
3471 // destroying the lock.
3473 m_public_run_lock.SetStopped();
3477 Status Process::Destroy(bool force_kill) {
3479 // Tell ourselves we are in the process of destroying the process, so that we
3480 // don't do any unnecessary work
3481 // that might hinder the destruction. Remember to set this back to false when
3482 // we are done. That way if the attempt
3483 // failed and the process stays around for some reason it won't be in a
3487 m_should_detach = false;
3489 if (GetShouldDetach()) {
3490 // FIXME: This will have to be a process setting:
3491 bool keep_stopped = false;
3492 Detach(keep_stopped);
3495 m_destroy_in_process = true;
3497 Status error(WillDestroy());
3498 if (error.Success()) {
3499 EventSP exit_event_sp;
3500 if (DestroyRequiresHalt()) {
3501 error = StopForDestroyOrDetach(exit_event_sp);
3504 if (m_public_state.GetValue() != eStateRunning) {
3505 // Ditch all thread plans, and remove all our breakpoints: in case we have
3506 // to restart the target to
3507 // kill it, we don't want it hitting a breakpoint...
3508 // Only do this if we've stopped, however, since if we didn't manage to
3509 // halt it above, then
3510 // we're not going to have much luck doing this now.
3511 m_thread_list.DiscardThreadPlans();
3512 DisableAllBreakpointSites();
3515 error = DoDestroy();
3516 if (error.Success()) {
3518 StopPrivateStateThread();
3520 m_stdio_communication.Disconnect();
3521 m_stdio_communication.StopReadThread();
3522 m_stdin_forward = false;
3524 if (m_process_input_reader) {
3525 m_process_input_reader->SetIsDone(true);
3526 m_process_input_reader->Cancel();
3527 m_process_input_reader.reset();
3530 // If we exited when we were waiting for a process to stop, then
3531 // forward the event here so we don't lose the event
3532 if (exit_event_sp) {
3533 // Directly broadcast our exited event because we shut down our
3534 // private state thread above
3535 BroadcastEvent(exit_event_sp);
3538 // If we have been interrupted (to kill us) in the middle of running, we may
3539 // not end up propagating
3540 // the last events through the event system, in which case we might strand
3541 // the write lock. Unlock
3542 // it here so when we do to tear down the process we don't get an error
3543 // destroying the lock.
3544 m_public_run_lock.SetStopped();
3547 m_destroy_in_process = false;
3552 Status Process::Signal(int signal) {
3553 Status error(WillSignal());
3554 if (error.Success()) {
3555 error = DoSignal(signal);
3556 if (error.Success())
3562 void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3563 assert(signals_sp && "null signals_sp");
3564 m_unix_signals_sp = signals_sp;
3567 const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3568 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3569 return m_unix_signals_sp;
3572 lldb::ByteOrder Process::GetByteOrder() const {
3573 return GetTarget().GetArchitecture().GetByteOrder();
3576 uint32_t Process::GetAddressByteSize() const {
3577 return GetTarget().GetArchitecture().GetAddressByteSize();
3580 bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3581 const StateType state =
3582 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3583 bool return_value = true;
3584 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3585 LIBLLDB_LOG_PROCESS));
3588 case eStateDetached:
3590 case eStateUnloaded:
3591 m_stdio_communication.SynchronizeWithReadThread();
3592 m_stdio_communication.Disconnect();
3593 m_stdio_communication.StopReadThread();
3594 m_stdin_forward = false;
3597 case eStateConnected:
3598 case eStateAttaching:
3599 case eStateLaunching:
3600 // These events indicate changes in the state of the debugging session,
3601 // always report them.
3602 return_value = true;
3605 // We stopped for no apparent reason, don't report it.
3606 return_value = false;
3609 case eStateStepping:
3610 // If we've started the target running, we handle the cases where we
3611 // are already running and where there is a transition from stopped to
3612 // running differently.
3613 // running -> running: Automatically suppress extra running events
3614 // stopped -> running: Report except when there is one or more no votes
3615 // and no yes votes.
3616 SynchronouslyNotifyStateChanged(state);
3617 if (m_force_next_event_delivery)
3618 return_value = true;
3620 switch (m_last_broadcast_state) {
3622 case eStateStepping:
3623 // We always suppress multiple runnings with no PUBLIC stop in between.
3624 return_value = false;
3627 // TODO: make this work correctly. For now always report
3628 // run if we aren't running so we don't miss any running
3629 // events. If I run the lldb/test/thread/a.out file and
3630 // break at main.cpp:58, run and hit the breakpoints on
3631 // multiple threads, then somehow during the stepping over
3632 // of all breakpoints no run gets reported.
3634 // This is a transition from stop to run.
3635 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3637 case eVoteNoOpinion:
3638 return_value = true;
3641 return_value = false;
3650 case eStateSuspended:
3651 // We've stopped. First see if we're going to restart the target.
3652 // If we are going to stop, then we always broadcast the event.
3653 // If we aren't going to stop, let the thread plans decide if we're going to
3654 // report this event.
3655 // If no thread has an opinion, we don't report it.
3657 m_stdio_communication.SynchronizeWithReadThread();
3658 RefreshStateAfterStop();
3659 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3661 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3662 "interrupt, state: %s",
3663 static_cast<void *>(event_ptr), StateAsCString(state));
3664 // Even though we know we are going to stop, we should let the threads
3665 // have a look at the stop,
3666 // so they can properly set their state.
3667 m_thread_list.ShouldStop(event_ptr);
3668 return_value = true;
3670 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3671 bool should_resume = false;
3673 // It makes no sense to ask "ShouldStop" if we've already been
3675 // Asking the thread list is also not likely to go well, since we are
3677 // So in that case just report the event.
3680 should_resume = !m_thread_list.ShouldStop(event_ptr);
3682 if (was_restarted || should_resume || m_resume_requested) {
3683 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3685 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3686 "%s was_restarted: %i stop_vote: %d.",
3687 should_resume, StateAsCString(state), was_restarted,
3690 switch (stop_vote) {
3692 return_value = true;
3694 case eVoteNoOpinion:
3696 return_value = false;
3700 if (!was_restarted) {
3702 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3704 static_cast<void *>(event_ptr), StateAsCString(state));
3705 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3709 return_value = true;
3710 SynchronouslyNotifyStateChanged(state);
3716 // Forcing the next event delivery is a one shot deal. So reset it here.
3717 m_force_next_event_delivery = false;
3719 // We do some coalescing of events (for instance two consecutive running
3720 // events get coalesced.)
3721 // But we only coalesce against events we actually broadcast. So we use
3722 // m_last_broadcast_state
3723 // to track that. NB - you can't use "m_public_state.GetValue()" for that
3724 // purpose, as was originally done,
3725 // because the PublicState reflects the last event pulled off the queue, and
3726 // there may be several
3727 // events stacked up on the queue unserviced. So the PublicState may not
3728 // reflect the last broadcasted event
3729 // yet. m_last_broadcast_state gets updated here.
3732 m_last_broadcast_state = state;
3735 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3736 "broadcast state: %s - %s",
3737 static_cast<void *>(event_ptr), StateAsCString(state),
3738 StateAsCString(m_last_broadcast_state),
3739 return_value ? "YES" : "NO");
3740 return return_value;
3743 bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3744 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3746 bool already_running = PrivateStateThreadIsValid();
3748 log->Printf("Process::%s()%s ", __FUNCTION__,
3749 already_running ? " already running"
3750 : " starting private state thread");
3752 if (!is_secondary_thread && already_running)
3755 // Create a thread that watches our internal state and controls which
3756 // events make it to clients (into the DCProcess event queue).
3757 char thread_name[1024];
3758 uint32_t max_len = llvm::get_max_thread_name_length();
3759 if (max_len > 0 && max_len <= 30) {
3760 // On platforms with abbreviated thread name lengths, choose thread names
3761 // that fit within the limit.
3762 if (already_running)
3763 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3765 snprintf(thread_name, sizeof(thread_name), "intern-state");
3767 if (already_running)
3768 snprintf(thread_name, sizeof(thread_name),
3769 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3772 snprintf(thread_name, sizeof(thread_name),
3773 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3776 // Create the private state thread, and start it running.
3777 PrivateStateThreadArgs *args_ptr =
3778 new PrivateStateThreadArgs(this, is_secondary_thread);
3779 m_private_state_thread =
3780 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3781 (void *)args_ptr, nullptr, 8 * 1024 * 1024);
3782 if (m_private_state_thread.IsJoinable()) {
3783 ResumePrivateStateThread();
3789 void Process::PausePrivateStateThread() {
3790 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3793 void Process::ResumePrivateStateThread() {
3794 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3797 void Process::StopPrivateStateThread() {
3798 if (m_private_state_thread.IsJoinable())
3799 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3801 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3804 "Went to stop the private state thread, but it was already invalid.");
3808 void Process::ControlPrivateStateThread(uint32_t signal) {
3809 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3811 assert(signal == eBroadcastInternalStateControlStop ||
3812 signal == eBroadcastInternalStateControlPause ||
3813 signal == eBroadcastInternalStateControlResume);
3816 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3818 // Signal the private state thread
3819 if (m_private_state_thread.IsJoinable()) {
3820 // Broadcast the event.
3821 // It is important to do this outside of the if below, because
3822 // it's possible that the thread state is invalid but that the
3823 // thread is waiting on a control event instead of simply being
3824 // on its way out (this should not happen, but it apparently can).
3826 log->Printf("Sending control event of type: %d.", signal);
3827 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3828 m_private_state_control_broadcaster.BroadcastEvent(signal,
3831 // Wait for the event receipt or for the private state thread to exit
3832 bool receipt_received = false;
3833 if (PrivateStateThreadIsValid()) {
3834 while (!receipt_received) {
3835 bool timed_out = false;
3836 // Check for a receipt for 2 seconds and then check if the private state
3837 // thread is still around.
3838 receipt_received = event_receipt_sp->WaitForEventReceived(
3839 std::chrono::seconds(2), &timed_out);
3840 if (!receipt_received) {
3841 // Check if the private state thread is still around. If it isn't then
3842 // we are done waiting
3843 if (!PrivateStateThreadIsValid())
3844 break; // Private state thread exited or is exiting, we are done
3849 if (signal == eBroadcastInternalStateControlStop) {
3850 thread_result_t result = NULL;
3851 m_private_state_thread.Join(&result);
3852 m_private_state_thread.Reset();
3857 "Private state thread already dead, no need to signal it to stop.");
3861 void Process::SendAsyncInterrupt() {
3862 if (PrivateStateThreadIsValid())
3863 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3866 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3869 void Process::HandlePrivateEvent(EventSP &event_sp) {
3870 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3871 m_resume_requested = false;
3873 const StateType new_state =
3874 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3876 // First check to see if anybody wants a shot at this event:
3877 if (m_next_event_action_ap) {
3878 NextEventAction::EventActionResult action_result =
3879 m_next_event_action_ap->PerformAction(event_sp);
3881 log->Printf("Ran next event action, result was %d.", action_result);
3883 switch (action_result) {
3884 case NextEventAction::eEventActionSuccess:
3885 SetNextEventAction(nullptr);
3888 case NextEventAction::eEventActionRetry:
3891 case NextEventAction::eEventActionExit:
3892 // Handle Exiting Here. If we already got an exited event,
3893 // we should just propagate it. Otherwise, swallow this event,
3894 // and set our state to exit so the next event will kill us.
3895 if (new_state != eStateExited) {
3896 // FIXME: should cons up an exited event, and discard this one.
3897 SetExitStatus(0, m_next_event_action_ap->GetExitString());
3898 SetNextEventAction(nullptr);
3901 SetNextEventAction(nullptr);
3906 // See if we should broadcast this state to external clients?
3907 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3909 if (should_broadcast) {
3910 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3912 log->Printf("Process::%s (pid = %" PRIu64
3913 ") broadcasting new state %s (old state %s) to %s",
3914 __FUNCTION__, GetID(), StateAsCString(new_state),
3915 StateAsCString(GetState()),
3916 is_hijacked ? "hijacked" : "public");
3918 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3919 if (StateIsRunningState(new_state)) {
3920 // Only push the input handler if we aren't fowarding events,
3921 // as this means the curses GUI is in use...
3922 // Or don't push it if we are launching since it will come up stopped.
3923 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3924 new_state != eStateLaunching && new_state != eStateAttaching) {
3925 PushProcessIOHandler();
3926 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3929 log->Printf("Process::%s updated m_iohandler_sync to %d",
3930 __FUNCTION__, m_iohandler_sync.GetValue());
3932 } else if (StateIsStoppedState(new_state, false)) {
3933 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
3934 // If the lldb_private::Debugger is handling the events, we don't
3935 // want to pop the process IOHandler here, we want to do it when
3936 // we receive the stopped event so we can carefully control when
3937 // the process IOHandler is popped because when we stop we want to
3938 // display some text stating how and why we stopped, then maybe some
3939 // process/thread/frame info, and then we want the "(lldb) " prompt
3940 // to show up. If we pop the process IOHandler here, then we will
3941 // cause the command interpreter to become the top IOHandler after
3942 // the process pops off and it will update its prompt right away...
3943 // See the Debugger.cpp file where it calls the function as
3944 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3945 // Otherwise we end up getting overlapping "(lldb) " prompts and
3948 // If we aren't handling the events in the debugger (which is indicated
3949 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
3950 // are hijacked, then we always pop the process IO handler manually.
3951 // Hijacking happens when the internal process state thread is running
3952 // thread plans, or when commands want to run in synchronous mode
3953 // and they call "process->WaitForProcessToStop()". An example of
3955 // that will hijack the events is a simple expression:
3957 // (lldb) expr (int)puts("hello")
3959 // This will cause the internal process state thread to resume and halt
3960 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3961 // events) and we do need the IO handler to be pushed and popped
3964 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3965 PopProcessIOHandler();
3969 BroadcastEvent(event_sp);
3973 "Process::%s (pid = %" PRIu64
3974 ") suppressing state %s (old state %s): should_broadcast == false",
3975 __FUNCTION__, GetID(), StateAsCString(new_state),
3976 StateAsCString(GetState()));
3981 Status Process::HaltPrivate() {
3983 Status error(WillHalt());
3987 // Ask the process subclass to actually halt our process
3989 error = DoHalt(caused_stop);
3995 thread_result_t Process::PrivateStateThread(void *arg) {
3996 std::unique_ptr<PrivateStateThreadArgs> args_up(
3997 static_cast<PrivateStateThreadArgs *>(arg));
3998 thread_result_t result =
3999 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
4003 thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
4004 bool control_only = true;
4006 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4008 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4009 __FUNCTION__, static_cast<void *>(this), GetID());
4011 bool exit_now = false;
4012 bool interrupt_requested = false;
4015 GetEventsPrivate(event_sp, llvm::None, control_only);
4016 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
4018 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4019 ") got a control event: %d",
4020 __FUNCTION__, static_cast<void *>(this), GetID(),
4021 event_sp->GetType());
4023 switch (event_sp->GetType()) {
4024 case eBroadcastInternalStateControlStop:
4026 break; // doing any internal state management below
4028 case eBroadcastInternalStateControlPause:
4029 control_only = true;
4032 case eBroadcastInternalStateControlResume:
4033 control_only = false;
4038 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
4039 if (m_public_state.GetValue() == eStateAttaching) {
4041 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4042 ") woke up with an interrupt while attaching - "
4043 "forwarding interrupt.",
4044 __FUNCTION__, static_cast<void *>(this), GetID());
4045 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
4046 } else if (StateIsRunningState(m_last_broadcast_state)) {
4048 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4049 ") woke up with an interrupt - Halting.",
4050 __FUNCTION__, static_cast<void *>(this), GetID());
4051 Status error = HaltPrivate();
4052 if (error.Fail() && log)
4053 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4054 ") failed to halt the process: %s",
4055 __FUNCTION__, static_cast<void *>(this), GetID(),
4057 // Halt should generate a stopped event. Make a note of the fact that we
4059 // doing the interrupt, so we can set the interrupted flag after we
4061 // event. We deliberately set this to true even if HaltPrivate failed,
4063 // can interrupt on the next natural stop.
4064 interrupt_requested = true;
4066 // This can happen when someone (e.g. Process::Halt) sees that we are
4068 // sends an interrupt request, but the process actually stops before we
4070 // it. In that case, we can just ignore the request. We use
4071 // m_last_broadcast_state, because the Stopped event may not have been
4073 // the event queue yet, which is when the public state gets updated.
4076 "Process::%s ignoring interrupt as we have already stopped.",
4082 const StateType internal_state =
4083 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4085 if (internal_state != eStateInvalid) {
4086 if (m_clear_thread_plans_on_stop &&
4087 StateIsStoppedState(internal_state, true)) {
4088 m_clear_thread_plans_on_stop = false;
4089 m_thread_list.DiscardThreadPlans();
4092 if (interrupt_requested) {
4093 if (StateIsStoppedState(internal_state, true)) {
4094 // We requested the interrupt, so mark this as such in the stop event
4096 // clients can tell an interrupted process from a natural stop
4097 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
4098 interrupt_requested = false;
4100 log->Printf("Process::%s interrupt_requested, but a non-stopped "
4101 "state '%s' received.",
4102 __FUNCTION__, StateAsCString(internal_state));
4106 HandlePrivateEvent(event_sp);
4109 if (internal_state == eStateInvalid || internal_state == eStateExited ||
4110 internal_state == eStateDetached) {
4112 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4113 ") about to exit with internal state %s...",
4114 __FUNCTION__, static_cast<void *>(this), GetID(),
4115 StateAsCString(internal_state));
4121 // Verify log is still enabled before attempting to write to it...
4123 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4124 __FUNCTION__, static_cast<void *>(this), GetID());
4126 // If we are a secondary thread, then the primary thread we are working for
4127 // will have already
4128 // acquired the public_run_lock, and isn't done with what it was doing yet, so
4130 // try to change it on the way out.
4131 if (!is_secondary_thread)
4132 m_public_run_lock.SetStopped();
4136 //------------------------------------------------------------------
4137 // Process Event Data
4138 //------------------------------------------------------------------
4140 Process::ProcessEventData::ProcessEventData()
4141 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
4142 m_update_state(0), m_interrupted(false) {}
4144 Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
4146 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
4147 m_update_state(0), m_interrupted(false) {
4149 m_process_wp = process_sp;
4152 Process::ProcessEventData::~ProcessEventData() = default;
4154 const ConstString &Process::ProcessEventData::GetFlavorString() {
4155 static ConstString g_flavor("Process::ProcessEventData");
4159 const ConstString &Process::ProcessEventData::GetFlavor() const {
4160 return ProcessEventData::GetFlavorString();
4163 void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
4164 ProcessSP process_sp(m_process_wp.lock());
4169 // This function gets called twice for each event, once when the event gets
4171 // off of the private process event queue, and then any number of times, first
4172 // when it gets pulled off of
4173 // the public event queue, then other times when we're pretending that this is
4174 // where we stopped at the
4175 // end of expression evaluation. m_update_state is used to distinguish these
4176 // three cases; it is 0 when we're just pulling it off for private handling,
4177 // and > 1 for expression evaluation, and we don't want to do the breakpoint
4178 // command handling then.
4179 if (m_update_state != 1)
4182 process_sp->SetPublicState(
4183 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4185 if (m_state == eStateStopped && !m_restarted) {
4186 // Let process subclasses know we are about to do a public stop and
4187 // do anything they might need to in order to speed up register and
4189 process_sp->WillPublicStop();
4192 // If this is a halt event, even if the halt stopped with some reason other
4193 // than a plain interrupt (e.g. we had
4194 // already stopped for a breakpoint when the halt request came through) don't
4195 // do the StopInfo actions, as they may
4196 // end up restarting the process.
4200 // If we're stopped and haven't restarted, then do the StopInfo actions here:
4201 if (m_state == eStateStopped && !m_restarted) {
4202 ThreadList &curr_thread_list = process_sp->GetThreadList();
4203 uint32_t num_threads = curr_thread_list.GetSize();
4206 // The actions might change one of the thread's stop_info's opinions about
4207 // whether we should
4208 // stop the process, so we need to query that as we go.
4210 // One other complication here, is that we try to catch any case where the
4211 // target has run (except for expressions)
4212 // and immediately exit, but if we get that wrong (which is possible) then
4213 // the thread list might have changed, and
4214 // that would cause our iteration here to crash. We could make a copy of
4215 // the thread list, but we'd really like
4216 // to also know if it has changed at all, so we make up a vector of the
4217 // thread ID's and check what we get back
4218 // against this list & bag out if anything differs.
4219 std::vector<uint32_t> thread_index_array(num_threads);
4220 for (idx = 0; idx < num_threads; ++idx)
4221 thread_index_array[idx] =
4222 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4224 // Use this to track whether we should continue from here. We will only
4225 // continue the target running if
4226 // no thread says we should stop. Of course if some thread's PerformAction
4227 // actually sets the target running,
4228 // then it doesn't matter what the other threads say...
4230 bool still_should_stop = false;
4232 // Sometimes - for instance if we have a bug in the stub we are talking to,
4233 // we stop but no thread has a
4234 // valid stop reason. In that case we should just stop, because we have no
4235 // way of telling what the right
4236 // thing to do is, and it's better to let the user decide than continue
4237 // behind their backs.
4239 bool does_anybody_have_an_opinion = false;
4241 for (idx = 0; idx < num_threads; ++idx) {
4242 curr_thread_list = process_sp->GetThreadList();
4243 if (curr_thread_list.GetSize() != num_threads) {
4244 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4245 LIBLLDB_LOG_PROCESS));
4248 "Number of threads changed from %u to %u while processing event.",
4249 num_threads, curr_thread_list.GetSize());
4253 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4255 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4256 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4257 LIBLLDB_LOG_PROCESS));
4259 log->Printf("The thread at position %u changed from %u to %u while "
4260 "processing event.",
4261 idx, thread_index_array[idx], thread_sp->GetIndexID());
4265 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4266 if (stop_info_sp && stop_info_sp->IsValid()) {
4267 does_anybody_have_an_opinion = true;
4268 bool this_thread_wants_to_stop;
4269 if (stop_info_sp->GetOverrideShouldStop()) {
4270 this_thread_wants_to_stop =
4271 stop_info_sp->GetOverriddenShouldStopValue();
4273 stop_info_sp->PerformAction(event_ptr);
4274 // The stop action might restart the target. If it does, then we want
4275 // to mark that in the
4276 // event so that whoever is receiving it will know to wait for the
4277 // running event and reflect
4278 // that state appropriately.
4279 // We also need to stop processing actions, since they aren't
4280 // expecting the target to be running.
4282 // FIXME: we might have run.
4283 if (stop_info_sp->HasTargetRunSinceMe()) {
4288 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4291 if (!still_should_stop)
4292 still_should_stop = this_thread_wants_to_stop;
4296 if (!GetRestarted()) {
4297 if (!still_should_stop && does_anybody_have_an_opinion) {
4298 // We've been asked to continue, so do that here.
4300 // Use the public resume method here, since this is just
4301 // extending a public resume.
4302 process_sp->PrivateResume();
4304 // If we didn't restart, run the Stop Hooks here:
4305 // They might also restart the target, so watch for that.
4306 process_sp->GetTarget().RunStopHooks();
4307 if (process_sp->GetPrivateState() == eStateRunning)
4314 void Process::ProcessEventData::Dump(Stream *s) const {
4315 ProcessSP process_sp(m_process_wp.lock());
4318 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4319 static_cast<void *>(process_sp.get()), process_sp->GetID());
4321 s->PutCString(" process = NULL, ");
4323 s->Printf("state = %s", StateAsCString(GetState()));
4326 const Process::ProcessEventData *
4327 Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4329 const EventData *event_data = event_ptr->GetData();
4331 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4332 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4338 Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4339 ProcessSP process_sp;
4340 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4342 process_sp = data->GetProcessSP();
4346 StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4347 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4348 if (data == nullptr)
4349 return eStateInvalid;
4351 return data->GetState();
4354 bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4355 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4356 if (data == nullptr)
4359 return data->GetRestarted();
4362 void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4364 ProcessEventData *data =
4365 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4366 if (data != nullptr)
4367 data->SetRestarted(new_value);
4371 Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4372 ProcessEventData *data =
4373 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4374 if (data != nullptr)
4375 return data->GetNumRestartedReasons();
4381 Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4383 ProcessEventData *data =
4384 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4385 if (data != nullptr)
4386 return data->GetRestartedReasonAtIndex(idx);
4391 void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4392 const char *reason) {
4393 ProcessEventData *data =
4394 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4395 if (data != nullptr)
4396 data->AddRestartedReason(reason);
4399 bool Process::ProcessEventData::GetInterruptedFromEvent(
4400 const Event *event_ptr) {
4401 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4402 if (data == nullptr)
4405 return data->GetInterrupted();
4408 void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4410 ProcessEventData *data =
4411 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4412 if (data != nullptr)
4413 data->SetInterrupted(new_value);
4416 bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4417 ProcessEventData *data =
4418 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4420 data->SetUpdateStateOnRemoval();
4426 lldb::TargetSP Process::CalculateTarget() { return m_target_sp.lock(); }
4428 void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4429 exe_ctx.SetTargetPtr(&GetTarget());
4430 exe_ctx.SetProcessPtr(this);
4431 exe_ctx.SetThreadPtr(nullptr);
4432 exe_ctx.SetFramePtr(nullptr);
4436 // Process::ListProcessesMatchingName (const char *name, StringList &matches,
4437 // std::vector<lldb::pid_t> &pids)
4443 // Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4445 // return Host::GetArchSpecForExistingProcess (pid);
4449 // Process::GetArchSpecForExistingProcess (const char *process_name)
4451 // return Host::GetArchSpecForExistingProcess (process_name);
4454 void Process::AppendSTDOUT(const char *s, size_t len) {
4455 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4456 m_stdout_data.append(s, len);
4457 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4458 new ProcessEventData(shared_from_this(), GetState()));
4461 void Process::AppendSTDERR(const char *s, size_t len) {
4462 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4463 m_stderr_data.append(s, len);
4464 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4465 new ProcessEventData(shared_from_this(), GetState()));
4468 void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4469 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4470 m_profile_data.push_back(one_profile_data);
4471 BroadcastEventIfUnique(eBroadcastBitProfileData,
4472 new ProcessEventData(shared_from_this(), GetState()));
4475 void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4476 const StructuredDataPluginSP &plugin_sp) {
4478 eBroadcastBitStructuredData,
4479 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
4482 StructuredDataPluginSP
4483 Process::GetStructuredDataPlugin(const ConstString &type_name) const {
4484 auto find_it = m_structured_data_plugin_map.find(type_name);
4485 if (find_it != m_structured_data_plugin_map.end())
4486 return find_it->second;
4488 return StructuredDataPluginSP();
4491 size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
4492 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4493 if (m_profile_data.empty())
4496 std::string &one_profile_data = m_profile_data.front();
4497 size_t bytes_available = one_profile_data.size();
4498 if (bytes_available > 0) {
4499 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4501 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4502 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4503 if (bytes_available > buf_size) {
4504 memcpy(buf, one_profile_data.c_str(), buf_size);
4505 one_profile_data.erase(0, buf_size);
4506 bytes_available = buf_size;
4508 memcpy(buf, one_profile_data.c_str(), bytes_available);
4509 m_profile_data.erase(m_profile_data.begin());
4512 return bytes_available;
4515 //------------------------------------------------------------------
4517 //------------------------------------------------------------------
4519 size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
4520 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4521 size_t bytes_available = m_stdout_data.size();
4522 if (bytes_available > 0) {
4523 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4525 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4526 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4527 if (bytes_available > buf_size) {
4528 memcpy(buf, m_stdout_data.c_str(), buf_size);
4529 m_stdout_data.erase(0, buf_size);
4530 bytes_available = buf_size;
4532 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4533 m_stdout_data.clear();
4536 return bytes_available;
4539 size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
4540 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4541 size_t bytes_available = m_stderr_data.size();
4542 if (bytes_available > 0) {
4543 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4545 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4546 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4547 if (bytes_available > buf_size) {
4548 memcpy(buf, m_stderr_data.c_str(), buf_size);
4549 m_stderr_data.erase(0, buf_size);
4550 bytes_available = buf_size;
4552 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4553 m_stderr_data.clear();
4556 return bytes_available;
4559 void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4561 Process *process = (Process *)baton;
4562 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
4565 class IOHandlerProcessSTDIO : public IOHandler {
4567 IOHandlerProcessSTDIO(Process *process, int write_fd)
4568 : IOHandler(process->GetTarget().GetDebugger(),
4569 IOHandler::Type::ProcessIO),
4570 m_process(process), m_write_file(write_fd, false) {
4571 m_pipe.CreateNew(false);
4572 m_read_file.SetDescriptor(GetInputFD(), false);
4575 ~IOHandlerProcessSTDIO() override = default;
4577 // Each IOHandler gets to run until it is done. It should read data
4578 // from the "in" and place output into "out" and "err and return
4580 void Run() override {
4581 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4582 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4588 const int read_fd = m_read_file.GetDescriptor();
4589 TerminalState terminal_state;
4590 terminal_state.Save(read_fd, false);
4591 Terminal terminal(read_fd);
4592 terminal.SetCanonical(false);
4593 terminal.SetEcho(false);
4594 // FD_ZERO, FD_SET are not supported on windows
4596 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4597 m_is_running = true;
4598 while (!GetIsDone()) {
4599 SelectHelper select_helper;
4600 select_helper.FDSetRead(read_fd);
4601 select_helper.FDSetRead(pipe_read_fd);
4602 Status error = select_helper.Select();
4609 if (select_helper.FDIsSetRead(read_fd)) {
4611 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4612 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4617 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4619 // Consume the interrupt byte
4620 Status error = m_pipe.Read(&ch, 1, bytes_read);
4621 if (error.Success()) {
4627 if (StateIsRunningState(m_process->GetState()))
4628 m_process->SendAsyncInterrupt();
4635 m_is_running = false;
4637 terminal_state.Restore();
4640 void Cancel() override {
4642 // Only write to our pipe to cancel if we are in
4643 // IOHandlerProcessSTDIO::Run().
4644 // We can end up with a python command that is being run from the command
4647 // (lldb) step_process_thousands_of_times
4649 // In this case the command interpreter will be in the middle of handling
4650 // the command and if the process pushes and pops the IOHandler thousands
4651 // of times, we can end up writing to m_pipe without ever consuming the
4652 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4653 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4655 char ch = 'q'; // Send 'q' for quit
4656 size_t bytes_written = 0;
4657 m_pipe.Write(&ch, 1, bytes_written);
4661 bool Interrupt() override {
4662 // Do only things that are safe to do in an interrupt context (like in
4663 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4664 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4665 // that was written to the pipe and then call
4666 // m_process->SendAsyncInterrupt()
4667 // from a much safer location in code.
4669 char ch = 'i'; // Send 'i' for interrupt
4670 size_t bytes_written = 0;
4671 Status result = m_pipe.Write(&ch, 1, bytes_written);
4672 return result.Success();
4674 // This IOHandler might be pushed on the stack, but not being run
4676 // so do the right thing if we aren't actively watching for STDIN by
4678 // the interrupt to the process. Otherwise the write to the pipe above
4680 // do nothing. This can happen when the command interpreter is running and
4681 // gets a "expression ...". It will be on the IOHandler thread and sending
4682 // the input is complete to the delegate which will cause the expression
4684 // run, which will push the process IO handler, but not run it.
4686 if (StateIsRunningState(m_process->GetState())) {
4687 m_process->SendAsyncInterrupt();
4694 void GotEOF() override {}
4698 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4699 File m_write_file; // Write to this file (usually the master pty for getting
4702 std::atomic<bool> m_is_running{false};
4705 void Process::SetSTDIOFileDescriptor(int fd) {
4706 // First set up the Read Thread for reading/handling process I/O
4708 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
4709 new ConnectionFileDescriptor(fd, true));
4712 m_stdio_communication.SetConnection(conn_ap.release());
4713 if (m_stdio_communication.IsConnected()) {
4714 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4715 STDIOReadThreadBytesReceived, this);
4716 m_stdio_communication.StartReadThread();
4718 // Now read thread is set up, set up input reader.
4720 if (!m_process_input_reader)
4721 m_process_input_reader.reset(new IOHandlerProcessSTDIO(this, fd));
4726 bool Process::ProcessIOHandlerIsActive() {
4727 IOHandlerSP io_handler_sp(m_process_input_reader);
4729 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4732 bool Process::PushProcessIOHandler() {
4733 IOHandlerSP io_handler_sp(m_process_input_reader);
4734 if (io_handler_sp) {
4735 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4737 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
4739 io_handler_sp->SetIsDone(false);
4740 GetTarget().GetDebugger().PushIOHandler(io_handler_sp);
4746 bool Process::PopProcessIOHandler() {
4747 IOHandlerSP io_handler_sp(m_process_input_reader);
4749 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4753 // The process needs to know about installed plug-ins
4754 void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
4756 void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
4759 // RestorePlanState is used to record the "is private", "is master" and "okay to
4760 // discard" fields of
4761 // the plan we are running, and reset it on Clean or on destruction.
4762 // It will only reset the state once, so you can call Clean and then monkey with
4764 // won't get reset on you again.
4766 class RestorePlanState {
4768 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4769 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4770 if (m_thread_plan_sp) {
4771 m_private = m_thread_plan_sp->GetPrivate();
4772 m_is_master = m_thread_plan_sp->IsMasterPlan();
4773 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4777 ~RestorePlanState() { Clean(); }
4780 if (!m_already_reset && m_thread_plan_sp) {
4781 m_already_reset = true;
4782 m_thread_plan_sp->SetPrivate(m_private);
4783 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4784 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4789 lldb::ThreadPlanSP m_thread_plan_sp;
4790 bool m_already_reset;
4793 bool m_okay_to_discard;
4795 } // anonymous namespace
4798 GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4799 const milliseconds default_one_thread_timeout(250);
4801 // If the overall wait is forever, then we don't need to worry about it.
4802 if (!options.GetTimeout()) {
4803 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4804 : default_one_thread_timeout;
4807 // If the one thread timeout is set, use it.
4808 if (options.GetOneThreadTimeout())
4809 return *options.GetOneThreadTimeout();
4811 // Otherwise use half the total timeout, bounded by the
4812 // default_one_thread_timeout.
4813 return std::min<microseconds>(default_one_thread_timeout,
4814 *options.GetTimeout() / 2);
4817 static Timeout<std::micro>
4818 GetExpressionTimeout(const EvaluateExpressionOptions &options,
4819 bool before_first_timeout) {
4820 // If we are going to run all threads the whole time, or if we are only
4821 // going to run one thread, we can just return the overall timeout.
4822 if (!options.GetStopOthers() || !options.GetTryAllThreads())
4823 return options.GetTimeout();
4825 if (before_first_timeout)
4826 return GetOneThreadExpressionTimeout(options);
4828 if (!options.GetTimeout())
4831 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
4834 static llvm::Optional<ExpressionResults>
4835 HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
4836 RestorePlanState &restorer, const EventSP &event_sp,
4837 EventSP &event_to_broadcast_sp,
4838 const EvaluateExpressionOptions &options, bool handle_interrupts) {
4839 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4841 ThreadPlanSP plan = thread.GetCompletedPlan();
4842 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4843 LLDB_LOG(log, "execution completed successfully");
4845 // Restore the plan state so it will get reported as intended when we are
4848 return eExpressionCompleted;
4851 StopInfoSP stop_info_sp = thread.GetStopInfo();
4852 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4853 stop_info_sp->ShouldNotify(event_sp.get())) {
4854 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4855 if (!options.DoesIgnoreBreakpoints()) {
4856 // Restore the plan state and then force Private to false. We are going
4857 // to stop because of this plan so we need it to become a public plan or
4858 // it won't report correctly when we continue to its termination later on.
4860 thread_plan_sp->SetPrivate(false);
4861 event_to_broadcast_sp = event_sp;
4863 return eExpressionHitBreakpoint;
4866 if (!handle_interrupts &&
4867 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4870 LLDB_LOG(log, "thread plan did not successfully complete");
4871 if (!options.DoesUnwindOnError())
4872 event_to_broadcast_sp = event_sp;
4873 return eExpressionInterrupted;
4877 Process::RunThreadPlan(ExecutionContext &exe_ctx,
4878 lldb::ThreadPlanSP &thread_plan_sp,
4879 const EvaluateExpressionOptions &options,
4880 DiagnosticManager &diagnostic_manager) {
4881 ExpressionResults return_value = eExpressionSetupError;
4883 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4885 if (!thread_plan_sp) {
4886 diagnostic_manager.PutString(
4887 eDiagnosticSeverityError,
4888 "RunThreadPlan called with empty thread plan.");
4889 return eExpressionSetupError;
4892 if (!thread_plan_sp->ValidatePlan(nullptr)) {
4893 diagnostic_manager.PutString(
4894 eDiagnosticSeverityError,
4895 "RunThreadPlan called with an invalid thread plan.");
4896 return eExpressionSetupError;
4899 if (exe_ctx.GetProcessPtr() != this) {
4900 diagnostic_manager.PutString(eDiagnosticSeverityError,
4901 "RunThreadPlan called on wrong process.");
4902 return eExpressionSetupError;
4905 Thread *thread = exe_ctx.GetThreadPtr();
4906 if (thread == nullptr) {
4907 diagnostic_manager.PutString(eDiagnosticSeverityError,
4908 "RunThreadPlan called with invalid thread.");
4909 return eExpressionSetupError;
4912 // We need to change some of the thread plan attributes for the thread plan
4913 // runner. This will restore them
4914 // when we are done:
4916 RestorePlanState thread_plan_restorer(thread_plan_sp);
4918 // We rely on the thread plan we are running returning "PlanCompleted" if when
4919 // it successfully completes.
4920 // For that to be true the plan can't be private - since private plans
4921 // suppress themselves in the
4922 // GetCompletedPlan call.
4924 thread_plan_sp->SetPrivate(false);
4926 // The plans run with RunThreadPlan also need to be terminal master plans or
4927 // when they are done we will end
4928 // up asking the plan above us whether we should stop, which may give the
4931 thread_plan_sp->SetIsMasterPlan(true);
4932 thread_plan_sp->SetOkayToDiscard(false);
4934 if (m_private_state.GetValue() != eStateStopped) {
4935 diagnostic_manager.PutString(
4936 eDiagnosticSeverityError,
4937 "RunThreadPlan called while the private state was not stopped.");
4938 return eExpressionSetupError;
4941 // Save the thread & frame from the exe_ctx for restoration after we run
4942 const uint32_t thread_idx_id = thread->GetIndexID();
4943 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4944 if (!selected_frame_sp) {
4945 thread->SetSelectedFrame(nullptr);
4946 selected_frame_sp = thread->GetSelectedFrame();
4947 if (!selected_frame_sp) {
4948 diagnostic_manager.Printf(
4949 eDiagnosticSeverityError,
4950 "RunThreadPlan called without a selected frame on thread %d",
4952 return eExpressionSetupError;
4956 // Make sure the timeout values make sense. The one thread timeout needs to be
4957 // smaller than the overall timeout.
4958 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4959 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
4960 diagnostic_manager.PutString(eDiagnosticSeverityError,
4961 "RunThreadPlan called with one thread "
4962 "timeout greater than total timeout");
4963 return eExpressionSetupError;
4966 StackID ctx_frame_id = selected_frame_sp->GetStackID();
4968 // N.B. Running the target may unset the currently selected thread and frame.
4969 // We don't want to do that either,
4970 // so we should arrange to reset them as well.
4972 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
4974 uint32_t selected_tid;
4975 StackID selected_stack_id;
4976 if (selected_thread_sp) {
4977 selected_tid = selected_thread_sp->GetIndexID();
4978 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4980 selected_tid = LLDB_INVALID_THREAD_ID;
4983 HostThread backup_private_state_thread;
4984 lldb::StateType old_state = eStateInvalid;
4985 lldb::ThreadPlanSP stopper_base_plan_sp;
4987 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4988 LIBLLDB_LOG_PROCESS));
4989 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4990 // Yikes, we are running on the private state thread! So we can't wait for
4991 // public events on this thread, since
4992 // we are the thread that is generating public events.
4993 // The simplest thing to do is to spin up a temporary thread to handle
4994 // private state thread events while
4995 // we are fielding public events here.
4997 log->Printf("Running thread plan on private state thread, spinning up "
4998 "another state thread to handle the events.");
5000 backup_private_state_thread = m_private_state_thread;
5002 // One other bit of business: we want to run just this thread plan and
5003 // anything it pushes, and then stop,
5004 // returning control here.
5005 // But in the normal course of things, the plan above us on the stack would
5006 // be given a shot at the stop
5007 // event before deciding to stop, and we don't want that. So we insert a
5008 // "stopper" base plan on the stack
5009 // before the plan we want to run. Since base plans always stop and return
5010 // control to the user, that will
5011 // do just what we want.
5012 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
5013 thread->QueueThreadPlan(stopper_base_plan_sp, false);
5014 // Have to make sure our public state is stopped, since otherwise the
5015 // reporting logic below doesn't work correctly.
5016 old_state = m_public_state.GetValue();
5017 m_public_state.SetValueNoLock(eStateStopped);
5019 // Now spin up the private state thread:
5020 StartPrivateStateThread(true);
5023 thread->QueueThreadPlan(
5024 thread_plan_sp, false); // This used to pass "true" does that make sense?
5026 if (options.GetDebug()) {
5027 // In this case, we aren't actually going to run, we just want to stop right
5029 // Flush this thread so we will refetch the stacks and show the correct
5031 // FIXME: To make this prettier we should invent some stop reason for this,
5033 // is only cosmetic, and this functionality is only of use to lldb
5034 // developers who can
5035 // live with not pretty...
5037 return eExpressionStoppedForDebug;
5040 ListenerSP listener_sp(
5041 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
5043 lldb::EventSP event_to_broadcast_sp;
5046 // This process event hijacker Hijacks the Public events and its destructor
5047 // makes sure that the process events get
5048 // restored on exit to the function.
5050 // If the event needs to propagate beyond the hijacker (e.g., the process
5051 // exits during execution), then the event
5052 // is put into event_to_broadcast_sp for rebroadcasting.
5054 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
5058 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
5059 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
5060 " to run thread plan \"%s\".",
5061 thread->GetIndexID(), thread->GetID(), s.GetData());
5065 lldb::EventSP event_sp;
5066 lldb::StateType stop_state = lldb::eStateInvalid;
5068 bool before_first_timeout = true; // This is set to false the first time
5069 // that we have to halt the target.
5070 bool do_resume = true;
5071 bool handle_running_event = true;
5073 // This is just for accounting:
5074 uint32_t num_resumes = 0;
5076 // If we are going to run all threads the whole time, or if we are only
5077 // going to run one thread, then we don't need the first timeout. So we
5078 // pretend we are after the first timeout already.
5079 if (!options.GetStopOthers() || !options.GetTryAllThreads())
5080 before_first_timeout = false;
5083 log->Printf("Stop others: %u, try all: %u, before_first: %u.\n",
5084 options.GetStopOthers(), options.GetTryAllThreads(),
5085 before_first_timeout);
5087 // This isn't going to work if there are unfetched events on the queue.
5088 // Are there cases where we might want to run the remaining events here, and
5090 // call the function? That's probably being too tricky for our own good.
5092 Event *other_events = listener_sp->PeekAtNextEvent();
5093 if (other_events != nullptr) {
5094 diagnostic_manager.PutString(
5095 eDiagnosticSeverityError,
5096 "RunThreadPlan called with pending events on the queue.");
5097 return eExpressionSetupError;
5100 // We also need to make sure that the next event is delivered. We might be
5101 // calling a function as part of
5102 // a thread plan, in which case the last delivered event could be the
5103 // running event, and we don't want
5104 // event coalescing to cause us to lose OUR running event...
5105 ForceNextEventDelivery();
5107 // This while loop must exit out the bottom, there's cleanup that we need to do
5108 // when we are done.
5109 // So don't call return anywhere within it.
5111 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5112 // It's pretty much impossible to write test cases for things like:
5113 // One thread timeout expires, I go to halt, but the process already stopped
5114 // on the function call stop breakpoint. Turning on this define will make
5116 // fetch the first event till after the halt. So if you run a quick
5117 // function, it will have
5118 // completed, and the completion event will be waiting, when you interrupt
5120 // The expression evaluation should still succeed.
5121 bool miss_first_event = true;
5124 // We usually want to resume the process if we get to the top of the loop.
5125 // The only exception is if we get two running events with no intervening
5126 // stop, which can happen, we will just wait for then next stop event.
5128 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
5129 "before_first_timeout: %i.",
5130 do_resume, handle_running_event, before_first_timeout);
5132 if (do_resume || handle_running_event) {
5133 // Do the initial resume and wait for the running event before going
5138 Status resume_error = PrivateResume();
5139 if (!resume_error.Success()) {
5140 diagnostic_manager.Printf(
5141 eDiagnosticSeverityError,
5142 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5143 resume_error.AsCString());
5144 return_value = eExpressionSetupError;
5150 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
5153 log->Printf("Process::RunThreadPlan(): didn't get any event after "
5154 "resume %" PRIu32 ", exiting.",
5157 diagnostic_manager.Printf(eDiagnosticSeverityError,
5158 "didn't get any event after resume %" PRIu32
5161 return_value = eExpressionSetupError;
5166 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5168 if (stop_state != eStateRunning) {
5169 bool restarted = false;
5171 if (stop_state == eStateStopped) {
5172 restarted = Process::ProcessEventData::GetRestartedFromEvent(
5176 "Process::RunThreadPlan(): didn't get running event after "
5177 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5178 "handle_running_event: %i).",
5179 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5180 handle_running_event);
5184 // This is probably an overabundance of caution, I don't think I
5185 // should ever get a stopped & restarted
5186 // event here. But if I do, the best thing is to Halt and then get
5188 const bool clear_thread_plans = false;
5189 const bool use_run_lock = false;
5190 Halt(clear_thread_plans, use_run_lock);
5193 diagnostic_manager.Printf(
5194 eDiagnosticSeverityError,
5195 "didn't get running event after initial resume, got %s instead.",
5196 StateAsCString(stop_state));
5197 return_value = eExpressionSetupError;
5202 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
5203 // We need to call the function synchronously, so spin waiting for it to
5205 // If we get interrupted while executing, we're going to lose our
5207 // won't be able to gather the result at this point.
5208 // We set the timeout AFTER the resume, since the resume takes some time
5210 // don't want to charge that to the timeout.
5213 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5217 handle_running_event = true;
5219 // Now wait for the process to stop again:
5222 Timeout<std::micro> timeout =
5223 GetExpressionTimeout(options, before_first_timeout);
5226 auto now = system_clock::now();
5227 log->Printf("Process::RunThreadPlan(): about to wait - now is %s - "
5229 llvm::to_string(now).c_str(),
5230 llvm::to_string(now + *timeout).c_str());
5232 log->Printf("Process::RunThreadPlan(): about to wait forever.");
5236 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5237 // See comment above...
5238 if (miss_first_event) {
5240 miss_first_event = false;
5244 got_event = listener_sp->GetEvent(event_sp, timeout);
5248 bool keep_going = false;
5249 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5250 const bool clear_thread_plans = false;
5251 const bool use_run_lock = false;
5252 Halt(clear_thread_plans, use_run_lock);
5253 return_value = eExpressionInterrupted;
5254 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5255 "execution halted by user interrupt.");
5257 log->Printf("Process::RunThreadPlan(): Got interrupted by "
5258 "eBroadcastBitInterrupted, exiting.");
5262 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5265 "Process::RunThreadPlan(): in while loop, got event: %s.",
5266 StateAsCString(stop_state));
5268 switch (stop_state) {
5269 case lldb::eStateStopped: {
5270 // We stopped, figure out what we are going to do now.
5271 ThreadSP thread_sp =
5272 GetThreadList().FindThreadByIndexID(thread_idx_id);
5274 // Ooh, our thread has vanished. Unlikely that this was
5275 // successful execution...
5277 log->Printf("Process::RunThreadPlan(): execution completed "
5278 "but our thread (index-id=%u) has vanished.",
5280 return_value = eExpressionInterrupted;
5281 } else if (Process::ProcessEventData::GetRestartedFromEvent(
5283 // If we were restarted, we just need to go back up to fetch
5286 log->Printf("Process::RunThreadPlan(): Got a stop and "
5287 "restart, so we'll continue waiting.");
5291 handle_running_event = true;
5293 const bool handle_interrupts = true;
5294 return_value = *HandleStoppedEvent(
5295 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5296 event_to_broadcast_sp, options, handle_interrupts);
5300 case lldb::eStateRunning:
5301 // This shouldn't really happen, but sometimes we do get two
5302 // running events without an
5303 // intervening stop, and in that case we should just go back to
5304 // waiting for the stop.
5307 handle_running_event = false;
5312 log->Printf("Process::RunThreadPlan(): execution stopped with "
5313 "unexpected state: %s.",
5314 StateAsCString(stop_state));
5316 if (stop_state == eStateExited)
5317 event_to_broadcast_sp = event_sp;
5319 diagnostic_manager.PutString(
5320 eDiagnosticSeverityError,
5321 "execution stopped with unexpected state.");
5322 return_value = eExpressionInterrupted;
5333 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5334 "the event pointer was null. How odd...");
5335 return_value = eExpressionInterrupted;
5339 // If we didn't get an event that means we've timed out...
5340 // We will interrupt the process here. Depending on what we were asked
5342 // either exit, or try with all threads running for the same timeout.
5345 if (options.GetTryAllThreads()) {
5346 if (before_first_timeout) {
5348 "Running function with one thread timeout timed out.");
5350 LLDB_LOG(log, "Restarting function with all threads enabled and "
5351 "timeout: {0} timed out, abandoning execution.",
5354 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5355 "abandoning execution.",
5359 // It is possible that between the time we issued the Halt, and we get
5360 // around to calling Halt the target
5361 // could have stopped. That's fine, Halt will figure that out and send
5362 // the appropriate Stopped event.
5363 // BUT it is also possible that we stopped & restarted (e.g. hit a
5364 // signal with "stop" set to false.) In
5365 // that case, we'll get the stopped & restarted event, and we should go
5366 // back to waiting for the Halt's
5367 // stopped event. That's what this while loop does.
5369 bool back_to_top = true;
5370 uint32_t try_halt_again = 0;
5371 bool do_halt = true;
5372 const uint32_t num_retries = 5;
5373 while (try_halt_again < num_retries) {
5377 log->Printf("Process::RunThreadPlan(): Running Halt.");
5378 const bool clear_thread_plans = false;
5379 const bool use_run_lock = false;
5380 Halt(clear_thread_plans, use_run_lock);
5382 if (halt_error.Success()) {
5384 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5387 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
5391 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5393 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5394 StateAsCString(stop_state));
5395 if (stop_state == lldb::eStateStopped &&
5396 Process::ProcessEventData::GetInterruptedFromEvent(
5398 log->PutCString(" Event was the Halt interruption event.");
5401 if (stop_state == lldb::eStateStopped) {
5402 if (Process::ProcessEventData::GetRestartedFromEvent(
5405 log->PutCString("Process::RunThreadPlan(): Went to halt "
5406 "but got a restarted event, there must be "
5407 "an un-restarted stopped event so try "
5409 "Exiting wait loop.");
5415 // Between the time we initiated the Halt and the time we
5416 // delivered it, the process could have
5417 // already finished its job. Check that here:
5418 const bool handle_interrupts = false;
5419 if (auto result = HandleStoppedEvent(
5420 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5421 event_to_broadcast_sp, options, handle_interrupts)) {
5422 return_value = *result;
5423 back_to_top = false;
5427 if (!options.GetTryAllThreads()) {
5429 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5430 "was false, we stopped so now we're "
5432 return_value = eExpressionInterrupted;
5433 back_to_top = false;
5437 if (before_first_timeout) {
5438 // Set all the other threads to run, and return to the top of
5439 // the loop, which will continue;
5440 before_first_timeout = false;
5441 thread_plan_sp->SetStopOthers(false);
5444 "Process::RunThreadPlan(): about to resume.");
5449 // Running all threads failed, so return Interrupted.
5451 log->PutCString("Process::RunThreadPlan(): running all "
5452 "threads timed out.");
5453 return_value = eExpressionInterrupted;
5454 back_to_top = false;
5460 log->PutCString("Process::RunThreadPlan(): halt said it "
5461 "succeeded, but I got no event. "
5462 "I'm getting out of here passing Interrupted.");
5463 return_value = eExpressionInterrupted;
5464 back_to_top = false;
5473 if (!back_to_top || try_halt_again > num_retries)
5480 // If we had to start up a temporary private state thread to run this thread
5481 // plan, shut it down now.
5482 if (backup_private_state_thread.IsJoinable()) {
5483 StopPrivateStateThread();
5485 m_private_state_thread = backup_private_state_thread;
5486 if (stopper_base_plan_sp) {
5487 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5489 if (old_state != eStateInvalid)
5490 m_public_state.SetValueNoLock(old_state);
5493 if (return_value != eExpressionCompleted && log) {
5494 // Print a backtrace into the log so we can figure out where we are:
5496 s.PutCString("Thread state after unsuccessful completion: \n");
5497 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
5498 log->PutString(s.GetString());
5500 // Restore the thread state if we are going to discard the plan execution.
5501 // There are three cases where this
5503 // 1) The execution successfully completed
5504 // 2) We hit a breakpoint, and ignore_breakpoints was true
5505 // 3) We got some other error, and discard_on_error was true
5506 bool should_unwind = (return_value == eExpressionInterrupted &&
5507 options.DoesUnwindOnError()) ||
5508 (return_value == eExpressionHitBreakpoint &&
5509 options.DoesIgnoreBreakpoints());
5511 if (return_value == eExpressionCompleted || should_unwind) {
5512 thread_plan_sp->RestoreThreadState();
5515 // Now do some processing on the results of the run:
5516 if (return_value == eExpressionInterrupted ||
5517 return_value == eExpressionHitBreakpoint) {
5523 log->PutCString("Process::RunThreadPlan(): Stop event that "
5524 "interrupted us is NULL.");
5529 const char *event_explanation = nullptr;
5533 event_explanation = "<no event>";
5535 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5536 event_explanation = "<user interrupt>";
5539 const Process::ProcessEventData *event_data =
5540 Process::ProcessEventData::GetEventDataFromEvent(
5544 event_explanation = "<no event data>";
5548 Process *process = event_data->GetProcessSP().get();
5551 event_explanation = "<no process>";
5555 ThreadList &thread_list = process->GetThreadList();
5557 uint32_t num_threads = thread_list.GetSize();
5558 uint32_t thread_index;
5560 ts.Printf("<%u threads> ", num_threads);
5562 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5563 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5570 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5571 RegisterContext *register_context =
5572 thread->GetRegisterContext().get();
5574 if (register_context)
5575 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5577 ts.Printf("[ip unknown] ");
5579 // Show the private stop info here, the public stop info will be
5580 // from the last natural stop.
5581 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5583 const char *stop_desc = stop_info_sp->GetDescription();
5585 ts.PutCString(stop_desc);
5590 event_explanation = ts.GetData();
5594 if (event_explanation)
5595 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5596 s.GetData(), event_explanation);
5598 log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5602 if (should_unwind) {
5604 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5605 "discarding thread plans up to %p.",
5606 static_cast<void *>(thread_plan_sp.get()));
5607 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5610 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5611 "plan: %p not discarding.",
5612 static_cast<void *>(thread_plan_sp.get()));
5614 } else if (return_value == eExpressionSetupError) {
5616 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5618 if (options.DoesUnwindOnError()) {
5619 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5622 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5624 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5625 return_value = eExpressionCompleted;
5626 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5629 "Process::RunThreadPlan(): thread plan was discarded");
5630 return_value = eExpressionDiscarded;
5634 "Process::RunThreadPlan(): thread plan stopped in mid course");
5635 if (options.DoesUnwindOnError() && thread_plan_sp) {
5637 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5638 "'cause unwind_on_error is set.");
5639 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5644 // Thread we ran the function in may have gone away because we ran the
5646 // Check that it's still there, and if it is put it back in the context.
5648 // frame in the context if it is still present.
5649 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5651 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5654 // Also restore the current process'es selected frame & thread, since this
5655 // function calling may
5656 // be done behind the user's back.
5658 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5659 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5660 selected_stack_id.IsValid()) {
5661 // We were able to restore the selected thread, now restore the frame:
5662 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5663 StackFrameSP old_frame_sp =
5664 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5667 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5668 old_frame_sp.get());
5673 // If the process exited during the run of the thread plan, notify everyone.
5675 if (event_to_broadcast_sp) {
5677 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5678 BroadcastEvent(event_to_broadcast_sp);
5681 return return_value;
5684 const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5685 const char *result_name;
5688 case eExpressionCompleted:
5689 result_name = "eExpressionCompleted";
5691 case eExpressionDiscarded:
5692 result_name = "eExpressionDiscarded";
5694 case eExpressionInterrupted:
5695 result_name = "eExpressionInterrupted";
5697 case eExpressionHitBreakpoint:
5698 result_name = "eExpressionHitBreakpoint";
5700 case eExpressionSetupError:
5701 result_name = "eExpressionSetupError";
5703 case eExpressionParseError:
5704 result_name = "eExpressionParseError";
5706 case eExpressionResultUnavailable:
5707 result_name = "eExpressionResultUnavailable";
5709 case eExpressionTimedOut:
5710 result_name = "eExpressionTimedOut";
5712 case eExpressionStoppedForDebug:
5713 result_name = "eExpressionStoppedForDebug";
5719 void Process::GetStatus(Stream &strm) {
5720 const StateType state = GetState();
5721 if (StateIsStoppedState(state, false)) {
5722 if (state == eStateExited) {
5723 int exit_status = GetExitStatus();
5724 const char *exit_description = GetExitDescription();
5725 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5726 GetID(), exit_status, exit_status,
5727 exit_description ? exit_description : "");
5729 if (state == eStateConnected)
5730 strm.Printf("Connected to remote target.\n");
5732 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5735 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5739 size_t Process::GetThreadStatus(Stream &strm,
5740 bool only_threads_with_stop_reason,
5741 uint32_t start_frame, uint32_t num_frames,
5742 uint32_t num_frames_with_source,
5744 size_t num_thread_infos_dumped = 0;
5746 // You can't hold the thread list lock while calling Thread::GetStatus. That
5747 // very well might run code (e.g. if we need it
5748 // to get return values or arguments.) For that to work the process has to be
5749 // able to acquire it. So instead copy the thread
5750 // ID's, and look them up one by one:
5752 uint32_t num_threads;
5753 std::vector<lldb::tid_t> thread_id_array;
5754 // Scope for thread list locker;
5756 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5757 ThreadList &curr_thread_list = GetThreadList();
5758 num_threads = curr_thread_list.GetSize();
5760 thread_id_array.resize(num_threads);
5761 for (idx = 0; idx < num_threads; ++idx)
5762 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5765 for (uint32_t i = 0; i < num_threads; i++) {
5766 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5768 if (only_threads_with_stop_reason) {
5769 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5770 if (!stop_info_sp || !stop_info_sp->IsValid())
5773 thread_sp->GetStatus(strm, start_frame, num_frames,
5774 num_frames_with_source,
5776 ++num_thread_infos_dumped;
5778 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5780 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5781 " vanished while running Thread::GetStatus.");
5784 return num_thread_infos_dumped;
5787 void Process::AddInvalidMemoryRegion(const LoadRange ®ion) {
5788 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5791 bool Process::RemoveInvalidMemoryRange(const LoadRange ®ion) {
5792 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5793 region.GetByteSize());
5796 void Process::AddPreResumeAction(PreResumeActionCallback callback,
5798 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5801 bool Process::RunPreResumeActions() {
5803 while (!m_pre_resume_actions.empty()) {
5804 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5805 m_pre_resume_actions.pop_back();
5806 bool this_result = action.callback(action.baton);
5808 result = this_result;
5813 void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5815 void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5817 PreResumeCallbackAndBaton element(callback, baton);
5818 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5819 if (found_iter != m_pre_resume_actions.end())
5821 m_pre_resume_actions.erase(found_iter);
5825 ProcessRunLock &Process::GetRunLock() {
5826 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5827 return m_private_run_lock;
5829 return m_public_run_lock;
5832 void Process::Flush() {
5833 m_thread_list.Flush();
5834 m_extended_thread_list.Flush();
5835 m_extended_thread_stop_id = 0;
5836 m_queue_list.Clear();
5837 m_queue_list_stop_id = 0;
5840 void Process::DidExec() {
5841 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5843 log->Printf("Process::%s()", __FUNCTION__);
5845 Target &target = GetTarget();
5846 target.CleanupProcess();
5847 target.ClearModules(false);
5848 m_dynamic_checkers_ap.reset();
5850 m_system_runtime_ap.reset();
5853 m_jit_loaders_ap.reset();
5854 m_image_tokens.clear();
5855 m_allocated_memory_cache.Clear();
5856 m_language_runtimes.clear();
5857 m_instrumentation_runtimes.clear();
5858 m_thread_list.DiscardThreadPlans();
5859 m_memory_cache.Clear(true);
5862 // Flush the process (threads and all stack frames) after running
5864 // in case the dynamic loader loaded things in new locations.
5867 // After we figure out what was loaded/unloaded in CompleteAttach,
5868 // we need to let the target know so it can do any cleanup it needs to.
5872 addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
5873 if (address == nullptr) {
5874 error.SetErrorString("Invalid address argument");
5875 return LLDB_INVALID_ADDRESS;
5878 addr_t function_addr = LLDB_INVALID_ADDRESS;
5880 addr_t addr = address->GetLoadAddress(&GetTarget());
5881 std::map<addr_t, addr_t>::const_iterator iter =
5882 m_resolved_indirect_addresses.find(addr);
5883 if (iter != m_resolved_indirect_addresses.end()) {
5884 function_addr = (*iter).second;
5886 if (!InferiorCall(this, address, function_addr)) {
5887 Symbol *symbol = address->CalculateSymbolContextSymbol();
5888 error.SetErrorStringWithFormat(
5889 "Unable to call resolver for indirect function %s",
5890 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5891 function_addr = LLDB_INVALID_ADDRESS;
5893 m_resolved_indirect_addresses.insert(
5894 std::pair<addr_t, addr_t>(addr, function_addr));
5897 return function_addr;
5900 void Process::ModulesDidLoad(ModuleList &module_list) {
5901 SystemRuntime *sys_runtime = GetSystemRuntime();
5903 sys_runtime->ModulesDidLoad(module_list);
5906 GetJITLoaders().ModulesDidLoad(module_list);
5908 // Give runtimes a chance to be created.
5909 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5910 m_instrumentation_runtimes);
5912 // Tell runtimes about new modules.
5913 for (auto pos = m_instrumentation_runtimes.begin();
5914 pos != m_instrumentation_runtimes.end(); ++pos) {
5915 InstrumentationRuntimeSP runtime = pos->second;
5916 runtime->ModulesDidLoad(module_list);
5919 // Let any language runtimes we have already created know
5920 // about the modules that loaded.
5922 // Iterate over a copy of this language runtime list in case
5923 // the language runtime ModulesDidLoad somehow causes the language
5924 // riuntime to be unloaded.
5925 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5926 for (const auto &pair : language_runtimes) {
5927 // We must check language_runtime_sp to make sure it is not
5928 // nullptr as we might cache the fact that we didn't have a
5929 // language runtime for a language.
5930 LanguageRuntimeSP language_runtime_sp = pair.second;
5931 if (language_runtime_sp)
5932 language_runtime_sp->ModulesDidLoad(module_list);
5935 // If we don't have an operating system plug-in, try to load one since
5936 // loading shared libraries might cause a new one to try and load
5938 LoadOperatingSystemPlugin(false);
5940 // Give structured-data plugins a chance to see the modified modules.
5941 for (auto pair : m_structured_data_plugin_map) {
5943 pair.second->ModulesDidLoad(*this, module_list);
5947 void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5948 const char *fmt, ...) {
5949 bool print_warning = true;
5951 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5954 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5958 if (repeat_key != nullptr) {
5959 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5960 if (it == m_warnings_issued.end()) {
5961 m_warnings_issued[warning_type] = WarningsPointerSet();
5962 m_warnings_issued[warning_type].insert(repeat_key);
5964 if (it->second.find(repeat_key) != it->second.end()) {
5965 print_warning = false;
5967 it->second.insert(repeat_key);
5972 if (print_warning) {
5974 va_start(args, fmt);
5975 stream_sp->PrintfVarArg(fmt, args);
5980 void Process::PrintWarningOptimization(const SymbolContext &sc) {
5981 if (GetWarningsOptimization() && sc.module_sp &&
5982 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5983 sc.function->GetIsOptimized()) {
5984 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5985 "%s was compiled with optimization - stepping may behave "
5986 "oddly; variables may not be available.\n",
5987 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5991 bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5994 PlatformSP platform_sp = GetTarget().GetPlatform();
5998 return platform_sp->GetProcessInfo(GetID(), info);
6001 ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
6002 ThreadCollectionSP threads;
6004 const MemoryHistorySP &memory_history =
6005 MemoryHistory::FindPlugin(shared_from_this());
6007 if (!memory_history) {
6011 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6016 InstrumentationRuntimeSP
6017 Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
6018 InstrumentationRuntimeCollection::iterator pos;
6019 pos = m_instrumentation_runtimes.find(type);
6020 if (pos == m_instrumentation_runtimes.end()) {
6021 return InstrumentationRuntimeSP();
6023 return (*pos).second;
6026 bool Process::GetModuleSpec(const FileSpec &module_file_spec,
6027 const ArchSpec &arch, ModuleSpec &module_spec) {
6028 module_spec.Clear();
6032 size_t Process::AddImageToken(lldb::addr_t image_ptr) {
6033 m_image_tokens.push_back(image_ptr);
6034 return m_image_tokens.size() - 1;
6037 lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
6038 if (token < m_image_tokens.size())
6039 return m_image_tokens[token];
6040 return LLDB_INVALID_IMAGE_TOKEN;
6043 void Process::ResetImageToken(size_t token) {
6044 if (token < m_image_tokens.size())
6045 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
6049 Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
6050 AddressRange range_bounds) {
6051 Target &target = GetTarget();
6052 DisassemblerSP disassembler_sp;
6053 InstructionList *insn_list = nullptr;
6055 Address retval = default_stop_addr;
6057 if (!target.GetUseFastStepping())
6059 if (!default_stop_addr.IsValid())
6062 ExecutionContext exe_ctx(this);
6063 const char *plugin_name = nullptr;
6064 const char *flavor = nullptr;
6065 const bool prefer_file_cache = true;
6066 disassembler_sp = Disassembler::DisassembleRange(
6067 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
6069 if (disassembler_sp)
6070 insn_list = &disassembler_sp->GetInstructionList();
6072 if (insn_list == nullptr) {
6076 size_t insn_offset =
6077 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
6078 if (insn_offset == UINT32_MAX) {
6082 uint32_t branch_index =
6083 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target);
6084 if (branch_index == UINT32_MAX) {
6088 if (branch_index > insn_offset) {
6089 Address next_branch_insn_address =
6090 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
6091 if (next_branch_insn_address.IsValid() &&
6092 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
6093 retval = next_branch_insn_address;
6101 Process::GetMemoryRegions(std::vector<lldb::MemoryRegionInfoSP> ®ion_list) {
6105 lldb::addr_t range_end = 0;
6107 region_list.clear();
6109 lldb::MemoryRegionInfoSP region_info(new lldb_private::MemoryRegionInfo());
6110 error = GetMemoryRegionInfo(range_end, *region_info);
6111 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6113 region_list.clear();
6117 range_end = region_info->GetRange().GetRangeEnd();
6118 if (region_info->GetMapped() == MemoryRegionInfo::eYes) {
6119 region_list.push_back(region_info);
6121 } while (range_end != LLDB_INVALID_ADDRESS);
6127 Process::ConfigureStructuredData(const ConstString &type_name,
6128 const StructuredData::ObjectSP &config_sp) {
6129 // If you get this, the Process-derived class needs to implement a method
6130 // to enable an already-reported asynchronous structured data feature.
6131 // See ProcessGDBRemote for an example implementation over gdb-remote.
6132 return Status("unimplemented");
6135 void Process::MapSupportedStructuredDataPlugins(
6136 const StructuredData::Array &supported_type_names) {
6137 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
6139 // Bail out early if there are no type names to map.
6140 if (supported_type_names.GetSize() == 0) {
6142 log->Printf("Process::%s(): no structured data types supported",
6147 // Convert StructuredData type names to ConstString instances.
6148 std::set<ConstString> const_type_names;
6151 log->Printf("Process::%s(): the process supports the following async "
6152 "structured data types:",
6155 supported_type_names.ForEach(
6156 [&const_type_names, &log](StructuredData::Object *object) {
6158 // Invalid - shouldn't be null objects in the array.
6162 auto type_name = object->GetAsString();
6164 // Invalid format - all type names should be strings.
6168 const_type_names.insert(ConstString(type_name->GetValue()));
6169 LLDB_LOG(log, "- {0}", type_name->GetValue());
6173 // For each StructuredDataPlugin, if the plugin handles any of the
6174 // types in the supported_type_names, map that type name to that plugin.
6175 uint32_t plugin_index = 0;
6176 for (auto create_instance =
6177 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
6179 create_instance && !const_type_names.empty(); ++plugin_index) {
6180 // Create the plugin.
6181 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
6183 // This plugin doesn't think it can work with the process.
6184 // Move on to the next.
6188 // For any of the remaining type names, map any that this plugin
6190 std::vector<ConstString> names_to_remove;
6191 for (auto &type_name : const_type_names) {
6192 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6193 m_structured_data_plugin_map.insert(
6194 std::make_pair(type_name, plugin_sp));
6195 names_to_remove.push_back(type_name);
6197 log->Printf("Process::%s(): using plugin %s for type name "
6199 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
6200 type_name.GetCString());
6204 // Remove the type names that were consumed by this plugin.
6205 for (auto &type_name : names_to_remove)
6206 const_type_names.erase(type_name);
6210 bool Process::RouteAsyncStructuredData(
6211 const StructuredData::ObjectSP object_sp) {
6212 // Nothing to do if there's no data.
6216 // The contract is this must be a dictionary, so we can look up the
6217 // routing key via the top-level 'type' string value within the dictionary.
6218 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6222 // Grab the async structured type name (i.e. the feature/plugin name).
6223 ConstString type_name;
6224 if (!dictionary->GetValueForKeyAsString("type", type_name))
6227 // Check if there's a plugin registered for this type name.
6228 auto find_it = m_structured_data_plugin_map.find(type_name);
6229 if (find_it == m_structured_data_plugin_map.end()) {
6230 // We don't have a mapping for this structured data type.
6234 // Route the structured data to the plugin.
6235 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6239 Status Process::UpdateAutomaticSignalFiltering() {
6240 // Default implementation does nothign.
6241 // No automatic signal filtering to speak of.