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