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