xref: /openbsd-src/gnu/llvm/lldb/source/Plugins/Process/Windows/Common/NativeProcessWindows.cpp (revision d89ec533011f513df1010f142a111086a0785f09)
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 bool NativeProcessWindows::FindSoftwareBreakpoint(lldb::addr_t addr) {
293   auto it = m_software_breakpoints.find(addr);
294   if (it == m_software_breakpoints.end())
295     return false;
296   return true;
297 }
298 
299 Status NativeProcessWindows::SetBreakpoint(lldb::addr_t addr, uint32_t size,
300                                            bool hardware) {
301   if (hardware)
302     return SetHardwareBreakpoint(addr, size);
303   return SetSoftwareBreakpoint(addr, size);
304 }
305 
306 Status NativeProcessWindows::RemoveBreakpoint(lldb::addr_t addr,
307                                               bool hardware) {
308   if (hardware)
309     return RemoveHardwareBreakpoint(addr);
310   return RemoveSoftwareBreakpoint(addr);
311 }
312 
313 Status NativeProcessWindows::CacheLoadedModules() {
314   Status error;
315   if (!m_loaded_modules.empty())
316     return Status();
317 
318   // Retrieve loaded modules by a Target/Module free implemenation.
319   AutoHandle snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetID()));
320   if (snapshot.IsValid()) {
321     MODULEENTRY32W me;
322     me.dwSize = sizeof(MODULEENTRY32W);
323     if (Module32FirstW(snapshot.get(), &me)) {
324       do {
325         std::string path;
326         if (!llvm::convertWideToUTF8(me.szExePath, path))
327           continue;
328 
329         FileSpec file_spec(path);
330         FileSystem::Instance().Resolve(file_spec);
331         m_loaded_modules[file_spec] = (addr_t)me.modBaseAddr;
332       } while (Module32Next(snapshot.get(), &me));
333     }
334 
335     if (!m_loaded_modules.empty())
336       return Status();
337   }
338 
339   error.SetError(::GetLastError(), lldb::ErrorType::eErrorTypeWin32);
340   return error;
341 }
342 
343 Status NativeProcessWindows::GetLoadedModuleFileSpec(const char *module_path,
344                                                      FileSpec &file_spec) {
345   Status error = CacheLoadedModules();
346   if (error.Fail())
347     return error;
348 
349   FileSpec module_file_spec(module_path);
350   FileSystem::Instance().Resolve(module_file_spec);
351   for (auto &it : m_loaded_modules) {
352     if (it.first == module_file_spec) {
353       file_spec = it.first;
354       return Status();
355     }
356   }
357   return Status("Module (%s) not found in process %" PRIu64 "!",
358                 module_file_spec.GetCString(), GetID());
359 }
360 
361 Status
362 NativeProcessWindows::GetFileLoadAddress(const llvm::StringRef &file_name,
363                                          lldb::addr_t &load_addr) {
364   Status error = CacheLoadedModules();
365   if (error.Fail())
366     return error;
367 
368   load_addr = LLDB_INVALID_ADDRESS;
369   FileSpec file_spec(file_name);
370   FileSystem::Instance().Resolve(file_spec);
371   for (auto &it : m_loaded_modules) {
372     if (it.first == file_spec) {
373       load_addr = it.second;
374       return Status();
375     }
376   }
377   return Status("Can't get loaded address of file (%s) in process %" PRIu64 "!",
378                 file_spec.GetCString(), GetID());
379 }
380 
381 void NativeProcessWindows::OnExitProcess(uint32_t exit_code) {
382   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
383   LLDB_LOG(log, "Process {0} exited with code {1}", GetID(), exit_code);
384 
385   ProcessDebugger::OnExitProcess(exit_code);
386 
387   // No signal involved.  It is just an exit event.
388   WaitStatus wait_status(WaitStatus::Exit, exit_code);
389   SetExitStatus(wait_status, true);
390 
391   // Notify the native delegate.
392   SetState(eStateExited, true);
393 }
394 
395 void NativeProcessWindows::OnDebuggerConnected(lldb::addr_t image_base) {
396   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_PROCESS);
397   LLDB_LOG(log, "Debugger connected to process {0}. Image base = {1:x}",
398            GetDebuggedProcessId(), image_base);
399 
400   // This is the earliest chance we can resolve the process ID and
401   // architecture if we don't know them yet.
402   if (GetID() == LLDB_INVALID_PROCESS_ID)
403     SetID(GetDebuggedProcessId());
404 
405   if (GetArchitecture().GetMachine() == llvm::Triple::UnknownArch) {
406     ProcessInstanceInfo process_info;
407     if (!Host::GetProcessInfo(GetDebuggedProcessId(), process_info)) {
408       LLDB_LOG(log, "Cannot get process information during debugger connecting "
409                     "to process");
410       return;
411     }
412     SetArchitecture(process_info.GetArchitecture());
413   }
414 
415   // The very first one shall always be the main thread.
416   assert(m_threads.empty());
417   m_threads.push_back(std::make_unique<NativeThreadWindows>(
418       *this, m_session_data->m_debugger->GetMainThread()));
419 }
420 
421 ExceptionResult
422 NativeProcessWindows::OnDebugException(bool first_chance,
423                                        const ExceptionRecord &record) {
424   Log *log = ProcessWindowsLog::GetLogIfAny(WINDOWS_LOG_EXCEPTION);
425   llvm::sys::ScopedLock lock(m_mutex);
426 
427   // Let the debugger establish the internal status.
428   ProcessDebugger::OnDebugException(first_chance, record);
429 
430   static bool initial_stop = false;
431   if (!first_chance) {
432     SetState(eStateStopped, false);
433   }
434 
435   ExceptionResult result = ExceptionResult::SendToApplication;
436   switch (record.GetExceptionCode()) {
437   case DWORD(STATUS_SINGLE_STEP):
438   case STATUS_WX86_SINGLE_STEP: {
439     uint32_t wp_id = LLDB_INVALID_INDEX32;
440     if (NativeThreadWindows *thread = GetThreadByID(record.GetThreadID())) {
441       NativeRegisterContextWindows &reg_ctx = thread->GetRegisterContext();
442       Status error =
443           reg_ctx.GetWatchpointHitIndex(wp_id, record.GetExceptionAddress());
444       if (error.Fail())
445         LLDB_LOG(log,
446                  "received error while checking for watchpoint hits, pid = "
447                  "{0}, error = {1}",
448                  thread->GetID(), error);
449       if (wp_id != LLDB_INVALID_INDEX32) {
450         addr_t wp_addr = reg_ctx.GetWatchpointAddress(wp_id);
451         addr_t wp_hit_addr = reg_ctx.GetWatchpointHitAddress(wp_id);
452         std::string desc =
453             formatv("{0} {1} {2}", wp_addr, wp_id, wp_hit_addr).str();
454         StopThread(record.GetThreadID(), StopReason::eStopReasonWatchpoint,
455                    desc);
456       }
457     }
458     if (wp_id == LLDB_INVALID_INDEX32)
459       StopThread(record.GetThreadID(), StopReason::eStopReasonTrace);
460 
461     SetState(eStateStopped, true);
462 
463     // Continue the debugger.
464     return ExceptionResult::MaskException;
465   }
466   case DWORD(STATUS_BREAKPOINT):
467   case STATUS_WX86_BREAKPOINT:
468     if (FindSoftwareBreakpoint(record.GetExceptionAddress())) {
469       LLDB_LOG(log, "Hit non-loader breakpoint at address {0:x}.",
470                record.GetExceptionAddress());
471 
472       StopThread(record.GetThreadID(), StopReason::eStopReasonBreakpoint);
473 
474       if (NativeThreadWindows *stop_thread =
475               GetThreadByID(record.GetThreadID())) {
476         auto &register_context = stop_thread->GetRegisterContext();
477         // The current EIP is AFTER the BP opcode, which is one byte '0xCC'
478         uint64_t pc = register_context.GetPC() - 1;
479         register_context.SetPC(pc);
480       }
481 
482       SetState(eStateStopped, true);
483       return ExceptionResult::MaskException;
484     }
485 
486     if (!initial_stop) {
487       initial_stop = true;
488       LLDB_LOG(log,
489                "Hit loader breakpoint at address {0:x}, setting initial stop "
490                "event.",
491                record.GetExceptionAddress());
492 
493       // We are required to report the reason for the first stop after
494       // launching or being attached.
495       if (NativeThreadWindows *thread = GetThreadByID(record.GetThreadID()))
496         SetStopReasonForThread(*thread, StopReason::eStopReasonBreakpoint);
497 
498       // Do not notify the native delegate (e.g. llgs) since at this moment
499       // the program hasn't returned from Factory::Launch() and the delegate
500       // might not have an valid native process to operate on.
501       SetState(eStateStopped, false);
502 
503       // Hit the initial stop. Continue the application.
504       return ExceptionResult::BreakInDebugger;
505     }
506 
507     LLVM_FALLTHROUGH;
508   default:
509     LLDB_LOG(log,
510              "Debugger thread reported exception {0:x} at address {1:x} "
511              "(first_chance={2})",
512              record.GetExceptionCode(), record.GetExceptionAddress(),
513              first_chance);
514 
515     {
516       std::string desc;
517       llvm::raw_string_ostream desc_stream(desc);
518       desc_stream << "Exception "
519                   << llvm::format_hex(record.GetExceptionCode(), 8)
520                   << " encountered at address "
521                   << llvm::format_hex(record.GetExceptionAddress(), 8);
522       StopThread(record.GetThreadID(), StopReason::eStopReasonException,
523                  desc_stream.str().c_str());
524 
525       SetState(eStateStopped, true);
526     }
527 
528     // For non-breakpoints, give the application a chance to handle the
529     // exception first.
530     if (first_chance)
531       result = ExceptionResult::SendToApplication;
532     else
533       result = ExceptionResult::BreakInDebugger;
534   }
535 
536   return result;
537 }
538 
539 void NativeProcessWindows::OnCreateThread(const HostThread &new_thread) {
540   llvm::sys::ScopedLock lock(m_mutex);
541 
542   auto thread = std::make_unique<NativeThreadWindows>(*this, new_thread);
543   thread->GetRegisterContext().ClearAllHardwareWatchpoints();
544   for (const auto &pair : GetWatchpointMap()) {
545     const NativeWatchpoint &wp = pair.second;
546     thread->SetWatchpoint(wp.m_addr, wp.m_size, wp.m_watch_flags,
547                           wp.m_hardware);
548   }
549 
550   m_threads.push_back(std::move(thread));
551 }
552 
553 void NativeProcessWindows::OnExitThread(lldb::tid_t thread_id,
554                                         uint32_t exit_code) {
555   llvm::sys::ScopedLock lock(m_mutex);
556   NativeThreadWindows *thread = GetThreadByID(thread_id);
557   if (!thread)
558     return;
559 
560   for (auto t = m_threads.begin(); t != m_threads.end();) {
561     if ((*t)->GetID() == thread_id) {
562       t = m_threads.erase(t);
563     } else {
564       ++t;
565     }
566   }
567 }
568 
569 void NativeProcessWindows::OnLoadDll(const ModuleSpec &module_spec,
570                                      lldb::addr_t module_addr) {
571   // Simply invalidate the cached loaded modules.
572   if (!m_loaded_modules.empty())
573     m_loaded_modules.clear();
574 }
575 
576 void NativeProcessWindows::OnUnloadDll(lldb::addr_t module_addr) {
577   if (!m_loaded_modules.empty())
578     m_loaded_modules.clear();
579 }
580 
581 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
582 NativeProcessWindows::Factory::Launch(
583     ProcessLaunchInfo &launch_info,
584     NativeProcessProtocol::NativeDelegate &native_delegate,
585     MainLoop &mainloop) const {
586   Error E = Error::success();
587   auto process_up = std::unique_ptr<NativeProcessWindows>(
588       new NativeProcessWindows(launch_info, native_delegate, E));
589   if (E)
590     return std::move(E);
591   return std::move(process_up);
592 }
593 
594 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
595 NativeProcessWindows::Factory::Attach(
596     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
597     MainLoop &mainloop) const {
598   Error E = Error::success();
599   // Set pty master fd invalid since it is not available.
600   auto process_up = std::unique_ptr<NativeProcessWindows>(
601       new NativeProcessWindows(pid, -1, native_delegate, E));
602   if (E)
603     return std::move(E);
604   return std::move(process_up);
605 }
606 } // namespace lldb_private
607