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