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"
18 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
19 #include "lldb/Breakpoint/BreakpointLocation.h"
20 #include "lldb/Breakpoint/StoppointCallbackContext.h"
21 #include "lldb/Core/Debugger.h"
22 #include "lldb/Core/Event.h"
23 #include "lldb/Core/Log.h"
24 #include "lldb/Core/Module.h"
25 #include "lldb/Core/ModuleSpec.h"
26 #include "lldb/Core/PluginManager.h"
27 #include "lldb/Core/State.h"
28 #include "lldb/Core/StreamFile.h"
29 #include "lldb/Expression/DiagnosticManager.h"
30 #include "lldb/Expression/IRDynamicChecks.h"
31 #include "lldb/Expression/UserExpression.h"
32 #include "lldb/Host/ConnectionFileDescriptor.h"
33 #include "lldb/Host/FileSystem.h"
34 #include "lldb/Host/Host.h"
35 #include "lldb/Host/HostInfo.h"
36 #include "lldb/Host/Pipe.h"
37 #include "lldb/Host/Terminal.h"
38 #include "lldb/Host/ThreadLauncher.h"
39 #include "lldb/Interpreter/CommandInterpreter.h"
40 #include "lldb/Interpreter/OptionValueProperties.h"
41 #include "lldb/Symbol/Function.h"
42 #include "lldb/Symbol/Symbol.h"
43 #include "lldb/Target/ABI.h"
44 #include "lldb/Target/CPPLanguageRuntime.h"
45 #include "lldb/Target/DynamicLoader.h"
46 #include "lldb/Target/InstrumentationRuntime.h"
47 #include "lldb/Target/JITLoader.h"
48 #include "lldb/Target/JITLoaderList.h"
49 #include "lldb/Target/LanguageRuntime.h"
50 #include "lldb/Target/MemoryHistory.h"
51 #include "lldb/Target/MemoryRegionInfo.h"
52 #include "lldb/Target/ObjCLanguageRuntime.h"
53 #include "lldb/Target/OperatingSystem.h"
54 #include "lldb/Target/Platform.h"
55 #include "lldb/Target/Process.h"
56 #include "lldb/Target/RegisterContext.h"
57 #include "lldb/Target/StopInfo.h"
58 #include "lldb/Target/StructuredDataPlugin.h"
59 #include "lldb/Target/SystemRuntime.h"
60 #include "lldb/Target/Target.h"
61 #include "lldb/Target/TargetList.h"
62 #include "lldb/Target/Thread.h"
63 #include "lldb/Target/ThreadPlan.h"
64 #include "lldb/Target/ThreadPlanBase.h"
65 #include "lldb/Target/UnixSignals.h"
66 #include "lldb/Utility/NameMatches.h"
67 #include "lldb/Utility/SelectHelper.h"
70 using namespace lldb_private;
71 using namespace std::chrono;
73 // Comment out line below to disable memory caching, overriding the process
74 // setting target.process.disable-memory-cache
75 #define ENABLE_MEMORY_CACHING
77 #ifdef ENABLE_MEMORY_CACHING
78 #define DISABLE_MEM_CACHE_DEFAULT false
80 #define DISABLE_MEM_CACHE_DEFAULT true
83 class ProcessOptionValueProperties : public OptionValueProperties {
85 ProcessOptionValueProperties(const ConstString &name)
86 : OptionValueProperties(name) {}
88 // This constructor is used when creating ProcessOptionValueProperties when it
89 // is part of a new lldb_private::Process instance. It will copy all current
90 // global property values as needed
91 ProcessOptionValueProperties(ProcessProperties *global_properties)
92 : OptionValueProperties(*global_properties->GetValueProperties()) {}
94 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
96 uint32_t idx) const override {
97 // When getting the value for a key from the process options, we will always
98 // try and grab the setting from the current process if there is one. Else
100 // use the one from this instance.
102 Process *process = exe_ctx->GetProcessPtr();
104 ProcessOptionValueProperties *instance_properties =
105 static_cast<ProcessOptionValueProperties *>(
106 process->GetValueProperties().get());
107 if (this != instance_properties)
108 return instance_properties->ProtectedGetPropertyAtIndex(idx);
111 return ProtectedGetPropertyAtIndex(idx);
115 static PropertyDefinition g_properties[] = {
116 {"disable-memory-cache", OptionValue::eTypeBoolean, false,
117 DISABLE_MEM_CACHE_DEFAULT, nullptr, nullptr,
118 "Disable reading and caching of memory in fixed-size units."},
119 {"extra-startup-command", OptionValue::eTypeArray, false,
120 OptionValue::eTypeString, nullptr, nullptr,
121 "A list containing extra commands understood by the particular process "
123 "For instance, to turn on debugserver logging set this to "
124 "\"QSetLogging:bitmask=LOG_DEFAULT;\""},
125 {"ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true,
127 "If true, breakpoints will be ignored during expression evaluation."},
128 {"unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true,
129 nullptr, nullptr, "If true, errors in expression evaluation will unwind "
130 "the stack back to the state before the call."},
131 {"python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, nullptr,
132 nullptr, "A path to a python OS plug-in module file that contains a "
133 "OperatingSystemPlugIn class."},
134 {"stop-on-sharedlibrary-events", OptionValue::eTypeBoolean, true, false,
136 "If true, stop when a shared library is loaded or unloaded."},
137 {"detach-keeps-stopped", OptionValue::eTypeBoolean, true, false, nullptr,
138 nullptr, "If true, detach will attempt to keep the process stopped."},
139 {"memory-cache-line-size", OptionValue::eTypeUInt64, false, 512, nullptr,
140 nullptr, "The memory cache line size"},
141 {"optimization-warnings", OptionValue::eTypeBoolean, false, true, nullptr,
142 nullptr, "If true, warn when stopped in code that is optimized where "
143 "stepping and variable availability may not behave as expected."},
144 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
147 ePropertyDisableMemCache,
148 ePropertyExtraStartCommand,
149 ePropertyIgnoreBreakpointsInExpressions,
150 ePropertyUnwindOnErrorInExpressions,
151 ePropertyPythonOSPluginPath,
152 ePropertyStopOnSharedLibraryEvents,
153 ePropertyDetachKeepsStopped,
154 ePropertyMemCacheLineSize,
155 ePropertyWarningOptimization
158 ProcessProperties::ProcessProperties(lldb_private::Process *process)
160 m_process(process) // Can be nullptr for global ProcessProperties
162 if (process == nullptr) {
163 // Global process properties, set them up one time
164 m_collection_sp.reset(
165 new ProcessOptionValueProperties(ConstString("process")));
166 m_collection_sp->Initialize(g_properties);
167 m_collection_sp->AppendProperty(
168 ConstString("thread"), ConstString("Settings specific to threads."),
169 true, Thread::GetGlobalProperties()->GetValueProperties());
171 m_collection_sp.reset(
172 new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
173 m_collection_sp->SetValueChangedCallback(
174 ePropertyPythonOSPluginPath,
175 ProcessProperties::OptionValueChangedCallback, this);
179 ProcessProperties::~ProcessProperties() = default;
181 void ProcessProperties::OptionValueChangedCallback(void *baton,
182 OptionValue *option_value) {
183 ProcessProperties *properties = (ProcessProperties *)baton;
184 if (properties->m_process)
185 properties->m_process->LoadOperatingSystemPlugin(true);
188 bool ProcessProperties::GetDisableMemoryCache() const {
189 const uint32_t idx = ePropertyDisableMemCache;
190 return m_collection_sp->GetPropertyAtIndexAsBoolean(
191 nullptr, idx, g_properties[idx].default_uint_value != 0);
194 uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
195 const uint32_t idx = ePropertyMemCacheLineSize;
196 return m_collection_sp->GetPropertyAtIndexAsUInt64(
197 nullptr, idx, g_properties[idx].default_uint_value);
200 Args ProcessProperties::GetExtraStartupCommands() const {
202 const uint32_t idx = ePropertyExtraStartCommand;
203 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
207 void ProcessProperties::SetExtraStartupCommands(const Args &args) {
208 const uint32_t idx = ePropertyExtraStartCommand;
209 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
212 FileSpec ProcessProperties::GetPythonOSPluginPath() const {
213 const uint32_t idx = ePropertyPythonOSPluginPath;
214 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
217 void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
218 const uint32_t idx = ePropertyPythonOSPluginPath;
219 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
222 bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
223 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
224 return m_collection_sp->GetPropertyAtIndexAsBoolean(
225 nullptr, idx, g_properties[idx].default_uint_value != 0);
228 void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
229 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
230 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
233 bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
234 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
235 return m_collection_sp->GetPropertyAtIndexAsBoolean(
236 nullptr, idx, g_properties[idx].default_uint_value != 0);
239 void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
240 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
241 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
244 bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
245 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
246 return m_collection_sp->GetPropertyAtIndexAsBoolean(
247 nullptr, idx, g_properties[idx].default_uint_value != 0);
250 void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
251 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
252 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
255 bool ProcessProperties::GetDetachKeepsStopped() const {
256 const uint32_t idx = ePropertyDetachKeepsStopped;
257 return m_collection_sp->GetPropertyAtIndexAsBoolean(
258 nullptr, idx, g_properties[idx].default_uint_value != 0);
261 void ProcessProperties::SetDetachKeepsStopped(bool stop) {
262 const uint32_t idx = ePropertyDetachKeepsStopped;
263 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
266 bool ProcessProperties::GetWarningsOptimization() const {
267 const uint32_t idx = ePropertyWarningOptimization;
268 return m_collection_sp->GetPropertyAtIndexAsBoolean(
269 nullptr, idx, g_properties[idx].default_uint_value != 0);
272 void ProcessInstanceInfo::Dump(Stream &s, Platform *platform) const {
274 if (m_pid != LLDB_INVALID_PROCESS_ID)
275 s.Printf(" pid = %" PRIu64 "\n", m_pid);
277 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
278 s.Printf(" parent = %" PRIu64 "\n", m_parent_pid);
281 s.Printf(" name = %s\n", m_executable.GetFilename().GetCString());
282 s.PutCString(" file = ");
283 m_executable.Dump(&s);
286 const uint32_t argc = m_arguments.GetArgumentCount();
288 for (uint32_t i = 0; i < argc; i++) {
289 const char *arg = m_arguments.GetArgumentAtIndex(i);
291 s.Printf(" arg[%u] = %s\n", i, arg);
293 s.Printf("arg[%u] = %s\n", i, arg);
297 const uint32_t envc = m_environment.GetArgumentCount();
299 for (uint32_t i = 0; i < envc; i++) {
300 const char *env = m_environment.GetArgumentAtIndex(i);
302 s.Printf(" env[%u] = %s\n", i, env);
304 s.Printf("env[%u] = %s\n", i, env);
308 if (m_arch.IsValid()) {
309 s.Printf(" arch = ");
310 m_arch.DumpTriple(s);
314 if (m_uid != UINT32_MAX) {
315 cstr = platform->GetUserName(m_uid);
316 s.Printf(" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
318 if (m_gid != UINT32_MAX) {
319 cstr = platform->GetGroupName(m_gid);
320 s.Printf(" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
322 if (m_euid != UINT32_MAX) {
323 cstr = platform->GetUserName(m_euid);
324 s.Printf(" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
326 if (m_egid != UINT32_MAX) {
327 cstr = platform->GetGroupName(m_egid);
328 s.Printf(" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
332 void ProcessInstanceInfo::DumpTableHeader(Stream &s, Platform *platform,
333 bool show_args, bool verbose) {
335 if (show_args || verbose)
341 s.Printf("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE "
344 s.PutCString("====== ====== ========== ========== ========== ========== "
345 "======================== ============================\n");
347 s.Printf("PID PARENT USER TRIPLE %s\n", label);
348 s.PutCString("====== ====== ========== ======================== "
349 "============================\n");
353 void ProcessInstanceInfo::DumpAsTableRow(Stream &s, Platform *platform,
354 bool show_args, bool verbose) const {
355 if (m_pid != LLDB_INVALID_PROCESS_ID) {
357 s.Printf("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
359 StreamString arch_strm;
360 if (m_arch.IsValid())
361 m_arch.DumpTriple(arch_strm);
364 cstr = platform->GetUserName(m_uid);
366 cstr[0]) // Watch for empty string that indicates lookup failed
367 s.Printf("%-10s ", cstr);
369 s.Printf("%-10u ", m_uid);
371 cstr = platform->GetGroupName(m_gid);
373 cstr[0]) // Watch for empty string that indicates lookup failed
374 s.Printf("%-10s ", cstr);
376 s.Printf("%-10u ", m_gid);
378 cstr = platform->GetUserName(m_euid);
380 cstr[0]) // Watch for empty string that indicates lookup failed
381 s.Printf("%-10s ", cstr);
383 s.Printf("%-10u ", m_euid);
385 cstr = platform->GetGroupName(m_egid);
387 cstr[0]) // Watch for empty string that indicates lookup failed
388 s.Printf("%-10s ", cstr);
390 s.Printf("%-10u ", m_egid);
392 s.Printf("%-24s ", arch_strm.GetData());
394 s.Printf("%-10s %-24s ", platform->GetUserName(m_euid),
395 arch_strm.GetData());
398 if (verbose || show_args) {
399 const uint32_t argc = m_arguments.GetArgumentCount();
401 for (uint32_t i = 0; i < argc; i++) {
404 s.PutCString(m_arguments.GetArgumentAtIndex(i));
408 s.PutCString(GetName());
415 Error ProcessLaunchCommandOptions::SetOptionValue(
416 uint32_t option_idx, llvm::StringRef option_arg,
417 ExecutionContext *execution_context) {
419 const int short_option = m_getopt_table[option_idx].val;
421 switch (short_option) {
422 case 's': // Stop at program entry point
423 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
426 case 'i': // STDIN for read only
429 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
430 launch_info.AppendFileAction(action);
434 case 'o': // Open STDOUT for write only
437 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
438 launch_info.AppendFileAction(action);
442 case 'e': // STDERR for write only
445 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
446 launch_info.AppendFileAction(action);
450 case 'p': // Process plug-in name
451 launch_info.SetProcessPluginName(option_arg);
454 case 'n': // Disable STDIO
457 const FileSpec dev_null{FileSystem::DEV_NULL, false};
458 if (action.Open(STDIN_FILENO, dev_null, true, false))
459 launch_info.AppendFileAction(action);
460 if (action.Open(STDOUT_FILENO, dev_null, false, true))
461 launch_info.AppendFileAction(action);
462 if (action.Open(STDERR_FILENO, dev_null, false, true))
463 launch_info.AppendFileAction(action);
468 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
471 case 't': // Open process in new terminal window
472 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
477 execution_context ? execution_context->GetTargetSP() : TargetSP();
478 PlatformSP platform_sp =
479 target_sp ? target_sp->GetPlatform() : PlatformSP();
480 if (!launch_info.GetArchitecture().SetTriple(option_arg, platform_sp.get()))
481 launch_info.GetArchitecture().SetTriple(option_arg);
484 case 'A': // Disable ASLR.
487 const bool disable_aslr_arg =
488 Args::StringToBoolean(option_arg, true, &success);
490 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
492 error.SetErrorStringWithFormat(
493 "Invalid boolean value for disable-aslr option: '%s'",
494 option_arg.empty() ? "<null>" : option_arg.str().c_str());
498 case 'X': // shell expand args.
501 const bool expand_args = Args::StringToBoolean(option_arg, true, &success);
503 launch_info.SetShellExpandArguments(expand_args);
505 error.SetErrorStringWithFormat(
506 "Invalid boolean value for shell-expand-args option: '%s'",
507 option_arg.empty() ? "<null>" : option_arg.str().c_str());
512 if (!option_arg.empty())
513 launch_info.SetShell(FileSpec(option_arg, false));
515 launch_info.SetShell(HostInfo::GetDefaultShell());
519 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
523 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
530 static OptionDefinition g_process_launch_options[] = {
531 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
532 nullptr, nullptr, 0, eArgTypeNone,
533 "Stop at the entry point of the program when launching a process."},
534 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
535 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
536 "Set whether to disable address space layout randomization when launching "
538 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
539 nullptr, nullptr, 0, eArgTypePlugin,
540 "Name of the process plugin you want to use."},
541 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
542 OptionParser::eRequiredArgument, nullptr, nullptr, 0,
543 eArgTypeDirectoryName,
544 "Set the current working directory to <path> when running the inferior."},
545 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
546 nullptr, nullptr, 0, eArgTypeArchitecture,
547 "Set the architecture for the process to launch when ambiguous."},
548 {LLDB_OPT_SET_ALL, false, "environment", 'v',
549 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone,
550 "Specify an environment variable name/value string (--environment "
551 "NAME=VALUE). Can be specified multiple times for subsequent environment "
553 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
554 OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeFilename,
555 "Run the process in a shell (not supported on all platforms)."},
557 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
558 nullptr, nullptr, 0, eArgTypeFilename,
559 "Redirect stdin for the process to <filename>."},
560 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
561 nullptr, nullptr, 0, eArgTypeFilename,
562 "Redirect stdout for the process to <filename>."},
563 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
564 nullptr, nullptr, 0, eArgTypeFilename,
565 "Redirect stderr for the process to <filename>."},
567 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
568 nullptr, 0, eArgTypeNone,
569 "Start the process in a terminal (not supported on all platforms)."},
571 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
572 nullptr, 0, eArgTypeNone,
573 "Do not set up for terminal I/O to go to running process."},
574 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
575 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
576 "Set whether to shell expand arguments to the process when launching."},
579 llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
580 return llvm::makeArrayRef(g_process_launch_options);
583 bool ProcessInstanceInfoMatch::NameMatches(const char *process_name) const {
584 if (m_name_match_type == eNameMatchIgnore || process_name == nullptr)
586 const char *match_name = m_match_info.GetName();
590 return lldb_private::NameMatches(process_name, m_name_match_type, match_name);
593 bool ProcessInstanceInfoMatch::Matches(
594 const ProcessInstanceInfo &proc_info) const {
595 if (!NameMatches(proc_info.GetName()))
598 if (m_match_info.ProcessIDIsValid() &&
599 m_match_info.GetProcessID() != proc_info.GetProcessID())
602 if (m_match_info.ParentProcessIDIsValid() &&
603 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
606 if (m_match_info.UserIDIsValid() &&
607 m_match_info.GetUserID() != proc_info.GetUserID())
610 if (m_match_info.GroupIDIsValid() &&
611 m_match_info.GetGroupID() != proc_info.GetGroupID())
614 if (m_match_info.EffectiveUserIDIsValid() &&
615 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
618 if (m_match_info.EffectiveGroupIDIsValid() &&
619 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
622 if (m_match_info.GetArchitecture().IsValid() &&
623 !m_match_info.GetArchitecture().IsCompatibleMatch(
624 proc_info.GetArchitecture()))
629 bool ProcessInstanceInfoMatch::MatchAllProcesses() const {
630 if (m_name_match_type != eNameMatchIgnore)
633 if (m_match_info.ProcessIDIsValid())
636 if (m_match_info.ParentProcessIDIsValid())
639 if (m_match_info.UserIDIsValid())
642 if (m_match_info.GroupIDIsValid())
645 if (m_match_info.EffectiveUserIDIsValid())
648 if (m_match_info.EffectiveGroupIDIsValid())
651 if (m_match_info.GetArchitecture().IsValid())
654 if (m_match_all_users)
660 void ProcessInstanceInfoMatch::Clear() {
661 m_match_info.Clear();
662 m_name_match_type = eNameMatchIgnore;
663 m_match_all_users = false;
666 ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
667 llvm::StringRef plugin_name,
668 ListenerSP listener_sp,
669 const FileSpec *crash_file_path) {
670 static uint32_t g_process_unique_id = 0;
672 ProcessSP process_sp;
673 ProcessCreateInstance create_callback = nullptr;
674 if (!plugin_name.empty()) {
675 ConstString const_plugin_name(plugin_name);
677 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
678 if (create_callback) {
679 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
681 if (process_sp->CanDebug(target_sp, true)) {
682 process_sp->m_process_unique_id = ++g_process_unique_id;
688 for (uint32_t idx = 0;
690 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
692 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
694 if (process_sp->CanDebug(target_sp, false)) {
695 process_sp->m_process_unique_id = ++g_process_unique_id;
705 ConstString &Process::GetStaticBroadcasterClass() {
706 static ConstString class_name("lldb.process");
710 Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
711 : Process(target_sp, listener_sp,
712 UnixSignals::Create(HostInfo::GetArchitecture())) {
713 // This constructor just delegates to the full Process constructor,
714 // defaulting to using the Host's UnixSignals.
717 Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
718 const UnixSignalsSP &unix_signals_sp)
719 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
720 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
721 Process::GetStaticBroadcasterClass().AsCString()),
722 m_target_sp(target_sp), m_public_state(eStateUnloaded),
723 m_private_state(eStateUnloaded),
724 m_private_state_broadcaster(nullptr,
725 "lldb.process.internal_state_broadcaster"),
726 m_private_state_control_broadcaster(
727 nullptr, "lldb.process.internal_state_control_broadcaster"),
728 m_private_state_listener_sp(
729 Listener::MakeListener("lldb.process.internal_state_listener")),
730 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
731 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
732 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
733 m_thread_list(this), m_extended_thread_list(this),
734 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
735 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
736 m_breakpoint_site_list(), m_dynamic_checkers_ap(),
737 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
738 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
739 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
740 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
741 m_memory_cache(*this), m_allocated_memory_cache(*this),
742 m_should_detach(false), m_next_event_action_ap(), m_public_run_lock(),
743 m_private_run_lock(), m_stop_info_override_callback(nullptr),
744 m_finalizing(false), m_finalize_called(false),
745 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
746 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
747 m_can_interpret_function_calls(false), m_warnings_issued(),
748 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
749 CheckInWithManager();
751 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
753 log->Printf("%p Process::Process()", static_cast<void *>(this));
755 if (!m_unix_signals_sp)
756 m_unix_signals_sp = std::make_shared<UnixSignals>();
758 SetEventName(eBroadcastBitStateChanged, "state-changed");
759 SetEventName(eBroadcastBitInterrupt, "interrupt");
760 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
761 SetEventName(eBroadcastBitSTDERR, "stderr-available");
762 SetEventName(eBroadcastBitProfileData, "profile-data-available");
763 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
765 m_private_state_control_broadcaster.SetEventName(
766 eBroadcastInternalStateControlStop, "control-stop");
767 m_private_state_control_broadcaster.SetEventName(
768 eBroadcastInternalStateControlPause, "control-pause");
769 m_private_state_control_broadcaster.SetEventName(
770 eBroadcastInternalStateControlResume, "control-resume");
772 m_listener_sp->StartListeningForEvents(
773 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
774 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
775 eBroadcastBitProfileData | eBroadcastBitStructuredData);
777 m_private_state_listener_sp->StartListeningForEvents(
778 &m_private_state_broadcaster,
779 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
781 m_private_state_listener_sp->StartListeningForEvents(
782 &m_private_state_control_broadcaster,
783 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
784 eBroadcastInternalStateControlResume);
785 // We need something valid here, even if just the default UnixSignalsSP.
786 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
788 // Allow the platform to override the default cache line size
789 OptionValueSP value_sp =
791 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
793 uint32_t platform_cache_line_size =
794 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
795 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
796 value_sp->SetUInt64Value(platform_cache_line_size);
799 Process::~Process() {
800 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
802 log->Printf("%p Process::~Process()", static_cast<void *>(this));
803 StopPrivateStateThread();
805 // ThreadList::Clear() will try to acquire this process's mutex, so
806 // explicitly clear the thread list here to ensure that the mutex
807 // is not destroyed before the thread list.
808 m_thread_list.Clear();
811 const ProcessPropertiesSP &Process::GetGlobalProperties() {
812 // NOTE: intentional leak so we don't crash if global destructor chain gets
813 // called as other threads still use the result of this function
814 static ProcessPropertiesSP *g_settings_sp_ptr =
815 new ProcessPropertiesSP(new ProcessProperties(nullptr));
816 return *g_settings_sp_ptr;
819 void Process::Finalize() {
822 // Destroy this process if needed
823 switch (GetPrivateState()) {
824 case eStateConnected:
825 case eStateAttaching:
826 case eStateLaunching:
831 case eStateSuspended:
842 // Clear our broadcaster before we proceed with destroying
843 Broadcaster::Clear();
845 // Do any cleanup needed prior to being destructed... Subclasses
846 // that override this method should call this superclass method as well.
848 // We need to destroy the loader before the derived Process class gets
850 // since it is very likely that undoing the loader will require access to the
852 m_dynamic_checkers_ap.reset();
855 m_system_runtime_ap.reset();
857 m_jit_loaders_ap.reset();
858 m_thread_list_real.Destroy();
859 m_thread_list.Destroy();
860 m_extended_thread_list.Destroy();
861 m_queue_list.Clear();
862 m_queue_list_stop_id = 0;
863 std::vector<Notifications> empty_notifications;
864 m_notifications.swap(empty_notifications);
865 m_image_tokens.clear();
866 m_memory_cache.Clear();
867 m_allocated_memory_cache.Clear();
868 m_language_runtimes.clear();
869 m_instrumentation_runtimes.clear();
870 m_next_event_action_ap.reset();
871 m_stop_info_override_callback = nullptr;
872 // Clear the last natural stop ID since it has a strong
873 // reference to this process
874 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
875 //#ifdef LLDB_CONFIGURATION_DEBUG
876 // StreamFile s(stdout, false);
878 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
880 // event_sp->Dump (&s);
884 // We have to be very careful here as the m_private_state_listener might
885 // contain events that have ProcessSP values in them which can keep this
886 // process around forever. These events need to be cleared out.
887 m_private_state_listener_sp->Clear();
888 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
889 m_public_run_lock.SetStopped();
890 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
891 m_private_run_lock.SetStopped();
892 m_structured_data_plugin_map.clear();
893 m_finalize_called = true;
896 void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
897 m_notifications.push_back(callbacks);
898 if (callbacks.initialize != nullptr)
899 callbacks.initialize(callbacks.baton, this);
902 bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
903 std::vector<Notifications>::iterator pos, end = m_notifications.end();
904 for (pos = m_notifications.begin(); pos != end; ++pos) {
905 if (pos->baton == callbacks.baton &&
906 pos->initialize == callbacks.initialize &&
907 pos->process_state_changed == callbacks.process_state_changed) {
908 m_notifications.erase(pos);
915 void Process::SynchronouslyNotifyStateChanged(StateType state) {
916 std::vector<Notifications>::iterator notification_pos,
917 notification_end = m_notifications.end();
918 for (notification_pos = m_notifications.begin();
919 notification_pos != notification_end; ++notification_pos) {
920 if (notification_pos->process_state_changed)
921 notification_pos->process_state_changed(notification_pos->baton, this,
926 // FIXME: We need to do some work on events before the general Listener sees
928 // For instance if we are continuing from a breakpoint, we need to ensure that
930 // the little "insert real insn, step & stop" trick. But we can't do that when
932 // event is delivered by the broadcaster - since that is done on the thread that
934 // waiting for new events, so if we needed more than one event for our handling,
936 // stall. So instead we do it when we fetch the event off of the queue.
939 StateType Process::GetNextEvent(EventSP &event_sp) {
940 StateType state = eStateInvalid;
942 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
943 std::chrono::seconds(0)) &&
945 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
950 void Process::SyncIOHandler(uint32_t iohandler_id, uint64_t timeout_msec) {
951 // don't sync (potentially context switch) in case where there is no process
953 if (!m_process_input_reader)
956 uint32_t new_iohandler_id = 0;
957 m_iohandler_sync.WaitForValueNotEqualTo(
958 iohandler_id, new_iohandler_id, std::chrono::milliseconds(timeout_msec));
960 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
962 log->Printf("Process::%s waited for m_iohandler_sync to change from %u, "
964 __FUNCTION__, iohandler_id, new_iohandler_id);
967 StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
968 EventSP *event_sp_ptr, bool wait_always,
969 ListenerSP hijack_listener_sp,
970 Stream *stream, bool use_run_lock) {
971 // We can't just wait for a "stopped" event, because the stopped event may
972 // have restarted the target.
973 // We have to actually check each event, and in the case of a stopped event
974 // check the restarted flag
977 event_sp_ptr->reset();
978 StateType state = GetState();
979 // If we are exited or detached, we won't ever get back to any
980 // other valid state...
981 if (state == eStateDetached || state == eStateExited)
984 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
987 "Process::%s (timeout = %llu)", __FUNCTION__,
988 static_cast<unsigned long long>(timeout ? timeout->count() : -1));
990 if (!wait_always && StateIsStoppedState(state, true) &&
991 StateIsStoppedState(GetPrivateState(), true)) {
993 log->Printf("Process::%s returning without waiting for events; process "
994 "private and public states are already 'stopped'.",
996 // We need to toggle the run lock as this won't get done in
997 // SetPublicState() if the process is hijacked.
998 if (hijack_listener_sp && use_run_lock)
999 m_public_run_lock.SetStopped();
1003 while (state != eStateInvalid) {
1005 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
1006 if (event_sp_ptr && event_sp)
1007 *event_sp_ptr = event_sp;
1009 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
1010 Process::HandleProcessStateChangedEvent(event_sp, stream,
1011 pop_process_io_handler);
1015 case eStateDetached:
1017 case eStateUnloaded:
1018 // We need to toggle the run lock as this won't get done in
1019 // SetPublicState() if the process is hijacked.
1020 if (hijack_listener_sp && use_run_lock)
1021 m_public_run_lock.SetStopped();
1024 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1027 // We need to toggle the run lock as this won't get done in
1028 // SetPublicState() if the process is hijacked.
1029 if (hijack_listener_sp && use_run_lock)
1030 m_public_run_lock.SetStopped();
1040 bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
1042 bool &pop_process_io_handler) {
1043 const bool handle_pop = pop_process_io_handler;
1045 pop_process_io_handler = false;
1046 ProcessSP process_sp =
1047 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1052 StateType event_state =
1053 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1054 if (event_state == eStateInvalid)
1057 switch (event_state) {
1059 case eStateUnloaded:
1060 case eStateAttaching:
1061 case eStateLaunching:
1062 case eStateStepping:
1063 case eStateDetached:
1065 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
1066 StateAsCString(event_state));
1067 if (event_state == eStateDetached)
1068 pop_process_io_handler = true;
1071 case eStateConnected:
1073 // Don't be chatty when we run...
1078 process_sp->GetStatus(*stream);
1079 pop_process_io_handler = true;
1084 case eStateSuspended:
1085 // Make sure the program hasn't been auto-restarted:
1086 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
1088 size_t num_reasons =
1089 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1090 if (num_reasons > 0) {
1091 // FIXME: Do we want to report this, or would that just be annoyingly
1093 if (num_reasons == 1) {
1094 const char *reason =
1095 Process::ProcessEventData::GetRestartedReasonAtIndex(
1097 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
1098 process_sp->GetID(),
1099 reason ? reason : "<UNKNOWN REASON>");
1101 stream->Printf("Process %" PRIu64
1102 " stopped and restarted, reasons:\n",
1103 process_sp->GetID());
1105 for (size_t i = 0; i < num_reasons; i++) {
1106 const char *reason =
1107 Process::ProcessEventData::GetRestartedReasonAtIndex(
1109 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1115 StopInfoSP curr_thread_stop_info_sp;
1116 // Lock the thread list so it doesn't change on us, this is the scope for
1119 ThreadList &thread_list = process_sp->GetThreadList();
1120 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
1122 ThreadSP curr_thread(thread_list.GetSelectedThread());
1124 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1126 curr_thread_stop_reason = curr_thread->GetStopReason();
1127 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
1129 if (!curr_thread || !curr_thread->IsValid() ||
1130 curr_thread_stop_reason == eStopReasonInvalid ||
1131 curr_thread_stop_reason == eStopReasonNone) {
1132 // Prefer a thread that has just completed its plan over another
1133 // thread as current thread.
1134 ThreadSP plan_thread;
1135 ThreadSP other_thread;
1137 const size_t num_threads = thread_list.GetSize();
1139 for (i = 0; i < num_threads; ++i) {
1140 thread = thread_list.GetThreadAtIndex(i);
1141 StopReason thread_stop_reason = thread->GetStopReason();
1142 switch (thread_stop_reason) {
1143 case eStopReasonInvalid:
1144 case eStopReasonNone:
1147 case eStopReasonSignal: {
1148 // Don't select a signal thread if we weren't going to stop at
1150 // signal. We have to have had another reason for stopping here,
1152 // the user doesn't want to see this thread.
1153 uint64_t signo = thread->GetStopInfo()->GetValue();
1154 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
1156 other_thread = thread;
1160 case eStopReasonTrace:
1161 case eStopReasonBreakpoint:
1162 case eStopReasonWatchpoint:
1163 case eStopReasonException:
1164 case eStopReasonExec:
1165 case eStopReasonThreadExiting:
1166 case eStopReasonInstrumentation:
1168 other_thread = thread;
1170 case eStopReasonPlanComplete:
1172 plan_thread = thread;
1177 thread_list.SetSelectedThreadByID(plan_thread->GetID());
1178 else if (other_thread)
1179 thread_list.SetSelectedThreadByID(other_thread->GetID());
1181 if (curr_thread && curr_thread->IsValid())
1182 thread = curr_thread;
1184 thread = thread_list.GetThreadAtIndex(0);
1187 thread_list.SetSelectedThreadByID(thread->GetID());
1191 // Drop the ThreadList mutex by here, since GetThreadStatus below might
1192 // have to run code,
1193 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the
1194 // process is going to
1195 // have a hard time restarting the process.
1197 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1198 if (debugger.GetTargetList().GetSelectedTarget().get() ==
1199 &process_sp->GetTarget()) {
1200 const bool only_threads_with_stop_reason = true;
1201 const uint32_t start_frame = 0;
1202 const uint32_t num_frames = 1;
1203 const uint32_t num_frames_with_source = 1;
1204 const bool stop_format = true;
1205 process_sp->GetStatus(*stream);
1206 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
1207 start_frame, num_frames,
1208 num_frames_with_source,
1210 if (curr_thread_stop_info_sp) {
1211 lldb::addr_t crashing_address;
1212 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1213 curr_thread_stop_info_sp, &crashing_address);
1215 const bool qualify_cxx_base_classes = false;
1217 const ValueObject::GetExpressionPathFormat format =
1218 ValueObject::GetExpressionPathFormat::
1219 eGetExpressionPathFormatHonorPointers;
1220 stream->PutCString("Likely cause: ");
1221 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
1223 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1227 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1228 process_sp->GetTarget().shared_from_this());
1229 if (target_idx != UINT32_MAX)
1230 stream->Printf("Target %d: (", target_idx);
1232 stream->Printf("Target <unknown index>: (");
1233 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1234 stream->Printf(") stopped.\n");
1238 // Pop the process IO handler
1239 pop_process_io_handler = true;
1244 if (handle_pop && pop_process_io_handler)
1245 process_sp->PopProcessIOHandler();
1250 bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1252 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1253 eBroadcastBitInterrupt);
1258 void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
1260 StateType Process::GetStateChangedEvents(EventSP &event_sp,
1261 const Timeout<std::micro> &timeout,
1262 ListenerSP hijack_listener_sp) {
1263 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1267 "Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1268 static_cast<unsigned long long>(timeout ? timeout->count() : -1));
1270 ListenerSP listener_sp = hijack_listener_sp;
1272 listener_sp = m_listener_sp;
1274 StateType state = eStateInvalid;
1275 if (listener_sp->GetEventForBroadcasterWithType(
1276 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
1278 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1279 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1281 log->Printf("Process::%s got no event or was interrupted.", __FUNCTION__);
1286 "Process::%s (timeout = %llu, event_sp) => %s", __FUNCTION__,
1287 static_cast<unsigned long long>(timeout ? timeout->count() : -1),
1288 StateAsCString(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));
1320 "Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1321 static_cast<unsigned long long>(timeout ? timeout->count() : -1));
1323 StateType state = eStateInvalid;
1324 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1325 &m_private_state_broadcaster,
1326 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
1328 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1329 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1331 // This is a bit of a hack, but when we wait here we could very well return
1332 // to the command-line, and that could disable the log, which would render the
1333 // log we got above invalid.
1336 "Process::%s (timeout = %llu, event_sp) => %s", __FUNCTION__,
1337 static_cast<unsigned long long>(timeout ? timeout->count() : -1),
1338 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
1342 bool Process::GetEventsPrivate(EventSP &event_sp,
1343 const Timeout<std::micro> &timeout,
1344 bool control_only) {
1345 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1349 "Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1350 static_cast<unsigned long long>(timeout ? timeout->count() : -1));
1353 return m_private_state_listener_sp->GetEventForBroadcaster(
1354 &m_private_state_control_broadcaster, event_sp, timeout);
1356 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
1359 bool Process::IsRunning() const {
1360 return StateIsRunningState(m_public_state.GetValue());
1363 int Process::GetExitStatus() {
1364 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1366 if (m_public_state.GetValue() == eStateExited)
1367 return m_exit_status;
1371 const char *Process::GetExitDescription() {
1372 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1374 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1375 return m_exit_string.c_str();
1379 bool Process::SetExitStatus(int status, const char *cstr) {
1380 // Use a mutex to protect setting the exit status.
1381 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1383 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1384 LIBLLDB_LOG_PROCESS));
1387 "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1388 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL",
1391 // We were already in the exited state
1392 if (m_private_state.GetValue() == eStateExited) {
1394 log->Printf("Process::SetExitStatus () ignoring exit status because "
1395 "state was already set to eStateExited");
1399 m_exit_status = status;
1401 m_exit_string = cstr;
1403 m_exit_string.clear();
1405 // Clear the last natural stop ID since it has a strong
1406 // reference to this process
1407 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1409 SetPrivateState(eStateExited);
1411 // Allow subclasses to do some cleanup
1417 bool Process::IsAlive() {
1418 switch (m_private_state.GetValue()) {
1419 case eStateConnected:
1420 case eStateAttaching:
1421 case eStateLaunching:
1424 case eStateStepping:
1426 case eStateSuspended:
1433 // This static callback can be used to watch for local child processes on
1434 // the current host. The child process exits, the process will be
1435 // found in the global target list (we want to be completely sure that the
1436 // lldb_private::Process doesn't go away before we can deliver the signal.
1437 bool Process::SetProcessExitStatus(
1438 lldb::pid_t pid, bool exited,
1439 int signo, // Zero for no signal
1440 int exit_status // Exit value of process if signal is zero
1442 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1444 log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64
1445 ", exited=%i, signal=%i, exit_status=%i)\n",
1446 pid, exited, signo, exit_status);
1449 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1451 ProcessSP process_sp(target_sp->GetProcessSP());
1453 const char *signal_cstr = nullptr;
1455 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1457 process_sp->SetExitStatus(exit_status, signal_cstr);
1465 void Process::UpdateThreadListIfNeeded() {
1466 const uint32_t stop_id = GetStopID();
1467 if (m_thread_list.GetSize(false) == 0 ||
1468 stop_id != m_thread_list.GetStopID()) {
1469 const StateType state = GetPrivateState();
1470 if (StateIsStoppedState(state, true)) {
1471 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
1472 // m_thread_list does have its own mutex, but we need to
1473 // hold onto the mutex between the call to UpdateThreadList(...)
1474 // and the os->UpdateThreadList(...) so it doesn't change on us
1475 ThreadList &old_thread_list = m_thread_list;
1476 ThreadList real_thread_list(this);
1477 ThreadList new_thread_list(this);
1478 // Always update the thread list with the protocol specific
1479 // thread list, but only update if "true" is returned
1480 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1481 // Don't call into the OperatingSystem to update the thread list if we
1482 // are shutting down, since
1483 // that may call back into the SBAPI's, requiring the API lock which is
1484 // already held by whoever is
1485 // shutting us down, causing a deadlock.
1486 OperatingSystem *os = GetOperatingSystem();
1487 if (os && !m_destroy_in_process) {
1488 // Clear any old backing threads where memory threads might have been
1489 // backed by actual threads from the lldb_private::Process subclass
1490 size_t num_old_threads = old_thread_list.GetSize(false);
1491 for (size_t i = 0; i < num_old_threads; ++i)
1492 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1494 // Turn off dynamic types to ensure we don't run any expressions.
1496 // can run an expression to determine if a SBValue is a dynamic type
1498 // and we need to avoid this. OperatingSystem plug-ins can't run
1500 // that require running code...
1502 Target &target = GetTarget();
1503 const lldb::DynamicValueType saved_prefer_dynamic =
1504 target.GetPreferDynamicValue();
1505 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1506 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1508 // Now let the OperatingSystem plug-in update the thread list
1510 os->UpdateThreadList(
1511 old_thread_list, // Old list full of threads created by OS plug-in
1512 real_thread_list, // The actual thread list full of threads
1513 // created by each lldb_private::Process
1515 new_thread_list); // The new thread list that we will show to the
1516 // user that gets filled in
1518 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1519 target.SetPreferDynamicValue(saved_prefer_dynamic);
1521 // No OS plug-in, the new thread list is the same as the real thread
1523 new_thread_list = real_thread_list;
1526 m_thread_list_real.Update(real_thread_list);
1527 m_thread_list.Update(new_thread_list);
1528 m_thread_list.SetStopID(stop_id);
1530 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1531 // Clear any extended threads that we may have accumulated previously
1532 m_extended_thread_list.Clear();
1533 m_extended_thread_stop_id = GetLastNaturalStopID();
1535 m_queue_list.Clear();
1536 m_queue_list_stop_id = GetLastNaturalStopID();
1543 void Process::UpdateQueueListIfNeeded() {
1544 if (m_system_runtime_ap) {
1545 if (m_queue_list.GetSize() == 0 ||
1546 m_queue_list_stop_id != GetLastNaturalStopID()) {
1547 const StateType state = GetPrivateState();
1548 if (StateIsStoppedState(state, true)) {
1549 m_system_runtime_ap->PopulateQueueList(m_queue_list);
1550 m_queue_list_stop_id = GetLastNaturalStopID();
1556 ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1557 OperatingSystem *os = GetOperatingSystem();
1559 return os->CreateThread(tid, context);
1563 uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1564 return AssignIndexIDToThread(thread_id);
1567 bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1568 return (m_thread_id_to_index_id_map.find(thread_id) !=
1569 m_thread_id_to_index_id_map.end());
1572 uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1573 uint32_t result = 0;
1574 std::map<uint64_t, uint32_t>::iterator iterator =
1575 m_thread_id_to_index_id_map.find(thread_id);
1576 if (iterator == m_thread_id_to_index_id_map.end()) {
1577 result = ++m_thread_index_id;
1578 m_thread_id_to_index_id_map[thread_id] = result;
1580 result = iterator->second;
1586 StateType Process::GetState() {
1587 // If any other threads access this we will need a mutex for it
1588 return m_public_state.GetValue();
1591 bool Process::StateChangedIsExternallyHijacked() {
1592 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1593 const char *hijacking_name = GetHijackingListenerName();
1594 if (hijacking_name &&
1595 strcmp(hijacking_name, "lldb.Process.ResumeSynchronous.hijack"))
1601 void Process::SetPublicState(StateType new_state, bool restarted) {
1602 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1603 LIBLLDB_LOG_PROCESS));
1605 log->Printf("Process::SetPublicState (state = %s, restarted = %i)",
1606 StateAsCString(new_state), restarted);
1607 const StateType old_state = m_public_state.GetValue();
1608 m_public_state.SetValue(new_state);
1610 // On the transition from Run to Stopped, we unlock the writer end of the
1611 // run lock. The lock gets locked in Resume, which is the public API
1612 // to tell the program to run.
1613 if (!StateChangedIsExternallyHijacked()) {
1614 if (new_state == eStateDetached) {
1617 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1618 StateAsCString(new_state));
1619 m_public_run_lock.SetStopped();
1621 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1622 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1623 if ((old_state_is_stopped != new_state_is_stopped)) {
1624 if (new_state_is_stopped && !restarted) {
1626 log->Printf("Process::SetPublicState (%s) -- unlocking run lock",
1627 StateAsCString(new_state));
1628 m_public_run_lock.SetStopped();
1635 Error Process::Resume() {
1636 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1637 LIBLLDB_LOG_PROCESS));
1639 log->Printf("Process::Resume -- locking run lock");
1640 if (!m_public_run_lock.TrySetRunning()) {
1641 Error error("Resume request failed - process still running.");
1643 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1646 return PrivateResume();
1649 Error Process::ResumeSynchronous(Stream *stream) {
1650 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1651 LIBLLDB_LOG_PROCESS));
1653 log->Printf("Process::ResumeSynchronous -- locking run lock");
1654 if (!m_public_run_lock.TrySetRunning()) {
1655 Error error("Resume request failed - process still running.");
1657 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1661 ListenerSP listener_sp(
1662 Listener::MakeListener("lldb.Process.ResumeSynchronous.hijack"));
1663 HijackProcessEvents(listener_sp);
1665 Error error = PrivateResume();
1666 if (error.Success()) {
1668 WaitForProcessToStop(llvm::None, NULL, true, listener_sp, stream);
1669 const bool must_be_alive =
1670 false; // eStateExited is ok, so this must be false
1671 if (!StateIsStoppedState(state, must_be_alive))
1672 error.SetErrorStringWithFormat(
1673 "process not in stopped state after synchronous resume: %s",
1674 StateAsCString(state));
1677 // Undo the hijacking of process events...
1678 RestoreProcessEvents();
1683 StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
1685 void Process::SetPrivateState(StateType new_state) {
1686 if (m_finalize_called)
1689 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1690 LIBLLDB_LOG_PROCESS));
1691 bool state_changed = false;
1694 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1696 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1697 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1699 const StateType old_state = m_private_state.GetValueNoLock();
1700 state_changed = old_state != new_state;
1702 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1703 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1704 if (old_state_is_stopped != new_state_is_stopped) {
1705 if (new_state_is_stopped)
1706 m_private_run_lock.SetStopped();
1708 m_private_run_lock.SetRunning();
1711 if (state_changed) {
1712 m_private_state.SetValueNoLock(new_state);
1714 new Event(eBroadcastBitStateChanged,
1715 new ProcessEventData(shared_from_this(), new_state)));
1716 if (StateIsStoppedState(new_state, false)) {
1717 // Note, this currently assumes that all threads in the list
1718 // stop when the process stops. In the future we will want to
1719 // support a debugging model where some threads continue to run
1720 // while others are stopped. When that happens we will either need
1721 // a way for the thread list to identify which threads are stopping
1722 // or create a special thread list containing only threads which
1723 // actually stopped.
1725 // The process plugin is responsible for managing the actual
1726 // behavior of the threads and should have stopped any threads
1727 // that are going to stop before we get here.
1728 m_thread_list.DidStop();
1730 m_mod_id.BumpStopID();
1731 if (!m_mod_id.IsLastResumeForUserExpression())
1732 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1733 m_memory_cache.Clear();
1735 log->Printf("Process::SetPrivateState (%s) stop_id = %u",
1736 StateAsCString(new_state), m_mod_id.GetStopID());
1739 // Use our target to get a shared pointer to ourselves...
1740 if (m_finalize_called && !PrivateStateThreadIsValid())
1741 BroadcastEvent(event_sp);
1743 m_private_state_broadcaster.BroadcastEvent(event_sp);
1747 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1748 StateAsCString(new_state));
1752 void Process::SetRunningUserExpression(bool on) {
1753 m_mod_id.SetRunningUserExpression(on);
1756 addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1758 const lldb::ABISP &Process::GetABI() {
1760 m_abi_sp = ABI::FindPlugin(GetTarget().GetArchitecture());
1764 LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language,
1765 bool retry_if_null) {
1769 LanguageRuntimeCollection::iterator pos;
1770 pos = m_language_runtimes.find(language);
1771 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) {
1772 lldb::LanguageRuntimeSP runtime_sp(
1773 LanguageRuntime::FindPlugin(this, language));
1775 m_language_runtimes[language] = runtime_sp;
1776 return runtime_sp.get();
1778 return (*pos).second.get();
1781 CPPLanguageRuntime *Process::GetCPPLanguageRuntime(bool retry_if_null) {
1782 LanguageRuntime *runtime =
1783 GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1784 if (runtime != nullptr &&
1785 runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1786 return static_cast<CPPLanguageRuntime *>(runtime);
1790 ObjCLanguageRuntime *Process::GetObjCLanguageRuntime(bool retry_if_null) {
1791 LanguageRuntime *runtime =
1792 GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1793 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC)
1794 return static_cast<ObjCLanguageRuntime *>(runtime);
1798 bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1802 if (in_value.IsDynamic())
1804 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1806 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1807 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1808 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1811 LanguageRuntime *cpp_runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1812 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1815 LanguageRuntime *objc_runtime = GetLanguageRuntime(eLanguageTypeObjC);
1816 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1819 void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
1820 m_dynamic_checkers_ap.reset(dynamic_checkers);
1823 BreakpointSiteList &Process::GetBreakpointSiteList() {
1824 return m_breakpoint_site_list;
1827 const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1828 return m_breakpoint_site_list;
1831 void Process::DisableAllBreakpointSites() {
1832 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1833 // bp_site->SetEnabled(true);
1834 DisableBreakpointSite(bp_site);
1838 Error Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1839 Error error(DisableBreakpointSiteByID(break_id));
1841 if (error.Success())
1842 m_breakpoint_site_list.Remove(break_id);
1847 Error Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1849 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1851 if (bp_site_sp->IsEnabled())
1852 error = DisableBreakpointSite(bp_site_sp.get());
1854 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1861 Error Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1863 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1865 if (!bp_site_sp->IsEnabled())
1866 error = EnableBreakpointSite(bp_site_sp.get());
1868 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1875 Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1876 bool use_hardware) {
1877 addr_t load_addr = LLDB_INVALID_ADDRESS;
1879 bool show_error = true;
1880 switch (GetState()) {
1882 case eStateUnloaded:
1883 case eStateConnected:
1884 case eStateAttaching:
1885 case eStateLaunching:
1886 case eStateDetached:
1893 case eStateStepping:
1895 case eStateSuspended:
1896 show_error = IsAlive();
1900 // Reset the IsIndirect flag here, in case the location changes from
1901 // pointing to a indirect symbol to a regular symbol.
1902 owner->SetIsIndirect(false);
1904 if (owner->ShouldResolveIndirectFunctions()) {
1905 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1906 if (symbol && symbol->IsIndirect()) {
1908 Address symbol_address = symbol->GetAddress();
1909 load_addr = ResolveIndirectFunction(&symbol_address, error);
1910 if (!error.Success() && show_error) {
1911 GetTarget().GetDebugger().GetErrorFile()->Printf(
1912 "warning: failed to resolve indirect function at 0x%" PRIx64
1913 " for breakpoint %i.%i: %s\n",
1914 symbol->GetLoadAddress(&GetTarget()),
1915 owner->GetBreakpoint().GetID(), owner->GetID(),
1916 error.AsCString() ? error.AsCString() : "unknown error");
1917 return LLDB_INVALID_BREAK_ID;
1919 Address resolved_address(load_addr);
1920 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1921 owner->SetIsIndirect(true);
1923 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1925 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1927 if (load_addr != LLDB_INVALID_ADDRESS) {
1928 BreakpointSiteSP bp_site_sp;
1930 // Look up this breakpoint site. If it exists, then add this new owner,
1932 // create a new breakpoint site and add it.
1934 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1937 bp_site_sp->AddOwner(owner);
1938 owner->SetBreakpointSite(bp_site_sp);
1939 return bp_site_sp->GetID();
1941 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1942 load_addr, use_hardware));
1944 Error error = EnableBreakpointSite(bp_site_sp.get());
1945 if (error.Success()) {
1946 owner->SetBreakpointSite(bp_site_sp);
1947 return m_breakpoint_site_list.Add(bp_site_sp);
1950 // Report error for setting breakpoint...
1951 GetTarget().GetDebugger().GetErrorFile()->Printf(
1952 "warning: failed to set breakpoint site at 0x%" PRIx64
1953 " for breakpoint %i.%i: %s\n",
1954 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1955 error.AsCString() ? error.AsCString() : "unknown error");
1961 // We failed to enable the breakpoint
1962 return LLDB_INVALID_BREAK_ID;
1965 void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1966 lldb::user_id_t owner_loc_id,
1967 BreakpointSiteSP &bp_site_sp) {
1968 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1969 if (num_owners == 0) {
1970 // Don't try to disable the site if we don't have a live process anymore.
1972 DisableBreakpointSite(bp_site_sp.get());
1973 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1977 size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1978 uint8_t *buf) const {
1979 size_t bytes_removed = 0;
1980 BreakpointSiteList bp_sites_in_range;
1982 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1983 bp_sites_in_range)) {
1984 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](
1985 BreakpointSite *bp_site) -> void {
1986 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1987 addr_t intersect_addr;
1988 size_t intersect_size;
1989 size_t opcode_offset;
1990 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1991 &intersect_size, &opcode_offset)) {
1992 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1993 assert(bp_addr < intersect_addr + intersect_size &&
1994 intersect_addr + intersect_size <= bp_addr + size);
1995 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1996 size_t buf_offset = intersect_addr - bp_addr;
1997 ::memcpy(buf + buf_offset,
1998 bp_site->GetSavedOpcodeBytes() + opcode_offset,
2004 return bytes_removed;
2007 size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
2008 PlatformSP platform_sp(GetTarget().GetPlatform());
2010 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
2014 Error Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
2016 assert(bp_site != nullptr);
2017 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2018 const addr_t bp_addr = bp_site->GetLoadAddress();
2021 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
2022 bp_site->GetID(), (uint64_t)bp_addr);
2023 if (bp_site->IsEnabled()) {
2026 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2027 " -- already enabled",
2028 bp_site->GetID(), (uint64_t)bp_addr);
2032 if (bp_addr == LLDB_INVALID_ADDRESS) {
2033 error.SetErrorString("BreakpointSite contains an invalid load address.");
2036 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2037 // trap for the breakpoint site
2038 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2040 if (bp_opcode_size == 0) {
2041 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
2042 "returned zero, unable to get breakpoint "
2043 "trap for address 0x%" PRIx64,
2046 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2048 if (bp_opcode_bytes == nullptr) {
2049 error.SetErrorString(
2050 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2054 // Save the original opcode by reading it
2055 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
2056 error) == bp_opcode_size) {
2057 // Write a software breakpoint in place of the original opcode
2058 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
2060 uint8_t verify_bp_opcode_bytes[64];
2061 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
2062 error) == bp_opcode_size) {
2063 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
2064 bp_opcode_size) == 0) {
2065 bp_site->SetEnabled(true);
2066 bp_site->SetType(BreakpointSite::eSoftware);
2068 log->Printf("Process::EnableSoftwareBreakpoint (site_id = %d) "
2069 "addr = 0x%" PRIx64 " -- SUCCESS",
2070 bp_site->GetID(), (uint64_t)bp_addr);
2072 error.SetErrorString(
2073 "failed to verify the breakpoint trap in memory.");
2075 error.SetErrorString(
2076 "Unable to read memory to verify breakpoint trap.");
2078 error.SetErrorString("Unable to write breakpoint trap to memory.");
2080 error.SetErrorString("Unable to read memory at breakpoint address.");
2082 if (log && error.Fail())
2084 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2086 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2090 Error Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
2092 assert(bp_site != nullptr);
2093 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2094 addr_t bp_addr = bp_site->GetLoadAddress();
2095 lldb::user_id_t breakID = bp_site->GetID();
2097 log->Printf("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
2098 ") addr = 0x%" PRIx64,
2099 breakID, (uint64_t)bp_addr);
2101 if (bp_site->IsHardware()) {
2102 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2103 } else if (bp_site->IsEnabled()) {
2104 const size_t break_op_size = bp_site->GetByteSize();
2105 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
2106 if (break_op_size > 0) {
2107 // Clear a software breakpoint instruction
2108 uint8_t curr_break_op[8];
2109 assert(break_op_size <= sizeof(curr_break_op));
2110 bool break_op_found = false;
2112 // Read the breakpoint opcode
2113 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
2115 bool verify = false;
2116 // Make sure the breakpoint opcode exists at this address
2117 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
2118 break_op_found = true;
2119 // We found a valid breakpoint opcode at this address, now restore
2120 // the saved opcode.
2121 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
2122 break_op_size, error) == break_op_size) {
2125 error.SetErrorString(
2126 "Memory write failed when restoring original opcode.");
2128 error.SetErrorString(
2129 "Original breakpoint trap is no longer in memory.");
2130 // Set verify to true and so we can check if the original opcode has
2131 // already been restored
2136 uint8_t verify_opcode[8];
2137 assert(break_op_size < sizeof(verify_opcode));
2138 // Verify that our original opcode made it back to the inferior
2139 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
2141 // compare the memory we just read with the original opcode
2142 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
2143 break_op_size) == 0) {
2145 bp_site->SetEnabled(false);
2147 log->Printf("Process::DisableSoftwareBreakpoint (site_id = %d) "
2148 "addr = 0x%" PRIx64 " -- SUCCESS",
2149 bp_site->GetID(), (uint64_t)bp_addr);
2153 error.SetErrorString("Failed to restore original opcode.");
2156 error.SetErrorString("Failed to read memory to verify that "
2157 "breakpoint trap was restored.");
2160 error.SetErrorString(
2161 "Unable to read memory that should contain the breakpoint trap.");
2166 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2167 " -- already disabled",
2168 bp_site->GetID(), (uint64_t)bp_addr);
2174 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2176 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2180 // Uncomment to verify memory caching works after making changes to caching code
2181 //#define VERIFY_MEMORY_READS
2183 size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Error &error) {
2185 if (!GetDisableMemoryCache()) {
2186 #if defined(VERIFY_MEMORY_READS)
2187 // Memory caching is enabled, with debug verification
2190 // Uncomment the line below to make sure memory caching is working.
2191 // I ran this through the test suite and got no assertions, so I am
2192 // pretty confident this is working well. If any changes are made to
2193 // memory caching, uncomment the line below and test your changes!
2195 // Verify all memory reads by using the cache first, then redundantly
2196 // reading the same memory from the inferior and comparing to make sure
2197 // everything is exactly the same.
2198 std::string verify_buf(size, '\0');
2199 assert(verify_buf.size() == size);
2200 const size_t cache_bytes_read =
2201 m_memory_cache.Read(this, addr, buf, size, error);
2203 const size_t verify_bytes_read =
2204 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2205 verify_buf.size(), verify_error);
2206 assert(cache_bytes_read == verify_bytes_read);
2207 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2208 assert(verify_error.Success() == error.Success());
2209 return cache_bytes_read;
2212 #else // !defined(VERIFY_MEMORY_READS)
2213 // Memory caching is enabled, without debug verification
2215 return m_memory_cache.Read(addr, buf, size, error);
2216 #endif // defined (VERIFY_MEMORY_READS)
2218 // Memory caching is disabled
2220 return ReadMemoryFromInferior(addr, buf, size, error);
2224 size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
2228 addr_t curr_addr = addr;
2230 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2233 out_str.append(buf, length);
2234 // If we got "length - 1" bytes, we didn't get the whole C string, we
2235 // need to read some more characters
2236 if (length == sizeof(buf) - 1)
2237 curr_addr += length;
2241 return out_str.size();
2244 size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
2245 Error &error, size_t type_width) {
2246 size_t total_bytes_read = 0;
2247 if (dst && max_bytes && type_width && max_bytes >= type_width) {
2248 // Ensure a null terminator independent of the number of bytes that is read.
2249 memset(dst, 0, max_bytes);
2250 size_t bytes_left = max_bytes - type_width;
2252 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2253 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2254 "string with more than 4 bytes "
2257 addr_t curr_addr = addr;
2258 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2259 char *curr_dst = dst;
2262 while (bytes_left > 0 && error.Success()) {
2263 addr_t cache_line_bytes_left =
2264 cache_line_size - (curr_addr % cache_line_size);
2265 addr_t bytes_to_read =
2266 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2267 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
2269 if (bytes_read == 0)
2272 // Search for a null terminator of correct size and alignment in
2274 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2275 for (size_t i = aligned_start;
2276 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2277 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2282 total_bytes_read += bytes_read;
2283 curr_dst += bytes_read;
2284 curr_addr += bytes_read;
2285 bytes_left -= bytes_read;
2289 error.SetErrorString("invalid arguments");
2291 return total_bytes_read;
2294 // Deprecated in favor of ReadStringFromMemory which has wchar support and
2295 // correct code to find
2296 // null terminators.
2297 size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
2298 size_t dst_max_len, Error &result_error) {
2299 size_t total_cstr_len = 0;
2300 if (dst && dst_max_len) {
2301 result_error.Clear();
2302 // NULL out everything just to be safe
2303 memset(dst, 0, dst_max_len);
2305 addr_t curr_addr = addr;
2306 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2307 size_t bytes_left = dst_max_len - 1;
2308 char *curr_dst = dst;
2310 while (bytes_left > 0) {
2311 addr_t cache_line_bytes_left =
2312 cache_line_size - (curr_addr % cache_line_size);
2313 addr_t bytes_to_read =
2314 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2315 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
2317 if (bytes_read == 0) {
2318 result_error = error;
2319 dst[total_cstr_len] = '\0';
2322 const size_t len = strlen(curr_dst);
2324 total_cstr_len += len;
2326 if (len < bytes_to_read)
2329 curr_dst += bytes_read;
2330 curr_addr += bytes_read;
2331 bytes_left -= bytes_read;
2335 result_error.SetErrorString("invalid arguments");
2337 result_error.Clear();
2339 return total_cstr_len;
2342 size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
2344 if (buf == nullptr || size == 0)
2347 size_t bytes_read = 0;
2348 uint8_t *bytes = (uint8_t *)buf;
2350 while (bytes_read < size) {
2351 const size_t curr_size = size - bytes_read;
2352 const size_t curr_bytes_read =
2353 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2354 bytes_read += curr_bytes_read;
2355 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2359 // Replace any software breakpoint opcodes that fall into this range back
2360 // into "buf" before we return
2362 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2366 uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2367 size_t integer_byte_size,
2368 uint64_t fail_value,
2371 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2373 return scalar.ULongLong(fail_value);
2377 int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2378 size_t integer_byte_size,
2379 int64_t fail_value, Error &error) {
2381 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2383 return scalar.SLongLong(fail_value);
2387 addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Error &error) {
2389 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2391 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2392 return LLDB_INVALID_ADDRESS;
2395 bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
2398 const uint32_t addr_byte_size = GetAddressByteSize();
2399 if (addr_byte_size <= 4)
2400 scalar = (uint32_t)ptr_value;
2403 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2407 size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
2409 size_t bytes_written = 0;
2410 const uint8_t *bytes = (const uint8_t *)buf;
2412 while (bytes_written < size) {
2413 const size_t curr_size = size - bytes_written;
2414 const size_t curr_bytes_written = DoWriteMemory(
2415 addr + bytes_written, bytes + bytes_written, curr_size, error);
2416 bytes_written += curr_bytes_written;
2417 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2420 return bytes_written;
2423 size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
2425 #if defined(ENABLE_MEMORY_CACHING)
2426 m_memory_cache.Flush(addr, size);
2429 if (buf == nullptr || size == 0)
2432 m_mod_id.BumpMemoryID();
2434 // We need to write any data that would go where any current software traps
2435 // (enabled software breakpoints) any software traps (breakpoints) that we
2436 // may have placed in our tasks memory.
2438 BreakpointSiteList bp_sites_in_range;
2440 if (m_breakpoint_site_list.FindInRange(addr, addr + size,
2441 bp_sites_in_range)) {
2442 // No breakpoint sites overlap
2443 if (bp_sites_in_range.IsEmpty())
2444 return WriteMemoryPrivate(addr, buf, size, error);
2446 const uint8_t *ubuf = (const uint8_t *)buf;
2447 uint64_t bytes_written = 0;
2449 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2450 &error](BreakpointSite *bp) -> void {
2452 if (error.Success()) {
2453 addr_t intersect_addr;
2454 size_t intersect_size;
2455 size_t opcode_offset;
2456 const bool intersects = bp->IntersectsRange(
2457 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2458 UNUSED_IF_ASSERT_DISABLED(intersects);
2460 assert(addr <= intersect_addr && intersect_addr < addr + size);
2461 assert(addr < intersect_addr + intersect_size &&
2462 intersect_addr + intersect_size <= addr + size);
2463 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2465 // Check for bytes before this breakpoint
2466 const addr_t curr_addr = addr + bytes_written;
2467 if (intersect_addr > curr_addr) {
2468 // There are some bytes before this breakpoint that we need to
2469 // just write to memory
2470 size_t curr_size = intersect_addr - curr_addr;
2471 size_t curr_bytes_written = WriteMemoryPrivate(
2472 curr_addr, ubuf + bytes_written, curr_size, error);
2473 bytes_written += curr_bytes_written;
2474 if (curr_bytes_written != curr_size) {
2475 // We weren't able to write all of the requested bytes, we
2476 // are done looping and will return the number of bytes that
2477 // we have written so far.
2478 if (error.Success())
2479 error.SetErrorToGenericError();
2482 // Now write any bytes that would cover up any software breakpoints
2483 // directly into the breakpoint opcode buffer
2484 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset,
2485 ubuf + bytes_written, intersect_size);
2486 bytes_written += intersect_size;
2490 if (bytes_written < size)
2491 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2492 size - bytes_written, error);
2495 return WriteMemoryPrivate(addr, buf, size, error);
2498 // Write any remaining bytes after the last breakpoint if we have any left
2499 return 0; // bytes_written;
2502 size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2503 size_t byte_size, Error &error) {
2504 if (byte_size == UINT32_MAX)
2505 byte_size = scalar.GetByteSize();
2506 if (byte_size > 0) {
2508 const size_t mem_size =
2509 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2511 return WriteMemory(addr, buf, mem_size, error);
2513 error.SetErrorString("failed to get scalar as memory data");
2515 error.SetErrorString("invalid scalar value");
2520 size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2521 bool is_signed, Scalar &scalar,
2524 if (byte_size == 0) {
2525 error.SetErrorString("byte size is zero");
2526 } else if (byte_size & (byte_size - 1)) {
2527 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2529 } else if (byte_size <= sizeof(uval)) {
2530 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2531 if (bytes_read == byte_size) {
2532 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2533 GetAddressByteSize());
2534 lldb::offset_t offset = 0;
2536 scalar = data.GetMaxU32(&offset, byte_size);
2538 scalar = data.GetMaxU64(&offset, byte_size);
2540 scalar.SignExtend(byte_size * 8);
2544 error.SetErrorStringWithFormat(
2545 "byte size of %u is too large for integer scalar type", byte_size);
2550 #define USE_ALLOCATE_MEMORY_CACHE 1
2551 addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2553 if (GetPrivateState() != eStateStopped)
2554 return LLDB_INVALID_ADDRESS;
2556 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2557 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2559 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2560 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2562 log->Printf("Process::AllocateMemory(size=%" PRIu64
2563 ", permissions=%s) => 0x%16.16" PRIx64
2564 " (m_stop_id = %u m_memory_id = %u)",
2565 (uint64_t)size, GetPermissionsAsCString(permissions),
2566 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2567 m_mod_id.GetMemoryID());
2568 return allocated_addr;
2572 addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2574 addr_t return_addr = AllocateMemory(size, permissions, error);
2575 if (error.Success()) {
2576 std::string buffer(size, 0);
2577 WriteMemory(return_addr, buffer.c_str(), size, error);
2582 bool Process::CanJIT() {
2583 if (m_can_jit == eCanJITDontKnow) {
2584 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2587 uint64_t allocated_memory = AllocateMemory(
2588 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2591 if (err.Success()) {
2592 m_can_jit = eCanJITYes;
2594 log->Printf("Process::%s pid %" PRIu64
2595 " allocation test passed, CanJIT () is true",
2596 __FUNCTION__, GetID());
2598 m_can_jit = eCanJITNo;
2600 log->Printf("Process::%s pid %" PRIu64
2601 " allocation test failed, CanJIT () is false: %s",
2602 __FUNCTION__, GetID(), err.AsCString());
2605 DeallocateMemory(allocated_memory);
2608 return m_can_jit == eCanJITYes;
2611 void Process::SetCanJIT(bool can_jit) {
2612 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2615 void Process::SetCanRunCode(bool can_run_code) {
2616 SetCanJIT(can_run_code);
2617 m_can_interpret_function_calls = can_run_code;
2620 Error Process::DeallocateMemory(addr_t ptr) {
2622 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2623 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2624 error.SetErrorStringWithFormat(
2625 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2628 error = DoDeallocateMemory(ptr);
2630 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2632 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64
2633 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2634 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2635 m_mod_id.GetMemoryID());
2640 ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2641 lldb::addr_t header_addr,
2642 size_t size_to_read) {
2643 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2645 log->Printf("Process::ReadModuleFromMemory reading %s binary from memory",
2646 file_spec.GetPath().c_str());
2648 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2651 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2652 shared_from_this(), header_addr, error, size_to_read);
2659 bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2660 uint32_t &permissions) {
2661 MemoryRegionInfo range_info;
2663 Error error(GetMemoryRegionInfo(load_addr, range_info));
2664 if (!error.Success())
2666 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2667 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2668 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2672 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2673 permissions |= lldb::ePermissionsReadable;
2675 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2676 permissions |= lldb::ePermissionsWritable;
2678 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2679 permissions |= lldb::ePermissionsExecutable;
2684 Error Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2686 error.SetErrorString("watchpoints are not supported");
2690 Error Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2692 error.SetErrorString("watchpoints are not supported");
2697 Process::WaitForProcessStopPrivate(EventSP &event_sp,
2698 const Timeout<std::micro> &timeout) {
2700 // Now wait for the process to launch and return control to us, and then
2704 state = GetStateChangedEventsPrivate(event_sp, timeout);
2706 if (StateIsStoppedState(state, false))
2709 // If state is invalid, then we timed out
2710 if (state == eStateInvalid)
2714 HandlePrivateEvent(event_sp);
2719 void Process::LoadOperatingSystemPlugin(bool flush) {
2721 m_thread_list.Clear();
2722 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
2727 Error Process::Launch(ProcessLaunchInfo &launch_info) {
2731 m_jit_loaders_ap.reset();
2732 m_system_runtime_ap.reset();
2734 m_process_input_reader.reset();
2735 m_stop_info_override_callback = nullptr;
2737 Module *exe_module = GetTarget().GetExecutableModulePointer();
2739 char local_exec_file_path[PATH_MAX];
2740 char platform_exec_file_path[PATH_MAX];
2741 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2742 sizeof(local_exec_file_path));
2743 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2744 sizeof(platform_exec_file_path));
2745 if (exe_module->GetFileSpec().Exists()) {
2746 // Install anything that might need to be installed prior to launching.
2747 // For host systems, this will do nothing, but if we are connected to a
2748 // remote platform it will install any needed binaries
2749 error = GetTarget().Install(&launch_info);
2753 if (PrivateStateThreadIsValid())
2754 PausePrivateStateThread();
2756 error = WillLaunch(exe_module);
2757 if (error.Success()) {
2758 const bool restarted = false;
2759 SetPublicState(eStateLaunching, restarted);
2760 m_should_detach = false;
2762 if (m_public_run_lock.TrySetRunning()) {
2763 // Now launch using these arguments.
2764 error = DoLaunch(exe_module, launch_info);
2766 // This shouldn't happen
2767 error.SetErrorString("failed to acquire process run lock");
2771 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2772 SetID(LLDB_INVALID_PROCESS_ID);
2773 const char *error_string = error.AsCString();
2774 if (error_string == nullptr)
2775 error_string = "launch failed";
2776 SetExitStatus(-1, error_string);
2780 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
2782 if (state == eStateInvalid || !event_sp) {
2783 // We were able to launch the process, but we failed to
2784 // catch the initial stop.
2785 error.SetErrorString("failed to catch stop after launch");
2786 SetExitStatus(0, "failed to catch stop after launch");
2788 } else if (state == eStateStopped || state == eStateCrashed) {
2791 DynamicLoader *dyld = GetDynamicLoader();
2795 GetJITLoaders().DidLaunch();
2797 SystemRuntime *system_runtime = GetSystemRuntime();
2799 system_runtime->DidLaunch();
2801 LoadOperatingSystemPlugin(false);
2803 // Note, the stop event was consumed above, but not handled. This
2805 // to give DidLaunch a chance to run. The target is either stopped
2807 // Directly set the state. This is done to prevent a stop message
2809 // of spurious output on thread status, as well as not pop a
2810 // ProcessIOHandler.
2811 SetPublicState(state, false);
2813 if (PrivateStateThreadIsValid())
2814 ResumePrivateStateThread();
2816 StartPrivateStateThread();
2818 m_stop_info_override_callback =
2819 GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
2821 // Target was stopped at entry as was intended. Need to notify the
2824 if (state == eStateStopped &&
2825 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2826 HandlePrivateEvent(event_sp);
2827 } else if (state == eStateExited) {
2828 // We exited while trying to launch somehow. Don't call DidLaunch
2830 // not likely to work, and return an invalid pid.
2831 HandlePrivateEvent(event_sp);
2836 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2837 local_exec_file_path);
2843 Error Process::LoadCore() {
2844 Error error = DoLoadCore();
2845 if (error.Success()) {
2846 ListenerSP listener_sp(
2847 Listener::MakeListener("lldb.process.load_core_listener"));
2848 HijackProcessEvents(listener_sp);
2850 if (PrivateStateThreadIsValid())
2851 ResumePrivateStateThread();
2853 StartPrivateStateThread();
2855 DynamicLoader *dyld = GetDynamicLoader();
2859 GetJITLoaders().DidAttach();
2861 SystemRuntime *system_runtime = GetSystemRuntime();
2863 system_runtime->DidAttach();
2865 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
2866 // We successfully loaded a core file, now pretend we stopped so we can
2867 // show all of the threads in the core file and explore the crashed
2869 SetPrivateState(eStateStopped);
2871 // Wait indefinitely for a stopped event since we just posted one above...
2872 lldb::EventSP event_sp;
2873 listener_sp->GetEvent(event_sp, llvm::None);
2874 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2876 if (!StateIsStoppedState(state, false)) {
2877 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2879 log->Printf("Process::Halt() failed to stop, state is: %s",
2880 StateAsCString(state));
2881 error.SetErrorString(
2882 "Did not get stopped event after loading the core file.");
2884 RestoreProcessEvents();
2889 DynamicLoader *Process::GetDynamicLoader() {
2891 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, nullptr));
2892 return m_dyld_ap.get();
2895 const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); }
2897 JITLoaderList &Process::GetJITLoaders() {
2898 if (!m_jit_loaders_ap) {
2899 m_jit_loaders_ap.reset(new JITLoaderList());
2900 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2902 return *m_jit_loaders_ap;
2905 SystemRuntime *Process::GetSystemRuntime() {
2906 if (!m_system_runtime_ap)
2907 m_system_runtime_ap.reset(SystemRuntime::FindPlugin(this));
2908 return m_system_runtime_ap.get();
2911 Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2912 uint32_t exec_count)
2913 : NextEventAction(process), m_exec_count(exec_count) {
2914 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2917 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2918 __FUNCTION__, static_cast<void *>(process), exec_count);
2921 Process::NextEventAction::EventActionResult
2922 Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2923 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2925 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2928 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2929 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2932 case eStateAttaching:
2933 return eEventActionSuccess;
2936 case eStateConnected:
2937 return eEventActionRetry;
2941 // During attach, prior to sending the eStateStopped event,
2942 // lldb_private::Process subclasses must set the new process ID.
2943 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2944 // We don't want these events to be reported, so go set the ShouldReportStop
2946 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2948 if (m_exec_count > 0) {
2952 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2953 "remaining exec count to %" PRIu32 ", requesting resume",
2954 __FUNCTION__, StateAsCString(state), m_exec_count);
2957 return eEventActionRetry;
2960 log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2961 "execs expected to start, continuing with attach",
2962 __FUNCTION__, StateAsCString(state));
2964 m_process->CompleteAttach();
2965 return eEventActionSuccess;
2975 m_exit_string.assign("No valid Process");
2976 return eEventActionExit;
2979 Process::NextEventAction::EventActionResult
2980 Process::AttachCompletionHandler::HandleBeingInterrupted() {
2981 return eEventActionSuccess;
2984 const char *Process::AttachCompletionHandler::GetExitString() {
2985 return m_exit_string.c_str();
2988 ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2990 return m_listener_sp;
2992 return debugger.GetListener();
2995 Error Process::Attach(ProcessAttachInfo &attach_info) {
2997 m_process_input_reader.reset();
2999 m_jit_loaders_ap.reset();
3000 m_system_runtime_ap.reset();
3002 m_stop_info_override_callback = nullptr;
3004 lldb::pid_t attach_pid = attach_info.GetProcessID();
3006 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
3007 char process_name[PATH_MAX];
3009 if (attach_info.GetExecutableFile().GetPath(process_name,
3010 sizeof(process_name))) {
3011 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3013 if (wait_for_launch) {
3014 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3015 if (error.Success()) {
3016 if (m_public_run_lock.TrySetRunning()) {
3017 m_should_detach = true;
3018 const bool restarted = false;
3019 SetPublicState(eStateAttaching, restarted);
3020 // Now attach using these arguments.
3021 error = DoAttachToProcessWithName(process_name, attach_info);
3023 // This shouldn't happen
3024 error.SetErrorString("failed to acquire process run lock");
3028 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3029 SetID(LLDB_INVALID_PROCESS_ID);
3030 if (error.AsCString() == nullptr)
3031 error.SetErrorString("attach failed");
3033 SetExitStatus(-1, error.AsCString());
3036 SetNextEventAction(new Process::AttachCompletionHandler(
3037 this, attach_info.GetResumeCount()));
3038 StartPrivateStateThread();
3043 ProcessInstanceInfoList process_infos;
3044 PlatformSP platform_sp(GetTarget().GetPlatform());
3047 ProcessInstanceInfoMatch match_info;
3048 match_info.GetProcessInfo() = attach_info;
3049 match_info.SetNameMatchType(eNameMatchEquals);
3050 platform_sp->FindProcesses(match_info, process_infos);
3051 const uint32_t num_matches = process_infos.GetSize();
3052 if (num_matches == 1) {
3053 attach_pid = process_infos.GetProcessIDAtIndex(0);
3054 // Fall through and attach using the above process ID
3056 match_info.GetProcessInfo().GetExecutableFile().GetPath(
3057 process_name, sizeof(process_name));
3058 if (num_matches > 1) {
3060 ProcessInstanceInfo::DumpTableHeader(s, platform_sp.get(), true,
3062 for (size_t i = 0; i < num_matches; i++) {
3063 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
3064 s, platform_sp.get(), true, false);
3066 error.SetErrorStringWithFormat(
3067 "more than one process named %s:\n%s", process_name,
3070 error.SetErrorStringWithFormat(
3071 "could not find a process named %s", process_name);
3074 error.SetErrorString(
3075 "invalid platform, can't find processes by name");
3080 error.SetErrorString("invalid process name");
3084 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
3085 error = WillAttachToProcessWithID(attach_pid);
3086 if (error.Success()) {
3088 if (m_public_run_lock.TrySetRunning()) {
3089 // Now attach using these arguments.
3090 m_should_detach = true;
3091 const bool restarted = false;
3092 SetPublicState(eStateAttaching, restarted);
3093 error = DoAttachToProcessWithID(attach_pid, attach_info);
3095 // This shouldn't happen
3096 error.SetErrorString("failed to acquire process run lock");
3099 if (error.Success()) {
3100 SetNextEventAction(new Process::AttachCompletionHandler(
3101 this, attach_info.GetResumeCount()));
3102 StartPrivateStateThread();
3104 if (GetID() != LLDB_INVALID_PROCESS_ID)
3105 SetID(LLDB_INVALID_PROCESS_ID);
3107 const char *error_string = error.AsCString();
3108 if (error_string == nullptr)
3109 error_string = "attach failed";
3111 SetExitStatus(-1, error_string);
3118 void Process::CompleteAttach() {
3119 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3120 LIBLLDB_LOG_TARGET));
3122 log->Printf("Process::%s()", __FUNCTION__);
3124 // Let the process subclass figure out at much as it can about the process
3125 // before we go looking for a dynamic loader plug-in.
3126 ArchSpec process_arch;
3127 DidAttach(process_arch);
3129 if (process_arch.IsValid()) {
3130 GetTarget().SetArchitecture(process_arch);
3132 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
3133 log->Printf("Process::%s replacing process architecture with DidAttach() "
3135 __FUNCTION__, triple_str ? triple_str : "<null>");
3139 // We just attached. If we have a platform, ask it for the process
3140 // architecture, and if it isn't
3141 // the same as the one we've already set, switch architectures.
3142 PlatformSP platform_sp(GetTarget().GetPlatform());
3143 assert(platform_sp);
3145 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3146 if (target_arch.IsValid() &&
3147 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
3148 ArchSpec platform_arch;
3150 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
3152 GetTarget().SetPlatform(platform_sp);
3153 GetTarget().SetArchitecture(platform_arch);
3155 log->Printf("Process::%s switching platform to %s and architecture "
3156 "to %s based on info from attach",
3157 __FUNCTION__, platform_sp->GetName().AsCString(""),
3158 platform_arch.GetTriple().getTriple().c_str());
3160 } else if (!process_arch.IsValid()) {
3161 ProcessInstanceInfo process_info;
3162 GetProcessInfo(process_info);
3163 const ArchSpec &process_arch = process_info.GetArchitecture();
3164 if (process_arch.IsValid() &&
3165 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
3166 GetTarget().SetArchitecture(process_arch);
3168 log->Printf("Process::%s switching architecture to %s based on info "
3169 "the platform retrieved for pid %" PRIu64,
3171 process_arch.GetTriple().getTriple().c_str(), GetID());
3176 // We have completed the attach, now it is time to find the dynamic loader
3178 DynamicLoader *dyld = GetDynamicLoader();
3182 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3183 log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
3184 "executable is %s (using %s plugin)",
3186 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3188 dyld->GetPluginName().AsCString("<unnamed>"));
3192 GetJITLoaders().DidAttach();
3194 SystemRuntime *system_runtime = GetSystemRuntime();
3195 if (system_runtime) {
3196 system_runtime->DidAttach();
3198 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3199 log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
3200 "executable is %s (using %s plugin)",
3202 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3204 system_runtime->GetPluginName().AsCString("<unnamed>"));
3208 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
3209 // Figure out which one is the executable, and set that in our target:
3210 const ModuleList &target_modules = GetTarget().GetImages();
3211 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3212 size_t num_modules = target_modules.GetSize();
3213 ModuleSP new_executable_module_sp;
3215 for (size_t i = 0; i < num_modules; i++) {
3216 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3217 if (module_sp && module_sp->IsExecutable()) {
3218 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3219 new_executable_module_sp = module_sp;
3223 if (new_executable_module_sp) {
3224 GetTarget().SetExecutableModule(new_executable_module_sp, false);
3226 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3228 "Process::%s after looping through modules, target executable is %s",
3230 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3235 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
3238 Error Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
3240 m_process_input_reader.reset();
3242 // Find the process and its architecture. Make sure it matches the
3243 // architecture of the current Target, and if not adjust it.
3245 Error error(DoConnectRemote(strm, remote_url));
3246 if (error.Success()) {
3247 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3249 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
3251 if (state == eStateStopped || state == eStateCrashed) {
3252 // If we attached and actually have a process on the other end, then
3253 // this ended up being the equivalent of an attach.
3256 // This delays passing the stopped event to listeners till
3257 // CompleteAttach gets a chance to complete...
3258 HandlePrivateEvent(event_sp);
3262 if (PrivateStateThreadIsValid())
3263 ResumePrivateStateThread();
3265 StartPrivateStateThread();
3270 Error Process::PrivateResume() {
3271 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3274 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3275 "private state: %s",
3276 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3277 StateAsCString(m_private_state.GetValue()));
3279 Error 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 Error Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3325 if (!StateIsRunningState(m_public_state.GetValue()))
3326 return Error("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 Error("Halt timed out. State = %s", StateAsCString(GetState()));
3360 BroadcastEvent(event_sp);
3365 Error 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) {
3413 return Error("Attempt to stop the target in order to detach timed out. "
3415 StateAsCString(GetState()));
3422 Error Process::Detach(bool keep_stopped) {
3423 EventSP exit_event_sp;
3425 m_destroy_in_process = true;
3427 error = WillDetach();
3429 if (error.Success()) {
3430 if (DetachRequiresHalt()) {
3431 error = StopForDestroyOrDetach(exit_event_sp);
3432 if (!error.Success()) {
3433 m_destroy_in_process = false;
3435 } else if (exit_event_sp) {
3436 // We shouldn't need to do anything else here. There's no process left
3437 // to detach from...
3438 StopPrivateStateThread();
3439 m_destroy_in_process = false;
3444 m_thread_list.DiscardThreadPlans();
3445 DisableAllBreakpointSites();
3447 error = DoDetach(keep_stopped);
3448 if (error.Success()) {
3450 StopPrivateStateThread();
3455 m_destroy_in_process = false;
3457 // If we exited when we were waiting for a process to stop, then
3458 // forward the event here so we don't lose the event
3459 if (exit_event_sp) {
3460 // Directly broadcast our exited event because we shut down our
3461 // private state thread above
3462 BroadcastEvent(exit_event_sp);
3465 // If we have been interrupted (to kill us) in the middle of running, we may
3466 // not end up propagating
3467 // the last events through the event system, in which case we might strand the
3468 // write lock. Unlock
3469 // it here so when we do to tear down the process we don't get an error
3470 // destroying the lock.
3472 m_public_run_lock.SetStopped();
3476 Error Process::Destroy(bool force_kill) {
3478 // Tell ourselves we are in the process of destroying the process, so that we
3479 // don't do any unnecessary work
3480 // that might hinder the destruction. Remember to set this back to false when
3481 // we are done. That way if the attempt
3482 // failed and the process stays around for some reason it won't be in a
3486 m_should_detach = false;
3488 if (GetShouldDetach()) {
3489 // FIXME: This will have to be a process setting:
3490 bool keep_stopped = false;
3491 Detach(keep_stopped);
3494 m_destroy_in_process = true;
3496 Error error(WillDestroy());
3497 if (error.Success()) {
3498 EventSP exit_event_sp;
3499 if (DestroyRequiresHalt()) {
3500 error = StopForDestroyOrDetach(exit_event_sp);
3503 if (m_public_state.GetValue() != eStateRunning) {
3504 // Ditch all thread plans, and remove all our breakpoints: in case we have
3505 // to restart the target to
3506 // kill it, we don't want it hitting a breakpoint...
3507 // Only do this if we've stopped, however, since if we didn't manage to
3508 // halt it above, then
3509 // we're not going to have much luck doing this now.
3510 m_thread_list.DiscardThreadPlans();
3511 DisableAllBreakpointSites();
3514 error = DoDestroy();
3515 if (error.Success()) {
3517 StopPrivateStateThread();
3519 m_stdio_communication.Disconnect();
3520 m_stdio_communication.StopReadThread();
3521 m_stdin_forward = false;
3523 if (m_process_input_reader) {
3524 m_process_input_reader->SetIsDone(true);
3525 m_process_input_reader->Cancel();
3526 m_process_input_reader.reset();
3529 // If we exited when we were waiting for a process to stop, then
3530 // forward the event here so we don't lose the event
3531 if (exit_event_sp) {
3532 // Directly broadcast our exited event because we shut down our
3533 // private state thread above
3534 BroadcastEvent(exit_event_sp);
3537 // If we have been interrupted (to kill us) in the middle of running, we may
3538 // not end up propagating
3539 // the last events through the event system, in which case we might strand
3540 // the write lock. Unlock
3541 // it here so when we do to tear down the process we don't get an error
3542 // destroying the lock.
3543 m_public_run_lock.SetStopped();
3546 m_destroy_in_process = false;
3551 Error Process::Signal(int signal) {
3552 Error error(WillSignal());
3553 if (error.Success()) {
3554 error = DoSignal(signal);
3555 if (error.Success())
3561 void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3562 assert(signals_sp && "null signals_sp");
3563 m_unix_signals_sp = signals_sp;
3566 const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3567 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3568 return m_unix_signals_sp;
3571 lldb::ByteOrder Process::GetByteOrder() const {
3572 return GetTarget().GetArchitecture().GetByteOrder();
3575 uint32_t Process::GetAddressByteSize() const {
3576 return GetTarget().GetArchitecture().GetAddressByteSize();
3579 bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3580 const StateType state =
3581 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3582 bool return_value = true;
3583 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3584 LIBLLDB_LOG_PROCESS));
3587 case eStateDetached:
3589 case eStateUnloaded:
3590 m_stdio_communication.SynchronizeWithReadThread();
3591 m_stdio_communication.Disconnect();
3592 m_stdio_communication.StopReadThread();
3593 m_stdin_forward = false;
3596 case eStateConnected:
3597 case eStateAttaching:
3598 case eStateLaunching:
3599 // These events indicate changes in the state of the debugging session,
3600 // always report them.
3601 return_value = true;
3604 // We stopped for no apparent reason, don't report it.
3605 return_value = false;
3608 case eStateStepping:
3609 // If we've started the target running, we handle the cases where we
3610 // are already running and where there is a transition from stopped to
3611 // running differently.
3612 // running -> running: Automatically suppress extra running events
3613 // stopped -> running: Report except when there is one or more no votes
3614 // and no yes votes.
3615 SynchronouslyNotifyStateChanged(state);
3616 if (m_force_next_event_delivery)
3617 return_value = true;
3619 switch (m_last_broadcast_state) {
3621 case eStateStepping:
3622 // We always suppress multiple runnings with no PUBLIC stop in between.
3623 return_value = false;
3626 // TODO: make this work correctly. For now always report
3627 // run if we aren't running so we don't miss any running
3628 // events. If I run the lldb/test/thread/a.out file and
3629 // break at main.cpp:58, run and hit the breakpoints on
3630 // multiple threads, then somehow during the stepping over
3631 // of all breakpoints no run gets reported.
3633 // This is a transition from stop to run.
3634 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3636 case eVoteNoOpinion:
3637 return_value = true;
3640 return_value = false;
3649 case eStateSuspended:
3650 // We've stopped. First see if we're going to restart the target.
3651 // If we are going to stop, then we always broadcast the event.
3652 // If we aren't going to stop, let the thread plans decide if we're going to
3653 // report this event.
3654 // If no thread has an opinion, we don't report it.
3656 m_stdio_communication.SynchronizeWithReadThread();
3657 RefreshStateAfterStop();
3658 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3660 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3661 "interrupt, state: %s",
3662 static_cast<void *>(event_ptr), StateAsCString(state));
3663 // Even though we know we are going to stop, we should let the threads
3664 // have a look at the stop,
3665 // so they can properly set their state.
3666 m_thread_list.ShouldStop(event_ptr);
3667 return_value = true;
3669 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3670 bool should_resume = false;
3672 // It makes no sense to ask "ShouldStop" if we've already been
3674 // Asking the thread list is also not likely to go well, since we are
3676 // So in that case just report the event.
3679 should_resume = !m_thread_list.ShouldStop(event_ptr);
3681 if (was_restarted || should_resume || m_resume_requested) {
3682 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3684 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3685 "%s was_restarted: %i stop_vote: %d.",
3686 should_resume, StateAsCString(state), was_restarted,
3689 switch (stop_vote) {
3691 return_value = true;
3693 case eVoteNoOpinion:
3695 return_value = false;
3699 if (!was_restarted) {
3701 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3703 static_cast<void *>(event_ptr), StateAsCString(state));
3704 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3708 return_value = true;
3709 SynchronouslyNotifyStateChanged(state);
3715 // Forcing the next event delivery is a one shot deal. So reset it here.
3716 m_force_next_event_delivery = false;
3718 // We do some coalescing of events (for instance two consecutive running
3719 // events get coalesced.)
3720 // But we only coalesce against events we actually broadcast. So we use
3721 // m_last_broadcast_state
3722 // to track that. NB - you can't use "m_public_state.GetValue()" for that
3723 // purpose, as was originally done,
3724 // because the PublicState reflects the last event pulled off the queue, and
3725 // there may be several
3726 // events stacked up on the queue unserviced. So the PublicState may not
3727 // reflect the last broadcasted event
3728 // yet. m_last_broadcast_state gets updated here.
3731 m_last_broadcast_state = state;
3734 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3735 "broadcast state: %s - %s",
3736 static_cast<void *>(event_ptr), StateAsCString(state),
3737 StateAsCString(m_last_broadcast_state),
3738 return_value ? "YES" : "NO");
3739 return return_value;
3742 bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3743 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3745 bool already_running = PrivateStateThreadIsValid();
3747 log->Printf("Process::%s()%s ", __FUNCTION__,
3748 already_running ? " already running"
3749 : " starting private state thread");
3751 if (!is_secondary_thread && already_running)
3754 // Create a thread that watches our internal state and controls which
3755 // events make it to clients (into the DCProcess event queue).
3756 char thread_name[1024];
3758 if (HostInfo::GetMaxThreadNameLength() <= 30) {
3759 // On platforms with abbreviated thread name lengths, choose thread names
3760 // that fit within the limit.
3761 if (already_running)
3762 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3764 snprintf(thread_name, sizeof(thread_name), "intern-state");
3766 if (already_running)
3767 snprintf(thread_name, sizeof(thread_name),
3768 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3771 snprintf(thread_name, sizeof(thread_name),
3772 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3775 // Create the private state thread, and start it running.
3776 PrivateStateThreadArgs *args_ptr =
3777 new PrivateStateThreadArgs(this, is_secondary_thread);
3778 m_private_state_thread =
3779 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3780 (void *)args_ptr, nullptr, 8 * 1024 * 1024);
3781 if (m_private_state_thread.IsJoinable()) {
3782 ResumePrivateStateThread();
3788 void Process::PausePrivateStateThread() {
3789 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3792 void Process::ResumePrivateStateThread() {
3793 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3796 void Process::StopPrivateStateThread() {
3797 if (m_private_state_thread.IsJoinable())
3798 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3800 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3803 "Went to stop the private state thread, but it was already invalid.");
3807 void Process::ControlPrivateStateThread(uint32_t signal) {
3808 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3810 assert(signal == eBroadcastInternalStateControlStop ||
3811 signal == eBroadcastInternalStateControlPause ||
3812 signal == eBroadcastInternalStateControlResume);
3815 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3817 // Signal the private state thread
3818 if (m_private_state_thread.IsJoinable()) {
3819 // Broadcast the event.
3820 // It is important to do this outside of the if below, because
3821 // it's possible that the thread state is invalid but that the
3822 // thread is waiting on a control event instead of simply being
3823 // on its way out (this should not happen, but it apparently can).
3825 log->Printf("Sending control event of type: %d.", signal);
3826 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3827 m_private_state_control_broadcaster.BroadcastEvent(signal,
3830 // Wait for the event receipt or for the private state thread to exit
3831 bool receipt_received = false;
3832 if (PrivateStateThreadIsValid()) {
3833 while (!receipt_received) {
3834 bool timed_out = false;
3835 // Check for a receipt for 2 seconds and then check if the private state
3836 // thread is still around.
3837 receipt_received = event_receipt_sp->WaitForEventReceived(
3838 std::chrono::seconds(2), &timed_out);
3839 if (!receipt_received) {
3840 // Check if the private state thread is still around. If it isn't then
3841 // we are done waiting
3842 if (!PrivateStateThreadIsValid())
3843 break; // Private state thread exited or is exiting, we are done
3848 if (signal == eBroadcastInternalStateControlStop) {
3849 thread_result_t result = NULL;
3850 m_private_state_thread.Join(&result);
3851 m_private_state_thread.Reset();
3856 "Private state thread already dead, no need to signal it to stop.");
3860 void Process::SendAsyncInterrupt() {
3861 if (PrivateStateThreadIsValid())
3862 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3865 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3868 void Process::HandlePrivateEvent(EventSP &event_sp) {
3869 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3870 m_resume_requested = false;
3872 const StateType new_state =
3873 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3875 // First check to see if anybody wants a shot at this event:
3876 if (m_next_event_action_ap) {
3877 NextEventAction::EventActionResult action_result =
3878 m_next_event_action_ap->PerformAction(event_sp);
3880 log->Printf("Ran next event action, result was %d.", action_result);
3882 switch (action_result) {
3883 case NextEventAction::eEventActionSuccess:
3884 SetNextEventAction(nullptr);
3887 case NextEventAction::eEventActionRetry:
3890 case NextEventAction::eEventActionExit:
3891 // Handle Exiting Here. If we already got an exited event,
3892 // we should just propagate it. Otherwise, swallow this event,
3893 // and set our state to exit so the next event will kill us.
3894 if (new_state != eStateExited) {
3895 // FIXME: should cons up an exited event, and discard this one.
3896 SetExitStatus(0, m_next_event_action_ap->GetExitString());
3897 SetNextEventAction(nullptr);
3900 SetNextEventAction(nullptr);
3905 // See if we should broadcast this state to external clients?
3906 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3908 if (should_broadcast) {
3909 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3911 log->Printf("Process::%s (pid = %" PRIu64
3912 ") broadcasting new state %s (old state %s) to %s",
3913 __FUNCTION__, GetID(), StateAsCString(new_state),
3914 StateAsCString(GetState()),
3915 is_hijacked ? "hijacked" : "public");
3917 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3918 if (StateIsRunningState(new_state)) {
3919 // Only push the input handler if we aren't fowarding events,
3920 // as this means the curses GUI is in use...
3921 // Or don't push it if we are launching since it will come up stopped.
3922 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3923 new_state != eStateLaunching && new_state != eStateAttaching) {
3924 PushProcessIOHandler();
3925 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3928 log->Printf("Process::%s updated m_iohandler_sync to %d",
3929 __FUNCTION__, m_iohandler_sync.GetValue());
3931 } else if (StateIsStoppedState(new_state, false)) {
3932 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
3933 // If the lldb_private::Debugger is handling the events, we don't
3934 // want to pop the process IOHandler here, we want to do it when
3935 // we receive the stopped event so we can carefully control when
3936 // the process IOHandler is popped because when we stop we want to
3937 // display some text stating how and why we stopped, then maybe some
3938 // process/thread/frame info, and then we want the "(lldb) " prompt
3939 // to show up. If we pop the process IOHandler here, then we will
3940 // cause the command interpreter to become the top IOHandler after
3941 // the process pops off and it will update its prompt right away...
3942 // See the Debugger.cpp file where it calls the function as
3943 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3944 // Otherwise we end up getting overlapping "(lldb) " prompts and
3947 // If we aren't handling the events in the debugger (which is indicated
3948 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
3949 // are hijacked, then we always pop the process IO handler manually.
3950 // Hijacking happens when the internal process state thread is running
3951 // thread plans, or when commands want to run in synchronous mode
3952 // and they call "process->WaitForProcessToStop()". An example of
3954 // that will hijack the events is a simple expression:
3956 // (lldb) expr (int)puts("hello")
3958 // This will cause the internal process state thread to resume and halt
3959 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3960 // events) and we do need the IO handler to be pushed and popped
3963 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3964 PopProcessIOHandler();
3968 BroadcastEvent(event_sp);
3972 "Process::%s (pid = %" PRIu64
3973 ") suppressing state %s (old state %s): should_broadcast == false",
3974 __FUNCTION__, GetID(), StateAsCString(new_state),
3975 StateAsCString(GetState()));
3980 Error Process::HaltPrivate() {
3982 Error error(WillHalt());
3986 // Ask the process subclass to actually halt our process
3988 error = DoHalt(caused_stop);
3994 thread_result_t Process::PrivateStateThread(void *arg) {
3995 std::unique_ptr<PrivateStateThreadArgs> args_up(
3996 static_cast<PrivateStateThreadArgs *>(arg));
3997 thread_result_t result =
3998 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
4002 thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
4003 bool control_only = true;
4005 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4007 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4008 __FUNCTION__, static_cast<void *>(this), GetID());
4010 bool exit_now = false;
4011 bool interrupt_requested = false;
4014 GetEventsPrivate(event_sp, llvm::None, control_only);
4015 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
4017 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4018 ") got a control event: %d",
4019 __FUNCTION__, static_cast<void *>(this), GetID(),
4020 event_sp->GetType());
4022 switch (event_sp->GetType()) {
4023 case eBroadcastInternalStateControlStop:
4025 break; // doing any internal state management below
4027 case eBroadcastInternalStateControlPause:
4028 control_only = true;
4031 case eBroadcastInternalStateControlResume:
4032 control_only = false;
4037 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
4038 if (m_public_state.GetValue() == eStateAttaching) {
4040 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4041 ") woke up with an interrupt while attaching - "
4042 "forwarding interrupt.",
4043 __FUNCTION__, static_cast<void *>(this), GetID());
4044 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
4045 } else if (StateIsRunningState(m_last_broadcast_state)) {
4047 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4048 ") woke up with an interrupt - Halting.",
4049 __FUNCTION__, static_cast<void *>(this), GetID());
4050 Error error = HaltPrivate();
4051 if (error.Fail() && log)
4052 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4053 ") failed to halt the process: %s",
4054 __FUNCTION__, static_cast<void *>(this), GetID(),
4056 // Halt should generate a stopped event. Make a note of the fact that we
4058 // doing the interrupt, so we can set the interrupted flag after we
4060 // event. We deliberately set this to true even if HaltPrivate failed,
4062 // can interrupt on the next natural stop.
4063 interrupt_requested = true;
4065 // This can happen when someone (e.g. Process::Halt) sees that we are
4067 // sends an interrupt request, but the process actually stops before we
4069 // it. In that case, we can just ignore the request. We use
4070 // m_last_broadcast_state, because the Stopped event may not have been
4072 // the event queue yet, which is when the public state gets updated.
4075 "Process::%s ignoring interrupt as we have already stopped.",
4081 const StateType internal_state =
4082 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4084 if (internal_state != eStateInvalid) {
4085 if (m_clear_thread_plans_on_stop &&
4086 StateIsStoppedState(internal_state, true)) {
4087 m_clear_thread_plans_on_stop = false;
4088 m_thread_list.DiscardThreadPlans();
4091 if (interrupt_requested) {
4092 if (StateIsStoppedState(internal_state, true)) {
4093 // We requested the interrupt, so mark this as such in the stop event
4095 // clients can tell an interrupted process from a natural stop
4096 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
4097 interrupt_requested = false;
4099 log->Printf("Process::%s interrupt_requested, but a non-stopped "
4100 "state '%s' received.",
4101 __FUNCTION__, StateAsCString(internal_state));
4105 HandlePrivateEvent(event_sp);
4108 if (internal_state == eStateInvalid || internal_state == eStateExited ||
4109 internal_state == eStateDetached) {
4111 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4112 ") about to exit with internal state %s...",
4113 __FUNCTION__, static_cast<void *>(this), GetID(),
4114 StateAsCString(internal_state));
4120 // Verify log is still enabled before attempting to write to it...
4122 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4123 __FUNCTION__, static_cast<void *>(this), GetID());
4125 // If we are a secondary thread, then the primary thread we are working for
4126 // will have already
4127 // acquired the public_run_lock, and isn't done with what it was doing yet, so
4129 // try to change it on the way out.
4130 if (!is_secondary_thread)
4131 m_public_run_lock.SetStopped();
4135 //------------------------------------------------------------------
4136 // Process Event Data
4137 //------------------------------------------------------------------
4139 Process::ProcessEventData::ProcessEventData()
4140 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
4141 m_update_state(0), m_interrupted(false) {}
4143 Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
4145 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
4146 m_update_state(0), m_interrupted(false) {
4148 m_process_wp = process_sp;
4151 Process::ProcessEventData::~ProcessEventData() = default;
4153 const ConstString &Process::ProcessEventData::GetFlavorString() {
4154 static ConstString g_flavor("Process::ProcessEventData");
4158 const ConstString &Process::ProcessEventData::GetFlavor() const {
4159 return ProcessEventData::GetFlavorString();
4162 void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
4163 ProcessSP process_sp(m_process_wp.lock());
4168 // This function gets called twice for each event, once when the event gets
4170 // off of the private process event queue, and then any number of times, first
4171 // when it gets pulled off of
4172 // the public event queue, then other times when we're pretending that this is
4173 // where we stopped at the
4174 // end of expression evaluation. m_update_state is used to distinguish these
4175 // three cases; it is 0 when we're just pulling it off for private handling,
4176 // and > 1 for expression evaluation, and we don't want to do the breakpoint
4177 // command handling then.
4178 if (m_update_state != 1)
4181 process_sp->SetPublicState(
4182 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4184 if (m_state == eStateStopped && !m_restarted) {
4185 // Let process subclasses know we are about to do a public stop and
4186 // do anything they might need to in order to speed up register and
4188 process_sp->WillPublicStop();
4191 // If this is a halt event, even if the halt stopped with some reason other
4192 // than a plain interrupt (e.g. we had
4193 // already stopped for a breakpoint when the halt request came through) don't
4194 // do the StopInfo actions, as they may
4195 // end up restarting the process.
4199 // If we're stopped and haven't restarted, then do the StopInfo actions here:
4200 if (m_state == eStateStopped && !m_restarted) {
4201 ThreadList &curr_thread_list = process_sp->GetThreadList();
4202 uint32_t num_threads = curr_thread_list.GetSize();
4205 // The actions might change one of the thread's stop_info's opinions about
4206 // whether we should
4207 // stop the process, so we need to query that as we go.
4209 // One other complication here, is that we try to catch any case where the
4210 // target has run (except for expressions)
4211 // and immediately exit, but if we get that wrong (which is possible) then
4212 // the thread list might have changed, and
4213 // that would cause our iteration here to crash. We could make a copy of
4214 // the thread list, but we'd really like
4215 // to also know if it has changed at all, so we make up a vector of the
4216 // thread ID's and check what we get back
4217 // against this list & bag out if anything differs.
4218 std::vector<uint32_t> thread_index_array(num_threads);
4219 for (idx = 0; idx < num_threads; ++idx)
4220 thread_index_array[idx] =
4221 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4223 // Use this to track whether we should continue from here. We will only
4224 // continue the target running if
4225 // no thread says we should stop. Of course if some thread's PerformAction
4226 // actually sets the target running,
4227 // then it doesn't matter what the other threads say...
4229 bool still_should_stop = false;
4231 // Sometimes - for instance if we have a bug in the stub we are talking to,
4232 // we stop but no thread has a
4233 // valid stop reason. In that case we should just stop, because we have no
4234 // way of telling what the right
4235 // thing to do is, and it's better to let the user decide than continue
4236 // behind their backs.
4238 bool does_anybody_have_an_opinion = false;
4240 for (idx = 0; idx < num_threads; ++idx) {
4241 curr_thread_list = process_sp->GetThreadList();
4242 if (curr_thread_list.GetSize() != num_threads) {
4243 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4244 LIBLLDB_LOG_PROCESS));
4247 "Number of threads changed from %u to %u while processing event.",
4248 num_threads, curr_thread_list.GetSize());
4252 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4254 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4255 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4256 LIBLLDB_LOG_PROCESS));
4258 log->Printf("The thread at position %u changed from %u to %u while "
4259 "processing event.",
4260 idx, thread_index_array[idx], thread_sp->GetIndexID());
4264 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4265 if (stop_info_sp && stop_info_sp->IsValid()) {
4266 does_anybody_have_an_opinion = true;
4267 bool this_thread_wants_to_stop;
4268 if (stop_info_sp->GetOverrideShouldStop()) {
4269 this_thread_wants_to_stop =
4270 stop_info_sp->GetOverriddenShouldStopValue();
4272 stop_info_sp->PerformAction(event_ptr);
4273 // The stop action might restart the target. If it does, then we want
4274 // to mark that in the
4275 // event so that whoever is receiving it will know to wait for the
4276 // running event and reflect
4277 // that state appropriately.
4278 // We also need to stop processing actions, since they aren't
4279 // expecting the target to be running.
4281 // FIXME: we might have run.
4282 if (stop_info_sp->HasTargetRunSinceMe()) {
4287 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4290 if (!still_should_stop)
4291 still_should_stop = this_thread_wants_to_stop;
4295 if (!GetRestarted()) {
4296 if (!still_should_stop && does_anybody_have_an_opinion) {
4297 // We've been asked to continue, so do that here.
4299 // Use the public resume method here, since this is just
4300 // extending a public resume.
4301 process_sp->PrivateResume();
4303 // If we didn't restart, run the Stop Hooks here:
4304 // They might also restart the target, so watch for that.
4305 process_sp->GetTarget().RunStopHooks();
4306 if (process_sp->GetPrivateState() == eStateRunning)
4313 void Process::ProcessEventData::Dump(Stream *s) const {
4314 ProcessSP process_sp(m_process_wp.lock());
4317 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4318 static_cast<void *>(process_sp.get()), process_sp->GetID());
4320 s->PutCString(" process = NULL, ");
4322 s->Printf("state = %s", StateAsCString(GetState()));
4325 const Process::ProcessEventData *
4326 Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4328 const EventData *event_data = event_ptr->GetData();
4330 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4331 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4337 Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4338 ProcessSP process_sp;
4339 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4341 process_sp = data->GetProcessSP();
4345 StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4346 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4347 if (data == nullptr)
4348 return eStateInvalid;
4350 return data->GetState();
4353 bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4354 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4355 if (data == nullptr)
4358 return data->GetRestarted();
4361 void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4363 ProcessEventData *data =
4364 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4365 if (data != nullptr)
4366 data->SetRestarted(new_value);
4370 Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4371 ProcessEventData *data =
4372 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4373 if (data != nullptr)
4374 return data->GetNumRestartedReasons();
4380 Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4382 ProcessEventData *data =
4383 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4384 if (data != nullptr)
4385 return data->GetRestartedReasonAtIndex(idx);
4390 void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4391 const char *reason) {
4392 ProcessEventData *data =
4393 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4394 if (data != nullptr)
4395 data->AddRestartedReason(reason);
4398 bool Process::ProcessEventData::GetInterruptedFromEvent(
4399 const Event *event_ptr) {
4400 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4401 if (data == nullptr)
4404 return data->GetInterrupted();
4407 void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4409 ProcessEventData *data =
4410 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4411 if (data != nullptr)
4412 data->SetInterrupted(new_value);
4415 bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4416 ProcessEventData *data =
4417 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4419 data->SetUpdateStateOnRemoval();
4425 lldb::TargetSP Process::CalculateTarget() { return m_target_sp.lock(); }
4427 void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4428 exe_ctx.SetTargetPtr(&GetTarget());
4429 exe_ctx.SetProcessPtr(this);
4430 exe_ctx.SetThreadPtr(nullptr);
4431 exe_ctx.SetFramePtr(nullptr);
4435 // Process::ListProcessesMatchingName (const char *name, StringList &matches,
4436 // std::vector<lldb::pid_t> &pids)
4442 // Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4444 // return Host::GetArchSpecForExistingProcess (pid);
4448 // Process::GetArchSpecForExistingProcess (const char *process_name)
4450 // return Host::GetArchSpecForExistingProcess (process_name);
4453 void Process::AppendSTDOUT(const char *s, size_t len) {
4454 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4455 m_stdout_data.append(s, len);
4456 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4457 new ProcessEventData(shared_from_this(), GetState()));
4460 void Process::AppendSTDERR(const char *s, size_t len) {
4461 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4462 m_stderr_data.append(s, len);
4463 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4464 new ProcessEventData(shared_from_this(), GetState()));
4467 void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4468 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4469 m_profile_data.push_back(one_profile_data);
4470 BroadcastEventIfUnique(eBroadcastBitProfileData,
4471 new ProcessEventData(shared_from_this(), GetState()));
4474 void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4475 const StructuredDataPluginSP &plugin_sp) {
4477 eBroadcastBitStructuredData,
4478 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
4481 StructuredDataPluginSP
4482 Process::GetStructuredDataPlugin(const ConstString &type_name) const {
4483 auto find_it = m_structured_data_plugin_map.find(type_name);
4484 if (find_it != m_structured_data_plugin_map.end())
4485 return find_it->second;
4487 return StructuredDataPluginSP();
4490 size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Error &error) {
4491 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4492 if (m_profile_data.empty())
4495 std::string &one_profile_data = m_profile_data.front();
4496 size_t bytes_available = one_profile_data.size();
4497 if (bytes_available > 0) {
4498 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4500 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4501 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4502 if (bytes_available > buf_size) {
4503 memcpy(buf, one_profile_data.c_str(), buf_size);
4504 one_profile_data.erase(0, buf_size);
4505 bytes_available = buf_size;
4507 memcpy(buf, one_profile_data.c_str(), bytes_available);
4508 m_profile_data.erase(m_profile_data.begin());
4511 return bytes_available;
4514 //------------------------------------------------------------------
4516 //------------------------------------------------------------------
4518 size_t Process::GetSTDOUT(char *buf, size_t buf_size, Error &error) {
4519 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4520 size_t bytes_available = m_stdout_data.size();
4521 if (bytes_available > 0) {
4522 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4524 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4525 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4526 if (bytes_available > buf_size) {
4527 memcpy(buf, m_stdout_data.c_str(), buf_size);
4528 m_stdout_data.erase(0, buf_size);
4529 bytes_available = buf_size;
4531 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4532 m_stdout_data.clear();
4535 return bytes_available;
4538 size_t Process::GetSTDERR(char *buf, size_t buf_size, Error &error) {
4539 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4540 size_t bytes_available = m_stderr_data.size();
4541 if (bytes_available > 0) {
4542 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4544 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4545 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4546 if (bytes_available > buf_size) {
4547 memcpy(buf, m_stderr_data.c_str(), buf_size);
4548 m_stderr_data.erase(0, buf_size);
4549 bytes_available = buf_size;
4551 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4552 m_stderr_data.clear();
4555 return bytes_available;
4558 void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4560 Process *process = (Process *)baton;
4561 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
4564 class IOHandlerProcessSTDIO : public IOHandler {
4566 IOHandlerProcessSTDIO(Process *process, int write_fd)
4567 : IOHandler(process->GetTarget().GetDebugger(),
4568 IOHandler::Type::ProcessIO),
4569 m_process(process), m_write_file(write_fd, false) {
4570 m_pipe.CreateNew(false);
4571 m_read_file.SetDescriptor(GetInputFD(), false);
4574 ~IOHandlerProcessSTDIO() override = default;
4576 // Each IOHandler gets to run until it is done. It should read data
4577 // from the "in" and place output into "out" and "err and return
4579 void Run() override {
4580 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4581 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4587 const int read_fd = m_read_file.GetDescriptor();
4588 TerminalState terminal_state;
4589 terminal_state.Save(read_fd, false);
4590 Terminal terminal(read_fd);
4591 terminal.SetCanonical(false);
4592 terminal.SetEcho(false);
4593 // FD_ZERO, FD_SET are not supported on windows
4595 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4596 m_is_running = true;
4597 while (!GetIsDone()) {
4598 SelectHelper select_helper;
4599 select_helper.FDSetRead(read_fd);
4600 select_helper.FDSetRead(pipe_read_fd);
4601 Error error = select_helper.Select();
4608 if (select_helper.FDIsSetRead(read_fd)) {
4610 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4611 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4616 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4618 // Consume the interrupt byte
4619 Error error = m_pipe.Read(&ch, 1, bytes_read);
4620 if (error.Success()) {
4626 if (StateIsRunningState(m_process->GetState()))
4627 m_process->SendAsyncInterrupt();
4634 m_is_running = false;
4636 terminal_state.Restore();
4639 void Cancel() override {
4641 // Only write to our pipe to cancel if we are in
4642 // IOHandlerProcessSTDIO::Run().
4643 // We can end up with a python command that is being run from the command
4646 // (lldb) step_process_thousands_of_times
4648 // In this case the command interpreter will be in the middle of handling
4649 // the command and if the process pushes and pops the IOHandler thousands
4650 // of times, we can end up writing to m_pipe without ever consuming the
4651 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4652 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4654 char ch = 'q'; // Send 'q' for quit
4655 size_t bytes_written = 0;
4656 m_pipe.Write(&ch, 1, bytes_written);
4660 bool Interrupt() override {
4661 // Do only things that are safe to do in an interrupt context (like in
4662 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4663 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4664 // that was written to the pipe and then call
4665 // m_process->SendAsyncInterrupt()
4666 // from a much safer location in code.
4668 char ch = 'i'; // Send 'i' for interrupt
4669 size_t bytes_written = 0;
4670 Error result = m_pipe.Write(&ch, 1, bytes_written);
4671 return result.Success();
4673 // This IOHandler might be pushed on the stack, but not being run
4675 // so do the right thing if we aren't actively watching for STDIN by
4677 // the interrupt to the process. Otherwise the write to the pipe above
4679 // do nothing. This can happen when the command interpreter is running and
4680 // gets a "expression ...". It will be on the IOHandler thread and sending
4681 // the input is complete to the delegate which will cause the expression
4683 // run, which will push the process IO handler, but not run it.
4685 if (StateIsRunningState(m_process->GetState())) {
4686 m_process->SendAsyncInterrupt();
4693 void GotEOF() override {}
4697 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4698 File m_write_file; // Write to this file (usually the master pty for getting
4701 std::atomic<bool> m_is_running{false};
4704 void Process::SetSTDIOFileDescriptor(int fd) {
4705 // First set up the Read Thread for reading/handling process I/O
4707 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
4708 new ConnectionFileDescriptor(fd, true));
4711 m_stdio_communication.SetConnection(conn_ap.release());
4712 if (m_stdio_communication.IsConnected()) {
4713 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4714 STDIOReadThreadBytesReceived, this);
4715 m_stdio_communication.StartReadThread();
4717 // Now read thread is set up, set up input reader.
4719 if (!m_process_input_reader)
4720 m_process_input_reader.reset(new IOHandlerProcessSTDIO(this, fd));
4725 bool Process::ProcessIOHandlerIsActive() {
4726 IOHandlerSP io_handler_sp(m_process_input_reader);
4728 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4731 bool Process::PushProcessIOHandler() {
4732 IOHandlerSP io_handler_sp(m_process_input_reader);
4733 if (io_handler_sp) {
4734 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4736 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
4738 io_handler_sp->SetIsDone(false);
4739 GetTarget().GetDebugger().PushIOHandler(io_handler_sp);
4745 bool Process::PopProcessIOHandler() {
4746 IOHandlerSP io_handler_sp(m_process_input_reader);
4748 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4752 // The process needs to know about installed plug-ins
4753 void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
4755 void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
4758 // RestorePlanState is used to record the "is private", "is master" and "okay to
4759 // discard" fields of
4760 // the plan we are running, and reset it on Clean or on destruction.
4761 // It will only reset the state once, so you can call Clean and then monkey with
4763 // won't get reset on you again.
4765 class RestorePlanState {
4767 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4768 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4769 if (m_thread_plan_sp) {
4770 m_private = m_thread_plan_sp->GetPrivate();
4771 m_is_master = m_thread_plan_sp->IsMasterPlan();
4772 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4776 ~RestorePlanState() { Clean(); }
4779 if (!m_already_reset && m_thread_plan_sp) {
4780 m_already_reset = true;
4781 m_thread_plan_sp->SetPrivate(m_private);
4782 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4783 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4788 lldb::ThreadPlanSP m_thread_plan_sp;
4789 bool m_already_reset;
4792 bool m_okay_to_discard;
4794 } // anonymous namespace
4797 GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4798 const milliseconds default_one_thread_timeout(250);
4800 // If the overall wait is forever, then we don't need to worry about it.
4801 if (!options.GetTimeout()) {
4802 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4803 : default_one_thread_timeout;
4806 // If the one thread timeout is set, use it.
4807 if (options.GetOneThreadTimeout())
4808 return *options.GetOneThreadTimeout();
4810 // Otherwise use half the total timeout, bounded by the
4811 // default_one_thread_timeout.
4812 return std::min<microseconds>(default_one_thread_timeout,
4813 *options.GetTimeout() / 2);
4816 static Timeout<std::micro>
4817 GetExpressionTimeout(const EvaluateExpressionOptions &options,
4818 bool before_first_timeout) {
4819 // If we are going to run all threads the whole time, or if we are only
4820 // going to run one thread, we can just return the overall timeout.
4821 if (!options.GetStopOthers() || !options.GetTryAllThreads())
4822 return options.GetTimeout();
4824 if (before_first_timeout)
4825 return GetOneThreadExpressionTimeout(options);
4827 if (!options.GetTimeout())
4830 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
4834 Process::RunThreadPlan(ExecutionContext &exe_ctx,
4835 lldb::ThreadPlanSP &thread_plan_sp,
4836 const EvaluateExpressionOptions &options,
4837 DiagnosticManager &diagnostic_manager) {
4838 ExpressionResults return_value = eExpressionSetupError;
4840 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4842 if (!thread_plan_sp) {
4843 diagnostic_manager.PutString(
4844 eDiagnosticSeverityError,
4845 "RunThreadPlan called with empty thread plan.");
4846 return eExpressionSetupError;
4849 if (!thread_plan_sp->ValidatePlan(nullptr)) {
4850 diagnostic_manager.PutString(
4851 eDiagnosticSeverityError,
4852 "RunThreadPlan called with an invalid thread plan.");
4853 return eExpressionSetupError;
4856 if (exe_ctx.GetProcessPtr() != this) {
4857 diagnostic_manager.PutString(eDiagnosticSeverityError,
4858 "RunThreadPlan called on wrong process.");
4859 return eExpressionSetupError;
4862 Thread *thread = exe_ctx.GetThreadPtr();
4863 if (thread == nullptr) {
4864 diagnostic_manager.PutString(eDiagnosticSeverityError,
4865 "RunThreadPlan called with invalid thread.");
4866 return eExpressionSetupError;
4869 // We need to change some of the thread plan attributes for the thread plan
4870 // runner. This will restore them
4871 // when we are done:
4873 RestorePlanState thread_plan_restorer(thread_plan_sp);
4875 // We rely on the thread plan we are running returning "PlanCompleted" if when
4876 // it successfully completes.
4877 // For that to be true the plan can't be private - since private plans
4878 // suppress themselves in the
4879 // GetCompletedPlan call.
4881 thread_plan_sp->SetPrivate(false);
4883 // The plans run with RunThreadPlan also need to be terminal master plans or
4884 // when they are done we will end
4885 // up asking the plan above us whether we should stop, which may give the
4888 thread_plan_sp->SetIsMasterPlan(true);
4889 thread_plan_sp->SetOkayToDiscard(false);
4891 if (m_private_state.GetValue() != eStateStopped) {
4892 diagnostic_manager.PutString(
4893 eDiagnosticSeverityError,
4894 "RunThreadPlan called while the private state was not stopped.");
4895 return eExpressionSetupError;
4898 // Save the thread & frame from the exe_ctx for restoration after we run
4899 const uint32_t thread_idx_id = thread->GetIndexID();
4900 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4901 if (!selected_frame_sp) {
4902 thread->SetSelectedFrame(nullptr);
4903 selected_frame_sp = thread->GetSelectedFrame();
4904 if (!selected_frame_sp) {
4905 diagnostic_manager.Printf(
4906 eDiagnosticSeverityError,
4907 "RunThreadPlan called without a selected frame on thread %d",
4909 return eExpressionSetupError;
4913 // Make sure the timeout values make sense. The one thread timeout needs to be
4914 // smaller than the overall timeout.
4915 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4916 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
4917 diagnostic_manager.PutString(eDiagnosticSeverityError,
4918 "RunThreadPlan called with one thread "
4919 "timeout greater than total timeout");
4920 return eExpressionSetupError;
4923 StackID ctx_frame_id = selected_frame_sp->GetStackID();
4925 // N.B. Running the target may unset the currently selected thread and frame.
4926 // We don't want to do that either,
4927 // so we should arrange to reset them as well.
4929 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
4931 uint32_t selected_tid;
4932 StackID selected_stack_id;
4933 if (selected_thread_sp) {
4934 selected_tid = selected_thread_sp->GetIndexID();
4935 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4937 selected_tid = LLDB_INVALID_THREAD_ID;
4940 HostThread backup_private_state_thread;
4941 lldb::StateType old_state = eStateInvalid;
4942 lldb::ThreadPlanSP stopper_base_plan_sp;
4944 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4945 LIBLLDB_LOG_PROCESS));
4946 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4947 // Yikes, we are running on the private state thread! So we can't wait for
4948 // public events on this thread, since
4949 // we are the thread that is generating public events.
4950 // The simplest thing to do is to spin up a temporary thread to handle
4951 // private state thread events while
4952 // we are fielding public events here.
4954 log->Printf("Running thread plan on private state thread, spinning up "
4955 "another state thread to handle the events.");
4957 backup_private_state_thread = m_private_state_thread;
4959 // One other bit of business: we want to run just this thread plan and
4960 // anything it pushes, and then stop,
4961 // returning control here.
4962 // But in the normal course of things, the plan above us on the stack would
4963 // be given a shot at the stop
4964 // event before deciding to stop, and we don't want that. So we insert a
4965 // "stopper" base plan on the stack
4966 // before the plan we want to run. Since base plans always stop and return
4967 // control to the user, that will
4968 // do just what we want.
4969 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4970 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4971 // Have to make sure our public state is stopped, since otherwise the
4972 // reporting logic below doesn't work correctly.
4973 old_state = m_public_state.GetValue();
4974 m_public_state.SetValueNoLock(eStateStopped);
4976 // Now spin up the private state thread:
4977 StartPrivateStateThread(true);
4980 thread->QueueThreadPlan(
4981 thread_plan_sp, false); // This used to pass "true" does that make sense?
4983 if (options.GetDebug()) {
4984 // In this case, we aren't actually going to run, we just want to stop right
4986 // Flush this thread so we will refetch the stacks and show the correct
4988 // FIXME: To make this prettier we should invent some stop reason for this,
4990 // is only cosmetic, and this functionality is only of use to lldb
4991 // developers who can
4992 // live with not pretty...
4994 return eExpressionStoppedForDebug;
4997 ListenerSP listener_sp(
4998 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
5000 lldb::EventSP event_to_broadcast_sp;
5003 // This process event hijacker Hijacks the Public events and its destructor
5004 // makes sure that the process events get
5005 // restored on exit to the function.
5007 // If the event needs to propagate beyond the hijacker (e.g., the process
5008 // exits during execution), then the event
5009 // is put into event_to_broadcast_sp for rebroadcasting.
5011 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
5015 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
5016 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
5017 " to run thread plan \"%s\".",
5018 thread->GetIndexID(), thread->GetID(), s.GetData());
5022 lldb::EventSP event_sp;
5023 lldb::StateType stop_state = lldb::eStateInvalid;
5025 bool before_first_timeout = true; // This is set to false the first time
5026 // that we have to halt the target.
5027 bool do_resume = true;
5028 bool handle_running_event = true;
5030 // This is just for accounting:
5031 uint32_t num_resumes = 0;
5033 // If we are going to run all threads the whole time, or if we are only
5034 // going to run one thread, then we don't need the first timeout. So we
5035 // pretend we are after the first timeout already.
5036 if (!options.GetStopOthers() || !options.GetTryAllThreads())
5037 before_first_timeout = false;
5040 log->Printf("Stop others: %u, try all: %u, before_first: %u.\n",
5041 options.GetStopOthers(), options.GetTryAllThreads(),
5042 before_first_timeout);
5044 // This isn't going to work if there are unfetched events on the queue.
5045 // Are there cases where we might want to run the remaining events here, and
5047 // call the function? That's probably being too tricky for our own good.
5049 Event *other_events = listener_sp->PeekAtNextEvent();
5050 if (other_events != nullptr) {
5051 diagnostic_manager.PutString(
5052 eDiagnosticSeverityError,
5053 "RunThreadPlan called with pending events on the queue.");
5054 return eExpressionSetupError;
5057 // We also need to make sure that the next event is delivered. We might be
5058 // calling a function as part of
5059 // a thread plan, in which case the last delivered event could be the
5060 // running event, and we don't want
5061 // event coalescing to cause us to lose OUR running event...
5062 ForceNextEventDelivery();
5064 // This while loop must exit out the bottom, there's cleanup that we need to do
5065 // when we are done.
5066 // So don't call return anywhere within it.
5068 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5069 // It's pretty much impossible to write test cases for things like:
5070 // One thread timeout expires, I go to halt, but the process already stopped
5071 // on the function call stop breakpoint. Turning on this define will make
5073 // fetch the first event till after the halt. So if you run a quick
5074 // function, it will have
5075 // completed, and the completion event will be waiting, when you interrupt
5077 // The expression evaluation should still succeed.
5078 bool miss_first_event = true;
5081 // We usually want to resume the process if we get to the top of the loop.
5082 // The only exception is if we get two running events with no intervening
5083 // stop, which can happen, we will just wait for then next stop event.
5085 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
5086 "before_first_timeout: %i.",
5087 do_resume, handle_running_event, before_first_timeout);
5089 if (do_resume || handle_running_event) {
5090 // Do the initial resume and wait for the running event before going
5095 Error resume_error = PrivateResume();
5096 if (!resume_error.Success()) {
5097 diagnostic_manager.Printf(
5098 eDiagnosticSeverityError,
5099 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5100 resume_error.AsCString());
5101 return_value = eExpressionSetupError;
5107 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
5110 log->Printf("Process::RunThreadPlan(): didn't get any event after "
5111 "resume %" PRIu32 ", exiting.",
5114 diagnostic_manager.Printf(eDiagnosticSeverityError,
5115 "didn't get any event after resume %" PRIu32
5118 return_value = eExpressionSetupError;
5123 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5125 if (stop_state != eStateRunning) {
5126 bool restarted = false;
5128 if (stop_state == eStateStopped) {
5129 restarted = Process::ProcessEventData::GetRestartedFromEvent(
5133 "Process::RunThreadPlan(): didn't get running event after "
5134 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5135 "handle_running_event: %i).",
5136 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5137 handle_running_event);
5141 // This is probably an overabundance of caution, I don't think I
5142 // should ever get a stopped & restarted
5143 // event here. But if I do, the best thing is to Halt and then get
5145 const bool clear_thread_plans = false;
5146 const bool use_run_lock = false;
5147 Halt(clear_thread_plans, use_run_lock);
5150 diagnostic_manager.Printf(
5151 eDiagnosticSeverityError,
5152 "didn't get running event after initial resume, got %s instead.",
5153 StateAsCString(stop_state));
5154 return_value = eExpressionSetupError;
5159 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
5160 // We need to call the function synchronously, so spin waiting for it to
5162 // If we get interrupted while executing, we're going to lose our
5164 // won't be able to gather the result at this point.
5165 // We set the timeout AFTER the resume, since the resume takes some time
5167 // don't want to charge that to the timeout.
5170 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5174 handle_running_event = true;
5176 // Now wait for the process to stop again:
5179 Timeout<std::micro> timeout =
5180 GetExpressionTimeout(options, before_first_timeout);
5183 auto now = system_clock::now();
5184 log->Printf("Process::RunThreadPlan(): about to wait - now is %s - "
5186 llvm::to_string(now).c_str(),
5187 llvm::to_string(now + *timeout).c_str());
5189 log->Printf("Process::RunThreadPlan(): about to wait forever.");
5193 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5194 // See comment above...
5195 if (miss_first_event) {
5197 miss_first_event = false;
5201 got_event = listener_sp->GetEvent(event_sp, timeout);
5205 bool keep_going = false;
5206 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5207 const bool clear_thread_plans = false;
5208 const bool use_run_lock = false;
5209 Halt(clear_thread_plans, use_run_lock);
5210 return_value = eExpressionInterrupted;
5211 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5212 "execution halted by user interrupt.");
5214 log->Printf("Process::RunThreadPlan(): Got interrupted by "
5215 "eBroadcastBitInterrupted, exiting.");
5219 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5222 "Process::RunThreadPlan(): in while loop, got event: %s.",
5223 StateAsCString(stop_state));
5225 switch (stop_state) {
5226 case lldb::eStateStopped: {
5227 // We stopped, figure out what we are going to do now.
5228 ThreadSP thread_sp =
5229 GetThreadList().FindThreadByIndexID(thread_idx_id);
5231 // Ooh, our thread has vanished. Unlikely that this was
5232 // successful execution...
5234 log->Printf("Process::RunThreadPlan(): execution completed "
5235 "but our thread (index-id=%u) has vanished.",
5237 return_value = eExpressionInterrupted;
5239 // If we were restarted, we just need to go back up to fetch
5241 if (Process::ProcessEventData::GetRestartedFromEvent(
5244 log->Printf("Process::RunThreadPlan(): Got a stop and "
5245 "restart, so we'll continue waiting.");
5249 handle_running_event = true;
5251 StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
5252 StopReason stop_reason = eStopReasonInvalid;
5254 stop_reason = stop_info_sp->GetStopReason();
5256 // FIXME: We only check if the stop reason is plan complete,
5257 // should we make sure that
5258 // it is OUR plan that is complete?
5259 if (stop_reason == eStopReasonPlanComplete) {
5261 log->PutCString("Process::RunThreadPlan(): execution "
5262 "completed successfully.");
5264 // Restore the plan state so it will get reported as
5265 // intended when we are done.
5266 thread_plan_restorer.Clean();
5268 return_value = eExpressionCompleted;
5270 // Something restarted the target, so just wait for it to
5272 if (stop_reason == eStopReasonBreakpoint) {
5274 log->Printf("Process::RunThreadPlan() stopped for "
5276 stop_info_sp->GetDescription());
5277 return_value = eExpressionHitBreakpoint;
5278 if (!options.DoesIgnoreBreakpoints()) {
5279 // Restore the plan state and then force Private to
5281 // going to stop because of this plan so we need it to
5283 // plan or it won't report correctly when we continue to
5286 thread_plan_restorer.Clean();
5288 thread_plan_sp->SetPrivate(false);
5289 event_to_broadcast_sp = event_sp;
5293 log->PutCString("Process::RunThreadPlan(): thread plan "
5294 "didn't successfully complete.");
5295 if (!options.DoesUnwindOnError())
5296 event_to_broadcast_sp = event_sp;
5297 return_value = eExpressionInterrupted;
5304 case lldb::eStateRunning:
5305 // This shouldn't really happen, but sometimes we do get two
5306 // running events without an
5307 // intervening stop, and in that case we should just go back to
5308 // waiting for the stop.
5311 handle_running_event = false;
5316 log->Printf("Process::RunThreadPlan(): execution stopped with "
5317 "unexpected state: %s.",
5318 StateAsCString(stop_state));
5320 if (stop_state == eStateExited)
5321 event_to_broadcast_sp = event_sp;
5323 diagnostic_manager.PutString(
5324 eDiagnosticSeverityError,
5325 "execution stopped with unexpected state.");
5326 return_value = eExpressionInterrupted;
5337 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5338 "the event pointer was null. How odd...");
5339 return_value = eExpressionInterrupted;
5343 // If we didn't get an event that means we've timed out...
5344 // We will interrupt the process here. Depending on what we were asked
5346 // either exit, or try with all threads running for the same timeout.
5349 if (options.GetTryAllThreads()) {
5350 if (before_first_timeout) {
5351 log->Printf("Process::RunThreadPlan(): Running function with "
5352 "one thread timeout timed out.");
5354 log->Printf("Process::RunThreadPlan(): Restarting function with "
5355 "all threads enabled "
5356 "and timeout: %" PRIu64
5357 " timed out, abandoning execution.",
5358 timeout ? timeout->count() : -1);
5360 log->Printf("Process::RunThreadPlan(): Running function with "
5361 "timeout: %" PRIu64 " timed out, "
5362 "abandoning execution.",
5363 timeout ? timeout->count() : -1);
5366 // It is possible that between the time we issued the Halt, and we get
5367 // around to calling Halt the target
5368 // could have stopped. That's fine, Halt will figure that out and send
5369 // the appropriate Stopped event.
5370 // BUT it is also possible that we stopped & restarted (e.g. hit a
5371 // signal with "stop" set to false.) In
5372 // that case, we'll get the stopped & restarted event, and we should go
5373 // back to waiting for the Halt's
5374 // stopped event. That's what this while loop does.
5376 bool back_to_top = true;
5377 uint32_t try_halt_again = 0;
5378 bool do_halt = true;
5379 const uint32_t num_retries = 5;
5380 while (try_halt_again < num_retries) {
5384 log->Printf("Process::RunThreadPlan(): Running Halt.");
5385 const bool clear_thread_plans = false;
5386 const bool use_run_lock = false;
5387 Halt(clear_thread_plans, use_run_lock);
5389 if (halt_error.Success()) {
5391 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5394 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
5398 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5400 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5401 StateAsCString(stop_state));
5402 if (stop_state == lldb::eStateStopped &&
5403 Process::ProcessEventData::GetInterruptedFromEvent(
5405 log->PutCString(" Event was the Halt interruption event.");
5408 if (stop_state == lldb::eStateStopped) {
5409 // Between the time we initiated the Halt and the time we
5410 // delivered it, the process could have
5411 // already finished its job. Check that here:
5413 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5415 log->PutCString("Process::RunThreadPlan(): Even though we "
5416 "timed out, the call plan was done. "
5417 "Exiting wait loop.");
5418 return_value = eExpressionCompleted;
5419 back_to_top = false;
5423 if (Process::ProcessEventData::GetRestartedFromEvent(
5426 log->PutCString("Process::RunThreadPlan(): Went to halt "
5427 "but got a restarted event, there must be "
5428 "an un-restarted stopped event so try "
5430 "Exiting wait loop.");
5436 if (!options.GetTryAllThreads()) {
5438 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5439 "was false, we stopped so now we're "
5441 return_value = eExpressionInterrupted;
5442 back_to_top = false;
5446 if (before_first_timeout) {
5447 // Set all the other threads to run, and return to the top of
5448 // the loop, which will continue;
5449 before_first_timeout = false;
5450 thread_plan_sp->SetStopOthers(false);
5453 "Process::RunThreadPlan(): about to resume.");
5458 // Running all threads failed, so return Interrupted.
5460 log->PutCString("Process::RunThreadPlan(): running all "
5461 "threads timed out.");
5462 return_value = eExpressionInterrupted;
5463 back_to_top = false;
5469 log->PutCString("Process::RunThreadPlan(): halt said it "
5470 "succeeded, but I got no event. "
5471 "I'm getting out of here passing Interrupted.");
5472 return_value = eExpressionInterrupted;
5473 back_to_top = false;
5482 if (!back_to_top || try_halt_again > num_retries)
5489 // If we had to start up a temporary private state thread to run this thread
5490 // plan, shut it down now.
5491 if (backup_private_state_thread.IsJoinable()) {
5492 StopPrivateStateThread();
5494 m_private_state_thread = backup_private_state_thread;
5495 if (stopper_base_plan_sp) {
5496 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5498 if (old_state != eStateInvalid)
5499 m_public_state.SetValueNoLock(old_state);
5502 if (return_value != eExpressionCompleted && log) {
5503 // Print a backtrace into the log so we can figure out where we are:
5505 s.PutCString("Thread state after unsuccessful completion: \n");
5506 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
5507 log->PutString(s.GetString());
5509 // Restore the thread state if we are going to discard the plan execution.
5510 // There are three cases where this
5512 // 1) The execution successfully completed
5513 // 2) We hit a breakpoint, and ignore_breakpoints was true
5514 // 3) We got some other error, and discard_on_error was true
5515 bool should_unwind = (return_value == eExpressionInterrupted &&
5516 options.DoesUnwindOnError()) ||
5517 (return_value == eExpressionHitBreakpoint &&
5518 options.DoesIgnoreBreakpoints());
5520 if (return_value == eExpressionCompleted || should_unwind) {
5521 thread_plan_sp->RestoreThreadState();
5524 // Now do some processing on the results of the run:
5525 if (return_value == eExpressionInterrupted ||
5526 return_value == eExpressionHitBreakpoint) {
5532 log->PutCString("Process::RunThreadPlan(): Stop event that "
5533 "interrupted us is NULL.");
5538 const char *event_explanation = nullptr;
5542 event_explanation = "<no event>";
5544 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5545 event_explanation = "<user interrupt>";
5548 const Process::ProcessEventData *event_data =
5549 Process::ProcessEventData::GetEventDataFromEvent(
5553 event_explanation = "<no event data>";
5557 Process *process = event_data->GetProcessSP().get();
5560 event_explanation = "<no process>";
5564 ThreadList &thread_list = process->GetThreadList();
5566 uint32_t num_threads = thread_list.GetSize();
5567 uint32_t thread_index;
5569 ts.Printf("<%u threads> ", num_threads);
5571 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5572 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5579 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5580 RegisterContext *register_context =
5581 thread->GetRegisterContext().get();
5583 if (register_context)
5584 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5586 ts.Printf("[ip unknown] ");
5588 // Show the private stop info here, the public stop info will be
5589 // from the last natural stop.
5590 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5592 const char *stop_desc = stop_info_sp->GetDescription();
5594 ts.PutCString(stop_desc);
5599 event_explanation = ts.GetData();
5603 if (event_explanation)
5604 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5605 s.GetData(), event_explanation);
5607 log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5611 if (should_unwind) {
5613 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5614 "discarding thread plans up to %p.",
5615 static_cast<void *>(thread_plan_sp.get()));
5616 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5619 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5620 "plan: %p not discarding.",
5621 static_cast<void *>(thread_plan_sp.get()));
5623 } else if (return_value == eExpressionSetupError) {
5625 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5627 if (options.DoesUnwindOnError()) {
5628 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5631 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5633 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5634 return_value = eExpressionCompleted;
5635 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5638 "Process::RunThreadPlan(): thread plan was discarded");
5639 return_value = eExpressionDiscarded;
5643 "Process::RunThreadPlan(): thread plan stopped in mid course");
5644 if (options.DoesUnwindOnError() && thread_plan_sp) {
5646 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5647 "'cause unwind_on_error is set.");
5648 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5653 // Thread we ran the function in may have gone away because we ran the
5655 // Check that it's still there, and if it is put it back in the context.
5657 // frame in the context if it is still present.
5658 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5660 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5663 // Also restore the current process'es selected frame & thread, since this
5664 // function calling may
5665 // be done behind the user's back.
5667 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5668 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5669 selected_stack_id.IsValid()) {
5670 // We were able to restore the selected thread, now restore the frame:
5671 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5672 StackFrameSP old_frame_sp =
5673 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5676 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5677 old_frame_sp.get());
5682 // If the process exited during the run of the thread plan, notify everyone.
5684 if (event_to_broadcast_sp) {
5686 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5687 BroadcastEvent(event_to_broadcast_sp);
5690 return return_value;
5693 const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5694 const char *result_name;
5697 case eExpressionCompleted:
5698 result_name = "eExpressionCompleted";
5700 case eExpressionDiscarded:
5701 result_name = "eExpressionDiscarded";
5703 case eExpressionInterrupted:
5704 result_name = "eExpressionInterrupted";
5706 case eExpressionHitBreakpoint:
5707 result_name = "eExpressionHitBreakpoint";
5709 case eExpressionSetupError:
5710 result_name = "eExpressionSetupError";
5712 case eExpressionParseError:
5713 result_name = "eExpressionParseError";
5715 case eExpressionResultUnavailable:
5716 result_name = "eExpressionResultUnavailable";
5718 case eExpressionTimedOut:
5719 result_name = "eExpressionTimedOut";
5721 case eExpressionStoppedForDebug:
5722 result_name = "eExpressionStoppedForDebug";
5728 void Process::GetStatus(Stream &strm) {
5729 const StateType state = GetState();
5730 if (StateIsStoppedState(state, false)) {
5731 if (state == eStateExited) {
5732 int exit_status = GetExitStatus();
5733 const char *exit_description = GetExitDescription();
5734 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5735 GetID(), exit_status, exit_status,
5736 exit_description ? exit_description : "");
5738 if (state == eStateConnected)
5739 strm.Printf("Connected to remote target.\n");
5741 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5744 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5748 size_t Process::GetThreadStatus(Stream &strm,
5749 bool only_threads_with_stop_reason,
5750 uint32_t start_frame, uint32_t num_frames,
5751 uint32_t num_frames_with_source,
5753 size_t num_thread_infos_dumped = 0;
5755 // You can't hold the thread list lock while calling Thread::GetStatus. That
5756 // very well might run code (e.g. if we need it
5757 // to get return values or arguments.) For that to work the process has to be
5758 // able to acquire it. So instead copy the thread
5759 // ID's, and look them up one by one:
5761 uint32_t num_threads;
5762 std::vector<lldb::tid_t> thread_id_array;
5763 // Scope for thread list locker;
5765 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5766 ThreadList &curr_thread_list = GetThreadList();
5767 num_threads = curr_thread_list.GetSize();
5769 thread_id_array.resize(num_threads);
5770 for (idx = 0; idx < num_threads; ++idx)
5771 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5774 for (uint32_t i = 0; i < num_threads; i++) {
5775 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5777 if (only_threads_with_stop_reason) {
5778 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5779 if (!stop_info_sp || !stop_info_sp->IsValid())
5782 thread_sp->GetStatus(strm, start_frame, num_frames,
5783 num_frames_with_source,
5785 ++num_thread_infos_dumped;
5787 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5789 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5790 " vanished while running Thread::GetStatus.");
5793 return num_thread_infos_dumped;
5796 void Process::AddInvalidMemoryRegion(const LoadRange ®ion) {
5797 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5800 bool Process::RemoveInvalidMemoryRange(const LoadRange ®ion) {
5801 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5802 region.GetByteSize());
5805 void Process::AddPreResumeAction(PreResumeActionCallback callback,
5807 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5810 bool Process::RunPreResumeActions() {
5812 while (!m_pre_resume_actions.empty()) {
5813 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5814 m_pre_resume_actions.pop_back();
5815 bool this_result = action.callback(action.baton);
5817 result = this_result;
5822 void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5824 void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5826 PreResumeCallbackAndBaton element(callback, baton);
5827 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5828 if (found_iter != m_pre_resume_actions.end())
5830 m_pre_resume_actions.erase(found_iter);
5834 ProcessRunLock &Process::GetRunLock() {
5835 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5836 return m_private_run_lock;
5838 return m_public_run_lock;
5841 void Process::Flush() {
5842 m_thread_list.Flush();
5843 m_extended_thread_list.Flush();
5844 m_extended_thread_stop_id = 0;
5845 m_queue_list.Clear();
5846 m_queue_list_stop_id = 0;
5849 void Process::DidExec() {
5850 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5852 log->Printf("Process::%s()", __FUNCTION__);
5854 Target &target = GetTarget();
5855 target.CleanupProcess();
5856 target.ClearModules(false);
5857 m_dynamic_checkers_ap.reset();
5859 m_system_runtime_ap.reset();
5862 m_jit_loaders_ap.reset();
5863 m_image_tokens.clear();
5864 m_allocated_memory_cache.Clear();
5865 m_language_runtimes.clear();
5866 m_instrumentation_runtimes.clear();
5867 m_thread_list.DiscardThreadPlans();
5868 m_memory_cache.Clear(true);
5869 m_stop_info_override_callback = nullptr;
5872 // Flush the process (threads and all stack frames) after running
5874 // in case the dynamic loader loaded things in new locations.
5877 // After we figure out what was loaded/unloaded in CompleteAttach,
5878 // we need to let the target know so it can do any cleanup it needs to.
5882 addr_t Process::ResolveIndirectFunction(const Address *address, Error &error) {
5883 if (address == nullptr) {
5884 error.SetErrorString("Invalid address argument");
5885 return LLDB_INVALID_ADDRESS;
5888 addr_t function_addr = LLDB_INVALID_ADDRESS;
5890 addr_t addr = address->GetLoadAddress(&GetTarget());
5891 std::map<addr_t, addr_t>::const_iterator iter =
5892 m_resolved_indirect_addresses.find(addr);
5893 if (iter != m_resolved_indirect_addresses.end()) {
5894 function_addr = (*iter).second;
5896 if (!InferiorCall(this, address, function_addr)) {
5897 Symbol *symbol = address->CalculateSymbolContextSymbol();
5898 error.SetErrorStringWithFormat(
5899 "Unable to call resolver for indirect function %s",
5900 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5901 function_addr = LLDB_INVALID_ADDRESS;
5903 m_resolved_indirect_addresses.insert(
5904 std::pair<addr_t, addr_t>(addr, function_addr));
5907 return function_addr;
5910 void Process::ModulesDidLoad(ModuleList &module_list) {
5911 SystemRuntime *sys_runtime = GetSystemRuntime();
5913 sys_runtime->ModulesDidLoad(module_list);
5916 GetJITLoaders().ModulesDidLoad(module_list);
5918 // Give runtimes a chance to be created.
5919 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5920 m_instrumentation_runtimes);
5922 // Tell runtimes about new modules.
5923 for (auto pos = m_instrumentation_runtimes.begin();
5924 pos != m_instrumentation_runtimes.end(); ++pos) {
5925 InstrumentationRuntimeSP runtime = pos->second;
5926 runtime->ModulesDidLoad(module_list);
5929 // Let any language runtimes we have already created know
5930 // about the modules that loaded.
5932 // Iterate over a copy of this language runtime list in case
5933 // the language runtime ModulesDidLoad somehow causes the language
5934 // riuntime to be unloaded.
5935 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5936 for (const auto &pair : language_runtimes) {
5937 // We must check language_runtime_sp to make sure it is not
5938 // nullptr as we might cache the fact that we didn't have a
5939 // language runtime for a language.
5940 LanguageRuntimeSP language_runtime_sp = pair.second;
5941 if (language_runtime_sp)
5942 language_runtime_sp->ModulesDidLoad(module_list);
5945 // If we don't have an operating system plug-in, try to load one since
5946 // loading shared libraries might cause a new one to try and load
5948 LoadOperatingSystemPlugin(false);
5950 // Give structured-data plugins a chance to see the modified modules.
5951 for (auto pair : m_structured_data_plugin_map) {
5953 pair.second->ModulesDidLoad(*this, module_list);
5957 void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5958 const char *fmt, ...) {
5959 bool print_warning = true;
5961 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5964 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5968 if (repeat_key != nullptr) {
5969 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5970 if (it == m_warnings_issued.end()) {
5971 m_warnings_issued[warning_type] = WarningsPointerSet();
5972 m_warnings_issued[warning_type].insert(repeat_key);
5974 if (it->second.find(repeat_key) != it->second.end()) {
5975 print_warning = false;
5977 it->second.insert(repeat_key);
5982 if (print_warning) {
5984 va_start(args, fmt);
5985 stream_sp->PrintfVarArg(fmt, args);
5990 void Process::PrintWarningOptimization(const SymbolContext &sc) {
5991 if (GetWarningsOptimization() && sc.module_sp &&
5992 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5993 sc.function->GetIsOptimized()) {
5994 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5995 "%s was compiled with optimization - stepping may behave "
5996 "oddly; variables may not be available.\n",
5997 sc.module_sp->GetFileSpec().GetFilename().GetCString());
6001 bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
6004 PlatformSP platform_sp = GetTarget().GetPlatform();
6008 return platform_sp->GetProcessInfo(GetID(), info);
6011 ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
6012 ThreadCollectionSP threads;
6014 const MemoryHistorySP &memory_history =
6015 MemoryHistory::FindPlugin(shared_from_this());
6017 if (!memory_history) {
6021 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6026 InstrumentationRuntimeSP
6027 Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
6028 InstrumentationRuntimeCollection::iterator pos;
6029 pos = m_instrumentation_runtimes.find(type);
6030 if (pos == m_instrumentation_runtimes.end()) {
6031 return InstrumentationRuntimeSP();
6033 return (*pos).second;
6036 bool Process::GetModuleSpec(const FileSpec &module_file_spec,
6037 const ArchSpec &arch, ModuleSpec &module_spec) {
6038 module_spec.Clear();
6042 size_t Process::AddImageToken(lldb::addr_t image_ptr) {
6043 m_image_tokens.push_back(image_ptr);
6044 return m_image_tokens.size() - 1;
6047 lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
6048 if (token < m_image_tokens.size())
6049 return m_image_tokens[token];
6050 return LLDB_INVALID_IMAGE_TOKEN;
6053 void Process::ResetImageToken(size_t token) {
6054 if (token < m_image_tokens.size())
6055 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
6059 Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
6060 AddressRange range_bounds) {
6061 Target &target = GetTarget();
6062 DisassemblerSP disassembler_sp;
6063 InstructionList *insn_list = nullptr;
6065 Address retval = default_stop_addr;
6067 if (!target.GetUseFastStepping())
6069 if (!default_stop_addr.IsValid())
6072 ExecutionContext exe_ctx(this);
6073 const char *plugin_name = nullptr;
6074 const char *flavor = nullptr;
6075 const bool prefer_file_cache = true;
6076 disassembler_sp = Disassembler::DisassembleRange(
6077 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
6079 if (disassembler_sp)
6080 insn_list = &disassembler_sp->GetInstructionList();
6082 if (insn_list == nullptr) {
6086 size_t insn_offset =
6087 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
6088 if (insn_offset == UINT32_MAX) {
6092 uint32_t branch_index =
6093 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target);
6094 if (branch_index == UINT32_MAX) {
6098 if (branch_index > insn_offset) {
6099 Address next_branch_insn_address =
6100 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
6101 if (next_branch_insn_address.IsValid() &&
6102 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
6103 retval = next_branch_insn_address;
6110 Error Process::GetMemoryRegions(
6111 std::vector<lldb::MemoryRegionInfoSP> ®ion_list) {
6115 lldb::addr_t range_end = 0;
6117 region_list.clear();
6119 lldb::MemoryRegionInfoSP region_info(new lldb_private::MemoryRegionInfo());
6120 error = GetMemoryRegionInfo(range_end, *region_info);
6121 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6123 region_list.clear();
6127 range_end = region_info->GetRange().GetRangeEnd();
6128 if (region_info->GetMapped() == MemoryRegionInfo::eYes) {
6129 region_list.push_back(region_info);
6131 } while (range_end != LLDB_INVALID_ADDRESS);
6136 Error Process::ConfigureStructuredData(
6137 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
6138 // If you get this, the Process-derived class needs to implement a method
6139 // to enable an already-reported asynchronous structured data feature.
6140 // See ProcessGDBRemote for an example implementation over gdb-remote.
6141 return Error("unimplemented");
6144 void Process::MapSupportedStructuredDataPlugins(
6145 const StructuredData::Array &supported_type_names) {
6146 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
6148 // Bail out early if there are no type names to map.
6149 if (supported_type_names.GetSize() == 0) {
6151 log->Printf("Process::%s(): no structured data types supported",
6156 // Convert StructuredData type names to ConstString instances.
6157 std::set<ConstString> const_type_names;
6160 log->Printf("Process::%s(): the process supports the following async "
6161 "structured data types:",
6164 supported_type_names.ForEach(
6165 [&const_type_names, &log](StructuredData::Object *object) {
6167 // Invalid - shouldn't be null objects in the array.
6171 auto type_name = object->GetAsString();
6173 // Invalid format - all type names should be strings.
6177 const_type_names.insert(ConstString(type_name->GetValue()));
6179 log->Printf("- %s", type_name->GetValue().c_str());
6183 // For each StructuredDataPlugin, if the plugin handles any of the
6184 // types in the supported_type_names, map that type name to that plugin.
6185 uint32_t plugin_index = 0;
6186 for (auto create_instance =
6187 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
6189 create_instance && !const_type_names.empty(); ++plugin_index) {
6190 // Create the plugin.
6191 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
6193 // This plugin doesn't think it can work with the process.
6194 // Move on to the next.
6198 // For any of the remaining type names, map any that this plugin
6200 std::vector<ConstString> names_to_remove;
6201 for (auto &type_name : const_type_names) {
6202 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6203 m_structured_data_plugin_map.insert(
6204 std::make_pair(type_name, plugin_sp));
6205 names_to_remove.push_back(type_name);
6207 log->Printf("Process::%s(): using plugin %s for type name "
6209 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
6210 type_name.GetCString());
6214 // Remove the type names that were consumed by this plugin.
6215 for (auto &type_name : names_to_remove)
6216 const_type_names.erase(type_name);
6220 bool Process::RouteAsyncStructuredData(
6221 const StructuredData::ObjectSP object_sp) {
6222 // Nothing to do if there's no data.
6226 // The contract is this must be a dictionary, so we can look up the
6227 // routing key via the top-level 'type' string value within the dictionary.
6228 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6232 // Grab the async structured type name (i.e. the feature/plugin name).
6233 ConstString type_name;
6234 if (!dictionary->GetValueForKeyAsString("type", type_name))
6237 // Check if there's a plugin registered for this type name.
6238 auto find_it = m_structured_data_plugin_map.find(type_name);
6239 if (find_it == m_structured_data_plugin_map.end()) {
6240 // We don't have a mapping for this structured data type.
6244 // Route the structured data to the plugin.
6245 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);