1 //===-- Process.cpp ---------------------------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include <atomic> 10 #include <memory> 11 #include <mutex> 12 13 #include "llvm/Support/ScopedPrinter.h" 14 #include "llvm/Support/Threading.h" 15 16 #include "Plugins/Process/Utility/InferiorCallPOSIX.h" 17 #include "lldb/Breakpoint/BreakpointLocation.h" 18 #include "lldb/Breakpoint/StoppointCallbackContext.h" 19 #include "lldb/Core/Debugger.h" 20 #include "lldb/Core/Module.h" 21 #include "lldb/Core/ModuleSpec.h" 22 #include "lldb/Core/PluginManager.h" 23 #include "lldb/Core/StreamFile.h" 24 #include "lldb/Expression/DiagnosticManager.h" 25 #include "lldb/Expression/IRDynamicChecks.h" 26 #include "lldb/Expression/UserExpression.h" 27 #include "lldb/Expression/UtilityFunction.h" 28 #include "lldb/Host/ConnectionFileDescriptor.h" 29 #include "lldb/Host/FileSystem.h" 30 #include "lldb/Host/Host.h" 31 #include "lldb/Host/HostInfo.h" 32 #include "lldb/Host/OptionParser.h" 33 #include "lldb/Host/Pipe.h" 34 #include "lldb/Host/Terminal.h" 35 #include "lldb/Host/ThreadLauncher.h" 36 #include "lldb/Interpreter/CommandInterpreter.h" 37 #include "lldb/Interpreter/OptionArgParser.h" 38 #include "lldb/Interpreter/OptionValueProperties.h" 39 #include "lldb/Symbol/Function.h" 40 #include "lldb/Symbol/Symbol.h" 41 #include "lldb/Target/ABI.h" 42 #include "lldb/Target/CPPLanguageRuntime.h" 43 #include "lldb/Target/DynamicLoader.h" 44 #include "lldb/Target/InstrumentationRuntime.h" 45 #include "lldb/Target/JITLoader.h" 46 #include "lldb/Target/JITLoaderList.h" 47 #include "lldb/Target/LanguageRuntime.h" 48 #include "lldb/Target/MemoryHistory.h" 49 #include "lldb/Target/MemoryRegionInfo.h" 50 #include "lldb/Target/ObjCLanguageRuntime.h" 51 #include "lldb/Target/OperatingSystem.h" 52 #include "lldb/Target/Platform.h" 53 #include "lldb/Target/Process.h" 54 #include "lldb/Target/RegisterContext.h" 55 #include "lldb/Target/StopInfo.h" 56 #include "lldb/Target/StructuredDataPlugin.h" 57 #include "lldb/Target/SystemRuntime.h" 58 #include "lldb/Target/Target.h" 59 #include "lldb/Target/TargetList.h" 60 #include "lldb/Target/Thread.h" 61 #include "lldb/Target/ThreadPlan.h" 62 #include "lldb/Target/ThreadPlanBase.h" 63 #include "lldb/Target/UnixSignals.h" 64 #include "lldb/Utility/Event.h" 65 #include "lldb/Utility/Log.h" 66 #include "lldb/Utility/NameMatches.h" 67 #include "lldb/Utility/ProcessInfo.h" 68 #include "lldb/Utility/SelectHelper.h" 69 #include "lldb/Utility/State.h" 70 71 using namespace lldb; 72 using namespace lldb_private; 73 using namespace std::chrono; 74 75 // Comment out line below to disable memory caching, overriding the process 76 // setting target.process.disable-memory-cache 77 #define ENABLE_MEMORY_CACHING 78 79 #ifdef ENABLE_MEMORY_CACHING 80 #define DISABLE_MEM_CACHE_DEFAULT false 81 #else 82 #define DISABLE_MEM_CACHE_DEFAULT true 83 #endif 84 85 class ProcessOptionValueProperties : public OptionValueProperties { 86 public: 87 ProcessOptionValueProperties(ConstString name) 88 : OptionValueProperties(name) {} 89 90 // This constructor is used when creating ProcessOptionValueProperties when 91 // it is part of a new lldb_private::Process instance. It will copy all 92 // current global property values as needed 93 ProcessOptionValueProperties(ProcessProperties *global_properties) 94 : OptionValueProperties(*global_properties->GetValueProperties()) {} 95 96 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx, 97 bool will_modify, 98 uint32_t idx) const override { 99 // When getting the value for a key from the process options, we will 100 // always try and grab the setting from the current process if there is 101 // one. Else we just use the one from this instance. 102 if (exe_ctx) { 103 Process *process = exe_ctx->GetProcessPtr(); 104 if (process) { 105 ProcessOptionValueProperties *instance_properties = 106 static_cast<ProcessOptionValueProperties *>( 107 process->GetValueProperties().get()); 108 if (this != instance_properties) 109 return instance_properties->ProtectedGetPropertyAtIndex(idx); 110 } 111 } 112 return ProtectedGetPropertyAtIndex(idx); 113 } 114 }; 115 116 static constexpr PropertyDefinition g_properties[] = { 117 {"disable-memory-cache", OptionValue::eTypeBoolean, false, 118 DISABLE_MEM_CACHE_DEFAULT, nullptr, {}, 119 "Disable reading and caching of memory in fixed-size units."}, 120 {"extra-startup-command", OptionValue::eTypeArray, false, 121 OptionValue::eTypeString, nullptr, {}, 122 "A list containing extra commands understood by the particular process " 123 "plugin used. " 124 "For instance, to turn on debugserver logging set this to " 125 "\"QSetLogging:bitmask=LOG_DEFAULT;\""}, 126 {"ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, 127 nullptr, {}, 128 "If true, breakpoints will be ignored during expression evaluation."}, 129 {"unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true, 130 nullptr, {}, "If true, errors in expression evaluation will unwind " 131 "the stack back to the state before the call."}, 132 {"python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, nullptr, 133 {}, "A path to a python OS plug-in module file that contains a " 134 "OperatingSystemPlugIn class."}, 135 {"stop-on-sharedlibrary-events", OptionValue::eTypeBoolean, true, false, 136 nullptr, {}, 137 "If true, stop when a shared library is loaded or unloaded."}, 138 {"detach-keeps-stopped", OptionValue::eTypeBoolean, true, false, nullptr, 139 {}, "If true, detach will attempt to keep the process stopped."}, 140 {"memory-cache-line-size", OptionValue::eTypeUInt64, false, 512, nullptr, 141 {}, "The memory cache line size"}, 142 {"optimization-warnings", OptionValue::eTypeBoolean, false, true, nullptr, 143 {}, "If true, warn when stopped in code that is optimized where " 144 "stepping and variable availability may not behave as expected."}, 145 {"stop-on-exec", OptionValue::eTypeBoolean, true, true, 146 nullptr, {}, 147 "If true, stop when a shared library is loaded or unloaded."}, 148 {"utility-expression-timeout", OptionValue::eTypeUInt64, false, 15, 149 nullptr, {}, 150 "The time in seconds to wait for LLDB-internal utility expressions."} 151 }; 152 153 enum { 154 ePropertyDisableMemCache, 155 ePropertyExtraStartCommand, 156 ePropertyIgnoreBreakpointsInExpressions, 157 ePropertyUnwindOnErrorInExpressions, 158 ePropertyPythonOSPluginPath, 159 ePropertyStopOnSharedLibraryEvents, 160 ePropertyDetachKeepsStopped, 161 ePropertyMemCacheLineSize, 162 ePropertyWarningOptimization, 163 ePropertyStopOnExec, 164 ePropertyUtilityExpressionTimeout, 165 }; 166 167 ProcessProperties::ProcessProperties(lldb_private::Process *process) 168 : Properties(), 169 m_process(process) // Can be nullptr for global ProcessProperties 170 { 171 if (process == nullptr) { 172 // Global process properties, set them up one time 173 m_collection_sp = 174 std::make_shared<ProcessOptionValueProperties>(ConstString("process")); 175 m_collection_sp->Initialize(g_properties); 176 m_collection_sp->AppendProperty( 177 ConstString("thread"), ConstString("Settings specific to threads."), 178 true, Thread::GetGlobalProperties()->GetValueProperties()); 179 } else { 180 m_collection_sp = std::make_shared<ProcessOptionValueProperties>( 181 Process::GetGlobalProperties().get()); 182 m_collection_sp->SetValueChangedCallback( 183 ePropertyPythonOSPluginPath, 184 ProcessProperties::OptionValueChangedCallback, this); 185 } 186 } 187 188 ProcessProperties::~ProcessProperties() = default; 189 190 void ProcessProperties::OptionValueChangedCallback(void *baton, 191 OptionValue *option_value) { 192 ProcessProperties *properties = (ProcessProperties *)baton; 193 if (properties->m_process) 194 properties->m_process->LoadOperatingSystemPlugin(true); 195 } 196 197 bool ProcessProperties::GetDisableMemoryCache() const { 198 const uint32_t idx = ePropertyDisableMemCache; 199 return m_collection_sp->GetPropertyAtIndexAsBoolean( 200 nullptr, idx, g_properties[idx].default_uint_value != 0); 201 } 202 203 uint64_t ProcessProperties::GetMemoryCacheLineSize() const { 204 const uint32_t idx = ePropertyMemCacheLineSize; 205 return m_collection_sp->GetPropertyAtIndexAsUInt64( 206 nullptr, idx, g_properties[idx].default_uint_value); 207 } 208 209 Args ProcessProperties::GetExtraStartupCommands() const { 210 Args args; 211 const uint32_t idx = ePropertyExtraStartCommand; 212 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args); 213 return args; 214 } 215 216 void ProcessProperties::SetExtraStartupCommands(const Args &args) { 217 const uint32_t idx = ePropertyExtraStartCommand; 218 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args); 219 } 220 221 FileSpec ProcessProperties::GetPythonOSPluginPath() const { 222 const uint32_t idx = ePropertyPythonOSPluginPath; 223 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx); 224 } 225 226 void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) { 227 const uint32_t idx = ePropertyPythonOSPluginPath; 228 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file); 229 } 230 231 bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const { 232 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions; 233 return m_collection_sp->GetPropertyAtIndexAsBoolean( 234 nullptr, idx, g_properties[idx].default_uint_value != 0); 235 } 236 237 void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) { 238 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions; 239 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore); 240 } 241 242 bool ProcessProperties::GetUnwindOnErrorInExpressions() const { 243 const uint32_t idx = ePropertyUnwindOnErrorInExpressions; 244 return m_collection_sp->GetPropertyAtIndexAsBoolean( 245 nullptr, idx, g_properties[idx].default_uint_value != 0); 246 } 247 248 void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) { 249 const uint32_t idx = ePropertyUnwindOnErrorInExpressions; 250 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore); 251 } 252 253 bool ProcessProperties::GetStopOnSharedLibraryEvents() const { 254 const uint32_t idx = ePropertyStopOnSharedLibraryEvents; 255 return m_collection_sp->GetPropertyAtIndexAsBoolean( 256 nullptr, idx, g_properties[idx].default_uint_value != 0); 257 } 258 259 void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) { 260 const uint32_t idx = ePropertyStopOnSharedLibraryEvents; 261 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop); 262 } 263 264 bool ProcessProperties::GetDetachKeepsStopped() const { 265 const uint32_t idx = ePropertyDetachKeepsStopped; 266 return m_collection_sp->GetPropertyAtIndexAsBoolean( 267 nullptr, idx, g_properties[idx].default_uint_value != 0); 268 } 269 270 void ProcessProperties::SetDetachKeepsStopped(bool stop) { 271 const uint32_t idx = ePropertyDetachKeepsStopped; 272 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop); 273 } 274 275 bool ProcessProperties::GetWarningsOptimization() const { 276 const uint32_t idx = ePropertyWarningOptimization; 277 return m_collection_sp->GetPropertyAtIndexAsBoolean( 278 nullptr, idx, g_properties[idx].default_uint_value != 0); 279 } 280 281 bool ProcessProperties::GetStopOnExec() const { 282 const uint32_t idx = ePropertyStopOnExec; 283 return m_collection_sp->GetPropertyAtIndexAsBoolean( 284 nullptr, idx, g_properties[idx].default_uint_value != 0); 285 } 286 287 std::chrono::seconds ProcessProperties::GetUtilityExpressionTimeout() const { 288 const uint32_t idx = ePropertyUtilityExpressionTimeout; 289 uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64( 290 nullptr, idx, g_properties[idx].default_uint_value); 291 return std::chrono::seconds(value); 292 } 293 294 Status ProcessLaunchCommandOptions::SetOptionValue( 295 uint32_t option_idx, llvm::StringRef option_arg, 296 ExecutionContext *execution_context) { 297 Status error; 298 const int short_option = m_getopt_table[option_idx].val; 299 300 switch (short_option) { 301 case 's': // Stop at program entry point 302 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry); 303 break; 304 305 case 'i': // STDIN for read only 306 { 307 FileAction action; 308 if (action.Open(STDIN_FILENO, FileSpec(option_arg), true, false)) 309 launch_info.AppendFileAction(action); 310 break; 311 } 312 313 case 'o': // Open STDOUT for write only 314 { 315 FileAction action; 316 if (action.Open(STDOUT_FILENO, FileSpec(option_arg), false, true)) 317 launch_info.AppendFileAction(action); 318 break; 319 } 320 321 case 'e': // STDERR for write only 322 { 323 FileAction action; 324 if (action.Open(STDERR_FILENO, FileSpec(option_arg), false, true)) 325 launch_info.AppendFileAction(action); 326 break; 327 } 328 329 case 'p': // Process plug-in name 330 launch_info.SetProcessPluginName(option_arg); 331 break; 332 333 case 'n': // Disable STDIO 334 { 335 FileAction action; 336 const FileSpec dev_null(FileSystem::DEV_NULL); 337 if (action.Open(STDIN_FILENO, dev_null, true, false)) 338 launch_info.AppendFileAction(action); 339 if (action.Open(STDOUT_FILENO, dev_null, false, true)) 340 launch_info.AppendFileAction(action); 341 if (action.Open(STDERR_FILENO, dev_null, false, true)) 342 launch_info.AppendFileAction(action); 343 break; 344 } 345 346 case 'w': 347 launch_info.SetWorkingDirectory(FileSpec(option_arg)); 348 break; 349 350 case 't': // Open process in new terminal window 351 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY); 352 break; 353 354 case 'a': { 355 TargetSP target_sp = 356 execution_context ? execution_context->GetTargetSP() : TargetSP(); 357 PlatformSP platform_sp = 358 target_sp ? target_sp->GetPlatform() : PlatformSP(); 359 launch_info.GetArchitecture() = 360 Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg); 361 } break; 362 363 case 'A': // Disable ASLR. 364 { 365 bool success; 366 const bool disable_aslr_arg = 367 OptionArgParser::ToBoolean(option_arg, true, &success); 368 if (success) 369 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo; 370 else 371 error.SetErrorStringWithFormat( 372 "Invalid boolean value for disable-aslr option: '%s'", 373 option_arg.empty() ? "<null>" : option_arg.str().c_str()); 374 break; 375 } 376 377 case 'X': // shell expand args. 378 { 379 bool success; 380 const bool expand_args = 381 OptionArgParser::ToBoolean(option_arg, true, &success); 382 if (success) 383 launch_info.SetShellExpandArguments(expand_args); 384 else 385 error.SetErrorStringWithFormat( 386 "Invalid boolean value for shell-expand-args option: '%s'", 387 option_arg.empty() ? "<null>" : option_arg.str().c_str()); 388 break; 389 } 390 391 case 'c': 392 if (!option_arg.empty()) 393 launch_info.SetShell(FileSpec(option_arg)); 394 else 395 launch_info.SetShell(HostInfo::GetDefaultShell()); 396 break; 397 398 case 'v': 399 launch_info.GetEnvironment().insert(option_arg); 400 break; 401 402 default: 403 error.SetErrorStringWithFormat("unrecognized short option character '%c'", 404 short_option); 405 break; 406 } 407 return error; 408 } 409 410 static constexpr OptionDefinition g_process_launch_options[] = { 411 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument, 412 nullptr, {}, 0, eArgTypeNone, 413 "Stop at the entry point of the program when launching a process."}, 414 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', 415 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, 416 "Set whether to disable address space layout randomization when launching " 417 "a process."}, 418 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, 419 nullptr, {}, 0, eArgTypePlugin, 420 "Name of the process plugin you want to use."}, 421 {LLDB_OPT_SET_ALL, false, "working-dir", 'w', 422 OptionParser::eRequiredArgument, nullptr, {}, 0, 423 eArgTypeDirectoryName, 424 "Set the current working directory to <path> when running the inferior."}, 425 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, 426 nullptr, {}, 0, eArgTypeArchitecture, 427 "Set the architecture for the process to launch when ambiguous."}, 428 {LLDB_OPT_SET_ALL, false, "environment", 'v', 429 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone, 430 "Specify an environment variable name/value string (--environment " 431 "NAME=VALUE). Can be specified multiple times for subsequent environment " 432 "entries."}, 433 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c', 434 OptionParser::eOptionalArgument, nullptr, {}, 0, eArgTypeFilename, 435 "Run the process in a shell (not supported on all platforms)."}, 436 437 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument, 438 nullptr, {}, 0, eArgTypeFilename, 439 "Redirect stdin for the process to <filename>."}, 440 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument, 441 nullptr, {}, 0, eArgTypeFilename, 442 "Redirect stdout for the process to <filename>."}, 443 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument, 444 nullptr, {}, 0, eArgTypeFilename, 445 "Redirect stderr for the process to <filename>."}, 446 447 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr, 448 {}, 0, eArgTypeNone, 449 "Start the process in a terminal (not supported on all platforms)."}, 450 451 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr, 452 {}, 0, eArgTypeNone, 453 "Do not set up for terminal I/O to go to running process."}, 454 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X', 455 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, 456 "Set whether to shell expand arguments to the process when launching."}, 457 }; 458 459 llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() { 460 return llvm::makeArrayRef(g_process_launch_options); 461 } 462 463 ProcessSP Process::FindPlugin(lldb::TargetSP target_sp, 464 llvm::StringRef plugin_name, 465 ListenerSP listener_sp, 466 const FileSpec *crash_file_path) { 467 static uint32_t g_process_unique_id = 0; 468 469 ProcessSP process_sp; 470 ProcessCreateInstance create_callback = nullptr; 471 if (!plugin_name.empty()) { 472 ConstString const_plugin_name(plugin_name); 473 create_callback = 474 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name); 475 if (create_callback) { 476 process_sp = create_callback(target_sp, listener_sp, crash_file_path); 477 if (process_sp) { 478 if (process_sp->CanDebug(target_sp, true)) { 479 process_sp->m_process_unique_id = ++g_process_unique_id; 480 } else 481 process_sp.reset(); 482 } 483 } 484 } else { 485 for (uint32_t idx = 0; 486 (create_callback = 487 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr; 488 ++idx) { 489 process_sp = create_callback(target_sp, listener_sp, crash_file_path); 490 if (process_sp) { 491 if (process_sp->CanDebug(target_sp, false)) { 492 process_sp->m_process_unique_id = ++g_process_unique_id; 493 break; 494 } else 495 process_sp.reset(); 496 } 497 } 498 } 499 return process_sp; 500 } 501 502 ConstString &Process::GetStaticBroadcasterClass() { 503 static ConstString class_name("lldb.process"); 504 return class_name; 505 } 506 507 Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp) 508 : Process(target_sp, listener_sp, 509 UnixSignals::Create(HostInfo::GetArchitecture())) { 510 // This constructor just delegates to the full Process constructor, 511 // defaulting to using the Host's UnixSignals. 512 } 513 514 Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp, 515 const UnixSignalsSP &unix_signals_sp) 516 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID), 517 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()), 518 Process::GetStaticBroadcasterClass().AsCString()), 519 m_target_wp(target_sp), m_public_state(eStateUnloaded), 520 m_private_state(eStateUnloaded), 521 m_private_state_broadcaster(nullptr, 522 "lldb.process.internal_state_broadcaster"), 523 m_private_state_control_broadcaster( 524 nullptr, "lldb.process.internal_state_control_broadcaster"), 525 m_private_state_listener_sp( 526 Listener::MakeListener("lldb.process.internal_state_listener")), 527 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0), 528 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(), 529 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this), 530 m_thread_list(this), m_extended_thread_list(this), 531 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0), 532 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp), 533 m_breakpoint_site_list(), m_dynamic_checkers_up(), 534 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(), 535 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(), 536 m_stdin_forward(false), m_stdout_data(), m_stderr_data(), 537 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0), 538 m_memory_cache(*this), m_allocated_memory_cache(*this), 539 m_should_detach(false), m_next_event_action_up(), m_public_run_lock(), 540 m_private_run_lock(), m_finalizing(false), m_finalize_called(false), 541 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false), 542 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false), 543 m_can_interpret_function_calls(false), m_warnings_issued(), 544 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) { 545 CheckInWithManager(); 546 547 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT)); 548 if (log) 549 log->Printf("%p Process::Process()", static_cast<void *>(this)); 550 551 if (!m_unix_signals_sp) 552 m_unix_signals_sp = std::make_shared<UnixSignals>(); 553 554 SetEventName(eBroadcastBitStateChanged, "state-changed"); 555 SetEventName(eBroadcastBitInterrupt, "interrupt"); 556 SetEventName(eBroadcastBitSTDOUT, "stdout-available"); 557 SetEventName(eBroadcastBitSTDERR, "stderr-available"); 558 SetEventName(eBroadcastBitProfileData, "profile-data-available"); 559 SetEventName(eBroadcastBitStructuredData, "structured-data-available"); 560 561 m_private_state_control_broadcaster.SetEventName( 562 eBroadcastInternalStateControlStop, "control-stop"); 563 m_private_state_control_broadcaster.SetEventName( 564 eBroadcastInternalStateControlPause, "control-pause"); 565 m_private_state_control_broadcaster.SetEventName( 566 eBroadcastInternalStateControlResume, "control-resume"); 567 568 m_listener_sp->StartListeningForEvents( 569 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt | 570 eBroadcastBitSTDOUT | eBroadcastBitSTDERR | 571 eBroadcastBitProfileData | eBroadcastBitStructuredData); 572 573 m_private_state_listener_sp->StartListeningForEvents( 574 &m_private_state_broadcaster, 575 eBroadcastBitStateChanged | eBroadcastBitInterrupt); 576 577 m_private_state_listener_sp->StartListeningForEvents( 578 &m_private_state_control_broadcaster, 579 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause | 580 eBroadcastInternalStateControlResume); 581 // We need something valid here, even if just the default UnixSignalsSP. 582 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization"); 583 584 // Allow the platform to override the default cache line size 585 OptionValueSP value_sp = 586 m_collection_sp 587 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize) 588 ->GetValue(); 589 uint32_t platform_cache_line_size = 590 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize(); 591 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0) 592 value_sp->SetUInt64Value(platform_cache_line_size); 593 } 594 595 Process::~Process() { 596 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT)); 597 if (log) 598 log->Printf("%p Process::~Process()", static_cast<void *>(this)); 599 StopPrivateStateThread(); 600 601 // ThreadList::Clear() will try to acquire this process's mutex, so 602 // explicitly clear the thread list here to ensure that the mutex is not 603 // destroyed before the thread list. 604 m_thread_list.Clear(); 605 } 606 607 const ProcessPropertiesSP &Process::GetGlobalProperties() { 608 // NOTE: intentional leak so we don't crash if global destructor chain gets 609 // called as other threads still use the result of this function 610 static ProcessPropertiesSP *g_settings_sp_ptr = 611 new ProcessPropertiesSP(new ProcessProperties(nullptr)); 612 return *g_settings_sp_ptr; 613 } 614 615 void Process::Finalize() { 616 m_finalizing = true; 617 618 // Destroy this process if needed 619 switch (GetPrivateState()) { 620 case eStateConnected: 621 case eStateAttaching: 622 case eStateLaunching: 623 case eStateStopped: 624 case eStateRunning: 625 case eStateStepping: 626 case eStateCrashed: 627 case eStateSuspended: 628 Destroy(false); 629 break; 630 631 case eStateInvalid: 632 case eStateUnloaded: 633 case eStateDetached: 634 case eStateExited: 635 break; 636 } 637 638 // Clear our broadcaster before we proceed with destroying 639 Broadcaster::Clear(); 640 641 // Do any cleanup needed prior to being destructed... Subclasses that 642 // override this method should call this superclass method as well. 643 644 // We need to destroy the loader before the derived Process class gets 645 // destroyed since it is very likely that undoing the loader will require 646 // access to the real process. 647 m_dynamic_checkers_up.reset(); 648 m_abi_sp.reset(); 649 m_os_up.reset(); 650 m_system_runtime_up.reset(); 651 m_dyld_up.reset(); 652 m_jit_loaders_up.reset(); 653 m_thread_list_real.Destroy(); 654 m_thread_list.Destroy(); 655 m_extended_thread_list.Destroy(); 656 m_queue_list.Clear(); 657 m_queue_list_stop_id = 0; 658 std::vector<Notifications> empty_notifications; 659 m_notifications.swap(empty_notifications); 660 m_image_tokens.clear(); 661 m_memory_cache.Clear(); 662 m_allocated_memory_cache.Clear(); 663 { 664 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex); 665 m_language_runtimes.clear(); 666 } 667 m_instrumentation_runtimes.clear(); 668 m_next_event_action_up.reset(); 669 // Clear the last natural stop ID since it has a strong reference to this 670 // process 671 m_mod_id.SetStopEventForLastNaturalStopID(EventSP()); 672 //#ifdef LLDB_CONFIGURATION_DEBUG 673 // StreamFile s(stdout, false); 674 // EventSP event_sp; 675 // while (m_private_state_listener_sp->GetNextEvent(event_sp)) 676 // { 677 // event_sp->Dump (&s); 678 // s.EOL(); 679 // } 680 //#endif 681 // We have to be very careful here as the m_private_state_listener might 682 // contain events that have ProcessSP values in them which can keep this 683 // process around forever. These events need to be cleared out. 684 m_private_state_listener_sp->Clear(); 685 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked 686 m_public_run_lock.SetStopped(); 687 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked 688 m_private_run_lock.SetStopped(); 689 m_structured_data_plugin_map.clear(); 690 m_finalize_called = true; 691 } 692 693 void Process::RegisterNotificationCallbacks(const Notifications &callbacks) { 694 m_notifications.push_back(callbacks); 695 if (callbacks.initialize != nullptr) 696 callbacks.initialize(callbacks.baton, this); 697 } 698 699 bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) { 700 std::vector<Notifications>::iterator pos, end = m_notifications.end(); 701 for (pos = m_notifications.begin(); pos != end; ++pos) { 702 if (pos->baton == callbacks.baton && 703 pos->initialize == callbacks.initialize && 704 pos->process_state_changed == callbacks.process_state_changed) { 705 m_notifications.erase(pos); 706 return true; 707 } 708 } 709 return false; 710 } 711 712 void Process::SynchronouslyNotifyStateChanged(StateType state) { 713 std::vector<Notifications>::iterator notification_pos, 714 notification_end = m_notifications.end(); 715 for (notification_pos = m_notifications.begin(); 716 notification_pos != notification_end; ++notification_pos) { 717 if (notification_pos->process_state_changed) 718 notification_pos->process_state_changed(notification_pos->baton, this, 719 state); 720 } 721 } 722 723 // FIXME: We need to do some work on events before the general Listener sees 724 // them. 725 // For instance if we are continuing from a breakpoint, we need to ensure that 726 // we do the little "insert real insn, step & stop" trick. But we can't do 727 // that when the event is delivered by the broadcaster - since that is done on 728 // the thread that is waiting for new events, so if we needed more than one 729 // event for our handling, we would stall. So instead we do it when we fetch 730 // the event off of the queue. 731 // 732 733 StateType Process::GetNextEvent(EventSP &event_sp) { 734 StateType state = eStateInvalid; 735 736 if (m_listener_sp->GetEventForBroadcaster(this, event_sp, 737 std::chrono::seconds(0)) && 738 event_sp) 739 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 740 741 return state; 742 } 743 744 void Process::SyncIOHandler(uint32_t iohandler_id, 745 const Timeout<std::micro> &timeout) { 746 // don't sync (potentially context switch) in case where there is no process 747 // IO 748 if (!m_process_input_reader) 749 return; 750 751 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout); 752 753 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 754 if (Result) { 755 LLDB_LOG( 756 log, 757 "waited from m_iohandler_sync to change from {0}. New value is {1}.", 758 iohandler_id, *Result); 759 } else { 760 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.", 761 iohandler_id); 762 } 763 } 764 765 StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout, 766 EventSP *event_sp_ptr, bool wait_always, 767 ListenerSP hijack_listener_sp, 768 Stream *stream, bool use_run_lock) { 769 // We can't just wait for a "stopped" event, because the stopped event may 770 // have restarted the target. We have to actually check each event, and in 771 // the case of a stopped event check the restarted flag on the event. 772 if (event_sp_ptr) 773 event_sp_ptr->reset(); 774 StateType state = GetState(); 775 // If we are exited or detached, we won't ever get back to any other valid 776 // state... 777 if (state == eStateDetached || state == eStateExited) 778 return state; 779 780 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 781 LLDB_LOG(log, "timeout = {0}", timeout); 782 783 if (!wait_always && StateIsStoppedState(state, true) && 784 StateIsStoppedState(GetPrivateState(), true)) { 785 if (log) 786 log->Printf("Process::%s returning without waiting for events; process " 787 "private and public states are already 'stopped'.", 788 __FUNCTION__); 789 // We need to toggle the run lock as this won't get done in 790 // SetPublicState() if the process is hijacked. 791 if (hijack_listener_sp && use_run_lock) 792 m_public_run_lock.SetStopped(); 793 return state; 794 } 795 796 while (state != eStateInvalid) { 797 EventSP event_sp; 798 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp); 799 if (event_sp_ptr && event_sp) 800 *event_sp_ptr = event_sp; 801 802 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr); 803 Process::HandleProcessStateChangedEvent(event_sp, stream, 804 pop_process_io_handler); 805 806 switch (state) { 807 case eStateCrashed: 808 case eStateDetached: 809 case eStateExited: 810 case eStateUnloaded: 811 // We need to toggle the run lock as this won't get done in 812 // SetPublicState() if the process is hijacked. 813 if (hijack_listener_sp && use_run_lock) 814 m_public_run_lock.SetStopped(); 815 return state; 816 case eStateStopped: 817 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) 818 continue; 819 else { 820 // We need to toggle the run lock as this won't get done in 821 // SetPublicState() if the process is hijacked. 822 if (hijack_listener_sp && use_run_lock) 823 m_public_run_lock.SetStopped(); 824 return state; 825 } 826 default: 827 continue; 828 } 829 } 830 return state; 831 } 832 833 bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp, 834 Stream *stream, 835 bool &pop_process_io_handler) { 836 const bool handle_pop = pop_process_io_handler; 837 838 pop_process_io_handler = false; 839 ProcessSP process_sp = 840 Process::ProcessEventData::GetProcessFromEvent(event_sp.get()); 841 842 if (!process_sp) 843 return false; 844 845 StateType event_state = 846 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 847 if (event_state == eStateInvalid) 848 return false; 849 850 switch (event_state) { 851 case eStateInvalid: 852 case eStateUnloaded: 853 case eStateAttaching: 854 case eStateLaunching: 855 case eStateStepping: 856 case eStateDetached: 857 if (stream) 858 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(), 859 StateAsCString(event_state)); 860 if (event_state == eStateDetached) 861 pop_process_io_handler = true; 862 break; 863 864 case eStateConnected: 865 case eStateRunning: 866 // Don't be chatty when we run... 867 break; 868 869 case eStateExited: 870 if (stream) 871 process_sp->GetStatus(*stream); 872 pop_process_io_handler = true; 873 break; 874 875 case eStateStopped: 876 case eStateCrashed: 877 case eStateSuspended: 878 // Make sure the program hasn't been auto-restarted: 879 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) { 880 if (stream) { 881 size_t num_reasons = 882 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get()); 883 if (num_reasons > 0) { 884 // FIXME: Do we want to report this, or would that just be annoyingly 885 // chatty? 886 if (num_reasons == 1) { 887 const char *reason = 888 Process::ProcessEventData::GetRestartedReasonAtIndex( 889 event_sp.get(), 0); 890 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n", 891 process_sp->GetID(), 892 reason ? reason : "<UNKNOWN REASON>"); 893 } else { 894 stream->Printf("Process %" PRIu64 895 " stopped and restarted, reasons:\n", 896 process_sp->GetID()); 897 898 for (size_t i = 0; i < num_reasons; i++) { 899 const char *reason = 900 Process::ProcessEventData::GetRestartedReasonAtIndex( 901 event_sp.get(), i); 902 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>"); 903 } 904 } 905 } 906 } 907 } else { 908 StopInfoSP curr_thread_stop_info_sp; 909 // Lock the thread list so it doesn't change on us, this is the scope for 910 // the locker: 911 { 912 ThreadList &thread_list = process_sp->GetThreadList(); 913 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex()); 914 915 ThreadSP curr_thread(thread_list.GetSelectedThread()); 916 ThreadSP thread; 917 StopReason curr_thread_stop_reason = eStopReasonInvalid; 918 if (curr_thread) { 919 curr_thread_stop_reason = curr_thread->GetStopReason(); 920 curr_thread_stop_info_sp = curr_thread->GetStopInfo(); 921 } 922 if (!curr_thread || !curr_thread->IsValid() || 923 curr_thread_stop_reason == eStopReasonInvalid || 924 curr_thread_stop_reason == eStopReasonNone) { 925 // Prefer a thread that has just completed its plan over another 926 // thread as current thread. 927 ThreadSP plan_thread; 928 ThreadSP other_thread; 929 930 const size_t num_threads = thread_list.GetSize(); 931 size_t i; 932 for (i = 0; i < num_threads; ++i) { 933 thread = thread_list.GetThreadAtIndex(i); 934 StopReason thread_stop_reason = thread->GetStopReason(); 935 switch (thread_stop_reason) { 936 case eStopReasonInvalid: 937 case eStopReasonNone: 938 break; 939 940 case eStopReasonSignal: { 941 // Don't select a signal thread if we weren't going to stop at 942 // that signal. We have to have had another reason for stopping 943 // here, and the user doesn't want to see this thread. 944 uint64_t signo = thread->GetStopInfo()->GetValue(); 945 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) { 946 if (!other_thread) 947 other_thread = thread; 948 } 949 break; 950 } 951 case eStopReasonTrace: 952 case eStopReasonBreakpoint: 953 case eStopReasonWatchpoint: 954 case eStopReasonException: 955 case eStopReasonExec: 956 case eStopReasonThreadExiting: 957 case eStopReasonInstrumentation: 958 if (!other_thread) 959 other_thread = thread; 960 break; 961 case eStopReasonPlanComplete: 962 if (!plan_thread) 963 plan_thread = thread; 964 break; 965 } 966 } 967 if (plan_thread) 968 thread_list.SetSelectedThreadByID(plan_thread->GetID()); 969 else if (other_thread) 970 thread_list.SetSelectedThreadByID(other_thread->GetID()); 971 else { 972 if (curr_thread && curr_thread->IsValid()) 973 thread = curr_thread; 974 else 975 thread = thread_list.GetThreadAtIndex(0); 976 977 if (thread) 978 thread_list.SetSelectedThreadByID(thread->GetID()); 979 } 980 } 981 } 982 // Drop the ThreadList mutex by here, since GetThreadStatus below might 983 // have to run code, e.g. for Data formatters, and if we hold the 984 // ThreadList mutex, then the process is going to have a hard time 985 // restarting the process. 986 if (stream) { 987 Debugger &debugger = process_sp->GetTarget().GetDebugger(); 988 if (debugger.GetTargetList().GetSelectedTarget().get() == 989 &process_sp->GetTarget()) { 990 const bool only_threads_with_stop_reason = true; 991 const uint32_t start_frame = 0; 992 const uint32_t num_frames = 1; 993 const uint32_t num_frames_with_source = 1; 994 const bool stop_format = true; 995 process_sp->GetStatus(*stream); 996 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason, 997 start_frame, num_frames, 998 num_frames_with_source, 999 stop_format); 1000 if (curr_thread_stop_info_sp) { 1001 lldb::addr_t crashing_address; 1002 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference( 1003 curr_thread_stop_info_sp, &crashing_address); 1004 if (valobj_sp) { 1005 const bool qualify_cxx_base_classes = false; 1006 1007 const ValueObject::GetExpressionPathFormat format = 1008 ValueObject::GetExpressionPathFormat:: 1009 eGetExpressionPathFormatHonorPointers; 1010 stream->PutCString("Likely cause: "); 1011 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes, 1012 format); 1013 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address); 1014 } 1015 } 1016 } else { 1017 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget( 1018 process_sp->GetTarget().shared_from_this()); 1019 if (target_idx != UINT32_MAX) 1020 stream->Printf("Target %d: (", target_idx); 1021 else 1022 stream->Printf("Target <unknown index>: ("); 1023 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief); 1024 stream->Printf(") stopped.\n"); 1025 } 1026 } 1027 1028 // Pop the process IO handler 1029 pop_process_io_handler = true; 1030 } 1031 break; 1032 } 1033 1034 if (handle_pop && pop_process_io_handler) 1035 process_sp->PopProcessIOHandler(); 1036 1037 return true; 1038 } 1039 1040 bool Process::HijackProcessEvents(ListenerSP listener_sp) { 1041 if (listener_sp) { 1042 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged | 1043 eBroadcastBitInterrupt); 1044 } else 1045 return false; 1046 } 1047 1048 void Process::RestoreProcessEvents() { RestoreBroadcaster(); } 1049 1050 StateType Process::GetStateChangedEvents(EventSP &event_sp, 1051 const Timeout<std::micro> &timeout, 1052 ListenerSP hijack_listener_sp) { 1053 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1054 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout); 1055 1056 ListenerSP listener_sp = hijack_listener_sp; 1057 if (!listener_sp) 1058 listener_sp = m_listener_sp; 1059 1060 StateType state = eStateInvalid; 1061 if (listener_sp->GetEventForBroadcasterWithType( 1062 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp, 1063 timeout)) { 1064 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged) 1065 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 1066 else 1067 LLDB_LOG(log, "got no event or was interrupted."); 1068 } 1069 1070 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state); 1071 return state; 1072 } 1073 1074 Event *Process::PeekAtStateChangedEvents() { 1075 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1076 1077 if (log) 1078 log->Printf("Process::%s...", __FUNCTION__); 1079 1080 Event *event_ptr; 1081 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType( 1082 this, eBroadcastBitStateChanged); 1083 if (log) { 1084 if (event_ptr) { 1085 log->Printf( 1086 "Process::%s (event_ptr) => %s", __FUNCTION__, 1087 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr))); 1088 } else { 1089 log->Printf("Process::%s no events found", __FUNCTION__); 1090 } 1091 } 1092 return event_ptr; 1093 } 1094 1095 StateType 1096 Process::GetStateChangedEventsPrivate(EventSP &event_sp, 1097 const Timeout<std::micro> &timeout) { 1098 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1099 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout); 1100 1101 StateType state = eStateInvalid; 1102 if (m_private_state_listener_sp->GetEventForBroadcasterWithType( 1103 &m_private_state_broadcaster, 1104 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp, 1105 timeout)) 1106 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged) 1107 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 1108 1109 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, 1110 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state)); 1111 return state; 1112 } 1113 1114 bool Process::GetEventsPrivate(EventSP &event_sp, 1115 const Timeout<std::micro> &timeout, 1116 bool control_only) { 1117 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1118 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout); 1119 1120 if (control_only) 1121 return m_private_state_listener_sp->GetEventForBroadcaster( 1122 &m_private_state_control_broadcaster, event_sp, timeout); 1123 else 1124 return m_private_state_listener_sp->GetEvent(event_sp, timeout); 1125 } 1126 1127 bool Process::IsRunning() const { 1128 return StateIsRunningState(m_public_state.GetValue()); 1129 } 1130 1131 int Process::GetExitStatus() { 1132 std::lock_guard<std::mutex> guard(m_exit_status_mutex); 1133 1134 if (m_public_state.GetValue() == eStateExited) 1135 return m_exit_status; 1136 return -1; 1137 } 1138 1139 const char *Process::GetExitDescription() { 1140 std::lock_guard<std::mutex> guard(m_exit_status_mutex); 1141 1142 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty()) 1143 return m_exit_string.c_str(); 1144 return nullptr; 1145 } 1146 1147 bool Process::SetExitStatus(int status, const char *cstr) { 1148 // Use a mutex to protect setting the exit status. 1149 std::lock_guard<std::mutex> guard(m_exit_status_mutex); 1150 1151 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE | 1152 LIBLLDB_LOG_PROCESS)); 1153 if (log) 1154 log->Printf( 1155 "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)", 1156 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL", 1157 cstr ? "\"" : ""); 1158 1159 // We were already in the exited state 1160 if (m_private_state.GetValue() == eStateExited) { 1161 if (log) 1162 log->Printf("Process::SetExitStatus () ignoring exit status because " 1163 "state was already set to eStateExited"); 1164 return false; 1165 } 1166 1167 m_exit_status = status; 1168 if (cstr) 1169 m_exit_string = cstr; 1170 else 1171 m_exit_string.clear(); 1172 1173 // Clear the last natural stop ID since it has a strong reference to this 1174 // process 1175 m_mod_id.SetStopEventForLastNaturalStopID(EventSP()); 1176 1177 SetPrivateState(eStateExited); 1178 1179 // Allow subclasses to do some cleanup 1180 DidExit(); 1181 1182 return true; 1183 } 1184 1185 bool Process::IsAlive() { 1186 switch (m_private_state.GetValue()) { 1187 case eStateConnected: 1188 case eStateAttaching: 1189 case eStateLaunching: 1190 case eStateStopped: 1191 case eStateRunning: 1192 case eStateStepping: 1193 case eStateCrashed: 1194 case eStateSuspended: 1195 return true; 1196 default: 1197 return false; 1198 } 1199 } 1200 1201 // This static callback can be used to watch for local child processes on the 1202 // current host. The child process exits, the process will be found in the 1203 // global target list (we want to be completely sure that the 1204 // lldb_private::Process doesn't go away before we can deliver the signal. 1205 bool Process::SetProcessExitStatus( 1206 lldb::pid_t pid, bool exited, 1207 int signo, // Zero for no signal 1208 int exit_status // Exit value of process if signal is zero 1209 ) { 1210 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 1211 if (log) 1212 log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64 1213 ", exited=%i, signal=%i, exit_status=%i)\n", 1214 pid, exited, signo, exit_status); 1215 1216 if (exited) { 1217 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid)); 1218 if (target_sp) { 1219 ProcessSP process_sp(target_sp->GetProcessSP()); 1220 if (process_sp) { 1221 const char *signal_cstr = nullptr; 1222 if (signo) 1223 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo); 1224 1225 process_sp->SetExitStatus(exit_status, signal_cstr); 1226 } 1227 } 1228 return true; 1229 } 1230 return false; 1231 } 1232 1233 void Process::UpdateThreadListIfNeeded() { 1234 const uint32_t stop_id = GetStopID(); 1235 if (m_thread_list.GetSize(false) == 0 || 1236 stop_id != m_thread_list.GetStopID()) { 1237 const StateType state = GetPrivateState(); 1238 if (StateIsStoppedState(state, true)) { 1239 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex()); 1240 // m_thread_list does have its own mutex, but we need to hold onto the 1241 // mutex between the call to UpdateThreadList(...) and the 1242 // os->UpdateThreadList(...) so it doesn't change on us 1243 ThreadList &old_thread_list = m_thread_list; 1244 ThreadList real_thread_list(this); 1245 ThreadList new_thread_list(this); 1246 // Always update the thread list with the protocol specific thread list, 1247 // but only update if "true" is returned 1248 if (UpdateThreadList(m_thread_list_real, real_thread_list)) { 1249 // Don't call into the OperatingSystem to update the thread list if we 1250 // are shutting down, since that may call back into the SBAPI's, 1251 // requiring the API lock which is already held by whoever is shutting 1252 // us down, causing a deadlock. 1253 OperatingSystem *os = GetOperatingSystem(); 1254 if (os && !m_destroy_in_process) { 1255 // Clear any old backing threads where memory threads might have been 1256 // backed by actual threads from the lldb_private::Process subclass 1257 size_t num_old_threads = old_thread_list.GetSize(false); 1258 for (size_t i = 0; i < num_old_threads; ++i) 1259 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread(); 1260 1261 // Turn off dynamic types to ensure we don't run any expressions. 1262 // Objective-C can run an expression to determine if a SBValue is a 1263 // dynamic type or not and we need to avoid this. OperatingSystem 1264 // plug-ins can't run expressions that require running code... 1265 1266 Target &target = GetTarget(); 1267 const lldb::DynamicValueType saved_prefer_dynamic = 1268 target.GetPreferDynamicValue(); 1269 if (saved_prefer_dynamic != lldb::eNoDynamicValues) 1270 target.SetPreferDynamicValue(lldb::eNoDynamicValues); 1271 1272 // Now let the OperatingSystem plug-in update the thread list 1273 1274 os->UpdateThreadList( 1275 old_thread_list, // Old list full of threads created by OS plug-in 1276 real_thread_list, // The actual thread list full of threads 1277 // created by each lldb_private::Process 1278 // subclass 1279 new_thread_list); // The new thread list that we will show to the 1280 // user that gets filled in 1281 1282 if (saved_prefer_dynamic != lldb::eNoDynamicValues) 1283 target.SetPreferDynamicValue(saved_prefer_dynamic); 1284 } else { 1285 // No OS plug-in, the new thread list is the same as the real thread 1286 // list 1287 new_thread_list = real_thread_list; 1288 } 1289 1290 m_thread_list_real.Update(real_thread_list); 1291 m_thread_list.Update(new_thread_list); 1292 m_thread_list.SetStopID(stop_id); 1293 1294 if (GetLastNaturalStopID() != m_extended_thread_stop_id) { 1295 // Clear any extended threads that we may have accumulated previously 1296 m_extended_thread_list.Clear(); 1297 m_extended_thread_stop_id = GetLastNaturalStopID(); 1298 1299 m_queue_list.Clear(); 1300 m_queue_list_stop_id = GetLastNaturalStopID(); 1301 } 1302 } 1303 } 1304 } 1305 } 1306 1307 void Process::UpdateQueueListIfNeeded() { 1308 if (m_system_runtime_up) { 1309 if (m_queue_list.GetSize() == 0 || 1310 m_queue_list_stop_id != GetLastNaturalStopID()) { 1311 const StateType state = GetPrivateState(); 1312 if (StateIsStoppedState(state, true)) { 1313 m_system_runtime_up->PopulateQueueList(m_queue_list); 1314 m_queue_list_stop_id = GetLastNaturalStopID(); 1315 } 1316 } 1317 } 1318 } 1319 1320 ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) { 1321 OperatingSystem *os = GetOperatingSystem(); 1322 if (os) 1323 return os->CreateThread(tid, context); 1324 return ThreadSP(); 1325 } 1326 1327 uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) { 1328 return AssignIndexIDToThread(thread_id); 1329 } 1330 1331 bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) { 1332 return (m_thread_id_to_index_id_map.find(thread_id) != 1333 m_thread_id_to_index_id_map.end()); 1334 } 1335 1336 uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) { 1337 uint32_t result = 0; 1338 std::map<uint64_t, uint32_t>::iterator iterator = 1339 m_thread_id_to_index_id_map.find(thread_id); 1340 if (iterator == m_thread_id_to_index_id_map.end()) { 1341 result = ++m_thread_index_id; 1342 m_thread_id_to_index_id_map[thread_id] = result; 1343 } else { 1344 result = iterator->second; 1345 } 1346 1347 return result; 1348 } 1349 1350 StateType Process::GetState() { 1351 return m_public_state.GetValue(); 1352 } 1353 1354 void Process::SetPublicState(StateType new_state, bool restarted) { 1355 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE | 1356 LIBLLDB_LOG_PROCESS)); 1357 if (log) 1358 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", 1359 StateAsCString(new_state), restarted); 1360 const StateType old_state = m_public_state.GetValue(); 1361 m_public_state.SetValue(new_state); 1362 1363 // On the transition from Run to Stopped, we unlock the writer end of the run 1364 // lock. The lock gets locked in Resume, which is the public API to tell the 1365 // program to run. 1366 if (!StateChangedIsExternallyHijacked()) { 1367 if (new_state == eStateDetached) { 1368 if (log) 1369 log->Printf( 1370 "Process::SetPublicState (%s) -- unlocking run lock for detach", 1371 StateAsCString(new_state)); 1372 m_public_run_lock.SetStopped(); 1373 } else { 1374 const bool old_state_is_stopped = StateIsStoppedState(old_state, false); 1375 const bool new_state_is_stopped = StateIsStoppedState(new_state, false); 1376 if ((old_state_is_stopped != new_state_is_stopped)) { 1377 if (new_state_is_stopped && !restarted) { 1378 if (log) 1379 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", 1380 StateAsCString(new_state)); 1381 m_public_run_lock.SetStopped(); 1382 } 1383 } 1384 } 1385 } 1386 } 1387 1388 Status Process::Resume() { 1389 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE | 1390 LIBLLDB_LOG_PROCESS)); 1391 if (log) 1392 log->Printf("Process::Resume -- locking run lock"); 1393 if (!m_public_run_lock.TrySetRunning()) { 1394 Status error("Resume request failed - process still running."); 1395 if (log) 1396 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming."); 1397 return error; 1398 } 1399 Status error = PrivateResume(); 1400 if (!error.Success()) { 1401 // Undo running state change 1402 m_public_run_lock.SetStopped(); 1403 } 1404 return error; 1405 } 1406 1407 static const char *g_resume_sync_name = "lldb.Process.ResumeSynchronous.hijack"; 1408 1409 Status Process::ResumeSynchronous(Stream *stream) { 1410 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE | 1411 LIBLLDB_LOG_PROCESS)); 1412 if (log) 1413 log->Printf("Process::ResumeSynchronous -- locking run lock"); 1414 if (!m_public_run_lock.TrySetRunning()) { 1415 Status error("Resume request failed - process still running."); 1416 if (log) 1417 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming."); 1418 return error; 1419 } 1420 1421 ListenerSP listener_sp( 1422 Listener::MakeListener(g_resume_sync_name)); 1423 HijackProcessEvents(listener_sp); 1424 1425 Status error = PrivateResume(); 1426 if (error.Success()) { 1427 StateType state = 1428 WaitForProcessToStop(llvm::None, nullptr, true, listener_sp, stream); 1429 const bool must_be_alive = 1430 false; // eStateExited is ok, so this must be false 1431 if (!StateIsStoppedState(state, must_be_alive)) 1432 error.SetErrorStringWithFormat( 1433 "process not in stopped state after synchronous resume: %s", 1434 StateAsCString(state)); 1435 } else { 1436 // Undo running state change 1437 m_public_run_lock.SetStopped(); 1438 } 1439 1440 // Undo the hijacking of process events... 1441 RestoreProcessEvents(); 1442 1443 return error; 1444 } 1445 1446 bool Process::StateChangedIsExternallyHijacked() { 1447 if (IsHijackedForEvent(eBroadcastBitStateChanged)) { 1448 const char *hijacking_name = GetHijackingListenerName(); 1449 if (hijacking_name && 1450 strcmp(hijacking_name, g_resume_sync_name)) 1451 return true; 1452 } 1453 return false; 1454 } 1455 1456 bool Process::StateChangedIsHijackedForSynchronousResume() { 1457 if (IsHijackedForEvent(eBroadcastBitStateChanged)) { 1458 const char *hijacking_name = GetHijackingListenerName(); 1459 if (hijacking_name && 1460 strcmp(hijacking_name, g_resume_sync_name) == 0) 1461 return true; 1462 } 1463 return false; 1464 } 1465 1466 StateType Process::GetPrivateState() { return m_private_state.GetValue(); } 1467 1468 void Process::SetPrivateState(StateType new_state) { 1469 if (m_finalize_called) 1470 return; 1471 1472 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE | 1473 LIBLLDB_LOG_PROCESS)); 1474 bool state_changed = false; 1475 1476 if (log) 1477 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state)); 1478 1479 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex()); 1480 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex()); 1481 1482 const StateType old_state = m_private_state.GetValueNoLock(); 1483 state_changed = old_state != new_state; 1484 1485 const bool old_state_is_stopped = StateIsStoppedState(old_state, false); 1486 const bool new_state_is_stopped = StateIsStoppedState(new_state, false); 1487 if (old_state_is_stopped != new_state_is_stopped) { 1488 if (new_state_is_stopped) 1489 m_private_run_lock.SetStopped(); 1490 else 1491 m_private_run_lock.SetRunning(); 1492 } 1493 1494 if (state_changed) { 1495 m_private_state.SetValueNoLock(new_state); 1496 EventSP event_sp( 1497 new Event(eBroadcastBitStateChanged, 1498 new ProcessEventData(shared_from_this(), new_state))); 1499 if (StateIsStoppedState(new_state, false)) { 1500 // Note, this currently assumes that all threads in the list stop when 1501 // the process stops. In the future we will want to support a debugging 1502 // model where some threads continue to run while others are stopped. 1503 // When that happens we will either need a way for the thread list to 1504 // identify which threads are stopping or create a special thread list 1505 // containing only threads which actually stopped. 1506 // 1507 // The process plugin is responsible for managing the actual behavior of 1508 // the threads and should have stopped any threads that are going to stop 1509 // before we get here. 1510 m_thread_list.DidStop(); 1511 1512 m_mod_id.BumpStopID(); 1513 if (!m_mod_id.IsLastResumeForUserExpression()) 1514 m_mod_id.SetStopEventForLastNaturalStopID(event_sp); 1515 m_memory_cache.Clear(); 1516 if (log) 1517 log->Printf("Process::SetPrivateState (%s) stop_id = %u", 1518 StateAsCString(new_state), m_mod_id.GetStopID()); 1519 } 1520 1521 // Use our target to get a shared pointer to ourselves... 1522 if (m_finalize_called && !PrivateStateThreadIsValid()) 1523 BroadcastEvent(event_sp); 1524 else 1525 m_private_state_broadcaster.BroadcastEvent(event_sp); 1526 } else { 1527 if (log) 1528 log->Printf( 1529 "Process::SetPrivateState (%s) state didn't change. Ignoring...", 1530 StateAsCString(new_state)); 1531 } 1532 } 1533 1534 void Process::SetRunningUserExpression(bool on) { 1535 m_mod_id.SetRunningUserExpression(on); 1536 } 1537 1538 void Process::SetRunningUtilityFunction(bool on) { 1539 m_mod_id.SetRunningUtilityFunction(on); 1540 } 1541 1542 addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; } 1543 1544 const lldb::ABISP &Process::GetABI() { 1545 if (!m_abi_sp) 1546 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture()); 1547 return m_abi_sp; 1548 } 1549 1550 LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language, 1551 bool retry_if_null) { 1552 if (m_finalizing) 1553 return nullptr; 1554 1555 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex); 1556 LanguageRuntimeCollection::iterator pos; 1557 pos = m_language_runtimes.find(language); 1558 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) { 1559 lldb::LanguageRuntimeSP runtime_sp( 1560 LanguageRuntime::FindPlugin(this, language)); 1561 1562 m_language_runtimes[language] = runtime_sp; 1563 return runtime_sp.get(); 1564 } else 1565 return (*pos).second.get(); 1566 } 1567 1568 CPPLanguageRuntime *Process::GetCPPLanguageRuntime(bool retry_if_null) { 1569 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex); 1570 LanguageRuntime *runtime = 1571 GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null); 1572 if (!runtime) 1573 return nullptr; 1574 1575 assert(runtime->GetLanguageType() == eLanguageTypeC_plus_plus); 1576 return static_cast<CPPLanguageRuntime *>(runtime); 1577 } 1578 1579 ObjCLanguageRuntime *Process::GetObjCLanguageRuntime(bool retry_if_null) { 1580 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex); 1581 LanguageRuntime *runtime = 1582 GetLanguageRuntime(eLanguageTypeObjC, retry_if_null); 1583 if (!runtime) 1584 return nullptr; 1585 1586 assert(runtime->GetLanguageType() == eLanguageTypeObjC); 1587 return static_cast<ObjCLanguageRuntime *>(runtime); 1588 } 1589 1590 bool Process::IsPossibleDynamicValue(ValueObject &in_value) { 1591 if (m_finalizing) 1592 return false; 1593 1594 if (in_value.IsDynamic()) 1595 return false; 1596 LanguageType known_type = in_value.GetObjectRuntimeLanguage(); 1597 1598 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) { 1599 LanguageRuntime *runtime = GetLanguageRuntime(known_type); 1600 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false; 1601 } 1602 1603 LanguageRuntime *cpp_runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus); 1604 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value)) 1605 return true; 1606 1607 LanguageRuntime *objc_runtime = GetLanguageRuntime(eLanguageTypeObjC); 1608 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false; 1609 } 1610 1611 void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) { 1612 m_dynamic_checkers_up.reset(dynamic_checkers); 1613 } 1614 1615 BreakpointSiteList &Process::GetBreakpointSiteList() { 1616 return m_breakpoint_site_list; 1617 } 1618 1619 const BreakpointSiteList &Process::GetBreakpointSiteList() const { 1620 return m_breakpoint_site_list; 1621 } 1622 1623 void Process::DisableAllBreakpointSites() { 1624 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void { 1625 // bp_site->SetEnabled(true); 1626 DisableBreakpointSite(bp_site); 1627 }); 1628 } 1629 1630 Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) { 1631 Status error(DisableBreakpointSiteByID(break_id)); 1632 1633 if (error.Success()) 1634 m_breakpoint_site_list.Remove(break_id); 1635 1636 return error; 1637 } 1638 1639 Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) { 1640 Status error; 1641 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id); 1642 if (bp_site_sp) { 1643 if (bp_site_sp->IsEnabled()) 1644 error = DisableBreakpointSite(bp_site_sp.get()); 1645 } else { 1646 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, 1647 break_id); 1648 } 1649 1650 return error; 1651 } 1652 1653 Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) { 1654 Status error; 1655 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id); 1656 if (bp_site_sp) { 1657 if (!bp_site_sp->IsEnabled()) 1658 error = EnableBreakpointSite(bp_site_sp.get()); 1659 } else { 1660 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, 1661 break_id); 1662 } 1663 return error; 1664 } 1665 1666 lldb::break_id_t 1667 Process::CreateBreakpointSite(const BreakpointLocationSP &owner, 1668 bool use_hardware) { 1669 addr_t load_addr = LLDB_INVALID_ADDRESS; 1670 1671 bool show_error = true; 1672 switch (GetState()) { 1673 case eStateInvalid: 1674 case eStateUnloaded: 1675 case eStateConnected: 1676 case eStateAttaching: 1677 case eStateLaunching: 1678 case eStateDetached: 1679 case eStateExited: 1680 show_error = false; 1681 break; 1682 1683 case eStateStopped: 1684 case eStateRunning: 1685 case eStateStepping: 1686 case eStateCrashed: 1687 case eStateSuspended: 1688 show_error = IsAlive(); 1689 break; 1690 } 1691 1692 // Reset the IsIndirect flag here, in case the location changes from pointing 1693 // to a indirect symbol to a regular symbol. 1694 owner->SetIsIndirect(false); 1695 1696 if (owner->ShouldResolveIndirectFunctions()) { 1697 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol(); 1698 if (symbol && symbol->IsIndirect()) { 1699 Status error; 1700 Address symbol_address = symbol->GetAddress(); 1701 load_addr = ResolveIndirectFunction(&symbol_address, error); 1702 if (!error.Success() && show_error) { 1703 GetTarget().GetDebugger().GetErrorFile()->Printf( 1704 "warning: failed to resolve indirect function at 0x%" PRIx64 1705 " for breakpoint %i.%i: %s\n", 1706 symbol->GetLoadAddress(&GetTarget()), 1707 owner->GetBreakpoint().GetID(), owner->GetID(), 1708 error.AsCString() ? error.AsCString() : "unknown error"); 1709 return LLDB_INVALID_BREAK_ID; 1710 } 1711 Address resolved_address(load_addr); 1712 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget()); 1713 owner->SetIsIndirect(true); 1714 } else 1715 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget()); 1716 } else 1717 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget()); 1718 1719 if (load_addr != LLDB_INVALID_ADDRESS) { 1720 BreakpointSiteSP bp_site_sp; 1721 1722 // Look up this breakpoint site. If it exists, then add this new owner, 1723 // otherwise create a new breakpoint site and add it. 1724 1725 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr); 1726 1727 if (bp_site_sp) { 1728 bp_site_sp->AddOwner(owner); 1729 owner->SetBreakpointSite(bp_site_sp); 1730 return bp_site_sp->GetID(); 1731 } else { 1732 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner, 1733 load_addr, use_hardware)); 1734 if (bp_site_sp) { 1735 Status error = EnableBreakpointSite(bp_site_sp.get()); 1736 if (error.Success()) { 1737 owner->SetBreakpointSite(bp_site_sp); 1738 return m_breakpoint_site_list.Add(bp_site_sp); 1739 } else { 1740 if (show_error || use_hardware) { 1741 // Report error for setting breakpoint... 1742 GetTarget().GetDebugger().GetErrorFile()->Printf( 1743 "warning: failed to set breakpoint site at 0x%" PRIx64 1744 " for breakpoint %i.%i: %s\n", 1745 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(), 1746 error.AsCString() ? error.AsCString() : "unknown error"); 1747 } 1748 } 1749 } 1750 } 1751 } 1752 // We failed to enable the breakpoint 1753 return LLDB_INVALID_BREAK_ID; 1754 } 1755 1756 void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id, 1757 lldb::user_id_t owner_loc_id, 1758 BreakpointSiteSP &bp_site_sp) { 1759 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id); 1760 if (num_owners == 0) { 1761 // Don't try to disable the site if we don't have a live process anymore. 1762 if (IsAlive()) 1763 DisableBreakpointSite(bp_site_sp.get()); 1764 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress()); 1765 } 1766 } 1767 1768 size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size, 1769 uint8_t *buf) const { 1770 size_t bytes_removed = 0; 1771 BreakpointSiteList bp_sites_in_range; 1772 1773 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size, 1774 bp_sites_in_range)) { 1775 bp_sites_in_range.ForEach([bp_addr, size, 1776 buf](BreakpointSite *bp_site) -> void { 1777 if (bp_site->GetType() == BreakpointSite::eSoftware) { 1778 addr_t intersect_addr; 1779 size_t intersect_size; 1780 size_t opcode_offset; 1781 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, 1782 &intersect_size, &opcode_offset)) { 1783 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size); 1784 assert(bp_addr < intersect_addr + intersect_size && 1785 intersect_addr + intersect_size <= bp_addr + size); 1786 assert(opcode_offset + intersect_size <= bp_site->GetByteSize()); 1787 size_t buf_offset = intersect_addr - bp_addr; 1788 ::memcpy(buf + buf_offset, 1789 bp_site->GetSavedOpcodeBytes() + opcode_offset, 1790 intersect_size); 1791 } 1792 } 1793 }); 1794 } 1795 return bytes_removed; 1796 } 1797 1798 size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) { 1799 PlatformSP platform_sp(GetTarget().GetPlatform()); 1800 if (platform_sp) 1801 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site); 1802 return 0; 1803 } 1804 1805 Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) { 1806 Status error; 1807 assert(bp_site != nullptr); 1808 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); 1809 const addr_t bp_addr = bp_site->GetLoadAddress(); 1810 if (log) 1811 log->Printf( 1812 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, 1813 bp_site->GetID(), (uint64_t)bp_addr); 1814 if (bp_site->IsEnabled()) { 1815 if (log) 1816 log->Printf( 1817 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 1818 " -- already enabled", 1819 bp_site->GetID(), (uint64_t)bp_addr); 1820 return error; 1821 } 1822 1823 if (bp_addr == LLDB_INVALID_ADDRESS) { 1824 error.SetErrorString("BreakpointSite contains an invalid load address."); 1825 return error; 1826 } 1827 // Ask the lldb::Process subclass to fill in the correct software breakpoint 1828 // trap for the breakpoint site 1829 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site); 1830 1831 if (bp_opcode_size == 0) { 1832 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() " 1833 "returned zero, unable to get breakpoint " 1834 "trap for address 0x%" PRIx64, 1835 bp_addr); 1836 } else { 1837 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes(); 1838 1839 if (bp_opcode_bytes == nullptr) { 1840 error.SetErrorString( 1841 "BreakpointSite doesn't contain a valid breakpoint trap opcode."); 1842 return error; 1843 } 1844 1845 // Save the original opcode by reading it 1846 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, 1847 error) == bp_opcode_size) { 1848 // Write a software breakpoint in place of the original opcode 1849 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == 1850 bp_opcode_size) { 1851 uint8_t verify_bp_opcode_bytes[64]; 1852 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, 1853 error) == bp_opcode_size) { 1854 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, 1855 bp_opcode_size) == 0) { 1856 bp_site->SetEnabled(true); 1857 bp_site->SetType(BreakpointSite::eSoftware); 1858 if (log) 1859 log->Printf("Process::EnableSoftwareBreakpoint (site_id = %d) " 1860 "addr = 0x%" PRIx64 " -- SUCCESS", 1861 bp_site->GetID(), (uint64_t)bp_addr); 1862 } else 1863 error.SetErrorString( 1864 "failed to verify the breakpoint trap in memory."); 1865 } else 1866 error.SetErrorString( 1867 "Unable to read memory to verify breakpoint trap."); 1868 } else 1869 error.SetErrorString("Unable to write breakpoint trap to memory."); 1870 } else 1871 error.SetErrorString("Unable to read memory at breakpoint address."); 1872 } 1873 if (log && error.Fail()) 1874 log->Printf( 1875 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 1876 " -- FAILED: %s", 1877 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString()); 1878 return error; 1879 } 1880 1881 Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) { 1882 Status error; 1883 assert(bp_site != nullptr); 1884 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); 1885 addr_t bp_addr = bp_site->GetLoadAddress(); 1886 lldb::user_id_t breakID = bp_site->GetID(); 1887 if (log) 1888 log->Printf("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 1889 ") addr = 0x%" PRIx64, 1890 breakID, (uint64_t)bp_addr); 1891 1892 if (bp_site->IsHardware()) { 1893 error.SetErrorString("Breakpoint site is a hardware breakpoint."); 1894 } else if (bp_site->IsEnabled()) { 1895 const size_t break_op_size = bp_site->GetByteSize(); 1896 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes(); 1897 if (break_op_size > 0) { 1898 // Clear a software breakpoint instruction 1899 uint8_t curr_break_op[8]; 1900 assert(break_op_size <= sizeof(curr_break_op)); 1901 bool break_op_found = false; 1902 1903 // Read the breakpoint opcode 1904 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) == 1905 break_op_size) { 1906 bool verify = false; 1907 // Make sure the breakpoint opcode exists at this address 1908 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) { 1909 break_op_found = true; 1910 // We found a valid breakpoint opcode at this address, now restore 1911 // the saved opcode. 1912 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), 1913 break_op_size, error) == break_op_size) { 1914 verify = true; 1915 } else 1916 error.SetErrorString( 1917 "Memory write failed when restoring original opcode."); 1918 } else { 1919 error.SetErrorString( 1920 "Original breakpoint trap is no longer in memory."); 1921 // Set verify to true and so we can check if the original opcode has 1922 // already been restored 1923 verify = true; 1924 } 1925 1926 if (verify) { 1927 uint8_t verify_opcode[8]; 1928 assert(break_op_size < sizeof(verify_opcode)); 1929 // Verify that our original opcode made it back to the inferior 1930 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) == 1931 break_op_size) { 1932 // compare the memory we just read with the original opcode 1933 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode, 1934 break_op_size) == 0) { 1935 // SUCCESS 1936 bp_site->SetEnabled(false); 1937 if (log) 1938 log->Printf("Process::DisableSoftwareBreakpoint (site_id = %d) " 1939 "addr = 0x%" PRIx64 " -- SUCCESS", 1940 bp_site->GetID(), (uint64_t)bp_addr); 1941 return error; 1942 } else { 1943 if (break_op_found) 1944 error.SetErrorString("Failed to restore original opcode."); 1945 } 1946 } else 1947 error.SetErrorString("Failed to read memory to verify that " 1948 "breakpoint trap was restored."); 1949 } 1950 } else 1951 error.SetErrorString( 1952 "Unable to read memory that should contain the breakpoint trap."); 1953 } 1954 } else { 1955 if (log) 1956 log->Printf( 1957 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 1958 " -- already disabled", 1959 bp_site->GetID(), (uint64_t)bp_addr); 1960 return error; 1961 } 1962 1963 if (log) 1964 log->Printf( 1965 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 1966 " -- FAILED: %s", 1967 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString()); 1968 return error; 1969 } 1970 1971 // Uncomment to verify memory caching works after making changes to caching 1972 // code 1973 //#define VERIFY_MEMORY_READS 1974 1975 size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) { 1976 error.Clear(); 1977 if (!GetDisableMemoryCache()) { 1978 #if defined(VERIFY_MEMORY_READS) 1979 // Memory caching is enabled, with debug verification 1980 1981 if (buf && size) { 1982 // Uncomment the line below to make sure memory caching is working. 1983 // I ran this through the test suite and got no assertions, so I am 1984 // pretty confident this is working well. If any changes are made to 1985 // memory caching, uncomment the line below and test your changes! 1986 1987 // Verify all memory reads by using the cache first, then redundantly 1988 // reading the same memory from the inferior and comparing to make sure 1989 // everything is exactly the same. 1990 std::string verify_buf(size, '\0'); 1991 assert(verify_buf.size() == size); 1992 const size_t cache_bytes_read = 1993 m_memory_cache.Read(this, addr, buf, size, error); 1994 Status verify_error; 1995 const size_t verify_bytes_read = 1996 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()), 1997 verify_buf.size(), verify_error); 1998 assert(cache_bytes_read == verify_bytes_read); 1999 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0); 2000 assert(verify_error.Success() == error.Success()); 2001 return cache_bytes_read; 2002 } 2003 return 0; 2004 #else // !defined(VERIFY_MEMORY_READS) 2005 // Memory caching is enabled, without debug verification 2006 2007 return m_memory_cache.Read(addr, buf, size, error); 2008 #endif // defined (VERIFY_MEMORY_READS) 2009 } else { 2010 // Memory caching is disabled 2011 2012 return ReadMemoryFromInferior(addr, buf, size, error); 2013 } 2014 } 2015 2016 size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str, 2017 Status &error) { 2018 char buf[256]; 2019 out_str.clear(); 2020 addr_t curr_addr = addr; 2021 while (true) { 2022 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error); 2023 if (length == 0) 2024 break; 2025 out_str.append(buf, length); 2026 // If we got "length - 1" bytes, we didn't get the whole C string, we need 2027 // to read some more characters 2028 if (length == sizeof(buf) - 1) 2029 curr_addr += length; 2030 else 2031 break; 2032 } 2033 return out_str.size(); 2034 } 2035 2036 size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes, 2037 Status &error, size_t type_width) { 2038 size_t total_bytes_read = 0; 2039 if (dst && max_bytes && type_width && max_bytes >= type_width) { 2040 // Ensure a null terminator independent of the number of bytes that is 2041 // read. 2042 memset(dst, 0, max_bytes); 2043 size_t bytes_left = max_bytes - type_width; 2044 2045 const char terminator[4] = {'\0', '\0', '\0', '\0'}; 2046 assert(sizeof(terminator) >= type_width && "Attempting to validate a " 2047 "string with more than 4 bytes " 2048 "per character!"); 2049 2050 addr_t curr_addr = addr; 2051 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize(); 2052 char *curr_dst = dst; 2053 2054 error.Clear(); 2055 while (bytes_left > 0 && error.Success()) { 2056 addr_t cache_line_bytes_left = 2057 cache_line_size - (curr_addr % cache_line_size); 2058 addr_t bytes_to_read = 2059 std::min<addr_t>(bytes_left, cache_line_bytes_left); 2060 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error); 2061 2062 if (bytes_read == 0) 2063 break; 2064 2065 // Search for a null terminator of correct size and alignment in 2066 // bytes_read 2067 size_t aligned_start = total_bytes_read - total_bytes_read % type_width; 2068 for (size_t i = aligned_start; 2069 i + type_width <= total_bytes_read + bytes_read; i += type_width) 2070 if (::memcmp(&dst[i], terminator, type_width) == 0) { 2071 error.Clear(); 2072 return i; 2073 } 2074 2075 total_bytes_read += bytes_read; 2076 curr_dst += bytes_read; 2077 curr_addr += bytes_read; 2078 bytes_left -= bytes_read; 2079 } 2080 } else { 2081 if (max_bytes) 2082 error.SetErrorString("invalid arguments"); 2083 } 2084 return total_bytes_read; 2085 } 2086 2087 // Deprecated in favor of ReadStringFromMemory which has wchar support and 2088 // correct code to find null terminators. 2089 size_t Process::ReadCStringFromMemory(addr_t addr, char *dst, 2090 size_t dst_max_len, 2091 Status &result_error) { 2092 size_t total_cstr_len = 0; 2093 if (dst && dst_max_len) { 2094 result_error.Clear(); 2095 // NULL out everything just to be safe 2096 memset(dst, 0, dst_max_len); 2097 Status error; 2098 addr_t curr_addr = addr; 2099 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize(); 2100 size_t bytes_left = dst_max_len - 1; 2101 char *curr_dst = dst; 2102 2103 while (bytes_left > 0) { 2104 addr_t cache_line_bytes_left = 2105 cache_line_size - (curr_addr % cache_line_size); 2106 addr_t bytes_to_read = 2107 std::min<addr_t>(bytes_left, cache_line_bytes_left); 2108 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error); 2109 2110 if (bytes_read == 0) { 2111 result_error = error; 2112 dst[total_cstr_len] = '\0'; 2113 break; 2114 } 2115 const size_t len = strlen(curr_dst); 2116 2117 total_cstr_len += len; 2118 2119 if (len < bytes_to_read) 2120 break; 2121 2122 curr_dst += bytes_read; 2123 curr_addr += bytes_read; 2124 bytes_left -= bytes_read; 2125 } 2126 } else { 2127 if (dst == nullptr) 2128 result_error.SetErrorString("invalid arguments"); 2129 else 2130 result_error.Clear(); 2131 } 2132 return total_cstr_len; 2133 } 2134 2135 size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size, 2136 Status &error) { 2137 if (buf == nullptr || size == 0) 2138 return 0; 2139 2140 size_t bytes_read = 0; 2141 uint8_t *bytes = (uint8_t *)buf; 2142 2143 while (bytes_read < size) { 2144 const size_t curr_size = size - bytes_read; 2145 const size_t curr_bytes_read = 2146 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error); 2147 bytes_read += curr_bytes_read; 2148 if (curr_bytes_read == curr_size || curr_bytes_read == 0) 2149 break; 2150 } 2151 2152 // Replace any software breakpoint opcodes that fall into this range back 2153 // into "buf" before we return 2154 if (bytes_read > 0) 2155 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf); 2156 return bytes_read; 2157 } 2158 2159 uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr, 2160 size_t integer_byte_size, 2161 uint64_t fail_value, 2162 Status &error) { 2163 Scalar scalar; 2164 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, 2165 error)) 2166 return scalar.ULongLong(fail_value); 2167 return fail_value; 2168 } 2169 2170 int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr, 2171 size_t integer_byte_size, 2172 int64_t fail_value, 2173 Status &error) { 2174 Scalar scalar; 2175 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar, 2176 error)) 2177 return scalar.SLongLong(fail_value); 2178 return fail_value; 2179 } 2180 2181 addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) { 2182 Scalar scalar; 2183 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, 2184 error)) 2185 return scalar.ULongLong(LLDB_INVALID_ADDRESS); 2186 return LLDB_INVALID_ADDRESS; 2187 } 2188 2189 bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value, 2190 Status &error) { 2191 Scalar scalar; 2192 const uint32_t addr_byte_size = GetAddressByteSize(); 2193 if (addr_byte_size <= 4) 2194 scalar = (uint32_t)ptr_value; 2195 else 2196 scalar = ptr_value; 2197 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == 2198 addr_byte_size; 2199 } 2200 2201 size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size, 2202 Status &error) { 2203 size_t bytes_written = 0; 2204 const uint8_t *bytes = (const uint8_t *)buf; 2205 2206 while (bytes_written < size) { 2207 const size_t curr_size = size - bytes_written; 2208 const size_t curr_bytes_written = DoWriteMemory( 2209 addr + bytes_written, bytes + bytes_written, curr_size, error); 2210 bytes_written += curr_bytes_written; 2211 if (curr_bytes_written == curr_size || curr_bytes_written == 0) 2212 break; 2213 } 2214 return bytes_written; 2215 } 2216 2217 size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size, 2218 Status &error) { 2219 #if defined(ENABLE_MEMORY_CACHING) 2220 m_memory_cache.Flush(addr, size); 2221 #endif 2222 2223 if (buf == nullptr || size == 0) 2224 return 0; 2225 2226 m_mod_id.BumpMemoryID(); 2227 2228 // We need to write any data that would go where any current software traps 2229 // (enabled software breakpoints) any software traps (breakpoints) that we 2230 // may have placed in our tasks memory. 2231 2232 BreakpointSiteList bp_sites_in_range; 2233 if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range)) 2234 return WriteMemoryPrivate(addr, buf, size, error); 2235 2236 // No breakpoint sites overlap 2237 if (bp_sites_in_range.IsEmpty()) 2238 return WriteMemoryPrivate(addr, buf, size, error); 2239 2240 const uint8_t *ubuf = (const uint8_t *)buf; 2241 uint64_t bytes_written = 0; 2242 2243 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, 2244 &error](BreakpointSite *bp) -> void { 2245 if (error.Fail()) 2246 return; 2247 2248 addr_t intersect_addr; 2249 size_t intersect_size; 2250 size_t opcode_offset; 2251 const bool intersects = bp->IntersectsRange( 2252 addr, size, &intersect_addr, &intersect_size, &opcode_offset); 2253 UNUSED_IF_ASSERT_DISABLED(intersects); 2254 assert(intersects); 2255 assert(addr <= intersect_addr && intersect_addr < addr + size); 2256 assert(addr < intersect_addr + intersect_size && 2257 intersect_addr + intersect_size <= addr + size); 2258 assert(opcode_offset + intersect_size <= bp->GetByteSize()); 2259 2260 // Check for bytes before this breakpoint 2261 const addr_t curr_addr = addr + bytes_written; 2262 if (intersect_addr > curr_addr) { 2263 // There are some bytes before this breakpoint that we need to just 2264 // write to memory 2265 size_t curr_size = intersect_addr - curr_addr; 2266 size_t curr_bytes_written = 2267 WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error); 2268 bytes_written += curr_bytes_written; 2269 if (curr_bytes_written != curr_size) { 2270 // We weren't able to write all of the requested bytes, we are 2271 // done looping and will return the number of bytes that we have 2272 // written so far. 2273 if (error.Success()) 2274 error.SetErrorToGenericError(); 2275 } 2276 } 2277 // Now write any bytes that would cover up any software breakpoints 2278 // directly into the breakpoint opcode buffer 2279 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, 2280 intersect_size); 2281 bytes_written += intersect_size; 2282 }); 2283 2284 // Write any remaining bytes after the last breakpoint if we have any left 2285 if (bytes_written < size) 2286 bytes_written += 2287 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written, 2288 size - bytes_written, error); 2289 2290 return bytes_written; 2291 } 2292 2293 size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar, 2294 size_t byte_size, Status &error) { 2295 if (byte_size == UINT32_MAX) 2296 byte_size = scalar.GetByteSize(); 2297 if (byte_size > 0) { 2298 uint8_t buf[32]; 2299 const size_t mem_size = 2300 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error); 2301 if (mem_size > 0) 2302 return WriteMemory(addr, buf, mem_size, error); 2303 else 2304 error.SetErrorString("failed to get scalar as memory data"); 2305 } else { 2306 error.SetErrorString("invalid scalar value"); 2307 } 2308 return 0; 2309 } 2310 2311 size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size, 2312 bool is_signed, Scalar &scalar, 2313 Status &error) { 2314 uint64_t uval = 0; 2315 if (byte_size == 0) { 2316 error.SetErrorString("byte size is zero"); 2317 } else if (byte_size & (byte_size - 1)) { 2318 error.SetErrorStringWithFormat("byte size %u is not a power of 2", 2319 byte_size); 2320 } else if (byte_size <= sizeof(uval)) { 2321 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error); 2322 if (bytes_read == byte_size) { 2323 DataExtractor data(&uval, sizeof(uval), GetByteOrder(), 2324 GetAddressByteSize()); 2325 lldb::offset_t offset = 0; 2326 if (byte_size <= 4) 2327 scalar = data.GetMaxU32(&offset, byte_size); 2328 else 2329 scalar = data.GetMaxU64(&offset, byte_size); 2330 if (is_signed) 2331 scalar.SignExtend(byte_size * 8); 2332 return bytes_read; 2333 } 2334 } else { 2335 error.SetErrorStringWithFormat( 2336 "byte size of %u is too large for integer scalar type", byte_size); 2337 } 2338 return 0; 2339 } 2340 2341 Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) { 2342 Status error; 2343 for (const auto &Entry : entries) { 2344 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(), 2345 error); 2346 if (!error.Success()) 2347 break; 2348 } 2349 return error; 2350 } 2351 2352 #define USE_ALLOCATE_MEMORY_CACHE 1 2353 addr_t Process::AllocateMemory(size_t size, uint32_t permissions, 2354 Status &error) { 2355 if (GetPrivateState() != eStateStopped) { 2356 error.SetErrorToGenericError(); 2357 return LLDB_INVALID_ADDRESS; 2358 } 2359 2360 #if defined(USE_ALLOCATE_MEMORY_CACHE) 2361 return m_allocated_memory_cache.AllocateMemory(size, permissions, error); 2362 #else 2363 addr_t allocated_addr = DoAllocateMemory(size, permissions, error); 2364 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 2365 if (log) 2366 log->Printf("Process::AllocateMemory(size=%" PRIu64 2367 ", permissions=%s) => 0x%16.16" PRIx64 2368 " (m_stop_id = %u m_memory_id = %u)", 2369 (uint64_t)size, GetPermissionsAsCString(permissions), 2370 (uint64_t)allocated_addr, m_mod_id.GetStopID(), 2371 m_mod_id.GetMemoryID()); 2372 return allocated_addr; 2373 #endif 2374 } 2375 2376 addr_t Process::CallocateMemory(size_t size, uint32_t permissions, 2377 Status &error) { 2378 addr_t return_addr = AllocateMemory(size, permissions, error); 2379 if (error.Success()) { 2380 std::string buffer(size, 0); 2381 WriteMemory(return_addr, buffer.c_str(), size, error); 2382 } 2383 return return_addr; 2384 } 2385 2386 bool Process::CanJIT() { 2387 if (m_can_jit == eCanJITDontKnow) { 2388 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 2389 Status err; 2390 2391 uint64_t allocated_memory = AllocateMemory( 2392 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable, 2393 err); 2394 2395 if (err.Success()) { 2396 m_can_jit = eCanJITYes; 2397 if (log) 2398 log->Printf("Process::%s pid %" PRIu64 2399 " allocation test passed, CanJIT () is true", 2400 __FUNCTION__, GetID()); 2401 } else { 2402 m_can_jit = eCanJITNo; 2403 if (log) 2404 log->Printf("Process::%s pid %" PRIu64 2405 " allocation test failed, CanJIT () is false: %s", 2406 __FUNCTION__, GetID(), err.AsCString()); 2407 } 2408 2409 DeallocateMemory(allocated_memory); 2410 } 2411 2412 return m_can_jit == eCanJITYes; 2413 } 2414 2415 void Process::SetCanJIT(bool can_jit) { 2416 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo); 2417 } 2418 2419 void Process::SetCanRunCode(bool can_run_code) { 2420 SetCanJIT(can_run_code); 2421 m_can_interpret_function_calls = can_run_code; 2422 } 2423 2424 Status Process::DeallocateMemory(addr_t ptr) { 2425 Status error; 2426 #if defined(USE_ALLOCATE_MEMORY_CACHE) 2427 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) { 2428 error.SetErrorStringWithFormat( 2429 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr); 2430 } 2431 #else 2432 error = DoDeallocateMemory(ptr); 2433 2434 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 2435 if (log) 2436 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64 2437 ") => err = %s (m_stop_id = %u, m_memory_id = %u)", 2438 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(), 2439 m_mod_id.GetMemoryID()); 2440 #endif 2441 return error; 2442 } 2443 2444 ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec, 2445 lldb::addr_t header_addr, 2446 size_t size_to_read) { 2447 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST); 2448 if (log) { 2449 log->Printf("Process::ReadModuleFromMemory reading %s binary from memory", 2450 file_spec.GetPath().c_str()); 2451 } 2452 ModuleSP module_sp(new Module(file_spec, ArchSpec())); 2453 if (module_sp) { 2454 Status error; 2455 ObjectFile *objfile = module_sp->GetMemoryObjectFile( 2456 shared_from_this(), header_addr, error, size_to_read); 2457 if (objfile) 2458 return module_sp; 2459 } 2460 return ModuleSP(); 2461 } 2462 2463 bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr, 2464 uint32_t &permissions) { 2465 MemoryRegionInfo range_info; 2466 permissions = 0; 2467 Status error(GetMemoryRegionInfo(load_addr, range_info)); 2468 if (!error.Success()) 2469 return false; 2470 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow || 2471 range_info.GetWritable() == MemoryRegionInfo::eDontKnow || 2472 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) { 2473 return false; 2474 } 2475 2476 if (range_info.GetReadable() == MemoryRegionInfo::eYes) 2477 permissions |= lldb::ePermissionsReadable; 2478 2479 if (range_info.GetWritable() == MemoryRegionInfo::eYes) 2480 permissions |= lldb::ePermissionsWritable; 2481 2482 if (range_info.GetExecutable() == MemoryRegionInfo::eYes) 2483 permissions |= lldb::ePermissionsExecutable; 2484 2485 return true; 2486 } 2487 2488 Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) { 2489 Status error; 2490 error.SetErrorString("watchpoints are not supported"); 2491 return error; 2492 } 2493 2494 Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) { 2495 Status error; 2496 error.SetErrorString("watchpoints are not supported"); 2497 return error; 2498 } 2499 2500 StateType 2501 Process::WaitForProcessStopPrivate(EventSP &event_sp, 2502 const Timeout<std::micro> &timeout) { 2503 StateType state; 2504 2505 while (true) { 2506 event_sp.reset(); 2507 state = GetStateChangedEventsPrivate(event_sp, timeout); 2508 2509 if (StateIsStoppedState(state, false)) 2510 break; 2511 2512 // If state is invalid, then we timed out 2513 if (state == eStateInvalid) 2514 break; 2515 2516 if (event_sp) 2517 HandlePrivateEvent(event_sp); 2518 } 2519 return state; 2520 } 2521 2522 void Process::LoadOperatingSystemPlugin(bool flush) { 2523 if (flush) 2524 m_thread_list.Clear(); 2525 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr)); 2526 if (flush) 2527 Flush(); 2528 } 2529 2530 Status Process::Launch(ProcessLaunchInfo &launch_info) { 2531 Status error; 2532 m_abi_sp.reset(); 2533 m_dyld_up.reset(); 2534 m_jit_loaders_up.reset(); 2535 m_system_runtime_up.reset(); 2536 m_os_up.reset(); 2537 m_process_input_reader.reset(); 2538 2539 Module *exe_module = GetTarget().GetExecutableModulePointer(); 2540 if (!exe_module) { 2541 error.SetErrorString("executable module does not exist"); 2542 return error; 2543 } 2544 2545 char local_exec_file_path[PATH_MAX]; 2546 char platform_exec_file_path[PATH_MAX]; 2547 exe_module->GetFileSpec().GetPath(local_exec_file_path, 2548 sizeof(local_exec_file_path)); 2549 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, 2550 sizeof(platform_exec_file_path)); 2551 if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) { 2552 // Install anything that might need to be installed prior to launching. 2553 // For host systems, this will do nothing, but if we are connected to a 2554 // remote platform it will install any needed binaries 2555 error = GetTarget().Install(&launch_info); 2556 if (error.Fail()) 2557 return error; 2558 2559 if (PrivateStateThreadIsValid()) 2560 PausePrivateStateThread(); 2561 2562 error = WillLaunch(exe_module); 2563 if (error.Success()) { 2564 const bool restarted = false; 2565 SetPublicState(eStateLaunching, restarted); 2566 m_should_detach = false; 2567 2568 if (m_public_run_lock.TrySetRunning()) { 2569 // Now launch using these arguments. 2570 error = DoLaunch(exe_module, launch_info); 2571 } else { 2572 // This shouldn't happen 2573 error.SetErrorString("failed to acquire process run lock"); 2574 } 2575 2576 if (error.Fail()) { 2577 if (GetID() != LLDB_INVALID_PROCESS_ID) { 2578 SetID(LLDB_INVALID_PROCESS_ID); 2579 const char *error_string = error.AsCString(); 2580 if (error_string == nullptr) 2581 error_string = "launch failed"; 2582 SetExitStatus(-1, error_string); 2583 } 2584 } else { 2585 EventSP event_sp; 2586 2587 // Now wait for the process to launch and return control to us, and then 2588 // call DidLaunch: 2589 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10)); 2590 2591 if (state == eStateInvalid || !event_sp) { 2592 // We were able to launch the process, but we failed to catch the 2593 // initial stop. 2594 error.SetErrorString("failed to catch stop after launch"); 2595 SetExitStatus(0, "failed to catch stop after launch"); 2596 Destroy(false); 2597 } else if (state == eStateStopped || state == eStateCrashed) { 2598 DidLaunch(); 2599 2600 DynamicLoader *dyld = GetDynamicLoader(); 2601 if (dyld) 2602 dyld->DidLaunch(); 2603 2604 GetJITLoaders().DidLaunch(); 2605 2606 SystemRuntime *system_runtime = GetSystemRuntime(); 2607 if (system_runtime) 2608 system_runtime->DidLaunch(); 2609 2610 if (!m_os_up) 2611 LoadOperatingSystemPlugin(false); 2612 2613 // We successfully launched the process and stopped, now it the 2614 // right time to set up signal filters before resuming. 2615 UpdateAutomaticSignalFiltering(); 2616 2617 // Note, the stop event was consumed above, but not handled. This 2618 // was done to give DidLaunch a chance to run. The target is either 2619 // stopped or crashed. Directly set the state. This is done to 2620 // prevent a stop message with a bunch of spurious output on thread 2621 // status, as well as not pop a ProcessIOHandler. 2622 SetPublicState(state, false); 2623 2624 if (PrivateStateThreadIsValid()) 2625 ResumePrivateStateThread(); 2626 else 2627 StartPrivateStateThread(); 2628 2629 // Target was stopped at entry as was intended. Need to notify the 2630 // listeners about it. 2631 if (state == eStateStopped && 2632 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) 2633 HandlePrivateEvent(event_sp); 2634 } else if (state == eStateExited) { 2635 // We exited while trying to launch somehow. Don't call DidLaunch 2636 // as that's not likely to work, and return an invalid pid. 2637 HandlePrivateEvent(event_sp); 2638 } 2639 } 2640 } 2641 } else { 2642 error.SetErrorStringWithFormat("file doesn't exist: '%s'", 2643 local_exec_file_path); 2644 } 2645 2646 return error; 2647 } 2648 2649 Status Process::LoadCore() { 2650 Status error = DoLoadCore(); 2651 if (error.Success()) { 2652 ListenerSP listener_sp( 2653 Listener::MakeListener("lldb.process.load_core_listener")); 2654 HijackProcessEvents(listener_sp); 2655 2656 if (PrivateStateThreadIsValid()) 2657 ResumePrivateStateThread(); 2658 else 2659 StartPrivateStateThread(); 2660 2661 DynamicLoader *dyld = GetDynamicLoader(); 2662 if (dyld) 2663 dyld->DidAttach(); 2664 2665 GetJITLoaders().DidAttach(); 2666 2667 SystemRuntime *system_runtime = GetSystemRuntime(); 2668 if (system_runtime) 2669 system_runtime->DidAttach(); 2670 2671 if (!m_os_up) 2672 LoadOperatingSystemPlugin(false); 2673 2674 // We successfully loaded a core file, now pretend we stopped so we can 2675 // show all of the threads in the core file and explore the crashed state. 2676 SetPrivateState(eStateStopped); 2677 2678 // Wait for a stopped event since we just posted one above... 2679 lldb::EventSP event_sp; 2680 StateType state = 2681 WaitForProcessToStop(seconds(10), &event_sp, true, listener_sp); 2682 2683 if (!StateIsStoppedState(state, false)) { 2684 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 2685 if (log) 2686 log->Printf("Process::Halt() failed to stop, state is: %s", 2687 StateAsCString(state)); 2688 error.SetErrorString( 2689 "Did not get stopped event after loading the core file."); 2690 } 2691 RestoreProcessEvents(); 2692 } 2693 return error; 2694 } 2695 2696 DynamicLoader *Process::GetDynamicLoader() { 2697 if (!m_dyld_up) 2698 m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr)); 2699 return m_dyld_up.get(); 2700 } 2701 2702 const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); } 2703 2704 JITLoaderList &Process::GetJITLoaders() { 2705 if (!m_jit_loaders_up) { 2706 m_jit_loaders_up.reset(new JITLoaderList()); 2707 JITLoader::LoadPlugins(this, *m_jit_loaders_up); 2708 } 2709 return *m_jit_loaders_up; 2710 } 2711 2712 SystemRuntime *Process::GetSystemRuntime() { 2713 if (!m_system_runtime_up) 2714 m_system_runtime_up.reset(SystemRuntime::FindPlugin(this)); 2715 return m_system_runtime_up.get(); 2716 } 2717 2718 Process::AttachCompletionHandler::AttachCompletionHandler(Process *process, 2719 uint32_t exec_count) 2720 : NextEventAction(process), m_exec_count(exec_count) { 2721 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 2722 if (log) 2723 log->Printf( 2724 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, 2725 __FUNCTION__, static_cast<void *>(process), exec_count); 2726 } 2727 2728 Process::NextEventAction::EventActionResult 2729 Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) { 2730 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 2731 2732 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get()); 2733 if (log) 2734 log->Printf( 2735 "Process::AttachCompletionHandler::%s called with state %s (%d)", 2736 __FUNCTION__, StateAsCString(state), static_cast<int>(state)); 2737 2738 switch (state) { 2739 case eStateAttaching: 2740 return eEventActionSuccess; 2741 2742 case eStateRunning: 2743 case eStateConnected: 2744 return eEventActionRetry; 2745 2746 case eStateStopped: 2747 case eStateCrashed: 2748 // During attach, prior to sending the eStateStopped event, 2749 // lldb_private::Process subclasses must set the new process ID. 2750 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID); 2751 // We don't want these events to be reported, so go set the 2752 // ShouldReportStop here: 2753 m_process->GetThreadList().SetShouldReportStop(eVoteNo); 2754 2755 if (m_exec_count > 0) { 2756 --m_exec_count; 2757 2758 if (log) 2759 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced " 2760 "remaining exec count to %" PRIu32 ", requesting resume", 2761 __FUNCTION__, StateAsCString(state), m_exec_count); 2762 2763 RequestResume(); 2764 return eEventActionRetry; 2765 } else { 2766 if (log) 2767 log->Printf("Process::AttachCompletionHandler::%s state %s: no more " 2768 "execs expected to start, continuing with attach", 2769 __FUNCTION__, StateAsCString(state)); 2770 2771 m_process->CompleteAttach(); 2772 return eEventActionSuccess; 2773 } 2774 break; 2775 2776 default: 2777 case eStateExited: 2778 case eStateInvalid: 2779 break; 2780 } 2781 2782 m_exit_string.assign("No valid Process"); 2783 return eEventActionExit; 2784 } 2785 2786 Process::NextEventAction::EventActionResult 2787 Process::AttachCompletionHandler::HandleBeingInterrupted() { 2788 return eEventActionSuccess; 2789 } 2790 2791 const char *Process::AttachCompletionHandler::GetExitString() { 2792 return m_exit_string.c_str(); 2793 } 2794 2795 ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) { 2796 if (m_listener_sp) 2797 return m_listener_sp; 2798 else 2799 return debugger.GetListener(); 2800 } 2801 2802 Status Process::Attach(ProcessAttachInfo &attach_info) { 2803 m_abi_sp.reset(); 2804 m_process_input_reader.reset(); 2805 m_dyld_up.reset(); 2806 m_jit_loaders_up.reset(); 2807 m_system_runtime_up.reset(); 2808 m_os_up.reset(); 2809 2810 lldb::pid_t attach_pid = attach_info.GetProcessID(); 2811 Status error; 2812 if (attach_pid == LLDB_INVALID_PROCESS_ID) { 2813 char process_name[PATH_MAX]; 2814 2815 if (attach_info.GetExecutableFile().GetPath(process_name, 2816 sizeof(process_name))) { 2817 const bool wait_for_launch = attach_info.GetWaitForLaunch(); 2818 2819 if (wait_for_launch) { 2820 error = WillAttachToProcessWithName(process_name, wait_for_launch); 2821 if (error.Success()) { 2822 if (m_public_run_lock.TrySetRunning()) { 2823 m_should_detach = true; 2824 const bool restarted = false; 2825 SetPublicState(eStateAttaching, restarted); 2826 // Now attach using these arguments. 2827 error = DoAttachToProcessWithName(process_name, attach_info); 2828 } else { 2829 // This shouldn't happen 2830 error.SetErrorString("failed to acquire process run lock"); 2831 } 2832 2833 if (error.Fail()) { 2834 if (GetID() != LLDB_INVALID_PROCESS_ID) { 2835 SetID(LLDB_INVALID_PROCESS_ID); 2836 if (error.AsCString() == nullptr) 2837 error.SetErrorString("attach failed"); 2838 2839 SetExitStatus(-1, error.AsCString()); 2840 } 2841 } else { 2842 SetNextEventAction(new Process::AttachCompletionHandler( 2843 this, attach_info.GetResumeCount())); 2844 StartPrivateStateThread(); 2845 } 2846 return error; 2847 } 2848 } else { 2849 ProcessInstanceInfoList process_infos; 2850 PlatformSP platform_sp(GetTarget().GetPlatform()); 2851 2852 if (platform_sp) { 2853 ProcessInstanceInfoMatch match_info; 2854 match_info.GetProcessInfo() = attach_info; 2855 match_info.SetNameMatchType(NameMatch::Equals); 2856 platform_sp->FindProcesses(match_info, process_infos); 2857 const uint32_t num_matches = process_infos.GetSize(); 2858 if (num_matches == 1) { 2859 attach_pid = process_infos.GetProcessIDAtIndex(0); 2860 // Fall through and attach using the above process ID 2861 } else { 2862 match_info.GetProcessInfo().GetExecutableFile().GetPath( 2863 process_name, sizeof(process_name)); 2864 if (num_matches > 1) { 2865 StreamString s; 2866 ProcessInstanceInfo::DumpTableHeader(s, true, false); 2867 for (size_t i = 0; i < num_matches; i++) { 2868 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow( 2869 s, platform_sp->GetUserIDResolver(), true, false); 2870 } 2871 error.SetErrorStringWithFormat( 2872 "more than one process named %s:\n%s", process_name, 2873 s.GetData()); 2874 } else 2875 error.SetErrorStringWithFormat( 2876 "could not find a process named %s", process_name); 2877 } 2878 } else { 2879 error.SetErrorString( 2880 "invalid platform, can't find processes by name"); 2881 return error; 2882 } 2883 } 2884 } else { 2885 error.SetErrorString("invalid process name"); 2886 } 2887 } 2888 2889 if (attach_pid != LLDB_INVALID_PROCESS_ID) { 2890 error = WillAttachToProcessWithID(attach_pid); 2891 if (error.Success()) { 2892 2893 if (m_public_run_lock.TrySetRunning()) { 2894 // Now attach using these arguments. 2895 m_should_detach = true; 2896 const bool restarted = false; 2897 SetPublicState(eStateAttaching, restarted); 2898 error = DoAttachToProcessWithID(attach_pid, attach_info); 2899 } else { 2900 // This shouldn't happen 2901 error.SetErrorString("failed to acquire process run lock"); 2902 } 2903 2904 if (error.Success()) { 2905 SetNextEventAction(new Process::AttachCompletionHandler( 2906 this, attach_info.GetResumeCount())); 2907 StartPrivateStateThread(); 2908 } else { 2909 if (GetID() != LLDB_INVALID_PROCESS_ID) 2910 SetID(LLDB_INVALID_PROCESS_ID); 2911 2912 const char *error_string = error.AsCString(); 2913 if (error_string == nullptr) 2914 error_string = "attach failed"; 2915 2916 SetExitStatus(-1, error_string); 2917 } 2918 } 2919 } 2920 return error; 2921 } 2922 2923 void Process::CompleteAttach() { 2924 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | 2925 LIBLLDB_LOG_TARGET)); 2926 if (log) 2927 log->Printf("Process::%s()", __FUNCTION__); 2928 2929 // Let the process subclass figure out at much as it can about the process 2930 // before we go looking for a dynamic loader plug-in. 2931 ArchSpec process_arch; 2932 DidAttach(process_arch); 2933 2934 if (process_arch.IsValid()) { 2935 GetTarget().SetArchitecture(process_arch); 2936 if (log) { 2937 const char *triple_str = process_arch.GetTriple().getTriple().c_str(); 2938 log->Printf("Process::%s replacing process architecture with DidAttach() " 2939 "architecture: %s", 2940 __FUNCTION__, triple_str ? triple_str : "<null>"); 2941 } 2942 } 2943 2944 // We just attached. If we have a platform, ask it for the process 2945 // architecture, and if it isn't the same as the one we've already set, 2946 // switch architectures. 2947 PlatformSP platform_sp(GetTarget().GetPlatform()); 2948 assert(platform_sp); 2949 if (platform_sp) { 2950 const ArchSpec &target_arch = GetTarget().GetArchitecture(); 2951 if (target_arch.IsValid() && 2952 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) { 2953 ArchSpec platform_arch; 2954 platform_sp = 2955 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch); 2956 if (platform_sp) { 2957 GetTarget().SetPlatform(platform_sp); 2958 GetTarget().SetArchitecture(platform_arch); 2959 if (log) 2960 log->Printf("Process::%s switching platform to %s and architecture " 2961 "to %s based on info from attach", 2962 __FUNCTION__, platform_sp->GetName().AsCString(""), 2963 platform_arch.GetTriple().getTriple().c_str()); 2964 } 2965 } else if (!process_arch.IsValid()) { 2966 ProcessInstanceInfo process_info; 2967 GetProcessInfo(process_info); 2968 const ArchSpec &process_arch = process_info.GetArchitecture(); 2969 if (process_arch.IsValid() && 2970 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) { 2971 GetTarget().SetArchitecture(process_arch); 2972 if (log) 2973 log->Printf("Process::%s switching architecture to %s based on info " 2974 "the platform retrieved for pid %" PRIu64, 2975 __FUNCTION__, 2976 process_arch.GetTriple().getTriple().c_str(), GetID()); 2977 } 2978 } 2979 } 2980 2981 // We have completed the attach, now it is time to find the dynamic loader 2982 // plug-in 2983 DynamicLoader *dyld = GetDynamicLoader(); 2984 if (dyld) { 2985 dyld->DidAttach(); 2986 if (log) { 2987 ModuleSP exe_module_sp = GetTarget().GetExecutableModule(); 2988 log->Printf("Process::%s after DynamicLoader::DidAttach(), target " 2989 "executable is %s (using %s plugin)", 2990 __FUNCTION__, 2991 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str() 2992 : "<none>", 2993 dyld->GetPluginName().AsCString("<unnamed>")); 2994 } 2995 } 2996 2997 GetJITLoaders().DidAttach(); 2998 2999 SystemRuntime *system_runtime = GetSystemRuntime(); 3000 if (system_runtime) { 3001 system_runtime->DidAttach(); 3002 if (log) { 3003 ModuleSP exe_module_sp = GetTarget().GetExecutableModule(); 3004 log->Printf("Process::%s after SystemRuntime::DidAttach(), target " 3005 "executable is %s (using %s plugin)", 3006 __FUNCTION__, 3007 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str() 3008 : "<none>", 3009 system_runtime->GetPluginName().AsCString("<unnamed>")); 3010 } 3011 } 3012 3013 if (!m_os_up) 3014 LoadOperatingSystemPlugin(false); 3015 // Figure out which one is the executable, and set that in our target: 3016 const ModuleList &target_modules = GetTarget().GetImages(); 3017 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex()); 3018 size_t num_modules = target_modules.GetSize(); 3019 ModuleSP new_executable_module_sp; 3020 3021 for (size_t i = 0; i < num_modules; i++) { 3022 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i)); 3023 if (module_sp && module_sp->IsExecutable()) { 3024 if (GetTarget().GetExecutableModulePointer() != module_sp.get()) 3025 new_executable_module_sp = module_sp; 3026 break; 3027 } 3028 } 3029 if (new_executable_module_sp) { 3030 GetTarget().SetExecutableModule(new_executable_module_sp, 3031 eLoadDependentsNo); 3032 if (log) { 3033 ModuleSP exe_module_sp = GetTarget().GetExecutableModule(); 3034 log->Printf( 3035 "Process::%s after looping through modules, target executable is %s", 3036 __FUNCTION__, 3037 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str() 3038 : "<none>"); 3039 } 3040 } 3041 } 3042 3043 Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) { 3044 m_abi_sp.reset(); 3045 m_process_input_reader.reset(); 3046 3047 // Find the process and its architecture. Make sure it matches the 3048 // architecture of the current Target, and if not adjust it. 3049 3050 Status error(DoConnectRemote(strm, remote_url)); 3051 if (error.Success()) { 3052 if (GetID() != LLDB_INVALID_PROCESS_ID) { 3053 EventSP event_sp; 3054 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None); 3055 3056 if (state == eStateStopped || state == eStateCrashed) { 3057 // If we attached and actually have a process on the other end, then 3058 // this ended up being the equivalent of an attach. 3059 CompleteAttach(); 3060 3061 // This delays passing the stopped event to listeners till 3062 // CompleteAttach gets a chance to complete... 3063 HandlePrivateEvent(event_sp); 3064 } 3065 } 3066 3067 if (PrivateStateThreadIsValid()) 3068 ResumePrivateStateThread(); 3069 else 3070 StartPrivateStateThread(); 3071 } 3072 return error; 3073 } 3074 3075 Status Process::PrivateResume() { 3076 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | 3077 LIBLLDB_LOG_STEP)); 3078 if (log) 3079 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s " 3080 "private state: %s", 3081 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()), 3082 StateAsCString(m_private_state.GetValue())); 3083 3084 // If signals handing status changed we might want to update our signal 3085 // filters before resuming. 3086 UpdateAutomaticSignalFiltering(); 3087 3088 Status error(WillResume()); 3089 // Tell the process it is about to resume before the thread list 3090 if (error.Success()) { 3091 // Now let the thread list know we are about to resume so it can let all of 3092 // our threads know that they are about to be resumed. Threads will each be 3093 // called with Thread::WillResume(StateType) where StateType contains the 3094 // state that they are supposed to have when the process is resumed 3095 // (suspended/running/stepping). Threads should also check their resume 3096 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to 3097 // start back up with a signal. 3098 if (m_thread_list.WillResume()) { 3099 // Last thing, do the PreResumeActions. 3100 if (!RunPreResumeActions()) { 3101 error.SetErrorStringWithFormat( 3102 "Process::PrivateResume PreResumeActions failed, not resuming."); 3103 } else { 3104 m_mod_id.BumpResumeID(); 3105 error = DoResume(); 3106 if (error.Success()) { 3107 DidResume(); 3108 m_thread_list.DidResume(); 3109 if (log) 3110 log->Printf("Process thinks the process has resumed."); 3111 } else { 3112 if (log) 3113 log->Printf( 3114 "Process::PrivateResume() DoResume failed."); 3115 return error; 3116 } 3117 } 3118 } else { 3119 // Somebody wanted to run without running (e.g. we were faking a step 3120 // from one frame of a set of inlined frames that share the same PC to 3121 // another.) So generate a continue & a stopped event, and let the world 3122 // handle them. 3123 if (log) 3124 log->Printf( 3125 "Process::PrivateResume() asked to simulate a start & stop."); 3126 3127 SetPrivateState(eStateRunning); 3128 SetPrivateState(eStateStopped); 3129 } 3130 } else if (log) 3131 log->Printf("Process::PrivateResume() got an error \"%s\".", 3132 error.AsCString("<unknown error>")); 3133 return error; 3134 } 3135 3136 Status Process::Halt(bool clear_thread_plans, bool use_run_lock) { 3137 if (!StateIsRunningState(m_public_state.GetValue())) 3138 return Status("Process is not running."); 3139 3140 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in 3141 // case it was already set and some thread plan logic calls halt on its own. 3142 m_clear_thread_plans_on_stop |= clear_thread_plans; 3143 3144 ListenerSP halt_listener_sp( 3145 Listener::MakeListener("lldb.process.halt_listener")); 3146 HijackProcessEvents(halt_listener_sp); 3147 3148 EventSP event_sp; 3149 3150 SendAsyncInterrupt(); 3151 3152 if (m_public_state.GetValue() == eStateAttaching) { 3153 // Don't hijack and eat the eStateExited as the code that was doing the 3154 // attach will be waiting for this event... 3155 RestoreProcessEvents(); 3156 SetExitStatus(SIGKILL, "Cancelled async attach."); 3157 Destroy(false); 3158 return Status(); 3159 } 3160 3161 // Wait for 10 second for the process to stop. 3162 StateType state = WaitForProcessToStop( 3163 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock); 3164 RestoreProcessEvents(); 3165 3166 if (state == eStateInvalid || !event_sp) { 3167 // We timed out and didn't get a stop event... 3168 return Status("Halt timed out. State = %s", StateAsCString(GetState())); 3169 } 3170 3171 BroadcastEvent(event_sp); 3172 3173 return Status(); 3174 } 3175 3176 Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) { 3177 Status error; 3178 3179 // Check both the public & private states here. If we're hung evaluating an 3180 // expression, for instance, then the public state will be stopped, but we 3181 // still need to interrupt. 3182 if (m_public_state.GetValue() == eStateRunning || 3183 m_private_state.GetValue() == eStateRunning) { 3184 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3185 if (log) 3186 log->Printf("Process::%s() About to stop.", __FUNCTION__); 3187 3188 ListenerSP listener_sp( 3189 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack")); 3190 HijackProcessEvents(listener_sp); 3191 3192 SendAsyncInterrupt(); 3193 3194 // Consume the interrupt event. 3195 StateType state = 3196 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp); 3197 3198 RestoreProcessEvents(); 3199 3200 // If the process exited while we were waiting for it to stop, put the 3201 // exited event into the shared pointer passed in and return. Our caller 3202 // doesn't need to do anything else, since they don't have a process 3203 // anymore... 3204 3205 if (state == eStateExited || m_private_state.GetValue() == eStateExited) { 3206 if (log) 3207 log->Printf("Process::%s() Process exited while waiting to stop.", 3208 __FUNCTION__); 3209 return error; 3210 } else 3211 exit_event_sp.reset(); // It is ok to consume any non-exit stop events 3212 3213 if (state != eStateStopped) { 3214 if (log) 3215 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__, 3216 StateAsCString(state)); 3217 // If we really couldn't stop the process then we should just error out 3218 // here, but if the lower levels just bobbled sending the event and we 3219 // really are stopped, then continue on. 3220 StateType private_state = m_private_state.GetValue(); 3221 if (private_state != eStateStopped) { 3222 return Status( 3223 "Attempt to stop the target in order to detach timed out. " 3224 "State = %s", 3225 StateAsCString(GetState())); 3226 } 3227 } 3228 } 3229 return error; 3230 } 3231 3232 Status Process::Detach(bool keep_stopped) { 3233 EventSP exit_event_sp; 3234 Status error; 3235 m_destroy_in_process = true; 3236 3237 error = WillDetach(); 3238 3239 if (error.Success()) { 3240 if (DetachRequiresHalt()) { 3241 error = StopForDestroyOrDetach(exit_event_sp); 3242 if (!error.Success()) { 3243 m_destroy_in_process = false; 3244 return error; 3245 } else if (exit_event_sp) { 3246 // We shouldn't need to do anything else here. There's no process left 3247 // to detach from... 3248 StopPrivateStateThread(); 3249 m_destroy_in_process = false; 3250 return error; 3251 } 3252 } 3253 3254 m_thread_list.DiscardThreadPlans(); 3255 DisableAllBreakpointSites(); 3256 3257 error = DoDetach(keep_stopped); 3258 if (error.Success()) { 3259 DidDetach(); 3260 StopPrivateStateThread(); 3261 } else { 3262 return error; 3263 } 3264 } 3265 m_destroy_in_process = false; 3266 3267 // If we exited when we were waiting for a process to stop, then forward the 3268 // event here so we don't lose the event 3269 if (exit_event_sp) { 3270 // Directly broadcast our exited event because we shut down our private 3271 // state thread above 3272 BroadcastEvent(exit_event_sp); 3273 } 3274 3275 // If we have been interrupted (to kill us) in the middle of running, we may 3276 // not end up propagating the last events through the event system, in which 3277 // case we might strand the write lock. Unlock it here so when we do to tear 3278 // down the process we don't get an error destroying the lock. 3279 3280 m_public_run_lock.SetStopped(); 3281 return error; 3282 } 3283 3284 Status Process::Destroy(bool force_kill) { 3285 3286 // Tell ourselves we are in the process of destroying the process, so that we 3287 // don't do any unnecessary work that might hinder the destruction. Remember 3288 // to set this back to false when we are done. That way if the attempt 3289 // failed and the process stays around for some reason it won't be in a 3290 // confused state. 3291 3292 if (force_kill) 3293 m_should_detach = false; 3294 3295 if (GetShouldDetach()) { 3296 // FIXME: This will have to be a process setting: 3297 bool keep_stopped = false; 3298 Detach(keep_stopped); 3299 } 3300 3301 m_destroy_in_process = true; 3302 3303 Status error(WillDestroy()); 3304 if (error.Success()) { 3305 EventSP exit_event_sp; 3306 if (DestroyRequiresHalt()) { 3307 error = StopForDestroyOrDetach(exit_event_sp); 3308 } 3309 3310 if (m_public_state.GetValue() != eStateRunning) { 3311 // Ditch all thread plans, and remove all our breakpoints: in case we 3312 // have to restart the target to kill it, we don't want it hitting a 3313 // breakpoint... Only do this if we've stopped, however, since if we 3314 // didn't manage to halt it above, then we're not going to have much luck 3315 // doing this now. 3316 m_thread_list.DiscardThreadPlans(); 3317 DisableAllBreakpointSites(); 3318 } 3319 3320 error = DoDestroy(); 3321 if (error.Success()) { 3322 DidDestroy(); 3323 StopPrivateStateThread(); 3324 } 3325 m_stdio_communication.Disconnect(); 3326 m_stdio_communication.StopReadThread(); 3327 m_stdin_forward = false; 3328 3329 if (m_process_input_reader) { 3330 m_process_input_reader->SetIsDone(true); 3331 m_process_input_reader->Cancel(); 3332 m_process_input_reader.reset(); 3333 } 3334 3335 // If we exited when we were waiting for a process to stop, then forward 3336 // the event here so we don't lose the event 3337 if (exit_event_sp) { 3338 // Directly broadcast our exited event because we shut down our private 3339 // state thread above 3340 BroadcastEvent(exit_event_sp); 3341 } 3342 3343 // If we have been interrupted (to kill us) in the middle of running, we 3344 // may not end up propagating the last events through the event system, in 3345 // which case we might strand the write lock. Unlock it here so when we do 3346 // to tear down the process we don't get an error destroying the lock. 3347 m_public_run_lock.SetStopped(); 3348 } 3349 3350 m_destroy_in_process = false; 3351 3352 return error; 3353 } 3354 3355 Status Process::Signal(int signal) { 3356 Status error(WillSignal()); 3357 if (error.Success()) { 3358 error = DoSignal(signal); 3359 if (error.Success()) 3360 DidSignal(); 3361 } 3362 return error; 3363 } 3364 3365 void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) { 3366 assert(signals_sp && "null signals_sp"); 3367 m_unix_signals_sp = signals_sp; 3368 } 3369 3370 const lldb::UnixSignalsSP &Process::GetUnixSignals() { 3371 assert(m_unix_signals_sp && "null m_unix_signals_sp"); 3372 return m_unix_signals_sp; 3373 } 3374 3375 lldb::ByteOrder Process::GetByteOrder() const { 3376 return GetTarget().GetArchitecture().GetByteOrder(); 3377 } 3378 3379 uint32_t Process::GetAddressByteSize() const { 3380 return GetTarget().GetArchitecture().GetAddressByteSize(); 3381 } 3382 3383 bool Process::ShouldBroadcastEvent(Event *event_ptr) { 3384 const StateType state = 3385 Process::ProcessEventData::GetStateFromEvent(event_ptr); 3386 bool return_value = true; 3387 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | 3388 LIBLLDB_LOG_PROCESS)); 3389 3390 switch (state) { 3391 case eStateDetached: 3392 case eStateExited: 3393 case eStateUnloaded: 3394 m_stdio_communication.SynchronizeWithReadThread(); 3395 m_stdio_communication.Disconnect(); 3396 m_stdio_communication.StopReadThread(); 3397 m_stdin_forward = false; 3398 3399 LLVM_FALLTHROUGH; 3400 case eStateConnected: 3401 case eStateAttaching: 3402 case eStateLaunching: 3403 // These events indicate changes in the state of the debugging session, 3404 // always report them. 3405 return_value = true; 3406 break; 3407 case eStateInvalid: 3408 // We stopped for no apparent reason, don't report it. 3409 return_value = false; 3410 break; 3411 case eStateRunning: 3412 case eStateStepping: 3413 // If we've started the target running, we handle the cases where we are 3414 // already running and where there is a transition from stopped to running 3415 // differently. running -> running: Automatically suppress extra running 3416 // events stopped -> running: Report except when there is one or more no 3417 // votes 3418 // and no yes votes. 3419 SynchronouslyNotifyStateChanged(state); 3420 if (m_force_next_event_delivery) 3421 return_value = true; 3422 else { 3423 switch (m_last_broadcast_state) { 3424 case eStateRunning: 3425 case eStateStepping: 3426 // We always suppress multiple runnings with no PUBLIC stop in between. 3427 return_value = false; 3428 break; 3429 default: 3430 // TODO: make this work correctly. For now always report 3431 // run if we aren't running so we don't miss any running events. If I 3432 // run the lldb/test/thread/a.out file and break at main.cpp:58, run 3433 // and hit the breakpoints on multiple threads, then somehow during the 3434 // stepping over of all breakpoints no run gets reported. 3435 3436 // This is a transition from stop to run. 3437 switch (m_thread_list.ShouldReportRun(event_ptr)) { 3438 case eVoteYes: 3439 case eVoteNoOpinion: 3440 return_value = true; 3441 break; 3442 case eVoteNo: 3443 return_value = false; 3444 break; 3445 } 3446 break; 3447 } 3448 } 3449 break; 3450 case eStateStopped: 3451 case eStateCrashed: 3452 case eStateSuspended: 3453 // We've stopped. First see if we're going to restart the target. If we 3454 // are going to stop, then we always broadcast the event. If we aren't 3455 // going to stop, let the thread plans decide if we're going to report this 3456 // event. If no thread has an opinion, we don't report it. 3457 3458 m_stdio_communication.SynchronizeWithReadThread(); 3459 RefreshStateAfterStop(); 3460 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) { 3461 if (log) 3462 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an " 3463 "interrupt, state: %s", 3464 static_cast<void *>(event_ptr), StateAsCString(state)); 3465 // Even though we know we are going to stop, we should let the threads 3466 // have a look at the stop, so they can properly set their state. 3467 m_thread_list.ShouldStop(event_ptr); 3468 return_value = true; 3469 } else { 3470 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr); 3471 bool should_resume = false; 3472 3473 // It makes no sense to ask "ShouldStop" if we've already been 3474 // restarted... Asking the thread list is also not likely to go well, 3475 // since we are running again. So in that case just report the event. 3476 3477 if (!was_restarted) 3478 should_resume = !m_thread_list.ShouldStop(event_ptr); 3479 3480 if (was_restarted || should_resume || m_resume_requested) { 3481 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr); 3482 if (log) 3483 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: " 3484 "%s was_restarted: %i stop_vote: %d.", 3485 should_resume, StateAsCString(state), was_restarted, 3486 stop_vote); 3487 3488 switch (stop_vote) { 3489 case eVoteYes: 3490 return_value = true; 3491 break; 3492 case eVoteNoOpinion: 3493 case eVoteNo: 3494 return_value = false; 3495 break; 3496 } 3497 3498 if (!was_restarted) { 3499 if (log) 3500 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process " 3501 "from state: %s", 3502 static_cast<void *>(event_ptr), StateAsCString(state)); 3503 ProcessEventData::SetRestartedInEvent(event_ptr, true); 3504 PrivateResume(); 3505 } 3506 } else { 3507 return_value = true; 3508 SynchronouslyNotifyStateChanged(state); 3509 } 3510 } 3511 break; 3512 } 3513 3514 // Forcing the next event delivery is a one shot deal. So reset it here. 3515 m_force_next_event_delivery = false; 3516 3517 // We do some coalescing of events (for instance two consecutive running 3518 // events get coalesced.) But we only coalesce against events we actually 3519 // broadcast. So we use m_last_broadcast_state to track that. NB - you 3520 // can't use "m_public_state.GetValue()" for that purpose, as was originally 3521 // done, because the PublicState reflects the last event pulled off the 3522 // queue, and there may be several events stacked up on the queue unserviced. 3523 // So the PublicState may not reflect the last broadcasted event yet. 3524 // m_last_broadcast_state gets updated here. 3525 3526 if (return_value) 3527 m_last_broadcast_state = state; 3528 3529 if (log) 3530 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last " 3531 "broadcast state: %s - %s", 3532 static_cast<void *>(event_ptr), StateAsCString(state), 3533 StateAsCString(m_last_broadcast_state), 3534 return_value ? "YES" : "NO"); 3535 return return_value; 3536 } 3537 3538 bool Process::StartPrivateStateThread(bool is_secondary_thread) { 3539 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS)); 3540 3541 bool already_running = PrivateStateThreadIsValid(); 3542 if (log) 3543 log->Printf("Process::%s()%s ", __FUNCTION__, 3544 already_running ? " already running" 3545 : " starting private state thread"); 3546 3547 if (!is_secondary_thread && already_running) 3548 return true; 3549 3550 // Create a thread that watches our internal state and controls which events 3551 // make it to clients (into the DCProcess event queue). 3552 char thread_name[1024]; 3553 uint32_t max_len = llvm::get_max_thread_name_length(); 3554 if (max_len > 0 && max_len <= 30) { 3555 // On platforms with abbreviated thread name lengths, choose thread names 3556 // that fit within the limit. 3557 if (already_running) 3558 snprintf(thread_name, sizeof(thread_name), "intern-state-OV"); 3559 else 3560 snprintf(thread_name, sizeof(thread_name), "intern-state"); 3561 } else { 3562 if (already_running) 3563 snprintf(thread_name, sizeof(thread_name), 3564 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", 3565 GetID()); 3566 else 3567 snprintf(thread_name, sizeof(thread_name), 3568 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID()); 3569 } 3570 3571 // Create the private state thread, and start it running. 3572 PrivateStateThreadArgs *args_ptr = 3573 new PrivateStateThreadArgs(this, is_secondary_thread); 3574 m_private_state_thread = 3575 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, 3576 (void *)args_ptr, nullptr, 8 * 1024 * 1024); 3577 if (m_private_state_thread.IsJoinable()) { 3578 ResumePrivateStateThread(); 3579 return true; 3580 } else 3581 return false; 3582 } 3583 3584 void Process::PausePrivateStateThread() { 3585 ControlPrivateStateThread(eBroadcastInternalStateControlPause); 3586 } 3587 3588 void Process::ResumePrivateStateThread() { 3589 ControlPrivateStateThread(eBroadcastInternalStateControlResume); 3590 } 3591 3592 void Process::StopPrivateStateThread() { 3593 if (m_private_state_thread.IsJoinable()) 3594 ControlPrivateStateThread(eBroadcastInternalStateControlStop); 3595 else { 3596 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3597 if (log) 3598 log->Printf( 3599 "Went to stop the private state thread, but it was already invalid."); 3600 } 3601 } 3602 3603 void Process::ControlPrivateStateThread(uint32_t signal) { 3604 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3605 3606 assert(signal == eBroadcastInternalStateControlStop || 3607 signal == eBroadcastInternalStateControlPause || 3608 signal == eBroadcastInternalStateControlResume); 3609 3610 if (log) 3611 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal); 3612 3613 // Signal the private state thread 3614 if (m_private_state_thread.IsJoinable()) { 3615 // Broadcast the event. 3616 // It is important to do this outside of the if below, because it's 3617 // possible that the thread state is invalid but that the thread is waiting 3618 // on a control event instead of simply being on its way out (this should 3619 // not happen, but it apparently can). 3620 if (log) 3621 log->Printf("Sending control event of type: %d.", signal); 3622 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt()); 3623 m_private_state_control_broadcaster.BroadcastEvent(signal, 3624 event_receipt_sp); 3625 3626 // Wait for the event receipt or for the private state thread to exit 3627 bool receipt_received = false; 3628 if (PrivateStateThreadIsValid()) { 3629 while (!receipt_received) { 3630 // Check for a receipt for n seconds and then check if the private 3631 // state thread is still around. 3632 receipt_received = 3633 event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout()); 3634 if (!receipt_received) { 3635 // Check if the private state thread is still around. If it isn't 3636 // then we are done waiting 3637 if (!PrivateStateThreadIsValid()) 3638 break; // Private state thread exited or is exiting, we are done 3639 } 3640 } 3641 } 3642 3643 if (signal == eBroadcastInternalStateControlStop) { 3644 thread_result_t result = {}; 3645 m_private_state_thread.Join(&result); 3646 m_private_state_thread.Reset(); 3647 } 3648 } else { 3649 if (log) 3650 log->Printf( 3651 "Private state thread already dead, no need to signal it to stop."); 3652 } 3653 } 3654 3655 void Process::SendAsyncInterrupt() { 3656 if (PrivateStateThreadIsValid()) 3657 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt, 3658 nullptr); 3659 else 3660 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr); 3661 } 3662 3663 void Process::HandlePrivateEvent(EventSP &event_sp) { 3664 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3665 m_resume_requested = false; 3666 3667 const StateType new_state = 3668 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 3669 3670 // First check to see if anybody wants a shot at this event: 3671 if (m_next_event_action_up) { 3672 NextEventAction::EventActionResult action_result = 3673 m_next_event_action_up->PerformAction(event_sp); 3674 if (log) 3675 log->Printf("Ran next event action, result was %d.", action_result); 3676 3677 switch (action_result) { 3678 case NextEventAction::eEventActionSuccess: 3679 SetNextEventAction(nullptr); 3680 break; 3681 3682 case NextEventAction::eEventActionRetry: 3683 break; 3684 3685 case NextEventAction::eEventActionExit: 3686 // Handle Exiting Here. If we already got an exited event, we should 3687 // just propagate it. Otherwise, swallow this event, and set our state 3688 // to exit so the next event will kill us. 3689 if (new_state != eStateExited) { 3690 // FIXME: should cons up an exited event, and discard this one. 3691 SetExitStatus(0, m_next_event_action_up->GetExitString()); 3692 SetNextEventAction(nullptr); 3693 return; 3694 } 3695 SetNextEventAction(nullptr); 3696 break; 3697 } 3698 } 3699 3700 // See if we should broadcast this state to external clients? 3701 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get()); 3702 3703 if (should_broadcast) { 3704 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged); 3705 if (log) { 3706 log->Printf("Process::%s (pid = %" PRIu64 3707 ") broadcasting new state %s (old state %s) to %s", 3708 __FUNCTION__, GetID(), StateAsCString(new_state), 3709 StateAsCString(GetState()), 3710 is_hijacked ? "hijacked" : "public"); 3711 } 3712 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get()); 3713 if (StateIsRunningState(new_state)) { 3714 // Only push the input handler if we aren't fowarding events, as this 3715 // means the curses GUI is in use... Or don't push it if we are launching 3716 // since it will come up stopped. 3717 if (!GetTarget().GetDebugger().IsForwardingEvents() && 3718 new_state != eStateLaunching && new_state != eStateAttaching) { 3719 PushProcessIOHandler(); 3720 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1, 3721 eBroadcastAlways); 3722 if (log) 3723 log->Printf("Process::%s updated m_iohandler_sync to %d", 3724 __FUNCTION__, m_iohandler_sync.GetValue()); 3725 } 3726 } else if (StateIsStoppedState(new_state, false)) { 3727 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) { 3728 // If the lldb_private::Debugger is handling the events, we don't want 3729 // to pop the process IOHandler here, we want to do it when we receive 3730 // the stopped event so we can carefully control when the process 3731 // IOHandler is popped because when we stop we want to display some 3732 // text stating how and why we stopped, then maybe some 3733 // process/thread/frame info, and then we want the "(lldb) " prompt to 3734 // show up. If we pop the process IOHandler here, then we will cause 3735 // the command interpreter to become the top IOHandler after the 3736 // process pops off and it will update its prompt right away... See the 3737 // Debugger.cpp file where it calls the function as 3738 // "process_sp->PopProcessIOHandler()" to see where I am talking about. 3739 // Otherwise we end up getting overlapping "(lldb) " prompts and 3740 // garbled output. 3741 // 3742 // If we aren't handling the events in the debugger (which is indicated 3743 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or 3744 // we are hijacked, then we always pop the process IO handler manually. 3745 // Hijacking happens when the internal process state thread is running 3746 // thread plans, or when commands want to run in synchronous mode and 3747 // they call "process->WaitForProcessToStop()". An example of something 3748 // that will hijack the events is a simple expression: 3749 // 3750 // (lldb) expr (int)puts("hello") 3751 // 3752 // This will cause the internal process state thread to resume and halt 3753 // the process (and _it_ will hijack the eBroadcastBitStateChanged 3754 // events) and we do need the IO handler to be pushed and popped 3755 // correctly. 3756 3757 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents()) 3758 PopProcessIOHandler(); 3759 } 3760 } 3761 3762 BroadcastEvent(event_sp); 3763 } else { 3764 if (log) { 3765 log->Printf( 3766 "Process::%s (pid = %" PRIu64 3767 ") suppressing state %s (old state %s): should_broadcast == false", 3768 __FUNCTION__, GetID(), StateAsCString(new_state), 3769 StateAsCString(GetState())); 3770 } 3771 } 3772 } 3773 3774 Status Process::HaltPrivate() { 3775 EventSP event_sp; 3776 Status error(WillHalt()); 3777 if (error.Fail()) 3778 return error; 3779 3780 // Ask the process subclass to actually halt our process 3781 bool caused_stop; 3782 error = DoHalt(caused_stop); 3783 3784 DidHalt(); 3785 return error; 3786 } 3787 3788 thread_result_t Process::PrivateStateThread(void *arg) { 3789 std::unique_ptr<PrivateStateThreadArgs> args_up( 3790 static_cast<PrivateStateThreadArgs *>(arg)); 3791 thread_result_t result = 3792 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread); 3793 return result; 3794 } 3795 3796 thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) { 3797 bool control_only = true; 3798 3799 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3800 if (log) 3801 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", 3802 __FUNCTION__, static_cast<void *>(this), GetID()); 3803 3804 bool exit_now = false; 3805 bool interrupt_requested = false; 3806 while (!exit_now) { 3807 EventSP event_sp; 3808 GetEventsPrivate(event_sp, llvm::None, control_only); 3809 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) { 3810 if (log) 3811 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 3812 ") got a control event: %d", 3813 __FUNCTION__, static_cast<void *>(this), GetID(), 3814 event_sp->GetType()); 3815 3816 switch (event_sp->GetType()) { 3817 case eBroadcastInternalStateControlStop: 3818 exit_now = true; 3819 break; // doing any internal state management below 3820 3821 case eBroadcastInternalStateControlPause: 3822 control_only = true; 3823 break; 3824 3825 case eBroadcastInternalStateControlResume: 3826 control_only = false; 3827 break; 3828 } 3829 3830 continue; 3831 } else if (event_sp->GetType() == eBroadcastBitInterrupt) { 3832 if (m_public_state.GetValue() == eStateAttaching) { 3833 if (log) 3834 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 3835 ") woke up with an interrupt while attaching - " 3836 "forwarding interrupt.", 3837 __FUNCTION__, static_cast<void *>(this), GetID()); 3838 BroadcastEvent(eBroadcastBitInterrupt, nullptr); 3839 } else if (StateIsRunningState(m_last_broadcast_state)) { 3840 if (log) 3841 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 3842 ") woke up with an interrupt - Halting.", 3843 __FUNCTION__, static_cast<void *>(this), GetID()); 3844 Status error = HaltPrivate(); 3845 if (error.Fail() && log) 3846 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 3847 ") failed to halt the process: %s", 3848 __FUNCTION__, static_cast<void *>(this), GetID(), 3849 error.AsCString()); 3850 // Halt should generate a stopped event. Make a note of the fact that 3851 // we were doing the interrupt, so we can set the interrupted flag 3852 // after we receive the event. We deliberately set this to true even if 3853 // HaltPrivate failed, so that we can interrupt on the next natural 3854 // stop. 3855 interrupt_requested = true; 3856 } else { 3857 // This can happen when someone (e.g. Process::Halt) sees that we are 3858 // running and sends an interrupt request, but the process actually 3859 // stops before we receive it. In that case, we can just ignore the 3860 // request. We use m_last_broadcast_state, because the Stopped event 3861 // may not have been popped of the event queue yet, which is when the 3862 // public state gets updated. 3863 if (log) 3864 log->Printf( 3865 "Process::%s ignoring interrupt as we have already stopped.", 3866 __FUNCTION__); 3867 } 3868 continue; 3869 } 3870 3871 const StateType internal_state = 3872 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 3873 3874 if (internal_state != eStateInvalid) { 3875 if (m_clear_thread_plans_on_stop && 3876 StateIsStoppedState(internal_state, true)) { 3877 m_clear_thread_plans_on_stop = false; 3878 m_thread_list.DiscardThreadPlans(); 3879 } 3880 3881 if (interrupt_requested) { 3882 if (StateIsStoppedState(internal_state, true)) { 3883 // We requested the interrupt, so mark this as such in the stop event 3884 // so clients can tell an interrupted process from a natural stop 3885 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true); 3886 interrupt_requested = false; 3887 } else if (log) { 3888 log->Printf("Process::%s interrupt_requested, but a non-stopped " 3889 "state '%s' received.", 3890 __FUNCTION__, StateAsCString(internal_state)); 3891 } 3892 } 3893 3894 HandlePrivateEvent(event_sp); 3895 } 3896 3897 if (internal_state == eStateInvalid || internal_state == eStateExited || 3898 internal_state == eStateDetached) { 3899 if (log) 3900 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 3901 ") about to exit with internal state %s...", 3902 __FUNCTION__, static_cast<void *>(this), GetID(), 3903 StateAsCString(internal_state)); 3904 3905 break; 3906 } 3907 } 3908 3909 // Verify log is still enabled before attempting to write to it... 3910 if (log) 3911 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", 3912 __FUNCTION__, static_cast<void *>(this), GetID()); 3913 3914 // If we are a secondary thread, then the primary thread we are working for 3915 // will have already acquired the public_run_lock, and isn't done with what 3916 // it was doing yet, so don't try to change it on the way out. 3917 if (!is_secondary_thread) 3918 m_public_run_lock.SetStopped(); 3919 return {}; 3920 } 3921 3922 // Process Event Data 3923 3924 Process::ProcessEventData::ProcessEventData() 3925 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false), 3926 m_update_state(0), m_interrupted(false) {} 3927 3928 Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp, 3929 StateType state) 3930 : EventData(), m_process_wp(), m_state(state), m_restarted(false), 3931 m_update_state(0), m_interrupted(false) { 3932 if (process_sp) 3933 m_process_wp = process_sp; 3934 } 3935 3936 Process::ProcessEventData::~ProcessEventData() = default; 3937 3938 ConstString Process::ProcessEventData::GetFlavorString() { 3939 static ConstString g_flavor("Process::ProcessEventData"); 3940 return g_flavor; 3941 } 3942 3943 ConstString Process::ProcessEventData::GetFlavor() const { 3944 return ProcessEventData::GetFlavorString(); 3945 } 3946 3947 void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) { 3948 ProcessSP process_sp(m_process_wp.lock()); 3949 3950 if (!process_sp) 3951 return; 3952 3953 // This function gets called twice for each event, once when the event gets 3954 // pulled off of the private process event queue, and then any number of 3955 // times, first when it gets pulled off of the public event queue, then other 3956 // times when we're pretending that this is where we stopped at the end of 3957 // expression evaluation. m_update_state is used to distinguish these three 3958 // cases; it is 0 when we're just pulling it off for private handling, and > 3959 // 1 for expression evaluation, and we don't want to do the breakpoint 3960 // command handling then. 3961 if (m_update_state != 1) 3962 return; 3963 3964 process_sp->SetPublicState( 3965 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr)); 3966 3967 if (m_state == eStateStopped && !m_restarted) { 3968 // Let process subclasses know we are about to do a public stop and do 3969 // anything they might need to in order to speed up register and memory 3970 // accesses. 3971 process_sp->WillPublicStop(); 3972 } 3973 3974 // If this is a halt event, even if the halt stopped with some reason other 3975 // than a plain interrupt (e.g. we had already stopped for a breakpoint when 3976 // the halt request came through) don't do the StopInfo actions, as they may 3977 // end up restarting the process. 3978 if (m_interrupted) 3979 return; 3980 3981 // If we're stopped and haven't restarted, then do the StopInfo actions here: 3982 if (m_state == eStateStopped && !m_restarted) { 3983 ThreadList &curr_thread_list = process_sp->GetThreadList(); 3984 uint32_t num_threads = curr_thread_list.GetSize(); 3985 uint32_t idx; 3986 3987 // The actions might change one of the thread's stop_info's opinions about 3988 // whether we should stop the process, so we need to query that as we go. 3989 3990 // One other complication here, is that we try to catch any case where the 3991 // target has run (except for expressions) and immediately exit, but if we 3992 // get that wrong (which is possible) then the thread list might have 3993 // changed, and that would cause our iteration here to crash. We could 3994 // make a copy of the thread list, but we'd really like to also know if it 3995 // has changed at all, so we make up a vector of the thread ID's and check 3996 // what we get back against this list & bag out if anything differs. 3997 std::vector<uint32_t> thread_index_array(num_threads); 3998 for (idx = 0; idx < num_threads; ++idx) 3999 thread_index_array[idx] = 4000 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID(); 4001 4002 // Use this to track whether we should continue from here. We will only 4003 // continue the target running if no thread says we should stop. Of course 4004 // if some thread's PerformAction actually sets the target running, then it 4005 // doesn't matter what the other threads say... 4006 4007 bool still_should_stop = false; 4008 4009 // Sometimes - for instance if we have a bug in the stub we are talking to, 4010 // we stop but no thread has a valid stop reason. In that case we should 4011 // just stop, because we have no way of telling what the right thing to do 4012 // is, and it's better to let the user decide than continue behind their 4013 // backs. 4014 4015 bool does_anybody_have_an_opinion = false; 4016 4017 for (idx = 0; idx < num_threads; ++idx) { 4018 curr_thread_list = process_sp->GetThreadList(); 4019 if (curr_thread_list.GetSize() != num_threads) { 4020 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | 4021 LIBLLDB_LOG_PROCESS)); 4022 if (log) 4023 log->Printf( 4024 "Number of threads changed from %u to %u while processing event.", 4025 num_threads, curr_thread_list.GetSize()); 4026 break; 4027 } 4028 4029 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx); 4030 4031 if (thread_sp->GetIndexID() != thread_index_array[idx]) { 4032 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | 4033 LIBLLDB_LOG_PROCESS)); 4034 if (log) 4035 log->Printf("The thread at position %u changed from %u to %u while " 4036 "processing event.", 4037 idx, thread_index_array[idx], thread_sp->GetIndexID()); 4038 break; 4039 } 4040 4041 StopInfoSP stop_info_sp = thread_sp->GetStopInfo(); 4042 if (stop_info_sp && stop_info_sp->IsValid()) { 4043 does_anybody_have_an_opinion = true; 4044 bool this_thread_wants_to_stop; 4045 if (stop_info_sp->GetOverrideShouldStop()) { 4046 this_thread_wants_to_stop = 4047 stop_info_sp->GetOverriddenShouldStopValue(); 4048 } else { 4049 stop_info_sp->PerformAction(event_ptr); 4050 // The stop action might restart the target. If it does, then we 4051 // want to mark that in the event so that whoever is receiving it 4052 // will know to wait for the running event and reflect that state 4053 // appropriately. We also need to stop processing actions, since they 4054 // aren't expecting the target to be running. 4055 4056 // FIXME: we might have run. 4057 if (stop_info_sp->HasTargetRunSinceMe()) { 4058 SetRestarted(true); 4059 break; 4060 } 4061 4062 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr); 4063 } 4064 4065 if (!still_should_stop) 4066 still_should_stop = this_thread_wants_to_stop; 4067 } 4068 } 4069 4070 if (!GetRestarted()) { 4071 if (!still_should_stop && does_anybody_have_an_opinion) { 4072 // We've been asked to continue, so do that here. 4073 SetRestarted(true); 4074 // Use the public resume method here, since this is just extending a 4075 // public resume. 4076 process_sp->PrivateResume(); 4077 } else { 4078 bool hijacked = 4079 process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) && 4080 !process_sp->StateChangedIsHijackedForSynchronousResume(); 4081 4082 if (!hijacked) { 4083 // If we didn't restart, run the Stop Hooks here. 4084 // Don't do that if state changed events aren't hooked up to the 4085 // public (or SyncResume) broadcasters. StopHooks are just for 4086 // real public stops. They might also restart the target, 4087 // so watch for that. 4088 process_sp->GetTarget().RunStopHooks(); 4089 if (process_sp->GetPrivateState() == eStateRunning) 4090 SetRestarted(true); 4091 } 4092 } 4093 } 4094 } 4095 } 4096 4097 void Process::ProcessEventData::Dump(Stream *s) const { 4098 ProcessSP process_sp(m_process_wp.lock()); 4099 4100 if (process_sp) 4101 s->Printf(" process = %p (pid = %" PRIu64 "), ", 4102 static_cast<void *>(process_sp.get()), process_sp->GetID()); 4103 else 4104 s->PutCString(" process = NULL, "); 4105 4106 s->Printf("state = %s", StateAsCString(GetState())); 4107 } 4108 4109 const Process::ProcessEventData * 4110 Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) { 4111 if (event_ptr) { 4112 const EventData *event_data = event_ptr->GetData(); 4113 if (event_data && 4114 event_data->GetFlavor() == ProcessEventData::GetFlavorString()) 4115 return static_cast<const ProcessEventData *>(event_ptr->GetData()); 4116 } 4117 return nullptr; 4118 } 4119 4120 ProcessSP 4121 Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) { 4122 ProcessSP process_sp; 4123 const ProcessEventData *data = GetEventDataFromEvent(event_ptr); 4124 if (data) 4125 process_sp = data->GetProcessSP(); 4126 return process_sp; 4127 } 4128 4129 StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) { 4130 const ProcessEventData *data = GetEventDataFromEvent(event_ptr); 4131 if (data == nullptr) 4132 return eStateInvalid; 4133 else 4134 return data->GetState(); 4135 } 4136 4137 bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) { 4138 const ProcessEventData *data = GetEventDataFromEvent(event_ptr); 4139 if (data == nullptr) 4140 return false; 4141 else 4142 return data->GetRestarted(); 4143 } 4144 4145 void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr, 4146 bool new_value) { 4147 ProcessEventData *data = 4148 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4149 if (data != nullptr) 4150 data->SetRestarted(new_value); 4151 } 4152 4153 size_t 4154 Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) { 4155 ProcessEventData *data = 4156 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4157 if (data != nullptr) 4158 return data->GetNumRestartedReasons(); 4159 else 4160 return 0; 4161 } 4162 4163 const char * 4164 Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, 4165 size_t idx) { 4166 ProcessEventData *data = 4167 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4168 if (data != nullptr) 4169 return data->GetRestartedReasonAtIndex(idx); 4170 else 4171 return nullptr; 4172 } 4173 4174 void Process::ProcessEventData::AddRestartedReason(Event *event_ptr, 4175 const char *reason) { 4176 ProcessEventData *data = 4177 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4178 if (data != nullptr) 4179 data->AddRestartedReason(reason); 4180 } 4181 4182 bool Process::ProcessEventData::GetInterruptedFromEvent( 4183 const Event *event_ptr) { 4184 const ProcessEventData *data = GetEventDataFromEvent(event_ptr); 4185 if (data == nullptr) 4186 return false; 4187 else 4188 return data->GetInterrupted(); 4189 } 4190 4191 void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr, 4192 bool new_value) { 4193 ProcessEventData *data = 4194 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4195 if (data != nullptr) 4196 data->SetInterrupted(new_value); 4197 } 4198 4199 bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) { 4200 ProcessEventData *data = 4201 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4202 if (data) { 4203 data->SetUpdateStateOnRemoval(); 4204 return true; 4205 } 4206 return false; 4207 } 4208 4209 lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); } 4210 4211 void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) { 4212 exe_ctx.SetTargetPtr(&GetTarget()); 4213 exe_ctx.SetProcessPtr(this); 4214 exe_ctx.SetThreadPtr(nullptr); 4215 exe_ctx.SetFramePtr(nullptr); 4216 } 4217 4218 // uint32_t 4219 // Process::ListProcessesMatchingName (const char *name, StringList &matches, 4220 // std::vector<lldb::pid_t> &pids) 4221 //{ 4222 // return 0; 4223 //} 4224 // 4225 // ArchSpec 4226 // Process::GetArchSpecForExistingProcess (lldb::pid_t pid) 4227 //{ 4228 // return Host::GetArchSpecForExistingProcess (pid); 4229 //} 4230 // 4231 // ArchSpec 4232 // Process::GetArchSpecForExistingProcess (const char *process_name) 4233 //{ 4234 // return Host::GetArchSpecForExistingProcess (process_name); 4235 //} 4236 4237 void Process::AppendSTDOUT(const char *s, size_t len) { 4238 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex); 4239 m_stdout_data.append(s, len); 4240 BroadcastEventIfUnique(eBroadcastBitSTDOUT, 4241 new ProcessEventData(shared_from_this(), GetState())); 4242 } 4243 4244 void Process::AppendSTDERR(const char *s, size_t len) { 4245 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex); 4246 m_stderr_data.append(s, len); 4247 BroadcastEventIfUnique(eBroadcastBitSTDERR, 4248 new ProcessEventData(shared_from_this(), GetState())); 4249 } 4250 4251 void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) { 4252 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex); 4253 m_profile_data.push_back(one_profile_data); 4254 BroadcastEventIfUnique(eBroadcastBitProfileData, 4255 new ProcessEventData(shared_from_this(), GetState())); 4256 } 4257 4258 void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp, 4259 const StructuredDataPluginSP &plugin_sp) { 4260 BroadcastEvent( 4261 eBroadcastBitStructuredData, 4262 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp)); 4263 } 4264 4265 StructuredDataPluginSP 4266 Process::GetStructuredDataPlugin(ConstString type_name) const { 4267 auto find_it = m_structured_data_plugin_map.find(type_name); 4268 if (find_it != m_structured_data_plugin_map.end()) 4269 return find_it->second; 4270 else 4271 return StructuredDataPluginSP(); 4272 } 4273 4274 size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) { 4275 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex); 4276 if (m_profile_data.empty()) 4277 return 0; 4278 4279 std::string &one_profile_data = m_profile_data.front(); 4280 size_t bytes_available = one_profile_data.size(); 4281 if (bytes_available > 0) { 4282 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4283 if (log) 4284 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", 4285 static_cast<void *>(buf), static_cast<uint64_t>(buf_size)); 4286 if (bytes_available > buf_size) { 4287 memcpy(buf, one_profile_data.c_str(), buf_size); 4288 one_profile_data.erase(0, buf_size); 4289 bytes_available = buf_size; 4290 } else { 4291 memcpy(buf, one_profile_data.c_str(), bytes_available); 4292 m_profile_data.erase(m_profile_data.begin()); 4293 } 4294 } 4295 return bytes_available; 4296 } 4297 4298 // Process STDIO 4299 4300 size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) { 4301 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex); 4302 size_t bytes_available = m_stdout_data.size(); 4303 if (bytes_available > 0) { 4304 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4305 if (log) 4306 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", 4307 static_cast<void *>(buf), static_cast<uint64_t>(buf_size)); 4308 if (bytes_available > buf_size) { 4309 memcpy(buf, m_stdout_data.c_str(), buf_size); 4310 m_stdout_data.erase(0, buf_size); 4311 bytes_available = buf_size; 4312 } else { 4313 memcpy(buf, m_stdout_data.c_str(), bytes_available); 4314 m_stdout_data.clear(); 4315 } 4316 } 4317 return bytes_available; 4318 } 4319 4320 size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) { 4321 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex); 4322 size_t bytes_available = m_stderr_data.size(); 4323 if (bytes_available > 0) { 4324 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4325 if (log) 4326 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", 4327 static_cast<void *>(buf), static_cast<uint64_t>(buf_size)); 4328 if (bytes_available > buf_size) { 4329 memcpy(buf, m_stderr_data.c_str(), buf_size); 4330 m_stderr_data.erase(0, buf_size); 4331 bytes_available = buf_size; 4332 } else { 4333 memcpy(buf, m_stderr_data.c_str(), bytes_available); 4334 m_stderr_data.clear(); 4335 } 4336 } 4337 return bytes_available; 4338 } 4339 4340 void Process::STDIOReadThreadBytesReceived(void *baton, const void *src, 4341 size_t src_len) { 4342 Process *process = (Process *)baton; 4343 process->AppendSTDOUT(static_cast<const char *>(src), src_len); 4344 } 4345 4346 class IOHandlerProcessSTDIO : public IOHandler { 4347 public: 4348 IOHandlerProcessSTDIO(Process *process, int write_fd) 4349 : IOHandler(process->GetTarget().GetDebugger(), 4350 IOHandler::Type::ProcessIO), 4351 m_process(process), m_write_file(write_fd, false) { 4352 m_pipe.CreateNew(false); 4353 m_read_file.SetDescriptor(GetInputFD(), false); 4354 } 4355 4356 ~IOHandlerProcessSTDIO() override = default; 4357 4358 // Each IOHandler gets to run until it is done. It should read data from the 4359 // "in" and place output into "out" and "err and return when done. 4360 void Run() override { 4361 if (!m_read_file.IsValid() || !m_write_file.IsValid() || 4362 !m_pipe.CanRead() || !m_pipe.CanWrite()) { 4363 SetIsDone(true); 4364 return; 4365 } 4366 4367 SetIsDone(false); 4368 const int read_fd = m_read_file.GetDescriptor(); 4369 TerminalState terminal_state; 4370 terminal_state.Save(read_fd, false); 4371 Terminal terminal(read_fd); 4372 terminal.SetCanonical(false); 4373 terminal.SetEcho(false); 4374 // FD_ZERO, FD_SET are not supported on windows 4375 #ifndef _WIN32 4376 const int pipe_read_fd = m_pipe.GetReadFileDescriptor(); 4377 m_is_running = true; 4378 while (!GetIsDone()) { 4379 SelectHelper select_helper; 4380 select_helper.FDSetRead(read_fd); 4381 select_helper.FDSetRead(pipe_read_fd); 4382 Status error = select_helper.Select(); 4383 4384 if (error.Fail()) { 4385 SetIsDone(true); 4386 } else { 4387 char ch = 0; 4388 size_t n; 4389 if (select_helper.FDIsSetRead(read_fd)) { 4390 n = 1; 4391 if (m_read_file.Read(&ch, n).Success() && n == 1) { 4392 if (m_write_file.Write(&ch, n).Fail() || n != 1) 4393 SetIsDone(true); 4394 } else 4395 SetIsDone(true); 4396 } 4397 if (select_helper.FDIsSetRead(pipe_read_fd)) { 4398 size_t bytes_read; 4399 // Consume the interrupt byte 4400 Status error = m_pipe.Read(&ch, 1, bytes_read); 4401 if (error.Success()) { 4402 switch (ch) { 4403 case 'q': 4404 SetIsDone(true); 4405 break; 4406 case 'i': 4407 if (StateIsRunningState(m_process->GetState())) 4408 m_process->SendAsyncInterrupt(); 4409 break; 4410 } 4411 } 4412 } 4413 } 4414 } 4415 m_is_running = false; 4416 #endif 4417 terminal_state.Restore(); 4418 } 4419 4420 void Cancel() override { 4421 SetIsDone(true); 4422 // Only write to our pipe to cancel if we are in 4423 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that 4424 // is being run from the command interpreter: 4425 // 4426 // (lldb) step_process_thousands_of_times 4427 // 4428 // In this case the command interpreter will be in the middle of handling 4429 // the command and if the process pushes and pops the IOHandler thousands 4430 // of times, we can end up writing to m_pipe without ever consuming the 4431 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up 4432 // deadlocking when the pipe gets fed up and blocks until data is consumed. 4433 if (m_is_running) { 4434 char ch = 'q'; // Send 'q' for quit 4435 size_t bytes_written = 0; 4436 m_pipe.Write(&ch, 1, bytes_written); 4437 } 4438 } 4439 4440 bool Interrupt() override { 4441 // Do only things that are safe to do in an interrupt context (like in a 4442 // SIGINT handler), like write 1 byte to a file descriptor. This will 4443 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte 4444 // that was written to the pipe and then call 4445 // m_process->SendAsyncInterrupt() from a much safer location in code. 4446 if (m_active) { 4447 char ch = 'i'; // Send 'i' for interrupt 4448 size_t bytes_written = 0; 4449 Status result = m_pipe.Write(&ch, 1, bytes_written); 4450 return result.Success(); 4451 } else { 4452 // This IOHandler might be pushed on the stack, but not being run 4453 // currently so do the right thing if we aren't actively watching for 4454 // STDIN by sending the interrupt to the process. Otherwise the write to 4455 // the pipe above would do nothing. This can happen when the command 4456 // interpreter is running and gets a "expression ...". It will be on the 4457 // IOHandler thread and sending the input is complete to the delegate 4458 // which will cause the expression to run, which will push the process IO 4459 // handler, but not run it. 4460 4461 if (StateIsRunningState(m_process->GetState())) { 4462 m_process->SendAsyncInterrupt(); 4463 return true; 4464 } 4465 } 4466 return false; 4467 } 4468 4469 void GotEOF() override {} 4470 4471 protected: 4472 Process *m_process; 4473 File m_read_file; // Read from this file (usually actual STDIN for LLDB 4474 File m_write_file; // Write to this file (usually the master pty for getting 4475 // io to debuggee) 4476 Pipe m_pipe; 4477 std::atomic<bool> m_is_running{false}; 4478 }; 4479 4480 void Process::SetSTDIOFileDescriptor(int fd) { 4481 // First set up the Read Thread for reading/handling process I/O 4482 4483 std::unique_ptr<ConnectionFileDescriptor> conn_up( 4484 new ConnectionFileDescriptor(fd, true)); 4485 4486 if (conn_up) { 4487 m_stdio_communication.SetConnection(conn_up.release()); 4488 if (m_stdio_communication.IsConnected()) { 4489 m_stdio_communication.SetReadThreadBytesReceivedCallback( 4490 STDIOReadThreadBytesReceived, this); 4491 m_stdio_communication.StartReadThread(); 4492 4493 // Now read thread is set up, set up input reader. 4494 4495 if (!m_process_input_reader) 4496 m_process_input_reader = 4497 std::make_shared<IOHandlerProcessSTDIO>(this, fd); 4498 } 4499 } 4500 } 4501 4502 bool Process::ProcessIOHandlerIsActive() { 4503 IOHandlerSP io_handler_sp(m_process_input_reader); 4504 if (io_handler_sp) 4505 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp); 4506 return false; 4507 } 4508 bool Process::PushProcessIOHandler() { 4509 IOHandlerSP io_handler_sp(m_process_input_reader); 4510 if (io_handler_sp) { 4511 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4512 if (log) 4513 log->Printf("Process::%s pushing IO handler", __FUNCTION__); 4514 4515 io_handler_sp->SetIsDone(false); 4516 // If we evaluate an utility function, then we don't cancel the current 4517 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the 4518 // existing IOHandler that potentially provides the user interface (e.g. 4519 // the IOHandler for Editline). 4520 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction(); 4521 GetTarget().GetDebugger().PushIOHandler(io_handler_sp, cancel_top_handler); 4522 return true; 4523 } 4524 return false; 4525 } 4526 4527 bool Process::PopProcessIOHandler() { 4528 IOHandlerSP io_handler_sp(m_process_input_reader); 4529 if (io_handler_sp) 4530 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp); 4531 return false; 4532 } 4533 4534 // The process needs to know about installed plug-ins 4535 void Process::SettingsInitialize() { Thread::SettingsInitialize(); } 4536 4537 void Process::SettingsTerminate() { Thread::SettingsTerminate(); } 4538 4539 namespace { 4540 // RestorePlanState is used to record the "is private", "is master" and "okay 4541 // to discard" fields of the plan we are running, and reset it on Clean or on 4542 // destruction. It will only reset the state once, so you can call Clean and 4543 // then monkey with the state and it won't get reset on you again. 4544 4545 class RestorePlanState { 4546 public: 4547 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp) 4548 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) { 4549 if (m_thread_plan_sp) { 4550 m_private = m_thread_plan_sp->GetPrivate(); 4551 m_is_master = m_thread_plan_sp->IsMasterPlan(); 4552 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard(); 4553 } 4554 } 4555 4556 ~RestorePlanState() { Clean(); } 4557 4558 void Clean() { 4559 if (!m_already_reset && m_thread_plan_sp) { 4560 m_already_reset = true; 4561 m_thread_plan_sp->SetPrivate(m_private); 4562 m_thread_plan_sp->SetIsMasterPlan(m_is_master); 4563 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard); 4564 } 4565 } 4566 4567 private: 4568 lldb::ThreadPlanSP m_thread_plan_sp; 4569 bool m_already_reset; 4570 bool m_private; 4571 bool m_is_master; 4572 bool m_okay_to_discard; 4573 }; 4574 } // anonymous namespace 4575 4576 static microseconds 4577 GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) { 4578 const milliseconds default_one_thread_timeout(250); 4579 4580 // If the overall wait is forever, then we don't need to worry about it. 4581 if (!options.GetTimeout()) { 4582 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout() 4583 : default_one_thread_timeout; 4584 } 4585 4586 // If the one thread timeout is set, use it. 4587 if (options.GetOneThreadTimeout()) 4588 return *options.GetOneThreadTimeout(); 4589 4590 // Otherwise use half the total timeout, bounded by the 4591 // default_one_thread_timeout. 4592 return std::min<microseconds>(default_one_thread_timeout, 4593 *options.GetTimeout() / 2); 4594 } 4595 4596 static Timeout<std::micro> 4597 GetExpressionTimeout(const EvaluateExpressionOptions &options, 4598 bool before_first_timeout) { 4599 // If we are going to run all threads the whole time, or if we are only going 4600 // to run one thread, we can just return the overall timeout. 4601 if (!options.GetStopOthers() || !options.GetTryAllThreads()) 4602 return options.GetTimeout(); 4603 4604 if (before_first_timeout) 4605 return GetOneThreadExpressionTimeout(options); 4606 4607 if (!options.GetTimeout()) 4608 return llvm::None; 4609 else 4610 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options); 4611 } 4612 4613 static llvm::Optional<ExpressionResults> 4614 HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp, 4615 RestorePlanState &restorer, const EventSP &event_sp, 4616 EventSP &event_to_broadcast_sp, 4617 const EvaluateExpressionOptions &options, bool handle_interrupts) { 4618 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS); 4619 4620 ThreadPlanSP plan = thread.GetCompletedPlan(); 4621 if (plan == thread_plan_sp && plan->PlanSucceeded()) { 4622 LLDB_LOG(log, "execution completed successfully"); 4623 4624 // Restore the plan state so it will get reported as intended when we are 4625 // done. 4626 restorer.Clean(); 4627 return eExpressionCompleted; 4628 } 4629 4630 StopInfoSP stop_info_sp = thread.GetStopInfo(); 4631 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint && 4632 stop_info_sp->ShouldNotify(event_sp.get())) { 4633 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription()); 4634 if (!options.DoesIgnoreBreakpoints()) { 4635 // Restore the plan state and then force Private to false. We are going 4636 // to stop because of this plan so we need it to become a public plan or 4637 // it won't report correctly when we continue to its termination later 4638 // on. 4639 restorer.Clean(); 4640 thread_plan_sp->SetPrivate(false); 4641 event_to_broadcast_sp = event_sp; 4642 } 4643 return eExpressionHitBreakpoint; 4644 } 4645 4646 if (!handle_interrupts && 4647 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get())) 4648 return llvm::None; 4649 4650 LLDB_LOG(log, "thread plan did not successfully complete"); 4651 if (!options.DoesUnwindOnError()) 4652 event_to_broadcast_sp = event_sp; 4653 return eExpressionInterrupted; 4654 } 4655 4656 ExpressionResults 4657 Process::RunThreadPlan(ExecutionContext &exe_ctx, 4658 lldb::ThreadPlanSP &thread_plan_sp, 4659 const EvaluateExpressionOptions &options, 4660 DiagnosticManager &diagnostic_manager) { 4661 ExpressionResults return_value = eExpressionSetupError; 4662 4663 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock); 4664 4665 if (!thread_plan_sp) { 4666 diagnostic_manager.PutString( 4667 eDiagnosticSeverityError, 4668 "RunThreadPlan called with empty thread plan."); 4669 return eExpressionSetupError; 4670 } 4671 4672 if (!thread_plan_sp->ValidatePlan(nullptr)) { 4673 diagnostic_manager.PutString( 4674 eDiagnosticSeverityError, 4675 "RunThreadPlan called with an invalid thread plan."); 4676 return eExpressionSetupError; 4677 } 4678 4679 if (exe_ctx.GetProcessPtr() != this) { 4680 diagnostic_manager.PutString(eDiagnosticSeverityError, 4681 "RunThreadPlan called on wrong process."); 4682 return eExpressionSetupError; 4683 } 4684 4685 Thread *thread = exe_ctx.GetThreadPtr(); 4686 if (thread == nullptr) { 4687 diagnostic_manager.PutString(eDiagnosticSeverityError, 4688 "RunThreadPlan called with invalid thread."); 4689 return eExpressionSetupError; 4690 } 4691 4692 // We need to change some of the thread plan attributes for the thread plan 4693 // runner. This will restore them when we are done: 4694 4695 RestorePlanState thread_plan_restorer(thread_plan_sp); 4696 4697 // We rely on the thread plan we are running returning "PlanCompleted" if 4698 // when it successfully completes. For that to be true the plan can't be 4699 // private - since private plans suppress themselves in the GetCompletedPlan 4700 // call. 4701 4702 thread_plan_sp->SetPrivate(false); 4703 4704 // The plans run with RunThreadPlan also need to be terminal master plans or 4705 // when they are done we will end up asking the plan above us whether we 4706 // should stop, which may give the wrong answer. 4707 4708 thread_plan_sp->SetIsMasterPlan(true); 4709 thread_plan_sp->SetOkayToDiscard(false); 4710 4711 // If we are running some utility expression for LLDB, we now have to mark 4712 // this in the ProcesModID of this process. This RAII takes care of marking 4713 // and reverting the mark it once we are done running the expression. 4714 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr); 4715 4716 if (m_private_state.GetValue() != eStateStopped) { 4717 diagnostic_manager.PutString( 4718 eDiagnosticSeverityError, 4719 "RunThreadPlan called while the private state was not stopped."); 4720 return eExpressionSetupError; 4721 } 4722 4723 // Save the thread & frame from the exe_ctx for restoration after we run 4724 const uint32_t thread_idx_id = thread->GetIndexID(); 4725 StackFrameSP selected_frame_sp = thread->GetSelectedFrame(); 4726 if (!selected_frame_sp) { 4727 thread->SetSelectedFrame(nullptr); 4728 selected_frame_sp = thread->GetSelectedFrame(); 4729 if (!selected_frame_sp) { 4730 diagnostic_manager.Printf( 4731 eDiagnosticSeverityError, 4732 "RunThreadPlan called without a selected frame on thread %d", 4733 thread_idx_id); 4734 return eExpressionSetupError; 4735 } 4736 } 4737 4738 // Make sure the timeout values make sense. The one thread timeout needs to 4739 // be smaller than the overall timeout. 4740 if (options.GetOneThreadTimeout() && options.GetTimeout() && 4741 *options.GetTimeout() < *options.GetOneThreadTimeout()) { 4742 diagnostic_manager.PutString(eDiagnosticSeverityError, 4743 "RunThreadPlan called with one thread " 4744 "timeout greater than total timeout"); 4745 return eExpressionSetupError; 4746 } 4747 4748 StackID ctx_frame_id = selected_frame_sp->GetStackID(); 4749 4750 // N.B. Running the target may unset the currently selected thread and frame. 4751 // We don't want to do that either, so we should arrange to reset them as 4752 // well. 4753 4754 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread(); 4755 4756 uint32_t selected_tid; 4757 StackID selected_stack_id; 4758 if (selected_thread_sp) { 4759 selected_tid = selected_thread_sp->GetIndexID(); 4760 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID(); 4761 } else { 4762 selected_tid = LLDB_INVALID_THREAD_ID; 4763 } 4764 4765 HostThread backup_private_state_thread; 4766 lldb::StateType old_state = eStateInvalid; 4767 lldb::ThreadPlanSP stopper_base_plan_sp; 4768 4769 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | 4770 LIBLLDB_LOG_PROCESS)); 4771 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) { 4772 // Yikes, we are running on the private state thread! So we can't wait for 4773 // public events on this thread, since we are the thread that is generating 4774 // public events. The simplest thing to do is to spin up a temporary thread 4775 // to handle private state thread events while we are fielding public 4776 // events here. 4777 if (log) 4778 log->Printf("Running thread plan on private state thread, spinning up " 4779 "another state thread to handle the events."); 4780 4781 backup_private_state_thread = m_private_state_thread; 4782 4783 // One other bit of business: we want to run just this thread plan and 4784 // anything it pushes, and then stop, returning control here. But in the 4785 // normal course of things, the plan above us on the stack would be given a 4786 // shot at the stop event before deciding to stop, and we don't want that. 4787 // So we insert a "stopper" base plan on the stack before the plan we want 4788 // to run. Since base plans always stop and return control to the user, 4789 // that will do just what we want. 4790 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread)); 4791 thread->QueueThreadPlan(stopper_base_plan_sp, false); 4792 // Have to make sure our public state is stopped, since otherwise the 4793 // reporting logic below doesn't work correctly. 4794 old_state = m_public_state.GetValue(); 4795 m_public_state.SetValueNoLock(eStateStopped); 4796 4797 // Now spin up the private state thread: 4798 StartPrivateStateThread(true); 4799 } 4800 4801 thread->QueueThreadPlan( 4802 thread_plan_sp, false); // This used to pass "true" does that make sense? 4803 4804 if (options.GetDebug()) { 4805 // In this case, we aren't actually going to run, we just want to stop 4806 // right away. Flush this thread so we will refetch the stacks and show the 4807 // correct backtrace. 4808 // FIXME: To make this prettier we should invent some stop reason for this, 4809 // but that 4810 // is only cosmetic, and this functionality is only of use to lldb 4811 // developers who can live with not pretty... 4812 thread->Flush(); 4813 return eExpressionStoppedForDebug; 4814 } 4815 4816 ListenerSP listener_sp( 4817 Listener::MakeListener("lldb.process.listener.run-thread-plan")); 4818 4819 lldb::EventSP event_to_broadcast_sp; 4820 4821 { 4822 // This process event hijacker Hijacks the Public events and its destructor 4823 // makes sure that the process events get restored on exit to the function. 4824 // 4825 // If the event needs to propagate beyond the hijacker (e.g., the process 4826 // exits during execution), then the event is put into 4827 // event_to_broadcast_sp for rebroadcasting. 4828 4829 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp); 4830 4831 if (log) { 4832 StreamString s; 4833 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose); 4834 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 4835 " to run thread plan \"%s\".", 4836 thread->GetIndexID(), thread->GetID(), s.GetData()); 4837 } 4838 4839 bool got_event; 4840 lldb::EventSP event_sp; 4841 lldb::StateType stop_state = lldb::eStateInvalid; 4842 4843 bool before_first_timeout = true; // This is set to false the first time 4844 // that we have to halt the target. 4845 bool do_resume = true; 4846 bool handle_running_event = true; 4847 4848 // This is just for accounting: 4849 uint32_t num_resumes = 0; 4850 4851 // If we are going to run all threads the whole time, or if we are only 4852 // going to run one thread, then we don't need the first timeout. So we 4853 // pretend we are after the first timeout already. 4854 if (!options.GetStopOthers() || !options.GetTryAllThreads()) 4855 before_first_timeout = false; 4856 4857 if (log) 4858 log->Printf("Stop others: %u, try all: %u, before_first: %u.\n", 4859 options.GetStopOthers(), options.GetTryAllThreads(), 4860 before_first_timeout); 4861 4862 // This isn't going to work if there are unfetched events on the queue. Are 4863 // there cases where we might want to run the remaining events here, and 4864 // then try to call the function? That's probably being too tricky for our 4865 // own good. 4866 4867 Event *other_events = listener_sp->PeekAtNextEvent(); 4868 if (other_events != nullptr) { 4869 diagnostic_manager.PutString( 4870 eDiagnosticSeverityError, 4871 "RunThreadPlan called with pending events on the queue."); 4872 return eExpressionSetupError; 4873 } 4874 4875 // We also need to make sure that the next event is delivered. We might be 4876 // calling a function as part of a thread plan, in which case the last 4877 // delivered event could be the running event, and we don't want event 4878 // coalescing to cause us to lose OUR running event... 4879 ForceNextEventDelivery(); 4880 4881 // This while loop must exit out the bottom, there's cleanup that we need to do 4882 // when we are done. So don't call return anywhere within it. 4883 4884 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT 4885 // It's pretty much impossible to write test cases for things like: One 4886 // thread timeout expires, I go to halt, but the process already stopped on 4887 // the function call stop breakpoint. Turning on this define will make us 4888 // not fetch the first event till after the halt. So if you run a quick 4889 // function, it will have completed, and the completion event will be 4890 // waiting, when you interrupt for halt. The expression evaluation should 4891 // still succeed. 4892 bool miss_first_event = true; 4893 #endif 4894 while (true) { 4895 // We usually want to resume the process if we get to the top of the 4896 // loop. The only exception is if we get two running events with no 4897 // intervening stop, which can happen, we will just wait for then next 4898 // stop event. 4899 if (log) 4900 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i " 4901 "before_first_timeout: %i.", 4902 do_resume, handle_running_event, before_first_timeout); 4903 4904 if (do_resume || handle_running_event) { 4905 // Do the initial resume and wait for the running event before going 4906 // further. 4907 4908 if (do_resume) { 4909 num_resumes++; 4910 Status resume_error = PrivateResume(); 4911 if (!resume_error.Success()) { 4912 diagnostic_manager.Printf( 4913 eDiagnosticSeverityError, 4914 "couldn't resume inferior the %d time: \"%s\".", num_resumes, 4915 resume_error.AsCString()); 4916 return_value = eExpressionSetupError; 4917 break; 4918 } 4919 } 4920 4921 got_event = 4922 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout()); 4923 if (!got_event) { 4924 if (log) 4925 log->Printf("Process::RunThreadPlan(): didn't get any event after " 4926 "resume %" PRIu32 ", exiting.", 4927 num_resumes); 4928 4929 diagnostic_manager.Printf(eDiagnosticSeverityError, 4930 "didn't get any event after resume %" PRIu32 4931 ", exiting.", 4932 num_resumes); 4933 return_value = eExpressionSetupError; 4934 break; 4935 } 4936 4937 stop_state = 4938 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 4939 4940 if (stop_state != eStateRunning) { 4941 bool restarted = false; 4942 4943 if (stop_state == eStateStopped) { 4944 restarted = Process::ProcessEventData::GetRestartedFromEvent( 4945 event_sp.get()); 4946 if (log) 4947 log->Printf( 4948 "Process::RunThreadPlan(): didn't get running event after " 4949 "resume %d, got %s instead (restarted: %i, do_resume: %i, " 4950 "handle_running_event: %i).", 4951 num_resumes, StateAsCString(stop_state), restarted, do_resume, 4952 handle_running_event); 4953 } 4954 4955 if (restarted) { 4956 // This is probably an overabundance of caution, I don't think I 4957 // should ever get a stopped & restarted event here. But if I do, 4958 // the best thing is to Halt and then get out of here. 4959 const bool clear_thread_plans = false; 4960 const bool use_run_lock = false; 4961 Halt(clear_thread_plans, use_run_lock); 4962 } 4963 4964 diagnostic_manager.Printf( 4965 eDiagnosticSeverityError, 4966 "didn't get running event after initial resume, got %s instead.", 4967 StateAsCString(stop_state)); 4968 return_value = eExpressionSetupError; 4969 break; 4970 } 4971 4972 if (log) 4973 log->PutCString("Process::RunThreadPlan(): resuming succeeded."); 4974 // We need to call the function synchronously, so spin waiting for it 4975 // to return. If we get interrupted while executing, we're going to 4976 // lose our context, and won't be able to gather the result at this 4977 // point. We set the timeout AFTER the resume, since the resume takes 4978 // some time and we don't want to charge that to the timeout. 4979 } else { 4980 if (log) 4981 log->PutCString("Process::RunThreadPlan(): waiting for next event."); 4982 } 4983 4984 do_resume = true; 4985 handle_running_event = true; 4986 4987 // Now wait for the process to stop again: 4988 event_sp.reset(); 4989 4990 Timeout<std::micro> timeout = 4991 GetExpressionTimeout(options, before_first_timeout); 4992 if (log) { 4993 if (timeout) { 4994 auto now = system_clock::now(); 4995 log->Printf("Process::RunThreadPlan(): about to wait - now is %s - " 4996 "endpoint is %s", 4997 llvm::to_string(now).c_str(), 4998 llvm::to_string(now + *timeout).c_str()); 4999 } else { 5000 log->Printf("Process::RunThreadPlan(): about to wait forever."); 5001 } 5002 } 5003 5004 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT 5005 // See comment above... 5006 if (miss_first_event) { 5007 usleep(1000); 5008 miss_first_event = false; 5009 got_event = false; 5010 } else 5011 #endif 5012 got_event = listener_sp->GetEvent(event_sp, timeout); 5013 5014 if (got_event) { 5015 if (event_sp) { 5016 bool keep_going = false; 5017 if (event_sp->GetType() == eBroadcastBitInterrupt) { 5018 const bool clear_thread_plans = false; 5019 const bool use_run_lock = false; 5020 Halt(clear_thread_plans, use_run_lock); 5021 return_value = eExpressionInterrupted; 5022 diagnostic_manager.PutString(eDiagnosticSeverityRemark, 5023 "execution halted by user interrupt."); 5024 if (log) 5025 log->Printf("Process::RunThreadPlan(): Got interrupted by " 5026 "eBroadcastBitInterrupted, exiting."); 5027 break; 5028 } else { 5029 stop_state = 5030 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 5031 if (log) 5032 log->Printf( 5033 "Process::RunThreadPlan(): in while loop, got event: %s.", 5034 StateAsCString(stop_state)); 5035 5036 switch (stop_state) { 5037 case lldb::eStateStopped: { 5038 // We stopped, figure out what we are going to do now. 5039 ThreadSP thread_sp = 5040 GetThreadList().FindThreadByIndexID(thread_idx_id); 5041 if (!thread_sp) { 5042 // Ooh, our thread has vanished. Unlikely that this was 5043 // successful execution... 5044 if (log) 5045 log->Printf("Process::RunThreadPlan(): execution completed " 5046 "but our thread (index-id=%u) has vanished.", 5047 thread_idx_id); 5048 return_value = eExpressionInterrupted; 5049 } else if (Process::ProcessEventData::GetRestartedFromEvent( 5050 event_sp.get())) { 5051 // If we were restarted, we just need to go back up to fetch 5052 // another event. 5053 if (log) { 5054 log->Printf("Process::RunThreadPlan(): Got a stop and " 5055 "restart, so we'll continue waiting."); 5056 } 5057 keep_going = true; 5058 do_resume = false; 5059 handle_running_event = true; 5060 } else { 5061 const bool handle_interrupts = true; 5062 return_value = *HandleStoppedEvent( 5063 *thread, thread_plan_sp, thread_plan_restorer, event_sp, 5064 event_to_broadcast_sp, options, handle_interrupts); 5065 } 5066 } break; 5067 5068 case lldb::eStateRunning: 5069 // This shouldn't really happen, but sometimes we do get two 5070 // running events without an intervening stop, and in that case 5071 // we should just go back to waiting for the stop. 5072 do_resume = false; 5073 keep_going = true; 5074 handle_running_event = false; 5075 break; 5076 5077 default: 5078 if (log) 5079 log->Printf("Process::RunThreadPlan(): execution stopped with " 5080 "unexpected state: %s.", 5081 StateAsCString(stop_state)); 5082 5083 if (stop_state == eStateExited) 5084 event_to_broadcast_sp = event_sp; 5085 5086 diagnostic_manager.PutString( 5087 eDiagnosticSeverityError, 5088 "execution stopped with unexpected state."); 5089 return_value = eExpressionInterrupted; 5090 break; 5091 } 5092 } 5093 5094 if (keep_going) 5095 continue; 5096 else 5097 break; 5098 } else { 5099 if (log) 5100 log->PutCString("Process::RunThreadPlan(): got_event was true, but " 5101 "the event pointer was null. How odd..."); 5102 return_value = eExpressionInterrupted; 5103 break; 5104 } 5105 } else { 5106 // If we didn't get an event that means we've timed out... We will 5107 // interrupt the process here. Depending on what we were asked to do 5108 // we will either exit, or try with all threads running for the same 5109 // timeout. 5110 5111 if (log) { 5112 if (options.GetTryAllThreads()) { 5113 if (before_first_timeout) { 5114 LLDB_LOG(log, 5115 "Running function with one thread timeout timed out."); 5116 } else 5117 LLDB_LOG(log, "Restarting function with all threads enabled and " 5118 "timeout: {0} timed out, abandoning execution.", 5119 timeout); 5120 } else 5121 LLDB_LOG(log, "Running function with timeout: {0} timed out, " 5122 "abandoning execution.", 5123 timeout); 5124 } 5125 5126 // It is possible that between the time we issued the Halt, and we get 5127 // around to calling Halt the target could have stopped. That's fine, 5128 // Halt will figure that out and send the appropriate Stopped event. 5129 // BUT it is also possible that we stopped & restarted (e.g. hit a 5130 // signal with "stop" set to false.) In 5131 // that case, we'll get the stopped & restarted event, and we should go 5132 // back to waiting for the Halt's stopped event. That's what this 5133 // while loop does. 5134 5135 bool back_to_top = true; 5136 uint32_t try_halt_again = 0; 5137 bool do_halt = true; 5138 const uint32_t num_retries = 5; 5139 while (try_halt_again < num_retries) { 5140 Status halt_error; 5141 if (do_halt) { 5142 if (log) 5143 log->Printf("Process::RunThreadPlan(): Running Halt."); 5144 const bool clear_thread_plans = false; 5145 const bool use_run_lock = false; 5146 Halt(clear_thread_plans, use_run_lock); 5147 } 5148 if (halt_error.Success()) { 5149 if (log) 5150 log->PutCString("Process::RunThreadPlan(): Halt succeeded."); 5151 5152 got_event = 5153 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout()); 5154 5155 if (got_event) { 5156 stop_state = 5157 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 5158 if (log) { 5159 log->Printf("Process::RunThreadPlan(): Stopped with event: %s", 5160 StateAsCString(stop_state)); 5161 if (stop_state == lldb::eStateStopped && 5162 Process::ProcessEventData::GetInterruptedFromEvent( 5163 event_sp.get())) 5164 log->PutCString(" Event was the Halt interruption event."); 5165 } 5166 5167 if (stop_state == lldb::eStateStopped) { 5168 if (Process::ProcessEventData::GetRestartedFromEvent( 5169 event_sp.get())) { 5170 if (log) 5171 log->PutCString("Process::RunThreadPlan(): Went to halt " 5172 "but got a restarted event, there must be " 5173 "an un-restarted stopped event so try " 5174 "again... " 5175 "Exiting wait loop."); 5176 try_halt_again++; 5177 do_halt = false; 5178 continue; 5179 } 5180 5181 // Between the time we initiated the Halt and the time we 5182 // delivered it, the process could have already finished its 5183 // job. Check that here: 5184 const bool handle_interrupts = false; 5185 if (auto result = HandleStoppedEvent( 5186 *thread, thread_plan_sp, thread_plan_restorer, event_sp, 5187 event_to_broadcast_sp, options, handle_interrupts)) { 5188 return_value = *result; 5189 back_to_top = false; 5190 break; 5191 } 5192 5193 if (!options.GetTryAllThreads()) { 5194 if (log) 5195 log->PutCString("Process::RunThreadPlan(): try_all_threads " 5196 "was false, we stopped so now we're " 5197 "quitting."); 5198 return_value = eExpressionInterrupted; 5199 back_to_top = false; 5200 break; 5201 } 5202 5203 if (before_first_timeout) { 5204 // Set all the other threads to run, and return to the top of 5205 // the loop, which will continue; 5206 before_first_timeout = false; 5207 thread_plan_sp->SetStopOthers(false); 5208 if (log) 5209 log->PutCString( 5210 "Process::RunThreadPlan(): about to resume."); 5211 5212 back_to_top = true; 5213 break; 5214 } else { 5215 // Running all threads failed, so return Interrupted. 5216 if (log) 5217 log->PutCString("Process::RunThreadPlan(): running all " 5218 "threads timed out."); 5219 return_value = eExpressionInterrupted; 5220 back_to_top = false; 5221 break; 5222 } 5223 } 5224 } else { 5225 if (log) 5226 log->PutCString("Process::RunThreadPlan(): halt said it " 5227 "succeeded, but I got no event. " 5228 "I'm getting out of here passing Interrupted."); 5229 return_value = eExpressionInterrupted; 5230 back_to_top = false; 5231 break; 5232 } 5233 } else { 5234 try_halt_again++; 5235 continue; 5236 } 5237 } 5238 5239 if (!back_to_top || try_halt_again > num_retries) 5240 break; 5241 else 5242 continue; 5243 } 5244 } // END WAIT LOOP 5245 5246 // If we had to start up a temporary private state thread to run this 5247 // thread plan, shut it down now. 5248 if (backup_private_state_thread.IsJoinable()) { 5249 StopPrivateStateThread(); 5250 Status error; 5251 m_private_state_thread = backup_private_state_thread; 5252 if (stopper_base_plan_sp) { 5253 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp); 5254 } 5255 if (old_state != eStateInvalid) 5256 m_public_state.SetValueNoLock(old_state); 5257 } 5258 5259 if (return_value != eExpressionCompleted && log) { 5260 // Print a backtrace into the log so we can figure out where we are: 5261 StreamString s; 5262 s.PutCString("Thread state after unsuccessful completion: \n"); 5263 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX); 5264 log->PutString(s.GetString()); 5265 } 5266 // Restore the thread state if we are going to discard the plan execution. 5267 // There are three cases where this could happen: 1) The execution 5268 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints 5269 // was true 3) We got some other error, and discard_on_error was true 5270 bool should_unwind = (return_value == eExpressionInterrupted && 5271 options.DoesUnwindOnError()) || 5272 (return_value == eExpressionHitBreakpoint && 5273 options.DoesIgnoreBreakpoints()); 5274 5275 if (return_value == eExpressionCompleted || should_unwind) { 5276 thread_plan_sp->RestoreThreadState(); 5277 } 5278 5279 // Now do some processing on the results of the run: 5280 if (return_value == eExpressionInterrupted || 5281 return_value == eExpressionHitBreakpoint) { 5282 if (log) { 5283 StreamString s; 5284 if (event_sp) 5285 event_sp->Dump(&s); 5286 else { 5287 log->PutCString("Process::RunThreadPlan(): Stop event that " 5288 "interrupted us is NULL."); 5289 } 5290 5291 StreamString ts; 5292 5293 const char *event_explanation = nullptr; 5294 5295 do { 5296 if (!event_sp) { 5297 event_explanation = "<no event>"; 5298 break; 5299 } else if (event_sp->GetType() == eBroadcastBitInterrupt) { 5300 event_explanation = "<user interrupt>"; 5301 break; 5302 } else { 5303 const Process::ProcessEventData *event_data = 5304 Process::ProcessEventData::GetEventDataFromEvent( 5305 event_sp.get()); 5306 5307 if (!event_data) { 5308 event_explanation = "<no event data>"; 5309 break; 5310 } 5311 5312 Process *process = event_data->GetProcessSP().get(); 5313 5314 if (!process) { 5315 event_explanation = "<no process>"; 5316 break; 5317 } 5318 5319 ThreadList &thread_list = process->GetThreadList(); 5320 5321 uint32_t num_threads = thread_list.GetSize(); 5322 uint32_t thread_index; 5323 5324 ts.Printf("<%u threads> ", num_threads); 5325 5326 for (thread_index = 0; thread_index < num_threads; ++thread_index) { 5327 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get(); 5328 5329 if (!thread) { 5330 ts.Printf("<?> "); 5331 continue; 5332 } 5333 5334 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID()); 5335 RegisterContext *register_context = 5336 thread->GetRegisterContext().get(); 5337 5338 if (register_context) 5339 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC()); 5340 else 5341 ts.Printf("[ip unknown] "); 5342 5343 // Show the private stop info here, the public stop info will be 5344 // from the last natural stop. 5345 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo(); 5346 if (stop_info_sp) { 5347 const char *stop_desc = stop_info_sp->GetDescription(); 5348 if (stop_desc) 5349 ts.PutCString(stop_desc); 5350 } 5351 ts.Printf(">"); 5352 } 5353 5354 event_explanation = ts.GetData(); 5355 } 5356 } while (false); 5357 5358 if (event_explanation) 5359 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", 5360 s.GetData(), event_explanation); 5361 else 5362 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", 5363 s.GetData()); 5364 } 5365 5366 if (should_unwind) { 5367 if (log) 5368 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - " 5369 "discarding thread plans up to %p.", 5370 static_cast<void *>(thread_plan_sp.get())); 5371 thread->DiscardThreadPlansUpToPlan(thread_plan_sp); 5372 } else { 5373 if (log) 5374 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for " 5375 "plan: %p not discarding.", 5376 static_cast<void *>(thread_plan_sp.get())); 5377 } 5378 } else if (return_value == eExpressionSetupError) { 5379 if (log) 5380 log->PutCString("Process::RunThreadPlan(): execution set up error."); 5381 5382 if (options.DoesUnwindOnError()) { 5383 thread->DiscardThreadPlansUpToPlan(thread_plan_sp); 5384 } 5385 } else { 5386 if (thread->IsThreadPlanDone(thread_plan_sp.get())) { 5387 if (log) 5388 log->PutCString("Process::RunThreadPlan(): thread plan is done"); 5389 return_value = eExpressionCompleted; 5390 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) { 5391 if (log) 5392 log->PutCString( 5393 "Process::RunThreadPlan(): thread plan was discarded"); 5394 return_value = eExpressionDiscarded; 5395 } else { 5396 if (log) 5397 log->PutCString( 5398 "Process::RunThreadPlan(): thread plan stopped in mid course"); 5399 if (options.DoesUnwindOnError() && thread_plan_sp) { 5400 if (log) 5401 log->PutCString("Process::RunThreadPlan(): discarding thread plan " 5402 "'cause unwind_on_error is set."); 5403 thread->DiscardThreadPlansUpToPlan(thread_plan_sp); 5404 } 5405 } 5406 } 5407 5408 // Thread we ran the function in may have gone away because we ran the 5409 // target Check that it's still there, and if it is put it back in the 5410 // context. Also restore the frame in the context if it is still present. 5411 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get(); 5412 if (thread) { 5413 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id)); 5414 } 5415 5416 // Also restore the current process'es selected frame & thread, since this 5417 // function calling may be done behind the user's back. 5418 5419 if (selected_tid != LLDB_INVALID_THREAD_ID) { 5420 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) && 5421 selected_stack_id.IsValid()) { 5422 // We were able to restore the selected thread, now restore the frame: 5423 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex()); 5424 StackFrameSP old_frame_sp = 5425 GetThreadList().GetSelectedThread()->GetFrameWithStackID( 5426 selected_stack_id); 5427 if (old_frame_sp) 5428 GetThreadList().GetSelectedThread()->SetSelectedFrame( 5429 old_frame_sp.get()); 5430 } 5431 } 5432 } 5433 5434 // If the process exited during the run of the thread plan, notify everyone. 5435 5436 if (event_to_broadcast_sp) { 5437 if (log) 5438 log->PutCString("Process::RunThreadPlan(): rebroadcasting event."); 5439 BroadcastEvent(event_to_broadcast_sp); 5440 } 5441 5442 return return_value; 5443 } 5444 5445 const char *Process::ExecutionResultAsCString(ExpressionResults result) { 5446 const char *result_name; 5447 5448 switch (result) { 5449 case eExpressionCompleted: 5450 result_name = "eExpressionCompleted"; 5451 break; 5452 case eExpressionDiscarded: 5453 result_name = "eExpressionDiscarded"; 5454 break; 5455 case eExpressionInterrupted: 5456 result_name = "eExpressionInterrupted"; 5457 break; 5458 case eExpressionHitBreakpoint: 5459 result_name = "eExpressionHitBreakpoint"; 5460 break; 5461 case eExpressionSetupError: 5462 result_name = "eExpressionSetupError"; 5463 break; 5464 case eExpressionParseError: 5465 result_name = "eExpressionParseError"; 5466 break; 5467 case eExpressionResultUnavailable: 5468 result_name = "eExpressionResultUnavailable"; 5469 break; 5470 case eExpressionTimedOut: 5471 result_name = "eExpressionTimedOut"; 5472 break; 5473 case eExpressionStoppedForDebug: 5474 result_name = "eExpressionStoppedForDebug"; 5475 break; 5476 } 5477 return result_name; 5478 } 5479 5480 void Process::GetStatus(Stream &strm) { 5481 const StateType state = GetState(); 5482 if (StateIsStoppedState(state, false)) { 5483 if (state == eStateExited) { 5484 int exit_status = GetExitStatus(); 5485 const char *exit_description = GetExitDescription(); 5486 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n", 5487 GetID(), exit_status, exit_status, 5488 exit_description ? exit_description : ""); 5489 } else { 5490 if (state == eStateConnected) 5491 strm.Printf("Connected to remote target.\n"); 5492 else 5493 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state)); 5494 } 5495 } else { 5496 strm.Printf("Process %" PRIu64 " is running.\n", GetID()); 5497 } 5498 } 5499 5500 size_t Process::GetThreadStatus(Stream &strm, 5501 bool only_threads_with_stop_reason, 5502 uint32_t start_frame, uint32_t num_frames, 5503 uint32_t num_frames_with_source, 5504 bool stop_format) { 5505 size_t num_thread_infos_dumped = 0; 5506 5507 // You can't hold the thread list lock while calling Thread::GetStatus. That 5508 // very well might run code (e.g. if we need it to get return values or 5509 // arguments.) For that to work the process has to be able to acquire it. 5510 // So instead copy the thread ID's, and look them up one by one: 5511 5512 uint32_t num_threads; 5513 std::vector<lldb::tid_t> thread_id_array; 5514 // Scope for thread list locker; 5515 { 5516 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex()); 5517 ThreadList &curr_thread_list = GetThreadList(); 5518 num_threads = curr_thread_list.GetSize(); 5519 uint32_t idx; 5520 thread_id_array.resize(num_threads); 5521 for (idx = 0; idx < num_threads; ++idx) 5522 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID(); 5523 } 5524 5525 for (uint32_t i = 0; i < num_threads; i++) { 5526 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i])); 5527 if (thread_sp) { 5528 if (only_threads_with_stop_reason) { 5529 StopInfoSP stop_info_sp = thread_sp->GetStopInfo(); 5530 if (!stop_info_sp || !stop_info_sp->IsValid()) 5531 continue; 5532 } 5533 thread_sp->GetStatus(strm, start_frame, num_frames, 5534 num_frames_with_source, 5535 stop_format); 5536 ++num_thread_infos_dumped; 5537 } else { 5538 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 5539 if (log) 5540 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 5541 " vanished while running Thread::GetStatus."); 5542 } 5543 } 5544 return num_thread_infos_dumped; 5545 } 5546 5547 void Process::AddInvalidMemoryRegion(const LoadRange ®ion) { 5548 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize()); 5549 } 5550 5551 bool Process::RemoveInvalidMemoryRange(const LoadRange ®ion) { 5552 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), 5553 region.GetByteSize()); 5554 } 5555 5556 void Process::AddPreResumeAction(PreResumeActionCallback callback, 5557 void *baton) { 5558 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton)); 5559 } 5560 5561 bool Process::RunPreResumeActions() { 5562 bool result = true; 5563 while (!m_pre_resume_actions.empty()) { 5564 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back(); 5565 m_pre_resume_actions.pop_back(); 5566 bool this_result = action.callback(action.baton); 5567 if (result) 5568 result = this_result; 5569 } 5570 return result; 5571 } 5572 5573 void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); } 5574 5575 void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton) 5576 { 5577 PreResumeCallbackAndBaton element(callback, baton); 5578 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element); 5579 if (found_iter != m_pre_resume_actions.end()) 5580 { 5581 m_pre_resume_actions.erase(found_iter); 5582 } 5583 } 5584 5585 ProcessRunLock &Process::GetRunLock() { 5586 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) 5587 return m_private_run_lock; 5588 else 5589 return m_public_run_lock; 5590 } 5591 5592 void Process::Flush() { 5593 m_thread_list.Flush(); 5594 m_extended_thread_list.Flush(); 5595 m_extended_thread_stop_id = 0; 5596 m_queue_list.Clear(); 5597 m_queue_list_stop_id = 0; 5598 } 5599 5600 void Process::DidExec() { 5601 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 5602 if (log) 5603 log->Printf("Process::%s()", __FUNCTION__); 5604 5605 Target &target = GetTarget(); 5606 target.CleanupProcess(); 5607 target.ClearModules(false); 5608 m_dynamic_checkers_up.reset(); 5609 m_abi_sp.reset(); 5610 m_system_runtime_up.reset(); 5611 m_os_up.reset(); 5612 m_dyld_up.reset(); 5613 m_jit_loaders_up.reset(); 5614 m_image_tokens.clear(); 5615 m_allocated_memory_cache.Clear(); 5616 { 5617 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex); 5618 m_language_runtimes.clear(); 5619 } 5620 m_instrumentation_runtimes.clear(); 5621 m_thread_list.DiscardThreadPlans(); 5622 m_memory_cache.Clear(true); 5623 DoDidExec(); 5624 CompleteAttach(); 5625 // Flush the process (threads and all stack frames) after running 5626 // CompleteAttach() in case the dynamic loader loaded things in new 5627 // locations. 5628 Flush(); 5629 5630 // After we figure out what was loaded/unloaded in CompleteAttach, we need to 5631 // let the target know so it can do any cleanup it needs to. 5632 target.DidExec(); 5633 } 5634 5635 addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) { 5636 if (address == nullptr) { 5637 error.SetErrorString("Invalid address argument"); 5638 return LLDB_INVALID_ADDRESS; 5639 } 5640 5641 addr_t function_addr = LLDB_INVALID_ADDRESS; 5642 5643 addr_t addr = address->GetLoadAddress(&GetTarget()); 5644 std::map<addr_t, addr_t>::const_iterator iter = 5645 m_resolved_indirect_addresses.find(addr); 5646 if (iter != m_resolved_indirect_addresses.end()) { 5647 function_addr = (*iter).second; 5648 } else { 5649 if (!InferiorCall(this, address, function_addr)) { 5650 Symbol *symbol = address->CalculateSymbolContextSymbol(); 5651 error.SetErrorStringWithFormat( 5652 "Unable to call resolver for indirect function %s", 5653 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>"); 5654 function_addr = LLDB_INVALID_ADDRESS; 5655 } else { 5656 m_resolved_indirect_addresses.insert( 5657 std::pair<addr_t, addr_t>(addr, function_addr)); 5658 } 5659 } 5660 return function_addr; 5661 } 5662 5663 void Process::ModulesDidLoad(ModuleList &module_list) { 5664 SystemRuntime *sys_runtime = GetSystemRuntime(); 5665 if (sys_runtime) { 5666 sys_runtime->ModulesDidLoad(module_list); 5667 } 5668 5669 GetJITLoaders().ModulesDidLoad(module_list); 5670 5671 // Give runtimes a chance to be created. 5672 InstrumentationRuntime::ModulesDidLoad(module_list, this, 5673 m_instrumentation_runtimes); 5674 5675 // Tell runtimes about new modules. 5676 for (auto pos = m_instrumentation_runtimes.begin(); 5677 pos != m_instrumentation_runtimes.end(); ++pos) { 5678 InstrumentationRuntimeSP runtime = pos->second; 5679 runtime->ModulesDidLoad(module_list); 5680 } 5681 5682 // Let any language runtimes we have already created know about the modules 5683 // that loaded. 5684 5685 // Iterate over a copy of this language runtime list in case the language 5686 // runtime ModulesDidLoad somehow causes the language runtime to be 5687 // unloaded. 5688 { 5689 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex); 5690 LanguageRuntimeCollection language_runtimes(m_language_runtimes); 5691 for (const auto &pair : language_runtimes) { 5692 // We must check language_runtime_sp to make sure it is not nullptr as we 5693 // might cache the fact that we didn't have a language runtime for a 5694 // language. 5695 LanguageRuntimeSP language_runtime_sp = pair.second; 5696 if (language_runtime_sp) 5697 language_runtime_sp->ModulesDidLoad(module_list); 5698 } 5699 } 5700 5701 // If we don't have an operating system plug-in, try to load one since 5702 // loading shared libraries might cause a new one to try and load 5703 if (!m_os_up) 5704 LoadOperatingSystemPlugin(false); 5705 5706 // Give structured-data plugins a chance to see the modified modules. 5707 for (auto pair : m_structured_data_plugin_map) { 5708 if (pair.second) 5709 pair.second->ModulesDidLoad(*this, module_list); 5710 } 5711 } 5712 5713 void Process::PrintWarning(uint64_t warning_type, const void *repeat_key, 5714 const char *fmt, ...) { 5715 bool print_warning = true; 5716 5717 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream(); 5718 if (!stream_sp) 5719 return; 5720 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) { 5721 return; 5722 } 5723 5724 if (repeat_key != nullptr) { 5725 WarningsCollection::iterator it = m_warnings_issued.find(warning_type); 5726 if (it == m_warnings_issued.end()) { 5727 m_warnings_issued[warning_type] = WarningsPointerSet(); 5728 m_warnings_issued[warning_type].insert(repeat_key); 5729 } else { 5730 if (it->second.find(repeat_key) != it->second.end()) { 5731 print_warning = false; 5732 } else { 5733 it->second.insert(repeat_key); 5734 } 5735 } 5736 } 5737 5738 if (print_warning) { 5739 va_list args; 5740 va_start(args, fmt); 5741 stream_sp->PrintfVarArg(fmt, args); 5742 va_end(args); 5743 } 5744 } 5745 5746 void Process::PrintWarningOptimization(const SymbolContext &sc) { 5747 if (GetWarningsOptimization() && sc.module_sp && 5748 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function && 5749 sc.function->GetIsOptimized()) { 5750 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(), 5751 "%s was compiled with optimization - stepping may behave " 5752 "oddly; variables may not be available.\n", 5753 sc.module_sp->GetFileSpec().GetFilename().GetCString()); 5754 } 5755 } 5756 5757 bool Process::GetProcessInfo(ProcessInstanceInfo &info) { 5758 info.Clear(); 5759 5760 PlatformSP platform_sp = GetTarget().GetPlatform(); 5761 if (!platform_sp) 5762 return false; 5763 5764 return platform_sp->GetProcessInfo(GetID(), info); 5765 } 5766 5767 ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) { 5768 ThreadCollectionSP threads; 5769 5770 const MemoryHistorySP &memory_history = 5771 MemoryHistory::FindPlugin(shared_from_this()); 5772 5773 if (!memory_history) { 5774 return threads; 5775 } 5776 5777 threads = std::make_shared<ThreadCollection>( 5778 memory_history->GetHistoryThreads(addr)); 5779 5780 return threads; 5781 } 5782 5783 InstrumentationRuntimeSP 5784 Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) { 5785 InstrumentationRuntimeCollection::iterator pos; 5786 pos = m_instrumentation_runtimes.find(type); 5787 if (pos == m_instrumentation_runtimes.end()) { 5788 return InstrumentationRuntimeSP(); 5789 } else 5790 return (*pos).second; 5791 } 5792 5793 bool Process::GetModuleSpec(const FileSpec &module_file_spec, 5794 const ArchSpec &arch, ModuleSpec &module_spec) { 5795 module_spec.Clear(); 5796 return false; 5797 } 5798 5799 size_t Process::AddImageToken(lldb::addr_t image_ptr) { 5800 m_image_tokens.push_back(image_ptr); 5801 return m_image_tokens.size() - 1; 5802 } 5803 5804 lldb::addr_t Process::GetImagePtrFromToken(size_t token) const { 5805 if (token < m_image_tokens.size()) 5806 return m_image_tokens[token]; 5807 return LLDB_INVALID_IMAGE_TOKEN; 5808 } 5809 5810 void Process::ResetImageToken(size_t token) { 5811 if (token < m_image_tokens.size()) 5812 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN; 5813 } 5814 5815 Address 5816 Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr, 5817 AddressRange range_bounds) { 5818 Target &target = GetTarget(); 5819 DisassemblerSP disassembler_sp; 5820 InstructionList *insn_list = nullptr; 5821 5822 Address retval = default_stop_addr; 5823 5824 if (!target.GetUseFastStepping()) 5825 return retval; 5826 if (!default_stop_addr.IsValid()) 5827 return retval; 5828 5829 ExecutionContext exe_ctx(this); 5830 const char *plugin_name = nullptr; 5831 const char *flavor = nullptr; 5832 const bool prefer_file_cache = true; 5833 disassembler_sp = Disassembler::DisassembleRange( 5834 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds, 5835 prefer_file_cache); 5836 if (disassembler_sp) 5837 insn_list = &disassembler_sp->GetInstructionList(); 5838 5839 if (insn_list == nullptr) { 5840 return retval; 5841 } 5842 5843 size_t insn_offset = 5844 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr); 5845 if (insn_offset == UINT32_MAX) { 5846 return retval; 5847 } 5848 5849 uint32_t branch_index = 5850 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target, 5851 false /* ignore_calls*/); 5852 if (branch_index == UINT32_MAX) { 5853 return retval; 5854 } 5855 5856 if (branch_index > insn_offset) { 5857 Address next_branch_insn_address = 5858 insn_list->GetInstructionAtIndex(branch_index)->GetAddress(); 5859 if (next_branch_insn_address.IsValid() && 5860 range_bounds.ContainsFileAddress(next_branch_insn_address)) { 5861 retval = next_branch_insn_address; 5862 } 5863 } 5864 5865 return retval; 5866 } 5867 5868 Status 5869 Process::GetMemoryRegions(lldb_private::MemoryRegionInfos ®ion_list) { 5870 5871 Status error; 5872 5873 lldb::addr_t range_end = 0; 5874 5875 region_list.clear(); 5876 do { 5877 lldb_private::MemoryRegionInfo region_info; 5878 error = GetMemoryRegionInfo(range_end, region_info); 5879 // GetMemoryRegionInfo should only return an error if it is unimplemented. 5880 if (error.Fail()) { 5881 region_list.clear(); 5882 break; 5883 } 5884 5885 range_end = region_info.GetRange().GetRangeEnd(); 5886 if (region_info.GetMapped() == MemoryRegionInfo::eYes) { 5887 region_list.push_back(std::move(region_info)); 5888 } 5889 } while (range_end != LLDB_INVALID_ADDRESS); 5890 5891 return error; 5892 } 5893 5894 Status 5895 Process::ConfigureStructuredData(ConstString type_name, 5896 const StructuredData::ObjectSP &config_sp) { 5897 // If you get this, the Process-derived class needs to implement a method to 5898 // enable an already-reported asynchronous structured data feature. See 5899 // ProcessGDBRemote for an example implementation over gdb-remote. 5900 return Status("unimplemented"); 5901 } 5902 5903 void Process::MapSupportedStructuredDataPlugins( 5904 const StructuredData::Array &supported_type_names) { 5905 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 5906 5907 // Bail out early if there are no type names to map. 5908 if (supported_type_names.GetSize() == 0) { 5909 if (log) 5910 log->Printf("Process::%s(): no structured data types supported", 5911 __FUNCTION__); 5912 return; 5913 } 5914 5915 // Convert StructuredData type names to ConstString instances. 5916 std::set<ConstString> const_type_names; 5917 5918 if (log) 5919 log->Printf("Process::%s(): the process supports the following async " 5920 "structured data types:", 5921 __FUNCTION__); 5922 5923 supported_type_names.ForEach( 5924 [&const_type_names, &log](StructuredData::Object *object) { 5925 if (!object) { 5926 // Invalid - shouldn't be null objects in the array. 5927 return false; 5928 } 5929 5930 auto type_name = object->GetAsString(); 5931 if (!type_name) { 5932 // Invalid format - all type names should be strings. 5933 return false; 5934 } 5935 5936 const_type_names.insert(ConstString(type_name->GetValue())); 5937 LLDB_LOG(log, "- {0}", type_name->GetValue()); 5938 return true; 5939 }); 5940 5941 // For each StructuredDataPlugin, if the plugin handles any of the types in 5942 // the supported_type_names, map that type name to that plugin. Stop when 5943 // we've consumed all the type names. 5944 // FIXME: should we return an error if there are type names nobody 5945 // supports? 5946 for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) { 5947 auto create_instance = 5948 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex( 5949 plugin_index); 5950 if (!create_instance) 5951 break; 5952 5953 // Create the plugin. 5954 StructuredDataPluginSP plugin_sp = (*create_instance)(*this); 5955 if (!plugin_sp) { 5956 // This plugin doesn't think it can work with the process. Move on to the 5957 // next. 5958 continue; 5959 } 5960 5961 // For any of the remaining type names, map any that this plugin supports. 5962 std::vector<ConstString> names_to_remove; 5963 for (auto &type_name : const_type_names) { 5964 if (plugin_sp->SupportsStructuredDataType(type_name)) { 5965 m_structured_data_plugin_map.insert( 5966 std::make_pair(type_name, plugin_sp)); 5967 names_to_remove.push_back(type_name); 5968 if (log) 5969 log->Printf("Process::%s(): using plugin %s for type name " 5970 "%s", 5971 __FUNCTION__, plugin_sp->GetPluginName().GetCString(), 5972 type_name.GetCString()); 5973 } 5974 } 5975 5976 // Remove the type names that were consumed by this plugin. 5977 for (auto &type_name : names_to_remove) 5978 const_type_names.erase(type_name); 5979 } 5980 } 5981 5982 bool Process::RouteAsyncStructuredData( 5983 const StructuredData::ObjectSP object_sp) { 5984 // Nothing to do if there's no data. 5985 if (!object_sp) 5986 return false; 5987 5988 // The contract is this must be a dictionary, so we can look up the routing 5989 // key via the top-level 'type' string value within the dictionary. 5990 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary(); 5991 if (!dictionary) 5992 return false; 5993 5994 // Grab the async structured type name (i.e. the feature/plugin name). 5995 ConstString type_name; 5996 if (!dictionary->GetValueForKeyAsString("type", type_name)) 5997 return false; 5998 5999 // Check if there's a plugin registered for this type name. 6000 auto find_it = m_structured_data_plugin_map.find(type_name); 6001 if (find_it == m_structured_data_plugin_map.end()) { 6002 // We don't have a mapping for this structured data type. 6003 return false; 6004 } 6005 6006 // Route the structured data to the plugin. 6007 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp); 6008 return true; 6009 } 6010 6011 Status Process::UpdateAutomaticSignalFiltering() { 6012 // Default implementation does nothign. 6013 // No automatic signal filtering to speak of. 6014 return Status(); 6015 } 6016 6017 UtilityFunction *Process::GetLoadImageUtilityFunction( 6018 Platform *platform, 6019 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) { 6020 if (platform != GetTarget().GetPlatform().get()) 6021 return nullptr; 6022 std::call_once(m_dlopen_utility_func_flag_once, 6023 [&] { m_dlopen_utility_func_up = factory(); }); 6024 return m_dlopen_utility_func_up.get(); 6025 } 6026