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 void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) { 4002 ProcessSP process_sp(m_process_wp.lock()); 4003 4004 if (!process_sp) 4005 return; 4006 4007 // This function gets called twice for each event, once when the event gets 4008 // pulled off of the private process event queue, and then any number of 4009 // times, first when it gets pulled off of the public event queue, then other 4010 // times when we're pretending that this is where we stopped at the end of 4011 // expression evaluation. m_update_state is used to distinguish these three 4012 // cases; it is 0 when we're just pulling it off for private handling, and > 4013 // 1 for expression evaluation, and we don't want to do the breakpoint 4014 // command handling then. 4015 if (m_update_state != 1) 4016 return; 4017 4018 process_sp->SetPublicState( 4019 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr)); 4020 4021 if (m_state == eStateStopped && !m_restarted) { 4022 // Let process subclasses know we are about to do a public stop and do 4023 // anything they might need to in order to speed up register and memory 4024 // accesses. 4025 process_sp->WillPublicStop(); 4026 } 4027 4028 // If this is a halt event, even if the halt stopped with some reason other 4029 // than a plain interrupt (e.g. we had already stopped for a breakpoint when 4030 // the halt request came through) don't do the StopInfo actions, as they may 4031 // end up restarting the process. 4032 if (m_interrupted) 4033 return; 4034 4035 // If we're stopped and haven't restarted, then do the StopInfo actions here: 4036 if (m_state == eStateStopped && !m_restarted) { 4037 ThreadList &curr_thread_list = process_sp->GetThreadList(); 4038 uint32_t num_threads = curr_thread_list.GetSize(); 4039 uint32_t idx; 4040 4041 // The actions might change one of the thread's stop_info's opinions about 4042 // whether we should stop the process, so we need to query that as we go. 4043 4044 // One other complication here, is that we try to catch any case where the 4045 // target has run (except for expressions) and immediately exit, but if we 4046 // get that wrong (which is possible) then the thread list might have 4047 // changed, and that would cause our iteration here to crash. We could 4048 // make a copy of the thread list, but we'd really like to also know if it 4049 // has changed at all, so we make up a vector of the thread ID's and check 4050 // what we get back against this list & bag out if anything differs. 4051 std::vector<uint32_t> thread_index_array(num_threads); 4052 for (idx = 0; idx < num_threads; ++idx) 4053 thread_index_array[idx] = 4054 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID(); 4055 4056 // Use this to track whether we should continue from here. We will only 4057 // continue the target running if no thread says we should stop. Of course 4058 // if some thread's PerformAction actually sets the target running, then it 4059 // doesn't matter what the other threads say... 4060 4061 bool still_should_stop = false; 4062 4063 // Sometimes - for instance if we have a bug in the stub we are talking to, 4064 // we stop but no thread has a valid stop reason. In that case we should 4065 // just stop, because we have no way of telling what the right thing to do 4066 // is, and it's better to let the user decide than continue behind their 4067 // backs. 4068 4069 bool does_anybody_have_an_opinion = false; 4070 4071 for (idx = 0; idx < num_threads; ++idx) { 4072 curr_thread_list = process_sp->GetThreadList(); 4073 if (curr_thread_list.GetSize() != num_threads) { 4074 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | 4075 LIBLLDB_LOG_PROCESS)); 4076 LLDB_LOGF( 4077 log, 4078 "Number of threads changed from %u to %u while processing event.", 4079 num_threads, curr_thread_list.GetSize()); 4080 break; 4081 } 4082 4083 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx); 4084 4085 if (thread_sp->GetIndexID() != thread_index_array[idx]) { 4086 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | 4087 LIBLLDB_LOG_PROCESS)); 4088 LLDB_LOGF(log, 4089 "The thread at position %u changed from %u to %u while " 4090 "processing event.", 4091 idx, thread_index_array[idx], thread_sp->GetIndexID()); 4092 break; 4093 } 4094 4095 StopInfoSP stop_info_sp = thread_sp->GetStopInfo(); 4096 if (stop_info_sp && stop_info_sp->IsValid()) { 4097 does_anybody_have_an_opinion = true; 4098 bool this_thread_wants_to_stop; 4099 if (stop_info_sp->GetOverrideShouldStop()) { 4100 this_thread_wants_to_stop = 4101 stop_info_sp->GetOverriddenShouldStopValue(); 4102 } else { 4103 stop_info_sp->PerformAction(event_ptr); 4104 // The stop action might restart the target. If it does, then we 4105 // want to mark that in the event so that whoever is receiving it 4106 // will know to wait for the running event and reflect that state 4107 // appropriately. We also need to stop processing actions, since they 4108 // aren't expecting the target to be running. 4109 4110 // FIXME: we might have run. 4111 if (stop_info_sp->HasTargetRunSinceMe()) { 4112 SetRestarted(true); 4113 break; 4114 } 4115 4116 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr); 4117 } 4118 4119 if (!still_should_stop) 4120 still_should_stop = this_thread_wants_to_stop; 4121 } 4122 } 4123 4124 if (!GetRestarted()) { 4125 if (!still_should_stop && does_anybody_have_an_opinion) { 4126 // We've been asked to continue, so do that here. 4127 SetRestarted(true); 4128 // Use the public resume method here, since this is just extending a 4129 // public resume. 4130 process_sp->PrivateResume(); 4131 } else { 4132 bool hijacked = 4133 process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) && 4134 !process_sp->StateChangedIsHijackedForSynchronousResume(); 4135 4136 if (!hijacked) { 4137 // If we didn't restart, run the Stop Hooks here. 4138 // Don't do that if state changed events aren't hooked up to the 4139 // public (or SyncResume) broadcasters. StopHooks are just for 4140 // real public stops. They might also restart the target, 4141 // so watch for that. 4142 process_sp->GetTarget().RunStopHooks(); 4143 if (process_sp->GetPrivateState() == eStateRunning) 4144 SetRestarted(true); 4145 } 4146 } 4147 } 4148 } 4149 } 4150 4151 void Process::ProcessEventData::Dump(Stream *s) const { 4152 ProcessSP process_sp(m_process_wp.lock()); 4153 4154 if (process_sp) 4155 s->Printf(" process = %p (pid = %" PRIu64 "), ", 4156 static_cast<void *>(process_sp.get()), process_sp->GetID()); 4157 else 4158 s->PutCString(" process = NULL, "); 4159 4160 s->Printf("state = %s", StateAsCString(GetState())); 4161 } 4162 4163 const Process::ProcessEventData * 4164 Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) { 4165 if (event_ptr) { 4166 const EventData *event_data = event_ptr->GetData(); 4167 if (event_data && 4168 event_data->GetFlavor() == ProcessEventData::GetFlavorString()) 4169 return static_cast<const ProcessEventData *>(event_ptr->GetData()); 4170 } 4171 return nullptr; 4172 } 4173 4174 ProcessSP 4175 Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) { 4176 ProcessSP process_sp; 4177 const ProcessEventData *data = GetEventDataFromEvent(event_ptr); 4178 if (data) 4179 process_sp = data->GetProcessSP(); 4180 return process_sp; 4181 } 4182 4183 StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) { 4184 const ProcessEventData *data = GetEventDataFromEvent(event_ptr); 4185 if (data == nullptr) 4186 return eStateInvalid; 4187 else 4188 return data->GetState(); 4189 } 4190 4191 bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) { 4192 const ProcessEventData *data = GetEventDataFromEvent(event_ptr); 4193 if (data == nullptr) 4194 return false; 4195 else 4196 return data->GetRestarted(); 4197 } 4198 4199 void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr, 4200 bool new_value) { 4201 ProcessEventData *data = 4202 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4203 if (data != nullptr) 4204 data->SetRestarted(new_value); 4205 } 4206 4207 size_t 4208 Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) { 4209 ProcessEventData *data = 4210 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4211 if (data != nullptr) 4212 return data->GetNumRestartedReasons(); 4213 else 4214 return 0; 4215 } 4216 4217 const char * 4218 Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, 4219 size_t idx) { 4220 ProcessEventData *data = 4221 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4222 if (data != nullptr) 4223 return data->GetRestartedReasonAtIndex(idx); 4224 else 4225 return nullptr; 4226 } 4227 4228 void Process::ProcessEventData::AddRestartedReason(Event *event_ptr, 4229 const char *reason) { 4230 ProcessEventData *data = 4231 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4232 if (data != nullptr) 4233 data->AddRestartedReason(reason); 4234 } 4235 4236 bool Process::ProcessEventData::GetInterruptedFromEvent( 4237 const Event *event_ptr) { 4238 const ProcessEventData *data = GetEventDataFromEvent(event_ptr); 4239 if (data == nullptr) 4240 return false; 4241 else 4242 return data->GetInterrupted(); 4243 } 4244 4245 void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr, 4246 bool new_value) { 4247 ProcessEventData *data = 4248 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4249 if (data != nullptr) 4250 data->SetInterrupted(new_value); 4251 } 4252 4253 bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) { 4254 ProcessEventData *data = 4255 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr)); 4256 if (data) { 4257 data->SetUpdateStateOnRemoval(); 4258 return true; 4259 } 4260 return false; 4261 } 4262 4263 lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); } 4264 4265 void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) { 4266 exe_ctx.SetTargetPtr(&GetTarget()); 4267 exe_ctx.SetProcessPtr(this); 4268 exe_ctx.SetThreadPtr(nullptr); 4269 exe_ctx.SetFramePtr(nullptr); 4270 } 4271 4272 // uint32_t 4273 // Process::ListProcessesMatchingName (const char *name, StringList &matches, 4274 // std::vector<lldb::pid_t> &pids) 4275 //{ 4276 // return 0; 4277 //} 4278 // 4279 // ArchSpec 4280 // Process::GetArchSpecForExistingProcess (lldb::pid_t pid) 4281 //{ 4282 // return Host::GetArchSpecForExistingProcess (pid); 4283 //} 4284 // 4285 // ArchSpec 4286 // Process::GetArchSpecForExistingProcess (const char *process_name) 4287 //{ 4288 // return Host::GetArchSpecForExistingProcess (process_name); 4289 //} 4290 4291 void Process::AppendSTDOUT(const char *s, size_t len) { 4292 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex); 4293 m_stdout_data.append(s, len); 4294 BroadcastEventIfUnique(eBroadcastBitSTDOUT, 4295 new ProcessEventData(shared_from_this(), GetState())); 4296 } 4297 4298 void Process::AppendSTDERR(const char *s, size_t len) { 4299 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex); 4300 m_stderr_data.append(s, len); 4301 BroadcastEventIfUnique(eBroadcastBitSTDERR, 4302 new ProcessEventData(shared_from_this(), GetState())); 4303 } 4304 4305 void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) { 4306 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex); 4307 m_profile_data.push_back(one_profile_data); 4308 BroadcastEventIfUnique(eBroadcastBitProfileData, 4309 new ProcessEventData(shared_from_this(), GetState())); 4310 } 4311 4312 void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp, 4313 const StructuredDataPluginSP &plugin_sp) { 4314 BroadcastEvent( 4315 eBroadcastBitStructuredData, 4316 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp)); 4317 } 4318 4319 StructuredDataPluginSP 4320 Process::GetStructuredDataPlugin(ConstString type_name) const { 4321 auto find_it = m_structured_data_plugin_map.find(type_name); 4322 if (find_it != m_structured_data_plugin_map.end()) 4323 return find_it->second; 4324 else 4325 return StructuredDataPluginSP(); 4326 } 4327 4328 size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) { 4329 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex); 4330 if (m_profile_data.empty()) 4331 return 0; 4332 4333 std::string &one_profile_data = m_profile_data.front(); 4334 size_t bytes_available = one_profile_data.size(); 4335 if (bytes_available > 0) { 4336 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4337 LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")", 4338 static_cast<void *>(buf), static_cast<uint64_t>(buf_size)); 4339 if (bytes_available > buf_size) { 4340 memcpy(buf, one_profile_data.c_str(), buf_size); 4341 one_profile_data.erase(0, buf_size); 4342 bytes_available = buf_size; 4343 } else { 4344 memcpy(buf, one_profile_data.c_str(), bytes_available); 4345 m_profile_data.erase(m_profile_data.begin()); 4346 } 4347 } 4348 return bytes_available; 4349 } 4350 4351 // Process STDIO 4352 4353 size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) { 4354 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex); 4355 size_t bytes_available = m_stdout_data.size(); 4356 if (bytes_available > 0) { 4357 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4358 LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", 4359 static_cast<void *>(buf), static_cast<uint64_t>(buf_size)); 4360 if (bytes_available > buf_size) { 4361 memcpy(buf, m_stdout_data.c_str(), buf_size); 4362 m_stdout_data.erase(0, buf_size); 4363 bytes_available = buf_size; 4364 } else { 4365 memcpy(buf, m_stdout_data.c_str(), bytes_available); 4366 m_stdout_data.clear(); 4367 } 4368 } 4369 return bytes_available; 4370 } 4371 4372 size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) { 4373 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex); 4374 size_t bytes_available = m_stderr_data.size(); 4375 if (bytes_available > 0) { 4376 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4377 LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", 4378 static_cast<void *>(buf), static_cast<uint64_t>(buf_size)); 4379 if (bytes_available > buf_size) { 4380 memcpy(buf, m_stderr_data.c_str(), buf_size); 4381 m_stderr_data.erase(0, buf_size); 4382 bytes_available = buf_size; 4383 } else { 4384 memcpy(buf, m_stderr_data.c_str(), bytes_available); 4385 m_stderr_data.clear(); 4386 } 4387 } 4388 return bytes_available; 4389 } 4390 4391 void Process::STDIOReadThreadBytesReceived(void *baton, const void *src, 4392 size_t src_len) { 4393 Process *process = (Process *)baton; 4394 process->AppendSTDOUT(static_cast<const char *>(src), src_len); 4395 } 4396 4397 class IOHandlerProcessSTDIO : public IOHandler { 4398 public: 4399 IOHandlerProcessSTDIO(Process *process, int write_fd) 4400 : IOHandler(process->GetTarget().GetDebugger(), 4401 IOHandler::Type::ProcessIO), 4402 m_process(process), 4403 m_read_file(GetInputFD(), File::eOpenOptionRead, false), 4404 m_write_file(write_fd, File::eOpenOptionWrite, false) { 4405 m_pipe.CreateNew(false); 4406 } 4407 4408 ~IOHandlerProcessSTDIO() override = default; 4409 4410 // Each IOHandler gets to run until it is done. It should read data from the 4411 // "in" and place output into "out" and "err and return when done. 4412 void Run() override { 4413 if (!m_read_file.IsValid() || !m_write_file.IsValid() || 4414 !m_pipe.CanRead() || !m_pipe.CanWrite()) { 4415 SetIsDone(true); 4416 return; 4417 } 4418 4419 SetIsDone(false); 4420 const int read_fd = m_read_file.GetDescriptor(); 4421 TerminalState terminal_state; 4422 terminal_state.Save(read_fd, false); 4423 Terminal terminal(read_fd); 4424 terminal.SetCanonical(false); 4425 terminal.SetEcho(false); 4426 // FD_ZERO, FD_SET are not supported on windows 4427 #ifndef _WIN32 4428 const int pipe_read_fd = m_pipe.GetReadFileDescriptor(); 4429 m_is_running = true; 4430 while (!GetIsDone()) { 4431 SelectHelper select_helper; 4432 select_helper.FDSetRead(read_fd); 4433 select_helper.FDSetRead(pipe_read_fd); 4434 Status error = select_helper.Select(); 4435 4436 if (error.Fail()) { 4437 SetIsDone(true); 4438 } else { 4439 char ch = 0; 4440 size_t n; 4441 if (select_helper.FDIsSetRead(read_fd)) { 4442 n = 1; 4443 if (m_read_file.Read(&ch, n).Success() && n == 1) { 4444 if (m_write_file.Write(&ch, n).Fail() || n != 1) 4445 SetIsDone(true); 4446 } else 4447 SetIsDone(true); 4448 } 4449 if (select_helper.FDIsSetRead(pipe_read_fd)) { 4450 size_t bytes_read; 4451 // Consume the interrupt byte 4452 Status error = m_pipe.Read(&ch, 1, bytes_read); 4453 if (error.Success()) { 4454 switch (ch) { 4455 case 'q': 4456 SetIsDone(true); 4457 break; 4458 case 'i': 4459 if (StateIsRunningState(m_process->GetState())) 4460 m_process->SendAsyncInterrupt(); 4461 break; 4462 } 4463 } 4464 } 4465 } 4466 } 4467 m_is_running = false; 4468 #endif 4469 terminal_state.Restore(); 4470 } 4471 4472 void Cancel() override { 4473 SetIsDone(true); 4474 // Only write to our pipe to cancel if we are in 4475 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that 4476 // is being run from the command interpreter: 4477 // 4478 // (lldb) step_process_thousands_of_times 4479 // 4480 // In this case the command interpreter will be in the middle of handling 4481 // the command and if the process pushes and pops the IOHandler thousands 4482 // of times, we can end up writing to m_pipe without ever consuming the 4483 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up 4484 // deadlocking when the pipe gets fed up and blocks until data is consumed. 4485 if (m_is_running) { 4486 char ch = 'q'; // Send 'q' for quit 4487 size_t bytes_written = 0; 4488 m_pipe.Write(&ch, 1, bytes_written); 4489 } 4490 } 4491 4492 bool Interrupt() override { 4493 // Do only things that are safe to do in an interrupt context (like in a 4494 // SIGINT handler), like write 1 byte to a file descriptor. This will 4495 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte 4496 // that was written to the pipe and then call 4497 // m_process->SendAsyncInterrupt() from a much safer location in code. 4498 if (m_active) { 4499 char ch = 'i'; // Send 'i' for interrupt 4500 size_t bytes_written = 0; 4501 Status result = m_pipe.Write(&ch, 1, bytes_written); 4502 return result.Success(); 4503 } else { 4504 // This IOHandler might be pushed on the stack, but not being run 4505 // currently so do the right thing if we aren't actively watching for 4506 // STDIN by sending the interrupt to the process. Otherwise the write to 4507 // the pipe above would do nothing. This can happen when the command 4508 // interpreter is running and gets a "expression ...". It will be on the 4509 // IOHandler thread and sending the input is complete to the delegate 4510 // which will cause the expression to run, which will push the process IO 4511 // handler, but not run it. 4512 4513 if (StateIsRunningState(m_process->GetState())) { 4514 m_process->SendAsyncInterrupt(); 4515 return true; 4516 } 4517 } 4518 return false; 4519 } 4520 4521 void GotEOF() override {} 4522 4523 protected: 4524 Process *m_process; 4525 NativeFile m_read_file; // Read from this file (usually actual STDIN for LLDB 4526 NativeFile m_write_file; // Write to this file (usually the master pty for 4527 // getting io to debuggee) 4528 Pipe m_pipe; 4529 std::atomic<bool> m_is_running{false}; 4530 }; 4531 4532 void Process::SetSTDIOFileDescriptor(int fd) { 4533 // First set up the Read Thread for reading/handling process I/O 4534 m_stdio_communication.SetConnection( 4535 std::make_unique<ConnectionFileDescriptor>(fd, true)); 4536 if (m_stdio_communication.IsConnected()) { 4537 m_stdio_communication.SetReadThreadBytesReceivedCallback( 4538 STDIOReadThreadBytesReceived, this); 4539 m_stdio_communication.StartReadThread(); 4540 4541 // Now read thread is set up, set up input reader. 4542 4543 if (!m_process_input_reader) 4544 m_process_input_reader = 4545 std::make_shared<IOHandlerProcessSTDIO>(this, fd); 4546 } 4547 } 4548 4549 bool Process::ProcessIOHandlerIsActive() { 4550 IOHandlerSP io_handler_sp(m_process_input_reader); 4551 if (io_handler_sp) 4552 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp); 4553 return false; 4554 } 4555 bool Process::PushProcessIOHandler() { 4556 IOHandlerSP io_handler_sp(m_process_input_reader); 4557 if (io_handler_sp) { 4558 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 4559 LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__); 4560 4561 io_handler_sp->SetIsDone(false); 4562 // If we evaluate an utility function, then we don't cancel the current 4563 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the 4564 // existing IOHandler that potentially provides the user interface (e.g. 4565 // the IOHandler for Editline). 4566 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction(); 4567 GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp, 4568 cancel_top_handler); 4569 return true; 4570 } 4571 return false; 4572 } 4573 4574 bool Process::PopProcessIOHandler() { 4575 IOHandlerSP io_handler_sp(m_process_input_reader); 4576 if (io_handler_sp) 4577 return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp); 4578 return false; 4579 } 4580 4581 // The process needs to know about installed plug-ins 4582 void Process::SettingsInitialize() { Thread::SettingsInitialize(); } 4583 4584 void Process::SettingsTerminate() { Thread::SettingsTerminate(); } 4585 4586 namespace { 4587 // RestorePlanState is used to record the "is private", "is master" and "okay 4588 // to discard" fields of the plan we are running, and reset it on Clean or on 4589 // destruction. It will only reset the state once, so you can call Clean and 4590 // then monkey with the state and it won't get reset on you again. 4591 4592 class RestorePlanState { 4593 public: 4594 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp) 4595 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) { 4596 if (m_thread_plan_sp) { 4597 m_private = m_thread_plan_sp->GetPrivate(); 4598 m_is_master = m_thread_plan_sp->IsMasterPlan(); 4599 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard(); 4600 } 4601 } 4602 4603 ~RestorePlanState() { Clean(); } 4604 4605 void Clean() { 4606 if (!m_already_reset && m_thread_plan_sp) { 4607 m_already_reset = true; 4608 m_thread_plan_sp->SetPrivate(m_private); 4609 m_thread_plan_sp->SetIsMasterPlan(m_is_master); 4610 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard); 4611 } 4612 } 4613 4614 private: 4615 lldb::ThreadPlanSP m_thread_plan_sp; 4616 bool m_already_reset; 4617 bool m_private; 4618 bool m_is_master; 4619 bool m_okay_to_discard; 4620 }; 4621 } // anonymous namespace 4622 4623 static microseconds 4624 GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) { 4625 const milliseconds default_one_thread_timeout(250); 4626 4627 // If the overall wait is forever, then we don't need to worry about it. 4628 if (!options.GetTimeout()) { 4629 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout() 4630 : default_one_thread_timeout; 4631 } 4632 4633 // If the one thread timeout is set, use it. 4634 if (options.GetOneThreadTimeout()) 4635 return *options.GetOneThreadTimeout(); 4636 4637 // Otherwise use half the total timeout, bounded by the 4638 // default_one_thread_timeout. 4639 return std::min<microseconds>(default_one_thread_timeout, 4640 *options.GetTimeout() / 2); 4641 } 4642 4643 static Timeout<std::micro> 4644 GetExpressionTimeout(const EvaluateExpressionOptions &options, 4645 bool before_first_timeout) { 4646 // If we are going to run all threads the whole time, or if we are only going 4647 // to run one thread, we can just return the overall timeout. 4648 if (!options.GetStopOthers() || !options.GetTryAllThreads()) 4649 return options.GetTimeout(); 4650 4651 if (before_first_timeout) 4652 return GetOneThreadExpressionTimeout(options); 4653 4654 if (!options.GetTimeout()) 4655 return llvm::None; 4656 else 4657 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options); 4658 } 4659 4660 static llvm::Optional<ExpressionResults> 4661 HandleStoppedEvent(lldb::tid_t thread_id, const ThreadPlanSP &thread_plan_sp, 4662 RestorePlanState &restorer, const EventSP &event_sp, 4663 EventSP &event_to_broadcast_sp, 4664 const EvaluateExpressionOptions &options, 4665 bool handle_interrupts) { 4666 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS); 4667 4668 ThreadSP thread_sp = thread_plan_sp->GetTarget() 4669 .GetProcessSP() 4670 ->GetThreadList() 4671 .FindThreadByID(thread_id); 4672 if (!thread_sp) { 4673 LLDB_LOG(log, 4674 "The thread on which we were running the " 4675 "expression: tid = {0}, exited while " 4676 "the expression was running.", 4677 thread_id); 4678 return eExpressionThreadVanished; 4679 } 4680 4681 ThreadPlanSP plan = thread_sp->GetCompletedPlan(); 4682 if (plan == thread_plan_sp && plan->PlanSucceeded()) { 4683 LLDB_LOG(log, "execution completed successfully"); 4684 4685 // Restore the plan state so it will get reported as intended when we are 4686 // done. 4687 restorer.Clean(); 4688 return eExpressionCompleted; 4689 } 4690 4691 StopInfoSP stop_info_sp = thread_sp->GetStopInfo(); 4692 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint && 4693 stop_info_sp->ShouldNotify(event_sp.get())) { 4694 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription()); 4695 if (!options.DoesIgnoreBreakpoints()) { 4696 // Restore the plan state and then force Private to false. We are going 4697 // to stop because of this plan so we need it to become a public plan or 4698 // it won't report correctly when we continue to its termination later 4699 // on. 4700 restorer.Clean(); 4701 thread_plan_sp->SetPrivate(false); 4702 event_to_broadcast_sp = event_sp; 4703 } 4704 return eExpressionHitBreakpoint; 4705 } 4706 4707 if (!handle_interrupts && 4708 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get())) 4709 return llvm::None; 4710 4711 LLDB_LOG(log, "thread plan did not successfully complete"); 4712 if (!options.DoesUnwindOnError()) 4713 event_to_broadcast_sp = event_sp; 4714 return eExpressionInterrupted; 4715 } 4716 4717 ExpressionResults 4718 Process::RunThreadPlan(ExecutionContext &exe_ctx, 4719 lldb::ThreadPlanSP &thread_plan_sp, 4720 const EvaluateExpressionOptions &options, 4721 DiagnosticManager &diagnostic_manager) { 4722 ExpressionResults return_value = eExpressionSetupError; 4723 4724 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock); 4725 4726 if (!thread_plan_sp) { 4727 diagnostic_manager.PutString( 4728 eDiagnosticSeverityError, 4729 "RunThreadPlan called with empty thread plan."); 4730 return eExpressionSetupError; 4731 } 4732 4733 if (!thread_plan_sp->ValidatePlan(nullptr)) { 4734 diagnostic_manager.PutString( 4735 eDiagnosticSeverityError, 4736 "RunThreadPlan called with an invalid thread plan."); 4737 return eExpressionSetupError; 4738 } 4739 4740 if (exe_ctx.GetProcessPtr() != this) { 4741 diagnostic_manager.PutString(eDiagnosticSeverityError, 4742 "RunThreadPlan called on wrong process."); 4743 return eExpressionSetupError; 4744 } 4745 4746 Thread *thread = exe_ctx.GetThreadPtr(); 4747 if (thread == nullptr) { 4748 diagnostic_manager.PutString(eDiagnosticSeverityError, 4749 "RunThreadPlan called with invalid thread."); 4750 return eExpressionSetupError; 4751 } 4752 4753 // Record the thread's id so we can tell when a thread we were using 4754 // to run the expression exits during the expression evaluation. 4755 lldb::tid_t expr_thread_id = thread->GetID(); 4756 4757 // We need to change some of the thread plan attributes for the thread plan 4758 // runner. This will restore them when we are done: 4759 4760 RestorePlanState thread_plan_restorer(thread_plan_sp); 4761 4762 // We rely on the thread plan we are running returning "PlanCompleted" if 4763 // when it successfully completes. For that to be true the plan can't be 4764 // private - since private plans suppress themselves in the GetCompletedPlan 4765 // call. 4766 4767 thread_plan_sp->SetPrivate(false); 4768 4769 // The plans run with RunThreadPlan also need to be terminal master plans or 4770 // when they are done we will end up asking the plan above us whether we 4771 // should stop, which may give the wrong answer. 4772 4773 thread_plan_sp->SetIsMasterPlan(true); 4774 thread_plan_sp->SetOkayToDiscard(false); 4775 4776 // If we are running some utility expression for LLDB, we now have to mark 4777 // this in the ProcesModID of this process. This RAII takes care of marking 4778 // and reverting the mark it once we are done running the expression. 4779 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr); 4780 4781 if (m_private_state.GetValue() != eStateStopped) { 4782 diagnostic_manager.PutString( 4783 eDiagnosticSeverityError, 4784 "RunThreadPlan called while the private state was not stopped."); 4785 return eExpressionSetupError; 4786 } 4787 4788 // Save the thread & frame from the exe_ctx for restoration after we run 4789 const uint32_t thread_idx_id = thread->GetIndexID(); 4790 StackFrameSP selected_frame_sp = thread->GetSelectedFrame(); 4791 if (!selected_frame_sp) { 4792 thread->SetSelectedFrame(nullptr); 4793 selected_frame_sp = thread->GetSelectedFrame(); 4794 if (!selected_frame_sp) { 4795 diagnostic_manager.Printf( 4796 eDiagnosticSeverityError, 4797 "RunThreadPlan called without a selected frame on thread %d", 4798 thread_idx_id); 4799 return eExpressionSetupError; 4800 } 4801 } 4802 4803 // Make sure the timeout values make sense. The one thread timeout needs to 4804 // be smaller than the overall timeout. 4805 if (options.GetOneThreadTimeout() && options.GetTimeout() && 4806 *options.GetTimeout() < *options.GetOneThreadTimeout()) { 4807 diagnostic_manager.PutString(eDiagnosticSeverityError, 4808 "RunThreadPlan called with one thread " 4809 "timeout greater than total timeout"); 4810 return eExpressionSetupError; 4811 } 4812 4813 StackID ctx_frame_id = selected_frame_sp->GetStackID(); 4814 4815 // N.B. Running the target may unset the currently selected thread and frame. 4816 // We don't want to do that either, so we should arrange to reset them as 4817 // well. 4818 4819 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread(); 4820 4821 uint32_t selected_tid; 4822 StackID selected_stack_id; 4823 if (selected_thread_sp) { 4824 selected_tid = selected_thread_sp->GetIndexID(); 4825 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID(); 4826 } else { 4827 selected_tid = LLDB_INVALID_THREAD_ID; 4828 } 4829 4830 HostThread backup_private_state_thread; 4831 lldb::StateType old_state = eStateInvalid; 4832 lldb::ThreadPlanSP stopper_base_plan_sp; 4833 4834 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | 4835 LIBLLDB_LOG_PROCESS)); 4836 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) { 4837 // Yikes, we are running on the private state thread! So we can't wait for 4838 // public events on this thread, since we are the thread that is generating 4839 // public events. The simplest thing to do is to spin up a temporary thread 4840 // to handle private state thread events while we are fielding public 4841 // events here. 4842 LLDB_LOGF(log, "Running thread plan on private state thread, spinning up " 4843 "another state thread to handle the events."); 4844 4845 backup_private_state_thread = m_private_state_thread; 4846 4847 // One other bit of business: we want to run just this thread plan and 4848 // anything it pushes, and then stop, returning control here. But in the 4849 // normal course of things, the plan above us on the stack would be given a 4850 // shot at the stop event before deciding to stop, and we don't want that. 4851 // So we insert a "stopper" base plan on the stack before the plan we want 4852 // to run. Since base plans always stop and return control to the user, 4853 // that will do just what we want. 4854 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread)); 4855 thread->QueueThreadPlan(stopper_base_plan_sp, false); 4856 // Have to make sure our public state is stopped, since otherwise the 4857 // reporting logic below doesn't work correctly. 4858 old_state = m_public_state.GetValue(); 4859 m_public_state.SetValueNoLock(eStateStopped); 4860 4861 // Now spin up the private state thread: 4862 StartPrivateStateThread(true); 4863 } 4864 4865 thread->QueueThreadPlan( 4866 thread_plan_sp, false); // This used to pass "true" does that make sense? 4867 4868 if (options.GetDebug()) { 4869 // In this case, we aren't actually going to run, we just want to stop 4870 // right away. Flush this thread so we will refetch the stacks and show the 4871 // correct backtrace. 4872 // FIXME: To make this prettier we should invent some stop reason for this, 4873 // but that 4874 // is only cosmetic, and this functionality is only of use to lldb 4875 // developers who can live with not pretty... 4876 thread->Flush(); 4877 return eExpressionStoppedForDebug; 4878 } 4879 4880 ListenerSP listener_sp( 4881 Listener::MakeListener("lldb.process.listener.run-thread-plan")); 4882 4883 lldb::EventSP event_to_broadcast_sp; 4884 4885 { 4886 // This process event hijacker Hijacks the Public events and its destructor 4887 // makes sure that the process events get restored on exit to the function. 4888 // 4889 // If the event needs to propagate beyond the hijacker (e.g., the process 4890 // exits during execution), then the event is put into 4891 // event_to_broadcast_sp for rebroadcasting. 4892 4893 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp); 4894 4895 if (log) { 4896 StreamString s; 4897 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose); 4898 LLDB_LOGF(log, 4899 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 4900 " to run thread plan \"%s\".", 4901 thread_idx_id, expr_thread_id, s.GetData()); 4902 } 4903 4904 bool got_event; 4905 lldb::EventSP event_sp; 4906 lldb::StateType stop_state = lldb::eStateInvalid; 4907 4908 bool before_first_timeout = true; // This is set to false the first time 4909 // that we have to halt the target. 4910 bool do_resume = true; 4911 bool handle_running_event = true; 4912 4913 // This is just for accounting: 4914 uint32_t num_resumes = 0; 4915 4916 // If we are going to run all threads the whole time, or if we are only 4917 // going to run one thread, then we don't need the first timeout. So we 4918 // pretend we are after the first timeout already. 4919 if (!options.GetStopOthers() || !options.GetTryAllThreads()) 4920 before_first_timeout = false; 4921 4922 LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n", 4923 options.GetStopOthers(), options.GetTryAllThreads(), 4924 before_first_timeout); 4925 4926 // This isn't going to work if there are unfetched events on the queue. Are 4927 // there cases where we might want to run the remaining events here, and 4928 // then try to call the function? That's probably being too tricky for our 4929 // own good. 4930 4931 Event *other_events = listener_sp->PeekAtNextEvent(); 4932 if (other_events != nullptr) { 4933 diagnostic_manager.PutString( 4934 eDiagnosticSeverityError, 4935 "RunThreadPlan called with pending events on the queue."); 4936 return eExpressionSetupError; 4937 } 4938 4939 // We also need to make sure that the next event is delivered. We might be 4940 // calling a function as part of a thread plan, in which case the last 4941 // delivered event could be the running event, and we don't want event 4942 // coalescing to cause us to lose OUR running event... 4943 ForceNextEventDelivery(); 4944 4945 // This while loop must exit out the bottom, there's cleanup that we need to do 4946 // when we are done. So don't call return anywhere within it. 4947 4948 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT 4949 // It's pretty much impossible to write test cases for things like: One 4950 // thread timeout expires, I go to halt, but the process already stopped on 4951 // the function call stop breakpoint. Turning on this define will make us 4952 // not fetch the first event till after the halt. So if you run a quick 4953 // function, it will have completed, and the completion event will be 4954 // waiting, when you interrupt for halt. The expression evaluation should 4955 // still succeed. 4956 bool miss_first_event = true; 4957 #endif 4958 while (true) { 4959 // We usually want to resume the process if we get to the top of the 4960 // loop. The only exception is if we get two running events with no 4961 // intervening stop, which can happen, we will just wait for then next 4962 // stop event. 4963 LLDB_LOGF(log, 4964 "Top of while loop: do_resume: %i handle_running_event: %i " 4965 "before_first_timeout: %i.", 4966 do_resume, handle_running_event, before_first_timeout); 4967 4968 if (do_resume || handle_running_event) { 4969 // Do the initial resume and wait for the running event before going 4970 // further. 4971 4972 if (do_resume) { 4973 num_resumes++; 4974 Status resume_error = PrivateResume(); 4975 if (!resume_error.Success()) { 4976 diagnostic_manager.Printf( 4977 eDiagnosticSeverityError, 4978 "couldn't resume inferior the %d time: \"%s\".", num_resumes, 4979 resume_error.AsCString()); 4980 return_value = eExpressionSetupError; 4981 break; 4982 } 4983 } 4984 4985 got_event = 4986 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout()); 4987 if (!got_event) { 4988 LLDB_LOGF(log, 4989 "Process::RunThreadPlan(): didn't get any event after " 4990 "resume %" PRIu32 ", exiting.", 4991 num_resumes); 4992 4993 diagnostic_manager.Printf(eDiagnosticSeverityError, 4994 "didn't get any event after resume %" PRIu32 4995 ", exiting.", 4996 num_resumes); 4997 return_value = eExpressionSetupError; 4998 break; 4999 } 5000 5001 stop_state = 5002 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 5003 5004 if (stop_state != eStateRunning) { 5005 bool restarted = false; 5006 5007 if (stop_state == eStateStopped) { 5008 restarted = Process::ProcessEventData::GetRestartedFromEvent( 5009 event_sp.get()); 5010 LLDB_LOGF( 5011 log, 5012 "Process::RunThreadPlan(): didn't get running event after " 5013 "resume %d, got %s instead (restarted: %i, do_resume: %i, " 5014 "handle_running_event: %i).", 5015 num_resumes, StateAsCString(stop_state), restarted, do_resume, 5016 handle_running_event); 5017 } 5018 5019 if (restarted) { 5020 // This is probably an overabundance of caution, I don't think I 5021 // should ever get a stopped & restarted event here. But if I do, 5022 // the best thing is to Halt and then get out of here. 5023 const bool clear_thread_plans = false; 5024 const bool use_run_lock = false; 5025 Halt(clear_thread_plans, use_run_lock); 5026 } 5027 5028 diagnostic_manager.Printf( 5029 eDiagnosticSeverityError, 5030 "didn't get running event after initial resume, got %s instead.", 5031 StateAsCString(stop_state)); 5032 return_value = eExpressionSetupError; 5033 break; 5034 } 5035 5036 if (log) 5037 log->PutCString("Process::RunThreadPlan(): resuming succeeded."); 5038 // We need to call the function synchronously, so spin waiting for it 5039 // to return. If we get interrupted while executing, we're going to 5040 // lose our context, and won't be able to gather the result at this 5041 // point. We set the timeout AFTER the resume, since the resume takes 5042 // some time and we don't want to charge that to the timeout. 5043 } else { 5044 if (log) 5045 log->PutCString("Process::RunThreadPlan(): waiting for next event."); 5046 } 5047 5048 do_resume = true; 5049 handle_running_event = true; 5050 5051 // Now wait for the process to stop again: 5052 event_sp.reset(); 5053 5054 Timeout<std::micro> timeout = 5055 GetExpressionTimeout(options, before_first_timeout); 5056 if (log) { 5057 if (timeout) { 5058 auto now = system_clock::now(); 5059 LLDB_LOGF(log, 5060 "Process::RunThreadPlan(): about to wait - now is %s - " 5061 "endpoint is %s", 5062 llvm::to_string(now).c_str(), 5063 llvm::to_string(now + *timeout).c_str()); 5064 } else { 5065 LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever."); 5066 } 5067 } 5068 5069 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT 5070 // See comment above... 5071 if (miss_first_event) { 5072 std::this_thread::sleep_for(std::chrono::milliseconds(1)); 5073 miss_first_event = false; 5074 got_event = false; 5075 } else 5076 #endif 5077 got_event = listener_sp->GetEvent(event_sp, timeout); 5078 5079 if (got_event) { 5080 if (event_sp) { 5081 bool keep_going = false; 5082 if (event_sp->GetType() == eBroadcastBitInterrupt) { 5083 const bool clear_thread_plans = false; 5084 const bool use_run_lock = false; 5085 Halt(clear_thread_plans, use_run_lock); 5086 return_value = eExpressionInterrupted; 5087 diagnostic_manager.PutString(eDiagnosticSeverityRemark, 5088 "execution halted by user interrupt."); 5089 LLDB_LOGF(log, "Process::RunThreadPlan(): Got interrupted by " 5090 "eBroadcastBitInterrupted, exiting."); 5091 break; 5092 } else { 5093 stop_state = 5094 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 5095 LLDB_LOGF(log, 5096 "Process::RunThreadPlan(): in while loop, got event: %s.", 5097 StateAsCString(stop_state)); 5098 5099 switch (stop_state) { 5100 case lldb::eStateStopped: { 5101 if (Process::ProcessEventData::GetRestartedFromEvent( 5102 event_sp.get())) { 5103 // If we were restarted, we just need to go back up to fetch 5104 // another event. 5105 LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and " 5106 "restart, so we'll continue waiting."); 5107 keep_going = true; 5108 do_resume = false; 5109 handle_running_event = true; 5110 } else { 5111 const bool handle_interrupts = true; 5112 return_value = *HandleStoppedEvent( 5113 expr_thread_id, thread_plan_sp, thread_plan_restorer, 5114 event_sp, event_to_broadcast_sp, options, 5115 handle_interrupts); 5116 if (return_value == eExpressionThreadVanished) 5117 keep_going = false; 5118 } 5119 } break; 5120 5121 case lldb::eStateRunning: 5122 // This shouldn't really happen, but sometimes we do get two 5123 // running events without an intervening stop, and in that case 5124 // we should just go back to waiting for the stop. 5125 do_resume = false; 5126 keep_going = true; 5127 handle_running_event = false; 5128 break; 5129 5130 default: 5131 LLDB_LOGF(log, 5132 "Process::RunThreadPlan(): execution stopped with " 5133 "unexpected state: %s.", 5134 StateAsCString(stop_state)); 5135 5136 if (stop_state == eStateExited) 5137 event_to_broadcast_sp = event_sp; 5138 5139 diagnostic_manager.PutString( 5140 eDiagnosticSeverityError, 5141 "execution stopped with unexpected state."); 5142 return_value = eExpressionInterrupted; 5143 break; 5144 } 5145 } 5146 5147 if (keep_going) 5148 continue; 5149 else 5150 break; 5151 } else { 5152 if (log) 5153 log->PutCString("Process::RunThreadPlan(): got_event was true, but " 5154 "the event pointer was null. How odd..."); 5155 return_value = eExpressionInterrupted; 5156 break; 5157 } 5158 } else { 5159 // If we didn't get an event that means we've timed out... We will 5160 // interrupt the process here. Depending on what we were asked to do 5161 // we will either exit, or try with all threads running for the same 5162 // timeout. 5163 5164 if (log) { 5165 if (options.GetTryAllThreads()) { 5166 if (before_first_timeout) { 5167 LLDB_LOG(log, 5168 "Running function with one thread timeout timed out."); 5169 } else 5170 LLDB_LOG(log, "Restarting function with all threads enabled and " 5171 "timeout: {0} timed out, abandoning execution.", 5172 timeout); 5173 } else 5174 LLDB_LOG(log, "Running function with timeout: {0} timed out, " 5175 "abandoning execution.", 5176 timeout); 5177 } 5178 5179 // It is possible that between the time we issued the Halt, and we get 5180 // around to calling Halt the target could have stopped. That's fine, 5181 // Halt will figure that out and send the appropriate Stopped event. 5182 // BUT it is also possible that we stopped & restarted (e.g. hit a 5183 // signal with "stop" set to false.) In 5184 // that case, we'll get the stopped & restarted event, and we should go 5185 // back to waiting for the Halt's stopped event. That's what this 5186 // while loop does. 5187 5188 bool back_to_top = true; 5189 uint32_t try_halt_again = 0; 5190 bool do_halt = true; 5191 const uint32_t num_retries = 5; 5192 while (try_halt_again < num_retries) { 5193 Status halt_error; 5194 if (do_halt) { 5195 LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt."); 5196 const bool clear_thread_plans = false; 5197 const bool use_run_lock = false; 5198 Halt(clear_thread_plans, use_run_lock); 5199 } 5200 if (halt_error.Success()) { 5201 if (log) 5202 log->PutCString("Process::RunThreadPlan(): Halt succeeded."); 5203 5204 got_event = 5205 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout()); 5206 5207 if (got_event) { 5208 stop_state = 5209 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 5210 if (log) { 5211 LLDB_LOGF(log, 5212 "Process::RunThreadPlan(): Stopped with event: %s", 5213 StateAsCString(stop_state)); 5214 if (stop_state == lldb::eStateStopped && 5215 Process::ProcessEventData::GetInterruptedFromEvent( 5216 event_sp.get())) 5217 log->PutCString(" Event was the Halt interruption event."); 5218 } 5219 5220 if (stop_state == lldb::eStateStopped) { 5221 if (Process::ProcessEventData::GetRestartedFromEvent( 5222 event_sp.get())) { 5223 if (log) 5224 log->PutCString("Process::RunThreadPlan(): Went to halt " 5225 "but got a restarted event, there must be " 5226 "an un-restarted stopped event so try " 5227 "again... " 5228 "Exiting wait loop."); 5229 try_halt_again++; 5230 do_halt = false; 5231 continue; 5232 } 5233 5234 // Between the time we initiated the Halt and the time we 5235 // delivered it, the process could have already finished its 5236 // job. Check that here: 5237 const bool handle_interrupts = false; 5238 if (auto result = HandleStoppedEvent( 5239 expr_thread_id, thread_plan_sp, thread_plan_restorer, 5240 event_sp, event_to_broadcast_sp, options, 5241 handle_interrupts)) { 5242 return_value = *result; 5243 back_to_top = false; 5244 break; 5245 } 5246 5247 if (!options.GetTryAllThreads()) { 5248 if (log) 5249 log->PutCString("Process::RunThreadPlan(): try_all_threads " 5250 "was false, we stopped so now we're " 5251 "quitting."); 5252 return_value = eExpressionInterrupted; 5253 back_to_top = false; 5254 break; 5255 } 5256 5257 if (before_first_timeout) { 5258 // Set all the other threads to run, and return to the top of 5259 // the loop, which will continue; 5260 before_first_timeout = false; 5261 thread_plan_sp->SetStopOthers(false); 5262 if (log) 5263 log->PutCString( 5264 "Process::RunThreadPlan(): about to resume."); 5265 5266 back_to_top = true; 5267 break; 5268 } else { 5269 // Running all threads failed, so return Interrupted. 5270 if (log) 5271 log->PutCString("Process::RunThreadPlan(): running all " 5272 "threads timed out."); 5273 return_value = eExpressionInterrupted; 5274 back_to_top = false; 5275 break; 5276 } 5277 } 5278 } else { 5279 if (log) 5280 log->PutCString("Process::RunThreadPlan(): halt said it " 5281 "succeeded, but I got no event. " 5282 "I'm getting out of here passing Interrupted."); 5283 return_value = eExpressionInterrupted; 5284 back_to_top = false; 5285 break; 5286 } 5287 } else { 5288 try_halt_again++; 5289 continue; 5290 } 5291 } 5292 5293 if (!back_to_top || try_halt_again > num_retries) 5294 break; 5295 else 5296 continue; 5297 } 5298 } // END WAIT LOOP 5299 5300 // If we had to start up a temporary private state thread to run this 5301 // thread plan, shut it down now. 5302 if (backup_private_state_thread.IsJoinable()) { 5303 StopPrivateStateThread(); 5304 Status error; 5305 m_private_state_thread = backup_private_state_thread; 5306 if (stopper_base_plan_sp) { 5307 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp); 5308 } 5309 if (old_state != eStateInvalid) 5310 m_public_state.SetValueNoLock(old_state); 5311 } 5312 5313 // If our thread went away on us, we need to get out of here without 5314 // doing any more work. We don't have to clean up the thread plan, that 5315 // will have happened when the Thread was destroyed. 5316 if (return_value == eExpressionThreadVanished) { 5317 return return_value; 5318 } 5319 5320 if (return_value != eExpressionCompleted && log) { 5321 // Print a backtrace into the log so we can figure out where we are: 5322 StreamString s; 5323 s.PutCString("Thread state after unsuccessful completion: \n"); 5324 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX); 5325 log->PutString(s.GetString()); 5326 } 5327 // Restore the thread state if we are going to discard the plan execution. 5328 // There are three cases where this could happen: 1) The execution 5329 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints 5330 // was true 3) We got some other error, and discard_on_error was true 5331 bool should_unwind = (return_value == eExpressionInterrupted && 5332 options.DoesUnwindOnError()) || 5333 (return_value == eExpressionHitBreakpoint && 5334 options.DoesIgnoreBreakpoints()); 5335 5336 if (return_value == eExpressionCompleted || should_unwind) { 5337 thread_plan_sp->RestoreThreadState(); 5338 } 5339 5340 // Now do some processing on the results of the run: 5341 if (return_value == eExpressionInterrupted || 5342 return_value == eExpressionHitBreakpoint) { 5343 if (log) { 5344 StreamString s; 5345 if (event_sp) 5346 event_sp->Dump(&s); 5347 else { 5348 log->PutCString("Process::RunThreadPlan(): Stop event that " 5349 "interrupted us is NULL."); 5350 } 5351 5352 StreamString ts; 5353 5354 const char *event_explanation = nullptr; 5355 5356 do { 5357 if (!event_sp) { 5358 event_explanation = "<no event>"; 5359 break; 5360 } else if (event_sp->GetType() == eBroadcastBitInterrupt) { 5361 event_explanation = "<user interrupt>"; 5362 break; 5363 } else { 5364 const Process::ProcessEventData *event_data = 5365 Process::ProcessEventData::GetEventDataFromEvent( 5366 event_sp.get()); 5367 5368 if (!event_data) { 5369 event_explanation = "<no event data>"; 5370 break; 5371 } 5372 5373 Process *process = event_data->GetProcessSP().get(); 5374 5375 if (!process) { 5376 event_explanation = "<no process>"; 5377 break; 5378 } 5379 5380 ThreadList &thread_list = process->GetThreadList(); 5381 5382 uint32_t num_threads = thread_list.GetSize(); 5383 uint32_t thread_index; 5384 5385 ts.Printf("<%u threads> ", num_threads); 5386 5387 for (thread_index = 0; thread_index < num_threads; ++thread_index) { 5388 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get(); 5389 5390 if (!thread) { 5391 ts.Printf("<?> "); 5392 continue; 5393 } 5394 5395 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID()); 5396 RegisterContext *register_context = 5397 thread->GetRegisterContext().get(); 5398 5399 if (register_context) 5400 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC()); 5401 else 5402 ts.Printf("[ip unknown] "); 5403 5404 // Show the private stop info here, the public stop info will be 5405 // from the last natural stop. 5406 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo(); 5407 if (stop_info_sp) { 5408 const char *stop_desc = stop_info_sp->GetDescription(); 5409 if (stop_desc) 5410 ts.PutCString(stop_desc); 5411 } 5412 ts.Printf(">"); 5413 } 5414 5415 event_explanation = ts.GetData(); 5416 } 5417 } while (false); 5418 5419 if (event_explanation) 5420 LLDB_LOGF(log, 5421 "Process::RunThreadPlan(): execution interrupted: %s %s", 5422 s.GetData(), event_explanation); 5423 else 5424 LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s", 5425 s.GetData()); 5426 } 5427 5428 if (should_unwind) { 5429 LLDB_LOGF(log, 5430 "Process::RunThreadPlan: ExecutionInterrupted - " 5431 "discarding thread plans up to %p.", 5432 static_cast<void *>(thread_plan_sp.get())); 5433 thread->DiscardThreadPlansUpToPlan(thread_plan_sp); 5434 } else { 5435 LLDB_LOGF(log, 5436 "Process::RunThreadPlan: ExecutionInterrupted - for " 5437 "plan: %p not discarding.", 5438 static_cast<void *>(thread_plan_sp.get())); 5439 } 5440 } else if (return_value == eExpressionSetupError) { 5441 if (log) 5442 log->PutCString("Process::RunThreadPlan(): execution set up error."); 5443 5444 if (options.DoesUnwindOnError()) { 5445 thread->DiscardThreadPlansUpToPlan(thread_plan_sp); 5446 } 5447 } else { 5448 if (thread->IsThreadPlanDone(thread_plan_sp.get())) { 5449 if (log) 5450 log->PutCString("Process::RunThreadPlan(): thread plan is done"); 5451 return_value = eExpressionCompleted; 5452 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) { 5453 if (log) 5454 log->PutCString( 5455 "Process::RunThreadPlan(): thread plan was discarded"); 5456 return_value = eExpressionDiscarded; 5457 } else { 5458 if (log) 5459 log->PutCString( 5460 "Process::RunThreadPlan(): thread plan stopped in mid course"); 5461 if (options.DoesUnwindOnError() && thread_plan_sp) { 5462 if (log) 5463 log->PutCString("Process::RunThreadPlan(): discarding thread plan " 5464 "'cause unwind_on_error is set."); 5465 thread->DiscardThreadPlansUpToPlan(thread_plan_sp); 5466 } 5467 } 5468 } 5469 5470 // Thread we ran the function in may have gone away because we ran the 5471 // target Check that it's still there, and if it is put it back in the 5472 // context. Also restore the frame in the context if it is still present. 5473 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get(); 5474 if (thread) { 5475 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id)); 5476 } 5477 5478 // Also restore the current process'es selected frame & thread, since this 5479 // function calling may be done behind the user's back. 5480 5481 if (selected_tid != LLDB_INVALID_THREAD_ID) { 5482 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) && 5483 selected_stack_id.IsValid()) { 5484 // We were able to restore the selected thread, now restore the frame: 5485 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex()); 5486 StackFrameSP old_frame_sp = 5487 GetThreadList().GetSelectedThread()->GetFrameWithStackID( 5488 selected_stack_id); 5489 if (old_frame_sp) 5490 GetThreadList().GetSelectedThread()->SetSelectedFrame( 5491 old_frame_sp.get()); 5492 } 5493 } 5494 } 5495 5496 // If the process exited during the run of the thread plan, notify everyone. 5497 5498 if (event_to_broadcast_sp) { 5499 if (log) 5500 log->PutCString("Process::RunThreadPlan(): rebroadcasting event."); 5501 BroadcastEvent(event_to_broadcast_sp); 5502 } 5503 5504 return return_value; 5505 } 5506 5507 const char *Process::ExecutionResultAsCString(ExpressionResults result) { 5508 const char *result_name = "<unknown>"; 5509 5510 switch (result) { 5511 case eExpressionCompleted: 5512 result_name = "eExpressionCompleted"; 5513 break; 5514 case eExpressionDiscarded: 5515 result_name = "eExpressionDiscarded"; 5516 break; 5517 case eExpressionInterrupted: 5518 result_name = "eExpressionInterrupted"; 5519 break; 5520 case eExpressionHitBreakpoint: 5521 result_name = "eExpressionHitBreakpoint"; 5522 break; 5523 case eExpressionSetupError: 5524 result_name = "eExpressionSetupError"; 5525 break; 5526 case eExpressionParseError: 5527 result_name = "eExpressionParseError"; 5528 break; 5529 case eExpressionResultUnavailable: 5530 result_name = "eExpressionResultUnavailable"; 5531 break; 5532 case eExpressionTimedOut: 5533 result_name = "eExpressionTimedOut"; 5534 break; 5535 case eExpressionStoppedForDebug: 5536 result_name = "eExpressionStoppedForDebug"; 5537 break; 5538 case eExpressionThreadVanished: 5539 result_name = "eExpressionThreadVanished"; 5540 } 5541 return result_name; 5542 } 5543 5544 void Process::GetStatus(Stream &strm) { 5545 const StateType state = GetState(); 5546 if (StateIsStoppedState(state, false)) { 5547 if (state == eStateExited) { 5548 int exit_status = GetExitStatus(); 5549 const char *exit_description = GetExitDescription(); 5550 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n", 5551 GetID(), exit_status, exit_status, 5552 exit_description ? exit_description : ""); 5553 } else { 5554 if (state == eStateConnected) 5555 strm.Printf("Connected to remote target.\n"); 5556 else 5557 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state)); 5558 } 5559 } else { 5560 strm.Printf("Process %" PRIu64 " is running.\n", GetID()); 5561 } 5562 } 5563 5564 size_t Process::GetThreadStatus(Stream &strm, 5565 bool only_threads_with_stop_reason, 5566 uint32_t start_frame, uint32_t num_frames, 5567 uint32_t num_frames_with_source, 5568 bool stop_format) { 5569 size_t num_thread_infos_dumped = 0; 5570 5571 // You can't hold the thread list lock while calling Thread::GetStatus. That 5572 // very well might run code (e.g. if we need it to get return values or 5573 // arguments.) For that to work the process has to be able to acquire it. 5574 // So instead copy the thread ID's, and look them up one by one: 5575 5576 uint32_t num_threads; 5577 std::vector<lldb::tid_t> thread_id_array; 5578 // Scope for thread list locker; 5579 { 5580 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex()); 5581 ThreadList &curr_thread_list = GetThreadList(); 5582 num_threads = curr_thread_list.GetSize(); 5583 uint32_t idx; 5584 thread_id_array.resize(num_threads); 5585 for (idx = 0; idx < num_threads; ++idx) 5586 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID(); 5587 } 5588 5589 for (uint32_t i = 0; i < num_threads; i++) { 5590 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i])); 5591 if (thread_sp) { 5592 if (only_threads_with_stop_reason) { 5593 StopInfoSP stop_info_sp = thread_sp->GetStopInfo(); 5594 if (!stop_info_sp || !stop_info_sp->IsValid()) 5595 continue; 5596 } 5597 thread_sp->GetStatus(strm, start_frame, num_frames, 5598 num_frames_with_source, 5599 stop_format); 5600 ++num_thread_infos_dumped; 5601 } else { 5602 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 5603 LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu64 5604 " vanished while running Thread::GetStatus."); 5605 } 5606 } 5607 return num_thread_infos_dumped; 5608 } 5609 5610 void Process::AddInvalidMemoryRegion(const LoadRange ®ion) { 5611 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize()); 5612 } 5613 5614 bool Process::RemoveInvalidMemoryRange(const LoadRange ®ion) { 5615 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), 5616 region.GetByteSize()); 5617 } 5618 5619 void Process::AddPreResumeAction(PreResumeActionCallback callback, 5620 void *baton) { 5621 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton)); 5622 } 5623 5624 bool Process::RunPreResumeActions() { 5625 bool result = true; 5626 while (!m_pre_resume_actions.empty()) { 5627 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back(); 5628 m_pre_resume_actions.pop_back(); 5629 bool this_result = action.callback(action.baton); 5630 if (result) 5631 result = this_result; 5632 } 5633 return result; 5634 } 5635 5636 void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); } 5637 5638 void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton) 5639 { 5640 PreResumeCallbackAndBaton element(callback, baton); 5641 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element); 5642 if (found_iter != m_pre_resume_actions.end()) 5643 { 5644 m_pre_resume_actions.erase(found_iter); 5645 } 5646 } 5647 5648 ProcessRunLock &Process::GetRunLock() { 5649 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) 5650 return m_private_run_lock; 5651 else 5652 return m_public_run_lock; 5653 } 5654 5655 bool Process::CurrentThreadIsPrivateStateThread() 5656 { 5657 return m_private_state_thread.EqualsThread(Host::GetCurrentThread()); 5658 } 5659 5660 5661 void Process::Flush() { 5662 m_thread_list.Flush(); 5663 m_extended_thread_list.Flush(); 5664 m_extended_thread_stop_id = 0; 5665 m_queue_list.Clear(); 5666 m_queue_list_stop_id = 0; 5667 } 5668 5669 void Process::DidExec() { 5670 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 5671 LLDB_LOGF(log, "Process::%s()", __FUNCTION__); 5672 5673 Target &target = GetTarget(); 5674 target.CleanupProcess(); 5675 target.ClearModules(false); 5676 m_dynamic_checkers_up.reset(); 5677 m_abi_sp.reset(); 5678 m_system_runtime_up.reset(); 5679 m_os_up.reset(); 5680 m_dyld_up.reset(); 5681 m_jit_loaders_up.reset(); 5682 m_image_tokens.clear(); 5683 m_allocated_memory_cache.Clear(); 5684 { 5685 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex); 5686 m_language_runtimes.clear(); 5687 } 5688 m_instrumentation_runtimes.clear(); 5689 m_thread_list.DiscardThreadPlans(); 5690 m_memory_cache.Clear(true); 5691 DoDidExec(); 5692 CompleteAttach(); 5693 // Flush the process (threads and all stack frames) after running 5694 // CompleteAttach() in case the dynamic loader loaded things in new 5695 // locations. 5696 Flush(); 5697 5698 // After we figure out what was loaded/unloaded in CompleteAttach, we need to 5699 // let the target know so it can do any cleanup it needs to. 5700 target.DidExec(); 5701 } 5702 5703 addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) { 5704 if (address == nullptr) { 5705 error.SetErrorString("Invalid address argument"); 5706 return LLDB_INVALID_ADDRESS; 5707 } 5708 5709 addr_t function_addr = LLDB_INVALID_ADDRESS; 5710 5711 addr_t addr = address->GetLoadAddress(&GetTarget()); 5712 std::map<addr_t, addr_t>::const_iterator iter = 5713 m_resolved_indirect_addresses.find(addr); 5714 if (iter != m_resolved_indirect_addresses.end()) { 5715 function_addr = (*iter).second; 5716 } else { 5717 if (!CallVoidArgVoidPtrReturn(address, function_addr)) { 5718 Symbol *symbol = address->CalculateSymbolContextSymbol(); 5719 error.SetErrorStringWithFormat( 5720 "Unable to call resolver for indirect function %s", 5721 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>"); 5722 function_addr = LLDB_INVALID_ADDRESS; 5723 } else { 5724 m_resolved_indirect_addresses.insert( 5725 std::pair<addr_t, addr_t>(addr, function_addr)); 5726 } 5727 } 5728 return function_addr; 5729 } 5730 5731 void Process::ModulesDidLoad(ModuleList &module_list) { 5732 SystemRuntime *sys_runtime = GetSystemRuntime(); 5733 if (sys_runtime) { 5734 sys_runtime->ModulesDidLoad(module_list); 5735 } 5736 5737 GetJITLoaders().ModulesDidLoad(module_list); 5738 5739 // Give runtimes a chance to be created. 5740 InstrumentationRuntime::ModulesDidLoad(module_list, this, 5741 m_instrumentation_runtimes); 5742 5743 // Tell runtimes about new modules. 5744 for (auto pos = m_instrumentation_runtimes.begin(); 5745 pos != m_instrumentation_runtimes.end(); ++pos) { 5746 InstrumentationRuntimeSP runtime = pos->second; 5747 runtime->ModulesDidLoad(module_list); 5748 } 5749 5750 // Let any language runtimes we have already created know about the modules 5751 // that loaded. 5752 5753 // Iterate over a copy of this language runtime list in case the language 5754 // runtime ModulesDidLoad somehow causes the language runtime to be 5755 // unloaded. 5756 { 5757 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex); 5758 LanguageRuntimeCollection language_runtimes(m_language_runtimes); 5759 for (const auto &pair : language_runtimes) { 5760 // We must check language_runtime_sp to make sure it is not nullptr as we 5761 // might cache the fact that we didn't have a language runtime for a 5762 // language. 5763 LanguageRuntimeSP language_runtime_sp = pair.second; 5764 if (language_runtime_sp) 5765 language_runtime_sp->ModulesDidLoad(module_list); 5766 } 5767 } 5768 5769 // If we don't have an operating system plug-in, try to load one since 5770 // loading shared libraries might cause a new one to try and load 5771 if (!m_os_up) 5772 LoadOperatingSystemPlugin(false); 5773 5774 // Give structured-data plugins a chance to see the modified modules. 5775 for (auto pair : m_structured_data_plugin_map) { 5776 if (pair.second) 5777 pair.second->ModulesDidLoad(*this, module_list); 5778 } 5779 } 5780 5781 void Process::PrintWarning(uint64_t warning_type, const void *repeat_key, 5782 const char *fmt, ...) { 5783 bool print_warning = true; 5784 5785 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream(); 5786 if (!stream_sp) 5787 return; 5788 5789 if (repeat_key != nullptr) { 5790 WarningsCollection::iterator it = m_warnings_issued.find(warning_type); 5791 if (it == m_warnings_issued.end()) { 5792 m_warnings_issued[warning_type] = WarningsPointerSet(); 5793 m_warnings_issued[warning_type].insert(repeat_key); 5794 } else { 5795 if (it->second.find(repeat_key) != it->second.end()) { 5796 print_warning = false; 5797 } else { 5798 it->second.insert(repeat_key); 5799 } 5800 } 5801 } 5802 5803 if (print_warning) { 5804 va_list args; 5805 va_start(args, fmt); 5806 stream_sp->PrintfVarArg(fmt, args); 5807 va_end(args); 5808 } 5809 } 5810 5811 void Process::PrintWarningOptimization(const SymbolContext &sc) { 5812 if (!GetWarningsOptimization()) 5813 return; 5814 if (!sc.module_sp) 5815 return; 5816 if (!sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function && 5817 sc.function->GetIsOptimized()) { 5818 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(), 5819 "%s was compiled with optimization - stepping may behave " 5820 "oddly; variables may not be available.\n", 5821 sc.module_sp->GetFileSpec().GetFilename().GetCString()); 5822 } 5823 } 5824 5825 void Process::PrintWarningUnsupportedLanguage(const SymbolContext &sc) { 5826 if (!GetWarningsUnsupportedLanguage()) 5827 return; 5828 if (!sc.module_sp) 5829 return; 5830 LanguageType language = sc.GetLanguage(); 5831 if (language == eLanguageTypeUnknown) 5832 return; 5833 auto type_system_or_err = sc.module_sp->GetTypeSystemForLanguage(language); 5834 if (auto err = type_system_or_err.takeError()) { 5835 llvm::consumeError(std::move(err)); 5836 PrintWarning(Process::Warnings::eWarningsUnsupportedLanguage, 5837 sc.module_sp.get(), 5838 "This version of LLDB has no plugin for the %s language. " 5839 "Inspection of frame variables will be limited.\n", 5840 Language::GetNameForLanguageType(language)); 5841 } 5842 } 5843 5844 bool Process::GetProcessInfo(ProcessInstanceInfo &info) { 5845 info.Clear(); 5846 5847 PlatformSP platform_sp = GetTarget().GetPlatform(); 5848 if (!platform_sp) 5849 return false; 5850 5851 return platform_sp->GetProcessInfo(GetID(), info); 5852 } 5853 5854 ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) { 5855 ThreadCollectionSP threads; 5856 5857 const MemoryHistorySP &memory_history = 5858 MemoryHistory::FindPlugin(shared_from_this()); 5859 5860 if (!memory_history) { 5861 return threads; 5862 } 5863 5864 threads = std::make_shared<ThreadCollection>( 5865 memory_history->GetHistoryThreads(addr)); 5866 5867 return threads; 5868 } 5869 5870 InstrumentationRuntimeSP 5871 Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) { 5872 InstrumentationRuntimeCollection::iterator pos; 5873 pos = m_instrumentation_runtimes.find(type); 5874 if (pos == m_instrumentation_runtimes.end()) { 5875 return InstrumentationRuntimeSP(); 5876 } else 5877 return (*pos).second; 5878 } 5879 5880 bool Process::GetModuleSpec(const FileSpec &module_file_spec, 5881 const ArchSpec &arch, ModuleSpec &module_spec) { 5882 module_spec.Clear(); 5883 return false; 5884 } 5885 5886 size_t Process::AddImageToken(lldb::addr_t image_ptr) { 5887 m_image_tokens.push_back(image_ptr); 5888 return m_image_tokens.size() - 1; 5889 } 5890 5891 lldb::addr_t Process::GetImagePtrFromToken(size_t token) const { 5892 if (token < m_image_tokens.size()) 5893 return m_image_tokens[token]; 5894 return LLDB_INVALID_ADDRESS; 5895 } 5896 5897 void Process::ResetImageToken(size_t token) { 5898 if (token < m_image_tokens.size()) 5899 m_image_tokens[token] = LLDB_INVALID_ADDRESS; 5900 } 5901 5902 Address 5903 Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr, 5904 AddressRange range_bounds) { 5905 Target &target = GetTarget(); 5906 DisassemblerSP disassembler_sp; 5907 InstructionList *insn_list = nullptr; 5908 5909 Address retval = default_stop_addr; 5910 5911 if (!target.GetUseFastStepping()) 5912 return retval; 5913 if (!default_stop_addr.IsValid()) 5914 return retval; 5915 5916 const char *plugin_name = nullptr; 5917 const char *flavor = nullptr; 5918 const bool prefer_file_cache = true; 5919 disassembler_sp = Disassembler::DisassembleRange( 5920 target.GetArchitecture(), plugin_name, flavor, GetTarget(), range_bounds, 5921 prefer_file_cache); 5922 if (disassembler_sp) 5923 insn_list = &disassembler_sp->GetInstructionList(); 5924 5925 if (insn_list == nullptr) { 5926 return retval; 5927 } 5928 5929 size_t insn_offset = 5930 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr); 5931 if (insn_offset == UINT32_MAX) { 5932 return retval; 5933 } 5934 5935 uint32_t branch_index = 5936 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target, 5937 false /* ignore_calls*/, 5938 nullptr); 5939 if (branch_index == UINT32_MAX) { 5940 return retval; 5941 } 5942 5943 if (branch_index > insn_offset) { 5944 Address next_branch_insn_address = 5945 insn_list->GetInstructionAtIndex(branch_index)->GetAddress(); 5946 if (next_branch_insn_address.IsValid() && 5947 range_bounds.ContainsFileAddress(next_branch_insn_address)) { 5948 retval = next_branch_insn_address; 5949 } 5950 } 5951 5952 return retval; 5953 } 5954 5955 Status 5956 Process::GetMemoryRegions(lldb_private::MemoryRegionInfos ®ion_list) { 5957 5958 Status error; 5959 5960 lldb::addr_t range_end = 0; 5961 5962 region_list.clear(); 5963 do { 5964 lldb_private::MemoryRegionInfo region_info; 5965 error = GetMemoryRegionInfo(range_end, region_info); 5966 // GetMemoryRegionInfo should only return an error if it is unimplemented. 5967 if (error.Fail()) { 5968 region_list.clear(); 5969 break; 5970 } 5971 5972 range_end = region_info.GetRange().GetRangeEnd(); 5973 if (region_info.GetMapped() == MemoryRegionInfo::eYes) { 5974 region_list.push_back(std::move(region_info)); 5975 } 5976 } while (range_end != LLDB_INVALID_ADDRESS); 5977 5978 return error; 5979 } 5980 5981 Status 5982 Process::ConfigureStructuredData(ConstString type_name, 5983 const StructuredData::ObjectSP &config_sp) { 5984 // If you get this, the Process-derived class needs to implement a method to 5985 // enable an already-reported asynchronous structured data feature. See 5986 // ProcessGDBRemote for an example implementation over gdb-remote. 5987 return Status("unimplemented"); 5988 } 5989 5990 void Process::MapSupportedStructuredDataPlugins( 5991 const StructuredData::Array &supported_type_names) { 5992 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 5993 5994 // Bail out early if there are no type names to map. 5995 if (supported_type_names.GetSize() == 0) { 5996 LLDB_LOGF(log, "Process::%s(): no structured data types supported", 5997 __FUNCTION__); 5998 return; 5999 } 6000 6001 // Convert StructuredData type names to ConstString instances. 6002 std::set<ConstString> const_type_names; 6003 6004 LLDB_LOGF(log, 6005 "Process::%s(): the process supports the following async " 6006 "structured data types:", 6007 __FUNCTION__); 6008 6009 supported_type_names.ForEach( 6010 [&const_type_names, &log](StructuredData::Object *object) { 6011 if (!object) { 6012 // Invalid - shouldn't be null objects in the array. 6013 return false; 6014 } 6015 6016 auto type_name = object->GetAsString(); 6017 if (!type_name) { 6018 // Invalid format - all type names should be strings. 6019 return false; 6020 } 6021 6022 const_type_names.insert(ConstString(type_name->GetValue())); 6023 LLDB_LOG(log, "- {0}", type_name->GetValue()); 6024 return true; 6025 }); 6026 6027 // For each StructuredDataPlugin, if the plugin handles any of the types in 6028 // the supported_type_names, map that type name to that plugin. Stop when 6029 // we've consumed all the type names. 6030 // FIXME: should we return an error if there are type names nobody 6031 // supports? 6032 for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) { 6033 auto create_instance = 6034 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex( 6035 plugin_index); 6036 if (!create_instance) 6037 break; 6038 6039 // Create the plugin. 6040 StructuredDataPluginSP plugin_sp = (*create_instance)(*this); 6041 if (!plugin_sp) { 6042 // This plugin doesn't think it can work with the process. Move on to the 6043 // next. 6044 continue; 6045 } 6046 6047 // For any of the remaining type names, map any that this plugin supports. 6048 std::vector<ConstString> names_to_remove; 6049 for (auto &type_name : const_type_names) { 6050 if (plugin_sp->SupportsStructuredDataType(type_name)) { 6051 m_structured_data_plugin_map.insert( 6052 std::make_pair(type_name, plugin_sp)); 6053 names_to_remove.push_back(type_name); 6054 LLDB_LOGF(log, 6055 "Process::%s(): using plugin %s for type name " 6056 "%s", 6057 __FUNCTION__, plugin_sp->GetPluginName().GetCString(), 6058 type_name.GetCString()); 6059 } 6060 } 6061 6062 // Remove the type names that were consumed by this plugin. 6063 for (auto &type_name : names_to_remove) 6064 const_type_names.erase(type_name); 6065 } 6066 } 6067 6068 bool Process::RouteAsyncStructuredData( 6069 const StructuredData::ObjectSP object_sp) { 6070 // Nothing to do if there's no data. 6071 if (!object_sp) 6072 return false; 6073 6074 // The contract is this must be a dictionary, so we can look up the routing 6075 // key via the top-level 'type' string value within the dictionary. 6076 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary(); 6077 if (!dictionary) 6078 return false; 6079 6080 // Grab the async structured type name (i.e. the feature/plugin name). 6081 ConstString type_name; 6082 if (!dictionary->GetValueForKeyAsString("type", type_name)) 6083 return false; 6084 6085 // Check if there's a plugin registered for this type name. 6086 auto find_it = m_structured_data_plugin_map.find(type_name); 6087 if (find_it == m_structured_data_plugin_map.end()) { 6088 // We don't have a mapping for this structured data type. 6089 return false; 6090 } 6091 6092 // Route the structured data to the plugin. 6093 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp); 6094 return true; 6095 } 6096 6097 Status Process::UpdateAutomaticSignalFiltering() { 6098 // Default implementation does nothign. 6099 // No automatic signal filtering to speak of. 6100 return Status(); 6101 } 6102 6103 UtilityFunction *Process::GetLoadImageUtilityFunction( 6104 Platform *platform, 6105 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) { 6106 if (platform != GetTarget().GetPlatform().get()) 6107 return nullptr; 6108 llvm::call_once(m_dlopen_utility_func_flag_once, 6109 [&] { m_dlopen_utility_func_up = factory(); }); 6110 return m_dlopen_utility_func_up.get(); 6111 } 6112 6113 bool Process::CallVoidArgVoidPtrReturn(const Address *address, 6114 addr_t &returned_func, 6115 bool trap_exceptions) { 6116 Thread *thread = GetThreadList().GetExpressionExecutionThread().get(); 6117 if (thread == nullptr || address == nullptr) 6118 return false; 6119 6120 EvaluateExpressionOptions options; 6121 options.SetStopOthers(true); 6122 options.SetUnwindOnError(true); 6123 options.SetIgnoreBreakpoints(true); 6124 options.SetTryAllThreads(true); 6125 options.SetDebug(false); 6126 options.SetTimeout(GetUtilityExpressionTimeout()); 6127 options.SetTrapExceptions(trap_exceptions); 6128 6129 auto type_system_or_err = 6130 GetTarget().GetScratchTypeSystemForLanguage(eLanguageTypeC); 6131 if (!type_system_or_err) { 6132 llvm::consumeError(type_system_or_err.takeError()); 6133 return false; 6134 } 6135 CompilerType void_ptr_type = 6136 type_system_or_err->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType(); 6137 lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallFunction( 6138 *thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options)); 6139 if (call_plan_sp) { 6140 DiagnosticManager diagnostics; 6141 6142 StackFrame *frame = thread->GetStackFrameAtIndex(0).get(); 6143 if (frame) { 6144 ExecutionContext exe_ctx; 6145 frame->CalculateExecutionContext(exe_ctx); 6146 ExpressionResults result = 6147 RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics); 6148 if (result == eExpressionCompleted) { 6149 returned_func = 6150 call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned( 6151 LLDB_INVALID_ADDRESS); 6152 6153 if (GetAddressByteSize() == 4) { 6154 if (returned_func == UINT32_MAX) 6155 return false; 6156 } else if (GetAddressByteSize() == 8) { 6157 if (returned_func == UINT64_MAX) 6158 return false; 6159 } 6160 return true; 6161 } 6162 } 6163 } 6164 6165 return false; 6166 } 6167