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