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