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