1 //===-- ProcessWindows.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 "ProcessWindows.h"
10 
11 // Windows includes
12 #include "lldb/Host/windows/windows.h"
13 #include <psapi.h>
14 
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/ModuleSpec.h"
17 #include "lldb/Core/PluginManager.h"
18 #include "lldb/Core/Section.h"
19 #include "lldb/Host/FileSystem.h"
20 #include "lldb/Host/HostNativeProcessBase.h"
21 #include "lldb/Host/HostProcess.h"
22 #include "lldb/Host/windows/HostThreadWindows.h"
23 #include "lldb/Host/windows/windows.h"
24 #include "lldb/Symbol/ObjectFile.h"
25 #include "lldb/Target/DynamicLoader.h"
26 #include "lldb/Target/MemoryRegionInfo.h"
27 #include "lldb/Target/StopInfo.h"
28 #include "lldb/Target/Target.h"
29 #include "lldb/Utility/State.h"
30 
31 #include "llvm/Support/ConvertUTF.h"
32 #include "llvm/Support/Format.h"
33 #include "llvm/Support/Threading.h"
34 #include "llvm/Support/raw_ostream.h"
35 
36 #include "DebuggerThread.h"
37 #include "ExceptionRecord.h"
38 #include "ForwardDecl.h"
39 #include "LocalDebugDelegate.h"
40 #include "ProcessWindowsLog.h"
41 #include "TargetThreadWindows.h"
42 
43 using namespace lldb;
44 using namespace lldb_private;
45 
46 namespace {
47 std::string GetProcessExecutableName(HANDLE process_handle) {
48   std::vector<wchar_t> file_name;
49   DWORD file_name_size = MAX_PATH; // first guess, not an absolute limit
50   DWORD copied = 0;
51   do {
52     file_name_size *= 2;
53     file_name.resize(file_name_size);
54     copied = ::GetModuleFileNameExW(process_handle, NULL, file_name.data(),
55                                     file_name_size);
56   } while (copied >= file_name_size);
57   file_name.resize(copied);
58   std::string result;
59   llvm::convertWideToUTF8(file_name.data(), result);
60   return result;
61 }
62 
63 std::string GetProcessExecutableName(DWORD pid) {
64   std::string file_name;
65   HANDLE process_handle =
66       ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
67   if (process_handle != NULL) {
68     file_name = GetProcessExecutableName(process_handle);
69     ::CloseHandle(process_handle);
70   }
71   return file_name;
72 }
73 
74 DWORD ConvertLldbToWinApiProtect(uint32_t protect) {
75   // We also can process a read / write permissions here, but if the debugger
76   // will make later a write into the allocated memory, it will fail. To get
77   // around it is possible inside DoWriteMemory to remember memory permissions,
78   // allow write, write and restore permissions, but for now we process only
79   // the executable permission.
80   //
81   // TODO: Process permissions other than executable
82   if (protect & ePermissionsExecutable)
83     return PAGE_EXECUTE_READWRITE;
84 
85   return PAGE_READWRITE;
86 }
87 
88 } // anonymous namespace
89 
90 namespace lldb_private {
91 
92 // We store a pointer to this class in the ProcessWindows, so that we don't
93 // expose Windows-specific types and implementation details from a public
94 // header file.
95 class ProcessWindowsData {
96 public:
97   ProcessWindowsData(bool stop_at_entry) : m_stop_at_entry(stop_at_entry) {
98     m_initial_stop_event = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
99   }
100 
101   ~ProcessWindowsData() { ::CloseHandle(m_initial_stop_event); }
102 
103   Status m_launch_error;
104   DebuggerThreadSP m_debugger;
105   StopInfoSP m_pending_stop_info;
106   HANDLE m_initial_stop_event = nullptr;
107   bool m_initial_stop_received = false;
108   bool m_stop_at_entry;
109   std::map<lldb::tid_t, HostThread> m_new_threads;
110   std::set<lldb::tid_t> m_exited_threads;
111 };
112 
113 ProcessSP ProcessWindows::CreateInstance(lldb::TargetSP target_sp,
114                                          lldb::ListenerSP listener_sp,
115                                          const FileSpec *) {
116   return ProcessSP(new ProcessWindows(target_sp, listener_sp));
117 }
118 
119 void ProcessWindows::Initialize() {
120   static llvm::once_flag g_once_flag;
121 
122   llvm::call_once(g_once_flag, []() {
123     PluginManager::RegisterPlugin(GetPluginNameStatic(),
124                                   GetPluginDescriptionStatic(), CreateInstance);
125   });
126 }
127 
128 void ProcessWindows::Terminate() {}
129 
130 lldb_private::ConstString ProcessWindows::GetPluginNameStatic() {
131   static ConstString g_name("windows");
132   return g_name;
133 }
134 
135 const char *ProcessWindows::GetPluginDescriptionStatic() {
136   return "Process plugin for Windows";
137 }
138 
139 // Constructors and destructors.
140 
141 ProcessWindows::ProcessWindows(lldb::TargetSP target_sp,
142                                lldb::ListenerSP listener_sp)
143     : lldb_private::Process(target_sp, listener_sp) {}
144 
145 ProcessWindows::~ProcessWindows() {}
146 
147 size_t ProcessWindows::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
148   error.SetErrorString("GetSTDOUT unsupported on Windows");
149   return 0;
150 }
151 
152 size_t ProcessWindows::GetSTDERR(char *buf, size_t buf_size, Status &error) {
153   error.SetErrorString("GetSTDERR unsupported on Windows");
154   return 0;
155 }
156 
157 size_t ProcessWindows::PutSTDIN(const char *buf, size_t buf_size,
158                                 Status &error) {
159   error.SetErrorString("PutSTDIN unsupported on Windows");
160   return 0;
161 }
162 
163 // ProcessInterface protocol.
164 
165 lldb_private::ConstString ProcessWindows::GetPluginName() {
166   return GetPluginNameStatic();
167 }
168 
169 uint32_t ProcessWindows::GetPluginVersion() { return 1; }
170 
171 Status ProcessWindows::EnableBreakpointSite(BreakpointSite *bp_site) {
172   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_BREAKPOINTS);
173   LLDB_LOG(log, "bp_site = {0:x}, id={1}, addr={2:x}", bp_site,
174            bp_site->GetID(), bp_site->GetLoadAddress());
175 
176   Status error = EnableSoftwareBreakpoint(bp_site);
177   if (!error.Success())
178     LLDB_LOG(log, "error: {0}", error);
179   return error;
180 }
181 
182 Status ProcessWindows::DisableBreakpointSite(BreakpointSite *bp_site) {
183   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_BREAKPOINTS);
184   LLDB_LOG(log, "bp_site = {0:x}, id={1}, addr={2:x}", bp_site,
185            bp_site->GetID(), bp_site->GetLoadAddress());
186 
187   Status error = DisableSoftwareBreakpoint(bp_site);
188 
189   if (!error.Success())
190     LLDB_LOG(log, "error: {0}", error);
191   return error;
192 }
193 
194 Status ProcessWindows::DoDetach(bool keep_stopped) {
195   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
196   DebuggerThreadSP debugger_thread;
197   StateType private_state;
198   {
199     // Acquire the lock only long enough to get the DebuggerThread.
200     // StopDebugging() will trigger a call back into ProcessWindows which will
201     // also acquire the lock.  Thus we have to release the lock before calling
202     // StopDebugging().
203     llvm::sys::ScopedLock lock(m_mutex);
204 
205     private_state = GetPrivateState();
206 
207     if (!m_session_data) {
208       LLDB_LOG(log, "state = {0}, but there is no active session.",
209                private_state);
210       return Status();
211     }
212 
213     debugger_thread = m_session_data->m_debugger;
214   }
215 
216   Status error;
217   if (private_state != eStateExited && private_state != eStateDetached) {
218     LLDB_LOG(log, "detaching from process {0} while state = {1}.",
219              debugger_thread->GetProcess().GetNativeProcess().GetSystemHandle(),
220              private_state);
221     error = debugger_thread->StopDebugging(false);
222     if (error.Success()) {
223       SetPrivateState(eStateDetached);
224     }
225 
226     // By the time StopDebugging returns, there is no more debugger thread, so
227     // we can be assured that no other thread will race for the session data.
228     m_session_data.reset();
229   } else {
230     LLDB_LOG(
231         log,
232         "error: process {0} in state = {1}, but cannot destroy in this state.",
233         debugger_thread->GetProcess().GetNativeProcess().GetSystemHandle(),
234         private_state);
235   }
236 
237   return error;
238 }
239 
240 Status ProcessWindows::DoLaunch(Module *exe_module,
241                                 ProcessLaunchInfo &launch_info) {
242   // Even though m_session_data is accessed here, it is before a debugger
243   // thread has been kicked off.  So there's no race conditions, and it
244   // shouldn't be necessary to acquire the mutex.
245 
246   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
247   Status result;
248 
249   FileSpec working_dir = launch_info.GetWorkingDirectory();
250   namespace fs = llvm::sys::fs;
251   if (working_dir) {
252     FileSystem::Instance().Resolve(working_dir);
253     if (!FileSystem::Instance().IsDirectory(working_dir)) {
254       result.SetErrorStringWithFormat("No such file or directory: %s",
255                                       working_dir.GetCString());
256       return result;
257     }
258   }
259 
260   if (!launch_info.GetFlags().Test(eLaunchFlagDebug)) {
261     StreamString stream;
262     stream.Printf("ProcessWindows unable to launch '%s'.  ProcessWindows can "
263                   "only be used for debug launches.",
264                   launch_info.GetExecutableFile().GetPath().c_str());
265     std::string message = stream.GetString();
266     result.SetErrorString(message.c_str());
267 
268     LLDB_LOG(log, "error: {0}", message);
269     return result;
270   }
271 
272   bool stop_at_entry = launch_info.GetFlags().Test(eLaunchFlagStopAtEntry);
273   m_session_data.reset(new ProcessWindowsData(stop_at_entry));
274 
275   DebugDelegateSP delegate(new LocalDebugDelegate(shared_from_this()));
276   m_session_data->m_debugger.reset(new DebuggerThread(delegate));
277   DebuggerThreadSP debugger = m_session_data->m_debugger;
278 
279   // Kick off the DebugLaunch asynchronously and wait for it to complete.
280   result = debugger->DebugLaunch(launch_info);
281   if (result.Fail()) {
282     LLDB_LOG(log, "failed launching '{0}'. {1}",
283              launch_info.GetExecutableFile().GetPath(), result);
284     return result;
285   }
286 
287   HostProcess process;
288   Status error = WaitForDebuggerConnection(debugger, process);
289   if (error.Fail()) {
290     LLDB_LOG(log, "failed launching '{0}'. {1}",
291              launch_info.GetExecutableFile().GetPath(), error);
292     return error;
293   }
294 
295   LLDB_LOG(log, "successfully launched '{0}'",
296            launch_info.GetExecutableFile().GetPath());
297 
298   // We've hit the initial stop.  If eLaunchFlagsStopAtEntry was specified, the
299   // private state should already be set to eStateStopped as a result of
300   // hitting the initial breakpoint.  If it was not set, the breakpoint should
301   // have already been resumed from and the private state should already be
302   // eStateRunning.
303   launch_info.SetProcessID(process.GetProcessId());
304   SetID(process.GetProcessId());
305 
306   return result;
307 }
308 
309 Status
310 ProcessWindows::DoAttachToProcessWithID(lldb::pid_t pid,
311                                         const ProcessAttachInfo &attach_info) {
312   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
313   m_session_data.reset(
314       new ProcessWindowsData(!attach_info.GetContinueOnceAttached()));
315 
316   DebugDelegateSP delegate(new LocalDebugDelegate(shared_from_this()));
317   DebuggerThreadSP debugger(new DebuggerThread(delegate));
318 
319   m_session_data->m_debugger = debugger;
320 
321   DWORD process_id = static_cast<DWORD>(pid);
322   Status error = debugger->DebugAttach(process_id, attach_info);
323   if (error.Fail()) {
324     LLDB_LOG(
325         log,
326         "encountered an error occurred initiating the asynchronous attach. {0}",
327         error);
328     return error;
329   }
330 
331   HostProcess process;
332   error = WaitForDebuggerConnection(debugger, process);
333   if (error.Fail()) {
334     LLDB_LOG(log,
335              "encountered an error waiting for the debugger to connect. {0}",
336              error);
337     return error;
338   }
339 
340   LLDB_LOG(log, "successfully attached to process with pid={0}", process_id);
341 
342   // We've hit the initial stop.  If eLaunchFlagsStopAtEntry was specified, the
343   // private state should already be set to eStateStopped as a result of
344   // hitting the initial breakpoint.  If it was not set, the breakpoint should
345   // have already been resumed from and the private state should already be
346   // eStateRunning.
347   SetID(process.GetProcessId());
348   return error;
349 }
350 
351 Status ProcessWindows::DoResume() {
352   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
353   llvm::sys::ScopedLock lock(m_mutex);
354   Status error;
355 
356   StateType private_state = GetPrivateState();
357   if (private_state == eStateStopped || private_state == eStateCrashed) {
358     LLDB_LOG(log, "process {0} is in state {1}.  Resuming...",
359              m_session_data->m_debugger->GetProcess().GetProcessId(),
360              GetPrivateState());
361 
362     ExceptionRecordSP active_exception =
363         m_session_data->m_debugger->GetActiveException().lock();
364     if (active_exception) {
365       // Resume the process and continue processing debug events.  Mask the
366       // exception so that from the process's view, there is no indication that
367       // anything happened.
368       m_session_data->m_debugger->ContinueAsyncException(
369           ExceptionResult::MaskException);
370     }
371 
372     LLDB_LOG(log, "resuming {0} threads.", m_thread_list.GetSize());
373 
374     bool failed = false;
375     for (uint32_t i = 0; i < m_thread_list.GetSize(); ++i) {
376       auto thread = std::static_pointer_cast<TargetThreadWindows>(
377           m_thread_list.GetThreadAtIndex(i));
378       Status result = thread->DoResume();
379       if (result.Fail()) {
380         failed = true;
381         LLDB_LOG(
382             log,
383             "Trying to resume thread at index {0}, but failed with error {1}.",
384             i, result);
385       }
386     }
387 
388     if (failed) {
389       error.SetErrorString("ProcessWindows::DoResume failed");
390       return error;
391     } else {
392       SetPrivateState(eStateRunning);
393     }
394   } else {
395     LLDB_LOG(log, "error: process {0} is in state {1}.  Returning...",
396              m_session_data->m_debugger->GetProcess().GetProcessId(),
397              GetPrivateState());
398   }
399   return error;
400 }
401 
402 Status ProcessWindows::DoDestroy() {
403   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
404   DebuggerThreadSP debugger_thread;
405   StateType private_state;
406   {
407     // Acquire this lock inside an inner scope, only long enough to get the
408     // DebuggerThread. StopDebugging() will trigger a call back into
409     // ProcessWindows which will acquire the lock again, so we need to not
410     // deadlock.
411     llvm::sys::ScopedLock lock(m_mutex);
412 
413     private_state = GetPrivateState();
414 
415     if (!m_session_data) {
416       LLDB_LOG(log, "warning: state = {0}, but there is no active session.",
417                private_state);
418       return Status();
419     }
420 
421     debugger_thread = m_session_data->m_debugger;
422   }
423 
424   Status error;
425   if (private_state != eStateExited && private_state != eStateDetached) {
426     LLDB_LOG(log, "Shutting down process {0} while state = {1}.",
427              debugger_thread->GetProcess().GetNativeProcess().GetSystemHandle(),
428              private_state);
429     error = debugger_thread->StopDebugging(true);
430 
431     // By the time StopDebugging returns, there is no more debugger thread, so
432     // we can be assured that no other thread will race for the session data.
433     m_session_data.reset();
434   } else {
435     LLDB_LOG(log, "cannot destroy process {0} while state = {1}",
436              debugger_thread->GetProcess().GetNativeProcess().GetSystemHandle(),
437              private_state);
438   }
439 
440   return error;
441 }
442 
443 Status ProcessWindows::DoHalt(bool &caused_stop) {
444   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
445   Status error;
446   StateType state = GetPrivateState();
447   if (state == eStateStopped)
448     caused_stop = false;
449   else {
450     llvm::sys::ScopedLock lock(m_mutex);
451     caused_stop = ::DebugBreakProcess(m_session_data->m_debugger->GetProcess()
452                                           .GetNativeProcess()
453                                           .GetSystemHandle());
454     if (!caused_stop) {
455       error.SetError(::GetLastError(), eErrorTypeWin32);
456       LLDB_LOG(log, "DebugBreakProcess failed with error {0}", error);
457     }
458   }
459   return error;
460 }
461 
462 void ProcessWindows::DidLaunch() {
463   ArchSpec arch_spec;
464   DidAttach(arch_spec);
465 }
466 
467 void ProcessWindows::DidAttach(ArchSpec &arch_spec) {
468   llvm::sys::ScopedLock lock(m_mutex);
469 
470   // The initial stop won't broadcast the state change event, so account for
471   // that here.
472   if (m_session_data && GetPrivateState() == eStateStopped &&
473       m_session_data->m_stop_at_entry)
474     RefreshStateAfterStop();
475 }
476 
477 static void
478 DumpAdditionalExceptionInformation(llvm::raw_ostream &stream,
479                                    const ExceptionRecordSP &exception) {
480   // Decode additional exception information for specific exception types based
481   // on
482   // https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_exception_record
483 
484   const int addr_min_width = 2 + 8; // "0x" + 4 address bytes
485 
486   const std::vector<ULONG_PTR> &args = exception->GetExceptionArguments();
487   switch (exception->GetExceptionCode()) {
488   case EXCEPTION_ACCESS_VIOLATION: {
489     if (args.size() < 2)
490       break;
491 
492     stream << ": ";
493     const int access_violation_code = args[0];
494     const lldb::addr_t access_violation_address = args[1];
495     switch (access_violation_code) {
496     case 0:
497       stream << "Access violation reading";
498       break;
499     case 1:
500       stream << "Access violation writing";
501       break;
502     case 8:
503       stream << "User-mode data execution prevention (DEP) violation at";
504       break;
505     default:
506       stream << "Unknown access violation (code " << access_violation_code
507              << ") at";
508       break;
509     }
510     stream << " location "
511            << llvm::format_hex(access_violation_address, addr_min_width);
512     break;
513   }
514   case EXCEPTION_IN_PAGE_ERROR: {
515     if (args.size() < 3)
516       break;
517 
518     stream << ": ";
519     const int page_load_error_code = args[0];
520     const lldb::addr_t page_load_error_address = args[1];
521     const DWORD underlying_code = args[2];
522     switch (page_load_error_code) {
523     case 0:
524       stream << "In page error reading";
525       break;
526     case 1:
527       stream << "In page error writing";
528       break;
529     case 8:
530       stream << "User-mode data execution prevention (DEP) violation at";
531       break;
532     default:
533       stream << "Unknown page loading error (code " << page_load_error_code
534              << ") at";
535       break;
536     }
537     stream << " location "
538            << llvm::format_hex(page_load_error_address, addr_min_width)
539            << " (status code " << llvm::format_hex(underlying_code, 8) << ")";
540     break;
541   }
542   }
543 }
544 
545 void ProcessWindows::RefreshStateAfterStop() {
546   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EXCEPTION);
547   llvm::sys::ScopedLock lock(m_mutex);
548 
549   if (!m_session_data) {
550     LLDB_LOG(log, "no active session.  Returning...");
551     return;
552   }
553 
554   m_thread_list.RefreshStateAfterStop();
555 
556   std::weak_ptr<ExceptionRecord> exception_record =
557       m_session_data->m_debugger->GetActiveException();
558   ExceptionRecordSP active_exception = exception_record.lock();
559   if (!active_exception) {
560     LLDB_LOG(log,
561              "there is no active exception in process {0}.  Why is the "
562              "process stopped?",
563              m_session_data->m_debugger->GetProcess().GetProcessId());
564     return;
565   }
566 
567   StopInfoSP stop_info;
568   m_thread_list.SetSelectedThreadByID(active_exception->GetThreadID());
569   ThreadSP stop_thread = m_thread_list.GetSelectedThread();
570   if (!stop_thread)
571     return;
572 
573   switch (active_exception->GetExceptionCode()) {
574   case EXCEPTION_SINGLE_STEP: {
575     RegisterContextSP register_context = stop_thread->GetRegisterContext();
576     const uint64_t pc = register_context->GetPC();
577     BreakpointSiteSP site(GetBreakpointSiteList().FindByAddress(pc));
578     if (site && site->ValidForThisThread(stop_thread.get())) {
579       LLDB_LOG(log,
580                "Single-stepped onto a breakpoint in process {0} at "
581                "address {1:x} with breakpoint site {2}",
582                m_session_data->m_debugger->GetProcess().GetProcessId(), pc,
583                site->GetID());
584       stop_info = StopInfo::CreateStopReasonWithBreakpointSiteID(*stop_thread,
585                                                                  site->GetID());
586       stop_thread->SetStopInfo(stop_info);
587     } else {
588       LLDB_LOG(log, "single stepping thread {0}", stop_thread->GetID());
589       stop_info = StopInfo::CreateStopReasonToTrace(*stop_thread);
590       stop_thread->SetStopInfo(stop_info);
591     }
592     return;
593   }
594 
595   case EXCEPTION_BREAKPOINT: {
596     RegisterContextSP register_context = stop_thread->GetRegisterContext();
597 
598     // The current EIP is AFTER the BP opcode, which is one byte.
599     uint64_t pc = register_context->GetPC() - 1;
600 
601     BreakpointSiteSP site(GetBreakpointSiteList().FindByAddress(pc));
602     if (site) {
603       LLDB_LOG(log,
604                "detected breakpoint in process {0} at address {1:x} with "
605                "breakpoint site {2}",
606                m_session_data->m_debugger->GetProcess().GetProcessId(), pc,
607                site->GetID());
608 
609       if (site->ValidForThisThread(stop_thread.get())) {
610         LLDB_LOG(log,
611                  "Breakpoint site {0} is valid for this thread ({1:x}), "
612                  "creating stop info.",
613                  site->GetID(), stop_thread->GetID());
614 
615         stop_info = StopInfo::CreateStopReasonWithBreakpointSiteID(
616             *stop_thread, site->GetID());
617         register_context->SetPC(pc);
618       } else {
619         LLDB_LOG(log,
620                  "Breakpoint site {0} is not valid for this thread, "
621                  "creating empty stop info.",
622                  site->GetID());
623       }
624       stop_thread->SetStopInfo(stop_info);
625       return;
626     } else {
627       // The thread hit a hard-coded breakpoint like an `int 3` or
628       // `__debugbreak()`.
629       LLDB_LOG(log,
630                "No breakpoint site matches for this thread. __debugbreak()?  "
631                "Creating stop info with the exception.");
632       // FALLTHROUGH:  We'll treat this as a generic exception record in the
633       // default case.
634       LLVM_FALLTHROUGH;
635     }
636   }
637 
638   default: {
639     std::string desc;
640     llvm::raw_string_ostream desc_stream(desc);
641     desc_stream << "Exception "
642                 << llvm::format_hex(active_exception->GetExceptionCode(), 8)
643                 << " encountered at address "
644                 << llvm::format_hex(active_exception->GetExceptionAddress(), 8);
645     DumpAdditionalExceptionInformation(desc_stream, active_exception);
646 
647     stop_info = StopInfo::CreateStopReasonWithException(
648         *stop_thread, desc_stream.str().c_str());
649     stop_thread->SetStopInfo(stop_info);
650     LLDB_LOG(log, "{0}", desc_stream.str());
651     return;
652   }
653   }
654 }
655 
656 bool ProcessWindows::CanDebug(lldb::TargetSP target_sp,
657                               bool plugin_specified_by_name) {
658   if (plugin_specified_by_name)
659     return true;
660 
661   // For now we are just making sure the file exists for a given module
662   ModuleSP exe_module_sp(target_sp->GetExecutableModule());
663   if (exe_module_sp.get())
664     return FileSystem::Instance().Exists(exe_module_sp->GetFileSpec());
665   // However, if there is no executable module, we return true since we might
666   // be preparing to attach.
667   return true;
668 }
669 
670 bool ProcessWindows::UpdateThreadList(ThreadList &old_thread_list,
671                                       ThreadList &new_thread_list) {
672   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_THREAD);
673   // Add all the threads that were previously running and for which we did not
674   // detect a thread exited event.
675   int new_size = 0;
676   int continued_threads = 0;
677   int exited_threads = 0;
678   int new_threads = 0;
679 
680   for (ThreadSP old_thread : old_thread_list.Threads()) {
681     lldb::tid_t old_thread_id = old_thread->GetID();
682     auto exited_thread_iter =
683         m_session_data->m_exited_threads.find(old_thread_id);
684     if (exited_thread_iter == m_session_data->m_exited_threads.end()) {
685       new_thread_list.AddThread(old_thread);
686       ++new_size;
687       ++continued_threads;
688       LLDB_LOGV(log, "Thread {0} was running and is still running.",
689                 old_thread_id);
690     } else {
691       LLDB_LOGV(log, "Thread {0} was running and has exited.", old_thread_id);
692       ++exited_threads;
693     }
694   }
695 
696   // Also add all the threads that are new since the last time we broke into
697   // the debugger.
698   for (const auto &thread_info : m_session_data->m_new_threads) {
699     ThreadSP thread(new TargetThreadWindows(*this, thread_info.second));
700     thread->SetID(thread_info.first);
701     new_thread_list.AddThread(thread);
702     ++new_size;
703     ++new_threads;
704     LLDB_LOGV(log, "Thread {0} is new since last update.", thread_info.first);
705   }
706 
707   LLDB_LOG(log, "{0} new threads, {1} old threads, {2} exited threads.",
708            new_threads, continued_threads, exited_threads);
709 
710   m_session_data->m_new_threads.clear();
711   m_session_data->m_exited_threads.clear();
712 
713   return new_size > 0;
714 }
715 
716 bool ProcessWindows::IsAlive() {
717   StateType state = GetPrivateState();
718   switch (state) {
719   case eStateCrashed:
720   case eStateDetached:
721   case eStateUnloaded:
722   case eStateExited:
723   case eStateInvalid:
724     return false;
725   default:
726     return true;
727   }
728 }
729 
730 size_t ProcessWindows::DoReadMemory(lldb::addr_t vm_addr, void *buf,
731                                     size_t size, Status &error) {
732   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY);
733   llvm::sys::ScopedLock lock(m_mutex);
734 
735   if (!m_session_data)
736     return 0;
737 
738   LLDB_LOG(log, "attempting to read {0} bytes from address {1:x}", size,
739            vm_addr);
740 
741   HostProcess process = m_session_data->m_debugger->GetProcess();
742   void *addr = reinterpret_cast<void *>(vm_addr);
743   SIZE_T bytes_read = 0;
744   if (!ReadProcessMemory(process.GetNativeProcess().GetSystemHandle(), addr,
745                          buf, size, &bytes_read)) {
746     // Reading from the process can fail for a number of reasons - set the
747     // error code and make sure that the number of bytes read is set back to 0
748     // because in some scenarios the value of bytes_read returned from the API
749     // is garbage.
750     error.SetError(GetLastError(), eErrorTypeWin32);
751     LLDB_LOG(log, "reading failed with error: {0}", error);
752     bytes_read = 0;
753   }
754   return bytes_read;
755 }
756 
757 size_t ProcessWindows::DoWriteMemory(lldb::addr_t vm_addr, const void *buf,
758                                      size_t size, Status &error) {
759   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY);
760   llvm::sys::ScopedLock lock(m_mutex);
761   LLDB_LOG(log, "attempting to write {0} bytes into address {1:x}", size,
762            vm_addr);
763 
764   if (!m_session_data) {
765     LLDB_LOG(log, "cannot write, there is no active debugger connection.");
766     return 0;
767   }
768 
769   HostProcess process = m_session_data->m_debugger->GetProcess();
770   void *addr = reinterpret_cast<void *>(vm_addr);
771   SIZE_T bytes_written = 0;
772   lldb::process_t handle = process.GetNativeProcess().GetSystemHandle();
773   if (WriteProcessMemory(handle, addr, buf, size, &bytes_written))
774     FlushInstructionCache(handle, addr, bytes_written);
775   else {
776     error.SetError(GetLastError(), eErrorTypeWin32);
777     LLDB_LOG(log, "writing failed with error: {0}", error);
778   }
779   return bytes_written;
780 }
781 
782 lldb::addr_t ProcessWindows::DoAllocateMemory(size_t size, uint32_t permissions,
783                                               Status &error) {
784   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY);
785   llvm::sys::ScopedLock lock(m_mutex);
786   LLDB_LOG(log, "attempting to allocate {0} bytes with permissions {1}", size,
787            permissions);
788 
789   if (!m_session_data) {
790     LLDB_LOG(log, "cannot allocate, there is no active debugger connection.");
791     error.SetErrorString(
792         "cannot allocate, there is no active debugger connection");
793     return LLDB_INVALID_ADDRESS;
794   }
795 
796   HostProcess process = m_session_data->m_debugger->GetProcess();
797   lldb::process_t handle = process.GetNativeProcess().GetSystemHandle();
798   auto protect = ConvertLldbToWinApiProtect(permissions);
799   auto result = VirtualAllocEx(handle, nullptr, size, MEM_COMMIT, protect);
800   if (!result) {
801     error.SetError(GetLastError(), eErrorTypeWin32);
802     LLDB_LOG(log, "allocating failed with error: {0}", error);
803     return LLDB_INVALID_ADDRESS;
804   }
805 
806   return reinterpret_cast<addr_t>(result);
807 }
808 
809 Status ProcessWindows::DoDeallocateMemory(lldb::addr_t ptr) {
810   Status result;
811 
812   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY);
813   llvm::sys::ScopedLock lock(m_mutex);
814   LLDB_LOG(log, "attempting to deallocate bytes at address {0}", ptr);
815 
816   if (!m_session_data) {
817     LLDB_LOG(log, "cannot deallocate, there is no active debugger connection.");
818     result.SetErrorString(
819         "cannot deallocate, there is no active debugger connection");
820     return result;
821   }
822 
823   HostProcess process = m_session_data->m_debugger->GetProcess();
824   lldb::process_t handle = process.GetNativeProcess().GetSystemHandle();
825   if (!VirtualFreeEx(handle, reinterpret_cast<LPVOID>(ptr), 0, MEM_RELEASE)) {
826     result.SetError(GetLastError(), eErrorTypeWin32);
827     LLDB_LOG(log, "deallocating failed with error: {0}", result);
828     return result;
829   }
830 
831   return result;
832 }
833 
834 Status ProcessWindows::GetMemoryRegionInfo(lldb::addr_t vm_addr,
835                                            MemoryRegionInfo &info) {
836   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY);
837   Status error;
838   llvm::sys::ScopedLock lock(m_mutex);
839   info.Clear();
840 
841   if (!m_session_data) {
842     error.SetErrorString(
843         "GetMemoryRegionInfo called with no debugging session.");
844     LLDB_LOG(log, "error: {0}", error);
845     return error;
846   }
847   HostProcess process = m_session_data->m_debugger->GetProcess();
848   lldb::process_t handle = process.GetNativeProcess().GetSystemHandle();
849   if (handle == nullptr || handle == LLDB_INVALID_PROCESS) {
850     error.SetErrorString(
851         "GetMemoryRegionInfo called with an invalid target process.");
852     LLDB_LOG(log, "error: {0}", error);
853     return error;
854   }
855 
856   LLDB_LOG(log, "getting info for address {0:x}", vm_addr);
857 
858   void *addr = reinterpret_cast<void *>(vm_addr);
859   MEMORY_BASIC_INFORMATION mem_info = {};
860   SIZE_T result = ::VirtualQueryEx(handle, addr, &mem_info, sizeof(mem_info));
861   if (result == 0) {
862     if (::GetLastError() == ERROR_INVALID_PARAMETER) {
863       // ERROR_INVALID_PARAMETER is returned if VirtualQueryEx is called with
864       // an address past the highest accessible address. We should return a
865       // range from the vm_addr to LLDB_INVALID_ADDRESS
866       info.GetRange().SetRangeBase(vm_addr);
867       info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
868       info.SetReadable(MemoryRegionInfo::eNo);
869       info.SetExecutable(MemoryRegionInfo::eNo);
870       info.SetWritable(MemoryRegionInfo::eNo);
871       info.SetMapped(MemoryRegionInfo::eNo);
872       return error;
873     } else {
874       error.SetError(::GetLastError(), eErrorTypeWin32);
875       LLDB_LOG(log,
876                "VirtualQueryEx returned error {0} while getting memory "
877                "region info for address {1:x}",
878                error, vm_addr);
879       return error;
880     }
881   }
882 
883   // Protect bits are only valid for MEM_COMMIT regions.
884   if (mem_info.State == MEM_COMMIT) {
885     const bool readable = IsPageReadable(mem_info.Protect);
886     const bool executable = IsPageExecutable(mem_info.Protect);
887     const bool writable = IsPageWritable(mem_info.Protect);
888     info.SetReadable(readable ? MemoryRegionInfo::eYes : MemoryRegionInfo::eNo);
889     info.SetExecutable(executable ? MemoryRegionInfo::eYes
890                                   : MemoryRegionInfo::eNo);
891     info.SetWritable(writable ? MemoryRegionInfo::eYes : MemoryRegionInfo::eNo);
892   } else {
893     info.SetReadable(MemoryRegionInfo::eNo);
894     info.SetExecutable(MemoryRegionInfo::eNo);
895     info.SetWritable(MemoryRegionInfo::eNo);
896   }
897 
898   // AllocationBase is defined for MEM_COMMIT and MEM_RESERVE but not MEM_FREE.
899   if (mem_info.State != MEM_FREE) {
900     info.GetRange().SetRangeBase(
901         reinterpret_cast<addr_t>(mem_info.AllocationBase));
902     info.GetRange().SetRangeEnd(reinterpret_cast<addr_t>(mem_info.BaseAddress) +
903                                 mem_info.RegionSize);
904     info.SetMapped(MemoryRegionInfo::eYes);
905   } else {
906     // In the unmapped case we need to return the distance to the next block of
907     // memory. VirtualQueryEx nearly does that except that it gives the
908     // distance from the start of the page containing vm_addr.
909     SYSTEM_INFO data;
910     GetSystemInfo(&data);
911     DWORD page_offset = vm_addr % data.dwPageSize;
912     info.GetRange().SetRangeBase(vm_addr);
913     info.GetRange().SetByteSize(mem_info.RegionSize - page_offset);
914     info.SetMapped(MemoryRegionInfo::eNo);
915   }
916 
917   error.SetError(::GetLastError(), eErrorTypeWin32);
918   LLDB_LOGV(log,
919             "Memory region info for address {0}: readable={1}, "
920             "executable={2}, writable={3}",
921             vm_addr, info.GetReadable(), info.GetExecutable(),
922             info.GetWritable());
923   return error;
924 }
925 
926 lldb::addr_t ProcessWindows::GetImageInfoAddress() {
927   Target &target = GetTarget();
928   ObjectFile *obj_file = target.GetExecutableModule()->GetObjectFile();
929   Address addr = obj_file->GetImageInfoAddress(&target);
930   if (addr.IsValid())
931     return addr.GetLoadAddress(&target);
932   else
933     return LLDB_INVALID_ADDRESS;
934 }
935 
936 DynamicLoaderWindowsDYLD *ProcessWindows::GetDynamicLoader() {
937   if (m_dyld_up.get() == NULL)
938     m_dyld_up.reset(DynamicLoader::FindPlugin(
939         this, DynamicLoaderWindowsDYLD::GetPluginNameStatic().GetCString()));
940   return static_cast<DynamicLoaderWindowsDYLD *>(m_dyld_up.get());
941 }
942 
943 void ProcessWindows::OnExitProcess(uint32_t exit_code) {
944   // No need to acquire the lock since m_session_data isn't accessed.
945   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
946   LLDB_LOG(log, "Process {0} exited with code {1}", GetID(), exit_code);
947 
948   TargetSP target = CalculateTarget();
949   if (target) {
950     ModuleSP executable_module = target->GetExecutableModule();
951     ModuleList unloaded_modules;
952     unloaded_modules.Append(executable_module);
953     target->ModulesDidUnload(unloaded_modules, true);
954   }
955 
956   SetProcessExitStatus(GetID(), true, 0, exit_code);
957   SetPrivateState(eStateExited);
958 
959   // If the process exits before any initial stop then notify the debugger
960   // of the error otherwise WaitForDebuggerConnection() will be blocked.
961   // An example of this issue is when a process fails to load a dependent DLL.
962   if (m_session_data && !m_session_data->m_initial_stop_received) {
963     Status error(exit_code, eErrorTypeWin32);
964     OnDebuggerError(error, 0);
965   }
966 }
967 
968 void ProcessWindows::OnDebuggerConnected(lldb::addr_t image_base) {
969   DebuggerThreadSP debugger = m_session_data->m_debugger;
970   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
971   LLDB_LOG(log, "Debugger connected to process {0}.  Image base = {1:x}",
972            debugger->GetProcess().GetProcessId(), image_base);
973 
974   ModuleSP module = GetTarget().GetExecutableModule();
975   if (!module) {
976     // During attach, we won't have the executable module, so find it now.
977     const DWORD pid = debugger->GetProcess().GetProcessId();
978     const std::string file_name = GetProcessExecutableName(pid);
979     if (file_name.empty()) {
980       return;
981     }
982 
983     FileSpec executable_file(file_name);
984     FileSystem::Instance().Resolve(executable_file);
985     ModuleSpec module_spec(executable_file);
986     Status error;
987     module = GetTarget().GetOrCreateModule(module_spec,
988                                            true /* notify */, &error);
989     if (!module) {
990       return;
991     }
992 
993     GetTarget().SetExecutableModule(module, eLoadDependentsNo);
994   }
995 
996   if (auto dyld = GetDynamicLoader())
997     dyld->OnLoadModule(module, ModuleSpec(), image_base);
998 
999   // Add the main executable module to the list of pending module loads.  We
1000   // can't call GetTarget().ModulesDidLoad() here because we still haven't
1001   // returned from DoLaunch() / DoAttach() yet so the target may not have set
1002   // the process instance to `this` yet.
1003   llvm::sys::ScopedLock lock(m_mutex);
1004   const HostThreadWindows &wmain_thread =
1005       debugger->GetMainThread().GetNativeThread();
1006   m_session_data->m_new_threads[wmain_thread.GetThreadId()] =
1007       debugger->GetMainThread();
1008 }
1009 
1010 ExceptionResult
1011 ProcessWindows::OnDebugException(bool first_chance,
1012                                  const ExceptionRecord &record) {
1013   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EXCEPTION);
1014   llvm::sys::ScopedLock lock(m_mutex);
1015 
1016   // FIXME: Without this check, occasionally when running the test suite there
1017   // is
1018   // an issue where m_session_data can be null.  It's not clear how this could
1019   // happen but it only surfaces while running the test suite.  In order to
1020   // properly diagnose this, we probably need to first figure allow the test
1021   // suite to print out full lldb logs, and then add logging to the process
1022   // plugin.
1023   if (!m_session_data) {
1024     LLDB_LOG(log,
1025              "Debugger thread reported exception {0:x} at address {1:x}, "
1026              "but there is no session.",
1027              record.GetExceptionCode(), record.GetExceptionAddress());
1028     return ExceptionResult::SendToApplication;
1029   }
1030 
1031   if (!first_chance) {
1032     // Not any second chance exception is an application crash by definition.
1033     // It may be an expression evaluation crash.
1034     SetPrivateState(eStateStopped);
1035   }
1036 
1037   ExceptionResult result = ExceptionResult::SendToApplication;
1038   switch (record.GetExceptionCode()) {
1039   case EXCEPTION_BREAKPOINT:
1040     // Handle breakpoints at the first chance.
1041     result = ExceptionResult::BreakInDebugger;
1042 
1043     if (!m_session_data->m_initial_stop_received) {
1044       LLDB_LOG(
1045           log,
1046           "Hit loader breakpoint at address {0:x}, setting initial stop event.",
1047           record.GetExceptionAddress());
1048       m_session_data->m_initial_stop_received = true;
1049       ::SetEvent(m_session_data->m_initial_stop_event);
1050     } else {
1051       LLDB_LOG(log, "Hit non-loader breakpoint at address {0:x}.",
1052                record.GetExceptionAddress());
1053     }
1054     SetPrivateState(eStateStopped);
1055     break;
1056   case EXCEPTION_SINGLE_STEP:
1057     result = ExceptionResult::BreakInDebugger;
1058     SetPrivateState(eStateStopped);
1059     break;
1060   default:
1061     LLDB_LOG(log,
1062              "Debugger thread reported exception {0:x} at address {1:x} "
1063              "(first_chance={2})",
1064              record.GetExceptionCode(), record.GetExceptionAddress(),
1065              first_chance);
1066     // For non-breakpoints, give the application a chance to handle the
1067     // exception first.
1068     if (first_chance)
1069       result = ExceptionResult::SendToApplication;
1070     else
1071       result = ExceptionResult::BreakInDebugger;
1072   }
1073 
1074   return result;
1075 }
1076 
1077 void ProcessWindows::OnCreateThread(const HostThread &new_thread) {
1078   llvm::sys::ScopedLock lock(m_mutex);
1079   const HostThreadWindows &wnew_thread = new_thread.GetNativeThread();
1080   m_session_data->m_new_threads[wnew_thread.GetThreadId()] = new_thread;
1081 }
1082 
1083 void ProcessWindows::OnExitThread(lldb::tid_t thread_id, uint32_t exit_code) {
1084   llvm::sys::ScopedLock lock(m_mutex);
1085 
1086   // On a forced termination, we may get exit thread events after the session
1087   // data has been cleaned up.
1088   if (!m_session_data)
1089     return;
1090 
1091   // A thread may have started and exited before the debugger stopped allowing a
1092   // refresh.
1093   // Just remove it from the new threads list in that case.
1094   auto iter = m_session_data->m_new_threads.find(thread_id);
1095   if (iter != m_session_data->m_new_threads.end())
1096     m_session_data->m_new_threads.erase(iter);
1097   else
1098     m_session_data->m_exited_threads.insert(thread_id);
1099 }
1100 
1101 void ProcessWindows::OnLoadDll(const ModuleSpec &module_spec,
1102                                lldb::addr_t module_addr) {
1103   if (auto dyld = GetDynamicLoader())
1104     dyld->OnLoadModule(nullptr, module_spec, module_addr);
1105 }
1106 
1107 void ProcessWindows::OnUnloadDll(lldb::addr_t module_addr) {
1108   if (auto dyld = GetDynamicLoader())
1109     dyld->OnUnloadModule(module_addr);
1110 }
1111 
1112 void ProcessWindows::OnDebugString(const std::string &string) {}
1113 
1114 void ProcessWindows::OnDebuggerError(const Status &error, uint32_t type) {
1115   llvm::sys::ScopedLock lock(m_mutex);
1116   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
1117 
1118   if (m_session_data->m_initial_stop_received) {
1119     // This happened while debugging.  Do we shutdown the debugging session,
1120     // try to continue, or do something else?
1121     LLDB_LOG(log,
1122              "Error {0} occurred during debugging.  Unexpected behavior "
1123              "may result.  {1}",
1124              error.GetError(), error);
1125   } else {
1126     // If we haven't actually launched the process yet, this was an error
1127     // launching the process.  Set the internal error and signal the initial
1128     // stop event so that the DoLaunch method wakes up and returns a failure.
1129     m_session_data->m_launch_error = error;
1130     ::SetEvent(m_session_data->m_initial_stop_event);
1131     LLDB_LOG(
1132         log,
1133         "Error {0} occurred launching the process before the initial stop. {1}",
1134         error.GetError(), error);
1135     return;
1136   }
1137 }
1138 
1139 Status ProcessWindows::WaitForDebuggerConnection(DebuggerThreadSP debugger,
1140                                                  HostProcess &process) {
1141   Status result;
1142   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS |
1143                                             WINDOWS_LOG_BREAKPOINTS);
1144   LLDB_LOG(log, "Waiting for loader breakpoint.");
1145 
1146   // Block this function until we receive the initial stop from the process.
1147   if (::WaitForSingleObject(m_session_data->m_initial_stop_event, INFINITE) ==
1148       WAIT_OBJECT_0) {
1149     LLDB_LOG(log, "hit loader breakpoint, returning.");
1150 
1151     process = debugger->GetProcess();
1152     return m_session_data->m_launch_error;
1153   } else
1154     return Status(::GetLastError(), eErrorTypeWin32);
1155 }
1156 
1157 // The Windows page protection bits are NOT independent masks that can be
1158 // bitwise-ORed together.  For example, PAGE_EXECUTE_READ is not (PAGE_EXECUTE
1159 // | PAGE_READ).  To test for an access type, it's necessary to test for any of
1160 // the bits that provide that access type.
1161 bool ProcessWindows::IsPageReadable(uint32_t protect) {
1162   return (protect & PAGE_NOACCESS) == 0;
1163 }
1164 
1165 bool ProcessWindows::IsPageWritable(uint32_t protect) {
1166   return (protect & (PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY |
1167                      PAGE_READWRITE | PAGE_WRITECOPY)) != 0;
1168 }
1169 
1170 bool ProcessWindows::IsPageExecutable(uint32_t protect) {
1171   return (protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE |
1172                      PAGE_EXECUTE_WRITECOPY)) != 0;
1173 }
1174 
1175 } // namespace lldb_private
1176