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