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