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