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
408 stop_info = StopInfo::CreateStopReasonWithWatchpointID(*stop_thread, id);
409 stop_thread->SetStopInfo(stop_info);
410
411 return;
412 }
413
414 LLDB_LOG(log, "single stepping thread {0}", stop_thread->GetID());
415 stop_info = StopInfo::CreateStopReasonToTrace(*stop_thread);
416 stop_thread->SetStopInfo(stop_info);
417
418 return;
419 }
420
421 case EXCEPTION_BREAKPOINT: {
422 RegisterContextSP register_context = stop_thread->GetRegisterContext();
423
424 int breakpoint_size = 1;
425 switch (GetTarget().GetArchitecture().GetMachine()) {
426 case llvm::Triple::aarch64:
427 breakpoint_size = 4;
428 break;
429
430 case llvm::Triple::arm:
431 case llvm::Triple::thumb:
432 breakpoint_size = 2;
433 break;
434
435 case llvm::Triple::x86:
436 case llvm::Triple::x86_64:
437 breakpoint_size = 1;
438 break;
439
440 default:
441 LLDB_LOG(log, "Unknown breakpoint size for architecture");
442 break;
443 }
444
445 // The current PC is AFTER the BP opcode, on all architectures.
446 uint64_t pc = register_context->GetPC() - breakpoint_size;
447
448 BreakpointSiteSP site(GetBreakpointSiteList().FindByAddress(pc));
449 if (site) {
450 LLDB_LOG(log,
451 "detected breakpoint in process {0} at address {1:x} with "
452 "breakpoint site {2}",
453 m_session_data->m_debugger->GetProcess().GetProcessId(), pc,
454 site->GetID());
455
456 if (site->ValidForThisThread(*stop_thread)) {
457 LLDB_LOG(log,
458 "Breakpoint site {0} is valid for this thread ({1:x}), "
459 "creating stop info.",
460 site->GetID(), stop_thread->GetID());
461
463 *stop_thread, site->GetID());
464 register_context->SetPC(pc);
465 } else {
466 LLDB_LOG(log,
467 "Breakpoint site {0} is not valid for this thread, "
468 "creating empty stop info.",
469 site->GetID());
470 }
471 stop_thread->SetStopInfo(stop_info);
472 return;
473 } else {
474 // The thread hit a hard-coded breakpoint like an `int 3` or
475 // `__debugbreak()`.
476 LLDB_LOG(log,
477 "No breakpoint site matches for this thread. __debugbreak()? "
478 "Creating stop info with the exception.");
479 // FALLTHROUGH: We'll treat this as a generic exception record in the
480 // default case.
481 [[fallthrough]];
482 }
483 }
484
485 default: {
486 std::string desc;
487 llvm::raw_string_ostream desc_stream(desc);
488 desc_stream << "Exception "
489 << llvm::format_hex(active_exception->GetExceptionCode(), 8)
490 << " encountered at address "
491 << llvm::format_hex(active_exception->GetExceptionAddress(), 8);
492 DumpAdditionalExceptionInformation(desc_stream, active_exception);
493
495 *stop_thread, desc_stream.str().c_str());
496 stop_thread->SetStopInfo(stop_info);
497 LLDB_LOG(log, "{0}", desc_stream.str());
498 return;
499 }
500 }
501}
502
504 bool plugin_specified_by_name) {
505 if (plugin_specified_by_name)
506 return true;
507
508 // For now we are just making sure the file exists for a given module
509 ModuleSP exe_module_sp(target_sp->GetExecutableModule());
510 if (exe_module_sp.get())
511 return FileSystem::Instance().Exists(exe_module_sp->GetFileSpec());
512 // However, if there is no executable module, we return true since we might
513 // be preparing to attach.
514 return true;
515}
516
518 ThreadList &new_thread_list) {
520 // Add all the threads that were previously running and for which we did not
521 // detect a thread exited event.
522 int new_size = 0;
523 int continued_threads = 0;
524 int exited_threads = 0;
525 int new_threads = 0;
526
527 for (ThreadSP old_thread : old_thread_list.Threads()) {
528 lldb::tid_t old_thread_id = old_thread->GetID();
529 auto exited_thread_iter =
530 m_session_data->m_exited_threads.find(old_thread_id);
531 if (exited_thread_iter == m_session_data->m_exited_threads.end()) {
532 new_thread_list.AddThread(old_thread);
533 ++new_size;
534 ++continued_threads;
535 LLDB_LOGV(log, "Thread {0} was running and is still running.",
536 old_thread_id);
537 } else {
538 LLDB_LOGV(log, "Thread {0} was running and has exited.", old_thread_id);
539 ++exited_threads;
540 }
541 }
542
543 // Also add all the threads that are new since the last time we broke into
544 // the debugger.
545 for (const auto &thread_info : m_session_data->m_new_threads) {
546 new_thread_list.AddThread(thread_info.second);
547 ++new_size;
548 ++new_threads;
549 LLDB_LOGV(log, "Thread {0} is new since last update.", thread_info.first);
550 }
551
552 LLDB_LOG(log, "{0} new threads, {1} old threads, {2} exited threads.",
553 new_threads, continued_threads, exited_threads);
554
555 m_session_data->m_new_threads.clear();
556 m_session_data->m_exited_threads.clear();
557
558 return new_size > 0;
559}
560
562 StateType state = GetPrivateState();
563 switch (state) {
564 case eStateCrashed:
565 case eStateDetached:
566 case eStateUnloaded:
567 case eStateExited:
568 case eStateInvalid:
569 return false;
570 default:
571 return true;
572 }
573}
574
576 return HostInfo::GetArchitecture();
577}
578
580 size_t size, Status &error) {
581 size_t bytes_read = 0;
582 error = ProcessDebugger::ReadMemory(vm_addr, buf, size, bytes_read);
583 return bytes_read;
584}
585
586size_t ProcessWindows::DoWriteMemory(lldb::addr_t vm_addr, const void *buf,
587 size_t size, Status &error) {
588 size_t bytes_written = 0;
589 error = ProcessDebugger::WriteMemory(vm_addr, buf, size, bytes_written);
590 return bytes_written;
591}
592
593lldb::addr_t ProcessWindows::DoAllocateMemory(size_t size, uint32_t permissions,
594 Status &error) {
596 error = ProcessDebugger::AllocateMemory(size, permissions, vm_addr);
597 return vm_addr;
598}
599
602}
603
605 MemoryRegionInfo &info) {
606 return ProcessDebugger::GetMemoryRegionInfo(vm_addr, info);
607}
608
610 Target &target = GetTarget();
611 ObjectFile *obj_file = target.GetExecutableModule()->GetObjectFile();
612 Address addr = obj_file->GetImageInfoAddress(&target);
613 if (addr.IsValid())
614 return addr.GetLoadAddress(&target);
615 else
617}
618
620 if (m_dyld_up.get() == NULL)
623 return static_cast<DynamicLoaderWindowsDYLD *>(m_dyld_up.get());
624}
625
626void ProcessWindows::OnExitProcess(uint32_t exit_code) {
627 // No need to acquire the lock since m_session_data isn't accessed.
629 LLDB_LOG(log, "Process {0} exited with code {1}", GetID(), exit_code);
630
631 TargetSP target = CalculateTarget();
632 if (target) {
633 ModuleSP executable_module = target->GetExecutableModule();
634 ModuleList unloaded_modules;
635 unloaded_modules.Append(executable_module);
636 target->ModulesDidUnload(unloaded_modules, true);
637 }
638
639 SetProcessExitStatus(GetID(), true, 0, exit_code);
641
643}
644
646 DebuggerThreadSP debugger = m_session_data->m_debugger;
648 LLDB_LOG(log, "Debugger connected to process {0}. Image base = {1:x}",
649 debugger->GetProcess().GetProcessId(), image_base);
650
651 ModuleSP module;
652 // During attach, we won't have the executable module, so find it now.
653 const DWORD pid = debugger->GetProcess().GetProcessId();
654 const std::string file_name = GetProcessExecutableName(pid);
655 if (file_name.empty()) {
656 return;
657 }
658
659 FileSpec executable_file(file_name);
660 FileSystem::Instance().Resolve(executable_file);
661 ModuleSpec module_spec(executable_file);
663 module =
664 GetTarget().GetOrCreateModule(module_spec, true /* notify */, &error);
665 if (!module) {
666 return;
667 }
668
670
671 if (auto dyld = GetDynamicLoader())
672 dyld->OnLoadModule(module, ModuleSpec(), image_base);
673
674 // Add the main executable module to the list of pending module loads. We
675 // can't call GetTarget().ModulesDidLoad() here because we still haven't
676 // returned from DoLaunch() / DoAttach() yet so the target may not have set
677 // the process instance to `this` yet.
678 llvm::sys::ScopedLock lock(m_mutex);
679
680 const HostThread &host_main_thread = debugger->GetMainThread();
681 ThreadSP main_thread =
682 std::make_shared<TargetThreadWindows>(*this, host_main_thread);
683
684 tid_t id = host_main_thread.GetNativeThread().GetThreadId();
685 main_thread->SetID(id);
686
687 m_session_data->m_new_threads[id] = main_thread;
688}
689
692 const ExceptionRecord &record) {
694 llvm::sys::ScopedLock lock(m_mutex);
695
696 // FIXME: Without this check, occasionally when running the test suite there
697 // is
698 // an issue where m_session_data can be null. It's not clear how this could
699 // happen but it only surfaces while running the test suite. In order to
700 // properly diagnose this, we probably need to first figure allow the test
701 // suite to print out full lldb logs, and then add logging to the process
702 // plugin.
703 if (!m_session_data) {
704 LLDB_LOG(log,
705 "Debugger thread reported exception {0:x} at address {1:x}, "
706 "but there is no session.",
707 record.GetExceptionCode(), record.GetExceptionAddress());
708 return ExceptionResult::SendToApplication;
709 }
710
711 if (!first_chance) {
712 // Not any second chance exception is an application crash by definition.
713 // It may be an expression evaluation crash.
715 }
716
717 ExceptionResult result = ExceptionResult::SendToApplication;
718 switch (record.GetExceptionCode()) {
719 case EXCEPTION_BREAKPOINT:
720 // Handle breakpoints at the first chance.
721 result = ExceptionResult::BreakInDebugger;
722
723 if (!m_session_data->m_initial_stop_received) {
724 LLDB_LOG(
725 log,
726 "Hit loader breakpoint at address {0:x}, setting initial stop event.",
727 record.GetExceptionAddress());
728 m_session_data->m_initial_stop_received = true;
729 ::SetEvent(m_session_data->m_initial_stop_event);
730 } else {
731 LLDB_LOG(log, "Hit non-loader breakpoint at address {0:x}.",
732 record.GetExceptionAddress());
733 }
735 break;
736 case EXCEPTION_SINGLE_STEP:
737 result = ExceptionResult::BreakInDebugger;
739 break;
740 default:
741 LLDB_LOG(log,
742 "Debugger thread reported exception {0:x} at address {1:x} "
743 "(first_chance={2})",
744 record.GetExceptionCode(), record.GetExceptionAddress(),
745 first_chance);
746 // For non-breakpoints, give the application a chance to handle the
747 // exception first.
748 if (first_chance)
749 result = ExceptionResult::SendToApplication;
750 else
751 result = ExceptionResult::BreakInDebugger;
752 }
753
754 return result;
755}
756
758 llvm::sys::ScopedLock lock(m_mutex);
759
760 ThreadSP thread = std::make_shared<TargetThreadWindows>(*this, new_thread);
761
762 const HostNativeThread &native_new_thread = new_thread.GetNativeThread();
763 tid_t id = native_new_thread.GetThreadId();
764 thread->SetID(id);
765
766 m_session_data->m_new_threads[id] = thread;
767
768 for (const std::map<int, WatchpointInfo>::value_type &p : m_watchpoints) {
769 auto *reg_ctx = static_cast<RegisterContextWindows *>(
770 thread->GetRegisterContext().get());
771 reg_ctx->AddHardwareBreakpoint(p.second.slot_id, p.second.address,
772 p.second.size, p.second.read,
773 p.second.write);
774 }
775}
776
777void ProcessWindows::OnExitThread(lldb::tid_t thread_id, uint32_t exit_code) {
778 llvm::sys::ScopedLock lock(m_mutex);
779
780 // On a forced termination, we may get exit thread events after the session
781 // data has been cleaned up.
782 if (!m_session_data)
783 return;
784
785 // A thread may have started and exited before the debugger stopped allowing a
786 // refresh.
787 // Just remove it from the new threads list in that case.
788 auto iter = m_session_data->m_new_threads.find(thread_id);
789 if (iter != m_session_data->m_new_threads.end())
790 m_session_data->m_new_threads.erase(iter);
791 else
792 m_session_data->m_exited_threads.insert(thread_id);
793}
794
795void ProcessWindows::OnLoadDll(const ModuleSpec &module_spec,
796 lldb::addr_t module_addr) {
797 if (auto dyld = GetDynamicLoader())
798 dyld->OnLoadModule(nullptr, module_spec, module_addr);
799}
800
802 if (auto dyld = GetDynamicLoader())
803 dyld->OnUnloadModule(module_addr);
804}
805
806void ProcessWindows::OnDebugString(const std::string &string) {}
807
808void ProcessWindows::OnDebuggerError(const Status &error, uint32_t type) {
809 llvm::sys::ScopedLock lock(m_mutex);
811
812 if (m_session_data->m_initial_stop_received) {
813 // This happened while debugging. Do we shutdown the debugging session,
814 // try to continue, or do something else?
815 LLDB_LOG(log,
816 "Error {0} occurred during debugging. Unexpected behavior "
817 "may result. {1}",
818 error.GetError(), error);
819 } else {
820 // If we haven't actually launched the process yet, this was an error
821 // launching the process. Set the internal error and signal the initial
822 // stop event so that the DoLaunch method wakes up and returns a failure.
823 m_session_data->m_launch_error = error;
824 ::SetEvent(m_session_data->m_initial_stop_event);
825 LLDB_LOG(
826 log,
827 "Error {0} occurred launching the process before the initial stop. {1}",
828 error.GetError(), error);
829 return;
830 }
831}
832
833std::optional<uint32_t> ProcessWindows::GetWatchpointSlotCount() {
835}
836
839
840 if (wp_sp->IsEnabled()) {
841 wp_sp->SetEnabled(true, notify);
842 return error;
843 }
844
845 WatchpointInfo info;
846 for (info.slot_id = 0;
848 info.slot_id++)
850 break;
852 error.SetErrorStringWithFormat("Can't find free slot for watchpoint %i",
853 wp_sp->GetID());
854 return error;
855 }
856 info.address = wp_sp->GetLoadAddress();
857 info.size = wp_sp->GetByteSize();
858 info.read = wp_sp->WatchpointRead();
859 info.write = wp_sp->WatchpointWrite() || wp_sp->WatchpointModify();
860
861 for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) {
862 Thread *thread = m_thread_list.GetThreadAtIndex(i).get();
863 auto *reg_ctx = static_cast<RegisterContextWindows *>(
864 thread->GetRegisterContext().get());
865 if (!reg_ctx->AddHardwareBreakpoint(info.slot_id, info.address, info.size,
866 info.read, info.write)) {
867 error.SetErrorStringWithFormat(
868 "Can't enable watchpoint %i on thread 0x%llx", wp_sp->GetID(),
869 thread->GetID());
870 break;
871 }
872 }
873 if (error.Fail()) {
874 for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) {
875 Thread *thread = m_thread_list.GetThreadAtIndex(i).get();
876 auto *reg_ctx = static_cast<RegisterContextWindows *>(
877 thread->GetRegisterContext().get());
878 reg_ctx->RemoveHardwareBreakpoint(info.slot_id);
879 }
880 return error;
881 }
882
883 m_watchpoints[wp_sp->GetID()] = info;
884 m_watchpoint_ids[info.slot_id] = wp_sp->GetID();
885
886 wp_sp->SetEnabled(true, notify);
887
888 return error;
889}
890
893
894 if (!wp_sp->IsEnabled()) {
895 wp_sp->SetEnabled(false, notify);
896 return error;
897 }
898
899 auto it = m_watchpoints.find(wp_sp->GetID());
900 if (it == m_watchpoints.end()) {
901 error.SetErrorStringWithFormat("Info about watchpoint %i is not found",
902 wp_sp->GetID());
903 return error;
904 }
905
906 for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) {
907 Thread *thread = m_thread_list.GetThreadAtIndex(i).get();
908 auto *reg_ctx = static_cast<RegisterContextWindows *>(
909 thread->GetRegisterContext().get());
910 if (!reg_ctx->RemoveHardwareBreakpoint(it->second.slot_id)) {
911 error.SetErrorStringWithFormat(
912 "Can't disable watchpoint %i on thread 0x%llx", wp_sp->GetID(),
913 thread->GetID());
914 break;
915 }
916 }
917 if (error.Fail())
918 return error;
919
920 m_watchpoint_ids[it->second.slot_id] = LLDB_INVALID_BREAK_ID;
921 m_watchpoints.erase(it);
922
923 wp_sp->SetEnabled(false, notify);
924
925 return error;
926}
927} // 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:359
#define LLDB_LOGV(log,...)
Definition: Log.h:373
#define LLDB_PLUGIN_DEFINE_ADV(ClassName, PluginName)
Definition: PluginManager.h:26
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:460
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:68
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:341
StopPointSiteList< lldb_private::BreakpointSite > & GetBreakpointSiteList()
Definition: Process.cpp:1610
virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition: Process.cpp:1879
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:540
lldb::StateType GetPrivateState()
Definition: Process.cpp:1452
lldb::DynamicLoaderUP m_dyld_up
Definition: Process.h:3133
lldb::TargetSP CalculateTarget() override
Definition: Process.cpp:4464
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:1147
virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition: Process.cpp:1803
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
Definition: Process.h:545
void SetPrivateState(lldb::StateType state)
Definition: Process.cpp:1454
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition: Process.h:3107
Target & GetTarget()
Get the target object pointer for this module.
Definition: Process.h:1279
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:180
static lldb::StopInfoSP CreateStopReasonToTrace(Thread &thread)
Definition: StopInfo.cpp:1421
static lldb::StopInfoSP CreateStopReasonWithWatchpointID(Thread &thread, lldb::break_id_t watch_id, bool silently_continue=false)
Definition: StopInfo.cpp:1402
static lldb::StopInfoSP CreateStopReasonWithException(Thread &thread, const char *description)
Definition: StopInfo.cpp:1432
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:683
uint32_t GetSize(bool can_update=true)
Definition: ThreadList.cpp:82
bool SetSelectedThreadByID(lldb::tid_t tid, bool notify=false)
Definition: ThreadList.cpp:695
lldb::ThreadSP GetThreadAtIndex(uint32_t idx, bool can_update=true)
Definition: ThreadList.cpp:90
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.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition: Log.h:331
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:320
std::shared_ptr< lldb_private::Thread > ThreadSP
Definition: lldb-forward.h:445
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:386
uint64_t pid_t
Definition: lldb-types.h:83
std::shared_ptr< lldb_private::Watchpoint > WatchpointSP
Definition: lldb-forward.h:484
std::shared_ptr< lldb_private::Listener > ListenerSP
Definition: lldb-forward.h:365
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
Definition: lldb-forward.h:426
uint64_t addr_t
Definition: lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
Definition: lldb-forward.h:443
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
Definition: lldb-forward.h:391
uint64_t tid_t
Definition: lldb-types.h:84
std::shared_ptr< lldb_private::Module > ModuleSP
Definition: lldb-forward.h:370
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition: UserID.h:47