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