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