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