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 if (bp->GetType() != BreakpointSite::eSoftware) 2295 return; 2296 2297 addr_t intersect_addr; 2298 size_t intersect_size; 2299 size_t opcode_offset; 2300 const bool intersects = bp->IntersectsRange( 2301 addr, size, &intersect_addr, &intersect_size, &opcode_offset); 2302 UNUSED_IF_ASSERT_DISABLED(intersects); 2303 assert(intersects); 2304 assert(addr <= intersect_addr && intersect_addr < addr + size); 2305 assert(addr < intersect_addr + intersect_size && 2306 intersect_addr + intersect_size <= addr + size); 2307 assert(opcode_offset + intersect_size <= bp->GetByteSize()); 2308 2309 // Check for bytes before this breakpoint 2310 const addr_t curr_addr = addr + bytes_written; 2311 if (intersect_addr > curr_addr) { 2312 // There are some bytes before this breakpoint that we need to just 2313 // write to memory 2314 size_t curr_size = intersect_addr - curr_addr; 2315 size_t curr_bytes_written = 2316 WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error); 2317 bytes_written += curr_bytes_written; 2318 if (curr_bytes_written != curr_size) { 2319 // We weren't able to write all of the requested bytes, we are 2320 // done looping and will return the number of bytes that we have 2321 // written so far. 2322 if (error.Success()) 2323 error.SetErrorToGenericError(); 2324 } 2325 } 2326 // Now write any bytes that would cover up any software breakpoints 2327 // directly into the breakpoint opcode buffer 2328 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, 2329 intersect_size); 2330 bytes_written += intersect_size; 2331 }); 2332 2333 // Write any remaining bytes after the last breakpoint if we have any left 2334 if (bytes_written < size) 2335 bytes_written += 2336 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written, 2337 size - bytes_written, error); 2338 2339 return bytes_written; 2340 } 2341 2342 size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar, 2343 size_t byte_size, Status &error) { 2344 if (byte_size == UINT32_MAX) 2345 byte_size = scalar.GetByteSize(); 2346 if (byte_size > 0) { 2347 uint8_t buf[32]; 2348 const size_t mem_size = 2349 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error); 2350 if (mem_size > 0) 2351 return WriteMemory(addr, buf, mem_size, error); 2352 else 2353 error.SetErrorString("failed to get scalar as memory data"); 2354 } else { 2355 error.SetErrorString("invalid scalar value"); 2356 } 2357 return 0; 2358 } 2359 2360 size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size, 2361 bool is_signed, Scalar &scalar, 2362 Status &error) { 2363 uint64_t uval = 0; 2364 if (byte_size == 0) { 2365 error.SetErrorString("byte size is zero"); 2366 } else if (byte_size & (byte_size - 1)) { 2367 error.SetErrorStringWithFormat("byte size %u is not a power of 2", 2368 byte_size); 2369 } else if (byte_size <= sizeof(uval)) { 2370 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error); 2371 if (bytes_read == byte_size) { 2372 DataExtractor data(&uval, sizeof(uval), GetByteOrder(), 2373 GetAddressByteSize()); 2374 lldb::offset_t offset = 0; 2375 if (byte_size <= 4) 2376 scalar = data.GetMaxU32(&offset, byte_size); 2377 else 2378 scalar = data.GetMaxU64(&offset, byte_size); 2379 if (is_signed) 2380 scalar.SignExtend(byte_size * 8); 2381 return bytes_read; 2382 } 2383 } else { 2384 error.SetErrorStringWithFormat( 2385 "byte size of %u is too large for integer scalar type", byte_size); 2386 } 2387 return 0; 2388 } 2389 2390 Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) { 2391 Status error; 2392 for (const auto &Entry : entries) { 2393 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(), 2394 error); 2395 if (!error.Success()) 2396 break; 2397 } 2398 return error; 2399 } 2400 2401 #define USE_ALLOCATE_MEMORY_CACHE 1 2402 addr_t Process::AllocateMemory(size_t size, uint32_t permissions, 2403 Status &error) { 2404 if (GetPrivateState() != eStateStopped) { 2405 error.SetErrorToGenericError(); 2406 return LLDB_INVALID_ADDRESS; 2407 } 2408 2409 #if defined(USE_ALLOCATE_MEMORY_CACHE) 2410 return m_allocated_memory_cache.AllocateMemory(size, permissions, error); 2411 #else 2412 addr_t allocated_addr = DoAllocateMemory(size, permissions, error); 2413 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 2414 LLDB_LOGF(log, 2415 "Process::AllocateMemory(size=%" PRIu64 2416 ", permissions=%s) => 0x%16.16" PRIx64 2417 " (m_stop_id = %u m_memory_id = %u)", 2418 (uint64_t)size, GetPermissionsAsCString(permissions), 2419 (uint64_t)allocated_addr, m_mod_id.GetStopID(), 2420 m_mod_id.GetMemoryID()); 2421 return allocated_addr; 2422 #endif 2423 } 2424 2425 addr_t Process::CallocateMemory(size_t size, uint32_t permissions, 2426 Status &error) { 2427 addr_t return_addr = AllocateMemory(size, permissions, error); 2428 if (error.Success()) { 2429 std::string buffer(size, 0); 2430 WriteMemory(return_addr, buffer.c_str(), size, error); 2431 } 2432 return return_addr; 2433 } 2434 2435 bool Process::CanJIT() { 2436 if (m_can_jit == eCanJITDontKnow) { 2437 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 2438 Status err; 2439 2440 uint64_t allocated_memory = AllocateMemory( 2441 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable, 2442 err); 2443 2444 if (err.Success()) { 2445 m_can_jit = eCanJITYes; 2446 LLDB_LOGF(log, 2447 "Process::%s pid %" PRIu64 2448 " allocation test passed, CanJIT () is true", 2449 __FUNCTION__, GetID()); 2450 } else { 2451 m_can_jit = eCanJITNo; 2452 LLDB_LOGF(log, 2453 "Process::%s pid %" PRIu64 2454 " allocation test failed, CanJIT () is false: %s", 2455 __FUNCTION__, GetID(), err.AsCString()); 2456 } 2457 2458 DeallocateMemory(allocated_memory); 2459 } 2460 2461 return m_can_jit == eCanJITYes; 2462 } 2463 2464 void Process::SetCanJIT(bool can_jit) { 2465 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo); 2466 } 2467 2468 void Process::SetCanRunCode(bool can_run_code) { 2469 SetCanJIT(can_run_code); 2470 m_can_interpret_function_calls = can_run_code; 2471 } 2472 2473 Status Process::DeallocateMemory(addr_t ptr) { 2474 Status error; 2475 #if defined(USE_ALLOCATE_MEMORY_CACHE) 2476 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) { 2477 error.SetErrorStringWithFormat( 2478 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr); 2479 } 2480 #else 2481 error = DoDeallocateMemory(ptr); 2482 2483 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 2484 LLDB_LOGF(log, 2485 "Process::DeallocateMemory(addr=0x%16.16" PRIx64 2486 ") => err = %s (m_stop_id = %u, m_memory_id = %u)", 2487 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(), 2488 m_mod_id.GetMemoryID()); 2489 #endif 2490 return error; 2491 } 2492 2493 ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec, 2494 lldb::addr_t header_addr, 2495 size_t size_to_read) { 2496 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST); 2497 if (log) { 2498 LLDB_LOGF(log, 2499 "Process::ReadModuleFromMemory reading %s binary from memory", 2500 file_spec.GetPath().c_str()); 2501 } 2502 ModuleSP module_sp(new Module(file_spec, ArchSpec())); 2503 if (module_sp) { 2504 Status error; 2505 ObjectFile *objfile = module_sp->GetMemoryObjectFile( 2506 shared_from_this(), header_addr, error, size_to_read); 2507 if (objfile) 2508 return module_sp; 2509 } 2510 return ModuleSP(); 2511 } 2512 2513 bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr, 2514 uint32_t &permissions) { 2515 MemoryRegionInfo range_info; 2516 permissions = 0; 2517 Status error(GetMemoryRegionInfo(load_addr, range_info)); 2518 if (!error.Success()) 2519 return false; 2520 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow || 2521 range_info.GetWritable() == MemoryRegionInfo::eDontKnow || 2522 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) { 2523 return false; 2524 } 2525 2526 if (range_info.GetReadable() == MemoryRegionInfo::eYes) 2527 permissions |= lldb::ePermissionsReadable; 2528 2529 if (range_info.GetWritable() == MemoryRegionInfo::eYes) 2530 permissions |= lldb::ePermissionsWritable; 2531 2532 if (range_info.GetExecutable() == MemoryRegionInfo::eYes) 2533 permissions |= lldb::ePermissionsExecutable; 2534 2535 return true; 2536 } 2537 2538 Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) { 2539 Status error; 2540 error.SetErrorString("watchpoints are not supported"); 2541 return error; 2542 } 2543 2544 Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) { 2545 Status error; 2546 error.SetErrorString("watchpoints are not supported"); 2547 return error; 2548 } 2549 2550 StateType 2551 Process::WaitForProcessStopPrivate(EventSP &event_sp, 2552 const Timeout<std::micro> &timeout) { 2553 StateType state; 2554 2555 while (true) { 2556 event_sp.reset(); 2557 state = GetStateChangedEventsPrivate(event_sp, timeout); 2558 2559 if (StateIsStoppedState(state, false)) 2560 break; 2561 2562 // If state is invalid, then we timed out 2563 if (state == eStateInvalid) 2564 break; 2565 2566 if (event_sp) 2567 HandlePrivateEvent(event_sp); 2568 } 2569 return state; 2570 } 2571 2572 void Process::LoadOperatingSystemPlugin(bool flush) { 2573 if (flush) 2574 m_thread_list.Clear(); 2575 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr)); 2576 if (flush) 2577 Flush(); 2578 } 2579 2580 Status Process::Launch(ProcessLaunchInfo &launch_info) { 2581 Status error; 2582 m_abi_sp.reset(); 2583 m_dyld_up.reset(); 2584 m_jit_loaders_up.reset(); 2585 m_system_runtime_up.reset(); 2586 m_os_up.reset(); 2587 m_process_input_reader.reset(); 2588 2589 Module *exe_module = GetTarget().GetExecutableModulePointer(); 2590 if (!exe_module) { 2591 error.SetErrorString("executable module does not exist"); 2592 return error; 2593 } 2594 2595 char local_exec_file_path[PATH_MAX]; 2596 char platform_exec_file_path[PATH_MAX]; 2597 exe_module->GetFileSpec().GetPath(local_exec_file_path, 2598 sizeof(local_exec_file_path)); 2599 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, 2600 sizeof(platform_exec_file_path)); 2601 if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) { 2602 // Install anything that might need to be installed prior to launching. 2603 // For host systems, this will do nothing, but if we are connected to a 2604 // remote platform it will install any needed binaries 2605 error = GetTarget().Install(&launch_info); 2606 if (error.Fail()) 2607 return error; 2608 2609 if (PrivateStateThreadIsValid()) 2610 PausePrivateStateThread(); 2611 2612 error = WillLaunch(exe_module); 2613 if (error.Success()) { 2614 const bool restarted = false; 2615 SetPublicState(eStateLaunching, restarted); 2616 m_should_detach = false; 2617 2618 if (m_public_run_lock.TrySetRunning()) { 2619 // Now launch using these arguments. 2620 error = DoLaunch(exe_module, launch_info); 2621 } else { 2622 // This shouldn't happen 2623 error.SetErrorString("failed to acquire process run lock"); 2624 } 2625 2626 if (error.Fail()) { 2627 if (GetID() != LLDB_INVALID_PROCESS_ID) { 2628 SetID(LLDB_INVALID_PROCESS_ID); 2629 const char *error_string = error.AsCString(); 2630 if (error_string == nullptr) 2631 error_string = "launch failed"; 2632 SetExitStatus(-1, error_string); 2633 } 2634 } else { 2635 EventSP event_sp; 2636 2637 // Now wait for the process to launch and return control to us, and then 2638 // call DidLaunch: 2639 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10)); 2640 2641 if (state == eStateInvalid || !event_sp) { 2642 // We were able to launch the process, but we failed to catch the 2643 // initial stop. 2644 error.SetErrorString("failed to catch stop after launch"); 2645 SetExitStatus(0, "failed to catch stop after launch"); 2646 Destroy(false); 2647 } else if (state == eStateStopped || state == eStateCrashed) { 2648 DidLaunch(); 2649 2650 DynamicLoader *dyld = GetDynamicLoader(); 2651 if (dyld) 2652 dyld->DidLaunch(); 2653 2654 GetJITLoaders().DidLaunch(); 2655 2656 SystemRuntime *system_runtime = GetSystemRuntime(); 2657 if (system_runtime) 2658 system_runtime->DidLaunch(); 2659 2660 if (!m_os_up) 2661 LoadOperatingSystemPlugin(false); 2662 2663 // We successfully launched the process and stopped, now it the 2664 // right time to set up signal filters before resuming. 2665 UpdateAutomaticSignalFiltering(); 2666 2667 // Note, the stop event was consumed above, but not handled. This 2668 // was done to give DidLaunch a chance to run. The target is either 2669 // stopped or crashed. Directly set the state. This is done to 2670 // prevent a stop message with a bunch of spurious output on thread 2671 // status, as well as not pop a ProcessIOHandler. 2672 SetPublicState(state, false); 2673 2674 if (PrivateStateThreadIsValid()) 2675 ResumePrivateStateThread(); 2676 else 2677 StartPrivateStateThread(); 2678 2679 // Target was stopped at entry as was intended. Need to notify the 2680 // listeners about it. 2681 if (state == eStateStopped && 2682 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) 2683 HandlePrivateEvent(event_sp); 2684 } else if (state == eStateExited) { 2685 // We exited while trying to launch somehow. Don't call DidLaunch 2686 // as that's not likely to work, and return an invalid pid. 2687 HandlePrivateEvent(event_sp); 2688 } 2689 } 2690 } 2691 } else { 2692 error.SetErrorStringWithFormat("file doesn't exist: '%s'", 2693 local_exec_file_path); 2694 } 2695 2696 return error; 2697 } 2698 2699 Status Process::LoadCore() { 2700 Status error = DoLoadCore(); 2701 if (error.Success()) { 2702 ListenerSP listener_sp( 2703 Listener::MakeListener("lldb.process.load_core_listener")); 2704 HijackProcessEvents(listener_sp); 2705 2706 if (PrivateStateThreadIsValid()) 2707 ResumePrivateStateThread(); 2708 else 2709 StartPrivateStateThread(); 2710 2711 DynamicLoader *dyld = GetDynamicLoader(); 2712 if (dyld) 2713 dyld->DidAttach(); 2714 2715 GetJITLoaders().DidAttach(); 2716 2717 SystemRuntime *system_runtime = GetSystemRuntime(); 2718 if (system_runtime) 2719 system_runtime->DidAttach(); 2720 2721 if (!m_os_up) 2722 LoadOperatingSystemPlugin(false); 2723 2724 // We successfully loaded a core file, now pretend we stopped so we can 2725 // show all of the threads in the core file and explore the crashed state. 2726 SetPrivateState(eStateStopped); 2727 2728 // Wait for a stopped event since we just posted one above... 2729 lldb::EventSP event_sp; 2730 StateType state = 2731 WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp); 2732 2733 if (!StateIsStoppedState(state, false)) { 2734 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 2735 LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s", 2736 StateAsCString(state)); 2737 error.SetErrorString( 2738 "Did not get stopped event after loading the core file."); 2739 } 2740 RestoreProcessEvents(); 2741 } 2742 return error; 2743 } 2744 2745 DynamicLoader *Process::GetDynamicLoader() { 2746 if (!m_dyld_up) 2747 m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr)); 2748 return m_dyld_up.get(); 2749 } 2750 2751 DataExtractor Process::GetAuxvData() { return DataExtractor(); } 2752 2753 JITLoaderList &Process::GetJITLoaders() { 2754 if (!m_jit_loaders_up) { 2755 m_jit_loaders_up = std::make_unique<JITLoaderList>(); 2756 JITLoader::LoadPlugins(this, *m_jit_loaders_up); 2757 } 2758 return *m_jit_loaders_up; 2759 } 2760 2761 SystemRuntime *Process::GetSystemRuntime() { 2762 if (!m_system_runtime_up) 2763 m_system_runtime_up.reset(SystemRuntime::FindPlugin(this)); 2764 return m_system_runtime_up.get(); 2765 } 2766 2767 Process::AttachCompletionHandler::AttachCompletionHandler(Process *process, 2768 uint32_t exec_count) 2769 : NextEventAction(process), m_exec_count(exec_count) { 2770 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 2771 LLDB_LOGF( 2772 log, 2773 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, 2774 __FUNCTION__, static_cast<void *>(process), exec_count); 2775 } 2776 2777 Process::NextEventAction::EventActionResult 2778 Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) { 2779 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 2780 2781 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get()); 2782 LLDB_LOGF(log, 2783 "Process::AttachCompletionHandler::%s called with state %s (%d)", 2784 __FUNCTION__, StateAsCString(state), static_cast<int>(state)); 2785 2786 switch (state) { 2787 case eStateAttaching: 2788 return eEventActionSuccess; 2789 2790 case eStateRunning: 2791 case eStateConnected: 2792 return eEventActionRetry; 2793 2794 case eStateStopped: 2795 case eStateCrashed: 2796 // During attach, prior to sending the eStateStopped event, 2797 // lldb_private::Process subclasses must set the new process ID. 2798 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID); 2799 // We don't want these events to be reported, so go set the 2800 // ShouldReportStop here: 2801 m_process->GetThreadList().SetShouldReportStop(eVoteNo); 2802 2803 if (m_exec_count > 0) { 2804 --m_exec_count; 2805 2806 LLDB_LOGF(log, 2807 "Process::AttachCompletionHandler::%s state %s: reduced " 2808 "remaining exec count to %" PRIu32 ", requesting resume", 2809 __FUNCTION__, StateAsCString(state), m_exec_count); 2810 2811 RequestResume(); 2812 return eEventActionRetry; 2813 } else { 2814 LLDB_LOGF(log, 2815 "Process::AttachCompletionHandler::%s state %s: no more " 2816 "execs expected to start, continuing with attach", 2817 __FUNCTION__, StateAsCString(state)); 2818 2819 m_process->CompleteAttach(); 2820 return eEventActionSuccess; 2821 } 2822 break; 2823 2824 default: 2825 case eStateExited: 2826 case eStateInvalid: 2827 break; 2828 } 2829 2830 m_exit_string.assign("No valid Process"); 2831 return eEventActionExit; 2832 } 2833 2834 Process::NextEventAction::EventActionResult 2835 Process::AttachCompletionHandler::HandleBeingInterrupted() { 2836 return eEventActionSuccess; 2837 } 2838 2839 const char *Process::AttachCompletionHandler::GetExitString() { 2840 return m_exit_string.c_str(); 2841 } 2842 2843 ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) { 2844 if (m_listener_sp) 2845 return m_listener_sp; 2846 else 2847 return debugger.GetListener(); 2848 } 2849 2850 Status Process::Attach(ProcessAttachInfo &attach_info) { 2851 m_abi_sp.reset(); 2852 m_process_input_reader.reset(); 2853 m_dyld_up.reset(); 2854 m_jit_loaders_up.reset(); 2855 m_system_runtime_up.reset(); 2856 m_os_up.reset(); 2857 2858 lldb::pid_t attach_pid = attach_info.GetProcessID(); 2859 Status error; 2860 if (attach_pid == LLDB_INVALID_PROCESS_ID) { 2861 char process_name[PATH_MAX]; 2862 2863 if (attach_info.GetExecutableFile().GetPath(process_name, 2864 sizeof(process_name))) { 2865 const bool wait_for_launch = attach_info.GetWaitForLaunch(); 2866 2867 if (wait_for_launch) { 2868 error = WillAttachToProcessWithName(process_name, wait_for_launch); 2869 if (error.Success()) { 2870 if (m_public_run_lock.TrySetRunning()) { 2871 m_should_detach = true; 2872 const bool restarted = false; 2873 SetPublicState(eStateAttaching, restarted); 2874 // Now attach using these arguments. 2875 error = DoAttachToProcessWithName(process_name, attach_info); 2876 } else { 2877 // This shouldn't happen 2878 error.SetErrorString("failed to acquire process run lock"); 2879 } 2880 2881 if (error.Fail()) { 2882 if (GetID() != LLDB_INVALID_PROCESS_ID) { 2883 SetID(LLDB_INVALID_PROCESS_ID); 2884 if (error.AsCString() == nullptr) 2885 error.SetErrorString("attach failed"); 2886 2887 SetExitStatus(-1, error.AsCString()); 2888 } 2889 } else { 2890 SetNextEventAction(new Process::AttachCompletionHandler( 2891 this, attach_info.GetResumeCount())); 2892 StartPrivateStateThread(); 2893 } 2894 return error; 2895 } 2896 } else { 2897 ProcessInstanceInfoList process_infos; 2898 PlatformSP platform_sp(GetTarget().GetPlatform()); 2899 2900 if (platform_sp) { 2901 ProcessInstanceInfoMatch match_info; 2902 match_info.GetProcessInfo() = attach_info; 2903 match_info.SetNameMatchType(NameMatch::Equals); 2904 platform_sp->FindProcesses(match_info, process_infos); 2905 const uint32_t num_matches = process_infos.size(); 2906 if (num_matches == 1) { 2907 attach_pid = process_infos[0].GetProcessID(); 2908 // Fall through and attach using the above process ID 2909 } else { 2910 match_info.GetProcessInfo().GetExecutableFile().GetPath( 2911 process_name, sizeof(process_name)); 2912 if (num_matches > 1) { 2913 StreamString s; 2914 ProcessInstanceInfo::DumpTableHeader(s, true, false); 2915 for (size_t i = 0; i < num_matches; i++) { 2916 process_infos[i].DumpAsTableRow( 2917 s, platform_sp->GetUserIDResolver(), true, false); 2918 } 2919 error.SetErrorStringWithFormat( 2920 "more than one process named %s:\n%s", process_name, 2921 s.GetData()); 2922 } else 2923 error.SetErrorStringWithFormat( 2924 "could not find a process named %s", process_name); 2925 } 2926 } else { 2927 error.SetErrorString( 2928 "invalid platform, can't find processes by name"); 2929 return error; 2930 } 2931 } 2932 } else { 2933 error.SetErrorString("invalid process name"); 2934 } 2935 } 2936 2937 if (attach_pid != LLDB_INVALID_PROCESS_ID) { 2938 error = WillAttachToProcessWithID(attach_pid); 2939 if (error.Success()) { 2940 2941 if (m_public_run_lock.TrySetRunning()) { 2942 // Now attach using these arguments. 2943 m_should_detach = true; 2944 const bool restarted = false; 2945 SetPublicState(eStateAttaching, restarted); 2946 error = DoAttachToProcessWithID(attach_pid, attach_info); 2947 } else { 2948 // This shouldn't happen 2949 error.SetErrorString("failed to acquire process run lock"); 2950 } 2951 2952 if (error.Success()) { 2953 SetNextEventAction(new Process::AttachCompletionHandler( 2954 this, attach_info.GetResumeCount())); 2955 StartPrivateStateThread(); 2956 } else { 2957 if (GetID() != LLDB_INVALID_PROCESS_ID) 2958 SetID(LLDB_INVALID_PROCESS_ID); 2959 2960 const char *error_string = error.AsCString(); 2961 if (error_string == nullptr) 2962 error_string = "attach failed"; 2963 2964 SetExitStatus(-1, error_string); 2965 } 2966 } 2967 } 2968 return error; 2969 } 2970 2971 void Process::CompleteAttach() { 2972 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | 2973 LIBLLDB_LOG_TARGET)); 2974 LLDB_LOGF(log, "Process::%s()", __FUNCTION__); 2975 2976 // Let the process subclass figure out at much as it can about the process 2977 // before we go looking for a dynamic loader plug-in. 2978 ArchSpec process_arch; 2979 DidAttach(process_arch); 2980 2981 if (process_arch.IsValid()) { 2982 GetTarget().SetArchitecture(process_arch); 2983 if (log) { 2984 const char *triple_str = process_arch.GetTriple().getTriple().c_str(); 2985 LLDB_LOGF(log, 2986 "Process::%s replacing process architecture with DidAttach() " 2987 "architecture: %s", 2988 __FUNCTION__, triple_str ? triple_str : "<null>"); 2989 } 2990 } 2991 2992 // We just attached. If we have a platform, ask it for the process 2993 // architecture, and if it isn't the same as the one we've already set, 2994 // switch architectures. 2995 PlatformSP platform_sp(GetTarget().GetPlatform()); 2996 assert(platform_sp); 2997 if (platform_sp) { 2998 const ArchSpec &target_arch = GetTarget().GetArchitecture(); 2999 if (target_arch.IsValid() && 3000 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) { 3001 ArchSpec platform_arch; 3002 platform_sp = 3003 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch); 3004 if (platform_sp) { 3005 GetTarget().SetPlatform(platform_sp); 3006 GetTarget().SetArchitecture(platform_arch); 3007 LLDB_LOGF(log, 3008 "Process::%s switching platform to %s and architecture " 3009 "to %s based on info from attach", 3010 __FUNCTION__, platform_sp->GetName().AsCString(""), 3011 platform_arch.GetTriple().getTriple().c_str()); 3012 } 3013 } else if (!process_arch.IsValid()) { 3014 ProcessInstanceInfo process_info; 3015 GetProcessInfo(process_info); 3016 const ArchSpec &process_arch = process_info.GetArchitecture(); 3017 if (process_arch.IsValid() && 3018 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) { 3019 GetTarget().SetArchitecture(process_arch); 3020 LLDB_LOGF(log, 3021 "Process::%s switching architecture to %s based on info " 3022 "the platform retrieved for pid %" PRIu64, 3023 __FUNCTION__, process_arch.GetTriple().getTriple().c_str(), 3024 GetID()); 3025 } 3026 } 3027 } 3028 3029 // We have completed the attach, now it is time to find the dynamic loader 3030 // plug-in 3031 DynamicLoader *dyld = GetDynamicLoader(); 3032 if (dyld) { 3033 dyld->DidAttach(); 3034 if (log) { 3035 ModuleSP exe_module_sp = GetTarget().GetExecutableModule(); 3036 LLDB_LOGF(log, 3037 "Process::%s after DynamicLoader::DidAttach(), target " 3038 "executable is %s (using %s plugin)", 3039 __FUNCTION__, 3040 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str() 3041 : "<none>", 3042 dyld->GetPluginName().AsCString("<unnamed>")); 3043 } 3044 } 3045 3046 GetJITLoaders().DidAttach(); 3047 3048 SystemRuntime *system_runtime = GetSystemRuntime(); 3049 if (system_runtime) { 3050 system_runtime->DidAttach(); 3051 if (log) { 3052 ModuleSP exe_module_sp = GetTarget().GetExecutableModule(); 3053 LLDB_LOGF(log, 3054 "Process::%s after SystemRuntime::DidAttach(), target " 3055 "executable is %s (using %s plugin)", 3056 __FUNCTION__, 3057 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str() 3058 : "<none>", 3059 system_runtime->GetPluginName().AsCString("<unnamed>")); 3060 } 3061 } 3062 3063 if (!m_os_up) { 3064 LoadOperatingSystemPlugin(false); 3065 if (m_os_up) { 3066 // Somebody might have gotten threads before now, but we need to force the 3067 // update after we've loaded the OperatingSystem plugin or it won't get a 3068 // chance to process the threads. 3069 m_thread_list.Clear(); 3070 UpdateThreadListIfNeeded(); 3071 } 3072 } 3073 // Figure out which one is the executable, and set that in our target: 3074 const ModuleList &target_modules = GetTarget().GetImages(); 3075 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex()); 3076 size_t num_modules = target_modules.GetSize(); 3077 ModuleSP new_executable_module_sp; 3078 3079 for (size_t i = 0; i < num_modules; i++) { 3080 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i)); 3081 if (module_sp && module_sp->IsExecutable()) { 3082 if (GetTarget().GetExecutableModulePointer() != module_sp.get()) 3083 new_executable_module_sp = module_sp; 3084 break; 3085 } 3086 } 3087 if (new_executable_module_sp) { 3088 GetTarget().SetExecutableModule(new_executable_module_sp, 3089 eLoadDependentsNo); 3090 if (log) { 3091 ModuleSP exe_module_sp = GetTarget().GetExecutableModule(); 3092 LLDB_LOGF( 3093 log, 3094 "Process::%s after looping through modules, target executable is %s", 3095 __FUNCTION__, 3096 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str() 3097 : "<none>"); 3098 } 3099 } 3100 } 3101 3102 Status Process::ConnectRemote(llvm::StringRef remote_url) { 3103 m_abi_sp.reset(); 3104 m_process_input_reader.reset(); 3105 3106 // Find the process and its architecture. Make sure it matches the 3107 // architecture of the current Target, and if not adjust it. 3108 3109 Status error(DoConnectRemote(remote_url)); 3110 if (error.Success()) { 3111 if (GetID() != LLDB_INVALID_PROCESS_ID) { 3112 EventSP event_sp; 3113 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None); 3114 3115 if (state == eStateStopped || state == eStateCrashed) { 3116 // If we attached and actually have a process on the other end, then 3117 // this ended up being the equivalent of an attach. 3118 CompleteAttach(); 3119 3120 // This delays passing the stopped event to listeners till 3121 // CompleteAttach gets a chance to complete... 3122 HandlePrivateEvent(event_sp); 3123 } 3124 } 3125 3126 if (PrivateStateThreadIsValid()) 3127 ResumePrivateStateThread(); 3128 else 3129 StartPrivateStateThread(); 3130 } 3131 return error; 3132 } 3133 3134 Status Process::PrivateResume() { 3135 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | 3136 LIBLLDB_LOG_STEP)); 3137 LLDB_LOGF(log, 3138 "Process::PrivateResume() m_stop_id = %u, public state: %s " 3139 "private state: %s", 3140 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()), 3141 StateAsCString(m_private_state.GetValue())); 3142 3143 // If signals handing status changed we might want to update our signal 3144 // filters before resuming. 3145 UpdateAutomaticSignalFiltering(); 3146 3147 Status error(WillResume()); 3148 // Tell the process it is about to resume before the thread list 3149 if (error.Success()) { 3150 // Now let the thread list know we are about to resume so it can let all of 3151 // our threads know that they are about to be resumed. Threads will each be 3152 // called with Thread::WillResume(StateType) where StateType contains the 3153 // state that they are supposed to have when the process is resumed 3154 // (suspended/running/stepping). Threads should also check their resume 3155 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to 3156 // start back up with a signal. 3157 if (m_thread_list.WillResume()) { 3158 // Last thing, do the PreResumeActions. 3159 if (!RunPreResumeActions()) { 3160 error.SetErrorString( 3161 "Process::PrivateResume PreResumeActions failed, not resuming."); 3162 } else { 3163 m_mod_id.BumpResumeID(); 3164 error = DoResume(); 3165 if (error.Success()) { 3166 DidResume(); 3167 m_thread_list.DidResume(); 3168 LLDB_LOGF(log, "Process thinks the process has resumed."); 3169 } else { 3170 LLDB_LOGF(log, "Process::PrivateResume() DoResume failed."); 3171 return error; 3172 } 3173 } 3174 } else { 3175 // Somebody wanted to run without running (e.g. we were faking a step 3176 // from one frame of a set of inlined frames that share the same PC to 3177 // another.) So generate a continue & a stopped event, and let the world 3178 // handle them. 3179 LLDB_LOGF(log, 3180 "Process::PrivateResume() asked to simulate a start & stop."); 3181 3182 SetPrivateState(eStateRunning); 3183 SetPrivateState(eStateStopped); 3184 } 3185 } else 3186 LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".", 3187 error.AsCString("<unknown error>")); 3188 return error; 3189 } 3190 3191 Status Process::Halt(bool clear_thread_plans, bool use_run_lock) { 3192 if (!StateIsRunningState(m_public_state.GetValue())) 3193 return Status("Process is not running."); 3194 3195 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in 3196 // case it was already set and some thread plan logic calls halt on its own. 3197 m_clear_thread_plans_on_stop |= clear_thread_plans; 3198 3199 ListenerSP halt_listener_sp( 3200 Listener::MakeListener("lldb.process.halt_listener")); 3201 HijackProcessEvents(halt_listener_sp); 3202 3203 EventSP event_sp; 3204 3205 SendAsyncInterrupt(); 3206 3207 if (m_public_state.GetValue() == eStateAttaching) { 3208 // Don't hijack and eat the eStateExited as the code that was doing the 3209 // attach will be waiting for this event... 3210 RestoreProcessEvents(); 3211 SetExitStatus(SIGKILL, "Cancelled async attach."); 3212 Destroy(false); 3213 return Status(); 3214 } 3215 3216 // Wait for 10 second for the process to stop. 3217 StateType state = WaitForProcessToStop( 3218 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock); 3219 RestoreProcessEvents(); 3220 3221 if (state == eStateInvalid || !event_sp) { 3222 // We timed out and didn't get a stop event... 3223 return Status("Halt timed out. State = %s", StateAsCString(GetState())); 3224 } 3225 3226 BroadcastEvent(event_sp); 3227 3228 return Status(); 3229 } 3230 3231 Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) { 3232 Status error; 3233 3234 // Check both the public & private states here. If we're hung evaluating an 3235 // expression, for instance, then the public state will be stopped, but we 3236 // still need to interrupt. 3237 if (m_public_state.GetValue() == eStateRunning || 3238 m_private_state.GetValue() == eStateRunning) { 3239 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3240 LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__); 3241 3242 ListenerSP listener_sp( 3243 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack")); 3244 HijackProcessEvents(listener_sp); 3245 3246 SendAsyncInterrupt(); 3247 3248 // Consume the interrupt event. 3249 StateType state = 3250 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp); 3251 3252 RestoreProcessEvents(); 3253 3254 // If the process exited while we were waiting for it to stop, put the 3255 // exited event into the shared pointer passed in and return. Our caller 3256 // doesn't need to do anything else, since they don't have a process 3257 // anymore... 3258 3259 if (state == eStateExited || m_private_state.GetValue() == eStateExited) { 3260 LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.", 3261 __FUNCTION__); 3262 return error; 3263 } else 3264 exit_event_sp.reset(); // It is ok to consume any non-exit stop events 3265 3266 if (state != eStateStopped) { 3267 LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__, 3268 StateAsCString(state)); 3269 // If we really couldn't stop the process then we should just error out 3270 // here, but if the lower levels just bobbled sending the event and we 3271 // really are stopped, then continue on. 3272 StateType private_state = m_private_state.GetValue(); 3273 if (private_state != eStateStopped) { 3274 return Status( 3275 "Attempt to stop the target in order to detach timed out. " 3276 "State = %s", 3277 StateAsCString(GetState())); 3278 } 3279 } 3280 } 3281 return error; 3282 } 3283 3284 Status Process::Detach(bool keep_stopped) { 3285 EventSP exit_event_sp; 3286 Status error; 3287 m_destroy_in_process = true; 3288 3289 error = WillDetach(); 3290 3291 if (error.Success()) { 3292 if (DetachRequiresHalt()) { 3293 error = StopForDestroyOrDetach(exit_event_sp); 3294 if (!error.Success()) { 3295 m_destroy_in_process = false; 3296 return error; 3297 } else if (exit_event_sp) { 3298 // We shouldn't need to do anything else here. There's no process left 3299 // to detach from... 3300 StopPrivateStateThread(); 3301 m_destroy_in_process = false; 3302 return error; 3303 } 3304 } 3305 3306 m_thread_list.DiscardThreadPlans(); 3307 DisableAllBreakpointSites(); 3308 3309 error = DoDetach(keep_stopped); 3310 if (error.Success()) { 3311 DidDetach(); 3312 StopPrivateStateThread(); 3313 } else { 3314 return error; 3315 } 3316 } 3317 m_destroy_in_process = false; 3318 3319 // If we exited when we were waiting for a process to stop, then forward the 3320 // event here so we don't lose the event 3321 if (exit_event_sp) { 3322 // Directly broadcast our exited event because we shut down our private 3323 // state thread above 3324 BroadcastEvent(exit_event_sp); 3325 } 3326 3327 // If we have been interrupted (to kill us) in the middle of running, we may 3328 // not end up propagating the last events through the event system, in which 3329 // case we might strand the write lock. Unlock it here so when we do to tear 3330 // down the process we don't get an error destroying the lock. 3331 3332 m_public_run_lock.SetStopped(); 3333 return error; 3334 } 3335 3336 Status Process::Destroy(bool force_kill) { 3337 // If we've already called Process::Finalize then there's nothing useful to 3338 // be done here. Finalize has actually called Destroy already. 3339 if (m_finalize_called) 3340 return {}; 3341 3342 // Tell ourselves we are in the process of destroying the process, so that we 3343 // don't do any unnecessary work that might hinder the destruction. Remember 3344 // to set this back to false when we are done. That way if the attempt 3345 // failed and the process stays around for some reason it won't be in a 3346 // confused state. 3347 3348 if (force_kill) 3349 m_should_detach = false; 3350 3351 if (GetShouldDetach()) { 3352 // FIXME: This will have to be a process setting: 3353 bool keep_stopped = false; 3354 Detach(keep_stopped); 3355 } 3356 3357 m_destroy_in_process = true; 3358 3359 Status error(WillDestroy()); 3360 if (error.Success()) { 3361 EventSP exit_event_sp; 3362 if (DestroyRequiresHalt()) { 3363 error = StopForDestroyOrDetach(exit_event_sp); 3364 } 3365 3366 if (m_public_state.GetValue() != eStateRunning) { 3367 // Ditch all thread plans, and remove all our breakpoints: in case we 3368 // have to restart the target to kill it, we don't want it hitting a 3369 // breakpoint... Only do this if we've stopped, however, since if we 3370 // didn't manage to halt it above, then we're not going to have much luck 3371 // doing this now. 3372 m_thread_list.DiscardThreadPlans(); 3373 DisableAllBreakpointSites(); 3374 } 3375 3376 error = DoDestroy(); 3377 if (error.Success()) { 3378 DidDestroy(); 3379 StopPrivateStateThread(); 3380 } 3381 m_stdio_communication.StopReadThread(); 3382 m_stdio_communication.Disconnect(); 3383 m_stdin_forward = false; 3384 3385 if (m_process_input_reader) { 3386 m_process_input_reader->SetIsDone(true); 3387 m_process_input_reader->Cancel(); 3388 m_process_input_reader.reset(); 3389 } 3390 3391 // If we exited when we were waiting for a process to stop, then forward 3392 // the event here so we don't lose the event 3393 if (exit_event_sp) { 3394 // Directly broadcast our exited event because we shut down our private 3395 // state thread above 3396 BroadcastEvent(exit_event_sp); 3397 } 3398 3399 // If we have been interrupted (to kill us) in the middle of running, we 3400 // may not end up propagating the last events through the event system, in 3401 // which case we might strand the write lock. Unlock it here so when we do 3402 // to tear down the process we don't get an error destroying the lock. 3403 m_public_run_lock.SetStopped(); 3404 } 3405 3406 m_destroy_in_process = false; 3407 3408 return error; 3409 } 3410 3411 Status Process::Signal(int signal) { 3412 Status error(WillSignal()); 3413 if (error.Success()) { 3414 error = DoSignal(signal); 3415 if (error.Success()) 3416 DidSignal(); 3417 } 3418 return error; 3419 } 3420 3421 void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) { 3422 assert(signals_sp && "null signals_sp"); 3423 m_unix_signals_sp = signals_sp; 3424 } 3425 3426 const lldb::UnixSignalsSP &Process::GetUnixSignals() { 3427 assert(m_unix_signals_sp && "null m_unix_signals_sp"); 3428 return m_unix_signals_sp; 3429 } 3430 3431 lldb::ByteOrder Process::GetByteOrder() const { 3432 return GetTarget().GetArchitecture().GetByteOrder(); 3433 } 3434 3435 uint32_t Process::GetAddressByteSize() const { 3436 return GetTarget().GetArchitecture().GetAddressByteSize(); 3437 } 3438 3439 bool Process::ShouldBroadcastEvent(Event *event_ptr) { 3440 const StateType state = 3441 Process::ProcessEventData::GetStateFromEvent(event_ptr); 3442 bool return_value = true; 3443 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | 3444 LIBLLDB_LOG_PROCESS)); 3445 3446 switch (state) { 3447 case eStateDetached: 3448 case eStateExited: 3449 case eStateUnloaded: 3450 m_stdio_communication.SynchronizeWithReadThread(); 3451 m_stdio_communication.StopReadThread(); 3452 m_stdio_communication.Disconnect(); 3453 m_stdin_forward = false; 3454 3455 LLVM_FALLTHROUGH; 3456 case eStateConnected: 3457 case eStateAttaching: 3458 case eStateLaunching: 3459 // These events indicate changes in the state of the debugging session, 3460 // always report them. 3461 return_value = true; 3462 break; 3463 case eStateInvalid: 3464 // We stopped for no apparent reason, don't report it. 3465 return_value = false; 3466 break; 3467 case eStateRunning: 3468 case eStateStepping: 3469 // If we've started the target running, we handle the cases where we are 3470 // already running and where there is a transition from stopped to running 3471 // differently. running -> running: Automatically suppress extra running 3472 // events stopped -> running: Report except when there is one or more no 3473 // votes 3474 // and no yes votes. 3475 SynchronouslyNotifyStateChanged(state); 3476 if (m_force_next_event_delivery) 3477 return_value = true; 3478 else { 3479 switch (m_last_broadcast_state) { 3480 case eStateRunning: 3481 case eStateStepping: 3482 // We always suppress multiple runnings with no PUBLIC stop in between. 3483 return_value = false; 3484 break; 3485 default: 3486 // TODO: make this work correctly. For now always report 3487 // run if we aren't running so we don't miss any running events. If I 3488 // run the lldb/test/thread/a.out file and break at main.cpp:58, run 3489 // and hit the breakpoints on multiple threads, then somehow during the 3490 // stepping over of all breakpoints no run gets reported. 3491 3492 // This is a transition from stop to run. 3493 switch (m_thread_list.ShouldReportRun(event_ptr)) { 3494 case eVoteYes: 3495 case eVoteNoOpinion: 3496 return_value = true; 3497 break; 3498 case eVoteNo: 3499 return_value = false; 3500 break; 3501 } 3502 break; 3503 } 3504 } 3505 break; 3506 case eStateStopped: 3507 case eStateCrashed: 3508 case eStateSuspended: 3509 // We've stopped. First see if we're going to restart the target. If we 3510 // are going to stop, then we always broadcast the event. If we aren't 3511 // going to stop, let the thread plans decide if we're going to report this 3512 // event. If no thread has an opinion, we don't report it. 3513 3514 m_stdio_communication.SynchronizeWithReadThread(); 3515 RefreshStateAfterStop(); 3516 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) { 3517 LLDB_LOGF(log, 3518 "Process::ShouldBroadcastEvent (%p) stopped due to an " 3519 "interrupt, state: %s", 3520 static_cast<void *>(event_ptr), StateAsCString(state)); 3521 // Even though we know we are going to stop, we should let the threads 3522 // have a look at the stop, so they can properly set their state. 3523 m_thread_list.ShouldStop(event_ptr); 3524 return_value = true; 3525 } else { 3526 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr); 3527 bool should_resume = false; 3528 3529 // It makes no sense to ask "ShouldStop" if we've already been 3530 // restarted... Asking the thread list is also not likely to go well, 3531 // since we are running again. So in that case just report the event. 3532 3533 if (!was_restarted) 3534 should_resume = !m_thread_list.ShouldStop(event_ptr); 3535 3536 if (was_restarted || should_resume || m_resume_requested) { 3537 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr); 3538 LLDB_LOGF(log, 3539 "Process::ShouldBroadcastEvent: should_resume: %i state: " 3540 "%s was_restarted: %i stop_vote: %d.", 3541 should_resume, StateAsCString(state), was_restarted, 3542 stop_vote); 3543 3544 switch (stop_vote) { 3545 case eVoteYes: 3546 return_value = true; 3547 break; 3548 case eVoteNoOpinion: 3549 case eVoteNo: 3550 return_value = false; 3551 break; 3552 } 3553 3554 if (!was_restarted) { 3555 LLDB_LOGF(log, 3556 "Process::ShouldBroadcastEvent (%p) Restarting process " 3557 "from state: %s", 3558 static_cast<void *>(event_ptr), StateAsCString(state)); 3559 ProcessEventData::SetRestartedInEvent(event_ptr, true); 3560 PrivateResume(); 3561 } 3562 } else { 3563 return_value = true; 3564 SynchronouslyNotifyStateChanged(state); 3565 } 3566 } 3567 break; 3568 } 3569 3570 // Forcing the next event delivery is a one shot deal. So reset it here. 3571 m_force_next_event_delivery = false; 3572 3573 // We do some coalescing of events (for instance two consecutive running 3574 // events get coalesced.) But we only coalesce against events we actually 3575 // broadcast. So we use m_last_broadcast_state to track that. NB - you 3576 // can't use "m_public_state.GetValue()" for that purpose, as was originally 3577 // done, because the PublicState reflects the last event pulled off the 3578 // queue, and there may be several events stacked up on the queue unserviced. 3579 // So the PublicState may not reflect the last broadcasted event yet. 3580 // m_last_broadcast_state gets updated here. 3581 3582 if (return_value) 3583 m_last_broadcast_state = state; 3584 3585 LLDB_LOGF(log, 3586 "Process::ShouldBroadcastEvent (%p) => new state: %s, last " 3587 "broadcast state: %s - %s", 3588 static_cast<void *>(event_ptr), StateAsCString(state), 3589 StateAsCString(m_last_broadcast_state), 3590 return_value ? "YES" : "NO"); 3591 return return_value; 3592 } 3593 3594 bool Process::StartPrivateStateThread(bool is_secondary_thread) { 3595 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS)); 3596 3597 bool already_running = PrivateStateThreadIsValid(); 3598 LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__, 3599 already_running ? " already running" 3600 : " starting private state thread"); 3601 3602 if (!is_secondary_thread && already_running) 3603 return true; 3604 3605 // Create a thread that watches our internal state and controls which events 3606 // make it to clients (into the DCProcess event queue). 3607 char thread_name[1024]; 3608 uint32_t max_len = llvm::get_max_thread_name_length(); 3609 if (max_len > 0 && max_len <= 30) { 3610 // On platforms with abbreviated thread name lengths, choose thread names 3611 // that fit within the limit. 3612 if (already_running) 3613 snprintf(thread_name, sizeof(thread_name), "intern-state-OV"); 3614 else 3615 snprintf(thread_name, sizeof(thread_name), "intern-state"); 3616 } else { 3617 if (already_running) 3618 snprintf(thread_name, sizeof(thread_name), 3619 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", 3620 GetID()); 3621 else 3622 snprintf(thread_name, sizeof(thread_name), 3623 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID()); 3624 } 3625 3626 // Create the private state thread, and start it running. 3627 PrivateStateThreadArgs *args_ptr = 3628 new PrivateStateThreadArgs(this, is_secondary_thread); 3629 llvm::Expected<HostThread> private_state_thread = 3630 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, 3631 (void *)args_ptr, 8 * 1024 * 1024); 3632 if (!private_state_thread) { 3633 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), 3634 "failed to launch host thread: {}", 3635 llvm::toString(private_state_thread.takeError())); 3636 return false; 3637 } 3638 3639 assert(private_state_thread->IsJoinable()); 3640 m_private_state_thread = *private_state_thread; 3641 ResumePrivateStateThread(); 3642 return true; 3643 } 3644 3645 void Process::PausePrivateStateThread() { 3646 ControlPrivateStateThread(eBroadcastInternalStateControlPause); 3647 } 3648 3649 void Process::ResumePrivateStateThread() { 3650 ControlPrivateStateThread(eBroadcastInternalStateControlResume); 3651 } 3652 3653 void Process::StopPrivateStateThread() { 3654 if (m_private_state_thread.IsJoinable()) 3655 ControlPrivateStateThread(eBroadcastInternalStateControlStop); 3656 else { 3657 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3658 LLDB_LOGF( 3659 log, 3660 "Went to stop the private state thread, but it was already invalid."); 3661 } 3662 } 3663 3664 void Process::ControlPrivateStateThread(uint32_t signal) { 3665 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3666 3667 assert(signal == eBroadcastInternalStateControlStop || 3668 signal == eBroadcastInternalStateControlPause || 3669 signal == eBroadcastInternalStateControlResume); 3670 3671 LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal); 3672 3673 // Signal the private state thread 3674 if (m_private_state_thread.IsJoinable()) { 3675 // Broadcast the event. 3676 // It is important to do this outside of the if below, because it's 3677 // possible that the thread state is invalid but that the thread is waiting 3678 // on a control event instead of simply being on its way out (this should 3679 // not happen, but it apparently can). 3680 LLDB_LOGF(log, "Sending control event of type: %d.", signal); 3681 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt()); 3682 m_private_state_control_broadcaster.BroadcastEvent(signal, 3683 event_receipt_sp); 3684 3685 // Wait for the event receipt or for the private state thread to exit 3686 bool receipt_received = false; 3687 if (PrivateStateThreadIsValid()) { 3688 while (!receipt_received) { 3689 // Check for a receipt for n seconds and then check if the private 3690 // state thread is still around. 3691 receipt_received = 3692 event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout()); 3693 if (!receipt_received) { 3694 // Check if the private state thread is still around. If it isn't 3695 // then we are done waiting 3696 if (!PrivateStateThreadIsValid()) 3697 break; // Private state thread exited or is exiting, we are done 3698 } 3699 } 3700 } 3701 3702 if (signal == eBroadcastInternalStateControlStop) { 3703 thread_result_t result = {}; 3704 m_private_state_thread.Join(&result); 3705 m_private_state_thread.Reset(); 3706 } 3707 } else { 3708 LLDB_LOGF( 3709 log, 3710 "Private state thread already dead, no need to signal it to stop."); 3711 } 3712 } 3713 3714 void Process::SendAsyncInterrupt() { 3715 if (PrivateStateThreadIsValid()) 3716 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt, 3717 nullptr); 3718 else 3719 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr); 3720 } 3721 3722 void Process::HandlePrivateEvent(EventSP &event_sp) { 3723 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3724 m_resume_requested = false; 3725 3726 const StateType new_state = 3727 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 3728 3729 // First check to see if anybody wants a shot at this event: 3730 if (m_next_event_action_up) { 3731 NextEventAction::EventActionResult action_result = 3732 m_next_event_action_up->PerformAction(event_sp); 3733 LLDB_LOGF(log, "Ran next event action, result was %d.", action_result); 3734 3735 switch (action_result) { 3736 case NextEventAction::eEventActionSuccess: 3737 SetNextEventAction(nullptr); 3738 break; 3739 3740 case NextEventAction::eEventActionRetry: 3741 break; 3742 3743 case NextEventAction::eEventActionExit: 3744 // Handle Exiting Here. If we already got an exited event, we should 3745 // just propagate it. Otherwise, swallow this event, and set our state 3746 // to exit so the next event will kill us. 3747 if (new_state != eStateExited) { 3748 // FIXME: should cons up an exited event, and discard this one. 3749 SetExitStatus(0, m_next_event_action_up->GetExitString()); 3750 SetNextEventAction(nullptr); 3751 return; 3752 } 3753 SetNextEventAction(nullptr); 3754 break; 3755 } 3756 } 3757 3758 // See if we should broadcast this state to external clients? 3759 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get()); 3760 3761 if (should_broadcast) { 3762 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged); 3763 if (log) { 3764 LLDB_LOGF(log, 3765 "Process::%s (pid = %" PRIu64 3766 ") broadcasting new state %s (old state %s) to %s", 3767 __FUNCTION__, GetID(), StateAsCString(new_state), 3768 StateAsCString(GetState()), 3769 is_hijacked ? "hijacked" : "public"); 3770 } 3771 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get()); 3772 if (StateIsRunningState(new_state)) { 3773 // Only push the input handler if we aren't fowarding events, as this 3774 // means the curses GUI is in use... Or don't push it if we are launching 3775 // since it will come up stopped. 3776 if (!GetTarget().GetDebugger().IsForwardingEvents() && 3777 new_state != eStateLaunching && new_state != eStateAttaching) { 3778 PushProcessIOHandler(); 3779 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1, 3780 eBroadcastAlways); 3781 LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d", 3782 __FUNCTION__, m_iohandler_sync.GetValue()); 3783 } 3784 } else if (StateIsStoppedState(new_state, false)) { 3785 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) { 3786 // If the lldb_private::Debugger is handling the events, we don't want 3787 // to pop the process IOHandler here, we want to do it when we receive 3788 // the stopped event so we can carefully control when the process 3789 // IOHandler is popped because when we stop we want to display some 3790 // text stating how and why we stopped, then maybe some 3791 // process/thread/frame info, and then we want the "(lldb) " prompt to 3792 // show up. If we pop the process IOHandler here, then we will cause 3793 // the command interpreter to become the top IOHandler after the 3794 // process pops off and it will update its prompt right away... See the 3795 // Debugger.cpp file where it calls the function as 3796 // "process_sp->PopProcessIOHandler()" to see where I am talking about. 3797 // Otherwise we end up getting overlapping "(lldb) " prompts and 3798 // garbled output. 3799 // 3800 // If we aren't handling the events in the debugger (which is indicated 3801 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or 3802 // we are hijacked, then we always pop the process IO handler manually. 3803 // Hijacking happens when the internal process state thread is running 3804 // thread plans, or when commands want to run in synchronous mode and 3805 // they call "process->WaitForProcessToStop()". An example of something 3806 // that will hijack the events is a simple expression: 3807 // 3808 // (lldb) expr (int)puts("hello") 3809 // 3810 // This will cause the internal process state thread to resume and halt 3811 // the process (and _it_ will hijack the eBroadcastBitStateChanged 3812 // events) and we do need the IO handler to be pushed and popped 3813 // correctly. 3814 3815 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents()) 3816 PopProcessIOHandler(); 3817 } 3818 } 3819 3820 BroadcastEvent(event_sp); 3821 } else { 3822 if (log) { 3823 LLDB_LOGF( 3824 log, 3825 "Process::%s (pid = %" PRIu64 3826 ") suppressing state %s (old state %s): should_broadcast == false", 3827 __FUNCTION__, GetID(), StateAsCString(new_state), 3828 StateAsCString(GetState())); 3829 } 3830 } 3831 } 3832 3833 Status Process::HaltPrivate() { 3834 EventSP event_sp; 3835 Status error(WillHalt()); 3836 if (error.Fail()) 3837 return error; 3838 3839 // Ask the process subclass to actually halt our process 3840 bool caused_stop; 3841 error = DoHalt(caused_stop); 3842 3843 DidHalt(); 3844 return error; 3845 } 3846 3847 thread_result_t Process::PrivateStateThread(void *arg) { 3848 std::unique_ptr<PrivateStateThreadArgs> args_up( 3849 static_cast<PrivateStateThreadArgs *>(arg)); 3850 thread_result_t result = 3851 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread); 3852 return result; 3853 } 3854 3855 thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) { 3856 bool control_only = true; 3857 3858 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 3859 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", 3860 __FUNCTION__, static_cast<void *>(this), GetID()); 3861 3862 bool exit_now = false; 3863 bool interrupt_requested = false; 3864 while (!exit_now) { 3865 EventSP event_sp; 3866 GetEventsPrivate(event_sp, llvm::None, control_only); 3867 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) { 3868 LLDB_LOGF(log, 3869 "Process::%s (arg = %p, pid = %" PRIu64 3870 ") got a control event: %d", 3871 __FUNCTION__, static_cast<void *>(this), GetID(), 3872 event_sp->GetType()); 3873 3874 switch (event_sp->GetType()) { 3875 case eBroadcastInternalStateControlStop: 3876 exit_now = true; 3877 break; // doing any internal state management below 3878 3879 case eBroadcastInternalStateControlPause: 3880 control_only = true; 3881 break; 3882 3883 case eBroadcastInternalStateControlResume: 3884 control_only = false; 3885 break; 3886 } 3887 3888 continue; 3889 } else if (event_sp->GetType() == eBroadcastBitInterrupt) { 3890 if (m_public_state.GetValue() == eStateAttaching) { 3891 LLDB_LOGF(log, 3892 "Process::%s (arg = %p, pid = %" PRIu64 3893 ") woke up with an interrupt while attaching - " 3894 "forwarding interrupt.", 3895 __FUNCTION__, static_cast<void *>(this), GetID()); 3896 BroadcastEvent(eBroadcastBitInterrupt, nullptr); 3897 } else if (StateIsRunningState(m_last_broadcast_state)) { 3898 LLDB_LOGF(log, 3899 "Process::%s (arg = %p, pid = %" PRIu64 3900 ") woke up with an interrupt - Halting.", 3901 __FUNCTION__, static_cast<void *>(this), GetID()); 3902 Status error = HaltPrivate(); 3903 if (error.Fail() && log) 3904 LLDB_LOGF(log, 3905 "Process::%s (arg = %p, pid = %" PRIu64 3906 ") failed to halt the process: %s", 3907 __FUNCTION__, static_cast<void *>(this), GetID(), 3908 error.AsCString()); 3909 // Halt should generate a stopped event. Make a note of the fact that 3910 // we were doing the interrupt, so we can set the interrupted flag 3911 // after we receive the event. We deliberately set this to true even if 3912 // HaltPrivate failed, so that we can interrupt on the next natural 3913 // stop. 3914 interrupt_requested = true; 3915 } else { 3916 // This can happen when someone (e.g. Process::Halt) sees that we are 3917 // running and sends an interrupt request, but the process actually 3918 // stops before we receive it. In that case, we can just ignore the 3919 // request. We use m_last_broadcast_state, because the Stopped event 3920 // may not have been popped of the event queue yet, which is when the 3921 // public state gets updated. 3922 LLDB_LOGF(log, 3923 "Process::%s ignoring interrupt as we have already stopped.", 3924 __FUNCTION__); 3925 } 3926 continue; 3927 } 3928 3929 const StateType internal_state = 3930 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 3931 3932 if (internal_state != eStateInvalid) { 3933 if (m_clear_thread_plans_on_stop && 3934 StateIsStoppedState(internal_state, true)) { 3935 m_clear_thread_plans_on_stop = false; 3936 m_thread_list.DiscardThreadPlans(); 3937 } 3938 3939 if (interrupt_requested) { 3940 if (StateIsStoppedState(internal_state, true)) { 3941 // We requested the interrupt, so mark this as such in the stop event 3942 // so clients can tell an interrupted process from a natural stop 3943 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true); 3944 interrupt_requested = false; 3945 } else if (log) { 3946 LLDB_LOGF(log, 3947 "Process::%s interrupt_requested, but a non-stopped " 3948 "state '%s' received.", 3949 __FUNCTION__, StateAsCString(internal_state)); 3950 } 3951 } 3952 3953 HandlePrivateEvent(event_sp); 3954 } 3955 3956 if (internal_state == eStateInvalid || internal_state == eStateExited || 3957 internal_state == eStateDetached) { 3958 LLDB_LOGF(log, 3959 "Process::%s (arg = %p, pid = %" PRIu64 3960 ") about to exit with internal state %s...", 3961 __FUNCTION__, static_cast<void *>(this), GetID(), 3962 StateAsCString(internal_state)); 3963 3964 break; 3965 } 3966 } 3967 3968 // Verify log is still enabled before attempting to write to it... 3969 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", 3970 __FUNCTION__, static_cast<void *>(this), GetID()); 3971 3972 // If we are a secondary thread, then the primary thread we are working for 3973 // will have already acquired the public_run_lock, and isn't done with what 3974 // it was doing yet, so don't try to change it on the way out. 3975 if (!is_secondary_thread) 3976 m_public_run_lock.SetStopped(); 3977 return {}; 3978 } 3979 3980 // Process Event Data 3981 3982 Process::ProcessEventData::ProcessEventData() 3983 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false), 3984 m_update_state(0), m_interrupted(false) {} 3985 3986 Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp, 3987 StateType state) 3988 : EventData(), m_process_wp(), m_state(state), m_restarted(false), 3989 m_update_state(0), m_interrupted(false) { 3990 if (process_sp) 3991 m_process_wp = process_sp; 3992 } 3993 3994 Process::ProcessEventData::~ProcessEventData() = default; 3995 3996 ConstString Process::ProcessEventData::GetFlavorString() { 3997 static ConstString g_flavor("Process::ProcessEventData"); 3998 return g_flavor; 3999 } 4000 4001 ConstString Process::ProcessEventData::GetFlavor() const { 4002 return ProcessEventData::GetFlavorString(); 4003 } 4004 4005 bool Process::ProcessEventData::ShouldStop(Event *event_ptr, 4006 bool &found_valid_stopinfo) { 4007 found_valid_stopinfo = false; 4008 4009 ProcessSP process_sp(m_process_wp.lock()); 4010 if (!process_sp) 4011 return false; 4012 4013 ThreadList &curr_thread_list = process_sp->GetThreadList(); 4014 uint32_t num_threads = curr_thread_list.GetSize(); 4015 uint32_t idx; 4016 4017 // The actions might change one of the thread's stop_info's opinions about 4018 // whether we should stop the process, so we need to query that as we go. 4019 4020 // One other complication here, is that we try to catch any case where the 4021 // target has run (except for expressions) and immediately exit, but if we 4022 // get that wrong (which is possible) then the thread list might have 4023 // changed, and that would cause our iteration here to crash. We could 4024 // make a copy of the thread list, but we'd really like to also know if it 4025 // has changed at all, so we make up a vector of the thread ID's and check 4026 // what we get back against this list & bag out if anything differs. 4027 ThreadList not_suspended_thread_list(process_sp.get()); 4028 std::vector<uint32_t> thread_index_array(num_threads); 4029 uint32_t not_suspended_idx = 0; 4030 for (idx = 0; idx < num_threads; ++idx) { 4031 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx); 4032 4033 /* 4034 Filter out all suspended threads, they could not be the reason 4035 of stop and no need to perform any actions on them. 4036 */ 4037 if (thread_sp->GetResumeState() != eStateSuspended) { 4038 not_suspended_thread_list.AddThread(thread_sp); 4039 thread_index_array[not_suspended_idx] = thread_sp->GetIndexID(); 4040 not_suspended_idx++; 4041 } 4042 } 4043 4044 // Use this to track whether we should continue from here. We will only 4045 // continue the target running if no thread says we should stop. Of course 4046 // if some thread's PerformAction actually sets the target running, then it 4047 // doesn't matter what the other threads say... 4048 4049 bool still_should_stop = false; 4050 4051 // Sometimes - for instance if we have a bug in the stub we are talking to, 4052 // we stop but no thread has a valid stop reason. In that case we should 4053 // just stop, because we have no way of telling what the right thing to do 4054 // is, and it's better to let the user decide than continue behind their 4055 // backs. 4056 4057 for (idx = 0; idx < not_suspended_thread_list.GetSize(); ++idx) { 4058 curr_thread_list = process_sp->GetThreadList(); 4059 if (curr_thread_list.GetSize() != num_threads) { 4060 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | 4061 LIBLLDB_LOG_PROCESS)); 4062 LLDB_LOGF( 4063 log, 4064 "Number of threads changed from %u to %u while processing event.", 4065 num_threads, curr_thread_list.GetSize()); 4066 break; 4067 } 4068 4069 lldb::ThreadSP thread_sp = not_suspended_thread_list.GetThreadAtIndex(idx); 4070 4071 if (thread_sp->GetIndexID() != thread_index_array[idx]) { 4072 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | 4073 LIBLLDB_LOG_PROCESS)); 4074 LLDB_LOGF(log, 4075 "The thread at position %u changed from %u to %u while " 4076 "processing event.", 4077 idx, thread_index_array[idx], thread_sp->GetIndexID()); 4078 break; 4079 } 4080 4081 StopInfoSP stop_info_sp = thread_sp->GetStopInfo(); 4082 if (stop_info_sp && stop_info_sp->IsValid()) { 4083 found_valid_stopinfo = true; 4084 bool this_thread_wants_to_stop; 4085 if (stop_info_sp->GetOverrideShouldStop()) { 4086 this_thread_wants_to_stop = 4087 stop_info_sp->GetOverriddenShouldStopValue(); 4088 } else { 4089 stop_info_sp->PerformAction(event_ptr); 4090 // The stop action might restart the target. If it does, then we 4091 // want to mark that in the event so that whoever is receiving it 4092 // will know to wait for the running event and reflect that state 4093 // appropriately. We also need to stop processing actions, since they 4094 // aren't expecting the target to be running. 4095 4096 // FIXME: we might have run. 4097 if (stop_info_sp->HasTargetRunSinceMe()) { 4098 SetRestarted(true); 4099 break; 4100 } 4101 4102 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr); 4103 } 4104 4105 if (!still_should_stop) 4106 still_should_stop = this_thread_wants_to_stop; 4107 } 4108 } 4109 4110 return still_should_stop; 4111 } 4112 4113 void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) { 4114 ProcessSP process_sp(m_process_wp.lock()); 4115 4116 if (!process_sp) 4117 return; 4118 4119 // This function gets called twice for each event, once when the event gets 4120 // pulled off of the private process event queue, and then any number of 4121 // times, first when it gets pulled off of the public event queue, then other 4122 // times when we're pretending that this is where we stopped at the end of 4123 // expression evaluation. m_update_state is used to distinguish these three 4124 // cases; it is 0 when we're just pulling it off for private handling, and > 4125 // 1 for expression evaluation, and we don't want to do the breakpoint 4126 // command handling then. 4127 if (m_update_state != 1) 4128 return; 4129 4130 process_sp->SetPublicState( 4131 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr)); 4132 4133 if (m_state == eStateStopped && !m_restarted) { 4134 // Let process subclasses know we are about to do a public stop and do 4135 // anything they might need to in order to speed up register and memory 4136 // accesses. 4137 process_sp->WillPublicStop(); 4138 } 4139 4140 // If this is a halt event, even if the halt stopped with some reason other 4141 // than a plain interrupt (e.g. we had already stopped for a breakpoint when 4142 // the halt request came through) don't do the StopInfo actions, as they may 4143 // end up restarting the process. 4144 if (m_interrupted) 4145 return; 4146 4147 // If we're not stopped or have restarted, then skip the StopInfo actions: 4148 if (m_state != eStateStopped || m_restarted) { 4149 return; 4150 } 4151 4152 bool does_anybody_have_an_opinion = false; 4153 bool still_should_stop = ShouldStop(event_ptr, does_anybody_have_an_opinion); 4154 4155 if (GetRestarted()) { 4156 return; 4157 } 4158 4159 if (!still_should_stop && does_anybody_have_an_opinion) { 4160 // We've been asked to continue, so do that here. 4161 SetRestarted(true); 4162 // Use the public resume method here, since this is just extending a 4163 // public resume. 4164 process_sp->PrivateResume(); 4165 } else { 4166 bool hijacked = process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) && 4167 !process_sp->StateChangedIsHijackedForSynchronousResume(); 4168 4169 if (!hijacked) { 4170 // If we didn't restart, run the Stop Hooks here. 4171 // Don't do that if state changed events aren't hooked up to the 4172 // public (or SyncResume) broadcasters. StopHooks are just for 4173 // real public stops. They might also restart the target, 4174 // so watch for that. 4175 process_sp->GetTarget().RunStopHooks(); 4176 if (process_sp->GetPrivateState() == eStateRunning) 4177 SetRestarted(true); 4178 } 4179 } 4180 } 4181 4182 void Process::ProcessEventData::Dump(Stream *s) const { 4183 ProcessSP process_sp(m_process_wp.lock()); 4184 4185 if (process_sp) 4186 s->Printf(" process = %p (pid = %" PRIu64 "), ", 4187 static_cast<void *>(process_sp.get()), process_sp->GetID()); 4188 else 4189 s->PutCString(" process = NULL, "); 4190 4191 s->Printf("state = %s", StateAsCString(GetState())); 4192 } 4193 4194 const Process::ProcessEventData * 4195 Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) { 4196 if (event_ptr) { 4197 const EventData *event_data = event_ptr->GetData(); 4198 if (event_data && 4199 event_data->GetFlavor() == ProcessEventData::GetFlavorString()) 4200 return static_cast<const ProcessEventData *>(event_ptr->GetData()); 4201 } 4202 return nullptr; 4203 } 4204 4205 ProcessSP 4206 Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) { 4207 ProcessSP process_sp; 4208 const ProcessEventData *data = GetEventDataFromEvent(event_ptr); 4209 if (data) 4210 process_sp = data->GetProcessSP(); 4211 return process_sp; 4212 } 4213 4214 StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) { 4215 const ProcessEventData *data = GetEventDataFromEvent(event_ptr); 4216 if (data == nullptr) 4217 return eStateInvalid; 4218 else 4219 return data->GetState(); 4220 } 4221 4222 bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) { 4223 const ProcessEventData *data = GetEventDataFromEvent(event_ptr); 4224 if (data == nullptr) 4225 return false; 4226 else 4227 return data->GetRestarted(); 4228 } 4229 4230 void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr, 4231 bool new_value) { 4232 ProcessEventData *data = 4233 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4234 if (data != nullptr) 4235 data->SetRestarted(new_value); 4236 } 4237 4238 size_t 4239 Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) { 4240 ProcessEventData *data = 4241 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4242 if (data != nullptr) 4243 return data->GetNumRestartedReasons(); 4244 else 4245 return 0; 4246 } 4247 4248 const char * 4249 Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, 4250 size_t idx) { 4251 ProcessEventData *data = 4252 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4253 if (data != nullptr) 4254 return data->GetRestartedReasonAtIndex(idx); 4255 else 4256 return nullptr; 4257 } 4258 4259 void Process::ProcessEventData::AddRestartedReason(Event *event_ptr, 4260 const char *reason) { 4261 ProcessEventData *data = 4262 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4263 if (data != nullptr) 4264 data->AddRestartedReason(reason); 4265 } 4266 4267 bool Process::ProcessEventData::GetInterruptedFromEvent( 4268 const Event *event_ptr) { 4269 const ProcessEventData *data = GetEventDataFromEvent(event_ptr); 4270 if (data == nullptr) 4271 return false; 4272 else 4273 return data->GetInterrupted(); 4274 } 4275 4276 void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr, 4277 bool new_value) { 4278 ProcessEventData *data = 4279 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4280 if (data != nullptr) 4281 data->SetInterrupted(new_value); 4282 } 4283 4284 bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) { 4285 ProcessEventData *data = 4286 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4287 if (data) { 4288 data->SetUpdateStateOnRemoval(); 4289 return true; 4290 } 4291 return false; 4292 } 4293 4294 lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); } 4295 4296 void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) { 4297 exe_ctx.SetTargetPtr(&GetTarget()); 4298 exe_ctx.SetProcessPtr(this); 4299 exe_ctx.SetThreadPtr(nullptr); 4300 exe_ctx.SetFramePtr(nullptr); 4301 } 4302 4303 // uint32_t 4304 // Process::ListProcessesMatchingName (const char *name, StringList &matches, 4305 // std::vector<lldb::pid_t> &pids) 4306 //{ 4307 // return 0; 4308 //} 4309 // 4310 // ArchSpec 4311 // Process::GetArchSpecForExistingProcess (lldb::pid_t pid) 4312 //{ 4313 // return Host::GetArchSpecForExistingProcess (pid); 4314 //} 4315 // 4316 // ArchSpec 4317 // Process::GetArchSpecForExistingProcess (const char *process_name) 4318 //{ 4319 // return Host::GetArchSpecForExistingProcess (process_name); 4320 //} 4321 4322 void Process::AppendSTDOUT(const char *s, size_t len) { 4323 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex); 4324 m_stdout_data.append(s, len); 4325 BroadcastEventIfUnique(eBroadcastBitSTDOUT, 4326 new ProcessEventData(shared_from_this(), GetState())); 4327 } 4328 4329 void Process::AppendSTDERR(const char *s, size_t len) { 4330 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex); 4331 m_stderr_data.append(s, len); 4332 BroadcastEventIfUnique(eBroadcastBitSTDERR, 4333 new ProcessEventData(shared_from_this(), GetState())); 4334 } 4335 4336 void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) { 4337 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex); 4338 m_profile_data.push_back(one_profile_data); 4339 BroadcastEventIfUnique(eBroadcastBitProfileData, 4340 new ProcessEventData(shared_from_this(), GetState())); 4341 } 4342 4343 void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp, 4344 const StructuredDataPluginSP &plugin_sp) { 4345 BroadcastEvent( 4346 eBroadcastBitStructuredData, 4347 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp)); 4348 } 4349 4350 StructuredDataPluginSP 4351 Process::GetStructuredDataPlugin(ConstString type_name) const { 4352 auto find_it = m_structured_data_plugin_map.find(type_name); 4353 if (find_it != m_structured_data_plugin_map.end()) 4354 return find_it->second; 4355 else 4356 return StructuredDataPluginSP(); 4357 } 4358 4359 size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) { 4360 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex); 4361 if (m_profile_data.empty()) 4362 return 0; 4363 4364 std::string &one_profile_data = m_profile_data.front(); 4365 size_t bytes_available = one_profile_data.size(); 4366 if (bytes_available > 0) { 4367 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4368 LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")", 4369 static_cast<void *>(buf), static_cast<uint64_t>(buf_size)); 4370 if (bytes_available > buf_size) { 4371 memcpy(buf, one_profile_data.c_str(), buf_size); 4372 one_profile_data.erase(0, buf_size); 4373 bytes_available = buf_size; 4374 } else { 4375 memcpy(buf, one_profile_data.c_str(), bytes_available); 4376 m_profile_data.erase(m_profile_data.begin()); 4377 } 4378 } 4379 return bytes_available; 4380 } 4381 4382 // Process STDIO 4383 4384 size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) { 4385 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex); 4386 size_t bytes_available = m_stdout_data.size(); 4387 if (bytes_available > 0) { 4388 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4389 LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", 4390 static_cast<void *>(buf), static_cast<uint64_t>(buf_size)); 4391 if (bytes_available > buf_size) { 4392 memcpy(buf, m_stdout_data.c_str(), buf_size); 4393 m_stdout_data.erase(0, buf_size); 4394 bytes_available = buf_size; 4395 } else { 4396 memcpy(buf, m_stdout_data.c_str(), bytes_available); 4397 m_stdout_data.clear(); 4398 } 4399 } 4400 return bytes_available; 4401 } 4402 4403 size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) { 4404 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex); 4405 size_t bytes_available = m_stderr_data.size(); 4406 if (bytes_available > 0) { 4407 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4408 LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", 4409 static_cast<void *>(buf), static_cast<uint64_t>(buf_size)); 4410 if (bytes_available > buf_size) { 4411 memcpy(buf, m_stderr_data.c_str(), buf_size); 4412 m_stderr_data.erase(0, buf_size); 4413 bytes_available = buf_size; 4414 } else { 4415 memcpy(buf, m_stderr_data.c_str(), bytes_available); 4416 m_stderr_data.clear(); 4417 } 4418 } 4419 return bytes_available; 4420 } 4421 4422 void Process::STDIOReadThreadBytesReceived(void *baton, const void *src, 4423 size_t src_len) { 4424 Process *process = (Process *)baton; 4425 process->AppendSTDOUT(static_cast<const char *>(src), src_len); 4426 } 4427 4428 class IOHandlerProcessSTDIO : public IOHandler { 4429 public: 4430 IOHandlerProcessSTDIO(Process *process, int write_fd) 4431 : IOHandler(process->GetTarget().GetDebugger(), 4432 IOHandler::Type::ProcessIO), 4433 m_process(process), 4434 m_read_file(GetInputFD(), File::eOpenOptionRead, false), 4435 m_write_file(write_fd, File::eOpenOptionWrite, false) { 4436 m_pipe.CreateNew(false); 4437 } 4438 4439 ~IOHandlerProcessSTDIO() override = default; 4440 4441 // Each IOHandler gets to run until it is done. It should read data from the 4442 // "in" and place output into "out" and "err and return when done. 4443 void Run() override { 4444 if (!m_read_file.IsValid() || !m_write_file.IsValid() || 4445 !m_pipe.CanRead() || !m_pipe.CanWrite()) { 4446 SetIsDone(true); 4447 return; 4448 } 4449 4450 SetIsDone(false); 4451 const int read_fd = m_read_file.GetDescriptor(); 4452 TerminalState terminal_state; 4453 terminal_state.Save(read_fd, false); 4454 Terminal terminal(read_fd); 4455 terminal.SetCanonical(false); 4456 terminal.SetEcho(false); 4457 // FD_ZERO, FD_SET are not supported on windows 4458 #ifndef _WIN32 4459 const int pipe_read_fd = m_pipe.GetReadFileDescriptor(); 4460 m_is_running = true; 4461 while (!GetIsDone()) { 4462 SelectHelper select_helper; 4463 select_helper.FDSetRead(read_fd); 4464 select_helper.FDSetRead(pipe_read_fd); 4465 Status error = select_helper.Select(); 4466 4467 if (error.Fail()) { 4468 SetIsDone(true); 4469 } else { 4470 char ch = 0; 4471 size_t n; 4472 if (select_helper.FDIsSetRead(read_fd)) { 4473 n = 1; 4474 if (m_read_file.Read(&ch, n).Success() && n == 1) { 4475 if (m_write_file.Write(&ch, n).Fail() || n != 1) 4476 SetIsDone(true); 4477 } else 4478 SetIsDone(true); 4479 } 4480 if (select_helper.FDIsSetRead(pipe_read_fd)) { 4481 size_t bytes_read; 4482 // Consume the interrupt byte 4483 Status error = m_pipe.Read(&ch, 1, bytes_read); 4484 if (error.Success()) { 4485 switch (ch) { 4486 case 'q': 4487 SetIsDone(true); 4488 break; 4489 case 'i': 4490 if (StateIsRunningState(m_process->GetState())) 4491 m_process->SendAsyncInterrupt(); 4492 break; 4493 } 4494 } 4495 } 4496 } 4497 } 4498 m_is_running = false; 4499 #endif 4500 terminal_state.Restore(); 4501 } 4502 4503 void Cancel() override { 4504 SetIsDone(true); 4505 // Only write to our pipe to cancel if we are in 4506 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that 4507 // is being run from the command interpreter: 4508 // 4509 // (lldb) step_process_thousands_of_times 4510 // 4511 // In this case the command interpreter will be in the middle of handling 4512 // the command and if the process pushes and pops the IOHandler thousands 4513 // of times, we can end up writing to m_pipe without ever consuming the 4514 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up 4515 // deadlocking when the pipe gets fed up and blocks until data is consumed. 4516 if (m_is_running) { 4517 char ch = 'q'; // Send 'q' for quit 4518 size_t bytes_written = 0; 4519 m_pipe.Write(&ch, 1, bytes_written); 4520 } 4521 } 4522 4523 bool Interrupt() override { 4524 // Do only things that are safe to do in an interrupt context (like in a 4525 // SIGINT handler), like write 1 byte to a file descriptor. This will 4526 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte 4527 // that was written to the pipe and then call 4528 // m_process->SendAsyncInterrupt() from a much safer location in code. 4529 if (m_active) { 4530 char ch = 'i'; // Send 'i' for interrupt 4531 size_t bytes_written = 0; 4532 Status result = m_pipe.Write(&ch, 1, bytes_written); 4533 return result.Success(); 4534 } else { 4535 // This IOHandler might be pushed on the stack, but not being run 4536 // currently so do the right thing if we aren't actively watching for 4537 // STDIN by sending the interrupt to the process. Otherwise the write to 4538 // the pipe above would do nothing. This can happen when the command 4539 // interpreter is running and gets a "expression ...". It will be on the 4540 // IOHandler thread and sending the input is complete to the delegate 4541 // which will cause the expression to run, which will push the process IO 4542 // handler, but not run it. 4543 4544 if (StateIsRunningState(m_process->GetState())) { 4545 m_process->SendAsyncInterrupt(); 4546 return true; 4547 } 4548 } 4549 return false; 4550 } 4551 4552 void GotEOF() override {} 4553 4554 protected: 4555 Process *m_process; 4556 NativeFile m_read_file; // Read from this file (usually actual STDIN for LLDB 4557 NativeFile m_write_file; // Write to this file (usually the master pty for 4558 // getting io to debuggee) 4559 Pipe m_pipe; 4560 std::atomic<bool> m_is_running{false}; 4561 }; 4562 4563 void Process::SetSTDIOFileDescriptor(int fd) { 4564 // First set up the Read Thread for reading/handling process I/O 4565 m_stdio_communication.SetConnection( 4566 std::make_unique<ConnectionFileDescriptor>(fd, true)); 4567 if (m_stdio_communication.IsConnected()) { 4568 m_stdio_communication.SetReadThreadBytesReceivedCallback( 4569 STDIOReadThreadBytesReceived, this); 4570 m_stdio_communication.StartReadThread(); 4571 4572 // Now read thread is set up, set up input reader. 4573 4574 if (!m_process_input_reader) 4575 m_process_input_reader = 4576 std::make_shared<IOHandlerProcessSTDIO>(this, fd); 4577 } 4578 } 4579 4580 bool Process::ProcessIOHandlerIsActive() { 4581 IOHandlerSP io_handler_sp(m_process_input_reader); 4582 if (io_handler_sp) 4583 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp); 4584 return false; 4585 } 4586 bool Process::PushProcessIOHandler() { 4587 IOHandlerSP io_handler_sp(m_process_input_reader); 4588 if (io_handler_sp) { 4589 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4590 LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__); 4591 4592 io_handler_sp->SetIsDone(false); 4593 // If we evaluate an utility function, then we don't cancel the current 4594 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the 4595 // existing IOHandler that potentially provides the user interface (e.g. 4596 // the IOHandler for Editline). 4597 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction(); 4598 GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp, 4599 cancel_top_handler); 4600 return true; 4601 } 4602 return false; 4603 } 4604 4605 bool Process::PopProcessIOHandler() { 4606 IOHandlerSP io_handler_sp(m_process_input_reader); 4607 if (io_handler_sp) 4608 return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp); 4609 return false; 4610 } 4611 4612 // The process needs to know about installed plug-ins 4613 void Process::SettingsInitialize() { Thread::SettingsInitialize(); } 4614 4615 void Process::SettingsTerminate() { Thread::SettingsTerminate(); } 4616 4617 namespace { 4618 // RestorePlanState is used to record the "is private", "is master" and "okay 4619 // to discard" fields of the plan we are running, and reset it on Clean or on 4620 // destruction. It will only reset the state once, so you can call Clean and 4621 // then monkey with the state and it won't get reset on you again. 4622 4623 class RestorePlanState { 4624 public: 4625 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp) 4626 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) { 4627 if (m_thread_plan_sp) { 4628 m_private = m_thread_plan_sp->GetPrivate(); 4629 m_is_master = m_thread_plan_sp->IsMasterPlan(); 4630 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard(); 4631 } 4632 } 4633 4634 ~RestorePlanState() { Clean(); } 4635 4636 void Clean() { 4637 if (!m_already_reset && m_thread_plan_sp) { 4638 m_already_reset = true; 4639 m_thread_plan_sp->SetPrivate(m_private); 4640 m_thread_plan_sp->SetIsMasterPlan(m_is_master); 4641 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard); 4642 } 4643 } 4644 4645 private: 4646 lldb::ThreadPlanSP m_thread_plan_sp; 4647 bool m_already_reset; 4648 bool m_private; 4649 bool m_is_master; 4650 bool m_okay_to_discard; 4651 }; 4652 } // anonymous namespace 4653 4654 static microseconds 4655 GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) { 4656 const milliseconds default_one_thread_timeout(250); 4657 4658 // If the overall wait is forever, then we don't need to worry about it. 4659 if (!options.GetTimeout()) { 4660 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout() 4661 : default_one_thread_timeout; 4662 } 4663 4664 // If the one thread timeout is set, use it. 4665 if (options.GetOneThreadTimeout()) 4666 return *options.GetOneThreadTimeout(); 4667 4668 // Otherwise use half the total timeout, bounded by the 4669 // default_one_thread_timeout. 4670 return std::min<microseconds>(default_one_thread_timeout, 4671 *options.GetTimeout() / 2); 4672 } 4673 4674 static Timeout<std::micro> 4675 GetExpressionTimeout(const EvaluateExpressionOptions &options, 4676 bool before_first_timeout) { 4677 // If we are going to run all threads the whole time, or if we are only going 4678 // to run one thread, we can just return the overall timeout. 4679 if (!options.GetStopOthers() || !options.GetTryAllThreads()) 4680 return options.GetTimeout(); 4681 4682 if (before_first_timeout) 4683 return GetOneThreadExpressionTimeout(options); 4684 4685 if (!options.GetTimeout()) 4686 return llvm::None; 4687 else 4688 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options); 4689 } 4690 4691 static llvm::Optional<ExpressionResults> 4692 HandleStoppedEvent(lldb::tid_t thread_id, const ThreadPlanSP &thread_plan_sp, 4693 RestorePlanState &restorer, const EventSP &event_sp, 4694 EventSP &event_to_broadcast_sp, 4695 const EvaluateExpressionOptions &options, 4696 bool handle_interrupts) { 4697 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS); 4698 4699 ThreadSP thread_sp = thread_plan_sp->GetTarget() 4700 .GetProcessSP() 4701 ->GetThreadList() 4702 .FindThreadByID(thread_id); 4703 if (!thread_sp) { 4704 LLDB_LOG(log, 4705 "The thread on which we were running the " 4706 "expression: tid = {0}, exited while " 4707 "the expression was running.", 4708 thread_id); 4709 return eExpressionThreadVanished; 4710 } 4711 4712 ThreadPlanSP plan = thread_sp->GetCompletedPlan(); 4713 if (plan == thread_plan_sp && plan->PlanSucceeded()) { 4714 LLDB_LOG(log, "execution completed successfully"); 4715 4716 // Restore the plan state so it will get reported as intended when we are 4717 // done. 4718 restorer.Clean(); 4719 return eExpressionCompleted; 4720 } 4721 4722 StopInfoSP stop_info_sp = thread_sp->GetStopInfo(); 4723 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint && 4724 stop_info_sp->ShouldNotify(event_sp.get())) { 4725 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription()); 4726 if (!options.DoesIgnoreBreakpoints()) { 4727 // Restore the plan state and then force Private to false. We are going 4728 // to stop because of this plan so we need it to become a public plan or 4729 // it won't report correctly when we continue to its termination later 4730 // on. 4731 restorer.Clean(); 4732 thread_plan_sp->SetPrivate(false); 4733 event_to_broadcast_sp = event_sp; 4734 } 4735 return eExpressionHitBreakpoint; 4736 } 4737 4738 if (!handle_interrupts && 4739 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get())) 4740 return llvm::None; 4741 4742 LLDB_LOG(log, "thread plan did not successfully complete"); 4743 if (!options.DoesUnwindOnError()) 4744 event_to_broadcast_sp = event_sp; 4745 return eExpressionInterrupted; 4746 } 4747 4748 ExpressionResults 4749 Process::RunThreadPlan(ExecutionContext &exe_ctx, 4750 lldb::ThreadPlanSP &thread_plan_sp, 4751 const EvaluateExpressionOptions &options, 4752 DiagnosticManager &diagnostic_manager) { 4753 ExpressionResults return_value = eExpressionSetupError; 4754 4755 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock); 4756 4757 if (!thread_plan_sp) { 4758 diagnostic_manager.PutString( 4759 eDiagnosticSeverityError, 4760 "RunThreadPlan called with empty thread plan."); 4761 return eExpressionSetupError; 4762 } 4763 4764 if (!thread_plan_sp->ValidatePlan(nullptr)) { 4765 diagnostic_manager.PutString( 4766 eDiagnosticSeverityError, 4767 "RunThreadPlan called with an invalid thread plan."); 4768 return eExpressionSetupError; 4769 } 4770 4771 if (exe_ctx.GetProcessPtr() != this) { 4772 diagnostic_manager.PutString(eDiagnosticSeverityError, 4773 "RunThreadPlan called on wrong process."); 4774 return eExpressionSetupError; 4775 } 4776 4777 Thread *thread = exe_ctx.GetThreadPtr(); 4778 if (thread == nullptr) { 4779 diagnostic_manager.PutString(eDiagnosticSeverityError, 4780 "RunThreadPlan called with invalid thread."); 4781 return eExpressionSetupError; 4782 } 4783 4784 // Record the thread's id so we can tell when a thread we were using 4785 // to run the expression exits during the expression evaluation. 4786 lldb::tid_t expr_thread_id = thread->GetID(); 4787 4788 // We need to change some of the thread plan attributes for the thread plan 4789 // runner. This will restore them when we are done: 4790 4791 RestorePlanState thread_plan_restorer(thread_plan_sp); 4792 4793 // We rely on the thread plan we are running returning "PlanCompleted" if 4794 // when it successfully completes. For that to be true the plan can't be 4795 // private - since private plans suppress themselves in the GetCompletedPlan 4796 // call. 4797 4798 thread_plan_sp->SetPrivate(false); 4799 4800 // The plans run with RunThreadPlan also need to be terminal master plans or 4801 // when they are done we will end up asking the plan above us whether we 4802 // should stop, which may give the wrong answer. 4803 4804 thread_plan_sp->SetIsMasterPlan(true); 4805 thread_plan_sp->SetOkayToDiscard(false); 4806 4807 // If we are running some utility expression for LLDB, we now have to mark 4808 // this in the ProcesModID of this process. This RAII takes care of marking 4809 // and reverting the mark it once we are done running the expression. 4810 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr); 4811 4812 if (m_private_state.GetValue() != eStateStopped) { 4813 diagnostic_manager.PutString( 4814 eDiagnosticSeverityError, 4815 "RunThreadPlan called while the private state was not stopped."); 4816 return eExpressionSetupError; 4817 } 4818 4819 // Save the thread & frame from the exe_ctx for restoration after we run 4820 const uint32_t thread_idx_id = thread->GetIndexID(); 4821 StackFrameSP selected_frame_sp = thread->GetSelectedFrame(); 4822 if (!selected_frame_sp) { 4823 thread->SetSelectedFrame(nullptr); 4824 selected_frame_sp = thread->GetSelectedFrame(); 4825 if (!selected_frame_sp) { 4826 diagnostic_manager.Printf( 4827 eDiagnosticSeverityError, 4828 "RunThreadPlan called without a selected frame on thread %d", 4829 thread_idx_id); 4830 return eExpressionSetupError; 4831 } 4832 } 4833 4834 // Make sure the timeout values make sense. The one thread timeout needs to 4835 // be smaller than the overall timeout. 4836 if (options.GetOneThreadTimeout() && options.GetTimeout() && 4837 *options.GetTimeout() < *options.GetOneThreadTimeout()) { 4838 diagnostic_manager.PutString(eDiagnosticSeverityError, 4839 "RunThreadPlan called with one thread " 4840 "timeout greater than total timeout"); 4841 return eExpressionSetupError; 4842 } 4843 4844 StackID ctx_frame_id = selected_frame_sp->GetStackID(); 4845 4846 // N.B. Running the target may unset the currently selected thread and frame. 4847 // We don't want to do that either, so we should arrange to reset them as 4848 // well. 4849 4850 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread(); 4851 4852 uint32_t selected_tid; 4853 StackID selected_stack_id; 4854 if (selected_thread_sp) { 4855 selected_tid = selected_thread_sp->GetIndexID(); 4856 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID(); 4857 } else { 4858 selected_tid = LLDB_INVALID_THREAD_ID; 4859 } 4860 4861 HostThread backup_private_state_thread; 4862 lldb::StateType old_state = eStateInvalid; 4863 lldb::ThreadPlanSP stopper_base_plan_sp; 4864 4865 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | 4866 LIBLLDB_LOG_PROCESS)); 4867 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) { 4868 // Yikes, we are running on the private state thread! So we can't wait for 4869 // public events on this thread, since we are the thread that is generating 4870 // public events. The simplest thing to do is to spin up a temporary thread 4871 // to handle private state thread events while we are fielding public 4872 // events here. 4873 LLDB_LOGF(log, "Running thread plan on private state thread, spinning up " 4874 "another state thread to handle the events."); 4875 4876 backup_private_state_thread = m_private_state_thread; 4877 4878 // One other bit of business: we want to run just this thread plan and 4879 // anything it pushes, and then stop, returning control here. But in the 4880 // normal course of things, the plan above us on the stack would be given a 4881 // shot at the stop event before deciding to stop, and we don't want that. 4882 // So we insert a "stopper" base plan on the stack before the plan we want 4883 // to run. Since base plans always stop and return control to the user, 4884 // that will do just what we want. 4885 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread)); 4886 thread->QueueThreadPlan(stopper_base_plan_sp, false); 4887 // Have to make sure our public state is stopped, since otherwise the 4888 // reporting logic below doesn't work correctly. 4889 old_state = m_public_state.GetValue(); 4890 m_public_state.SetValueNoLock(eStateStopped); 4891 4892 // Now spin up the private state thread: 4893 StartPrivateStateThread(true); 4894 } 4895 4896 thread->QueueThreadPlan( 4897 thread_plan_sp, false); // This used to pass "true" does that make sense? 4898 4899 if (options.GetDebug()) { 4900 // In this case, we aren't actually going to run, we just want to stop 4901 // right away. Flush this thread so we will refetch the stacks and show the 4902 // correct backtrace. 4903 // FIXME: To make this prettier we should invent some stop reason for this, 4904 // but that 4905 // is only cosmetic, and this functionality is only of use to lldb 4906 // developers who can live with not pretty... 4907 thread->Flush(); 4908 return eExpressionStoppedForDebug; 4909 } 4910 4911 ListenerSP listener_sp( 4912 Listener::MakeListener("lldb.process.listener.run-thread-plan")); 4913 4914 lldb::EventSP event_to_broadcast_sp; 4915 4916 { 4917 // This process event hijacker Hijacks the Public events and its destructor 4918 // makes sure that the process events get restored on exit to the function. 4919 // 4920 // If the event needs to propagate beyond the hijacker (e.g., the process 4921 // exits during execution), then the event is put into 4922 // event_to_broadcast_sp for rebroadcasting. 4923 4924 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp); 4925 4926 if (log) { 4927 StreamString s; 4928 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose); 4929 LLDB_LOGF(log, 4930 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 4931 " to run thread plan \"%s\".", 4932 thread_idx_id, expr_thread_id, s.GetData()); 4933 } 4934 4935 bool got_event; 4936 lldb::EventSP event_sp; 4937 lldb::StateType stop_state = lldb::eStateInvalid; 4938 4939 bool before_first_timeout = true; // This is set to false the first time 4940 // that we have to halt the target. 4941 bool do_resume = true; 4942 bool handle_running_event = true; 4943 4944 // This is just for accounting: 4945 uint32_t num_resumes = 0; 4946 4947 // If we are going to run all threads the whole time, or if we are only 4948 // going to run one thread, then we don't need the first timeout. So we 4949 // pretend we are after the first timeout already. 4950 if (!options.GetStopOthers() || !options.GetTryAllThreads()) 4951 before_first_timeout = false; 4952 4953 LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n", 4954 options.GetStopOthers(), options.GetTryAllThreads(), 4955 before_first_timeout); 4956 4957 // This isn't going to work if there are unfetched events on the queue. Are 4958 // there cases where we might want to run the remaining events here, and 4959 // then try to call the function? That's probably being too tricky for our 4960 // own good. 4961 4962 Event *other_events = listener_sp->PeekAtNextEvent(); 4963 if (other_events != nullptr) { 4964 diagnostic_manager.PutString( 4965 eDiagnosticSeverityError, 4966 "RunThreadPlan called with pending events on the queue."); 4967 return eExpressionSetupError; 4968 } 4969 4970 // We also need to make sure that the next event is delivered. We might be 4971 // calling a function as part of a thread plan, in which case the last 4972 // delivered event could be the running event, and we don't want event 4973 // coalescing to cause us to lose OUR running event... 4974 ForceNextEventDelivery(); 4975 4976 // This while loop must exit out the bottom, there's cleanup that we need to do 4977 // when we are done. So don't call return anywhere within it. 4978 4979 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT 4980 // It's pretty much impossible to write test cases for things like: One 4981 // thread timeout expires, I go to halt, but the process already stopped on 4982 // the function call stop breakpoint. Turning on this define will make us 4983 // not fetch the first event till after the halt. So if you run a quick 4984 // function, it will have completed, and the completion event will be 4985 // waiting, when you interrupt for halt. The expression evaluation should 4986 // still succeed. 4987 bool miss_first_event = true; 4988 #endif 4989 while (true) { 4990 // We usually want to resume the process if we get to the top of the 4991 // loop. The only exception is if we get two running events with no 4992 // intervening stop, which can happen, we will just wait for then next 4993 // stop event. 4994 LLDB_LOGF(log, 4995 "Top of while loop: do_resume: %i handle_running_event: %i " 4996 "before_first_timeout: %i.", 4997 do_resume, handle_running_event, before_first_timeout); 4998 4999 if (do_resume || handle_running_event) { 5000 // Do the initial resume and wait for the running event before going 5001 // further. 5002 5003 if (do_resume) { 5004 num_resumes++; 5005 Status resume_error = PrivateResume(); 5006 if (!resume_error.Success()) { 5007 diagnostic_manager.Printf( 5008 eDiagnosticSeverityError, 5009 "couldn't resume inferior the %d time: \"%s\".", num_resumes, 5010 resume_error.AsCString()); 5011 return_value = eExpressionSetupError; 5012 break; 5013 } 5014 } 5015 5016 got_event = 5017 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout()); 5018 if (!got_event) { 5019 LLDB_LOGF(log, 5020 "Process::RunThreadPlan(): didn't get any event after " 5021 "resume %" PRIu32 ", exiting.", 5022 num_resumes); 5023 5024 diagnostic_manager.Printf(eDiagnosticSeverityError, 5025 "didn't get any event after resume %" PRIu32 5026 ", exiting.", 5027 num_resumes); 5028 return_value = eExpressionSetupError; 5029 break; 5030 } 5031 5032 stop_state = 5033 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 5034 5035 if (stop_state != eStateRunning) { 5036 bool restarted = false; 5037 5038 if (stop_state == eStateStopped) { 5039 restarted = Process::ProcessEventData::GetRestartedFromEvent( 5040 event_sp.get()); 5041 LLDB_LOGF( 5042 log, 5043 "Process::RunThreadPlan(): didn't get running event after " 5044 "resume %d, got %s instead (restarted: %i, do_resume: %i, " 5045 "handle_running_event: %i).", 5046 num_resumes, StateAsCString(stop_state), restarted, do_resume, 5047 handle_running_event); 5048 } 5049 5050 if (restarted) { 5051 // This is probably an overabundance of caution, I don't think I 5052 // should ever get a stopped & restarted event here. But if I do, 5053 // the best thing is to Halt and then get out of here. 5054 const bool clear_thread_plans = false; 5055 const bool use_run_lock = false; 5056 Halt(clear_thread_plans, use_run_lock); 5057 } 5058 5059 diagnostic_manager.Printf( 5060 eDiagnosticSeverityError, 5061 "didn't get running event after initial resume, got %s instead.", 5062 StateAsCString(stop_state)); 5063 return_value = eExpressionSetupError; 5064 break; 5065 } 5066 5067 if (log) 5068 log->PutCString("Process::RunThreadPlan(): resuming succeeded."); 5069 // We need to call the function synchronously, so spin waiting for it 5070 // to return. If we get interrupted while executing, we're going to 5071 // lose our context, and won't be able to gather the result at this 5072 // point. We set the timeout AFTER the resume, since the resume takes 5073 // some time and we don't want to charge that to the timeout. 5074 } else { 5075 if (log) 5076 log->PutCString("Process::RunThreadPlan(): waiting for next event."); 5077 } 5078 5079 do_resume = true; 5080 handle_running_event = true; 5081 5082 // Now wait for the process to stop again: 5083 event_sp.reset(); 5084 5085 Timeout<std::micro> timeout = 5086 GetExpressionTimeout(options, before_first_timeout); 5087 if (log) { 5088 if (timeout) { 5089 auto now = system_clock::now(); 5090 LLDB_LOGF(log, 5091 "Process::RunThreadPlan(): about to wait - now is %s - " 5092 "endpoint is %s", 5093 llvm::to_string(now).c_str(), 5094 llvm::to_string(now + *timeout).c_str()); 5095 } else { 5096 LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever."); 5097 } 5098 } 5099 5100 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT 5101 // See comment above... 5102 if (miss_first_event) { 5103 std::this_thread::sleep_for(std::chrono::milliseconds(1)); 5104 miss_first_event = false; 5105 got_event = false; 5106 } else 5107 #endif 5108 got_event = listener_sp->GetEvent(event_sp, timeout); 5109 5110 if (got_event) { 5111 if (event_sp) { 5112 bool keep_going = false; 5113 if (event_sp->GetType() == eBroadcastBitInterrupt) { 5114 const bool clear_thread_plans = false; 5115 const bool use_run_lock = false; 5116 Halt(clear_thread_plans, use_run_lock); 5117 return_value = eExpressionInterrupted; 5118 diagnostic_manager.PutString(eDiagnosticSeverityRemark, 5119 "execution halted by user interrupt."); 5120 LLDB_LOGF(log, "Process::RunThreadPlan(): Got interrupted by " 5121 "eBroadcastBitInterrupted, exiting."); 5122 break; 5123 } else { 5124 stop_state = 5125 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 5126 LLDB_LOGF(log, 5127 "Process::RunThreadPlan(): in while loop, got event: %s.", 5128 StateAsCString(stop_state)); 5129 5130 switch (stop_state) { 5131 case lldb::eStateStopped: { 5132 if (Process::ProcessEventData::GetRestartedFromEvent( 5133 event_sp.get())) { 5134 // If we were restarted, we just need to go back up to fetch 5135 // another event. 5136 LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and " 5137 "restart, so we'll continue waiting."); 5138 keep_going = true; 5139 do_resume = false; 5140 handle_running_event = true; 5141 } else { 5142 const bool handle_interrupts = true; 5143 return_value = *HandleStoppedEvent( 5144 expr_thread_id, thread_plan_sp, thread_plan_restorer, 5145 event_sp, event_to_broadcast_sp, options, 5146 handle_interrupts); 5147 if (return_value == eExpressionThreadVanished) 5148 keep_going = false; 5149 } 5150 } break; 5151 5152 case lldb::eStateRunning: 5153 // This shouldn't really happen, but sometimes we do get two 5154 // running events without an intervening stop, and in that case 5155 // we should just go back to waiting for the stop. 5156 do_resume = false; 5157 keep_going = true; 5158 handle_running_event = false; 5159 break; 5160 5161 default: 5162 LLDB_LOGF(log, 5163 "Process::RunThreadPlan(): execution stopped with " 5164 "unexpected state: %s.", 5165 StateAsCString(stop_state)); 5166 5167 if (stop_state == eStateExited) 5168 event_to_broadcast_sp = event_sp; 5169 5170 diagnostic_manager.PutString( 5171 eDiagnosticSeverityError, 5172 "execution stopped with unexpected state."); 5173 return_value = eExpressionInterrupted; 5174 break; 5175 } 5176 } 5177 5178 if (keep_going) 5179 continue; 5180 else 5181 break; 5182 } else { 5183 if (log) 5184 log->PutCString("Process::RunThreadPlan(): got_event was true, but " 5185 "the event pointer was null. How odd..."); 5186 return_value = eExpressionInterrupted; 5187 break; 5188 } 5189 } else { 5190 // If we didn't get an event that means we've timed out... We will 5191 // interrupt the process here. Depending on what we were asked to do 5192 // we will either exit, or try with all threads running for the same 5193 // timeout. 5194 5195 if (log) { 5196 if (options.GetTryAllThreads()) { 5197 if (before_first_timeout) { 5198 LLDB_LOG(log, 5199 "Running function with one thread timeout timed out."); 5200 } else 5201 LLDB_LOG(log, "Restarting function with all threads enabled and " 5202 "timeout: {0} timed out, abandoning execution.", 5203 timeout); 5204 } else 5205 LLDB_LOG(log, "Running function with timeout: {0} timed out, " 5206 "abandoning execution.", 5207 timeout); 5208 } 5209 5210 // It is possible that between the time we issued the Halt, and we get 5211 // around to calling Halt the target could have stopped. That's fine, 5212 // Halt will figure that out and send the appropriate Stopped event. 5213 // BUT it is also possible that we stopped & restarted (e.g. hit a 5214 // signal with "stop" set to false.) In 5215 // that case, we'll get the stopped & restarted event, and we should go 5216 // back to waiting for the Halt's stopped event. That's what this 5217 // while loop does. 5218 5219 bool back_to_top = true; 5220 uint32_t try_halt_again = 0; 5221 bool do_halt = true; 5222 const uint32_t num_retries = 5; 5223 while (try_halt_again < num_retries) { 5224 Status halt_error; 5225 if (do_halt) { 5226 LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt."); 5227 const bool clear_thread_plans = false; 5228 const bool use_run_lock = false; 5229 Halt(clear_thread_plans, use_run_lock); 5230 } 5231 if (halt_error.Success()) { 5232 if (log) 5233 log->PutCString("Process::RunThreadPlan(): Halt succeeded."); 5234 5235 got_event = 5236 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout()); 5237 5238 if (got_event) { 5239 stop_state = 5240 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 5241 if (log) { 5242 LLDB_LOGF(log, 5243 "Process::RunThreadPlan(): Stopped with event: %s", 5244 StateAsCString(stop_state)); 5245 if (stop_state == lldb::eStateStopped && 5246 Process::ProcessEventData::GetInterruptedFromEvent( 5247 event_sp.get())) 5248 log->PutCString(" Event was the Halt interruption event."); 5249 } 5250 5251 if (stop_state == lldb::eStateStopped) { 5252 if (Process::ProcessEventData::GetRestartedFromEvent( 5253 event_sp.get())) { 5254 if (log) 5255 log->PutCString("Process::RunThreadPlan(): Went to halt " 5256 "but got a restarted event, there must be " 5257 "an un-restarted stopped event so try " 5258 "again... " 5259 "Exiting wait loop."); 5260 try_halt_again++; 5261 do_halt = false; 5262 continue; 5263 } 5264 5265 // Between the time we initiated the Halt and the time we 5266 // delivered it, the process could have already finished its 5267 // job. Check that here: 5268 const bool handle_interrupts = false; 5269 if (auto result = HandleStoppedEvent( 5270 expr_thread_id, thread_plan_sp, thread_plan_restorer, 5271 event_sp, event_to_broadcast_sp, options, 5272 handle_interrupts)) { 5273 return_value = *result; 5274 back_to_top = false; 5275 break; 5276 } 5277 5278 if (!options.GetTryAllThreads()) { 5279 if (log) 5280 log->PutCString("Process::RunThreadPlan(): try_all_threads " 5281 "was false, we stopped so now we're " 5282 "quitting."); 5283 return_value = eExpressionInterrupted; 5284 back_to_top = false; 5285 break; 5286 } 5287 5288 if (before_first_timeout) { 5289 // Set all the other threads to run, and return to the top of 5290 // the loop, which will continue; 5291 before_first_timeout = false; 5292 thread_plan_sp->SetStopOthers(false); 5293 if (log) 5294 log->PutCString( 5295 "Process::RunThreadPlan(): about to resume."); 5296 5297 back_to_top = true; 5298 break; 5299 } else { 5300 // Running all threads failed, so return Interrupted. 5301 if (log) 5302 log->PutCString("Process::RunThreadPlan(): running all " 5303 "threads timed out."); 5304 return_value = eExpressionInterrupted; 5305 back_to_top = false; 5306 break; 5307 } 5308 } 5309 } else { 5310 if (log) 5311 log->PutCString("Process::RunThreadPlan(): halt said it " 5312 "succeeded, but I got no event. " 5313 "I'm getting out of here passing Interrupted."); 5314 return_value = eExpressionInterrupted; 5315 back_to_top = false; 5316 break; 5317 } 5318 } else { 5319 try_halt_again++; 5320 continue; 5321 } 5322 } 5323 5324 if (!back_to_top || try_halt_again > num_retries) 5325 break; 5326 else 5327 continue; 5328 } 5329 } // END WAIT LOOP 5330 5331 // If we had to start up a temporary private state thread to run this 5332 // thread plan, shut it down now. 5333 if (backup_private_state_thread.IsJoinable()) { 5334 StopPrivateStateThread(); 5335 Status error; 5336 m_private_state_thread = backup_private_state_thread; 5337 if (stopper_base_plan_sp) { 5338 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp); 5339 } 5340 if (old_state != eStateInvalid) 5341 m_public_state.SetValueNoLock(old_state); 5342 } 5343 5344 // If our thread went away on us, we need to get out of here without 5345 // doing any more work. We don't have to clean up the thread plan, that 5346 // will have happened when the Thread was destroyed. 5347 if (return_value == eExpressionThreadVanished) { 5348 return return_value; 5349 } 5350 5351 if (return_value != eExpressionCompleted && log) { 5352 // Print a backtrace into the log so we can figure out where we are: 5353 StreamString s; 5354 s.PutCString("Thread state after unsuccessful completion: \n"); 5355 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX); 5356 log->PutString(s.GetString()); 5357 } 5358 // Restore the thread state if we are going to discard the plan execution. 5359 // There are three cases where this could happen: 1) The execution 5360 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints 5361 // was true 3) We got some other error, and discard_on_error was true 5362 bool should_unwind = (return_value == eExpressionInterrupted && 5363 options.DoesUnwindOnError()) || 5364 (return_value == eExpressionHitBreakpoint && 5365 options.DoesIgnoreBreakpoints()); 5366 5367 if (return_value == eExpressionCompleted || should_unwind) { 5368 thread_plan_sp->RestoreThreadState(); 5369 } 5370 5371 // Now do some processing on the results of the run: 5372 if (return_value == eExpressionInterrupted || 5373 return_value == eExpressionHitBreakpoint) { 5374 if (log) { 5375 StreamString s; 5376 if (event_sp) 5377 event_sp->Dump(&s); 5378 else { 5379 log->PutCString("Process::RunThreadPlan(): Stop event that " 5380 "interrupted us is NULL."); 5381 } 5382 5383 StreamString ts; 5384 5385 const char *event_explanation = nullptr; 5386 5387 do { 5388 if (!event_sp) { 5389 event_explanation = "<no event>"; 5390 break; 5391 } else if (event_sp->GetType() == eBroadcastBitInterrupt) { 5392 event_explanation = "<user interrupt>"; 5393 break; 5394 } else { 5395 const Process::ProcessEventData *event_data = 5396 Process::ProcessEventData::GetEventDataFromEvent( 5397 event_sp.get()); 5398 5399 if (!event_data) { 5400 event_explanation = "<no event data>"; 5401 break; 5402 } 5403 5404 Process *process = event_data->GetProcessSP().get(); 5405 5406 if (!process) { 5407 event_explanation = "<no process>"; 5408 break; 5409 } 5410 5411 ThreadList &thread_list = process->GetThreadList(); 5412 5413 uint32_t num_threads = thread_list.GetSize(); 5414 uint32_t thread_index; 5415 5416 ts.Printf("<%u threads> ", num_threads); 5417 5418 for (thread_index = 0; thread_index < num_threads; ++thread_index) { 5419 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get(); 5420 5421 if (!thread) { 5422 ts.Printf("<?> "); 5423 continue; 5424 } 5425 5426 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID()); 5427 RegisterContext *register_context = 5428 thread->GetRegisterContext().get(); 5429 5430 if (register_context) 5431 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC()); 5432 else 5433 ts.Printf("[ip unknown] "); 5434 5435 // Show the private stop info here, the public stop info will be 5436 // from the last natural stop. 5437 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo(); 5438 if (stop_info_sp) { 5439 const char *stop_desc = stop_info_sp->GetDescription(); 5440 if (stop_desc) 5441 ts.PutCString(stop_desc); 5442 } 5443 ts.Printf(">"); 5444 } 5445 5446 event_explanation = ts.GetData(); 5447 } 5448 } while (false); 5449 5450 if (event_explanation) 5451 LLDB_LOGF(log, 5452 "Process::RunThreadPlan(): execution interrupted: %s %s", 5453 s.GetData(), event_explanation); 5454 else 5455 LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s", 5456 s.GetData()); 5457 } 5458 5459 if (should_unwind) { 5460 LLDB_LOGF(log, 5461 "Process::RunThreadPlan: ExecutionInterrupted - " 5462 "discarding thread plans up to %p.", 5463 static_cast<void *>(thread_plan_sp.get())); 5464 thread->DiscardThreadPlansUpToPlan(thread_plan_sp); 5465 } else { 5466 LLDB_LOGF(log, 5467 "Process::RunThreadPlan: ExecutionInterrupted - for " 5468 "plan: %p not discarding.", 5469 static_cast<void *>(thread_plan_sp.get())); 5470 } 5471 } else if (return_value == eExpressionSetupError) { 5472 if (log) 5473 log->PutCString("Process::RunThreadPlan(): execution set up error."); 5474 5475 if (options.DoesUnwindOnError()) { 5476 thread->DiscardThreadPlansUpToPlan(thread_plan_sp); 5477 } 5478 } else { 5479 if (thread->IsThreadPlanDone(thread_plan_sp.get())) { 5480 if (log) 5481 log->PutCString("Process::RunThreadPlan(): thread plan is done"); 5482 return_value = eExpressionCompleted; 5483 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) { 5484 if (log) 5485 log->PutCString( 5486 "Process::RunThreadPlan(): thread plan was discarded"); 5487 return_value = eExpressionDiscarded; 5488 } else { 5489 if (log) 5490 log->PutCString( 5491 "Process::RunThreadPlan(): thread plan stopped in mid course"); 5492 if (options.DoesUnwindOnError() && thread_plan_sp) { 5493 if (log) 5494 log->PutCString("Process::RunThreadPlan(): discarding thread plan " 5495 "'cause unwind_on_error is set."); 5496 thread->DiscardThreadPlansUpToPlan(thread_plan_sp); 5497 } 5498 } 5499 } 5500 5501 // Thread we ran the function in may have gone away because we ran the 5502 // target Check that it's still there, and if it is put it back in the 5503 // context. Also restore the frame in the context if it is still present. 5504 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get(); 5505 if (thread) { 5506 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id)); 5507 } 5508 5509 // Also restore the current process'es selected frame & thread, since this 5510 // function calling may be done behind the user's back. 5511 5512 if (selected_tid != LLDB_INVALID_THREAD_ID) { 5513 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) && 5514 selected_stack_id.IsValid()) { 5515 // We were able to restore the selected thread, now restore the frame: 5516 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex()); 5517 StackFrameSP old_frame_sp = 5518 GetThreadList().GetSelectedThread()->GetFrameWithStackID( 5519 selected_stack_id); 5520 if (old_frame_sp) 5521 GetThreadList().GetSelectedThread()->SetSelectedFrame( 5522 old_frame_sp.get()); 5523 } 5524 } 5525 } 5526 5527 // If the process exited during the run of the thread plan, notify everyone. 5528 5529 if (event_to_broadcast_sp) { 5530 if (log) 5531 log->PutCString("Process::RunThreadPlan(): rebroadcasting event."); 5532 BroadcastEvent(event_to_broadcast_sp); 5533 } 5534 5535 return return_value; 5536 } 5537 5538 const char *Process::ExecutionResultAsCString(ExpressionResults result) { 5539 const char *result_name = "<unknown>"; 5540 5541 switch (result) { 5542 case eExpressionCompleted: 5543 result_name = "eExpressionCompleted"; 5544 break; 5545 case eExpressionDiscarded: 5546 result_name = "eExpressionDiscarded"; 5547 break; 5548 case eExpressionInterrupted: 5549 result_name = "eExpressionInterrupted"; 5550 break; 5551 case eExpressionHitBreakpoint: 5552 result_name = "eExpressionHitBreakpoint"; 5553 break; 5554 case eExpressionSetupError: 5555 result_name = "eExpressionSetupError"; 5556 break; 5557 case eExpressionParseError: 5558 result_name = "eExpressionParseError"; 5559 break; 5560 case eExpressionResultUnavailable: 5561 result_name = "eExpressionResultUnavailable"; 5562 break; 5563 case eExpressionTimedOut: 5564 result_name = "eExpressionTimedOut"; 5565 break; 5566 case eExpressionStoppedForDebug: 5567 result_name = "eExpressionStoppedForDebug"; 5568 break; 5569 case eExpressionThreadVanished: 5570 result_name = "eExpressionThreadVanished"; 5571 } 5572 return result_name; 5573 } 5574 5575 void Process::GetStatus(Stream &strm) { 5576 const StateType state = GetState(); 5577 if (StateIsStoppedState(state, false)) { 5578 if (state == eStateExited) { 5579 int exit_status = GetExitStatus(); 5580 const char *exit_description = GetExitDescription(); 5581 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n", 5582 GetID(), exit_status, exit_status, 5583 exit_description ? exit_description : ""); 5584 } else { 5585 if (state == eStateConnected) 5586 strm.Printf("Connected to remote target.\n"); 5587 else 5588 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state)); 5589 } 5590 } else { 5591 strm.Printf("Process %" PRIu64 " is running.\n", GetID()); 5592 } 5593 } 5594 5595 size_t Process::GetThreadStatus(Stream &strm, 5596 bool only_threads_with_stop_reason, 5597 uint32_t start_frame, uint32_t num_frames, 5598 uint32_t num_frames_with_source, 5599 bool stop_format) { 5600 size_t num_thread_infos_dumped = 0; 5601 5602 // You can't hold the thread list lock while calling Thread::GetStatus. That 5603 // very well might run code (e.g. if we need it to get return values or 5604 // arguments.) For that to work the process has to be able to acquire it. 5605 // So instead copy the thread ID's, and look them up one by one: 5606 5607 uint32_t num_threads; 5608 std::vector<lldb::tid_t> thread_id_array; 5609 // Scope for thread list locker; 5610 { 5611 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex()); 5612 ThreadList &curr_thread_list = GetThreadList(); 5613 num_threads = curr_thread_list.GetSize(); 5614 uint32_t idx; 5615 thread_id_array.resize(num_threads); 5616 for (idx = 0; idx < num_threads; ++idx) 5617 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID(); 5618 } 5619 5620 for (uint32_t i = 0; i < num_threads; i++) { 5621 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i])); 5622 if (thread_sp) { 5623 if (only_threads_with_stop_reason) { 5624 StopInfoSP stop_info_sp = thread_sp->GetStopInfo(); 5625 if (!stop_info_sp || !stop_info_sp->IsValid()) 5626 continue; 5627 } 5628 thread_sp->GetStatus(strm, start_frame, num_frames, 5629 num_frames_with_source, 5630 stop_format); 5631 ++num_thread_infos_dumped; 5632 } else { 5633 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 5634 LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu64 5635 " vanished while running Thread::GetStatus."); 5636 } 5637 } 5638 return num_thread_infos_dumped; 5639 } 5640 5641 void Process::AddInvalidMemoryRegion(const LoadRange ®ion) { 5642 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize()); 5643 } 5644 5645 bool Process::RemoveInvalidMemoryRange(const LoadRange ®ion) { 5646 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), 5647 region.GetByteSize()); 5648 } 5649 5650 void Process::AddPreResumeAction(PreResumeActionCallback callback, 5651 void *baton) { 5652 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton)); 5653 } 5654 5655 bool Process::RunPreResumeActions() { 5656 bool result = true; 5657 while (!m_pre_resume_actions.empty()) { 5658 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back(); 5659 m_pre_resume_actions.pop_back(); 5660 bool this_result = action.callback(action.baton); 5661 if (result) 5662 result = this_result; 5663 } 5664 return result; 5665 } 5666 5667 void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); } 5668 5669 void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton) 5670 { 5671 PreResumeCallbackAndBaton element(callback, baton); 5672 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element); 5673 if (found_iter != m_pre_resume_actions.end()) 5674 { 5675 m_pre_resume_actions.erase(found_iter); 5676 } 5677 } 5678 5679 ProcessRunLock &Process::GetRunLock() { 5680 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) 5681 return m_private_run_lock; 5682 else 5683 return m_public_run_lock; 5684 } 5685 5686 bool Process::CurrentThreadIsPrivateStateThread() 5687 { 5688 return m_private_state_thread.EqualsThread(Host::GetCurrentThread()); 5689 } 5690 5691 5692 void Process::Flush() { 5693 m_thread_list.Flush(); 5694 m_extended_thread_list.Flush(); 5695 m_extended_thread_stop_id = 0; 5696 m_queue_list.Clear(); 5697 m_queue_list_stop_id = 0; 5698 } 5699 5700 void Process::DidExec() { 5701 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 5702 LLDB_LOGF(log, "Process::%s()", __FUNCTION__); 5703 5704 Target &target = GetTarget(); 5705 target.CleanupProcess(); 5706 target.ClearModules(false); 5707 m_dynamic_checkers_up.reset(); 5708 m_abi_sp.reset(); 5709 m_system_runtime_up.reset(); 5710 m_os_up.reset(); 5711 m_dyld_up.reset(); 5712 m_jit_loaders_up.reset(); 5713 m_image_tokens.clear(); 5714 m_allocated_memory_cache.Clear(); 5715 { 5716 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex); 5717 m_language_runtimes.clear(); 5718 } 5719 m_instrumentation_runtimes.clear(); 5720 m_thread_list.DiscardThreadPlans(); 5721 m_memory_cache.Clear(true); 5722 DoDidExec(); 5723 CompleteAttach(); 5724 // Flush the process (threads and all stack frames) after running 5725 // CompleteAttach() in case the dynamic loader loaded things in new 5726 // locations. 5727 Flush(); 5728 5729 // After we figure out what was loaded/unloaded in CompleteAttach, we need to 5730 // let the target know so it can do any cleanup it needs to. 5731 target.DidExec(); 5732 } 5733 5734 addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) { 5735 if (address == nullptr) { 5736 error.SetErrorString("Invalid address argument"); 5737 return LLDB_INVALID_ADDRESS; 5738 } 5739 5740 addr_t function_addr = LLDB_INVALID_ADDRESS; 5741 5742 addr_t addr = address->GetLoadAddress(&GetTarget()); 5743 std::map<addr_t, addr_t>::const_iterator iter = 5744 m_resolved_indirect_addresses.find(addr); 5745 if (iter != m_resolved_indirect_addresses.end()) { 5746 function_addr = (*iter).second; 5747 } else { 5748 if (!CallVoidArgVoidPtrReturn(address, function_addr)) { 5749 Symbol *symbol = address->CalculateSymbolContextSymbol(); 5750 error.SetErrorStringWithFormat( 5751 "Unable to call resolver for indirect function %s", 5752 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>"); 5753 function_addr = LLDB_INVALID_ADDRESS; 5754 } else { 5755 m_resolved_indirect_addresses.insert( 5756 std::pair<addr_t, addr_t>(addr, function_addr)); 5757 } 5758 } 5759 return function_addr; 5760 } 5761 5762 void Process::ModulesDidLoad(ModuleList &module_list) { 5763 // Inform the system runtime of the modified modules. 5764 SystemRuntime *sys_runtime = GetSystemRuntime(); 5765 if (sys_runtime) 5766 sys_runtime->ModulesDidLoad(module_list); 5767 5768 GetJITLoaders().ModulesDidLoad(module_list); 5769 5770 // Give the instrumentation runtimes a chance to be created before informing 5771 // them of the modified modules. 5772 InstrumentationRuntime::ModulesDidLoad(module_list, this, 5773 m_instrumentation_runtimes); 5774 for (auto &runtime : m_instrumentation_runtimes) 5775 runtime.second->ModulesDidLoad(module_list); 5776 5777 // Give the language runtimes a chance to be created before informing them of 5778 // the modified modules. 5779 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) { 5780 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type)) 5781 runtime->ModulesDidLoad(module_list); 5782 } 5783 5784 // If we don't have an operating system plug-in, try to load one since 5785 // loading shared libraries might cause a new one to try and load 5786 if (!m_os_up) 5787 LoadOperatingSystemPlugin(false); 5788 5789 // Inform the structured-data plugins of the modified modules. 5790 for (auto pair : m_structured_data_plugin_map) { 5791 if (pair.second) 5792 pair.second->ModulesDidLoad(*this, module_list); 5793 } 5794 } 5795 5796 void Process::PrintWarning(uint64_t warning_type, const void *repeat_key, 5797 const char *fmt, ...) { 5798 bool print_warning = true; 5799 5800 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream(); 5801 if (!stream_sp) 5802 return; 5803 5804 if (repeat_key != nullptr) { 5805 WarningsCollection::iterator it = m_warnings_issued.find(warning_type); 5806 if (it == m_warnings_issued.end()) { 5807 m_warnings_issued[warning_type] = WarningsPointerSet(); 5808 m_warnings_issued[warning_type].insert(repeat_key); 5809 } else { 5810 if (it->second.find(repeat_key) != it->second.end()) { 5811 print_warning = false; 5812 } else { 5813 it->second.insert(repeat_key); 5814 } 5815 } 5816 } 5817 5818 if (print_warning) { 5819 va_list args; 5820 va_start(args, fmt); 5821 stream_sp->PrintfVarArg(fmt, args); 5822 va_end(args); 5823 } 5824 } 5825 5826 void Process::PrintWarningOptimization(const SymbolContext &sc) { 5827 if (!GetWarningsOptimization()) 5828 return; 5829 if (!sc.module_sp) 5830 return; 5831 if (!sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function && 5832 sc.function->GetIsOptimized()) { 5833 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(), 5834 "%s was compiled with optimization - stepping may behave " 5835 "oddly; variables may not be available.\n", 5836 sc.module_sp->GetFileSpec().GetFilename().GetCString()); 5837 } 5838 } 5839 5840 void Process::PrintWarningUnsupportedLanguage(const SymbolContext &sc) { 5841 if (!GetWarningsUnsupportedLanguage()) 5842 return; 5843 if (!sc.module_sp) 5844 return; 5845 LanguageType language = sc.GetLanguage(); 5846 if (language == eLanguageTypeUnknown) 5847 return; 5848 auto type_system_or_err = sc.module_sp->GetTypeSystemForLanguage(language); 5849 if (auto err = type_system_or_err.takeError()) { 5850 llvm::consumeError(std::move(err)); 5851 PrintWarning(Process::Warnings::eWarningsUnsupportedLanguage, 5852 sc.module_sp.get(), 5853 "This version of LLDB has no plugin for the %s language. " 5854 "Inspection of frame variables will be limited.\n", 5855 Language::GetNameForLanguageType(language)); 5856 } 5857 } 5858 5859 bool Process::GetProcessInfo(ProcessInstanceInfo &info) { 5860 info.Clear(); 5861 5862 PlatformSP platform_sp = GetTarget().GetPlatform(); 5863 if (!platform_sp) 5864 return false; 5865 5866 return platform_sp->GetProcessInfo(GetID(), info); 5867 } 5868 5869 ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) { 5870 ThreadCollectionSP threads; 5871 5872 const MemoryHistorySP &memory_history = 5873 MemoryHistory::FindPlugin(shared_from_this()); 5874 5875 if (!memory_history) { 5876 return threads; 5877 } 5878 5879 threads = std::make_shared<ThreadCollection>( 5880 memory_history->GetHistoryThreads(addr)); 5881 5882 return threads; 5883 } 5884 5885 InstrumentationRuntimeSP 5886 Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) { 5887 InstrumentationRuntimeCollection::iterator pos; 5888 pos = m_instrumentation_runtimes.find(type); 5889 if (pos == m_instrumentation_runtimes.end()) { 5890 return InstrumentationRuntimeSP(); 5891 } else 5892 return (*pos).second; 5893 } 5894 5895 bool Process::GetModuleSpec(const FileSpec &module_file_spec, 5896 const ArchSpec &arch, ModuleSpec &module_spec) { 5897 module_spec.Clear(); 5898 return false; 5899 } 5900 5901 size_t Process::AddImageToken(lldb::addr_t image_ptr) { 5902 m_image_tokens.push_back(image_ptr); 5903 return m_image_tokens.size() - 1; 5904 } 5905 5906 lldb::addr_t Process::GetImagePtrFromToken(size_t token) const { 5907 if (token < m_image_tokens.size()) 5908 return m_image_tokens[token]; 5909 return LLDB_INVALID_ADDRESS; 5910 } 5911 5912 void Process::ResetImageToken(size_t token) { 5913 if (token < m_image_tokens.size()) 5914 m_image_tokens[token] = LLDB_INVALID_ADDRESS; 5915 } 5916 5917 Address 5918 Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr, 5919 AddressRange range_bounds) { 5920 Target &target = GetTarget(); 5921 DisassemblerSP disassembler_sp; 5922 InstructionList *insn_list = nullptr; 5923 5924 Address retval = default_stop_addr; 5925 5926 if (!target.GetUseFastStepping()) 5927 return retval; 5928 if (!default_stop_addr.IsValid()) 5929 return retval; 5930 5931 const char *plugin_name = nullptr; 5932 const char *flavor = nullptr; 5933 const bool prefer_file_cache = true; 5934 disassembler_sp = Disassembler::DisassembleRange( 5935 target.GetArchitecture(), plugin_name, flavor, GetTarget(), range_bounds, 5936 prefer_file_cache); 5937 if (disassembler_sp) 5938 insn_list = &disassembler_sp->GetInstructionList(); 5939 5940 if (insn_list == nullptr) { 5941 return retval; 5942 } 5943 5944 size_t insn_offset = 5945 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr); 5946 if (insn_offset == UINT32_MAX) { 5947 return retval; 5948 } 5949 5950 uint32_t branch_index = 5951 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target, 5952 false /* ignore_calls*/, 5953 nullptr); 5954 if (branch_index == UINT32_MAX) { 5955 return retval; 5956 } 5957 5958 if (branch_index > insn_offset) { 5959 Address next_branch_insn_address = 5960 insn_list->GetInstructionAtIndex(branch_index)->GetAddress(); 5961 if (next_branch_insn_address.IsValid() && 5962 range_bounds.ContainsFileAddress(next_branch_insn_address)) { 5963 retval = next_branch_insn_address; 5964 } 5965 } 5966 5967 return retval; 5968 } 5969 5970 Status 5971 Process::GetMemoryRegions(lldb_private::MemoryRegionInfos ®ion_list) { 5972 5973 Status error; 5974 5975 lldb::addr_t range_end = 0; 5976 5977 region_list.clear(); 5978 do { 5979 lldb_private::MemoryRegionInfo region_info; 5980 error = GetMemoryRegionInfo(range_end, region_info); 5981 // GetMemoryRegionInfo should only return an error if it is unimplemented. 5982 if (error.Fail()) { 5983 region_list.clear(); 5984 break; 5985 } 5986 5987 range_end = region_info.GetRange().GetRangeEnd(); 5988 if (region_info.GetMapped() == MemoryRegionInfo::eYes) { 5989 region_list.push_back(std::move(region_info)); 5990 } 5991 } while (range_end != LLDB_INVALID_ADDRESS); 5992 5993 return error; 5994 } 5995 5996 Status 5997 Process::ConfigureStructuredData(ConstString type_name, 5998 const StructuredData::ObjectSP &config_sp) { 5999 // If you get this, the Process-derived class needs to implement a method to 6000 // enable an already-reported asynchronous structured data feature. See 6001 // ProcessGDBRemote for an example implementation over gdb-remote. 6002 return Status("unimplemented"); 6003 } 6004 6005 void Process::MapSupportedStructuredDataPlugins( 6006 const StructuredData::Array &supported_type_names) { 6007 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 6008 6009 // Bail out early if there are no type names to map. 6010 if (supported_type_names.GetSize() == 0) { 6011 LLDB_LOGF(log, "Process::%s(): no structured data types supported", 6012 __FUNCTION__); 6013 return; 6014 } 6015 6016 // Convert StructuredData type names to ConstString instances. 6017 std::set<ConstString> const_type_names; 6018 6019 LLDB_LOGF(log, 6020 "Process::%s(): the process supports the following async " 6021 "structured data types:", 6022 __FUNCTION__); 6023 6024 supported_type_names.ForEach( 6025 [&const_type_names, &log](StructuredData::Object *object) { 6026 if (!object) { 6027 // Invalid - shouldn't be null objects in the array. 6028 return false; 6029 } 6030 6031 auto type_name = object->GetAsString(); 6032 if (!type_name) { 6033 // Invalid format - all type names should be strings. 6034 return false; 6035 } 6036 6037 const_type_names.insert(ConstString(type_name->GetValue())); 6038 LLDB_LOG(log, "- {0}", type_name->GetValue()); 6039 return true; 6040 }); 6041 6042 // For each StructuredDataPlugin, if the plugin handles any of the types in 6043 // the supported_type_names, map that type name to that plugin. Stop when 6044 // we've consumed all the type names. 6045 // FIXME: should we return an error if there are type names nobody 6046 // supports? 6047 for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) { 6048 auto create_instance = 6049 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex( 6050 plugin_index); 6051 if (!create_instance) 6052 break; 6053 6054 // Create the plugin. 6055 StructuredDataPluginSP plugin_sp = (*create_instance)(*this); 6056 if (!plugin_sp) { 6057 // This plugin doesn't think it can work with the process. Move on to the 6058 // next. 6059 continue; 6060 } 6061 6062 // For any of the remaining type names, map any that this plugin supports. 6063 std::vector<ConstString> names_to_remove; 6064 for (auto &type_name : const_type_names) { 6065 if (plugin_sp->SupportsStructuredDataType(type_name)) { 6066 m_structured_data_plugin_map.insert( 6067 std::make_pair(type_name, plugin_sp)); 6068 names_to_remove.push_back(type_name); 6069 LLDB_LOGF(log, 6070 "Process::%s(): using plugin %s for type name " 6071 "%s", 6072 __FUNCTION__, plugin_sp->GetPluginName().GetCString(), 6073 type_name.GetCString()); 6074 } 6075 } 6076 6077 // Remove the type names that were consumed by this plugin. 6078 for (auto &type_name : names_to_remove) 6079 const_type_names.erase(type_name); 6080 } 6081 } 6082 6083 bool Process::RouteAsyncStructuredData( 6084 const StructuredData::ObjectSP object_sp) { 6085 // Nothing to do if there's no data. 6086 if (!object_sp) 6087 return false; 6088 6089 // The contract is this must be a dictionary, so we can look up the routing 6090 // key via the top-level 'type' string value within the dictionary. 6091 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary(); 6092 if (!dictionary) 6093 return false; 6094 6095 // Grab the async structured type name (i.e. the feature/plugin name). 6096 ConstString type_name; 6097 if (!dictionary->GetValueForKeyAsString("type", type_name)) 6098 return false; 6099 6100 // Check if there's a plugin registered for this type name. 6101 auto find_it = m_structured_data_plugin_map.find(type_name); 6102 if (find_it == m_structured_data_plugin_map.end()) { 6103 // We don't have a mapping for this structured data type. 6104 return false; 6105 } 6106 6107 // Route the structured data to the plugin. 6108 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp); 6109 return true; 6110 } 6111 6112 Status Process::UpdateAutomaticSignalFiltering() { 6113 // Default implementation does nothign. 6114 // No automatic signal filtering to speak of. 6115 return Status(); 6116 } 6117 6118 UtilityFunction *Process::GetLoadImageUtilityFunction( 6119 Platform *platform, 6120 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) { 6121 if (platform != GetTarget().GetPlatform().get()) 6122 return nullptr; 6123 llvm::call_once(m_dlopen_utility_func_flag_once, 6124 [&] { m_dlopen_utility_func_up = factory(); }); 6125 return m_dlopen_utility_func_up.get(); 6126 } 6127 6128 bool Process::CallVoidArgVoidPtrReturn(const Address *address, 6129 addr_t &returned_func, 6130 bool trap_exceptions) { 6131 Thread *thread = GetThreadList().GetExpressionExecutionThread().get(); 6132 if (thread == nullptr || address == nullptr) 6133 return false; 6134 6135 EvaluateExpressionOptions options; 6136 options.SetStopOthers(true); 6137 options.SetUnwindOnError(true); 6138 options.SetIgnoreBreakpoints(true); 6139 options.SetTryAllThreads(true); 6140 options.SetDebug(false); 6141 options.SetTimeout(GetUtilityExpressionTimeout()); 6142 options.SetTrapExceptions(trap_exceptions); 6143 6144 auto type_system_or_err = 6145 GetTarget().GetScratchTypeSystemForLanguage(eLanguageTypeC); 6146 if (!type_system_or_err) { 6147 llvm::consumeError(type_system_or_err.takeError()); 6148 return false; 6149 } 6150 CompilerType void_ptr_type = 6151 type_system_or_err->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType(); 6152 lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallFunction( 6153 *thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options)); 6154 if (call_plan_sp) { 6155 DiagnosticManager diagnostics; 6156 6157 StackFrame *frame = thread->GetStackFrameAtIndex(0).get(); 6158 if (frame) { 6159 ExecutionContext exe_ctx; 6160 frame->CalculateExecutionContext(exe_ctx); 6161 ExpressionResults result = 6162 RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics); 6163 if (result == eExpressionCompleted) { 6164 returned_func = 6165 call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned( 6166 LLDB_INVALID_ADDRESS); 6167 6168 if (GetAddressByteSize() == 4) { 6169 if (returned_func == UINT32_MAX) 6170 return false; 6171 } else if (GetAddressByteSize() == 8) { 6172 if (returned_func == UINT64_MAX) 6173 return false; 6174 } 6175 return true; 6176 } 6177 } 6178 } 6179 6180 return false; 6181 } 6182