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   SetPrivateState(eStateLaunching);
253   DebugDelegateSP delegate(new LocalDebugDelegate(shared_from_this()));
254   m_session_data->m_debugger.reset(new DebuggerThread(delegate));
255   DebuggerThreadSP debugger = m_session_data->m_debugger;
256 
257   // Kick off the DebugLaunch asynchronously and wait for it to complete.
258   result = debugger->DebugLaunch(launch_info);
259   if (result.Fail()) {
260     LLDB_LOG(log, "failed launching '{0}'. {1}",
261              launch_info.GetExecutableFile().GetPath(), result);
262     return result;
263   }
264 
265   HostProcess process;
266   Status error = WaitForDebuggerConnection(debugger, process);
267   if (error.Fail()) {
268     LLDB_LOG(log, "failed launching '{0}'. {1}",
269              launch_info.GetExecutableFile().GetPath(), error);
270     return error;
271   }
272 
273   LLDB_LOG(log, "successfully launched '{0}'",
274            launch_info.GetExecutableFile().GetPath());
275 
276   // We've hit the initial stop.  If eLaunchFlagsStopAtEntry was specified, the
277   // private state should already be set to eStateStopped as a result of
278   // hitting the initial breakpoint.  If it was not set, the breakpoint should
279   // have already been resumed from and the private state should already be
280   // eStateRunning.
281   launch_info.SetProcessID(process.GetProcessId());
282   SetID(process.GetProcessId());
283 
284   return result;
285 }
286 
287 Status
288 ProcessWindows::DoAttachToProcessWithID(lldb::pid_t pid,
289                                         const ProcessAttachInfo &attach_info) {
290   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
291   m_session_data.reset(
292       new ProcessWindowsData(!attach_info.GetContinueOnceAttached()));
293 
294   DebugDelegateSP delegate(new LocalDebugDelegate(shared_from_this()));
295   DebuggerThreadSP debugger(new DebuggerThread(delegate));
296 
297   m_session_data->m_debugger = debugger;
298 
299   DWORD process_id = static_cast<DWORD>(pid);
300   Status error = debugger->DebugAttach(process_id, attach_info);
301   if (error.Fail()) {
302     LLDB_LOG(
303         log,
304         "encountered an error occurred initiating the asynchronous attach. {0}",
305         error);
306     return error;
307   }
308 
309   HostProcess process;
310   error = WaitForDebuggerConnection(debugger, process);
311   if (error.Fail()) {
312     LLDB_LOG(log,
313              "encountered an error waiting for the debugger to connect. {0}",
314              error);
315     return error;
316   }
317 
318   LLDB_LOG(log, "successfully attached to process with pid={0}", process_id);
319 
320   // We've hit the initial stop.  If eLaunchFlagsStopAtEntry was specified, the
321   // private state should already be set to eStateStopped as a result of
322   // hitting the initial breakpoint.  If it was not set, the breakpoint should
323   // have already been resumed from and the private state should already be
324   // eStateRunning.
325   SetID(process.GetProcessId());
326   return error;
327 }
328 
329 Status ProcessWindows::DoResume() {
330   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
331   llvm::sys::ScopedLock lock(m_mutex);
332   Status error;
333 
334   StateType private_state = GetPrivateState();
335   if (private_state == eStateStopped || private_state == eStateCrashed) {
336     LLDB_LOG(log, "process {0} is in state {1}.  Resuming...",
337              m_session_data->m_debugger->GetProcess().GetProcessId(),
338              GetPrivateState());
339 
340     ExceptionRecordSP active_exception =
341         m_session_data->m_debugger->GetActiveException().lock();
342     if (active_exception) {
343       // Resume the process and continue processing debug events.  Mask the
344       // exception so that from the process's view, there is no indication that
345       // anything happened.
346       m_session_data->m_debugger->ContinueAsyncException(
347           ExceptionResult::MaskException);
348     }
349 
350     LLDB_LOG(log, "resuming {0} threads.", m_thread_list.GetSize());
351 
352     bool failed = false;
353     for (uint32_t i = 0; i < m_thread_list.GetSize(); ++i) {
354       auto thread = std::static_pointer_cast<TargetThreadWindows>(
355           m_thread_list.GetThreadAtIndex(i));
356       Status result = thread->DoResume();
357       if (result.Fail()) {
358         failed = true;
359         LLDB_LOG(log, "Trying to resume thread at index {0}, but failed with error {1}.", i, result);
360       }
361     }
362 
363     if (failed) {
364       error.SetErrorString("ProcessWindows::DoResume failed");
365       return error;
366     } else {
367       SetPrivateState(eStateRunning);
368     }
369   } else {
370     LLDB_LOG(log, "error: process %I64u is in state %u.  Returning...",
371              m_session_data->m_debugger->GetProcess().GetProcessId(),
372              GetPrivateState());
373   }
374   return error;
375 }
376 
377 Status ProcessWindows::DoDestroy() {
378   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
379   DebuggerThreadSP debugger_thread;
380   StateType private_state;
381   {
382     // Acquire this lock inside an inner scope, only long enough to get the
383     // DebuggerThread. StopDebugging() will trigger a call back into
384     // ProcessWindows which will acquire the lock again, so we need to not
385     // deadlock.
386     llvm::sys::ScopedLock lock(m_mutex);
387 
388     private_state = GetPrivateState();
389 
390     if (!m_session_data) {
391       LLDB_LOG(log, "warning: state = {0}, but there is no active session.",
392                private_state);
393       return Status();
394     }
395 
396     debugger_thread = m_session_data->m_debugger;
397   }
398 
399   Status error;
400   if (private_state != eStateExited && private_state != eStateDetached) {
401     LLDB_LOG(log, "Shutting down process {0} while state = {1}.",
402              debugger_thread->GetProcess().GetNativeProcess().GetSystemHandle(),
403              private_state);
404     error = debugger_thread->StopDebugging(true);
405 
406     // By the time StopDebugging returns, there is no more debugger thread, so
407     // we can be assured that no other thread will race for the session data.
408     m_session_data.reset();
409   } else {
410     LLDB_LOG(log, "cannot destroy process {0} while state = {1}",
411              debugger_thread->GetProcess().GetNativeProcess().GetSystemHandle(),
412              private_state);
413   }
414 
415   return error;
416 }
417 
418 Status ProcessWindows::DoHalt(bool &caused_stop) {
419   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
420   Status error;
421   StateType state = GetPrivateState();
422   if (state == eStateStopped)
423     caused_stop = false;
424   else {
425     llvm::sys::ScopedLock lock(m_mutex);
426     caused_stop = ::DebugBreakProcess(m_session_data->m_debugger->GetProcess()
427                                           .GetNativeProcess()
428                                           .GetSystemHandle());
429     if (!caused_stop) {
430       error.SetError(::GetLastError(), eErrorTypeWin32);
431       LLDB_LOG(log, "DebugBreakProcess failed with error {0}", error);
432     }
433   }
434   return error;
435 }
436 
437 void ProcessWindows::DidLaunch() {
438   ArchSpec arch_spec;
439   DidAttach(arch_spec);
440 }
441 
442 void ProcessWindows::DidAttach(ArchSpec &arch_spec) {
443   llvm::sys::ScopedLock lock(m_mutex);
444 
445   // The initial stop won't broadcast the state change event, so account for
446   // that here.
447   if (m_session_data && GetPrivateState() == eStateStopped &&
448       m_session_data->m_stop_at_entry)
449     RefreshStateAfterStop();
450 }
451 
452 void ProcessWindows::RefreshStateAfterStop() {
453   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EXCEPTION);
454   llvm::sys::ScopedLock lock(m_mutex);
455 
456   if (!m_session_data) {
457     LLDB_LOG(log, "no active session.  Returning...");
458     return;
459   }
460 
461   m_thread_list.RefreshStateAfterStop();
462 
463   std::weak_ptr<ExceptionRecord> exception_record =
464       m_session_data->m_debugger->GetActiveException();
465   ExceptionRecordSP active_exception = exception_record.lock();
466   if (!active_exception) {
467     LLDB_LOG(log, "there is no active exception in process {0}.  Why is the "
468                   "process stopped?",
469              m_session_data->m_debugger->GetProcess().GetProcessId());
470     return;
471   }
472 
473   StopInfoSP stop_info;
474   m_thread_list.SetSelectedThreadByID(active_exception->GetThreadID());
475   ThreadSP stop_thread = m_thread_list.GetSelectedThread();
476   if (!stop_thread)
477     return;
478 
479   switch (active_exception->GetExceptionCode()) {
480   case EXCEPTION_SINGLE_STEP: {
481     RegisterContextSP register_context = stop_thread->GetRegisterContext();
482     const uint64_t pc = register_context->GetPC();
483     BreakpointSiteSP site(GetBreakpointSiteList().FindByAddress(pc));
484     if (site && site->ValidForThisThread(stop_thread.get())) {
485       LLDB_LOG(log, "Single-stepped onto a breakpoint in process {0} at "
486                     "address {1:x} with breakpoint site {2}",
487                m_session_data->m_debugger->GetProcess().GetProcessId(), pc,
488                site->GetID());
489       stop_info = StopInfo::CreateStopReasonWithBreakpointSiteID(*stop_thread,
490                                                                  site->GetID());
491       stop_thread->SetStopInfo(stop_info);
492     } else {
493       LLDB_LOG(log, "single stepping thread {0}", stop_thread->GetID());
494       stop_info = StopInfo::CreateStopReasonToTrace(*stop_thread);
495       stop_thread->SetStopInfo(stop_info);
496     }
497     return;
498   }
499 
500   case EXCEPTION_BREAKPOINT: {
501     RegisterContextSP register_context = stop_thread->GetRegisterContext();
502 
503     // The current EIP is AFTER the BP opcode, which is one byte.
504     uint64_t pc = register_context->GetPC() - 1;
505 
506     BreakpointSiteSP site(GetBreakpointSiteList().FindByAddress(pc));
507     if (site) {
508       LLDB_LOG(log, "detected breakpoint in process {0} at address {1:x} with "
509                     "breakpoint site {2}",
510                m_session_data->m_debugger->GetProcess().GetProcessId(), pc,
511                site->GetID());
512 
513       if (site->ValidForThisThread(stop_thread.get())) {
514         LLDB_LOG(log, "Breakpoint site {0} is valid for this thread ({1:x}), "
515                       "creating stop info.",
516                  site->GetID(), stop_thread->GetID());
517 
518         stop_info = StopInfo::CreateStopReasonWithBreakpointSiteID(
519             *stop_thread, site->GetID());
520         register_context->SetPC(pc);
521       } else {
522         LLDB_LOG(log, "Breakpoint site {0} is not valid for this thread, "
523                       "creating empty stop info.",
524                  site->GetID());
525       }
526       stop_thread->SetStopInfo(stop_info);
527       return;
528     } else {
529       // The thread hit a hard-coded breakpoint like an `int 3` or
530       // `__debugbreak()`.
531       LLDB_LOG(log,
532                "No breakpoint site matches for this thread. __debugbreak()?  "
533                "Creating stop info with the exception.");
534       // FALLTHROUGH:  We'll treat this as a generic exception record in the
535       // default case.
536     }
537   }
538 
539   default: {
540     std::string desc;
541     llvm::raw_string_ostream desc_stream(desc);
542     desc_stream << "Exception "
543                 << llvm::format_hex(active_exception->GetExceptionCode(), 8)
544                 << " encountered at address "
545                 << llvm::format_hex(active_exception->GetExceptionAddress(), 8);
546     stop_info = StopInfo::CreateStopReasonWithException(
547         *stop_thread, desc_stream.str().c_str());
548     stop_thread->SetStopInfo(stop_info);
549     LLDB_LOG(log, "{0}", desc_stream.str());
550     return;
551   }
552   }
553 }
554 
555 bool ProcessWindows::CanDebug(lldb::TargetSP target_sp,
556                               bool plugin_specified_by_name) {
557   if (plugin_specified_by_name)
558     return true;
559 
560   // For now we are just making sure the file exists for a given module
561   ModuleSP exe_module_sp(target_sp->GetExecutableModule());
562   if (exe_module_sp.get())
563     return exe_module_sp->GetFileSpec().Exists();
564   // However, if there is no executable module, we return true since we might
565   // be preparing to attach.
566   return true;
567 }
568 
569 bool ProcessWindows::UpdateThreadList(ThreadList &old_thread_list,
570                                       ThreadList &new_thread_list) {
571   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_THREAD);
572   // Add all the threads that were previously running and for which we did not
573   // detect a thread exited event.
574   int new_size = 0;
575   int continued_threads = 0;
576   int exited_threads = 0;
577   int new_threads = 0;
578 
579   for (ThreadSP old_thread : old_thread_list.Threads()) {
580     lldb::tid_t old_thread_id = old_thread->GetID();
581     auto exited_thread_iter =
582         m_session_data->m_exited_threads.find(old_thread_id);
583     if (exited_thread_iter == m_session_data->m_exited_threads.end()) {
584       new_thread_list.AddThread(old_thread);
585       ++new_size;
586       ++continued_threads;
587       LLDB_LOGV(log, "Thread {0} was running and is still running.",
588                 old_thread_id);
589     } else {
590       LLDB_LOGV(log, "Thread {0} was running and has exited.", old_thread_id);
591       ++exited_threads;
592     }
593   }
594 
595   // Also add all the threads that are new since the last time we broke into
596   // the debugger.
597   for (const auto &thread_info : m_session_data->m_new_threads) {
598     ThreadSP thread(new TargetThreadWindows(*this, thread_info.second));
599     thread->SetID(thread_info.first);
600     new_thread_list.AddThread(thread);
601     ++new_size;
602     ++new_threads;
603     LLDB_LOGV(log, "Thread {0} is new since last update.", thread_info.first);
604   }
605 
606   LLDB_LOG(log, "{0} new threads, {1} old threads, {2} exited threads.",
607            new_threads, continued_threads, exited_threads);
608 
609   m_session_data->m_new_threads.clear();
610   m_session_data->m_exited_threads.clear();
611 
612   return new_size > 0;
613 }
614 
615 bool ProcessWindows::IsAlive() {
616   StateType state = GetPrivateState();
617   switch (state) {
618   case eStateCrashed:
619   case eStateDetached:
620   case eStateUnloaded:
621   case eStateExited:
622   case eStateInvalid:
623     return false;
624   default:
625     return true;
626   }
627 }
628 
629 size_t ProcessWindows::DoReadMemory(lldb::addr_t vm_addr, void *buf,
630                                     size_t size, Status &error) {
631   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY);
632   llvm::sys::ScopedLock lock(m_mutex);
633 
634   if (!m_session_data)
635     return 0;
636 
637   LLDB_LOG(log, "attempting to read {0} bytes from address {1:x}", size,
638            vm_addr);
639 
640   HostProcess process = m_session_data->m_debugger->GetProcess();
641   void *addr = reinterpret_cast<void *>(vm_addr);
642   SIZE_T bytes_read = 0;
643   if (!ReadProcessMemory(process.GetNativeProcess().GetSystemHandle(), addr,
644                          buf, size, &bytes_read)) {
645     error.SetError(GetLastError(), eErrorTypeWin32);
646     LLDB_LOG(log, "reading failed with error: {0}", error);
647   }
648   return bytes_read;
649 }
650 
651 size_t ProcessWindows::DoWriteMemory(lldb::addr_t vm_addr, const void *buf,
652                                      size_t size, Status &error) {
653   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY);
654   llvm::sys::ScopedLock lock(m_mutex);
655   LLDB_LOG(log, "attempting to write {0} bytes into address {1:x}", size,
656            vm_addr);
657 
658   if (!m_session_data) {
659     LLDB_LOG(log, "cannot write, there is no active debugger connection.");
660     return 0;
661   }
662 
663   HostProcess process = m_session_data->m_debugger->GetProcess();
664   void *addr = reinterpret_cast<void *>(vm_addr);
665   SIZE_T bytes_written = 0;
666   lldb::process_t handle = process.GetNativeProcess().GetSystemHandle();
667   if (WriteProcessMemory(handle, addr, buf, size, &bytes_written))
668     FlushInstructionCache(handle, addr, bytes_written);
669   else {
670     error.SetError(GetLastError(), eErrorTypeWin32);
671     LLDB_LOG(log, "writing failed with error: {0}", error);
672   }
673   return bytes_written;
674 }
675 
676 Status ProcessWindows::GetMemoryRegionInfo(lldb::addr_t vm_addr,
677                                            MemoryRegionInfo &info) {
678   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_MEMORY);
679   Status error;
680   llvm::sys::ScopedLock lock(m_mutex);
681   info.Clear();
682 
683   if (!m_session_data) {
684     error.SetErrorString(
685         "GetMemoryRegionInfo called with no debugging session.");
686     LLDB_LOG(log, "error: {0}", error);
687     return error;
688   }
689   HostProcess process = m_session_data->m_debugger->GetProcess();
690   lldb::process_t handle = process.GetNativeProcess().GetSystemHandle();
691   if (handle == nullptr || handle == LLDB_INVALID_PROCESS) {
692     error.SetErrorString(
693         "GetMemoryRegionInfo called with an invalid target process.");
694     LLDB_LOG(log, "error: {0}", error);
695     return error;
696   }
697 
698   LLDB_LOG(log, "getting info for address {0:x}", vm_addr);
699 
700   void *addr = reinterpret_cast<void *>(vm_addr);
701   MEMORY_BASIC_INFORMATION mem_info = {};
702   SIZE_T result = ::VirtualQueryEx(handle, addr, &mem_info, sizeof(mem_info));
703   if (result == 0) {
704     if (::GetLastError() == ERROR_INVALID_PARAMETER) {
705       // ERROR_INVALID_PARAMETER is returned if VirtualQueryEx is called with
706       // an address past the highest accessible address. We should return a
707       // range from the vm_addr to LLDB_INVALID_ADDRESS
708       info.GetRange().SetRangeBase(vm_addr);
709       info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
710       info.SetReadable(MemoryRegionInfo::eNo);
711       info.SetExecutable(MemoryRegionInfo::eNo);
712       info.SetWritable(MemoryRegionInfo::eNo);
713       info.SetMapped(MemoryRegionInfo::eNo);
714       return error;
715     } else {
716       error.SetError(::GetLastError(), eErrorTypeWin32);
717       LLDB_LOG(log, "VirtualQueryEx returned error {0} while getting memory "
718                     "region info for address {1:x}",
719                error, vm_addr);
720       return error;
721     }
722   }
723 
724   // Protect bits are only valid for MEM_COMMIT regions.
725   if (mem_info.State == MEM_COMMIT) {
726     const bool readable = IsPageReadable(mem_info.Protect);
727     const bool executable = IsPageExecutable(mem_info.Protect);
728     const bool writable = IsPageWritable(mem_info.Protect);
729     info.SetReadable(readable ? MemoryRegionInfo::eYes : MemoryRegionInfo::eNo);
730     info.SetExecutable(executable ? MemoryRegionInfo::eYes
731                                   : MemoryRegionInfo::eNo);
732     info.SetWritable(writable ? MemoryRegionInfo::eYes : MemoryRegionInfo::eNo);
733   } else {
734     info.SetReadable(MemoryRegionInfo::eNo);
735     info.SetExecutable(MemoryRegionInfo::eNo);
736     info.SetWritable(MemoryRegionInfo::eNo);
737   }
738 
739   // AllocationBase is defined for MEM_COMMIT and MEM_RESERVE but not MEM_FREE.
740   if (mem_info.State != MEM_FREE) {
741     info.GetRange().SetRangeBase(
742         reinterpret_cast<addr_t>(mem_info.AllocationBase));
743     info.GetRange().SetRangeEnd(reinterpret_cast<addr_t>(mem_info.BaseAddress) +
744                                 mem_info.RegionSize);
745     info.SetMapped(MemoryRegionInfo::eYes);
746   } else {
747     // In the unmapped case we need to return the distance to the next block of
748     // memory. VirtualQueryEx nearly does that except that it gives the
749     // distance from the start of the page containing vm_addr.
750     SYSTEM_INFO data;
751     GetSystemInfo(&data);
752     DWORD page_offset = vm_addr % data.dwPageSize;
753     info.GetRange().SetRangeBase(vm_addr);
754     info.GetRange().SetByteSize(mem_info.RegionSize - page_offset);
755     info.SetMapped(MemoryRegionInfo::eNo);
756   }
757 
758   error.SetError(::GetLastError(), eErrorTypeWin32);
759   LLDB_LOGV(log, "Memory region info for address {0}: readable={1}, "
760                  "executable={2}, writable={3}",
761             vm_addr, info.GetReadable(), info.GetExecutable(),
762             info.GetWritable());
763   return error;
764 }
765 
766 lldb::addr_t ProcessWindows::GetImageInfoAddress() {
767   Target &target = GetTarget();
768   ObjectFile *obj_file = target.GetExecutableModule()->GetObjectFile();
769   Address addr = obj_file->GetImageInfoAddress(&target);
770   if (addr.IsValid())
771     return addr.GetLoadAddress(&target);
772   else
773     return LLDB_INVALID_ADDRESS;
774 }
775 
776 void ProcessWindows::OnExitProcess(uint32_t exit_code) {
777   // No need to acquire the lock since m_session_data isn't accessed.
778   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
779   LLDB_LOG(log, "Process {0} exited with code {1}", GetID(), exit_code);
780 
781   TargetSP target = m_target_sp.lock();
782   if (target) {
783     ModuleSP executable_module = target->GetExecutableModule();
784     ModuleList unloaded_modules;
785     unloaded_modules.Append(executable_module);
786     target->ModulesDidUnload(unloaded_modules, true);
787   }
788 
789   SetProcessExitStatus(GetID(), true, 0, exit_code);
790   SetPrivateState(eStateExited);
791 }
792 
793 void ProcessWindows::OnDebuggerConnected(lldb::addr_t image_base) {
794   DebuggerThreadSP debugger = m_session_data->m_debugger;
795   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
796   LLDB_LOG(log, "Debugger connected to process {0}.  Image base = {1:x}",
797            debugger->GetProcess().GetProcessId(), image_base);
798 
799   ModuleSP module = GetTarget().GetExecutableModule();
800   if (!module) {
801     // During attach, we won't have the executable module, so find it now.
802     const DWORD pid = debugger->GetProcess().GetProcessId();
803     const std::string file_name = GetProcessExecutableName(pid);
804     if (file_name.empty()) {
805       return;
806     }
807 
808     FileSpec executable_file(file_name, true);
809     ModuleSpec module_spec(executable_file);
810     Status error;
811     module = GetTarget().GetSharedModule(module_spec, &error);
812     if (!module) {
813       return;
814     }
815 
816     GetTarget().SetExecutableModule(module, false);
817   }
818 
819   bool load_addr_changed;
820   module->SetLoadAddress(GetTarget(), image_base, false, load_addr_changed);
821 
822   ModuleList loaded_modules;
823   loaded_modules.Append(module);
824   GetTarget().ModulesDidLoad(loaded_modules);
825 
826   // Add the main executable module to the list of pending module loads.  We
827   // can't call GetTarget().ModulesDidLoad() here because we still haven't
828   // returned from DoLaunch() / DoAttach() yet so the target may not have set
829   // the process instance to `this` yet.
830   llvm::sys::ScopedLock lock(m_mutex);
831   const HostThreadWindows &wmain_thread =
832       debugger->GetMainThread().GetNativeThread();
833   m_session_data->m_new_threads[wmain_thread.GetThreadId()] =
834       debugger->GetMainThread();
835 }
836 
837 ExceptionResult
838 ProcessWindows::OnDebugException(bool first_chance,
839                                  const ExceptionRecord &record) {
840   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EXCEPTION);
841   llvm::sys::ScopedLock lock(m_mutex);
842 
843   // FIXME: Without this check, occasionally when running the test suite there
844   // is
845   // an issue where m_session_data can be null.  It's not clear how this could
846   // happen but it only surfaces while running the test suite.  In order to
847   // properly diagnose this, we probably need to first figure allow the test
848   // suite to print out full lldb logs, and then add logging to the process
849   // plugin.
850   if (!m_session_data) {
851     LLDB_LOG(log, "Debugger thread reported exception {0:x} at address {1:x}, "
852                   "but there is no session.",
853              record.GetExceptionCode(), record.GetExceptionAddress());
854     return ExceptionResult::SendToApplication;
855   }
856 
857   if (!first_chance) {
858     // Any second chance exception is an application crash by definition.
859     SetPrivateState(eStateCrashed);
860   }
861 
862   ExceptionResult result = ExceptionResult::SendToApplication;
863   switch (record.GetExceptionCode()) {
864   case EXCEPTION_BREAKPOINT:
865     // Handle breakpoints at the first chance.
866     result = ExceptionResult::BreakInDebugger;
867 
868     if (!m_session_data->m_initial_stop_received) {
869       LLDB_LOG(
870           log,
871           "Hit loader breakpoint at address {0:x}, setting initial stop event.",
872           record.GetExceptionAddress());
873       m_session_data->m_initial_stop_received = true;
874       ::SetEvent(m_session_data->m_initial_stop_event);
875     } else {
876       LLDB_LOG(log, "Hit non-loader breakpoint at address {0:x}.",
877                record.GetExceptionAddress());
878     }
879     SetPrivateState(eStateStopped);
880     break;
881   case EXCEPTION_SINGLE_STEP:
882     result = ExceptionResult::BreakInDebugger;
883     SetPrivateState(eStateStopped);
884     break;
885   default:
886     LLDB_LOG(log, "Debugger thread reported exception {0:x} at address {1:x} "
887                   "(first_chance={2})",
888              record.GetExceptionCode(), record.GetExceptionAddress(),
889              first_chance);
890     // For non-breakpoints, give the application a chance to handle the
891     // exception first.
892     if (first_chance)
893       result = ExceptionResult::SendToApplication;
894     else
895       result = ExceptionResult::BreakInDebugger;
896   }
897 
898   return result;
899 }
900 
901 void ProcessWindows::OnCreateThread(const HostThread &new_thread) {
902   llvm::sys::ScopedLock lock(m_mutex);
903   const HostThreadWindows &wnew_thread = new_thread.GetNativeThread();
904   m_session_data->m_new_threads[wnew_thread.GetThreadId()] = new_thread;
905 }
906 
907 void ProcessWindows::OnExitThread(lldb::tid_t thread_id, uint32_t exit_code) {
908   llvm::sys::ScopedLock lock(m_mutex);
909 
910   // On a forced termination, we may get exit thread events after the session
911   // data has been cleaned up.
912   if (!m_session_data)
913     return;
914 
915   // A thread may have started and exited before the debugger stopped allowing a
916   // refresh.
917   // Just remove it from the new threads list in that case.
918   auto iter = m_session_data->m_new_threads.find(thread_id);
919   if (iter != m_session_data->m_new_threads.end())
920     m_session_data->m_new_threads.erase(iter);
921   else
922     m_session_data->m_exited_threads.insert(thread_id);
923 }
924 
925 void ProcessWindows::OnLoadDll(const ModuleSpec &module_spec,
926                                lldb::addr_t module_addr) {
927   // Confusingly, there is no Target::AddSharedModule.  Instead, calling
928   // GetSharedModule() with a new module will add it to the module list and
929   // return a corresponding ModuleSP.
930   Status error;
931   ModuleSP module = GetTarget().GetSharedModule(module_spec, &error);
932   bool load_addr_changed = false;
933   module->SetLoadAddress(GetTarget(), module_addr, false, load_addr_changed);
934 
935   ModuleList loaded_modules;
936   loaded_modules.Append(module);
937   GetTarget().ModulesDidLoad(loaded_modules);
938 }
939 
940 void ProcessWindows::OnUnloadDll(lldb::addr_t module_addr) {
941   Address resolved_addr;
942   if (GetTarget().ResolveLoadAddress(module_addr, resolved_addr)) {
943     ModuleSP module = resolved_addr.GetModule();
944     if (module) {
945       ModuleList unloaded_modules;
946       unloaded_modules.Append(module);
947       GetTarget().ModulesDidUnload(unloaded_modules, false);
948     }
949   }
950 }
951 
952 void ProcessWindows::OnDebugString(const std::string &string) {}
953 
954 void ProcessWindows::OnDebuggerError(const Status &error, uint32_t type) {
955   llvm::sys::ScopedLock lock(m_mutex);
956   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
957 
958   if (m_session_data->m_initial_stop_received) {
959     // This happened while debugging.  Do we shutdown the debugging session,
960     // try to continue, or do something else?
961     LLDB_LOG(log, "Error {0} occurred during debugging.  Unexpected behavior "
962                   "may result.  {1}",
963              error.GetError(), error);
964   } else {
965     // If we haven't actually launched the process yet, this was an error
966     // launching the process.  Set the internal error and signal the initial
967     // stop event so that the DoLaunch method wakes up and returns a failure.
968     m_session_data->m_launch_error = error;
969     ::SetEvent(m_session_data->m_initial_stop_event);
970     LLDB_LOG(
971         log,
972         "Error {0} occurred launching the process before the initial stop. {1}",
973         error.GetError(), error);
974     return;
975   }
976 }
977 
978 Status ProcessWindows::WaitForDebuggerConnection(DebuggerThreadSP debugger,
979                                                  HostProcess &process) {
980   Status result;
981   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS |
982                                             WINDOWS_LOG_BREAKPOINTS);
983   LLDB_LOG(log, "Waiting for loader breakpoint.");
984 
985   // Block this function until we receive the initial stop from the process.
986   if (::WaitForSingleObject(m_session_data->m_initial_stop_event, INFINITE) ==
987       WAIT_OBJECT_0) {
988     LLDB_LOG(log, "hit loader breakpoint, returning.");
989 
990     process = debugger->GetProcess();
991     return m_session_data->m_launch_error;
992   } else
993     return Status(::GetLastError(), eErrorTypeWin32);
994 }
995 
996 // The Windows page protection bits are NOT independent masks that can be
997 // bitwise-ORed together.  For example, PAGE_EXECUTE_READ is not (PAGE_EXECUTE
998 // | PAGE_READ).  To test for an access type, it's necessary to test for any of
999 // the bits that provide that access type.
1000 bool ProcessWindows::IsPageReadable(uint32_t protect) {
1001   return (protect & PAGE_NOACCESS) == 0;
1002 }
1003 
1004 bool ProcessWindows::IsPageWritable(uint32_t protect) {
1005   return (protect & (PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY |
1006                      PAGE_READWRITE | PAGE_WRITECOPY)) != 0;
1007 }
1008 
1009 bool ProcessWindows::IsPageExecutable(uint32_t protect) {
1010   return (protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE |
1011                      PAGE_EXECUTE_WRITECOPY)) != 0;
1012 }
1013 
1014 } // namespace lldb_private
1015