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