1 //===-- NativeProcessWindows.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 "lldb/Host/windows/windows.h"
10 #include <psapi.h>
11 
12 #include "NativeProcessWindows.h"
13 #include "NativeThreadWindows.h"
14 #include "lldb/Host/FileSystem.h"
15 #include "lldb/Host/HostNativeProcessBase.h"
16 #include "lldb/Host/HostProcess.h"
17 #include "lldb/Host/ProcessLaunchInfo.h"
18 #include "lldb/Host/windows/AutoHandle.h"
19 #include "lldb/Host/windows/HostThreadWindows.h"
20 #include "lldb/Host/windows/ProcessLauncherWindows.h"
21 #include "lldb/Target/MemoryRegionInfo.h"
22 #include "lldb/Target/Process.h"
23 #include "lldb/Utility/State.h"
24 #include "llvm/Support/ConvertUTF.h"
25 #include "llvm/Support/Errc.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/Format.h"
28 #include "llvm/Support/Threading.h"
29 #include "llvm/Support/raw_ostream.h"
30 
31 #include "DebuggerThread.h"
32 #include "ExceptionRecord.h"
33 #include "ProcessWindowsLog.h"
34 
35 #include <tlhelp32.h>
36 
37 #pragma warning(disable : 4005)
38 #include "winternl.h"
39 #include <ntstatus.h>
40 
41 using namespace lldb;
42 using namespace lldb_private;
43 using namespace llvm;
44 
45 namespace lldb_private {
46 
47 NativeProcessWindows::NativeProcessWindows(ProcessLaunchInfo &launch_info,
48                                            NativeDelegate &delegate,
49                                            llvm::Error &E)
50     : NativeProcessProtocol(LLDB_INVALID_PROCESS_ID,
51                             launch_info.GetPTY().ReleasePrimaryFileDescriptor(),
52                             delegate),
53       ProcessDebugger(), m_arch(launch_info.GetArchitecture()) {
54   ErrorAsOutParameter EOut(&E);
55   DebugDelegateSP delegate_sp(new NativeDebugDelegate(*this));
56   E = LaunchProcess(launch_info, delegate_sp).ToError();
57   if (E)
58     return;
59 
60   SetID(GetDebuggedProcessId());
61 }
62 
63 NativeProcessWindows::NativeProcessWindows(lldb::pid_t pid, int terminal_fd,
64                                            NativeDelegate &delegate,
65                                            llvm::Error &E)
66     : NativeProcessProtocol(pid, terminal_fd, delegate), ProcessDebugger() {
67   ErrorAsOutParameter EOut(&E);
68   DebugDelegateSP delegate_sp(new NativeDebugDelegate(*this));
69   ProcessAttachInfo attach_info;
70   attach_info.SetProcessID(pid);
71   E = AttachProcess(pid, attach_info, delegate_sp).ToError();
72   if (E)
73     return;
74 
75   SetID(GetDebuggedProcessId());
76 
77   ProcessInstanceInfo info;
78   if (!Host::GetProcessInfo(pid, info)) {
79     E = createStringError(inconvertibleErrorCode(),
80                           "Cannot get process information");
81     return;
82   }
83   m_arch = info.GetArchitecture();
84 }
85 
86 Status NativeProcessWindows::Resume(const ResumeActionList &resume_actions) {
87   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
88   Status error;
89   llvm::sys::ScopedLock lock(m_mutex);
90 
91   StateType state = GetState();
92   if (state == eStateStopped || state == eStateCrashed) {
93     LLDB_LOG(log, "process {0} is in state {1}.  Resuming...",
94              GetDebuggedProcessId(), state);
95     LLDB_LOG(log, "resuming {0} threads.", m_threads.size());
96 
97     bool failed = false;
98     for (uint32_t i = 0; i < m_threads.size(); ++i) {
99       auto thread = static_cast<NativeThreadWindows *>(m_threads[i].get());
100       const ResumeAction *const action =
101           resume_actions.GetActionForThread(thread->GetID(), true);
102       if (action == nullptr)
103         continue;
104 
105       switch (action->state) {
106       case eStateRunning:
107       case eStateStepping: {
108         Status result = thread->DoResume(action->state);
109         if (result.Fail()) {
110           failed = true;
111           LLDB_LOG(log,
112                    "Trying to resume thread at index {0}, but failed with "
113                    "error {1}.",
114                    i, result);
115         }
116         break;
117       }
118       case eStateSuspended:
119       case eStateStopped:
120         llvm_unreachable("Unexpected state");
121 
122       default:
123         return Status(
124             "NativeProcessWindows::%s (): unexpected state %s specified "
125             "for pid %" PRIu64 ", tid %" PRIu64,
126             __FUNCTION__, StateAsCString(action->state), GetID(),
127             thread->GetID());
128       }
129     }
130 
131     if (failed) {
132       error.SetErrorString("NativeProcessWindows::DoResume failed");
133     } else {
134       SetState(eStateRunning);
135     }
136 
137     // Resume the debug loop.
138     ExceptionRecordSP active_exception =
139         m_session_data->m_debugger->GetActiveException().lock();
140     if (active_exception) {
141       // Resume the process and continue processing debug events.  Mask the
142       // exception so that from the process's view, there is no indication that
143       // anything happened.
144       m_session_data->m_debugger->ContinueAsyncException(
145           ExceptionResult::MaskException);
146     }
147   } else {
148     LLDB_LOG(log, "error: process {0} is in state {1}.  Returning...",
149              GetDebuggedProcessId(), GetState());
150   }
151 
152   return error;
153 }
154 
155 NativeThreadWindows *
156 NativeProcessWindows::GetThreadByID(lldb::tid_t thread_id) {
157   return static_cast<NativeThreadWindows *>(
158       NativeProcessProtocol::GetThreadByID(thread_id));
159 }
160 
161 Status NativeProcessWindows::Halt() {
162   bool caused_stop = false;
163   StateType state = GetState();
164   if (state != eStateStopped)
165     return HaltProcess(caused_stop);
166   return Status();
167 }
168 
169 Status NativeProcessWindows::Detach() {
170   Status error;
171   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
172   StateType state = GetState();
173   if (state != eStateExited && state != eStateDetached) {
174     error = DetachProcess();
175     if (error.Success())
176       SetState(eStateDetached);
177     else
178       LLDB_LOG(log, "Detaching process error: {0}", error);
179   } else {
180     error.SetErrorStringWithFormatv("error: process {0} in state = {1}, but "
181                                     "cannot detach it in this state.",
182                                     GetID(), state);
183     LLDB_LOG(log, "error: {0}", error);
184   }
185   return error;
186 }
187 
188 Status NativeProcessWindows::Signal(int signo) {
189   Status error;
190   error.SetErrorString("Windows does not support sending signals to processes");
191   return error;
192 }
193 
194 Status NativeProcessWindows::Interrupt() { return Halt(); }
195 
196 Status NativeProcessWindows::Kill() {
197   StateType state = GetState();
198   return DestroyProcess(state);
199 }
200 
201 Status NativeProcessWindows::IgnoreSignals(llvm::ArrayRef<int> signals) {
202   return Status();
203 }
204 
205 Status NativeProcessWindows::GetMemoryRegionInfo(lldb::addr_t load_addr,
206                                                  MemoryRegionInfo &range_info) {
207   return ProcessDebugger::GetMemoryRegionInfo(load_addr, range_info);
208 }
209 
210 Status NativeProcessWindows::ReadMemory(lldb::addr_t addr, void *buf,
211                                         size_t size, size_t &bytes_read) {
212   return ProcessDebugger::ReadMemory(addr, buf, size, bytes_read);
213 }
214 
215 Status NativeProcessWindows::WriteMemory(lldb::addr_t addr, const void *buf,
216                                          size_t size, size_t &bytes_written) {
217   return ProcessDebugger::WriteMemory(addr, buf, size, bytes_written);
218 }
219 
220 Status NativeProcessWindows::AllocateMemory(size_t size, uint32_t permissions,
221                                             lldb::addr_t &addr) {
222   return ProcessDebugger::AllocateMemory(size, permissions, addr);
223 }
224 
225 Status NativeProcessWindows::DeallocateMemory(lldb::addr_t addr) {
226   return ProcessDebugger::DeallocateMemory(addr);
227 }
228 
229 lldb::addr_t NativeProcessWindows::GetSharedLibraryInfoAddress() { return 0; }
230 
231 bool NativeProcessWindows::IsAlive() const {
232   StateType state = GetState();
233   switch (state) {
234   case eStateCrashed:
235   case eStateDetached:
236   case eStateExited:
237   case eStateInvalid:
238   case eStateUnloaded:
239     return false;
240   default:
241     return true;
242   }
243 }
244 
245 void NativeProcessWindows::SetStopReasonForThread(NativeThreadWindows &thread,
246                                                   lldb::StopReason reason,
247                                                   std::string description) {
248   SetCurrentThreadID(thread.GetID());
249 
250   ThreadStopInfo stop_info;
251   stop_info.reason = reason;
252 
253   // No signal support on Windows but required to provide a 'valid' signum.
254   if (reason == StopReason::eStopReasonException) {
255     stop_info.details.exception.type = 0;
256     stop_info.details.exception.data_count = 0;
257   } else {
258     stop_info.details.signal.signo = SIGTRAP;
259   }
260 
261   thread.SetStopReason(stop_info, description);
262 }
263 
264 void NativeProcessWindows::StopThread(lldb::tid_t thread_id,
265                                       lldb::StopReason reason,
266                                       std::string description) {
267   NativeThreadWindows *thread = GetThreadByID(thread_id);
268   if (!thread)
269     return;
270 
271   for (uint32_t i = 0; i < m_threads.size(); ++i) {
272     auto t = static_cast<NativeThreadWindows *>(m_threads[i].get());
273     Status error = t->DoStop();
274     if (error.Fail())
275       exit(1);
276   }
277   SetStopReasonForThread(*thread, reason, description);
278 }
279 
280 size_t NativeProcessWindows::UpdateThreads() { return m_threads.size(); }
281 
282 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
283 NativeProcessWindows::GetAuxvData() const {
284   // Not available on this target.
285   return llvm::errc::not_supported;
286 }
287 
288 bool NativeProcessWindows::FindSoftwareBreakpoint(lldb::addr_t addr) {
289   auto it = m_software_breakpoints.find(addr);
290   if (it == m_software_breakpoints.end())
291     return false;
292   return true;
293 }
294 
295 Status NativeProcessWindows::SetBreakpoint(lldb::addr_t addr, uint32_t size,
296                                            bool hardware) {
297   if (hardware)
298     return SetHardwareBreakpoint(addr, size);
299   return SetSoftwareBreakpoint(addr, size);
300 }
301 
302 Status NativeProcessWindows::RemoveBreakpoint(lldb::addr_t addr,
303                                               bool hardware) {
304   if (hardware)
305     return RemoveHardwareBreakpoint(addr);
306   return RemoveSoftwareBreakpoint(addr);
307 }
308 
309 Status NativeProcessWindows::CacheLoadedModules() {
310   Status error;
311   if (!m_loaded_modules.empty())
312     return Status();
313 
314   // Retrieve loaded modules by a Target/Module free implemenation.
315   AutoHandle snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetID()));
316   if (snapshot.IsValid()) {
317     MODULEENTRY32W me;
318     me.dwSize = sizeof(MODULEENTRY32W);
319     if (Module32FirstW(snapshot.get(), &me)) {
320       do {
321         std::string path;
322         if (!llvm::convertWideToUTF8(me.szExePath, path))
323           continue;
324 
325         FileSpec file_spec(path);
326         FileSystem::Instance().Resolve(file_spec);
327         m_loaded_modules[file_spec] = (addr_t)me.modBaseAddr;
328       } while (Module32Next(snapshot.get(), &me));
329     }
330 
331     if (!m_loaded_modules.empty())
332       return Status();
333   }
334 
335   error.SetError(::GetLastError(), lldb::ErrorType::eErrorTypeWin32);
336   return error;
337 }
338 
339 Status NativeProcessWindows::GetLoadedModuleFileSpec(const char *module_path,
340                                                      FileSpec &file_spec) {
341   Status error = CacheLoadedModules();
342   if (error.Fail())
343     return error;
344 
345   FileSpec module_file_spec(module_path);
346   FileSystem::Instance().Resolve(module_file_spec);
347   for (auto &it : m_loaded_modules) {
348     if (it.first == module_file_spec) {
349       file_spec = it.first;
350       return Status();
351     }
352   }
353   return Status("Module (%s) not found in process %" PRIu64 "!",
354                 module_file_spec.GetCString(), GetID());
355 }
356 
357 Status
358 NativeProcessWindows::GetFileLoadAddress(const llvm::StringRef &file_name,
359                                          lldb::addr_t &load_addr) {
360   Status error = CacheLoadedModules();
361   if (error.Fail())
362     return error;
363 
364   load_addr = LLDB_INVALID_ADDRESS;
365   FileSpec file_spec(file_name);
366   FileSystem::Instance().Resolve(file_spec);
367   for (auto &it : m_loaded_modules) {
368     if (it.first == file_spec) {
369       load_addr = it.second;
370       return Status();
371     }
372   }
373   return Status("Can't get loaded address of file (%s) in process %" PRIu64 "!",
374                 file_spec.GetCString(), GetID());
375 }
376 
377 void NativeProcessWindows::OnExitProcess(uint32_t exit_code) {
378   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
379   LLDB_LOG(log, "Process {0} exited with code {1}", GetID(), exit_code);
380 
381   ProcessDebugger::OnExitProcess(exit_code);
382 
383   // No signal involved.  It is just an exit event.
384   WaitStatus wait_status(WaitStatus::Exit, exit_code);
385   SetExitStatus(wait_status, true);
386 
387   // Notify the native delegate.
388   SetState(eStateExited, true);
389 }
390 
391 void NativeProcessWindows::OnDebuggerConnected(lldb::addr_t image_base) {
392   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
393   LLDB_LOG(log, "Debugger connected to process {0}. Image base = {1:x}",
394            GetDebuggedProcessId(), image_base);
395 
396   // This is the earliest chance we can resolve the process ID and
397   // architecture if we don't know them yet.
398   if (GetID() == LLDB_INVALID_PROCESS_ID)
399     SetID(GetDebuggedProcessId());
400 
401   if (GetArchitecture().GetMachine() == llvm::Triple::UnknownArch) {
402     ProcessInstanceInfo process_info;
403     if (!Host::GetProcessInfo(GetDebuggedProcessId(), process_info)) {
404       LLDB_LOG(log, "Cannot get process information during debugger connecting "
405                     "to process");
406       return;
407     }
408     SetArchitecture(process_info.GetArchitecture());
409   }
410 
411   // The very first one shall always be the main thread.
412   assert(m_threads.empty());
413   m_threads.push_back(std::make_unique<NativeThreadWindows>(
414       *this, m_session_data->m_debugger->GetMainThread()));
415 }
416 
417 ExceptionResult
418 NativeProcessWindows::OnDebugException(bool first_chance,
419                                        const ExceptionRecord &record) {
420   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EXCEPTION);
421   llvm::sys::ScopedLock lock(m_mutex);
422 
423   // Let the debugger establish the internal status.
424   ProcessDebugger::OnDebugException(first_chance, record);
425 
426   static bool initial_stop = false;
427   if (!first_chance) {
428     SetState(eStateStopped, false);
429   }
430 
431   ExceptionResult result = ExceptionResult::SendToApplication;
432   switch (record.GetExceptionCode()) {
433   case DWORD(STATUS_SINGLE_STEP):
434   case STATUS_WX86_SINGLE_STEP: {
435     uint32_t wp_id = LLDB_INVALID_INDEX32;
436     if (NativeThreadWindows *thread = GetThreadByID(record.GetThreadID())) {
437       NativeRegisterContextWindows &reg_ctx = thread->GetRegisterContext();
438       Status error =
439           reg_ctx.GetWatchpointHitIndex(wp_id, record.GetExceptionAddress());
440       if (error.Fail())
441         LLDB_LOG(log,
442                  "received error while checking for watchpoint hits, pid = "
443                  "{0}, error = {1}",
444                  thread->GetID(), error);
445       if (wp_id != LLDB_INVALID_INDEX32) {
446         addr_t wp_addr = reg_ctx.GetWatchpointAddress(wp_id);
447         addr_t wp_hit_addr = reg_ctx.GetWatchpointHitAddress(wp_id);
448         std::string desc =
449             formatv("{0} {1} {2}", wp_addr, wp_id, wp_hit_addr).str();
450         StopThread(record.GetThreadID(), StopReason::eStopReasonWatchpoint,
451                    desc);
452       }
453     }
454     if (wp_id == LLDB_INVALID_INDEX32)
455       StopThread(record.GetThreadID(), StopReason::eStopReasonTrace);
456 
457     SetState(eStateStopped, true);
458 
459     // Continue the debugger.
460     return ExceptionResult::MaskException;
461   }
462   case DWORD(STATUS_BREAKPOINT):
463   case STATUS_WX86_BREAKPOINT:
464     if (FindSoftwareBreakpoint(record.GetExceptionAddress())) {
465       LLDB_LOG(log, "Hit non-loader breakpoint at address {0:x}.",
466                record.GetExceptionAddress());
467 
468       StopThread(record.GetThreadID(), StopReason::eStopReasonBreakpoint);
469 
470       if (NativeThreadWindows *stop_thread =
471               GetThreadByID(record.GetThreadID())) {
472         auto &register_context = stop_thread->GetRegisterContext();
473         // The current EIP is AFTER the BP opcode, which is one byte '0xCC'
474         uint64_t pc = register_context.GetPC() - 1;
475         register_context.SetPC(pc);
476       }
477 
478       SetState(eStateStopped, true);
479       return ExceptionResult::MaskException;
480     }
481 
482     if (!initial_stop) {
483       initial_stop = true;
484       LLDB_LOG(log,
485                "Hit loader breakpoint at address {0:x}, setting initial stop "
486                "event.",
487                record.GetExceptionAddress());
488 
489       // We are required to report the reason for the first stop after
490       // launching or being attached.
491       if (NativeThreadWindows *thread = GetThreadByID(record.GetThreadID()))
492         SetStopReasonForThread(*thread, StopReason::eStopReasonBreakpoint);
493 
494       // Do not notify the native delegate (e.g. llgs) since at this moment
495       // the program hasn't returned from Factory::Launch() and the delegate
496       // might not have an valid native process to operate on.
497       SetState(eStateStopped, false);
498 
499       // Hit the initial stop. Continue the application.
500       return ExceptionResult::BreakInDebugger;
501     }
502 
503     LLVM_FALLTHROUGH;
504   default:
505     LLDB_LOG(log,
506              "Debugger thread reported exception {0:x} at address {1:x} "
507              "(first_chance={2})",
508              record.GetExceptionCode(), record.GetExceptionAddress(),
509              first_chance);
510 
511     {
512       std::string desc;
513       llvm::raw_string_ostream desc_stream(desc);
514       desc_stream << "Exception "
515                   << llvm::format_hex(record.GetExceptionCode(), 8)
516                   << " encountered at address "
517                   << llvm::format_hex(record.GetExceptionAddress(), 8);
518       StopThread(record.GetThreadID(), StopReason::eStopReasonException,
519                  desc_stream.str().c_str());
520 
521       SetState(eStateStopped, true);
522     }
523 
524     // For non-breakpoints, give the application a chance to handle the
525     // exception first.
526     if (first_chance)
527       result = ExceptionResult::SendToApplication;
528     else
529       result = ExceptionResult::BreakInDebugger;
530   }
531 
532   return result;
533 }
534 
535 void NativeProcessWindows::OnCreateThread(const HostThread &new_thread) {
536   llvm::sys::ScopedLock lock(m_mutex);
537 
538   auto thread = std::make_unique<NativeThreadWindows>(*this, new_thread);
539   thread->GetRegisterContext().ClearAllHardwareWatchpoints();
540   for (const auto &pair : GetWatchpointMap()) {
541     const NativeWatchpoint &wp = pair.second;
542     thread->SetWatchpoint(wp.m_addr, wp.m_size, wp.m_watch_flags,
543                           wp.m_hardware);
544   }
545 
546   m_threads.push_back(std::move(thread));
547 }
548 
549 void NativeProcessWindows::OnExitThread(lldb::tid_t thread_id,
550                                         uint32_t exit_code) {
551   llvm::sys::ScopedLock lock(m_mutex);
552   NativeThreadWindows *thread = GetThreadByID(thread_id);
553   if (!thread)
554     return;
555 
556   for (auto t = m_threads.begin(); t != m_threads.end();) {
557     if ((*t)->GetID() == thread_id) {
558       t = m_threads.erase(t);
559     } else {
560       ++t;
561     }
562   }
563 }
564 
565 void NativeProcessWindows::OnLoadDll(const ModuleSpec &module_spec,
566                                      lldb::addr_t module_addr) {
567   // Simply invalidate the cached loaded modules.
568   if (!m_loaded_modules.empty())
569     m_loaded_modules.clear();
570 }
571 
572 void NativeProcessWindows::OnUnloadDll(lldb::addr_t module_addr) {
573   if (!m_loaded_modules.empty())
574     m_loaded_modules.clear();
575 }
576 
577 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
578 NativeProcessWindows::Factory::Launch(
579     ProcessLaunchInfo &launch_info,
580     NativeProcessProtocol::NativeDelegate &native_delegate,
581     MainLoop &mainloop) const {
582   Error E = Error::success();
583   auto process_up = std::unique_ptr<NativeProcessWindows>(
584       new NativeProcessWindows(launch_info, native_delegate, E));
585   if (E)
586     return std::move(E);
587   return std::move(process_up);
588 }
589 
590 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
591 NativeProcessWindows::Factory::Attach(
592     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
593     MainLoop &mainloop) const {
594   Error E = Error::success();
595   // Set pty master fd invalid since it is not available.
596   auto process_up = std::unique_ptr<NativeProcessWindows>(
597       new NativeProcessWindows(pid, -1, native_delegate, E));
598   if (E)
599     return std::move(E);
600   return std::move(process_up);
601 }
602 } // namespace lldb_private
603