1 //===-- ProcessWindows.cpp ------------------------------------------------===//
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/Breakpoint/Watchpoint.h"
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 LLDB_PLUGIN_DEFINE_ADV(ProcessWindows, ProcessWindowsCommon)
48 
49 namespace {
50 std::string GetProcessExecutableName(HANDLE process_handle) {
51   std::vector<wchar_t> file_name;
52   DWORD file_name_size = MAX_PATH; // first guess, not an absolute limit
53   DWORD copied = 0;
54   do {
55     file_name_size *= 2;
56     file_name.resize(file_name_size);
57     copied = ::GetModuleFileNameExW(process_handle, NULL, file_name.data(),
58                                     file_name_size);
59   } while (copied >= file_name_size);
60   file_name.resize(copied);
61   std::string result;
62   llvm::convertWideToUTF8(file_name.data(), result);
63   return result;
64 }
65 
66 std::string GetProcessExecutableName(DWORD pid) {
67   std::string file_name;
68   HANDLE process_handle =
69       ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
70   if (process_handle != NULL) {
71     file_name = GetProcessExecutableName(process_handle);
72     ::CloseHandle(process_handle);
73   }
74   return file_name;
75 }
76 } // anonymous namespace
77 
78 namespace lldb_private {
79 
80 ProcessSP ProcessWindows::CreateInstance(lldb::TargetSP target_sp,
81                                          lldb::ListenerSP listener_sp,
82                                          const FileSpec *,
83                                          bool can_connect) {
84   return ProcessSP(new ProcessWindows(target_sp, listener_sp));
85 }
86 
87 static bool ShouldUseLLDBServer() {
88   llvm::StringRef use_lldb_server = ::getenv("LLDB_USE_LLDB_SERVER");
89   return use_lldb_server.equals_insensitive("on") ||
90          use_lldb_server.equals_insensitive("yes") ||
91          use_lldb_server.equals_insensitive("1") ||
92          use_lldb_server.equals_insensitive("true");
93 }
94 
95 void ProcessWindows::Initialize() {
96   if (!ShouldUseLLDBServer()) {
97     static llvm::once_flag g_once_flag;
98 
99     llvm::call_once(g_once_flag, []() {
100       PluginManager::RegisterPlugin(GetPluginNameStatic(),
101                                     GetPluginDescriptionStatic(),
102                                     CreateInstance);
103     });
104   }
105 }
106 
107 void ProcessWindows::Terminate() {}
108 
109 lldb_private::ConstString ProcessWindows::GetPluginNameStatic() {
110   static ConstString g_name("windows");
111   return g_name;
112 }
113 
114 const char *ProcessWindows::GetPluginDescriptionStatic() {
115   return "Process plugin for Windows";
116 }
117 
118 // Constructors and destructors.
119 
120 ProcessWindows::ProcessWindows(lldb::TargetSP target_sp,
121                                lldb::ListenerSP listener_sp)
122     : lldb_private::Process(target_sp, listener_sp),
123       m_watchpoint_ids(
124           RegisterContextWindows::GetNumHardwareBreakpointSlots(),
125           LLDB_INVALID_BREAK_ID) {}
126 
127 ProcessWindows::~ProcessWindows() {}
128 
129 size_t ProcessWindows::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
130   error.SetErrorString("GetSTDOUT unsupported on Windows");
131   return 0;
132 }
133 
134 size_t ProcessWindows::GetSTDERR(char *buf, size_t buf_size, Status &error) {
135   error.SetErrorString("GetSTDERR unsupported on Windows");
136   return 0;
137 }
138 
139 size_t ProcessWindows::PutSTDIN(const char *buf, size_t buf_size,
140                                 Status &error) {
141   error.SetErrorString("PutSTDIN unsupported on Windows");
142   return 0;
143 }
144 
145 // ProcessInterface protocol.
146 
147 lldb_private::ConstString ProcessWindows::GetPluginName() {
148   return GetPluginNameStatic();
149 }
150 
151 Status ProcessWindows::EnableBreakpointSite(BreakpointSite *bp_site) {
152   if (bp_site->HardwareRequired())
153     return Status("Hardware breakpoints are not supported.");
154 
155   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_BREAKPOINTS);
156   LLDB_LOG(log, "bp_site = {0:x}, id={1}, addr={2:x}", bp_site,
157            bp_site->GetID(), bp_site->GetLoadAddress());
158 
159   Status error = EnableSoftwareBreakpoint(bp_site);
160   if (!error.Success())
161     LLDB_LOG(log, "error: {0}", error);
162   return error;
163 }
164 
165 Status ProcessWindows::DisableBreakpointSite(BreakpointSite *bp_site) {
166   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_BREAKPOINTS);
167   LLDB_LOG(log, "bp_site = {0:x}, id={1}, addr={2:x}", bp_site,
168            bp_site->GetID(), bp_site->GetLoadAddress());
169 
170   Status error = DisableSoftwareBreakpoint(bp_site);
171 
172   if (!error.Success())
173     LLDB_LOG(log, "error: {0}", error);
174   return error;
175 }
176 
177 Status ProcessWindows::DoDetach(bool keep_stopped) {
178   Status error;
179   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
180   StateType private_state = GetPrivateState();
181   if (private_state != eStateExited && private_state != eStateDetached) {
182     error = DetachProcess();
183     if (error.Success())
184       SetPrivateState(eStateDetached);
185     else
186       LLDB_LOG(log, "Detaching process error: {0}", error);
187   } else {
188     error.SetErrorStringWithFormatv("error: process {0} in state = {1}, but "
189                                     "cannot detach it in this state.",
190                                     GetID(), private_state);
191     LLDB_LOG(log, "error: {0}", error);
192   }
193   return error;
194 }
195 
196 Status ProcessWindows::DoLaunch(Module *exe_module,
197                                 ProcessLaunchInfo &launch_info) {
198   Status error;
199   DebugDelegateSP delegate(new LocalDebugDelegate(shared_from_this()));
200   error = LaunchProcess(launch_info, delegate);
201   if (error.Success())
202     SetID(launch_info.GetProcessID());
203   return error;
204 }
205 
206 Status
207 ProcessWindows::DoAttachToProcessWithID(lldb::pid_t pid,
208                                         const ProcessAttachInfo &attach_info) {
209   DebugDelegateSP delegate(new LocalDebugDelegate(shared_from_this()));
210   Status error = AttachProcess(pid, attach_info, delegate);
211   if (error.Success())
212     SetID(GetDebuggedProcessId());
213   return error;
214 }
215 
216 Status ProcessWindows::DoResume() {
217   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
218   llvm::sys::ScopedLock lock(m_mutex);
219   Status error;
220 
221   StateType private_state = GetPrivateState();
222   if (private_state == eStateStopped || private_state == eStateCrashed) {
223     LLDB_LOG(log, "process {0} is in state {1}.  Resuming...",
224              m_session_data->m_debugger->GetProcess().GetProcessId(),
225              GetPrivateState());
226 
227     LLDB_LOG(log, "resuming {0} threads.", m_thread_list.GetSize());
228 
229     bool failed = false;
230     for (uint32_t i = 0; i < m_thread_list.GetSize(); ++i) {
231       auto thread = std::static_pointer_cast<TargetThreadWindows>(
232           m_thread_list.GetThreadAtIndex(i));
233       Status result = thread->DoResume();
234       if (result.Fail()) {
235         failed = true;
236         LLDB_LOG(
237             log,
238             "Trying to resume thread at index {0}, but failed with error {1}.",
239             i, result);
240       }
241     }
242 
243     if (failed) {
244       error.SetErrorString("ProcessWindows::DoResume failed");
245     } else {
246       SetPrivateState(eStateRunning);
247     }
248 
249     ExceptionRecordSP active_exception =
250         m_session_data->m_debugger->GetActiveException().lock();
251     if (active_exception) {
252       // Resume the process and continue processing debug events.  Mask the
253       // exception so that from the process's view, there is no indication that
254       // anything happened.
255       m_session_data->m_debugger->ContinueAsyncException(
256           ExceptionResult::MaskException);
257     }
258   } else {
259     LLDB_LOG(log, "error: process {0} is in state {1}.  Returning...",
260              m_session_data->m_debugger->GetProcess().GetProcessId(),
261              GetPrivateState());
262   }
263   return error;
264 }
265 
266 Status ProcessWindows::DoDestroy() {
267   StateType private_state = GetPrivateState();
268   return DestroyProcess(private_state);
269 }
270 
271 Status ProcessWindows::DoHalt(bool &caused_stop) {
272   StateType state = GetPrivateState();
273   if (state != eStateStopped)
274     return HaltProcess(caused_stop);
275   caused_stop = false;
276   return Status();
277 }
278 
279 void ProcessWindows::DidLaunch() {
280   ArchSpec arch_spec;
281   DidAttach(arch_spec);
282 }
283 
284 void ProcessWindows::DidAttach(ArchSpec &arch_spec) {
285   llvm::sys::ScopedLock lock(m_mutex);
286 
287   // The initial stop won't broadcast the state change event, so account for
288   // that here.
289   if (m_session_data && GetPrivateState() == eStateStopped &&
290       m_session_data->m_stop_at_entry)
291     RefreshStateAfterStop();
292 }
293 
294 static void
295 DumpAdditionalExceptionInformation(llvm::raw_ostream &stream,
296                                    const ExceptionRecordSP &exception) {
297   // Decode additional exception information for specific exception types based
298   // on
299   // https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_exception_record
300 
301   const int addr_min_width = 2 + 8; // "0x" + 4 address bytes
302 
303   const std::vector<ULONG_PTR> &args = exception->GetExceptionArguments();
304   switch (exception->GetExceptionCode()) {
305   case EXCEPTION_ACCESS_VIOLATION: {
306     if (args.size() < 2)
307       break;
308 
309     stream << ": ";
310     const int access_violation_code = args[0];
311     const lldb::addr_t access_violation_address = args[1];
312     switch (access_violation_code) {
313     case 0:
314       stream << "Access violation reading";
315       break;
316     case 1:
317       stream << "Access violation writing";
318       break;
319     case 8:
320       stream << "User-mode data execution prevention (DEP) violation at";
321       break;
322     default:
323       stream << "Unknown access violation (code " << access_violation_code
324              << ") at";
325       break;
326     }
327     stream << " location "
328            << llvm::format_hex(access_violation_address, addr_min_width);
329     break;
330   }
331   case EXCEPTION_IN_PAGE_ERROR: {
332     if (args.size() < 3)
333       break;
334 
335     stream << ": ";
336     const int page_load_error_code = args[0];
337     const lldb::addr_t page_load_error_address = args[1];
338     const DWORD underlying_code = args[2];
339     switch (page_load_error_code) {
340     case 0:
341       stream << "In page error reading";
342       break;
343     case 1:
344       stream << "In page error writing";
345       break;
346     case 8:
347       stream << "User-mode data execution prevention (DEP) violation at";
348       break;
349     default:
350       stream << "Unknown page loading error (code " << page_load_error_code
351              << ") at";
352       break;
353     }
354     stream << " location "
355            << llvm::format_hex(page_load_error_address, addr_min_width)
356            << " (status code " << llvm::format_hex(underlying_code, 8) << ")";
357     break;
358   }
359   }
360 }
361 
362 void ProcessWindows::RefreshStateAfterStop() {
363   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EXCEPTION);
364   llvm::sys::ScopedLock lock(m_mutex);
365 
366   if (!m_session_data) {
367     LLDB_LOG(log, "no active session.  Returning...");
368     return;
369   }
370 
371   m_thread_list.RefreshStateAfterStop();
372 
373   std::weak_ptr<ExceptionRecord> exception_record =
374       m_session_data->m_debugger->GetActiveException();
375   ExceptionRecordSP active_exception = exception_record.lock();
376   if (!active_exception) {
377     LLDB_LOG(log,
378              "there is no active exception in process {0}.  Why is the "
379              "process stopped?",
380              m_session_data->m_debugger->GetProcess().GetProcessId());
381     return;
382   }
383 
384   StopInfoSP stop_info;
385   m_thread_list.SetSelectedThreadByID(active_exception->GetThreadID());
386   ThreadSP stop_thread = m_thread_list.GetSelectedThread();
387   if (!stop_thread)
388     return;
389 
390   switch (active_exception->GetExceptionCode()) {
391   case EXCEPTION_SINGLE_STEP: {
392     RegisterContextSP register_context = stop_thread->GetRegisterContext();
393     const uint64_t pc = register_context->GetPC();
394     BreakpointSiteSP site(GetBreakpointSiteList().FindByAddress(pc));
395     if (site && site->ValidForThisThread(*stop_thread)) {
396       LLDB_LOG(log,
397                "Single-stepped onto a breakpoint in process {0} at "
398                "address {1:x} with breakpoint site {2}",
399                m_session_data->m_debugger->GetProcess().GetProcessId(), pc,
400                site->GetID());
401       stop_info = StopInfo::CreateStopReasonWithBreakpointSiteID(*stop_thread,
402                                                                  site->GetID());
403       stop_thread->SetStopInfo(stop_info);
404 
405       return;
406     }
407 
408     auto *reg_ctx = static_cast<RegisterContextWindows *>(
409         stop_thread->GetRegisterContext().get());
410     uint32_t slot_id = reg_ctx->GetTriggeredHardwareBreakpointSlotId();
411     if (slot_id != LLDB_INVALID_INDEX32) {
412       int id = m_watchpoint_ids[slot_id];
413       LLDB_LOG(log,
414                "Single-stepped onto a watchpoint in process {0} at address "
415                "{1:x} with watchpoint {2}",
416                m_session_data->m_debugger->GetProcess().GetProcessId(), pc, id);
417 
418       if (lldb::WatchpointSP wp_sp =
419               GetTarget().GetWatchpointList().FindByID(id))
420         wp_sp->SetHardwareIndex(slot_id);
421 
422       stop_info = StopInfo::CreateStopReasonWithWatchpointID(
423           *stop_thread, id, m_watchpoints[id].address);
424       stop_thread->SetStopInfo(stop_info);
425 
426       return;
427     }
428 
429     LLDB_LOG(log, "single stepping thread {0}", stop_thread->GetID());
430     stop_info = StopInfo::CreateStopReasonToTrace(*stop_thread);
431     stop_thread->SetStopInfo(stop_info);
432 
433     return;
434   }
435 
436   case EXCEPTION_BREAKPOINT: {
437     RegisterContextSP register_context = stop_thread->GetRegisterContext();
438 
439     // The current EIP is AFTER the BP opcode, which is one byte.
440     uint64_t pc = register_context->GetPC() - 1;
441 
442     BreakpointSiteSP site(GetBreakpointSiteList().FindByAddress(pc));
443     if (site) {
444       LLDB_LOG(log,
445                "detected breakpoint in process {0} at address {1:x} with "
446                "breakpoint site {2}",
447                m_session_data->m_debugger->GetProcess().GetProcessId(), pc,
448                site->GetID());
449 
450       if (site->ValidForThisThread(*stop_thread)) {
451         LLDB_LOG(log,
452                  "Breakpoint site {0} is valid for this thread ({1:x}), "
453                  "creating stop info.",
454                  site->GetID(), stop_thread->GetID());
455 
456         stop_info = StopInfo::CreateStopReasonWithBreakpointSiteID(
457             *stop_thread, site->GetID());
458         register_context->SetPC(pc);
459       } else {
460         LLDB_LOG(log,
461                  "Breakpoint site {0} is not valid for this thread, "
462                  "creating empty stop info.",
463                  site->GetID());
464       }
465       stop_thread->SetStopInfo(stop_info);
466       return;
467     } else {
468       // The thread hit a hard-coded breakpoint like an `int 3` or
469       // `__debugbreak()`.
470       LLDB_LOG(log,
471                "No breakpoint site matches for this thread. __debugbreak()?  "
472                "Creating stop info with the exception.");
473       // FALLTHROUGH:  We'll treat this as a generic exception record in the
474       // default case.
475       LLVM_FALLTHROUGH;
476     }
477   }
478 
479   default: {
480     std::string desc;
481     llvm::raw_string_ostream desc_stream(desc);
482     desc_stream << "Exception "
483                 << llvm::format_hex(active_exception->GetExceptionCode(), 8)
484                 << " encountered at address "
485                 << llvm::format_hex(active_exception->GetExceptionAddress(), 8);
486     DumpAdditionalExceptionInformation(desc_stream, active_exception);
487 
488     stop_info = StopInfo::CreateStopReasonWithException(
489         *stop_thread, desc_stream.str().c_str());
490     stop_thread->SetStopInfo(stop_info);
491     LLDB_LOG(log, "{0}", desc_stream.str());
492     return;
493   }
494   }
495 }
496 
497 bool ProcessWindows::CanDebug(lldb::TargetSP target_sp,
498                               bool plugin_specified_by_name) {
499   if (plugin_specified_by_name)
500     return true;
501 
502   // For now we are just making sure the file exists for a given module
503   ModuleSP exe_module_sp(target_sp->GetExecutableModule());
504   if (exe_module_sp.get())
505     return FileSystem::Instance().Exists(exe_module_sp->GetFileSpec());
506   // However, if there is no executable module, we return true since we might
507   // be preparing to attach.
508   return true;
509 }
510 
511 bool ProcessWindows::DoUpdateThreadList(ThreadList &old_thread_list,
512                                         ThreadList &new_thread_list) {
513   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_THREAD);
514   // Add all the threads that were previously running and for which we did not
515   // detect a thread exited event.
516   int new_size = 0;
517   int continued_threads = 0;
518   int exited_threads = 0;
519   int new_threads = 0;
520 
521   for (ThreadSP old_thread : old_thread_list.Threads()) {
522     lldb::tid_t old_thread_id = old_thread->GetID();
523     auto exited_thread_iter =
524         m_session_data->m_exited_threads.find(old_thread_id);
525     if (exited_thread_iter == m_session_data->m_exited_threads.end()) {
526       new_thread_list.AddThread(old_thread);
527       ++new_size;
528       ++continued_threads;
529       LLDB_LOGV(log, "Thread {0} was running and is still running.",
530                 old_thread_id);
531     } else {
532       LLDB_LOGV(log, "Thread {0} was running and has exited.", old_thread_id);
533       ++exited_threads;
534     }
535   }
536 
537   // Also add all the threads that are new since the last time we broke into
538   // the debugger.
539   for (const auto &thread_info : m_session_data->m_new_threads) {
540     new_thread_list.AddThread(thread_info.second);
541     ++new_size;
542     ++new_threads;
543     LLDB_LOGV(log, "Thread {0} is new since last update.", thread_info.first);
544   }
545 
546   LLDB_LOG(log, "{0} new threads, {1} old threads, {2} exited threads.",
547            new_threads, continued_threads, exited_threads);
548 
549   m_session_data->m_new_threads.clear();
550   m_session_data->m_exited_threads.clear();
551 
552   return new_size > 0;
553 }
554 
555 bool ProcessWindows::IsAlive() {
556   StateType state = GetPrivateState();
557   switch (state) {
558   case eStateCrashed:
559   case eStateDetached:
560   case eStateUnloaded:
561   case eStateExited:
562   case eStateInvalid:
563     return false;
564   default:
565     return true;
566   }
567 }
568 
569 size_t ProcessWindows::DoReadMemory(lldb::addr_t vm_addr, void *buf,
570                                     size_t size, Status &error) {
571   size_t bytes_read = 0;
572   error = ProcessDebugger::ReadMemory(vm_addr, buf, size, bytes_read);
573   return bytes_read;
574 }
575 
576 size_t ProcessWindows::DoWriteMemory(lldb::addr_t vm_addr, const void *buf,
577                                      size_t size, Status &error) {
578   size_t bytes_written = 0;
579   error = ProcessDebugger::WriteMemory(vm_addr, buf, size, bytes_written);
580   return bytes_written;
581 }
582 
583 lldb::addr_t ProcessWindows::DoAllocateMemory(size_t size, uint32_t permissions,
584                                               Status &error) {
585   lldb::addr_t vm_addr = LLDB_INVALID_ADDRESS;
586   error = ProcessDebugger::AllocateMemory(size, permissions, vm_addr);
587   return vm_addr;
588 }
589 
590 Status ProcessWindows::DoDeallocateMemory(lldb::addr_t ptr) {
591   return ProcessDebugger::DeallocateMemory(ptr);
592 }
593 
594 Status ProcessWindows::GetMemoryRegionInfo(lldb::addr_t vm_addr,
595                                            MemoryRegionInfo &info) {
596   return ProcessDebugger::GetMemoryRegionInfo(vm_addr, info);
597 }
598 
599 lldb::addr_t ProcessWindows::GetImageInfoAddress() {
600   Target &target = GetTarget();
601   ObjectFile *obj_file = target.GetExecutableModule()->GetObjectFile();
602   Address addr = obj_file->GetImageInfoAddress(&target);
603   if (addr.IsValid())
604     return addr.GetLoadAddress(&target);
605   else
606     return LLDB_INVALID_ADDRESS;
607 }
608 
609 DynamicLoaderWindowsDYLD *ProcessWindows::GetDynamicLoader() {
610   if (m_dyld_up.get() == NULL)
611     m_dyld_up.reset(DynamicLoader::FindPlugin(
612         this, DynamicLoaderWindowsDYLD::GetPluginNameStatic().GetCString()));
613   return static_cast<DynamicLoaderWindowsDYLD *>(m_dyld_up.get());
614 }
615 
616 void ProcessWindows::OnExitProcess(uint32_t exit_code) {
617   // No need to acquire the lock since m_session_data isn't accessed.
618   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
619   LLDB_LOG(log, "Process {0} exited with code {1}", GetID(), exit_code);
620 
621   TargetSP target = CalculateTarget();
622   if (target) {
623     ModuleSP executable_module = target->GetExecutableModule();
624     ModuleList unloaded_modules;
625     unloaded_modules.Append(executable_module);
626     target->ModulesDidUnload(unloaded_modules, true);
627   }
628 
629   SetProcessExitStatus(GetID(), true, 0, exit_code);
630   SetPrivateState(eStateExited);
631 
632   ProcessDebugger::OnExitProcess(exit_code);
633 }
634 
635 void ProcessWindows::OnDebuggerConnected(lldb::addr_t image_base) {
636   DebuggerThreadSP debugger = m_session_data->m_debugger;
637   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
638   LLDB_LOG(log, "Debugger connected to process {0}.  Image base = {1:x}",
639            debugger->GetProcess().GetProcessId(), image_base);
640 
641   ModuleSP module = GetTarget().GetExecutableModule();
642   if (!module) {
643     // During attach, we won't have the executable module, so find it now.
644     const DWORD pid = debugger->GetProcess().GetProcessId();
645     const std::string file_name = GetProcessExecutableName(pid);
646     if (file_name.empty()) {
647       return;
648     }
649 
650     FileSpec executable_file(file_name);
651     FileSystem::Instance().Resolve(executable_file);
652     ModuleSpec module_spec(executable_file);
653     Status error;
654     module =
655         GetTarget().GetOrCreateModule(module_spec, true /* notify */, &error);
656     if (!module) {
657       return;
658     }
659 
660     GetTarget().SetExecutableModule(module, eLoadDependentsNo);
661   }
662 
663   if (auto dyld = GetDynamicLoader())
664     dyld->OnLoadModule(module, ModuleSpec(), image_base);
665 
666   // Add the main executable module to the list of pending module loads.  We
667   // can't call GetTarget().ModulesDidLoad() here because we still haven't
668   // returned from DoLaunch() / DoAttach() yet so the target may not have set
669   // the process instance to `this` yet.
670   llvm::sys::ScopedLock lock(m_mutex);
671 
672   const HostThread &host_main_thread = debugger->GetMainThread();
673   ThreadSP main_thread =
674       std::make_shared<TargetThreadWindows>(*this, host_main_thread);
675 
676   tid_t id = host_main_thread.GetNativeThread().GetThreadId();
677   main_thread->SetID(id);
678 
679   m_session_data->m_new_threads[id] = main_thread;
680 }
681 
682 ExceptionResult
683 ProcessWindows::OnDebugException(bool first_chance,
684                                  const ExceptionRecord &record) {
685   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EXCEPTION);
686   llvm::sys::ScopedLock lock(m_mutex);
687 
688   // FIXME: Without this check, occasionally when running the test suite there
689   // is
690   // an issue where m_session_data can be null.  It's not clear how this could
691   // happen but it only surfaces while running the test suite.  In order to
692   // properly diagnose this, we probably need to first figure allow the test
693   // suite to print out full lldb logs, and then add logging to the process
694   // plugin.
695   if (!m_session_data) {
696     LLDB_LOG(log,
697              "Debugger thread reported exception {0:x} at address {1:x}, "
698              "but there is no session.",
699              record.GetExceptionCode(), record.GetExceptionAddress());
700     return ExceptionResult::SendToApplication;
701   }
702 
703   if (!first_chance) {
704     // Not any second chance exception is an application crash by definition.
705     // It may be an expression evaluation crash.
706     SetPrivateState(eStateStopped);
707   }
708 
709   ExceptionResult result = ExceptionResult::SendToApplication;
710   switch (record.GetExceptionCode()) {
711   case EXCEPTION_BREAKPOINT:
712     // Handle breakpoints at the first chance.
713     result = ExceptionResult::BreakInDebugger;
714 
715     if (!m_session_data->m_initial_stop_received) {
716       LLDB_LOG(
717           log,
718           "Hit loader breakpoint at address {0:x}, setting initial stop event.",
719           record.GetExceptionAddress());
720       m_session_data->m_initial_stop_received = true;
721       ::SetEvent(m_session_data->m_initial_stop_event);
722     } else {
723       LLDB_LOG(log, "Hit non-loader breakpoint at address {0:x}.",
724                record.GetExceptionAddress());
725     }
726     SetPrivateState(eStateStopped);
727     break;
728   case EXCEPTION_SINGLE_STEP:
729     result = ExceptionResult::BreakInDebugger;
730     SetPrivateState(eStateStopped);
731     break;
732   default:
733     LLDB_LOG(log,
734              "Debugger thread reported exception {0:x} at address {1:x} "
735              "(first_chance={2})",
736              record.GetExceptionCode(), record.GetExceptionAddress(),
737              first_chance);
738     // For non-breakpoints, give the application a chance to handle the
739     // exception first.
740     if (first_chance)
741       result = ExceptionResult::SendToApplication;
742     else
743       result = ExceptionResult::BreakInDebugger;
744   }
745 
746   return result;
747 }
748 
749 void ProcessWindows::OnCreateThread(const HostThread &new_thread) {
750   llvm::sys::ScopedLock lock(m_mutex);
751 
752   ThreadSP thread = std::make_shared<TargetThreadWindows>(*this, new_thread);
753 
754   const HostNativeThread &native_new_thread = new_thread.GetNativeThread();
755   tid_t id = native_new_thread.GetThreadId();
756   thread->SetID(id);
757 
758   m_session_data->m_new_threads[id] = thread;
759 
760   for (const std::map<int, WatchpointInfo>::value_type &p : m_watchpoints) {
761     auto *reg_ctx = static_cast<RegisterContextWindows *>(
762         thread->GetRegisterContext().get());
763     reg_ctx->AddHardwareBreakpoint(p.second.slot_id, p.second.address,
764                                    p.second.size, p.second.read,
765                                    p.second.write);
766   }
767 }
768 
769 void ProcessWindows::OnExitThread(lldb::tid_t thread_id, uint32_t exit_code) {
770   llvm::sys::ScopedLock lock(m_mutex);
771 
772   // On a forced termination, we may get exit thread events after the session
773   // data has been cleaned up.
774   if (!m_session_data)
775     return;
776 
777   // A thread may have started and exited before the debugger stopped allowing a
778   // refresh.
779   // Just remove it from the new threads list in that case.
780   auto iter = m_session_data->m_new_threads.find(thread_id);
781   if (iter != m_session_data->m_new_threads.end())
782     m_session_data->m_new_threads.erase(iter);
783   else
784     m_session_data->m_exited_threads.insert(thread_id);
785 }
786 
787 void ProcessWindows::OnLoadDll(const ModuleSpec &module_spec,
788                                lldb::addr_t module_addr) {
789   if (auto dyld = GetDynamicLoader())
790     dyld->OnLoadModule(nullptr, module_spec, module_addr);
791 }
792 
793 void ProcessWindows::OnUnloadDll(lldb::addr_t module_addr) {
794   if (auto dyld = GetDynamicLoader())
795     dyld->OnUnloadModule(module_addr);
796 }
797 
798 void ProcessWindows::OnDebugString(const std::string &string) {}
799 
800 void ProcessWindows::OnDebuggerError(const Status &error, uint32_t type) {
801   llvm::sys::ScopedLock lock(m_mutex);
802   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
803 
804   if (m_session_data->m_initial_stop_received) {
805     // This happened while debugging.  Do we shutdown the debugging session,
806     // try to continue, or do something else?
807     LLDB_LOG(log,
808              "Error {0} occurred during debugging.  Unexpected behavior "
809              "may result.  {1}",
810              error.GetError(), error);
811   } else {
812     // If we haven't actually launched the process yet, this was an error
813     // launching the process.  Set the internal error and signal the initial
814     // stop event so that the DoLaunch method wakes up and returns a failure.
815     m_session_data->m_launch_error = error;
816     ::SetEvent(m_session_data->m_initial_stop_event);
817     LLDB_LOG(
818         log,
819         "Error {0} occurred launching the process before the initial stop. {1}",
820         error.GetError(), error);
821     return;
822   }
823 }
824 
825 Status ProcessWindows::GetWatchpointSupportInfo(uint32_t &num) {
826   num = RegisterContextWindows::GetNumHardwareBreakpointSlots();
827   return {};
828 }
829 
830 Status ProcessWindows::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
831   num = RegisterContextWindows::GetNumHardwareBreakpointSlots();
832   after = RegisterContextWindows::DoHardwareBreakpointsTriggerAfter();
833   return {};
834 }
835 
836 Status ProcessWindows::EnableWatchpoint(Watchpoint *wp, bool notify) {
837   Status error;
838 
839   if (wp->IsEnabled()) {
840     wp->SetEnabled(true, notify);
841     return error;
842   }
843 
844   WatchpointInfo info;
845   for (info.slot_id = 0;
846        info.slot_id < RegisterContextWindows::GetNumHardwareBreakpointSlots();
847        info.slot_id++)
848     if (m_watchpoint_ids[info.slot_id] == LLDB_INVALID_BREAK_ID)
849       break;
850   if (info.slot_id == RegisterContextWindows::GetNumHardwareBreakpointSlots()) {
851     error.SetErrorStringWithFormat("Can't find free slot for watchpoint %i",
852                                    wp->GetID());
853     return error;
854   }
855   info.address = wp->GetLoadAddress();
856   info.size = wp->GetByteSize();
857   info.read = wp->WatchpointRead();
858   info.write = wp->WatchpointWrite();
859 
860   for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) {
861     Thread *thread = m_thread_list.GetThreadAtIndex(i).get();
862     auto *reg_ctx = static_cast<RegisterContextWindows *>(
863         thread->GetRegisterContext().get());
864     if (!reg_ctx->AddHardwareBreakpoint(info.slot_id, info.address, info.size,
865                                         info.read, info.write)) {
866       error.SetErrorStringWithFormat(
867           "Can't enable watchpoint %i on thread 0x%llx", wp->GetID(),
868           thread->GetID());
869       break;
870     }
871   }
872   if (error.Fail()) {
873     for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) {
874       Thread *thread = m_thread_list.GetThreadAtIndex(i).get();
875       auto *reg_ctx = static_cast<RegisterContextWindows *>(
876           thread->GetRegisterContext().get());
877       reg_ctx->RemoveHardwareBreakpoint(info.slot_id);
878     }
879     return error;
880   }
881 
882   m_watchpoints[wp->GetID()] = info;
883   m_watchpoint_ids[info.slot_id] = wp->GetID();
884 
885   wp->SetEnabled(true, notify);
886 
887   return error;
888 }
889 
890 Status ProcessWindows::DisableWatchpoint(Watchpoint *wp, bool notify) {
891   Status error;
892 
893   if (!wp->IsEnabled()) {
894     wp->SetEnabled(false, notify);
895     return error;
896   }
897 
898   auto it = m_watchpoints.find(wp->GetID());
899   if (it == m_watchpoints.end()) {
900     error.SetErrorStringWithFormat("Info about watchpoint %i is not found",
901                                    wp->GetID());
902     return error;
903   }
904 
905   for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) {
906     Thread *thread = m_thread_list.GetThreadAtIndex(i).get();
907     auto *reg_ctx = static_cast<RegisterContextWindows *>(
908         thread->GetRegisterContext().get());
909     if (!reg_ctx->RemoveHardwareBreakpoint(it->second.slot_id)) {
910       error.SetErrorStringWithFormat(
911           "Can't disable watchpoint %i on thread 0x%llx", wp->GetID(),
912           thread->GetID());
913       break;
914     }
915   }
916   if (error.Fail())
917     return error;
918 
919   m_watchpoint_ids[it->second.slot_id] = LLDB_INVALID_BREAK_ID;
920   m_watchpoints.erase(it);
921 
922   wp->SetEnabled(false, notify);
923 
924   return error;
925 }
926 } // namespace lldb_private
927