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