1 //===-- DebuggerThread.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 "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 = GetLog(WindowsLog::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> secondary_thread = 74 ThreadLauncher::LaunchThread("lldb.plugin.process-windows.secondary[?]", 75 DebuggerThreadLaunchRoutine, context); 76 if (!secondary_thread) { 77 result = Status(secondary_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 = GetLog(WindowsLog::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> secondary_thread = 93 ThreadLauncher::LaunchThread("lldb.plugin.process-windows.secondary[?]", 94 DebuggerThreadAttachRoutine, context); 95 if (!secondary_thread) { 96 result = Status(secondary_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 = GetLog(WindowsLog::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 = GetLog(WindowsLog::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 = GetLog(WindowsLog::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 = GetLog(WindowsLog::Process | WindowsLog::Exception); 250 LLDB_LOG(log, "broadcasting for inferior process {0}.", 251 m_process.GetProcessId()); 252 253 m_active_exception.reset(); 254 m_exception_pred.SetValue(result, eBroadcastAlways); 255 } 256 257 void DebuggerThread::FreeProcessHandles() { 258 m_process = HostProcess(); 259 m_main_thread = HostThread(); 260 if (m_image_file) { 261 ::CloseHandle(m_image_file); 262 m_image_file = nullptr; 263 } 264 } 265 266 void DebuggerThread::DebugLoop() { 267 Log *log = GetLog(WindowsLog::Event); 268 DEBUG_EVENT dbe = {}; 269 bool should_debug = true; 270 LLDB_LOGV(log, "Entering WaitForDebugEvent loop"); 271 while (should_debug) { 272 LLDB_LOGV(log, "Calling WaitForDebugEvent"); 273 BOOL wait_result = WaitForDebugEvent(&dbe, INFINITE); 274 if (wait_result) { 275 DWORD continue_status = DBG_CONTINUE; 276 switch (dbe.dwDebugEventCode) { 277 default: 278 llvm_unreachable("Unhandle debug event code!"); 279 case EXCEPTION_DEBUG_EVENT: { 280 ExceptionResult status = 281 HandleExceptionEvent(dbe.u.Exception, dbe.dwThreadId); 282 283 if (status == ExceptionResult::MaskException) 284 continue_status = DBG_CONTINUE; 285 else if (status == ExceptionResult::SendToApplication) 286 continue_status = DBG_EXCEPTION_NOT_HANDLED; 287 288 break; 289 } 290 case CREATE_THREAD_DEBUG_EVENT: 291 continue_status = 292 HandleCreateThreadEvent(dbe.u.CreateThread, dbe.dwThreadId); 293 break; 294 case CREATE_PROCESS_DEBUG_EVENT: 295 continue_status = 296 HandleCreateProcessEvent(dbe.u.CreateProcessInfo, dbe.dwThreadId); 297 break; 298 case EXIT_THREAD_DEBUG_EVENT: 299 continue_status = 300 HandleExitThreadEvent(dbe.u.ExitThread, dbe.dwThreadId); 301 break; 302 case EXIT_PROCESS_DEBUG_EVENT: 303 continue_status = 304 HandleExitProcessEvent(dbe.u.ExitProcess, dbe.dwThreadId); 305 should_debug = false; 306 break; 307 case LOAD_DLL_DEBUG_EVENT: 308 continue_status = HandleLoadDllEvent(dbe.u.LoadDll, dbe.dwThreadId); 309 break; 310 case UNLOAD_DLL_DEBUG_EVENT: 311 continue_status = HandleUnloadDllEvent(dbe.u.UnloadDll, dbe.dwThreadId); 312 break; 313 case OUTPUT_DEBUG_STRING_EVENT: 314 continue_status = HandleODSEvent(dbe.u.DebugString, dbe.dwThreadId); 315 break; 316 case RIP_EVENT: 317 continue_status = HandleRipEvent(dbe.u.RipInfo, dbe.dwThreadId); 318 if (dbe.u.RipInfo.dwType == SLE_ERROR) 319 should_debug = false; 320 break; 321 } 322 323 LLDB_LOGV(log, "calling ContinueDebugEvent({0}, {1}, {2}) on thread {3}.", 324 dbe.dwProcessId, dbe.dwThreadId, continue_status, 325 ::GetCurrentThreadId()); 326 327 ::ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, continue_status); 328 329 if (m_detached) { 330 should_debug = false; 331 } 332 } else { 333 LLDB_LOG(log, "returned FALSE from WaitForDebugEvent. Error = {0}", 334 ::GetLastError()); 335 336 should_debug = false; 337 } 338 } 339 FreeProcessHandles(); 340 341 LLDB_LOG(log, "WaitForDebugEvent loop completed, exiting."); 342 ::SetEvent(m_debugging_ended_event); 343 } 344 345 ExceptionResult 346 DebuggerThread::HandleExceptionEvent(const EXCEPTION_DEBUG_INFO &info, 347 DWORD thread_id) { 348 Log *log = GetLog(WindowsLog::Event | WindowsLog::Exception); 349 if (m_is_shutting_down) { 350 // A breakpoint that occurs while `m_pid_to_detach` is non-zero is a magic 351 // exception that 352 // we use simply to wake up the DebuggerThread so that we can close out the 353 // debug loop. 354 if (m_pid_to_detach != 0 && 355 (info.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT || 356 info.ExceptionRecord.ExceptionCode == STATUS_WX86_BREAKPOINT)) { 357 LLDB_LOG(log, "Breakpoint exception is cue to detach from process {0:x}", 358 m_pid_to_detach.load()); 359 ::DebugActiveProcessStop(m_pid_to_detach); 360 m_detached = true; 361 } 362 363 // Don't perform any blocking operations while we're shutting down. That 364 // will cause TerminateProcess -> WaitForSingleObject to time out. 365 return ExceptionResult::SendToApplication; 366 } 367 368 bool first_chance = (info.dwFirstChance != 0); 369 370 m_active_exception.reset( 371 new ExceptionRecord(info.ExceptionRecord, thread_id)); 372 LLDB_LOG(log, "encountered {0} chance exception {1:x} on thread {2:x}", 373 first_chance ? "first" : "second", 374 info.ExceptionRecord.ExceptionCode, thread_id); 375 376 ExceptionResult result = 377 m_debug_delegate->OnDebugException(first_chance, *m_active_exception); 378 m_exception_pred.SetValue(result, eBroadcastNever); 379 380 LLDB_LOG(log, "waiting for ExceptionPred != BreakInDebugger"); 381 result = *m_exception_pred.WaitForValueNotEqualTo( 382 ExceptionResult::BreakInDebugger); 383 384 LLDB_LOG(log, "got ExceptionPred = {0}", (int)m_exception_pred.GetValue()); 385 return result; 386 } 387 388 DWORD 389 DebuggerThread::HandleCreateThreadEvent(const CREATE_THREAD_DEBUG_INFO &info, 390 DWORD thread_id) { 391 Log *log = GetLog(WindowsLog::Event | WindowsLog::Thread); 392 LLDB_LOG(log, "Thread {0} spawned in process {1}", thread_id, 393 m_process.GetProcessId()); 394 HostThread thread(info.hThread); 395 thread.GetNativeThread().SetOwnsHandle(false); 396 m_debug_delegate->OnCreateThread(thread); 397 return DBG_CONTINUE; 398 } 399 400 DWORD 401 DebuggerThread::HandleCreateProcessEvent(const CREATE_PROCESS_DEBUG_INFO &info, 402 DWORD thread_id) { 403 Log *log = GetLog(WindowsLog::Event | WindowsLog::Process); 404 uint32_t process_id = ::GetProcessId(info.hProcess); 405 406 LLDB_LOG(log, "process {0} spawned", process_id); 407 408 std::string thread_name; 409 llvm::raw_string_ostream name_stream(thread_name); 410 name_stream << "lldb.plugin.process-windows.secondary[" << process_id << "]"; 411 name_stream.flush(); 412 llvm::set_thread_name(thread_name); 413 414 // info.hProcess and info.hThread are closed automatically by Windows when 415 // EXIT_PROCESS_DEBUG_EVENT is received. 416 m_process = HostProcess(info.hProcess); 417 ((HostProcessWindows &)m_process.GetNativeProcess()).SetOwnsHandle(false); 418 m_main_thread = HostThread(info.hThread); 419 m_main_thread.GetNativeThread().SetOwnsHandle(false); 420 m_image_file = info.hFile; 421 422 lldb::addr_t load_addr = reinterpret_cast<lldb::addr_t>(info.lpBaseOfImage); 423 m_debug_delegate->OnDebuggerConnected(load_addr); 424 425 return DBG_CONTINUE; 426 } 427 428 DWORD 429 DebuggerThread::HandleExitThreadEvent(const EXIT_THREAD_DEBUG_INFO &info, 430 DWORD thread_id) { 431 Log *log = GetLog(WindowsLog::Event | WindowsLog::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 = GetLog(WindowsLog::Event | WindowsLog::Thread); 442 LLDB_LOG(log, "process {0} exited with code {1}", m_process.GetProcessId(), 443 info.dwExitCode); 444 445 m_debug_delegate->OnExitProcess(info.dwExitCode); 446 447 return DBG_CONTINUE; 448 } 449 450 DWORD 451 DebuggerThread::HandleLoadDllEvent(const LOAD_DLL_DEBUG_INFO &info, 452 DWORD thread_id) { 453 Log *log = GetLog(WindowsLog::Event); 454 if (info.hFile == nullptr) { 455 // Not sure what this is, so just ignore it. 456 LLDB_LOG(log, "Warning: Inferior {0} has a NULL file handle, returning...", 457 m_process.GetProcessId()); 458 return DBG_CONTINUE; 459 } 460 461 std::vector<wchar_t> buffer(1); 462 DWORD required_size = 463 GetFinalPathNameByHandleW(info.hFile, &buffer[0], 0, VOLUME_NAME_DOS); 464 if (required_size > 0) { 465 buffer.resize(required_size + 1); 466 required_size = GetFinalPathNameByHandleW(info.hFile, &buffer[0], 467 required_size, VOLUME_NAME_DOS); 468 std::string path_str_utf8; 469 llvm::convertWideToUTF8(buffer.data(), path_str_utf8); 470 llvm::StringRef path_str = path_str_utf8; 471 const char *path = path_str.data(); 472 if (path_str.startswith("\\\\?\\")) 473 path += 4; 474 475 FileSpec file_spec(path); 476 ModuleSpec module_spec(file_spec); 477 lldb::addr_t load_addr = reinterpret_cast<lldb::addr_t>(info.lpBaseOfDll); 478 479 LLDB_LOG(log, "Inferior {0} - DLL '{1}' loaded at address {2:x}...", 480 m_process.GetProcessId(), path, info.lpBaseOfDll); 481 482 m_debug_delegate->OnLoadDll(module_spec, load_addr); 483 } else { 484 LLDB_LOG( 485 log, 486 "Inferior {0} - Error {1} occurred calling GetFinalPathNameByHandle", 487 m_process.GetProcessId(), ::GetLastError()); 488 } 489 // Windows does not automatically close info.hFile, so we need to do it. 490 ::CloseHandle(info.hFile); 491 return DBG_CONTINUE; 492 } 493 494 DWORD 495 DebuggerThread::HandleUnloadDllEvent(const UNLOAD_DLL_DEBUG_INFO &info, 496 DWORD thread_id) { 497 Log *log = GetLog(WindowsLog::Event); 498 LLDB_LOG(log, "process {0} unloading DLL at addr {1:x}.", 499 m_process.GetProcessId(), info.lpBaseOfDll); 500 501 m_debug_delegate->OnUnloadDll( 502 reinterpret_cast<lldb::addr_t>(info.lpBaseOfDll)); 503 return DBG_CONTINUE; 504 } 505 506 DWORD 507 DebuggerThread::HandleODSEvent(const OUTPUT_DEBUG_STRING_INFO &info, 508 DWORD thread_id) { 509 return DBG_CONTINUE; 510 } 511 512 DWORD 513 DebuggerThread::HandleRipEvent(const RIP_INFO &info, DWORD thread_id) { 514 Log *log = GetLog(WindowsLog::Event); 515 LLDB_LOG(log, "encountered error {0} (type={1}) in process {2} thread {3}", 516 info.dwError, info.dwType, m_process.GetProcessId(), thread_id); 517 518 Status error(info.dwError, eErrorTypeWin32); 519 m_debug_delegate->OnDebuggerError(error, info.dwType); 520 521 return DBG_CONTINUE; 522 } 523