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