LLDB mainline
ProcessWindows.cpp
Go to the documentation of this file.
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
13#include <psapi.h>
14
16#include "lldb/Core/Module.h"
19#include "lldb/Core/Section.h"
21#include "lldb/Host/HostInfo.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
45using namespace lldb;
46using namespace lldb_private;
47
48LLDB_PLUGIN_DEFINE_ADV(ProcessWindows, ProcessWindowsCommon)
49
50namespace {
51std::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(file_name.data(), result);
64 return result;
65}
66
67std::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
79namespace lldb_private {
80
82 lldb::ListenerSP listener_sp,
83 const FileSpec *,
84 bool can_connect) {
85 return ProcessSP(new ProcessWindows(target_sp, listener_sp));
86}
87
88static bool ShouldUseLLDBServer() {
89 llvm::StringRef use_lldb_server = ::getenv("LLDB_USE_LLDB_SERVER");
90 return use_lldb_server.equals_insensitive("on") ||
91 use_lldb_server.equals_insensitive("yes") ||
92 use_lldb_server.equals_insensitive("1") ||
93 use_lldb_server.equals_insensitive("true");
94}
95
97 if (!ShouldUseLLDBServer()) {
98 static llvm::once_flag g_once_flag;
99
100 llvm::call_once(g_once_flag, []() {
104 });
105 }
106}
107
109
111 return "Process plugin for Windows";
112}
113
114// Constructors and destructors.
115
117 lldb::ListenerSP listener_sp)
118 : lldb_private::Process(target_sp, listener_sp),
119 m_watchpoint_ids(
120 RegisterContextWindows::GetNumHardwareBreakpointSlots(),
122
124
125size_t ProcessWindows::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
126 error.SetErrorString("GetSTDOUT unsupported on Windows");
127 return 0;
128}
129
130size_t ProcessWindows::GetSTDERR(char *buf, size_t buf_size, Status &error) {
131 error.SetErrorString("GetSTDERR unsupported on Windows");
132 return 0;
133}
134
135size_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
142 if (bp_site->HardwareRequired())
143 return Status("Hardware breakpoints are not supported.");
144
146 LLDB_LOG(log, "bp_site = {0:x}, id={1}, addr={2:x}", bp_site,
147 bp_site->GetID(), bp_site->GetLoadAddress());
148
150 if (!error.Success())
151 LLDB_LOG(log, "error: {0}", error);
152 return error;
153}
154
157 LLDB_LOG(log, "bp_site = {0:x}, id={1}, addr={2:x}", bp_site,
158 bp_site->GetID(), bp_site->GetLoadAddress());
159
161
162 if (!error.Success())
163 LLDB_LOG(log, "error: {0}", error);
164 return error;
165}
166
170 StateType private_state = GetPrivateState();
171 if (private_state != eStateExited && private_state != eStateDetached) {
173 if (error.Success())
175 else
176 LLDB_LOG(log, "Detaching process error: {0}", error);
177 } else {
178 error.SetErrorStringWithFormatv("error: process {0} in state = {1}, but "
179 "cannot detach it in this state.",
180 GetID(), private_state);
181 LLDB_LOG(log, "error: {0}", error);
182 }
183 return error;
184}
185
187 ProcessLaunchInfo &launch_info) {
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
196Status
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())
203 return error;
204}
205
208 llvm::sys::ScopedLock lock(m_mutex);
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(),
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>(
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 {
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 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(),
252 }
253 return error;
254}
255
257 StateType private_state = GetPrivateState();
258 return DestroyProcess(private_state);
259}
260
261Status 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
270 ArchSpec arch_spec;
271 DidAttach(arch_spec);
272}
273
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.
280 m_session_data->m_stop_at_entry)
282}
283
284static void
285DumpAdditionalExceptionInformation(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(access_violation_address, 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(page_load_error_address, addr_min_width)
346 << " (status code " << llvm::format_hex(underlying_code, 8) << ")";
347 break;
348 }
349 }
350}
351
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
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(active_exception->GetThreadID());
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(pc));
385 if (site && site->ValidForThisThread(*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(*stop_thread,
392 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
409 *stop_thread, id, 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(*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(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(*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
464 *stop_thread, 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(active_exception->GetExceptionCode(), 8)
491 << " encountered at address "
492 << llvm::format_hex(active_exception->GetExceptionAddress(), 8);
493 DumpAdditionalExceptionInformation(desc_stream, active_exception);
494
496 *stop_thread, 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
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(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
519 ThreadList &new_thread_list) {
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(old_thread_id);
532 if (exited_thread_iter == m_session_data->m_exited_threads.end()) {
533 new_thread_list.AddThread(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_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
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
577 return HostInfo::GetArchitecture();
578}
579
581 size_t size, Status &error) {
582 size_t bytes_read = 0;
583 error = ProcessDebugger::ReadMemory(vm_addr, buf, size, bytes_read);
584 return bytes_read;
585}
586
587size_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(vm_addr, buf, size, bytes_written);
591 return bytes_written;
592}
593
594lldb::addr_t ProcessWindows::DoAllocateMemory(size_t size, uint32_t permissions,
595 Status &error) {
597 error = ProcessDebugger::AllocateMemory(size, permissions, vm_addr);
598 return vm_addr;
599}
600
603}
604
606 MemoryRegionInfo &info) {
607 return ProcessDebugger::GetMemoryRegionInfo(vm_addr, info);
608}
609
611 Target &target = GetTarget();
612 ObjectFile *obj_file = target.GetExecutableModule()->GetObjectFile();
613 Address addr = obj_file->GetImageInfoAddress(&target);
614 if (addr.IsValid())
615 return addr.GetLoadAddress(&target);
616 else
618}
619
621 if (m_dyld_up.get() == NULL)
624 return static_cast<DynamicLoaderWindowsDYLD *>(m_dyld_up.get());
625}
626
627void ProcessWindows::OnExitProcess(uint32_t exit_code) {
628 // No need to acquire the lock since m_session_data isn't accessed.
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(executable_module);
637 target->ModulesDidUnload(unloaded_modules, true);
638 }
639
640 SetProcessExitStatus(GetID(), true, 0, exit_code);
642
644}
645
647 DebuggerThreadSP debugger = m_session_data->m_debugger;
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(executable_file);
662 ModuleSpec module_spec(executable_file);
664 module =
665 GetTarget().GetOrCreateModule(module_spec, true /* notify */, &error);
666 if (!module) {
667 return;
668 }
669
671
672 if (auto dyld = GetDynamicLoader())
673 dyld->OnLoadModule(module, ModuleSpec(), 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>(*this, 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
693 const ExceptionRecord &record) {
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.
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 }
736 break;
737 case EXCEPTION_SINGLE_STEP:
738 result = ExceptionResult::BreakInDebugger;
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
759 llvm::sys::ScopedLock lock(m_mutex);
760
761 ThreadSP thread = std::make_shared<TargetThreadWindows>(*this, 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(p.second.slot_id, p.second.address,
773 p.second.size, p.second.read,
774 p.second.write);
775 }
776}
777
778void 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(thread_id);
790 if (iter != m_session_data->m_new_threads.end())
791 m_session_data->m_new_threads.erase(iter);
792 else
793 m_session_data->m_exited_threads.insert(thread_id);
794}
795
796void ProcessWindows::OnLoadDll(const ModuleSpec &module_spec,
797 lldb::addr_t module_addr) {
798 if (auto dyld = GetDynamicLoader())
799 dyld->OnLoadModule(nullptr, module_spec, module_addr);
800}
801
803 if (auto dyld = GetDynamicLoader())
804 dyld->OnUnloadModule(module_addr);
805}
806
807void ProcessWindows::OnDebugString(const std::string &string) {}
808
809void ProcessWindows::OnDebuggerError(const Status &error, uint32_t type) {
810 llvm::sys::ScopedLock lock(m_mutex);
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
834std::optional<uint32_t> ProcessWindows::GetWatchpointSlotCount() {
836}
837
840
841 if (wp_sp->IsEnabled()) {
842 wp_sp->SetEnabled(true, notify);
843 return error;
844 }
845
846 WatchpointInfo info;
847 for (info.slot_id = 0;
849 info.slot_id++)
851 break;
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(i).get();
864 auto *reg_ctx = static_cast<RegisterContextWindows *>(
865 thread->GetRegisterContext().get());
866 if (!reg_ctx->AddHardwareBreakpoint(info.slot_id, info.address, info.size,
867 info.read, 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(i).get();
877 auto *reg_ctx = static_cast<RegisterContextWindows *>(
878 thread->GetRegisterContext().get());
879 reg_ctx->RemoveHardwareBreakpoint(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(true, notify);
888
889 return error;
890}
891
894
895 if (!wp_sp->IsEnabled()) {
896 wp_sp->SetEnabled(false, notify);
897 return error;
898 }
899
900 auto it = m_watchpoints.find(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(i).get();
909 auto *reg_ctx = static_cast<RegisterContextWindows *>(
910 thread->GetRegisterContext().get());
911 if (!reg_ctx->RemoveHardwareBreakpoint(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(it);
923
924 wp_sp->SetEnabled(false, notify);
925
926 return error;
927}
928} // namespace lldb_private
static llvm::raw_ostream & error(Stream &strm)
ExceptionResult
Definition: ForwardDecl.h:16
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition: Log.h:342
#define LLDB_LOGV(log,...)
Definition: Log.h:356
#define LLDB_PLUGIN_DEFINE_ADV(ClassName, PluginName)
Definition: PluginManager.h:25
A section + offset based address class.
Definition: Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition: Address.cpp:313
bool IsValid() const
Check if the object state is valid.
Definition: Address.h:355
An architecture specification class.
Definition: ArchSpec.h:31
Class that manages the actual breakpoint that will be inserted into the running program.
static DynamicLoader * FindPlugin(Process *process, llvm::StringRef plugin_name)
Find a dynamic loader plugin for a given process.
lldb::addr_t GetExceptionAddress() const
A file utility class.
Definition: FileSpec.h:56
void Resolve(llvm::SmallVectorImpl< char > &path)
Resolve path to make it canonical.
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
static FileSystem & Instance()
HostNativeThread & GetNativeThread()
Definition: HostThread.cpp:32
A collection class for Module objects.
Definition: ModuleList.h:103
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
Definition: ModuleList.cpp:247
A class that describes an executable image and its associated object and symbol files.
Definition: Module.h:88
A plug-in interface definition class for object file parsers.
Definition: ObjectFile.h:44
virtual lldb_private::Address GetImageInfoAddress(Target *target)
Similar to Process::GetImageInfoAddress().
Definition: ObjectFile.h:459
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
Status WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Status DestroyProcess(lldb::StateType process_state)
Status LaunchProcess(ProcessLaunchInfo &launch_info, DebugDelegateSP delegate)
Status GetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info)
std::unique_ptr< ProcessWindowsData > m_session_data
Status AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Status AttachProcess(lldb::pid_t pid, const ProcessAttachInfo &attach_info, DebugDelegateSP delegate)
lldb::pid_t GetDebuggedProcessId() const
Status ReadMemory(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
virtual void OnExitProcess(uint32_t exit_code)
Status HaltProcess(bool &caused_stop)
Status DeallocateMemory(lldb::addr_t addr)
lldb::pid_t GetProcessID() const
Definition: ProcessInfo.h:67
void OnLoadDll(const ModuleSpec &module_spec, lldb::addr_t module_addr) override
void OnDebugString(const std::string &string) override
ProcessWindows(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
bool DoUpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list) override
Update the thread list following process plug-in's specific logic.
size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) override
Puts data into this process's STDIN.
void RefreshStateAfterStop() override
Currently called as part of ShouldStop.
void OnDebuggerConnected(lldb::addr_t image_base) override
Status DoDeallocateMemory(lldb::addr_t ptr) override
Actually deallocate memory in the process.
Status EnableBreakpointSite(BreakpointSite *bp_site) override
void DidLaunch() override
Called after launching a process.
std::optional< uint32_t > GetWatchpointSlotCount() override
Get the number of watchpoints supported by this target.
void OnUnloadDll(lldb::addr_t module_addr) override
DynamicLoaderWindowsDYLD * GetDynamicLoader() override
Get the dynamic loader plug-in for this process.
Status DoResume() override
Resumes all of a process's threads as configured using the Thread run control functions.
size_t GetSTDOUT(char *buf, size_t buf_size, Status &error) override
Get any available STDOUT.
Status DisableWatchpoint(lldb::WatchpointSP wp_sp, bool notify=true) override
bool IsAlive() override
Check if a process is still alive.
Status DoGetMemoryRegionInfo(lldb::addr_t vm_addr, MemoryRegionInfo &info) override
DoGetMemoryRegionInfo is called by GetMemoryRegionInfo after it has removed non address bits from loa...
void OnCreateThread(const HostThread &thread) override
static llvm::StringRef GetPluginDescriptionStatic()
size_t DoWriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error) override
Actually do the writing of memory to a process.
Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) override
Launch a new process.
size_t DoReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, Status &error) override
Actually do the reading of memory from a process.
bool CanDebug(lldb::TargetSP target_sp, bool plugin_specified_by_name) override
Check if a plug-in instance can debug the file in module.
static llvm::StringRef GetPluginNameStatic()
void DidAttach(lldb_private::ArchSpec &arch_spec) override
Called after attaching a process.
void OnExitProcess(uint32_t exit_code) override
static lldb::ProcessSP CreateInstance(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const FileSpec *, bool can_connect)
void OnExitThread(lldb::tid_t thread_id, uint32_t exit_code) override
Status DoAttachToProcessWithID(lldb::pid_t pid, const lldb_private::ProcessAttachInfo &attach_info) override
Attach to an existing process using a process ID.
lldb::addr_t GetImageInfoAddress() override
Get the image information address for the current process.
ExceptionResult OnDebugException(bool first_chance, const ExceptionRecord &record) override
std::map< lldb::break_id_t, WatchpointInfo > m_watchpoints
void OnDebuggerError(const Status &error, uint32_t type) override
ArchSpec GetSystemArchitecture() override
Get the system architecture for this process.
Status DoDetach(bool keep_stopped) override
Detaches from a running or stopped process.
std::vector< lldb::break_id_t > m_watchpoint_ids
size_t GetSTDERR(char *buf, size_t buf_size, Status &error) override
Get any available STDERR.
lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions, Status &error) override
Actually allocate memory in the process.
Status DisableBreakpointSite(BreakpointSite *bp_site) override
Status DoHalt(bool &caused_stop) override
Halts a running process.
Status EnableWatchpoint(lldb::WatchpointSP wp_sp, bool notify=true) override
A plug-in interface definition class for debugging a process.
Definition: Process.h:340
StopPointSiteList< lldb_private::BreakpointSite > & GetBreakpointSiteList()
Definition: Process.cpp:1575
virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition: Process.cpp:1844
lldb::pid_t GetID() const
Returns the pid of the process or LLDB_INVALID_PROCESS_ID if there is no known pid.
Definition: Process.h:537
lldb::StateType GetPrivateState()
Definition: Process.cpp:1417
lldb::DynamicLoaderUP m_dyld_up
Definition: Process.h:3064
lldb::TargetSP CalculateTarget() override
Definition: Process.cpp:4253
static bool SetProcessExitStatus(lldb::pid_t pid, bool exited, int signo, int status)
Static function that can be used with the host function Host::StartMonitoringChildProcess ().
Definition: Process.cpp:1112
virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition: Process.cpp:1768
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
Definition: Process.h:542
void SetPrivateState(lldb::StateType state)
Definition: Process.cpp:1419
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition: Process.h:3038
Target & GetTarget()
Get the target object pointer for this module.
Definition: Process.h:1276
static constexpr uint32_t GetNumHardwareBreakpointSlots()
bool AddHardwareBreakpoint(uint32_t slot, lldb::addr_t address, uint32_t size, bool read, bool write)
An error handling class.
Definition: Status.h:44
bool Fail() const
Test for error condition.
Definition: Status.cpp:181
static lldb::StopInfoSP CreateStopReasonToTrace(Thread &thread)
Definition: StopInfo.cpp:1393
static lldb::StopInfoSP CreateStopReasonWithWatchpointID(Thread &thread, lldb::break_id_t watch_id, bool silently_continue=false)
Definition: StopInfo.cpp:1379
static lldb::StopInfoSP CreateStopReasonWithException(Thread &thread, const char *description)
Definition: StopInfo.cpp:1404
static lldb::StopInfoSP CreateStopReasonWithBreakpointSiteID(Thread &thread, lldb::break_id_t break_id)
lldb::break_id_t GetID() const
Definition: StoppointSite.h:45
virtual lldb::addr_t GetLoadAddress() const
Definition: StoppointSite.h:27
lldb::ModuleSP GetOrCreateModule(const ModuleSpec &module_spec, bool notify, Status *error_ptr=nullptr)
Find a binary on the system and return its Module, or return an existing Module that is already in th...
Definition: Target.cpp:2158
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition: Target.cpp:1422
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
Definition: Target.cpp:1471
void AddThread(const lldb::ThreadSP &thread_sp)
virtual ThreadIterable Threads()
lldb::ThreadSP GetSelectedThread()
Definition: ThreadList.cpp:684
uint32_t GetSize(bool can_update=true)
Definition: ThreadList.cpp:83
bool SetSelectedThreadByID(lldb::tid_t tid, bool notify=false)
Definition: ThreadList.cpp:696
lldb::ThreadSP GetThreadAtIndex(uint32_t idx, bool can_update=true)
Definition: ThreadList.cpp:91
virtual lldb::RegisterContextSP GetRegisterContext()=0
#define LLDB_INVALID_BREAK_ID
Definition: lldb-defines.h:37
#define LLDB_INVALID_INDEX32
Definition: lldb-defines.h:83
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:82
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition: Log.h:314
std::shared_ptr< ExceptionRecord > ExceptionRecordSP
Definition: ForwardDecl.h:37
std::shared_ptr< IDebugDelegate > DebugDelegateSP
Definition: ForwardDecl.h:35
std::shared_ptr< DebuggerThread > DebuggerThreadSP
Definition: ForwardDecl.h:36
static void DumpAdditionalExceptionInformation(llvm::raw_ostream &stream, const ExceptionRecordSP &exception)
static bool ShouldUseLLDBServer()
Definition: SBAddress.h:15
std::shared_ptr< lldb_private::BreakpointSite > BreakpointSiteSP
Definition: lldb-forward.h:315
std::shared_ptr< lldb_private::Thread > ThreadSP
Definition: lldb-forward.h:438
StateType
Process and Thread States.
@ eStateUnloaded
Process is object is valid, but not currently loaded.
@ eStateDetached
Process has been detached and can't be examined.
@ eStateStopped
Process or thread is stopped and can be examined.
@ eStateRunning
Process or thread is running and can't be examined.
@ eStateExited
Process has exited and can't be examined.
@ eStateCrashed
Process or thread has crashed and can be examined.
std::shared_ptr< lldb_private::Process > ProcessSP
Definition: lldb-forward.h:381
uint64_t pid_t
Definition: lldb-types.h:81
std::shared_ptr< lldb_private::Watchpoint > WatchpointSP
Definition: lldb-forward.h:477
std::shared_ptr< lldb_private::Listener > ListenerSP
Definition: lldb-forward.h:360
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
Definition: lldb-forward.h:419
uint64_t addr_t
Definition: lldb-types.h:79
std::shared_ptr< lldb_private::Target > TargetSP
Definition: lldb-forward.h:436
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
Definition: lldb-forward.h:386
uint64_t tid_t
Definition: lldb-types.h:82
std::shared_ptr< lldb_private::Module > ModuleSP
Definition: lldb-forward.h:365
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition: UserID.h:47