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