1 //===-- DebuggerThread.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 "DebuggerThread.h" 10 #include "ExceptionRecord.h" 11 #include "IDebugDelegate.h" 12 13 #include "lldb/Core/ModuleSpec.h" 14 #include "lldb/Host/ProcessLaunchInfo.h" 15 #include "lldb/Host/ThreadLauncher.h" 16 #include "lldb/Host/windows/HostProcessWindows.h" 17 #include "lldb/Host/windows/HostThreadWindows.h" 18 #include "lldb/Host/windows/ProcessLauncherWindows.h" 19 #include "lldb/Target/Process.h" 20 #include "lldb/Utility/FileSpec.h" 21 #include "lldb/Utility/Log.h" 22 #include "lldb/Utility/Predicate.h" 23 #include "lldb/Utility/Status.h" 24 25 #include "Plugins/Process/Windows/Common/ProcessWindowsLog.h" 26 27 #include "llvm/ADT/STLExtras.h" 28 #include "llvm/Support/ConvertUTF.h" 29 #include "llvm/Support/Threading.h" 30 #include "llvm/Support/raw_ostream.h" 31 32 #ifndef STATUS_WX86_BREAKPOINT 33 #define STATUS_WX86_BREAKPOINT 0x4000001FL // For WOW64 34 #endif 35 36 using namespace lldb; 37 using namespace lldb_private; 38 39 namespace { 40 struct DebugLaunchContext { 41 DebugLaunchContext(DebuggerThread *thread, 42 const ProcessLaunchInfo &launch_info) 43 : m_thread(thread), m_launch_info(launch_info) {} 44 DebuggerThread *m_thread; 45 ProcessLaunchInfo m_launch_info; 46 }; 47 48 struct DebugAttachContext { 49 DebugAttachContext(DebuggerThread *thread, lldb::pid_t pid, 50 const ProcessAttachInfo &attach_info) 51 : m_thread(thread), m_pid(pid), m_attach_info(attach_info) {} 52 DebuggerThread *m_thread; 53 lldb::pid_t m_pid; 54 ProcessAttachInfo m_attach_info; 55 }; 56 } // namespace 57 58 DebuggerThread::DebuggerThread(DebugDelegateSP debug_delegate) 59 : m_debug_delegate(debug_delegate), m_pid_to_detach(0), 60 m_is_shutting_down(false) { 61 m_debugging_ended_event = ::CreateEvent(nullptr, TRUE, FALSE, nullptr); 62 } 63 64 DebuggerThread::~DebuggerThread() { ::CloseHandle(m_debugging_ended_event); } 65 66 Status DebuggerThread::DebugLaunch(const ProcessLaunchInfo &launch_info) { 67 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); 68 LLDB_LOG(log, "launching '{0}'", launch_info.GetExecutableFile().GetPath()); 69 70 Status result; 71 DebugLaunchContext *context = new DebugLaunchContext(this, launch_info); 72 73 llvm::Expected<HostThread> slave_thread = ThreadLauncher::LaunchThread( 74 "lldb.plugin.process-windows.slave[?]", DebuggerThreadLaunchRoutine, 75 context); 76 if (!slave_thread) { 77 result = Status(slave_thread.takeError()); 78 LLDB_LOG(log, "couldn't launch debugger thread. {0}", result); 79 } 80 81 return result; 82 } 83 84 Status DebuggerThread::DebugAttach(lldb::pid_t pid, 85 const ProcessAttachInfo &attach_info) { 86 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); 87 LLDB_LOG(log, "attaching to '{0}'", pid); 88 89 Status result; 90 DebugAttachContext *context = new DebugAttachContext(this, pid, attach_info); 91 92 llvm::Expected<HostThread> slave_thread = ThreadLauncher::LaunchThread( 93 "lldb.plugin.process-windows.slave[?]", DebuggerThreadAttachRoutine, 94 context); 95 if (!slave_thread) { 96 result = Status(slave_thread.takeError()); 97 LLDB_LOG(log, "couldn't attach to process '{0}'. {1}", pid, result); 98 } 99 100 return result; 101 } 102 103 lldb::thread_result_t DebuggerThread::DebuggerThreadLaunchRoutine(void *data) { 104 DebugLaunchContext *context = static_cast<DebugLaunchContext *>(data); 105 lldb::thread_result_t result = 106 context->m_thread->DebuggerThreadLaunchRoutine(context->m_launch_info); 107 delete context; 108 return result; 109 } 110 111 lldb::thread_result_t DebuggerThread::DebuggerThreadAttachRoutine(void *data) { 112 DebugAttachContext *context = static_cast<DebugAttachContext *>(data); 113 lldb::thread_result_t result = context->m_thread->DebuggerThreadAttachRoutine( 114 context->m_pid, context->m_attach_info); 115 delete context; 116 return result; 117 } 118 119 lldb::thread_result_t DebuggerThread::DebuggerThreadLaunchRoutine( 120 const ProcessLaunchInfo &launch_info) { 121 // Grab a shared_ptr reference to this so that we know it won't get deleted 122 // until after the thread routine has exited. 123 std::shared_ptr<DebuggerThread> this_ref(shared_from_this()); 124 125 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); 126 LLDB_LOG(log, "preparing to launch '{0}' on background thread.", 127 launch_info.GetExecutableFile().GetPath()); 128 129 Status error; 130 ProcessLauncherWindows launcher; 131 HostProcess process(launcher.LaunchProcess(launch_info, error)); 132 // If we couldn't create the process, notify waiters immediately. Otherwise 133 // enter the debug loop and wait until we get the create process debug 134 // notification. Note that if the process was created successfully, we can 135 // throw away the process handle we got from CreateProcess because Windows 136 // will give us another (potentially more useful?) handle when it sends us 137 // the CREATE_PROCESS_DEBUG_EVENT. 138 if (error.Success()) 139 DebugLoop(); 140 else 141 m_debug_delegate->OnDebuggerError(error, 0); 142 143 return {}; 144 } 145 146 lldb::thread_result_t DebuggerThread::DebuggerThreadAttachRoutine( 147 lldb::pid_t pid, const ProcessAttachInfo &attach_info) { 148 // Grab a shared_ptr reference to this so that we know it won't get deleted 149 // until after the thread routine has exited. 150 std::shared_ptr<DebuggerThread> this_ref(shared_from_this()); 151 152 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); 153 LLDB_LOG(log, "preparing to attach to process '{0}' on background thread.", 154 pid); 155 156 if (!DebugActiveProcess((DWORD)pid)) { 157 Status error(::GetLastError(), eErrorTypeWin32); 158 m_debug_delegate->OnDebuggerError(error, 0); 159 return {}; 160 } 161 162 // The attach was successful, enter the debug loop. From here on out, this 163 // is no different than a create process operation, so all the same comments 164 // in DebugLaunch should apply from this point out. 165 DebugLoop(); 166 167 return {}; 168 } 169 170 Status DebuggerThread::StopDebugging(bool terminate) { 171 Status error; 172 173 lldb::pid_t pid = m_process.GetProcessId(); 174 175 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS); 176 LLDB_LOG(log, "terminate = {0}, inferior={1}.", terminate, pid); 177 178 // Set m_is_shutting_down to true if it was false. Return if it was already 179 // true. 180 bool expected = false; 181 if (!m_is_shutting_down.compare_exchange_strong(expected, true)) 182 return error; 183 184 // Make a copy of the process, since the termination sequence will reset 185 // DebuggerThread's internal copy and it needs to remain open for the Wait 186 // operation. 187 HostProcess process_copy = m_process; 188 lldb::process_t handle = m_process.GetNativeProcess().GetSystemHandle(); 189 190 if (terminate) { 191 if (handle != nullptr && handle != LLDB_INVALID_PROCESS) { 192 // Initiate the termination before continuing the exception, so that the 193 // next debug event we get is the exit process event, and not some other 194 // event. 195 BOOL terminate_suceeded = TerminateProcess(handle, 0); 196 LLDB_LOG(log, 197 "calling TerminateProcess({0}, 0) (inferior={1}), success={2}", 198 handle, pid, terminate_suceeded); 199 } else { 200 LLDB_LOG(log, 201 "NOT calling TerminateProcess because the inferior is not valid " 202 "({0}, 0) (inferior={1})", 203 handle, pid); 204 } 205 } 206 207 // If we're stuck waiting for an exception to continue (e.g. the user is at a 208 // breakpoint messing around in the debugger), continue it now. But only 209 // AFTER calling TerminateProcess to make sure that the very next call to 210 // WaitForDebugEvent is an exit process event. 211 if (m_active_exception.get()) { 212 LLDB_LOG(log, "masking active exception"); 213 ContinueAsyncException(ExceptionResult::MaskException); 214 } 215 216 if (!terminate) { 217 // Indicate that we want to detach. 218 m_pid_to_detach = GetProcess().GetProcessId(); 219 220 // Force a fresh break so that the detach can happen from the debugger 221 // thread. 222 if (!::DebugBreakProcess( 223 GetProcess().GetNativeProcess().GetSystemHandle())) { 224 error.SetError(::GetLastError(), eErrorTypeWin32); 225 } 226 } 227 228 LLDB_LOG(log, "waiting for detach from process {0} to complete.", pid); 229 230 DWORD wait_result = WaitForSingleObject(m_debugging_ended_event, 5000); 231 if (wait_result != WAIT_OBJECT_0) { 232 error.SetError(GetLastError(), eErrorTypeWin32); 233 LLDB_LOG(log, "error: WaitForSingleObject({0}, 5000) returned {1}", 234 m_debugging_ended_event, wait_result); 235 } else 236 LLDB_LOG(log, "detach from process {0} completed successfully.", pid); 237 238 if (!error.Success()) { 239 LLDB_LOG(log, "encountered an error while trying to stop process {0}. {1}", 240 pid, error); 241 } 242 return error; 243 } 244 245 void DebuggerThread::ContinueAsyncException(ExceptionResult result) { 246 if (!m_active_exception.get()) 247 return; 248 249 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS | 250 WINDOWS_LOG_EXCEPTION); 251 LLDB_LOG(log, "broadcasting for inferior process {0}.", 252 m_process.GetProcessId()); 253 254 m_active_exception.reset(); 255 m_exception_pred.SetValue(result, eBroadcastAlways); 256 } 257 258 void DebuggerThread::FreeProcessHandles() { 259 m_process = HostProcess(); 260 m_main_thread = HostThread(); 261 if (m_image_file) { 262 ::CloseHandle(m_image_file); 263 m_image_file = nullptr; 264 } 265 } 266 267 void DebuggerThread::DebugLoop() { 268 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT); 269 DEBUG_EVENT dbe = {}; 270 bool should_debug = true; 271 LLDB_LOGV(log, "Entering WaitForDebugEvent loop"); 272 while (should_debug) { 273 LLDB_LOGV(log, "Calling WaitForDebugEvent"); 274 BOOL wait_result = WaitForDebugEvent(&dbe, INFINITE); 275 if (wait_result) { 276 DWORD continue_status = DBG_CONTINUE; 277 switch (dbe.dwDebugEventCode) { 278 default: 279 llvm_unreachable("Unhandle debug event code!"); 280 case EXCEPTION_DEBUG_EVENT: { 281 ExceptionResult status = 282 HandleExceptionEvent(dbe.u.Exception, dbe.dwThreadId); 283 284 if (status == ExceptionResult::MaskException) 285 continue_status = DBG_CONTINUE; 286 else if (status == ExceptionResult::SendToApplication) 287 continue_status = DBG_EXCEPTION_NOT_HANDLED; 288 289 break; 290 } 291 case CREATE_THREAD_DEBUG_EVENT: 292 continue_status = 293 HandleCreateThreadEvent(dbe.u.CreateThread, dbe.dwThreadId); 294 break; 295 case CREATE_PROCESS_DEBUG_EVENT: 296 continue_status = 297 HandleCreateProcessEvent(dbe.u.CreateProcessInfo, dbe.dwThreadId); 298 break; 299 case EXIT_THREAD_DEBUG_EVENT: 300 continue_status = 301 HandleExitThreadEvent(dbe.u.ExitThread, dbe.dwThreadId); 302 break; 303 case EXIT_PROCESS_DEBUG_EVENT: 304 continue_status = 305 HandleExitProcessEvent(dbe.u.ExitProcess, dbe.dwThreadId); 306 should_debug = false; 307 break; 308 case LOAD_DLL_DEBUG_EVENT: 309 continue_status = HandleLoadDllEvent(dbe.u.LoadDll, dbe.dwThreadId); 310 break; 311 case UNLOAD_DLL_DEBUG_EVENT: 312 continue_status = HandleUnloadDllEvent(dbe.u.UnloadDll, dbe.dwThreadId); 313 break; 314 case OUTPUT_DEBUG_STRING_EVENT: 315 continue_status = HandleODSEvent(dbe.u.DebugString, dbe.dwThreadId); 316 break; 317 case RIP_EVENT: 318 continue_status = HandleRipEvent(dbe.u.RipInfo, dbe.dwThreadId); 319 if (dbe.u.RipInfo.dwType == SLE_ERROR) 320 should_debug = false; 321 break; 322 } 323 324 LLDB_LOGV(log, "calling ContinueDebugEvent({0}, {1}, {2}) on thread {3}.", 325 dbe.dwProcessId, dbe.dwThreadId, continue_status, 326 ::GetCurrentThreadId()); 327 328 ::ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, continue_status); 329 330 if (m_detached) { 331 should_debug = false; 332 } 333 } else { 334 LLDB_LOG(log, "returned FALSE from WaitForDebugEvent. Error = {0}", 335 ::GetLastError()); 336 337 should_debug = false; 338 } 339 } 340 FreeProcessHandles(); 341 342 LLDB_LOG(log, "WaitForDebugEvent loop completed, exiting."); 343 ::SetEvent(m_debugging_ended_event); 344 } 345 346 ExceptionResult 347 DebuggerThread::HandleExceptionEvent(const EXCEPTION_DEBUG_INFO &info, 348 DWORD thread_id) { 349 Log *log = 350 ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT | WINDOWS_LOG_EXCEPTION); 351 if (m_is_shutting_down) { 352 // A breakpoint that occurs while `m_pid_to_detach` is non-zero is a magic 353 // exception that 354 // we use simply to wake up the DebuggerThread so that we can close out the 355 // debug loop. 356 if (m_pid_to_detach != 0 && 357 (info.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT || 358 info.ExceptionRecord.ExceptionCode == STATUS_WX86_BREAKPOINT)) { 359 LLDB_LOG(log, "Breakpoint exception is cue to detach from process {0:x}", 360 m_pid_to_detach.load()); 361 ::DebugActiveProcessStop(m_pid_to_detach); 362 m_detached = true; 363 } 364 365 // Don't perform any blocking operations while we're shutting down. That 366 // will cause TerminateProcess -> WaitForSingleObject to time out. 367 return ExceptionResult::SendToApplication; 368 } 369 370 bool first_chance = (info.dwFirstChance != 0); 371 372 m_active_exception.reset( 373 new ExceptionRecord(info.ExceptionRecord, thread_id)); 374 LLDB_LOG(log, "encountered {0} chance exception {1:x} on thread {2:x}", 375 first_chance ? "first" : "second", 376 info.ExceptionRecord.ExceptionCode, thread_id); 377 378 ExceptionResult result = 379 m_debug_delegate->OnDebugException(first_chance, *m_active_exception); 380 m_exception_pred.SetValue(result, eBroadcastNever); 381 382 LLDB_LOG(log, "waiting for ExceptionPred != BreakInDebugger"); 383 result = *m_exception_pred.WaitForValueNotEqualTo( 384 ExceptionResult::BreakInDebugger); 385 386 LLDB_LOG(log, "got ExceptionPred = {0}", (int)m_exception_pred.GetValue()); 387 return result; 388 } 389 390 DWORD 391 DebuggerThread::HandleCreateThreadEvent(const CREATE_THREAD_DEBUG_INFO &info, 392 DWORD thread_id) { 393 Log *log = 394 ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT | WINDOWS_LOG_THREAD); 395 LLDB_LOG(log, "Thread {0} spawned in process {1}", thread_id, 396 m_process.GetProcessId()); 397 HostThread thread(info.hThread); 398 thread.GetNativeThread().SetOwnsHandle(false); 399 m_debug_delegate->OnCreateThread(thread); 400 return DBG_CONTINUE; 401 } 402 403 DWORD 404 DebuggerThread::HandleCreateProcessEvent(const CREATE_PROCESS_DEBUG_INFO &info, 405 DWORD thread_id) { 406 Log *log = 407 ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT | WINDOWS_LOG_PROCESS); 408 uint32_t process_id = ::GetProcessId(info.hProcess); 409 410 LLDB_LOG(log, "process {0} spawned", process_id); 411 412 std::string thread_name; 413 llvm::raw_string_ostream name_stream(thread_name); 414 name_stream << "lldb.plugin.process-windows.slave[" << process_id << "]"; 415 name_stream.flush(); 416 llvm::set_thread_name(thread_name); 417 418 // info.hProcess and info.hThread are closed automatically by Windows when 419 // EXIT_PROCESS_DEBUG_EVENT is received. 420 m_process = HostProcess(info.hProcess); 421 ((HostProcessWindows &)m_process.GetNativeProcess()).SetOwnsHandle(false); 422 m_main_thread = HostThread(info.hThread); 423 m_main_thread.GetNativeThread().SetOwnsHandle(false); 424 m_image_file = info.hFile; 425 426 lldb::addr_t load_addr = reinterpret_cast<lldb::addr_t>(info.lpBaseOfImage); 427 m_debug_delegate->OnDebuggerConnected(load_addr); 428 429 return DBG_CONTINUE; 430 } 431 432 DWORD 433 DebuggerThread::HandleExitThreadEvent(const EXIT_THREAD_DEBUG_INFO &info, 434 DWORD thread_id) { 435 Log *log = 436 ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT | WINDOWS_LOG_THREAD); 437 LLDB_LOG(log, "Thread {0} exited with code {1} in process {2}", thread_id, 438 info.dwExitCode, m_process.GetProcessId()); 439 m_debug_delegate->OnExitThread(thread_id, info.dwExitCode); 440 return DBG_CONTINUE; 441 } 442 443 DWORD 444 DebuggerThread::HandleExitProcessEvent(const EXIT_PROCESS_DEBUG_INFO &info, 445 DWORD thread_id) { 446 Log *log = 447 ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT | WINDOWS_LOG_THREAD); 448 LLDB_LOG(log, "process {0} exited with code {1}", m_process.GetProcessId(), 449 info.dwExitCode); 450 451 m_debug_delegate->OnExitProcess(info.dwExitCode); 452 453 return DBG_CONTINUE; 454 } 455 456 DWORD 457 DebuggerThread::HandleLoadDllEvent(const LOAD_DLL_DEBUG_INFO &info, 458 DWORD thread_id) { 459 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT); 460 if (info.hFile == nullptr) { 461 // Not sure what this is, so just ignore it. 462 LLDB_LOG(log, "Warning: Inferior {0} has a NULL file handle, returning...", 463 m_process.GetProcessId()); 464 return DBG_CONTINUE; 465 } 466 467 std::vector<wchar_t> buffer(1); 468 DWORD required_size = 469 GetFinalPathNameByHandleW(info.hFile, &buffer[0], 0, VOLUME_NAME_DOS); 470 if (required_size > 0) { 471 buffer.resize(required_size + 1); 472 required_size = GetFinalPathNameByHandleW(info.hFile, &buffer[0], 473 required_size, VOLUME_NAME_DOS); 474 std::string path_str_utf8; 475 llvm::convertWideToUTF8(buffer.data(), path_str_utf8); 476 llvm::StringRef path_str = path_str_utf8; 477 const char *path = path_str.data(); 478 if (path_str.startswith("\\\\?\\")) 479 path += 4; 480 481 FileSpec file_spec(path); 482 ModuleSpec module_spec(file_spec); 483 lldb::addr_t load_addr = reinterpret_cast<lldb::addr_t>(info.lpBaseOfDll); 484 485 LLDB_LOG(log, "Inferior {0} - DLL '{1}' loaded at address {2:x}...", 486 m_process.GetProcessId(), path, info.lpBaseOfDll); 487 488 m_debug_delegate->OnLoadDll(module_spec, load_addr); 489 } else { 490 LLDB_LOG( 491 log, 492 "Inferior {0} - Error {1} occurred calling GetFinalPathNameByHandle", 493 m_process.GetProcessId(), ::GetLastError()); 494 } 495 // Windows does not automatically close info.hFile, so we need to do it. 496 ::CloseHandle(info.hFile); 497 return DBG_CONTINUE; 498 } 499 500 DWORD 501 DebuggerThread::HandleUnloadDllEvent(const UNLOAD_DLL_DEBUG_INFO &info, 502 DWORD thread_id) { 503 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT); 504 LLDB_LOG(log, "process {0} unloading DLL at addr {1:x}.", 505 m_process.GetProcessId(), info.lpBaseOfDll); 506 507 m_debug_delegate->OnUnloadDll( 508 reinterpret_cast<lldb::addr_t>(info.lpBaseOfDll)); 509 return DBG_CONTINUE; 510 } 511 512 DWORD 513 DebuggerThread::HandleODSEvent(const OUTPUT_DEBUG_STRING_INFO &info, 514 DWORD thread_id) { 515 return DBG_CONTINUE; 516 } 517 518 DWORD 519 DebuggerThread::HandleRipEvent(const RIP_INFO &info, DWORD thread_id) { 520 Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EVENT); 521 LLDB_LOG(log, "encountered error {0} (type={1}) in process {2} thread {3}", 522 info.dwError, info.dwType, m_process.GetProcessId(), thread_id); 523 524 Status error(info.dwError, eErrorTypeWin32); 525 m_debug_delegate->OnDebuggerError(error, info.dwType); 526 527 return DBG_CONTINUE; 528 } 529