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