1 //===-- ProcessWindows.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 "ProcessWindows.h" 10 11 // Windows includes 12 #include "lldb/Host/windows/windows.h" 13 #include <psapi.h> 14 15 #include "lldb/Breakpoint/Watchpoint.h" 16 #include "lldb/Core/Module.h" 17 #include "lldb/Core/ModuleSpec.h" 18 #include "lldb/Core/PluginManager.h" 19 #include "lldb/Core/Section.h" 20 #include "lldb/Host/FileSystem.h" 21 #include "lldb/Host/HostNativeProcessBase.h" 22 #include "lldb/Host/HostProcess.h" 23 #include "lldb/Host/windows/HostThreadWindows.h" 24 #include "lldb/Host/windows/windows.h" 25 #include "lldb/Symbol/ObjectFile.h" 26 #include "lldb/Target/DynamicLoader.h" 27 #include "lldb/Target/MemoryRegionInfo.h" 28 #include "lldb/Target/StopInfo.h" 29 #include "lldb/Target/Target.h" 30 #include "lldb/Utility/State.h" 31 32 #include "llvm/Support/ConvertUTF.h" 33 #include "llvm/Support/Format.h" 34 #include "llvm/Support/Threading.h" 35 #include "llvm/Support/raw_ostream.h" 36 37 #include "DebuggerThread.h" 38 #include "ExceptionRecord.h" 39 #include "ForwardDecl.h" 40 #include "LocalDebugDelegate.h" 41 #include "ProcessWindowsLog.h" 42 #include "TargetThreadWindows.h" 43 44 using namespace lldb; 45 using namespace lldb_private; 46 47 LLDB_PLUGIN_DEFINE_ADV(ProcessWindows, ProcessWindowsCommon) 48 49 namespace { 50 std::string GetProcessExecutableName(HANDLE process_handle) { 51 std::vector<wchar_t> file_name; 52 DWORD file_name_size = MAX_PATH; // first guess, not an absolute limit 53 DWORD copied = 0; 54 do { 55 file_name_size *= 2; 56 file_name.resize(file_name_size); 57 copied = ::GetModuleFileNameExW(process_handle, NULL, file_name.data(), 58 file_name_size); 59 } while (copied >= file_name_size); 60 file_name.resize(copied); 61 std::string result; 62 llvm::convertWideToUTF8(file_name.data(), result); 63 return result; 64 } 65 66 std::string GetProcessExecutableName(DWORD pid) { 67 std::string file_name; 68 HANDLE process_handle = 69 ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid); 70 if (process_handle != NULL) { 71 file_name = GetProcessExecutableName(process_handle); 72 ::CloseHandle(process_handle); 73 } 74 return file_name; 75 } 76 } // anonymous namespace 77 78 namespace lldb_private { 79 80 ProcessSP ProcessWindows::CreateInstance(lldb::TargetSP target_sp, 81 lldb::ListenerSP listener_sp, 82 const FileSpec *, 83 bool can_connect) { 84 return ProcessSP(new ProcessWindows(target_sp, listener_sp)); 85 } 86 87 static bool ShouldUseLLDBServer() { 88 llvm::StringRef use_lldb_server = ::getenv("LLDB_USE_LLDB_SERVER"); 89 return use_lldb_server.equals_insensitive("on") || 90 use_lldb_server.equals_insensitive("yes") || 91 use_lldb_server.equals_insensitive("1") || 92 use_lldb_server.equals_insensitive("true"); 93 } 94 95 void ProcessWindows::Initialize() { 96 if (!ShouldUseLLDBServer()) { 97 static llvm::once_flag g_once_flag; 98 99 llvm::call_once(g_once_flag, []() { 100 PluginManager::RegisterPlugin(GetPluginNameStatic(), 101 GetPluginDescriptionStatic(), 102 CreateInstance); 103 }); 104 } 105 } 106 107 void ProcessWindows::Terminate() {} 108 109 lldb_private::ConstString ProcessWindows::GetPluginNameStatic() { 110 static ConstString g_name("windows"); 111 return g_name; 112 } 113 114 const char *ProcessWindows::GetPluginDescriptionStatic() { 115 return "Process plugin for Windows"; 116 } 117 118 // Constructors and destructors. 119 120 ProcessWindows::ProcessWindows(lldb::TargetSP target_sp, 121 lldb::ListenerSP listener_sp) 122 : lldb_private::Process(target_sp, listener_sp), 123 m_watchpoint_ids( 124 RegisterContextWindows::GetNumHardwareBreakpointSlots(), 125 LLDB_INVALID_BREAK_ID) {} 126 127 ProcessWindows::~ProcessWindows() {} 128 129 size_t ProcessWindows::GetSTDOUT(char *buf, size_t buf_size, Status &error) { 130 error.SetErrorString("GetSTDOUT unsupported on Windows"); 131 return 0; 132 } 133 134 size_t ProcessWindows::GetSTDERR(char *buf, size_t buf_size, Status &error) { 135 error.SetErrorString("GetSTDERR unsupported on Windows"); 136 return 0; 137 } 138 139 size_t ProcessWindows::PutSTDIN(const char *buf, size_t buf_size, 140 Status &error) { 141 error.SetErrorString("PutSTDIN unsupported on Windows"); 142 return 0; 143 } 144 145 // ProcessInterface protocol. 146 147 lldb_private::ConstString ProcessWindows::GetPluginName() { 148 return GetPluginNameStatic(); 149 } 150 151 Status ProcessWindows::EnableBreakpointSite(BreakpointSite *bp_site) { 152 if (bp_site->HardwareRequired()) 153 return Status("Hardware breakpoints are not supported."); 154 155 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_BREAKPOINTS); 156 LLDB_LOG(log, "bp_site = {0:x}, id={1}, addr={2:x}", bp_site, 157 bp_site->GetID(), bp_site->GetLoadAddress()); 158 159 Status error = EnableSoftwareBreakpoint(bp_site); 160 if (!error.Success()) 161 LLDB_LOG(log, "error: {0}", error); 162 return error; 163 } 164 165 Status ProcessWindows::DisableBreakpointSite(BreakpointSite *bp_site) { 166 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_BREAKPOINTS); 167 LLDB_LOG(log, "bp_site = {0:x}, id={1}, addr={2:x}", bp_site, 168 bp_site->GetID(), bp_site->GetLoadAddress()); 169 170 Status error = DisableSoftwareBreakpoint(bp_site); 171 172 if (!error.Success()) 173 LLDB_LOG(log, "error: {0}", error); 174 return error; 175 } 176 177 Status ProcessWindows::DoDetach(bool keep_stopped) { 178 Status error; 179 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); 180 StateType private_state = GetPrivateState(); 181 if (private_state != eStateExited && private_state != eStateDetached) { 182 error = DetachProcess(); 183 if (error.Success()) 184 SetPrivateState(eStateDetached); 185 else 186 LLDB_LOG(log, "Detaching process error: {0}", error); 187 } else { 188 error.SetErrorStringWithFormatv("error: process {0} in state = {1}, but " 189 "cannot detach it in this state.", 190 GetID(), private_state); 191 LLDB_LOG(log, "error: {0}", error); 192 } 193 return error; 194 } 195 196 Status ProcessWindows::DoLaunch(Module *exe_module, 197 ProcessLaunchInfo &launch_info) { 198 Status error; 199 DebugDelegateSP delegate(new LocalDebugDelegate(shared_from_this())); 200 error = LaunchProcess(launch_info, delegate); 201 if (error.Success()) 202 SetID(launch_info.GetProcessID()); 203 return error; 204 } 205 206 Status 207 ProcessWindows::DoAttachToProcessWithID(lldb::pid_t pid, 208 const ProcessAttachInfo &attach_info) { 209 DebugDelegateSP delegate(new LocalDebugDelegate(shared_from_this())); 210 Status error = AttachProcess(pid, attach_info, delegate); 211 if (error.Success()) 212 SetID(GetDebuggedProcessId()); 213 return error; 214 } 215 216 Status ProcessWindows::DoResume() { 217 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); 218 llvm::sys::ScopedLock lock(m_mutex); 219 Status error; 220 221 StateType private_state = GetPrivateState(); 222 if (private_state == eStateStopped || private_state == eStateCrashed) { 223 LLDB_LOG(log, "process {0} is in state {1}. Resuming...", 224 m_session_data->m_debugger->GetProcess().GetProcessId(), 225 GetPrivateState()); 226 227 LLDB_LOG(log, "resuming {0} threads.", m_thread_list.GetSize()); 228 229 bool failed = false; 230 for (uint32_t i = 0; i < m_thread_list.GetSize(); ++i) { 231 auto thread = std::static_pointer_cast<TargetThreadWindows>( 232 m_thread_list.GetThreadAtIndex(i)); 233 Status result = thread->DoResume(); 234 if (result.Fail()) { 235 failed = true; 236 LLDB_LOG( 237 log, 238 "Trying to resume thread at index {0}, but failed with error {1}.", 239 i, result); 240 } 241 } 242 243 if (failed) { 244 error.SetErrorString("ProcessWindows::DoResume failed"); 245 } else { 246 SetPrivateState(eStateRunning); 247 } 248 249 ExceptionRecordSP active_exception = 250 m_session_data->m_debugger->GetActiveException().lock(); 251 if (active_exception) { 252 // Resume the process and continue processing debug events. Mask the 253 // exception so that from the process's view, there is no indication that 254 // anything happened. 255 m_session_data->m_debugger->ContinueAsyncException( 256 ExceptionResult::MaskException); 257 } 258 } else { 259 LLDB_LOG(log, "error: process {0} is in state {1}. Returning...", 260 m_session_data->m_debugger->GetProcess().GetProcessId(), 261 GetPrivateState()); 262 } 263 return error; 264 } 265 266 Status ProcessWindows::DoDestroy() { 267 StateType private_state = GetPrivateState(); 268 return DestroyProcess(private_state); 269 } 270 271 Status ProcessWindows::DoHalt(bool &caused_stop) { 272 StateType state = GetPrivateState(); 273 if (state != eStateStopped) 274 return HaltProcess(caused_stop); 275 caused_stop = false; 276 return Status(); 277 } 278 279 void ProcessWindows::DidLaunch() { 280 ArchSpec arch_spec; 281 DidAttach(arch_spec); 282 } 283 284 void ProcessWindows::DidAttach(ArchSpec &arch_spec) { 285 llvm::sys::ScopedLock lock(m_mutex); 286 287 // The initial stop won't broadcast the state change event, so account for 288 // that here. 289 if (m_session_data && GetPrivateState() == eStateStopped && 290 m_session_data->m_stop_at_entry) 291 RefreshStateAfterStop(); 292 } 293 294 static void 295 DumpAdditionalExceptionInformation(llvm::raw_ostream &stream, 296 const ExceptionRecordSP &exception) { 297 // Decode additional exception information for specific exception types based 298 // on 299 // https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_exception_record 300 301 const int addr_min_width = 2 + 8; // "0x" + 4 address bytes 302 303 const std::vector<ULONG_PTR> &args = exception->GetExceptionArguments(); 304 switch (exception->GetExceptionCode()) { 305 case EXCEPTION_ACCESS_VIOLATION: { 306 if (args.size() < 2) 307 break; 308 309 stream << ": "; 310 const int access_violation_code = args[0]; 311 const lldb::addr_t access_violation_address = args[1]; 312 switch (access_violation_code) { 313 case 0: 314 stream << "Access violation reading"; 315 break; 316 case 1: 317 stream << "Access violation writing"; 318 break; 319 case 8: 320 stream << "User-mode data execution prevention (DEP) violation at"; 321 break; 322 default: 323 stream << "Unknown access violation (code " << access_violation_code 324 << ") at"; 325 break; 326 } 327 stream << " location " 328 << llvm::format_hex(access_violation_address, addr_min_width); 329 break; 330 } 331 case EXCEPTION_IN_PAGE_ERROR: { 332 if (args.size() < 3) 333 break; 334 335 stream << ": "; 336 const int page_load_error_code = args[0]; 337 const lldb::addr_t page_load_error_address = args[1]; 338 const DWORD underlying_code = args[2]; 339 switch (page_load_error_code) { 340 case 0: 341 stream << "In page error reading"; 342 break; 343 case 1: 344 stream << "In page error writing"; 345 break; 346 case 8: 347 stream << "User-mode data execution prevention (DEP) violation at"; 348 break; 349 default: 350 stream << "Unknown page loading error (code " << page_load_error_code 351 << ") at"; 352 break; 353 } 354 stream << " location " 355 << llvm::format_hex(page_load_error_address, addr_min_width) 356 << " (status code " << llvm::format_hex(underlying_code, 8) << ")"; 357 break; 358 } 359 } 360 } 361 362 void ProcessWindows::RefreshStateAfterStop() { 363 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EXCEPTION); 364 llvm::sys::ScopedLock lock(m_mutex); 365 366 if (!m_session_data) { 367 LLDB_LOG(log, "no active session. Returning..."); 368 return; 369 } 370 371 m_thread_list.RefreshStateAfterStop(); 372 373 std::weak_ptr<ExceptionRecord> exception_record = 374 m_session_data->m_debugger->GetActiveException(); 375 ExceptionRecordSP active_exception = exception_record.lock(); 376 if (!active_exception) { 377 LLDB_LOG(log, 378 "there is no active exception in process {0}. Why is the " 379 "process stopped?", 380 m_session_data->m_debugger->GetProcess().GetProcessId()); 381 return; 382 } 383 384 StopInfoSP stop_info; 385 m_thread_list.SetSelectedThreadByID(active_exception->GetThreadID()); 386 ThreadSP stop_thread = m_thread_list.GetSelectedThread(); 387 if (!stop_thread) 388 return; 389 390 switch (active_exception->GetExceptionCode()) { 391 case EXCEPTION_SINGLE_STEP: { 392 RegisterContextSP register_context = stop_thread->GetRegisterContext(); 393 const uint64_t pc = register_context->GetPC(); 394 BreakpointSiteSP site(GetBreakpointSiteList().FindByAddress(pc)); 395 if (site && site->ValidForThisThread(*stop_thread)) { 396 LLDB_LOG(log, 397 "Single-stepped onto a breakpoint in process {0} at " 398 "address {1:x} with breakpoint site {2}", 399 m_session_data->m_debugger->GetProcess().GetProcessId(), pc, 400 site->GetID()); 401 stop_info = StopInfo::CreateStopReasonWithBreakpointSiteID(*stop_thread, 402 site->GetID()); 403 stop_thread->SetStopInfo(stop_info); 404 405 return; 406 } 407 408 auto *reg_ctx = static_cast<RegisterContextWindows *>( 409 stop_thread->GetRegisterContext().get()); 410 uint32_t slot_id = reg_ctx->GetTriggeredHardwareBreakpointSlotId(); 411 if (slot_id != LLDB_INVALID_INDEX32) { 412 int id = m_watchpoint_ids[slot_id]; 413 LLDB_LOG(log, 414 "Single-stepped onto a watchpoint in process {0} at address " 415 "{1:x} with watchpoint {2}", 416 m_session_data->m_debugger->GetProcess().GetProcessId(), pc, id); 417 418 if (lldb::WatchpointSP wp_sp = 419 GetTarget().GetWatchpointList().FindByID(id)) 420 wp_sp->SetHardwareIndex(slot_id); 421 422 stop_info = StopInfo::CreateStopReasonWithWatchpointID( 423 *stop_thread, id, m_watchpoints[id].address); 424 stop_thread->SetStopInfo(stop_info); 425 426 return; 427 } 428 429 LLDB_LOG(log, "single stepping thread {0}", stop_thread->GetID()); 430 stop_info = StopInfo::CreateStopReasonToTrace(*stop_thread); 431 stop_thread->SetStopInfo(stop_info); 432 433 return; 434 } 435 436 case EXCEPTION_BREAKPOINT: { 437 RegisterContextSP register_context = stop_thread->GetRegisterContext(); 438 439 int breakpoint_size = 1; 440 switch (GetTarget().GetArchitecture().GetMachine()) { 441 case llvm::Triple::aarch64: 442 breakpoint_size = 4; 443 break; 444 445 case llvm::Triple::arm: 446 case llvm::Triple::thumb: 447 breakpoint_size = 2; 448 break; 449 450 case llvm::Triple::x86: 451 case llvm::Triple::x86_64: 452 breakpoint_size = 1; 453 break; 454 455 default: 456 LLDB_LOG(log, "Unknown breakpoint size for architecture"); 457 break; 458 } 459 460 // The current PC is AFTER the BP opcode, on all architectures. 461 uint64_t pc = register_context->GetPC() - breakpoint_size; 462 463 BreakpointSiteSP site(GetBreakpointSiteList().FindByAddress(pc)); 464 if (site) { 465 LLDB_LOG(log, 466 "detected breakpoint in process {0} at address {1:x} with " 467 "breakpoint site {2}", 468 m_session_data->m_debugger->GetProcess().GetProcessId(), pc, 469 site->GetID()); 470 471 if (site->ValidForThisThread(*stop_thread)) { 472 LLDB_LOG(log, 473 "Breakpoint site {0} is valid for this thread ({1:x}), " 474 "creating stop info.", 475 site->GetID(), stop_thread->GetID()); 476 477 stop_info = StopInfo::CreateStopReasonWithBreakpointSiteID( 478 *stop_thread, site->GetID()); 479 register_context->SetPC(pc); 480 } else { 481 LLDB_LOG(log, 482 "Breakpoint site {0} is not valid for this thread, " 483 "creating empty stop info.", 484 site->GetID()); 485 } 486 stop_thread->SetStopInfo(stop_info); 487 return; 488 } else { 489 // The thread hit a hard-coded breakpoint like an `int 3` or 490 // `__debugbreak()`. 491 LLDB_LOG(log, 492 "No breakpoint site matches for this thread. __debugbreak()? " 493 "Creating stop info with the exception."); 494 // FALLTHROUGH: We'll treat this as a generic exception record in the 495 // default case. 496 LLVM_FALLTHROUGH; 497 } 498 } 499 500 default: { 501 std::string desc; 502 llvm::raw_string_ostream desc_stream(desc); 503 desc_stream << "Exception " 504 << llvm::format_hex(active_exception->GetExceptionCode(), 8) 505 << " encountered at address " 506 << llvm::format_hex(active_exception->GetExceptionAddress(), 8); 507 DumpAdditionalExceptionInformation(desc_stream, active_exception); 508 509 stop_info = StopInfo::CreateStopReasonWithException( 510 *stop_thread, desc_stream.str().c_str()); 511 stop_thread->SetStopInfo(stop_info); 512 LLDB_LOG(log, "{0}", desc_stream.str()); 513 return; 514 } 515 } 516 } 517 518 bool ProcessWindows::CanDebug(lldb::TargetSP target_sp, 519 bool plugin_specified_by_name) { 520 if (plugin_specified_by_name) 521 return true; 522 523 // For now we are just making sure the file exists for a given module 524 ModuleSP exe_module_sp(target_sp->GetExecutableModule()); 525 if (exe_module_sp.get()) 526 return FileSystem::Instance().Exists(exe_module_sp->GetFileSpec()); 527 // However, if there is no executable module, we return true since we might 528 // be preparing to attach. 529 return true; 530 } 531 532 bool ProcessWindows::DoUpdateThreadList(ThreadList &old_thread_list, 533 ThreadList &new_thread_list) { 534 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_THREAD); 535 // Add all the threads that were previously running and for which we did not 536 // detect a thread exited event. 537 int new_size = 0; 538 int continued_threads = 0; 539 int exited_threads = 0; 540 int new_threads = 0; 541 542 for (ThreadSP old_thread : old_thread_list.Threads()) { 543 lldb::tid_t old_thread_id = old_thread->GetID(); 544 auto exited_thread_iter = 545 m_session_data->m_exited_threads.find(old_thread_id); 546 if (exited_thread_iter == m_session_data->m_exited_threads.end()) { 547 new_thread_list.AddThread(old_thread); 548 ++new_size; 549 ++continued_threads; 550 LLDB_LOGV(log, "Thread {0} was running and is still running.", 551 old_thread_id); 552 } else { 553 LLDB_LOGV(log, "Thread {0} was running and has exited.", old_thread_id); 554 ++exited_threads; 555 } 556 } 557 558 // Also add all the threads that are new since the last time we broke into 559 // the debugger. 560 for (const auto &thread_info : m_session_data->m_new_threads) { 561 new_thread_list.AddThread(thread_info.second); 562 ++new_size; 563 ++new_threads; 564 LLDB_LOGV(log, "Thread {0} is new since last update.", thread_info.first); 565 } 566 567 LLDB_LOG(log, "{0} new threads, {1} old threads, {2} exited threads.", 568 new_threads, continued_threads, exited_threads); 569 570 m_session_data->m_new_threads.clear(); 571 m_session_data->m_exited_threads.clear(); 572 573 return new_size > 0; 574 } 575 576 bool ProcessWindows::IsAlive() { 577 StateType state = GetPrivateState(); 578 switch (state) { 579 case eStateCrashed: 580 case eStateDetached: 581 case eStateUnloaded: 582 case eStateExited: 583 case eStateInvalid: 584 return false; 585 default: 586 return true; 587 } 588 } 589 590 size_t ProcessWindows::DoReadMemory(lldb::addr_t vm_addr, void *buf, 591 size_t size, Status &error) { 592 size_t bytes_read = 0; 593 error = ProcessDebugger::ReadMemory(vm_addr, buf, size, bytes_read); 594 return bytes_read; 595 } 596 597 size_t ProcessWindows::DoWriteMemory(lldb::addr_t vm_addr, const void *buf, 598 size_t size, Status &error) { 599 size_t bytes_written = 0; 600 error = ProcessDebugger::WriteMemory(vm_addr, buf, size, bytes_written); 601 return bytes_written; 602 } 603 604 lldb::addr_t ProcessWindows::DoAllocateMemory(size_t size, uint32_t permissions, 605 Status &error) { 606 lldb::addr_t vm_addr = LLDB_INVALID_ADDRESS; 607 error = ProcessDebugger::AllocateMemory(size, permissions, vm_addr); 608 return vm_addr; 609 } 610 611 Status ProcessWindows::DoDeallocateMemory(lldb::addr_t ptr) { 612 return ProcessDebugger::DeallocateMemory(ptr); 613 } 614 615 Status ProcessWindows::GetMemoryRegionInfo(lldb::addr_t vm_addr, 616 MemoryRegionInfo &info) { 617 return ProcessDebugger::GetMemoryRegionInfo(vm_addr, info); 618 } 619 620 lldb::addr_t ProcessWindows::GetImageInfoAddress() { 621 Target &target = GetTarget(); 622 ObjectFile *obj_file = target.GetExecutableModule()->GetObjectFile(); 623 Address addr = obj_file->GetImageInfoAddress(&target); 624 if (addr.IsValid()) 625 return addr.GetLoadAddress(&target); 626 else 627 return LLDB_INVALID_ADDRESS; 628 } 629 630 DynamicLoaderWindowsDYLD *ProcessWindows::GetDynamicLoader() { 631 if (m_dyld_up.get() == NULL) 632 m_dyld_up.reset(DynamicLoader::FindPlugin( 633 this, DynamicLoaderWindowsDYLD::GetPluginNameStatic().GetCString())); 634 return static_cast<DynamicLoaderWindowsDYLD *>(m_dyld_up.get()); 635 } 636 637 void ProcessWindows::OnExitProcess(uint32_t exit_code) { 638 // No need to acquire the lock since m_session_data isn't accessed. 639 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); 640 LLDB_LOG(log, "Process {0} exited with code {1}", GetID(), exit_code); 641 642 TargetSP target = CalculateTarget(); 643 if (target) { 644 ModuleSP executable_module = target->GetExecutableModule(); 645 ModuleList unloaded_modules; 646 unloaded_modules.Append(executable_module); 647 target->ModulesDidUnload(unloaded_modules, true); 648 } 649 650 SetProcessExitStatus(GetID(), true, 0, exit_code); 651 SetPrivateState(eStateExited); 652 653 ProcessDebugger::OnExitProcess(exit_code); 654 } 655 656 void ProcessWindows::OnDebuggerConnected(lldb::addr_t image_base) { 657 DebuggerThreadSP debugger = m_session_data->m_debugger; 658 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); 659 LLDB_LOG(log, "Debugger connected to process {0}. Image base = {1:x}", 660 debugger->GetProcess().GetProcessId(), image_base); 661 662 ModuleSP module = GetTarget().GetExecutableModule(); 663 if (!module) { 664 // During attach, we won't have the executable module, so find it now. 665 const DWORD pid = debugger->GetProcess().GetProcessId(); 666 const std::string file_name = GetProcessExecutableName(pid); 667 if (file_name.empty()) { 668 return; 669 } 670 671 FileSpec executable_file(file_name); 672 FileSystem::Instance().Resolve(executable_file); 673 ModuleSpec module_spec(executable_file); 674 Status error; 675 module = 676 GetTarget().GetOrCreateModule(module_spec, true /* notify */, &error); 677 if (!module) { 678 return; 679 } 680 681 GetTarget().SetExecutableModule(module, eLoadDependentsNo); 682 } 683 684 if (auto dyld = GetDynamicLoader()) 685 dyld->OnLoadModule(module, ModuleSpec(), image_base); 686 687 // Add the main executable module to the list of pending module loads. We 688 // can't call GetTarget().ModulesDidLoad() here because we still haven't 689 // returned from DoLaunch() / DoAttach() yet so the target may not have set 690 // the process instance to `this` yet. 691 llvm::sys::ScopedLock lock(m_mutex); 692 693 const HostThread &host_main_thread = debugger->GetMainThread(); 694 ThreadSP main_thread = 695 std::make_shared<TargetThreadWindows>(*this, host_main_thread); 696 697 tid_t id = host_main_thread.GetNativeThread().GetThreadId(); 698 main_thread->SetID(id); 699 700 m_session_data->m_new_threads[id] = main_thread; 701 } 702 703 ExceptionResult 704 ProcessWindows::OnDebugException(bool first_chance, 705 const ExceptionRecord &record) { 706 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EXCEPTION); 707 llvm::sys::ScopedLock lock(m_mutex); 708 709 // FIXME: Without this check, occasionally when running the test suite there 710 // is 711 // an issue where m_session_data can be null. It's not clear how this could 712 // happen but it only surfaces while running the test suite. In order to 713 // properly diagnose this, we probably need to first figure allow the test 714 // suite to print out full lldb logs, and then add logging to the process 715 // plugin. 716 if (!m_session_data) { 717 LLDB_LOG(log, 718 "Debugger thread reported exception {0:x} at address {1:x}, " 719 "but there is no session.", 720 record.GetExceptionCode(), record.GetExceptionAddress()); 721 return ExceptionResult::SendToApplication; 722 } 723 724 if (!first_chance) { 725 // Not any second chance exception is an application crash by definition. 726 // It may be an expression evaluation crash. 727 SetPrivateState(eStateStopped); 728 } 729 730 ExceptionResult result = ExceptionResult::SendToApplication; 731 switch (record.GetExceptionCode()) { 732 case EXCEPTION_BREAKPOINT: 733 // Handle breakpoints at the first chance. 734 result = ExceptionResult::BreakInDebugger; 735 736 if (!m_session_data->m_initial_stop_received) { 737 LLDB_LOG( 738 log, 739 "Hit loader breakpoint at address {0:x}, setting initial stop event.", 740 record.GetExceptionAddress()); 741 m_session_data->m_initial_stop_received = true; 742 ::SetEvent(m_session_data->m_initial_stop_event); 743 } else { 744 LLDB_LOG(log, "Hit non-loader breakpoint at address {0:x}.", 745 record.GetExceptionAddress()); 746 } 747 SetPrivateState(eStateStopped); 748 break; 749 case EXCEPTION_SINGLE_STEP: 750 result = ExceptionResult::BreakInDebugger; 751 SetPrivateState(eStateStopped); 752 break; 753 default: 754 LLDB_LOG(log, 755 "Debugger thread reported exception {0:x} at address {1:x} " 756 "(first_chance={2})", 757 record.GetExceptionCode(), record.GetExceptionAddress(), 758 first_chance); 759 // For non-breakpoints, give the application a chance to handle the 760 // exception first. 761 if (first_chance) 762 result = ExceptionResult::SendToApplication; 763 else 764 result = ExceptionResult::BreakInDebugger; 765 } 766 767 return result; 768 } 769 770 void ProcessWindows::OnCreateThread(const HostThread &new_thread) { 771 llvm::sys::ScopedLock lock(m_mutex); 772 773 ThreadSP thread = std::make_shared<TargetThreadWindows>(*this, new_thread); 774 775 const HostNativeThread &native_new_thread = new_thread.GetNativeThread(); 776 tid_t id = native_new_thread.GetThreadId(); 777 thread->SetID(id); 778 779 m_session_data->m_new_threads[id] = thread; 780 781 for (const std::map<int, WatchpointInfo>::value_type &p : m_watchpoints) { 782 auto *reg_ctx = static_cast<RegisterContextWindows *>( 783 thread->GetRegisterContext().get()); 784 reg_ctx->AddHardwareBreakpoint(p.second.slot_id, p.second.address, 785 p.second.size, p.second.read, 786 p.second.write); 787 } 788 } 789 790 void ProcessWindows::OnExitThread(lldb::tid_t thread_id, uint32_t exit_code) { 791 llvm::sys::ScopedLock lock(m_mutex); 792 793 // On a forced termination, we may get exit thread events after the session 794 // data has been cleaned up. 795 if (!m_session_data) 796 return; 797 798 // A thread may have started and exited before the debugger stopped allowing a 799 // refresh. 800 // Just remove it from the new threads list in that case. 801 auto iter = m_session_data->m_new_threads.find(thread_id); 802 if (iter != m_session_data->m_new_threads.end()) 803 m_session_data->m_new_threads.erase(iter); 804 else 805 m_session_data->m_exited_threads.insert(thread_id); 806 } 807 808 void ProcessWindows::OnLoadDll(const ModuleSpec &module_spec, 809 lldb::addr_t module_addr) { 810 if (auto dyld = GetDynamicLoader()) 811 dyld->OnLoadModule(nullptr, module_spec, module_addr); 812 } 813 814 void ProcessWindows::OnUnloadDll(lldb::addr_t module_addr) { 815 if (auto dyld = GetDynamicLoader()) 816 dyld->OnUnloadModule(module_addr); 817 } 818 819 void ProcessWindows::OnDebugString(const std::string &string) {} 820 821 void ProcessWindows::OnDebuggerError(const Status &error, uint32_t type) { 822 llvm::sys::ScopedLock lock(m_mutex); 823 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); 824 825 if (m_session_data->m_initial_stop_received) { 826 // This happened while debugging. Do we shutdown the debugging session, 827 // try to continue, or do something else? 828 LLDB_LOG(log, 829 "Error {0} occurred during debugging. Unexpected behavior " 830 "may result. {1}", 831 error.GetError(), error); 832 } else { 833 // If we haven't actually launched the process yet, this was an error 834 // launching the process. Set the internal error and signal the initial 835 // stop event so that the DoLaunch method wakes up and returns a failure. 836 m_session_data->m_launch_error = error; 837 ::SetEvent(m_session_data->m_initial_stop_event); 838 LLDB_LOG( 839 log, 840 "Error {0} occurred launching the process before the initial stop. {1}", 841 error.GetError(), error); 842 return; 843 } 844 } 845 846 Status ProcessWindows::GetWatchpointSupportInfo(uint32_t &num) { 847 num = RegisterContextWindows::GetNumHardwareBreakpointSlots(); 848 return {}; 849 } 850 851 Status ProcessWindows::GetWatchpointSupportInfo(uint32_t &num, bool &after) { 852 num = RegisterContextWindows::GetNumHardwareBreakpointSlots(); 853 after = RegisterContextWindows::DoHardwareBreakpointsTriggerAfter(); 854 return {}; 855 } 856 857 Status ProcessWindows::EnableWatchpoint(Watchpoint *wp, bool notify) { 858 Status error; 859 860 if (wp->IsEnabled()) { 861 wp->SetEnabled(true, notify); 862 return error; 863 } 864 865 WatchpointInfo info; 866 for (info.slot_id = 0; 867 info.slot_id < RegisterContextWindows::GetNumHardwareBreakpointSlots(); 868 info.slot_id++) 869 if (m_watchpoint_ids[info.slot_id] == LLDB_INVALID_BREAK_ID) 870 break; 871 if (info.slot_id == RegisterContextWindows::GetNumHardwareBreakpointSlots()) { 872 error.SetErrorStringWithFormat("Can't find free slot for watchpoint %i", 873 wp->GetID()); 874 return error; 875 } 876 info.address = wp->GetLoadAddress(); 877 info.size = wp->GetByteSize(); 878 info.read = wp->WatchpointRead(); 879 info.write = wp->WatchpointWrite(); 880 881 for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) { 882 Thread *thread = m_thread_list.GetThreadAtIndex(i).get(); 883 auto *reg_ctx = static_cast<RegisterContextWindows *>( 884 thread->GetRegisterContext().get()); 885 if (!reg_ctx->AddHardwareBreakpoint(info.slot_id, info.address, info.size, 886 info.read, info.write)) { 887 error.SetErrorStringWithFormat( 888 "Can't enable watchpoint %i on thread 0x%llx", wp->GetID(), 889 thread->GetID()); 890 break; 891 } 892 } 893 if (error.Fail()) { 894 for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) { 895 Thread *thread = m_thread_list.GetThreadAtIndex(i).get(); 896 auto *reg_ctx = static_cast<RegisterContextWindows *>( 897 thread->GetRegisterContext().get()); 898 reg_ctx->RemoveHardwareBreakpoint(info.slot_id); 899 } 900 return error; 901 } 902 903 m_watchpoints[wp->GetID()] = info; 904 m_watchpoint_ids[info.slot_id] = wp->GetID(); 905 906 wp->SetEnabled(true, notify); 907 908 return error; 909 } 910 911 Status ProcessWindows::DisableWatchpoint(Watchpoint *wp, bool notify) { 912 Status error; 913 914 if (!wp->IsEnabled()) { 915 wp->SetEnabled(false, notify); 916 return error; 917 } 918 919 auto it = m_watchpoints.find(wp->GetID()); 920 if (it == m_watchpoints.end()) { 921 error.SetErrorStringWithFormat("Info about watchpoint %i is not found", 922 wp->GetID()); 923 return error; 924 } 925 926 for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) { 927 Thread *thread = m_thread_list.GetThreadAtIndex(i).get(); 928 auto *reg_ctx = static_cast<RegisterContextWindows *>( 929 thread->GetRegisterContext().get()); 930 if (!reg_ctx->RemoveHardwareBreakpoint(it->second.slot_id)) { 931 error.SetErrorStringWithFormat( 932 "Can't disable watchpoint %i on thread 0x%llx", wp->GetID(), 933 thread->GetID()); 934 break; 935 } 936 } 937 if (error.Fail()) 938 return error; 939 940 m_watchpoint_ids[it->second.slot_id] = LLDB_INVALID_BREAK_ID; 941 m_watchpoints.erase(it); 942 943 wp->SetEnabled(false, notify); 944 945 return error; 946 } 947 } // namespace lldb_private 948