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