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