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