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