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