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     }
635   }
636 
637   default: {
638     std::string desc;
639     llvm::raw_string_ostream desc_stream(desc);
640     desc_stream << "Exception "
641                 << llvm::format_hex(active_exception->GetExceptionCode(), 8)
642                 << " encountered at address "
643                 << llvm::format_hex(active_exception->GetExceptionAddress(), 8);
644     DumpAdditionalExceptionInformation(desc_stream, active_exception);
645 
646     stop_info = StopInfo::CreateStopReasonWithException(
647         *stop_thread, desc_stream.str().c_str());
648     stop_thread->SetStopInfo(stop_info);
649     LLDB_LOG(log, "{0}", desc_stream.str());
650     return;
651   }
652   }
653 }
654 
655 bool ProcessWindows::CanDebug(lldb::TargetSP target_sp,
656                               bool plugin_specified_by_name) {
657   if (plugin_specified_by_name)
658     return true;
659 
660   // For now we are just making sure the file exists for a given module
661   ModuleSP exe_module_sp(target_sp->GetExecutableModule());
662   if (exe_module_sp.get())
663     return FileSystem::Instance().Exists(exe_module_sp->GetFileSpec());
664   // However, if there is no executable module, we return true since we might
665   // be preparing to attach.
666   return true;
667 }
668 
669 bool ProcessWindows::UpdateThreadList(ThreadList &old_thread_list,
670                                       ThreadList &new_thread_list) {
671   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_THREAD);
672   // Add all the threads that were previously running and for which we did not
673   // detect a thread exited event.
674   int new_size = 0;
675   int continued_threads = 0;
676   int exited_threads = 0;
677   int new_threads = 0;
678 
679   for (ThreadSP old_thread : old_thread_list.Threads()) {
680     lldb::tid_t old_thread_id = old_thread->GetID();
681     auto exited_thread_iter =
682         m_session_data->m_exited_threads.find(old_thread_id);
683     if (exited_thread_iter == m_session_data->m_exited_threads.end()) {
684       new_thread_list.AddThread(old_thread);
685       ++new_size;
686       ++continued_threads;
687       LLDB_LOGV(log, "Thread {0} was running and is still running.",
688                 old_thread_id);
689     } else {
690       LLDB_LOGV(log, "Thread {0} was running and has exited.", old_thread_id);
691       ++exited_threads;
692     }
693   }
694 
695   // Also add all the threads that are new since the last time we broke into
696   // the debugger.
697   for (const auto &thread_info : m_session_data->m_new_threads) {
698     ThreadSP thread(new TargetThreadWindows(*this, thread_info.second));
699     thread->SetID(thread_info.first);
700     new_thread_list.AddThread(thread);
701     ++new_size;
702     ++new_threads;
703     LLDB_LOGV(log, "Thread {0} is new since last update.", thread_info.first);
704   }
705 
706   LLDB_LOG(log, "{0} new threads, {1} old threads, {2} exited threads.",
707            new_threads, continued_threads, exited_threads);
708 
709   m_session_data->m_new_threads.clear();
710   m_session_data->m_exited_threads.clear();
711 
712   return new_size > 0;
713 }
714 
715 bool ProcessWindows::IsAlive() {
716   StateType state = GetPrivateState();
717   switch (state) {
718   case eStateCrashed:
719   case eStateDetached:
720   case eStateUnloaded:
721   case eStateExited:
722   case eStateInvalid:
723     return false;
724   default:
725     return true;
726   }
727 }
728 
729 size_t ProcessWindows::DoReadMemory(lldb::addr_t vm_addr, void *buf,
730                                     size_t size, Status &error) {
731   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY);
732   llvm::sys::ScopedLock lock(m_mutex);
733 
734   if (!m_session_data)
735     return 0;
736 
737   LLDB_LOG(log, "attempting to read {0} bytes from address {1:x}", size,
738            vm_addr);
739 
740   HostProcess process = m_session_data->m_debugger->GetProcess();
741   void *addr = reinterpret_cast<void *>(vm_addr);
742   SIZE_T bytes_read = 0;
743   if (!ReadProcessMemory(process.GetNativeProcess().GetSystemHandle(), addr,
744                          buf, size, &bytes_read)) {
745     // Reading from the process can fail for a number of reasons - set the
746     // error code and make sure that the number of bytes read is set back to 0
747     // because in some scenarios the value of bytes_read returned from the API
748     // is garbage.
749     error.SetError(GetLastError(), eErrorTypeWin32);
750     LLDB_LOG(log, "reading failed with error: {0}", error);
751     bytes_read = 0;
752   }
753   return bytes_read;
754 }
755 
756 size_t ProcessWindows::DoWriteMemory(lldb::addr_t vm_addr, const void *buf,
757                                      size_t size, Status &error) {
758   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY);
759   llvm::sys::ScopedLock lock(m_mutex);
760   LLDB_LOG(log, "attempting to write {0} bytes into address {1:x}", size,
761            vm_addr);
762 
763   if (!m_session_data) {
764     LLDB_LOG(log, "cannot write, there is no active debugger connection.");
765     return 0;
766   }
767 
768   HostProcess process = m_session_data->m_debugger->GetProcess();
769   void *addr = reinterpret_cast<void *>(vm_addr);
770   SIZE_T bytes_written = 0;
771   lldb::process_t handle = process.GetNativeProcess().GetSystemHandle();
772   if (WriteProcessMemory(handle, addr, buf, size, &bytes_written))
773     FlushInstructionCache(handle, addr, bytes_written);
774   else {
775     error.SetError(GetLastError(), eErrorTypeWin32);
776     LLDB_LOG(log, "writing failed with error: {0}", error);
777   }
778   return bytes_written;
779 }
780 
781 lldb::addr_t ProcessWindows::DoAllocateMemory(size_t size, uint32_t permissions,
782                                               Status &error) {
783   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY);
784   llvm::sys::ScopedLock lock(m_mutex);
785   LLDB_LOG(log, "attempting to allocate {0} bytes with permissions {1}", size,
786            permissions);
787 
788   if (!m_session_data) {
789     LLDB_LOG(log, "cannot allocate, there is no active debugger connection.");
790     error.SetErrorString(
791         "cannot allocate, there is no active debugger connection");
792     return LLDB_INVALID_ADDRESS;
793   }
794 
795   HostProcess process = m_session_data->m_debugger->GetProcess();
796   lldb::process_t handle = process.GetNativeProcess().GetSystemHandle();
797   auto protect = ConvertLldbToWinApiProtect(permissions);
798   auto result = VirtualAllocEx(handle, nullptr, size, MEM_COMMIT, protect);
799   if (!result) {
800     error.SetError(GetLastError(), eErrorTypeWin32);
801     LLDB_LOG(log, "allocating failed with error: {0}", error);
802     return LLDB_INVALID_ADDRESS;
803   }
804 
805   return reinterpret_cast<addr_t>(result);
806 }
807 
808 Status ProcessWindows::DoDeallocateMemory(lldb::addr_t ptr) {
809   Status result;
810 
811   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY);
812   llvm::sys::ScopedLock lock(m_mutex);
813   LLDB_LOG(log, "attempting to deallocate bytes at address {0}", ptr);
814 
815   if (!m_session_data) {
816     LLDB_LOG(log, "cannot deallocate, there is no active debugger connection.");
817     result.SetErrorString(
818         "cannot deallocate, there is no active debugger connection");
819     return result;
820   }
821 
822   HostProcess process = m_session_data->m_debugger->GetProcess();
823   lldb::process_t handle = process.GetNativeProcess().GetSystemHandle();
824   if (!VirtualFreeEx(handle, reinterpret_cast<LPVOID>(ptr), 0, MEM_RELEASE)) {
825     result.SetError(GetLastError(), eErrorTypeWin32);
826     LLDB_LOG(log, "deallocating failed with error: {0}", result);
827     return result;
828   }
829 
830   return result;
831 }
832 
833 Status ProcessWindows::GetMemoryRegionInfo(lldb::addr_t vm_addr,
834                                            MemoryRegionInfo &info) {
835   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY);
836   Status error;
837   llvm::sys::ScopedLock lock(m_mutex);
838   info.Clear();
839 
840   if (!m_session_data) {
841     error.SetErrorString(
842         "GetMemoryRegionInfo called with no debugging session.");
843     LLDB_LOG(log, "error: {0}", error);
844     return error;
845   }
846   HostProcess process = m_session_data->m_debugger->GetProcess();
847   lldb::process_t handle = process.GetNativeProcess().GetSystemHandle();
848   if (handle == nullptr || handle == LLDB_INVALID_PROCESS) {
849     error.SetErrorString(
850         "GetMemoryRegionInfo called with an invalid target process.");
851     LLDB_LOG(log, "error: {0}", error);
852     return error;
853   }
854 
855   LLDB_LOG(log, "getting info for address {0:x}", vm_addr);
856 
857   void *addr = reinterpret_cast<void *>(vm_addr);
858   MEMORY_BASIC_INFORMATION mem_info = {};
859   SIZE_T result = ::VirtualQueryEx(handle, addr, &mem_info, sizeof(mem_info));
860   if (result == 0) {
861     if (::GetLastError() == ERROR_INVALID_PARAMETER) {
862       // ERROR_INVALID_PARAMETER is returned if VirtualQueryEx is called with
863       // an address past the highest accessible address. We should return a
864       // range from the vm_addr to LLDB_INVALID_ADDRESS
865       info.GetRange().SetRangeBase(vm_addr);
866       info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
867       info.SetReadable(MemoryRegionInfo::eNo);
868       info.SetExecutable(MemoryRegionInfo::eNo);
869       info.SetWritable(MemoryRegionInfo::eNo);
870       info.SetMapped(MemoryRegionInfo::eNo);
871       return error;
872     } else {
873       error.SetError(::GetLastError(), eErrorTypeWin32);
874       LLDB_LOG(log,
875                "VirtualQueryEx returned error {0} while getting memory "
876                "region info for address {1:x}",
877                error, vm_addr);
878       return error;
879     }
880   }
881 
882   // Protect bits are only valid for MEM_COMMIT regions.
883   if (mem_info.State == MEM_COMMIT) {
884     const bool readable = IsPageReadable(mem_info.Protect);
885     const bool executable = IsPageExecutable(mem_info.Protect);
886     const bool writable = IsPageWritable(mem_info.Protect);
887     info.SetReadable(readable ? MemoryRegionInfo::eYes : MemoryRegionInfo::eNo);
888     info.SetExecutable(executable ? MemoryRegionInfo::eYes
889                                   : MemoryRegionInfo::eNo);
890     info.SetWritable(writable ? MemoryRegionInfo::eYes : MemoryRegionInfo::eNo);
891   } else {
892     info.SetReadable(MemoryRegionInfo::eNo);
893     info.SetExecutable(MemoryRegionInfo::eNo);
894     info.SetWritable(MemoryRegionInfo::eNo);
895   }
896 
897   // AllocationBase is defined for MEM_COMMIT and MEM_RESERVE but not MEM_FREE.
898   if (mem_info.State != MEM_FREE) {
899     info.GetRange().SetRangeBase(
900         reinterpret_cast<addr_t>(mem_info.AllocationBase));
901     info.GetRange().SetRangeEnd(reinterpret_cast<addr_t>(mem_info.BaseAddress) +
902                                 mem_info.RegionSize);
903     info.SetMapped(MemoryRegionInfo::eYes);
904   } else {
905     // In the unmapped case we need to return the distance to the next block of
906     // memory. VirtualQueryEx nearly does that except that it gives the
907     // distance from the start of the page containing vm_addr.
908     SYSTEM_INFO data;
909     GetSystemInfo(&data);
910     DWORD page_offset = vm_addr % data.dwPageSize;
911     info.GetRange().SetRangeBase(vm_addr);
912     info.GetRange().SetByteSize(mem_info.RegionSize - page_offset);
913     info.SetMapped(MemoryRegionInfo::eNo);
914   }
915 
916   error.SetError(::GetLastError(), eErrorTypeWin32);
917   LLDB_LOGV(log,
918             "Memory region info for address {0}: readable={1}, "
919             "executable={2}, writable={3}",
920             vm_addr, info.GetReadable(), info.GetExecutable(),
921             info.GetWritable());
922   return error;
923 }
924 
925 lldb::addr_t ProcessWindows::GetImageInfoAddress() {
926   Target &target = GetTarget();
927   ObjectFile *obj_file = target.GetExecutableModule()->GetObjectFile();
928   Address addr = obj_file->GetImageInfoAddress(&target);
929   if (addr.IsValid())
930     return addr.GetLoadAddress(&target);
931   else
932     return LLDB_INVALID_ADDRESS;
933 }
934 
935 DynamicLoaderWindowsDYLD *ProcessWindows::GetDynamicLoader() {
936   if (m_dyld_up.get() == NULL)
937     m_dyld_up.reset(DynamicLoader::FindPlugin(
938         this, DynamicLoaderWindowsDYLD::GetPluginNameStatic().GetCString()));
939   return static_cast<DynamicLoaderWindowsDYLD *>(m_dyld_up.get());
940 }
941 
942 void ProcessWindows::OnExitProcess(uint32_t exit_code) {
943   // No need to acquire the lock since m_session_data isn't accessed.
944   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
945   LLDB_LOG(log, "Process {0} exited with code {1}", GetID(), exit_code);
946 
947   TargetSP target = CalculateTarget();
948   if (target) {
949     ModuleSP executable_module = target->GetExecutableModule();
950     ModuleList unloaded_modules;
951     unloaded_modules.Append(executable_module);
952     target->ModulesDidUnload(unloaded_modules, true);
953   }
954 
955   SetProcessExitStatus(GetID(), true, 0, exit_code);
956   SetPrivateState(eStateExited);
957 
958   // If the process exits before any initial stop then notify the debugger
959   // of the error otherwise WaitForDebuggerConnection() will be blocked.
960   // An example of this issue is when a process fails to load a dependent DLL.
961   if (m_session_data && !m_session_data->m_initial_stop_received) {
962     Status error(exit_code, eErrorTypeWin32);
963     OnDebuggerError(error, 0);
964   }
965 }
966 
967 void ProcessWindows::OnDebuggerConnected(lldb::addr_t image_base) {
968   DebuggerThreadSP debugger = m_session_data->m_debugger;
969   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
970   LLDB_LOG(log, "Debugger connected to process {0}.  Image base = {1:x}",
971            debugger->GetProcess().GetProcessId(), image_base);
972 
973   ModuleSP module = GetTarget().GetExecutableModule();
974   if (!module) {
975     // During attach, we won't have the executable module, so find it now.
976     const DWORD pid = debugger->GetProcess().GetProcessId();
977     const std::string file_name = GetProcessExecutableName(pid);
978     if (file_name.empty()) {
979       return;
980     }
981 
982     FileSpec executable_file(file_name);
983     FileSystem::Instance().Resolve(executable_file);
984     ModuleSpec module_spec(executable_file);
985     Status error;
986     module = GetTarget().GetOrCreateModule(module_spec,
987                                            true /* notify */, &error);
988     if (!module) {
989       return;
990     }
991 
992     GetTarget().SetExecutableModule(module, eLoadDependentsNo);
993   }
994 
995   if (auto dyld = GetDynamicLoader())
996     dyld->OnLoadModule(module, ModuleSpec(), image_base);
997 
998   // Add the main executable module to the list of pending module loads.  We
999   // can't call GetTarget().ModulesDidLoad() here because we still haven't
1000   // returned from DoLaunch() / DoAttach() yet so the target may not have set
1001   // the process instance to `this` yet.
1002   llvm::sys::ScopedLock lock(m_mutex);
1003   const HostThreadWindows &wmain_thread =
1004       debugger->GetMainThread().GetNativeThread();
1005   m_session_data->m_new_threads[wmain_thread.GetThreadId()] =
1006       debugger->GetMainThread();
1007 }
1008 
1009 ExceptionResult
1010 ProcessWindows::OnDebugException(bool first_chance,
1011                                  const ExceptionRecord &record) {
1012   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EXCEPTION);
1013   llvm::sys::ScopedLock lock(m_mutex);
1014 
1015   // FIXME: Without this check, occasionally when running the test suite there
1016   // is
1017   // an issue where m_session_data can be null.  It's not clear how this could
1018   // happen but it only surfaces while running the test suite.  In order to
1019   // properly diagnose this, we probably need to first figure allow the test
1020   // suite to print out full lldb logs, and then add logging to the process
1021   // plugin.
1022   if (!m_session_data) {
1023     LLDB_LOG(log,
1024              "Debugger thread reported exception {0:x} at address {1:x}, "
1025              "but there is no session.",
1026              record.GetExceptionCode(), record.GetExceptionAddress());
1027     return ExceptionResult::SendToApplication;
1028   }
1029 
1030   if (!first_chance) {
1031     // Not any second chance exception is an application crash by definition.
1032     // It may be an expression evaluation crash.
1033     SetPrivateState(eStateStopped);
1034   }
1035 
1036   ExceptionResult result = ExceptionResult::SendToApplication;
1037   switch (record.GetExceptionCode()) {
1038   case EXCEPTION_BREAKPOINT:
1039     // Handle breakpoints at the first chance.
1040     result = ExceptionResult::BreakInDebugger;
1041 
1042     if (!m_session_data->m_initial_stop_received) {
1043       LLDB_LOG(
1044           log,
1045           "Hit loader breakpoint at address {0:x}, setting initial stop event.",
1046           record.GetExceptionAddress());
1047       m_session_data->m_initial_stop_received = true;
1048       ::SetEvent(m_session_data->m_initial_stop_event);
1049     } else {
1050       LLDB_LOG(log, "Hit non-loader breakpoint at address {0:x}.",
1051                record.GetExceptionAddress());
1052     }
1053     SetPrivateState(eStateStopped);
1054     break;
1055   case EXCEPTION_SINGLE_STEP:
1056     result = ExceptionResult::BreakInDebugger;
1057     SetPrivateState(eStateStopped);
1058     break;
1059   default:
1060     LLDB_LOG(log,
1061              "Debugger thread reported exception {0:x} at address {1:x} "
1062              "(first_chance={2})",
1063              record.GetExceptionCode(), record.GetExceptionAddress(),
1064              first_chance);
1065     // For non-breakpoints, give the application a chance to handle the
1066     // exception first.
1067     if (first_chance)
1068       result = ExceptionResult::SendToApplication;
1069     else
1070       result = ExceptionResult::BreakInDebugger;
1071   }
1072 
1073   return result;
1074 }
1075 
1076 void ProcessWindows::OnCreateThread(const HostThread &new_thread) {
1077   llvm::sys::ScopedLock lock(m_mutex);
1078   const HostThreadWindows &wnew_thread = new_thread.GetNativeThread();
1079   m_session_data->m_new_threads[wnew_thread.GetThreadId()] = new_thread;
1080 }
1081 
1082 void ProcessWindows::OnExitThread(lldb::tid_t thread_id, uint32_t exit_code) {
1083   llvm::sys::ScopedLock lock(m_mutex);
1084 
1085   // On a forced termination, we may get exit thread events after the session
1086   // data has been cleaned up.
1087   if (!m_session_data)
1088     return;
1089 
1090   // A thread may have started and exited before the debugger stopped allowing a
1091   // refresh.
1092   // Just remove it from the new threads list in that case.
1093   auto iter = m_session_data->m_new_threads.find(thread_id);
1094   if (iter != m_session_data->m_new_threads.end())
1095     m_session_data->m_new_threads.erase(iter);
1096   else
1097     m_session_data->m_exited_threads.insert(thread_id);
1098 }
1099 
1100 void ProcessWindows::OnLoadDll(const ModuleSpec &module_spec,
1101                                lldb::addr_t module_addr) {
1102   if (auto dyld = GetDynamicLoader())
1103     dyld->OnLoadModule(nullptr, module_spec, module_addr);
1104 }
1105 
1106 void ProcessWindows::OnUnloadDll(lldb::addr_t module_addr) {
1107   if (auto dyld = GetDynamicLoader())
1108     dyld->OnUnloadModule(module_addr);
1109 }
1110 
1111 void ProcessWindows::OnDebugString(const std::string &string) {}
1112 
1113 void ProcessWindows::OnDebuggerError(const Status &error, uint32_t type) {
1114   llvm::sys::ScopedLock lock(m_mutex);
1115   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
1116 
1117   if (m_session_data->m_initial_stop_received) {
1118     // This happened while debugging.  Do we shutdown the debugging session,
1119     // try to continue, or do something else?
1120     LLDB_LOG(log,
1121              "Error {0} occurred during debugging.  Unexpected behavior "
1122              "may result.  {1}",
1123              error.GetError(), error);
1124   } else {
1125     // If we haven't actually launched the process yet, this was an error
1126     // launching the process.  Set the internal error and signal the initial
1127     // stop event so that the DoLaunch method wakes up and returns a failure.
1128     m_session_data->m_launch_error = error;
1129     ::SetEvent(m_session_data->m_initial_stop_event);
1130     LLDB_LOG(
1131         log,
1132         "Error {0} occurred launching the process before the initial stop. {1}",
1133         error.GetError(), error);
1134     return;
1135   }
1136 }
1137 
1138 Status ProcessWindows::WaitForDebuggerConnection(DebuggerThreadSP debugger,
1139                                                  HostProcess &process) {
1140   Status result;
1141   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS |
1142                                             WINDOWS_LOG_BREAKPOINTS);
1143   LLDB_LOG(log, "Waiting for loader breakpoint.");
1144 
1145   // Block this function until we receive the initial stop from the process.
1146   if (::WaitForSingleObject(m_session_data->m_initial_stop_event, INFINITE) ==
1147       WAIT_OBJECT_0) {
1148     LLDB_LOG(log, "hit loader breakpoint, returning.");
1149 
1150     process = debugger->GetProcess();
1151     return m_session_data->m_launch_error;
1152   } else
1153     return Status(::GetLastError(), eErrorTypeWin32);
1154 }
1155 
1156 // The Windows page protection bits are NOT independent masks that can be
1157 // bitwise-ORed together.  For example, PAGE_EXECUTE_READ is not (PAGE_EXECUTE
1158 // | PAGE_READ).  To test for an access type, it's necessary to test for any of
1159 // the bits that provide that access type.
1160 bool ProcessWindows::IsPageReadable(uint32_t protect) {
1161   return (protect & PAGE_NOACCESS) == 0;
1162 }
1163 
1164 bool ProcessWindows::IsPageWritable(uint32_t protect) {
1165   return (protect & (PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY |
1166                      PAGE_READWRITE | PAGE_WRITECOPY)) != 0;
1167 }
1168 
1169 bool ProcessWindows::IsPageExecutable(uint32_t protect) {
1170   return (protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE |
1171                      PAGE_EXECUTE_WRITECOPY)) != 0;
1172 }
1173 
1174 } // namespace lldb_private
1175