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