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