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