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