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