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