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