1 //===-- ProcessDebugger.cpp -------------------------------------*- C++ -*-===// 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 "ProcessDebugger.h" 10 11 // Windows includes 12 #include "lldb/Host/windows/windows.h" 13 #include <psapi.h> 14 15 #include "lldb/Host/FileSystem.h" 16 #include "lldb/Host/HostNativeProcessBase.h" 17 #include "lldb/Host/HostProcess.h" 18 #include "lldb/Host/HostThread.h" 19 #include "lldb/Host/ProcessLaunchInfo.h" 20 #include "lldb/Target/MemoryRegionInfo.h" 21 #include "lldb/Target/Process.h" 22 #include "llvm/Support/ConvertUTF.h" 23 #include "llvm/Support/Error.h" 24 25 #include "DebuggerThread.h" 26 #include "ExceptionRecord.h" 27 #include "ProcessWindowsLog.h" 28 29 using namespace lldb; 30 using namespace lldb_private; 31 32 static DWORD ConvertLldbToWinApiProtect(uint32_t protect) { 33 // We also can process a read / write permissions here, but if the debugger 34 // will make later a write into the allocated memory, it will fail. To get 35 // around it is possible inside DoWriteMemory to remember memory permissions, 36 // allow write, write and restore permissions, but for now we process only 37 // the executable permission. 38 // 39 // TODO: Process permissions other than executable 40 if (protect & ePermissionsExecutable) 41 return PAGE_EXECUTE_READWRITE; 42 43 return PAGE_READWRITE; 44 } 45 46 // The Windows page protection bits are NOT independent masks that can be 47 // bitwise-ORed together. For example, PAGE_EXECUTE_READ is not (PAGE_EXECUTE 48 // | PAGE_READ). To test for an access type, it's necessary to test for any of 49 // the bits that provide that access type. 50 static bool IsPageReadable(uint32_t protect) { 51 return (protect & PAGE_NOACCESS) == 0; 52 } 53 54 static bool IsPageWritable(uint32_t protect) { 55 return (protect & (PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY | 56 PAGE_READWRITE | PAGE_WRITECOPY)) != 0; 57 } 58 59 static bool IsPageExecutable(uint32_t protect) { 60 return (protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | 61 PAGE_EXECUTE_WRITECOPY)) != 0; 62 } 63 64 namespace lldb_private { 65 66 lldb::pid_t ProcessDebugger::GetDebuggedProcessId() const { 67 if (m_session_data) 68 return m_session_data->m_debugger->GetProcess().GetProcessId(); 69 return LLDB_INVALID_PROCESS_ID; 70 } 71 72 Status ProcessDebugger::DetachProcess() { 73 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); 74 DebuggerThreadSP debugger_thread; 75 { 76 // Acquire the lock only long enough to get the DebuggerThread. 77 // StopDebugging() will trigger a call back into ProcessDebugger which will 78 // also acquire the lock. Thus we have to release the lock before calling 79 // StopDebugging(). 80 llvm::sys::ScopedLock lock(m_mutex); 81 82 if (!m_session_data) { 83 LLDB_LOG(log, "there is no active session."); 84 return Status(); 85 } 86 87 debugger_thread = m_session_data->m_debugger; 88 } 89 90 Status error; 91 92 LLDB_LOG(log, "detaching from process {0}.", 93 debugger_thread->GetProcess().GetNativeProcess().GetSystemHandle()); 94 error = debugger_thread->StopDebugging(false); 95 96 // By the time StopDebugging returns, there is no more debugger thread, so 97 // we can be assured that no other thread will race for the session data. 98 m_session_data.reset(); 99 100 return error; 101 } 102 103 Status ProcessDebugger::LaunchProcess(ProcessLaunchInfo &launch_info, 104 DebugDelegateSP delegate) { 105 // Even though m_session_data is accessed here, it is before a debugger 106 // thread has been kicked off. So there's no race conditions, and it 107 // shouldn't be necessary to acquire the mutex. 108 109 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); 110 Status result; 111 112 FileSpec working_dir = launch_info.GetWorkingDirectory(); 113 namespace fs = llvm::sys::fs; 114 if (working_dir) { 115 FileSystem::Instance().Resolve(working_dir); 116 if (!FileSystem::Instance().IsDirectory(working_dir)) { 117 result.SetErrorStringWithFormat("No such file or directory: %s", 118 working_dir.GetCString()); 119 return result; 120 } 121 } 122 123 if (!launch_info.GetFlags().Test(eLaunchFlagDebug)) { 124 StreamString stream; 125 stream.Printf("ProcessDebugger unable to launch '%s'. ProcessDebugger can " 126 "only be used for debug launches.", 127 launch_info.GetExecutableFile().GetPath().c_str()); 128 std::string message = stream.GetString(); 129 result.SetErrorString(message.c_str()); 130 131 LLDB_LOG(log, "error: {0}", message); 132 return result; 133 } 134 135 bool stop_at_entry = launch_info.GetFlags().Test(eLaunchFlagStopAtEntry); 136 m_session_data.reset(new ProcessWindowsData(stop_at_entry)); 137 m_session_data->m_debugger.reset(new DebuggerThread(delegate)); 138 DebuggerThreadSP debugger = m_session_data->m_debugger; 139 140 // Kick off the DebugLaunch asynchronously and wait for it to complete. 141 result = debugger->DebugLaunch(launch_info); 142 if (result.Fail()) { 143 LLDB_LOG(log, "failed launching '{0}'. {1}", 144 launch_info.GetExecutableFile().GetPath(), result); 145 return result; 146 } 147 148 HostProcess process; 149 Status error = WaitForDebuggerConnection(debugger, process); 150 if (error.Fail()) { 151 LLDB_LOG(log, "failed launching '{0}'. {1}", 152 launch_info.GetExecutableFile().GetPath(), error); 153 return error; 154 } 155 156 LLDB_LOG(log, "successfully launched '{0}'", 157 launch_info.GetExecutableFile().GetPath()); 158 159 // We've hit the initial stop. If eLaunchFlagsStopAtEntry was specified, the 160 // private state should already be set to eStateStopped as a result of 161 // hitting the initial breakpoint. If it was not set, the breakpoint should 162 // have already been resumed from and the private state should already be 163 // eStateRunning. 164 launch_info.SetProcessID(process.GetProcessId()); 165 166 return result; 167 } 168 169 Status ProcessDebugger::AttachProcess(lldb::pid_t pid, 170 const ProcessAttachInfo &attach_info, 171 DebugDelegateSP delegate) { 172 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); 173 m_session_data.reset( 174 new ProcessWindowsData(!attach_info.GetContinueOnceAttached())); 175 DebuggerThreadSP debugger(new DebuggerThread(delegate)); 176 177 m_session_data->m_debugger = debugger; 178 179 DWORD process_id = static_cast<DWORD>(pid); 180 Status error = debugger->DebugAttach(process_id, attach_info); 181 if (error.Fail()) { 182 LLDB_LOG( 183 log, 184 "encountered an error occurred initiating the asynchronous attach. {0}", 185 error); 186 return error; 187 } 188 189 HostProcess process; 190 error = WaitForDebuggerConnection(debugger, process); 191 if (error.Fail()) { 192 LLDB_LOG(log, 193 "encountered an error waiting for the debugger to connect. {0}", 194 error); 195 return error; 196 } 197 198 LLDB_LOG(log, "successfully attached to process with pid={0}", process_id); 199 200 // We've hit the initial stop. If eLaunchFlagsStopAtEntry was specified, the 201 // private state should already be set to eStateStopped as a result of 202 // hitting the initial breakpoint. If it was not set, the breakpoint should 203 // have already been resumed from and the private state should already be 204 // eStateRunning. 205 206 return error; 207 } 208 209 Status ProcessDebugger::DestroyProcess(const lldb::StateType state) { 210 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); 211 DebuggerThreadSP debugger_thread; 212 { 213 // Acquire this lock inside an inner scope, only long enough to get the 214 // DebuggerThread. StopDebugging() will trigger a call back into 215 // ProcessDebugger which will acquire the lock again, so we need to not 216 // deadlock. 217 llvm::sys::ScopedLock lock(m_mutex); 218 219 if (!m_session_data) { 220 LLDB_LOG(log, "warning: state = {0}, but there is no active session.", 221 state); 222 return Status(); 223 } 224 225 debugger_thread = m_session_data->m_debugger; 226 } 227 228 Status error; 229 if (state != eStateExited && state != eStateDetached) { 230 LLDB_LOG( 231 log, "Shutting down process {0}.", 232 debugger_thread->GetProcess().GetNativeProcess().GetSystemHandle()); 233 error = debugger_thread->StopDebugging(true); 234 235 // By the time StopDebugging returns, there is no more debugger thread, so 236 // we can be assured that no other thread will race for the session data. 237 m_session_data.reset(); 238 } else { 239 error.SetErrorStringWithFormat("cannot destroy process %" PRIx64 240 " while state = %d", 241 GetDebuggedProcessId(), state); 242 LLDB_LOG(log, "error: {0}", error); 243 } 244 return error; 245 } 246 247 Status ProcessDebugger::HaltProcess(bool &caused_stop) { 248 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); 249 Status error; 250 llvm::sys::ScopedLock lock(m_mutex); 251 caused_stop = ::DebugBreakProcess(m_session_data->m_debugger->GetProcess() 252 .GetNativeProcess() 253 .GetSystemHandle()); 254 if (!caused_stop) { 255 error.SetError(::GetLastError(), eErrorTypeWin32); 256 LLDB_LOG(log, "DebugBreakProcess failed with error {0}", error); 257 } 258 259 return error; 260 } 261 262 Status ProcessDebugger::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, 263 size_t &bytes_read) { 264 Status error; 265 bytes_read = 0; 266 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY); 267 llvm::sys::ScopedLock lock(m_mutex); 268 269 if (!m_session_data) { 270 error.SetErrorString( 271 "cannot read, there is no active debugger connection."); 272 LLDB_LOG(log, "error: {0}", error); 273 return error; 274 } 275 276 LLDB_LOG(log, "attempting to read {0} bytes from address {1:x}", size, 277 vm_addr); 278 279 HostProcess process = m_session_data->m_debugger->GetProcess(); 280 void *addr = reinterpret_cast<void *>(vm_addr); 281 SIZE_T num_of_bytes_read = 0; 282 if (!::ReadProcessMemory(process.GetNativeProcess().GetSystemHandle(), addr, 283 buf, size, &num_of_bytes_read)) { 284 // Reading from the process can fail for a number of reasons - set the 285 // error code and make sure that the number of bytes read is set back to 0 286 // because in some scenarios the value of bytes_read returned from the API 287 // is garbage. 288 error.SetError(GetLastError(), eErrorTypeWin32); 289 LLDB_LOG(log, "reading failed with error: {0}", error); 290 } else { 291 bytes_read = num_of_bytes_read; 292 } 293 return error; 294 } 295 296 Status ProcessDebugger::WriteMemory(lldb::addr_t vm_addr, const void *buf, 297 size_t size, size_t &bytes_written) { 298 Status error; 299 bytes_written = 0; 300 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY); 301 llvm::sys::ScopedLock lock(m_mutex); 302 LLDB_LOG(log, "attempting to write {0} bytes into address {1:x}", size, 303 vm_addr); 304 305 if (!m_session_data) { 306 error.SetErrorString( 307 "cannot write, there is no active debugger connection."); 308 LLDB_LOG(log, "error: {0}", error); 309 return error; 310 } 311 312 HostProcess process = m_session_data->m_debugger->GetProcess(); 313 void *addr = reinterpret_cast<void *>(vm_addr); 314 SIZE_T num_of_bytes_written = 0; 315 lldb::process_t handle = process.GetNativeProcess().GetSystemHandle(); 316 if (::WriteProcessMemory(handle, addr, buf, size, &num_of_bytes_written)) { 317 FlushInstructionCache(handle, addr, num_of_bytes_written); 318 bytes_written = num_of_bytes_written; 319 } else { 320 error.SetError(GetLastError(), eErrorTypeWin32); 321 LLDB_LOG(log, "writing failed with error: {0}", error); 322 } 323 return error; 324 } 325 326 Status ProcessDebugger::AllocateMemory(size_t size, uint32_t permissions, 327 lldb::addr_t &addr) { 328 Status error; 329 addr = LLDB_INVALID_ADDRESS; 330 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY); 331 llvm::sys::ScopedLock lock(m_mutex); 332 LLDB_LOG(log, "attempting to allocate {0} bytes with permissions {1}", size, 333 permissions); 334 335 if (!m_session_data) { 336 error.SetErrorString( 337 "cannot allocate, there is no active debugger connection"); 338 LLDB_LOG(log, "error: {0}", error); 339 return error; 340 } 341 342 HostProcess process = m_session_data->m_debugger->GetProcess(); 343 lldb::process_t handle = process.GetNativeProcess().GetSystemHandle(); 344 auto protect = ConvertLldbToWinApiProtect(permissions); 345 auto result = ::VirtualAllocEx(handle, nullptr, size, MEM_COMMIT, protect); 346 if (!result) { 347 error.SetError(GetLastError(), eErrorTypeWin32); 348 LLDB_LOG(log, "allocating failed with error: {0}", error); 349 } else { 350 addr = reinterpret_cast<addr_t>(result); 351 } 352 return error; 353 } 354 355 Status ProcessDebugger::DeallocateMemory(lldb::addr_t vm_addr) { 356 Status result; 357 358 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY); 359 llvm::sys::ScopedLock lock(m_mutex); 360 LLDB_LOG(log, "attempting to deallocate bytes at address {0}", vm_addr); 361 362 if (!m_session_data) { 363 result.SetErrorString( 364 "cannot deallocate, there is no active debugger connection"); 365 LLDB_LOG(log, "error: {0}", result); 366 return result; 367 } 368 369 HostProcess process = m_session_data->m_debugger->GetProcess(); 370 lldb::process_t handle = process.GetNativeProcess().GetSystemHandle(); 371 if (!::VirtualFreeEx(handle, reinterpret_cast<LPVOID>(vm_addr), 0, 372 MEM_RELEASE)) { 373 result.SetError(GetLastError(), eErrorTypeWin32); 374 LLDB_LOG(log, "deallocating failed with error: {0}", result); 375 } 376 377 return result; 378 } 379 380 Status ProcessDebugger::GetMemoryRegionInfo(lldb::addr_t vm_addr, 381 MemoryRegionInfo &info) { 382 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY); 383 Status error; 384 llvm::sys::ScopedLock lock(m_mutex); 385 info.Clear(); 386 387 if (!m_session_data) { 388 error.SetErrorString( 389 "GetMemoryRegionInfo called with no debugging session."); 390 LLDB_LOG(log, "error: {0}", error); 391 return error; 392 } 393 HostProcess process = m_session_data->m_debugger->GetProcess(); 394 lldb::process_t handle = process.GetNativeProcess().GetSystemHandle(); 395 if (handle == nullptr || handle == LLDB_INVALID_PROCESS) { 396 error.SetErrorString( 397 "GetMemoryRegionInfo called with an invalid target process."); 398 LLDB_LOG(log, "error: {0}", error); 399 return error; 400 } 401 402 LLDB_LOG(log, "getting info for address {0:x}", vm_addr); 403 404 void *addr = reinterpret_cast<void *>(vm_addr); 405 MEMORY_BASIC_INFORMATION mem_info = {}; 406 SIZE_T result = ::VirtualQueryEx(handle, addr, &mem_info, sizeof(mem_info)); 407 if (result == 0) { 408 if (::GetLastError() == ERROR_INVALID_PARAMETER) { 409 // ERROR_INVALID_PARAMETER is returned if VirtualQueryEx is called with 410 // an address past the highest accessible address. We should return a 411 // range from the vm_addr to LLDB_INVALID_ADDRESS 412 info.GetRange().SetRangeBase(vm_addr); 413 info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS); 414 info.SetReadable(MemoryRegionInfo::eNo); 415 info.SetExecutable(MemoryRegionInfo::eNo); 416 info.SetWritable(MemoryRegionInfo::eNo); 417 info.SetMapped(MemoryRegionInfo::eNo); 418 return error; 419 } else { 420 error.SetError(::GetLastError(), eErrorTypeWin32); 421 LLDB_LOG(log, 422 "VirtualQueryEx returned error {0} while getting memory " 423 "region info for address {1:x}", 424 error, vm_addr); 425 return error; 426 } 427 } 428 429 // Protect bits are only valid for MEM_COMMIT regions. 430 if (mem_info.State == MEM_COMMIT) { 431 const bool readable = IsPageReadable(mem_info.Protect); 432 const bool executable = IsPageExecutable(mem_info.Protect); 433 const bool writable = IsPageWritable(mem_info.Protect); 434 info.SetReadable(readable ? MemoryRegionInfo::eYes : MemoryRegionInfo::eNo); 435 info.SetExecutable(executable ? MemoryRegionInfo::eYes 436 : MemoryRegionInfo::eNo); 437 info.SetWritable(writable ? MemoryRegionInfo::eYes : MemoryRegionInfo::eNo); 438 } else { 439 info.SetReadable(MemoryRegionInfo::eNo); 440 info.SetExecutable(MemoryRegionInfo::eNo); 441 info.SetWritable(MemoryRegionInfo::eNo); 442 } 443 444 // AllocationBase is defined for MEM_COMMIT and MEM_RESERVE but not MEM_FREE. 445 if (mem_info.State != MEM_FREE) { 446 info.GetRange().SetRangeBase( 447 reinterpret_cast<addr_t>(mem_info.AllocationBase)); 448 info.GetRange().SetRangeEnd(reinterpret_cast<addr_t>(mem_info.BaseAddress) + 449 mem_info.RegionSize); 450 info.SetMapped(MemoryRegionInfo::eYes); 451 } else { 452 // In the unmapped case we need to return the distance to the next block of 453 // memory. VirtualQueryEx nearly does that except that it gives the 454 // distance from the start of the page containing vm_addr. 455 SYSTEM_INFO data; 456 ::GetSystemInfo(&data); 457 DWORD page_offset = vm_addr % data.dwPageSize; 458 info.GetRange().SetRangeBase(vm_addr); 459 info.GetRange().SetByteSize(mem_info.RegionSize - page_offset); 460 info.SetMapped(MemoryRegionInfo::eNo); 461 } 462 463 error.SetError(::GetLastError(), eErrorTypeWin32); 464 LLDB_LOGV(log, 465 "Memory region info for address {0}: readable={1}, " 466 "executable={2}, writable={3}", 467 vm_addr, info.GetReadable(), info.GetExecutable(), 468 info.GetWritable()); 469 return error; 470 } 471 472 void ProcessDebugger::OnExitProcess(uint32_t exit_code) { 473 // If the process exits before any initial stop then notify the debugger 474 // of the error otherwise WaitForDebuggerConnection() will be blocked. 475 // An example of this issue is when a process fails to load a dependent DLL. 476 if (m_session_data && !m_session_data->m_initial_stop_received) { 477 Status error(exit_code, eErrorTypeWin32); 478 OnDebuggerError(error, 0); 479 } 480 } 481 482 void ProcessDebugger::OnDebuggerConnected(lldb::addr_t image_base) {} 483 484 ExceptionResult 485 ProcessDebugger::OnDebugException(bool first_chance, 486 const ExceptionRecord &record) { 487 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EXCEPTION); 488 llvm::sys::ScopedLock lock(m_mutex); 489 // FIXME: Without this check, occasionally when running the test suite 490 // there is an issue where m_session_data can be null. It's not clear how 491 // this could happen but it only surfaces while running the test suite. In 492 // order to properly diagnose this, we probably need to first figure allow the 493 // test suite to print out full lldb logs, and then add logging to the process 494 // plugin. 495 if (!m_session_data) { 496 LLDB_LOG(log, 497 "Debugger thread reported exception {0:x} at address {1:x}, but " 498 "there is no session.", 499 record.GetExceptionCode(), record.GetExceptionAddress()); 500 return ExceptionResult::SendToApplication; 501 } 502 503 ExceptionResult result = ExceptionResult::SendToApplication; 504 if ((record.GetExceptionCode() == EXCEPTION_BREAKPOINT || 505 record.GetExceptionCode() == 506 0x4000001FL /*WOW64 STATUS_WX86_BREAKPOINT*/) && 507 !m_session_data->m_initial_stop_received) { 508 // Handle breakpoints at the first chance. 509 result = ExceptionResult::BreakInDebugger; 510 LLDB_LOG( 511 log, 512 "Hit loader breakpoint at address {0:x}, setting initial stop event.", 513 record.GetExceptionAddress()); 514 m_session_data->m_initial_stop_received = true; 515 ::SetEvent(m_session_data->m_initial_stop_event); 516 } 517 return result; 518 } 519 520 void ProcessDebugger::OnCreateThread(const HostThread &thread) { 521 // Do nothing by default 522 } 523 524 void ProcessDebugger::OnExitThread(lldb::tid_t thread_id, uint32_t exit_code) { 525 // Do nothing by default 526 } 527 528 void ProcessDebugger::OnLoadDll(const ModuleSpec &module_spec, 529 lldb::addr_t module_addr) { 530 // Do nothing by default 531 } 532 533 void ProcessDebugger::OnUnloadDll(lldb::addr_t module_addr) { 534 // Do nothing by default 535 } 536 537 void ProcessDebugger::OnDebugString(const std::string &string) {} 538 539 void ProcessDebugger::OnDebuggerError(const Status &error, uint32_t type) { 540 llvm::sys::ScopedLock lock(m_mutex); 541 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); 542 543 if (m_session_data->m_initial_stop_received) { 544 // This happened while debugging. Do we shutdown the debugging session, 545 // try to continue, or do something else? 546 LLDB_LOG(log, 547 "Error {0} occurred during debugging. Unexpected behavior " 548 "may result. {1}", 549 error.GetError(), error); 550 } else { 551 // If we haven't actually launched the process yet, this was an error 552 // launching the process. Set the internal error and signal the initial 553 // stop event so that the DoLaunch method wakes up and returns a failure. 554 m_session_data->m_launch_error = error; 555 ::SetEvent(m_session_data->m_initial_stop_event); 556 LLDB_LOG(log, 557 "Error {0} occurred launching the process before the initial " 558 "stop. {1}", 559 error.GetError(), error); 560 return; 561 } 562 } 563 564 Status ProcessDebugger::WaitForDebuggerConnection(DebuggerThreadSP debugger, 565 HostProcess &process) { 566 Status result; 567 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS | 568 WINDOWS_LOG_BREAKPOINTS); 569 LLDB_LOG(log, "Waiting for loader breakpoint."); 570 571 // Block this function until we receive the initial stop from the process. 572 if (::WaitForSingleObject(m_session_data->m_initial_stop_event, INFINITE) == 573 WAIT_OBJECT_0) { 574 LLDB_LOG(log, "hit loader breakpoint, returning."); 575 576 process = debugger->GetProcess(); 577 return m_session_data->m_launch_error; 578 } else 579 return Status(::GetLastError(), eErrorTypeWin32); 580 } 581 582 } // namespace lldb_private 583