xref: /llvm-project/lldb/source/Plugins/Process/Windows/Common/NativeProcessWindows.cpp (revision 52a3ed5b93ca9aba042d87e2bb697bf0dda2e43c)
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 llvm::Expected<lldb::addr_t>
221 NativeProcessWindows::AllocateMemory(size_t size, uint32_t permissions) {
222   lldb::addr_t addr;
223   Status ST = ProcessDebugger::AllocateMemory(size, permissions, addr);
224   if (ST.Success())
225     return addr;
226   return ST.ToError();
227 }
228 
229 llvm::Error NativeProcessWindows::DeallocateMemory(lldb::addr_t addr) {
230   return ProcessDebugger::DeallocateMemory(addr).ToError();
231 }
232 
233 lldb::addr_t NativeProcessWindows::GetSharedLibraryInfoAddress() { return 0; }
234 
235 bool NativeProcessWindows::IsAlive() const {
236   StateType state = GetState();
237   switch (state) {
238   case eStateCrashed:
239   case eStateDetached:
240   case eStateExited:
241   case eStateInvalid:
242   case eStateUnloaded:
243     return false;
244   default:
245     return true;
246   }
247 }
248 
249 void NativeProcessWindows::SetStopReasonForThread(NativeThreadWindows &thread,
250                                                   lldb::StopReason reason,
251                                                   std::string description) {
252   SetCurrentThreadID(thread.GetID());
253 
254   ThreadStopInfo stop_info;
255   stop_info.reason = reason;
256 
257   // No signal support on Windows but required to provide a 'valid' signum.
258   if (reason == StopReason::eStopReasonException) {
259     stop_info.details.exception.type = 0;
260     stop_info.details.exception.data_count = 0;
261   } else {
262     stop_info.details.signal.signo = SIGTRAP;
263   }
264 
265   thread.SetStopReason(stop_info, description);
266 }
267 
268 void NativeProcessWindows::StopThread(lldb::tid_t thread_id,
269                                       lldb::StopReason reason,
270                                       std::string description) {
271   NativeThreadWindows *thread = GetThreadByID(thread_id);
272   if (!thread)
273     return;
274 
275   for (uint32_t i = 0; i < m_threads.size(); ++i) {
276     auto t = static_cast<NativeThreadWindows *>(m_threads[i].get());
277     Status error = t->DoStop();
278     if (error.Fail())
279       exit(1);
280   }
281   SetStopReasonForThread(*thread, reason, description);
282 }
283 
284 size_t NativeProcessWindows::UpdateThreads() { return m_threads.size(); }
285 
286 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
287 NativeProcessWindows::GetAuxvData() const {
288   // Not available on this target.
289   return llvm::errc::not_supported;
290 }
291 
292 llvm::Expected<llvm::ArrayRef<uint8_t>>
293 NativeProcessWindows::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
294   static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x3e, 0xd4}; // brk #0xf000
295   static const uint8_t g_thumb_opcode[] = {0xfe, 0xde}; // udf #0xfe
296 
297   switch (GetArchitecture().GetMachine()) {
298   case llvm::Triple::aarch64:
299     return llvm::makeArrayRef(g_aarch64_opcode);
300 
301   case llvm::Triple::arm:
302   case llvm::Triple::thumb:
303     return llvm::makeArrayRef(g_thumb_opcode);
304 
305   default:
306     return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
307   }
308 }
309 
310 size_t NativeProcessWindows::GetSoftwareBreakpointPCOffset() {
311     // Windows always reports an incremented PC after a breakpoint is hit,
312     // even on ARM.
313     return cantFail(GetSoftwareBreakpointTrapOpcode(0)).size();
314 }
315 
316 bool NativeProcessWindows::FindSoftwareBreakpoint(lldb::addr_t addr) {
317   auto it = m_software_breakpoints.find(addr);
318   if (it == m_software_breakpoints.end())
319     return false;
320   return true;
321 }
322 
323 Status NativeProcessWindows::SetBreakpoint(lldb::addr_t addr, uint32_t size,
324                                            bool hardware) {
325   if (hardware)
326     return SetHardwareBreakpoint(addr, size);
327   return SetSoftwareBreakpoint(addr, size);
328 }
329 
330 Status NativeProcessWindows::RemoveBreakpoint(lldb::addr_t addr,
331                                               bool hardware) {
332   if (hardware)
333     return RemoveHardwareBreakpoint(addr);
334   return RemoveSoftwareBreakpoint(addr);
335 }
336 
337 Status NativeProcessWindows::CacheLoadedModules() {
338   Status error;
339   if (!m_loaded_modules.empty())
340     return Status();
341 
342   // Retrieve loaded modules by a Target/Module free implemenation.
343   AutoHandle snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetID()));
344   if (snapshot.IsValid()) {
345     MODULEENTRY32W me;
346     me.dwSize = sizeof(MODULEENTRY32W);
347     if (Module32FirstW(snapshot.get(), &me)) {
348       do {
349         std::string path;
350         if (!llvm::convertWideToUTF8(me.szExePath, path))
351           continue;
352 
353         FileSpec file_spec(path);
354         FileSystem::Instance().Resolve(file_spec);
355         m_loaded_modules[file_spec] = (addr_t)me.modBaseAddr;
356       } while (Module32Next(snapshot.get(), &me));
357     }
358 
359     if (!m_loaded_modules.empty())
360       return Status();
361   }
362 
363   error.SetError(::GetLastError(), lldb::ErrorType::eErrorTypeWin32);
364   return error;
365 }
366 
367 Status NativeProcessWindows::GetLoadedModuleFileSpec(const char *module_path,
368                                                      FileSpec &file_spec) {
369   Status error = CacheLoadedModules();
370   if (error.Fail())
371     return error;
372 
373   FileSpec module_file_spec(module_path);
374   FileSystem::Instance().Resolve(module_file_spec);
375   for (auto &it : m_loaded_modules) {
376     if (it.first == module_file_spec) {
377       file_spec = it.first;
378       return Status();
379     }
380   }
381   return Status("Module (%s) not found in process %" PRIu64 "!",
382                 module_file_spec.GetCString(), GetID());
383 }
384 
385 Status
386 NativeProcessWindows::GetFileLoadAddress(const llvm::StringRef &file_name,
387                                          lldb::addr_t &load_addr) {
388   Status error = CacheLoadedModules();
389   if (error.Fail())
390     return error;
391 
392   load_addr = LLDB_INVALID_ADDRESS;
393   FileSpec file_spec(file_name);
394   FileSystem::Instance().Resolve(file_spec);
395   for (auto &it : m_loaded_modules) {
396     if (it.first == file_spec) {
397       load_addr = it.second;
398       return Status();
399     }
400   }
401   return Status("Can't get loaded address of file (%s) in process %" PRIu64 "!",
402                 file_spec.GetCString(), GetID());
403 }
404 
405 void NativeProcessWindows::OnExitProcess(uint32_t exit_code) {
406   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
407   LLDB_LOG(log, "Process {0} exited with code {1}", GetID(), exit_code);
408 
409   ProcessDebugger::OnExitProcess(exit_code);
410 
411   // No signal involved.  It is just an exit event.
412   WaitStatus wait_status(WaitStatus::Exit, exit_code);
413   SetExitStatus(wait_status, true);
414 
415   // Notify the native delegate.
416   SetState(eStateExited, true);
417 }
418 
419 void NativeProcessWindows::OnDebuggerConnected(lldb::addr_t image_base) {
420   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
421   LLDB_LOG(log, "Debugger connected to process {0}. Image base = {1:x}",
422            GetDebuggedProcessId(), image_base);
423 
424   // This is the earliest chance we can resolve the process ID and
425   // architecture if we don't know them yet.
426   if (GetID() == LLDB_INVALID_PROCESS_ID)
427     SetID(GetDebuggedProcessId());
428 
429   if (GetArchitecture().GetMachine() == llvm::Triple::UnknownArch) {
430     ProcessInstanceInfo process_info;
431     if (!Host::GetProcessInfo(GetDebuggedProcessId(), process_info)) {
432       LLDB_LOG(log, "Cannot get process information during debugger connecting "
433                     "to process");
434       return;
435     }
436     SetArchitecture(process_info.GetArchitecture());
437   }
438 
439   // The very first one shall always be the main thread.
440   assert(m_threads.empty());
441   m_threads.push_back(std::make_unique<NativeThreadWindows>(
442       *this, m_session_data->m_debugger->GetMainThread()));
443 }
444 
445 ExceptionResult
446 NativeProcessWindows::OnDebugException(bool first_chance,
447                                        const ExceptionRecord &record) {
448   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EXCEPTION);
449   llvm::sys::ScopedLock lock(m_mutex);
450 
451   // Let the debugger establish the internal status.
452   ProcessDebugger::OnDebugException(first_chance, record);
453 
454   static bool initial_stop = false;
455   if (!first_chance) {
456     SetState(eStateStopped, false);
457   }
458 
459   ExceptionResult result = ExceptionResult::SendToApplication;
460   switch (record.GetExceptionCode()) {
461   case DWORD(STATUS_SINGLE_STEP):
462   case STATUS_WX86_SINGLE_STEP: {
463     uint32_t wp_id = LLDB_INVALID_INDEX32;
464     if (NativeThreadWindows *thread = GetThreadByID(record.GetThreadID())) {
465       NativeRegisterContextWindows &reg_ctx = thread->GetRegisterContext();
466       Status error =
467           reg_ctx.GetWatchpointHitIndex(wp_id, record.GetExceptionAddress());
468       if (error.Fail())
469         LLDB_LOG(log,
470                  "received error while checking for watchpoint hits, pid = "
471                  "{0}, error = {1}",
472                  thread->GetID(), error);
473       if (wp_id != LLDB_INVALID_INDEX32) {
474         addr_t wp_addr = reg_ctx.GetWatchpointAddress(wp_id);
475         addr_t wp_hit_addr = reg_ctx.GetWatchpointHitAddress(wp_id);
476         std::string desc =
477             formatv("{0} {1} {2}", wp_addr, wp_id, wp_hit_addr).str();
478         StopThread(record.GetThreadID(), StopReason::eStopReasonWatchpoint,
479                    desc);
480       }
481     }
482     if (wp_id == LLDB_INVALID_INDEX32)
483       StopThread(record.GetThreadID(), StopReason::eStopReasonTrace);
484 
485     SetState(eStateStopped, true);
486 
487     // Continue the debugger.
488     return ExceptionResult::MaskException;
489   }
490   case DWORD(STATUS_BREAKPOINT):
491   case STATUS_WX86_BREAKPOINT:
492     if (FindSoftwareBreakpoint(record.GetExceptionAddress())) {
493       LLDB_LOG(log, "Hit non-loader breakpoint at address {0:x}.",
494                record.GetExceptionAddress());
495 
496       StopThread(record.GetThreadID(), StopReason::eStopReasonBreakpoint);
497 
498       if (NativeThreadWindows *stop_thread =
499               GetThreadByID(record.GetThreadID())) {
500         auto &register_context = stop_thread->GetRegisterContext();
501         uint32_t breakpoint_size = GetSoftwareBreakpointPCOffset();
502         // The current PC is AFTER the BP opcode, on all architectures.
503         uint64_t pc = register_context.GetPC() - breakpoint_size;
504         register_context.SetPC(pc);
505       }
506 
507       SetState(eStateStopped, true);
508       return ExceptionResult::MaskException;
509     }
510 
511     if (!initial_stop) {
512       initial_stop = true;
513       LLDB_LOG(log,
514                "Hit loader breakpoint at address {0:x}, setting initial stop "
515                "event.",
516                record.GetExceptionAddress());
517 
518       // We are required to report the reason for the first stop after
519       // launching or being attached.
520       if (NativeThreadWindows *thread = GetThreadByID(record.GetThreadID()))
521         SetStopReasonForThread(*thread, StopReason::eStopReasonBreakpoint);
522 
523       // Do not notify the native delegate (e.g. llgs) since at this moment
524       // the program hasn't returned from Factory::Launch() and the delegate
525       // might not have an valid native process to operate on.
526       SetState(eStateStopped, false);
527 
528       // Hit the initial stop. Continue the application.
529       return ExceptionResult::BreakInDebugger;
530     }
531 
532     LLVM_FALLTHROUGH;
533   default:
534     LLDB_LOG(log,
535              "Debugger thread reported exception {0:x} at address {1:x} "
536              "(first_chance={2})",
537              record.GetExceptionCode(), record.GetExceptionAddress(),
538              first_chance);
539 
540     {
541       std::string desc;
542       llvm::raw_string_ostream desc_stream(desc);
543       desc_stream << "Exception "
544                   << llvm::format_hex(record.GetExceptionCode(), 8)
545                   << " encountered at address "
546                   << llvm::format_hex(record.GetExceptionAddress(), 8);
547       StopThread(record.GetThreadID(), StopReason::eStopReasonException,
548                  desc_stream.str().c_str());
549 
550       SetState(eStateStopped, true);
551     }
552 
553     // For non-breakpoints, give the application a chance to handle the
554     // exception first.
555     if (first_chance)
556       result = ExceptionResult::SendToApplication;
557     else
558       result = ExceptionResult::BreakInDebugger;
559   }
560 
561   return result;
562 }
563 
564 void NativeProcessWindows::OnCreateThread(const HostThread &new_thread) {
565   llvm::sys::ScopedLock lock(m_mutex);
566 
567   auto thread = std::make_unique<NativeThreadWindows>(*this, new_thread);
568   thread->GetRegisterContext().ClearAllHardwareWatchpoints();
569   for (const auto &pair : GetWatchpointMap()) {
570     const NativeWatchpoint &wp = pair.second;
571     thread->SetWatchpoint(wp.m_addr, wp.m_size, wp.m_watch_flags,
572                           wp.m_hardware);
573   }
574 
575   m_threads.push_back(std::move(thread));
576 }
577 
578 void NativeProcessWindows::OnExitThread(lldb::tid_t thread_id,
579                                         uint32_t exit_code) {
580   llvm::sys::ScopedLock lock(m_mutex);
581   NativeThreadWindows *thread = GetThreadByID(thread_id);
582   if (!thread)
583     return;
584 
585   for (auto t = m_threads.begin(); t != m_threads.end();) {
586     if ((*t)->GetID() == thread_id) {
587       t = m_threads.erase(t);
588     } else {
589       ++t;
590     }
591   }
592 }
593 
594 void NativeProcessWindows::OnLoadDll(const ModuleSpec &module_spec,
595                                      lldb::addr_t module_addr) {
596   // Simply invalidate the cached loaded modules.
597   if (!m_loaded_modules.empty())
598     m_loaded_modules.clear();
599 }
600 
601 void NativeProcessWindows::OnUnloadDll(lldb::addr_t module_addr) {
602   if (!m_loaded_modules.empty())
603     m_loaded_modules.clear();
604 }
605 
606 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
607 NativeProcessWindows::Factory::Launch(
608     ProcessLaunchInfo &launch_info,
609     NativeProcessProtocol::NativeDelegate &native_delegate,
610     MainLoop &mainloop) const {
611   Error E = Error::success();
612   auto process_up = std::unique_ptr<NativeProcessWindows>(
613       new NativeProcessWindows(launch_info, native_delegate, E));
614   if (E)
615     return std::move(E);
616   return std::move(process_up);
617 }
618 
619 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
620 NativeProcessWindows::Factory::Attach(
621     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
622     MainLoop &mainloop) const {
623   Error E = Error::success();
624   // Set pty primary fd invalid since it is not available.
625   auto process_up = std::unique_ptr<NativeProcessWindows>(
626       new NativeProcessWindows(pid, -1, native_delegate, E));
627   if (E)
628     return std::move(E);
629   return std::move(process_up);
630 }
631 } // namespace lldb_private
632