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/IOHandler.h"
17#include "lldb/Core/Module.h"
20#include "lldb/Core/Section.h"
22#include "lldb/Host/HostInfo.h"
25#include "lldb/Host/Pipe.h"
33#include "lldb/Target/Target.h"
35#include "lldb/Utility/Log.h"
36#include "lldb/Utility/State.h"
37
38#include "llvm/Support/ConvertUTF.h"
39#include "llvm/Support/Format.h"
40#include "llvm/Support/Threading.h"
41#include "llvm/Support/raw_ostream.h"
42
43#include "DebuggerThread.h"
44#include "ExceptionRecord.h"
45#include "ForwardDecl.h"
46#include "LocalDebugDelegate.h"
48#include "ProcessWindowsLog.h"
49#include "TargetThreadWindows.h"
50
51using namespace lldb;
52using namespace lldb_private;
53
54LLDB_PLUGIN_DEFINE_ADV(ProcessWindows, ProcessWindowsCommon)
55
56namespace {
57std::string GetProcessExecutableName(HANDLE process_handle) {
58 std::vector<wchar_t> file_name;
59 DWORD file_name_size = MAX_PATH; // first guess, not an absolute limit
60 DWORD copied = 0;
61 do {
62 file_name_size *= 2;
63 file_name.resize(file_name_size);
64 copied = ::GetModuleFileNameExW(process_handle, NULL, file_name.data(),
65 file_name_size);
66 } while (copied >= file_name_size);
67 file_name.resize(copied);
68 std::string result;
69 llvm::convertWideToUTF8(file_name.data(), result);
70 return result;
71}
72
73std::string GetProcessExecutableName(DWORD pid) {
74 std::string file_name;
75 HANDLE process_handle =
76 ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
77 if (process_handle != NULL) {
78 file_name = GetProcessExecutableName(process_handle);
79 ::CloseHandle(process_handle);
80 }
81 return file_name;
82}
83} // anonymous namespace
84
85namespace lldb_private {
86
88 lldb::ListenerSP listener_sp,
89 const FileSpec *crash_file_path,
90 bool can_connect) {
91 if (crash_file_path)
92 return nullptr; // Cannot create a Windows process from a crash_file.
93 return ProcessSP(new ProcessWindows(target_sp, listener_sp));
94}
95
96static bool ShouldUseLLDBServer() {
97 llvm::StringRef use_lldb_server = ::getenv("LLDB_USE_LLDB_SERVER");
98 return use_lldb_server.equals_insensitive("on") ||
99 use_lldb_server.equals_insensitive("yes") ||
100 use_lldb_server.equals_insensitive("1") ||
101 use_lldb_server.equals_insensitive("true");
102}
103
110
115
117 return "Process plugin for Windows";
118}
119
120// Constructors and destructors.
121
123 lldb::ListenerSP listener_sp)
124 : lldb_private::Process(target_sp, listener_sp),
126 RegisterContextWindows::GetNumHardwareBreakpointSlots(),
128
130
132 if (bp_site->HardwareRequired())
133 return Status::FromErrorString("Hardware breakpoints are not supported.");
134
136 LLDB_LOG(log, "bp_site = {0:x}, id={1}, addr={2:x}", bp_site,
137 bp_site->GetID(), bp_site->GetLoadAddress());
138
140 if (!error.Success())
141 LLDB_LOG(log, "error: {0}", error);
142 return error;
143}
144
147 LLDB_LOG(log, "bp_site = {0:x}, id={1}, addr={2:x}", bp_site,
148 bp_site->GetID(), bp_site->GetLoadAddress());
149
151
152 if (!error.Success())
153 LLDB_LOG(log, "error: {0}", error);
154 return error;
155}
156
160 StateType private_state = GetPrivateState();
161 if (private_state != eStateExited && private_state != eStateDetached) {
162 if (!keep_stopped) {
163 // if the thread is suspended by lldb, we have to resume threads before
164 // detaching process. When we do after DetachProcess(), thread handles
165 // become invalid so we do before detach.
166 if (private_state == eStateStopped || private_state == eStateCrashed) {
167 LLDB_LOG(log, "process {0} is in state {1}. Resuming for detach...",
168 m_session_data->m_debugger->GetProcess().GetProcessId(),
170
171 LLDB_LOG(log, "resuming {0} threads for detach.",
172 m_thread_list.GetSize());
173
174 bool failed = false;
175 for (uint32_t i = 0; i < m_thread_list.GetSize(); ++i) {
176 auto thread = std::static_pointer_cast<TargetThreadWindows>(
177 m_thread_list.GetThreadAtIndex(i));
178 Status result = thread->DoResume();
179 if (result.Fail()) {
180 failed = true;
181 LLDB_LOG(log,
182 "Trying to resume thread at index {0}, but failed with "
183 "error {1}.",
184 i, result);
185 }
186 }
187
188 if (failed) {
189 error = Status::FromErrorString("Resuming Threads for Detach failed");
190 }
191 }
192 }
193
195 if (error.Success())
197 else
198 LLDB_LOG(log, "Detaching process error: {0}", error);
199 } else {
201 "error: process {0} in state = {1}, but "
202 "cannot detach it in this state.",
203 GetID(), private_state);
204 LLDB_LOG(log, "error: {0}", error);
205 }
206 return error;
207}
208
210 ProcessLaunchInfo &launch_info) {
212 DebugDelegateSP delegate(new LocalDebugDelegate(shared_from_this()));
213 error = LaunchProcess(launch_info, delegate);
214 if (error.Success())
215 SetID(launch_info.GetProcessID());
216 m_pty = launch_info.TakePTY();
217 return error;
218}
219
220Status
222 const ProcessAttachInfo &attach_info) {
223 DebugDelegateSP delegate(new LocalDebugDelegate(shared_from_this()));
224 Status error = AttachProcess(pid, attach_info, delegate);
225 if (error.Success())
227 return error;
228}
229
232 llvm::sys::ScopedLock lock(m_mutex);
233
234 if (direction == RunDirection::eRunReverse) {
236 "{0} does not support reverse execution of processes", GetPluginName());
237 }
238
240
241 StateType private_state = GetPrivateState();
242 if (private_state == eStateStopped || private_state == eStateCrashed) {
243 LLDB_LOG(log, "process {0} is in state {1}. Resuming...",
244 m_session_data->m_debugger->GetProcess().GetProcessId(),
246
247 LLDB_LOG(log, "resuming {0} threads.", m_thread_list.GetSize());
248
249 bool failed = false;
250 for (uint32_t i = 0; i < m_thread_list.GetSize(); ++i) {
251 auto thread = std::static_pointer_cast<TargetThreadWindows>(
252 m_thread_list.GetThreadAtIndex(i));
253 Status result = thread->DoResume();
254 if (result.Fail()) {
255 failed = true;
256 LLDB_LOG(
257 log,
258 "Trying to resume thread at index {0}, but failed with error {1}.",
259 i, result);
260 }
261 }
262
263 if (failed) {
264 error = Status::FromErrorString("ProcessWindows::DoResume failed");
265 } else {
267 }
268
269 ExceptionRecordSP active_exception =
270 m_session_data->m_debugger->GetActiveException().lock();
271 if (active_exception) {
272 // Resume the process and continue processing debug events. Mask the
273 // exception so that from the process's view, there is no indication that
274 // anything happened.
275 m_session_data->m_debugger->ContinueAsyncException(
277 }
278 } else {
279 LLDB_LOG(log, "error: process {0} is in state {1}. Returning...",
280 m_session_data->m_debugger->GetProcess().GetProcessId(),
282 }
283 return error;
284}
285
287 StateType private_state = GetPrivateState();
288 return DestroyProcess(private_state);
289}
290
291Status ProcessWindows::DoHalt(bool &caused_stop) {
292 StateType state = GetPrivateState();
293 if (state != eStateStopped)
294 return HaltProcess(caused_stop);
295 caused_stop = false;
296 return Status();
297}
298
300 ArchSpec arch_spec;
301 DidAttach(arch_spec);
302}
303
305 llvm::sys::ScopedLock lock(m_mutex);
306
308
309 // The initial stop won't broadcast the state change event, so account for
310 // that here.
312 m_session_data->m_stop_at_entry)
314}
315
316static void
317DumpAdditionalExceptionInformation(llvm::raw_ostream &stream,
318 const ExceptionRecordSP &exception) {
319 // Decode additional exception information for specific exception types based
320 // on
321 // https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_exception_record
322
323 const int addr_min_width = 2 + 8; // "0x" + 4 address bytes
324
325 const std::vector<ULONG_PTR> &args = exception->GetExceptionArguments();
326 switch (exception->GetExceptionCode()) {
327 case EXCEPTION_ACCESS_VIOLATION: {
328 if (args.size() < 2)
329 break;
330
331 stream << ": ";
332 const int access_violation_code = args[0];
333 const lldb::addr_t access_violation_address = args[1];
334 switch (access_violation_code) {
335 case 0:
336 stream << "Access violation reading";
337 break;
338 case 1:
339 stream << "Access violation writing";
340 break;
341 case 8:
342 stream << "User-mode data execution prevention (DEP) violation at";
343 break;
344 default:
345 stream << "Unknown access violation (code " << access_violation_code
346 << ") at";
347 break;
348 }
349 stream << " location "
350 << llvm::format_hex(access_violation_address, addr_min_width);
351 break;
352 }
353 case EXCEPTION_IN_PAGE_ERROR: {
354 if (args.size() < 3)
355 break;
356
357 stream << ": ";
358 const int page_load_error_code = args[0];
359 const lldb::addr_t page_load_error_address = args[1];
360 const DWORD underlying_code = args[2];
361 switch (page_load_error_code) {
362 case 0:
363 stream << "In page error reading";
364 break;
365 case 1:
366 stream << "In page error writing";
367 break;
368 case 8:
369 stream << "User-mode data execution prevention (DEP) violation at";
370 break;
371 default:
372 stream << "Unknown page loading error (code " << page_load_error_code
373 << ") at";
374 break;
375 }
376 stream << " location "
377 << llvm::format_hex(page_load_error_address, addr_min_width)
378 << " (status code " << llvm::format_hex(underlying_code, 8) << ")";
379 break;
380 }
381 }
382}
383
386 llvm::sys::ScopedLock lock(m_mutex);
387
388 if (!m_session_data) {
389 LLDB_LOG(log, "no active session. Returning...");
390 return;
391 }
392
393 m_thread_list.RefreshStateAfterStop();
394
395 std::weak_ptr<ExceptionRecord> exception_record =
396 m_session_data->m_debugger->GetActiveException();
397 ExceptionRecordSP active_exception = exception_record.lock();
398 if (!active_exception) {
399 LLDB_LOG(log,
400 "there is no active exception in process {0}. Why is the "
401 "process stopped?",
402 m_session_data->m_debugger->GetProcess().GetProcessId());
403 return;
404 }
405
406 StopInfoSP stop_info;
407 m_thread_list.SetSelectedThreadByID(active_exception->GetThreadID());
408 ThreadSP stop_thread = m_thread_list.GetSelectedThread();
409 if (!stop_thread)
410 return;
411
412 RegisterContextSP register_context = stop_thread->GetRegisterContext();
413 uint64_t pc = register_context->GetPC();
414
415 // If we're at a BreakpointSite, mark this as an Unexecuted Breakpoint.
416 // We'll clear that state if we've actually executed the breakpoint.
417 BreakpointSiteSP site(GetBreakpointSiteList().FindByAddress(pc));
418 if (site && site->IsEnabled())
419 stop_thread->SetThreadStoppedAtUnexecutedBP(pc);
420
421 switch (active_exception->GetExceptionCode()) {
422 case EXCEPTION_SINGLE_STEP: {
423 auto *reg_ctx = static_cast<RegisterContextWindows *>(
424 stop_thread->GetRegisterContext().get());
425 uint32_t slot_id = reg_ctx->GetTriggeredHardwareBreakpointSlotId();
426 if (slot_id != LLDB_INVALID_INDEX32) {
427 int id = m_watchpoint_ids[slot_id];
428 LLDB_LOG(log,
429 "Single-stepped onto a watchpoint in process {0} at address "
430 "{1:x} with watchpoint {2}",
431 m_session_data->m_debugger->GetProcess().GetProcessId(), pc, id);
432
433 stop_info = StopInfo::CreateStopReasonWithWatchpointID(*stop_thread, id);
434 stop_thread->SetStopInfo(stop_info);
435
436 return;
437 }
438
439 LLDB_LOG(log, "single stepping thread {0}", stop_thread->GetID());
440 stop_info = StopInfo::CreateStopReasonToTrace(*stop_thread);
441 stop_thread->SetStopInfo(stop_info);
442
443 return;
444 }
445
446 case EXCEPTION_BREAKPOINT: {
447 int breakpoint_size = 1;
448 switch (GetTarget().GetArchitecture().GetMachine()) {
449 case llvm::Triple::aarch64:
450 breakpoint_size = 4;
451 break;
452
453 case llvm::Triple::arm:
454 case llvm::Triple::thumb:
455 breakpoint_size = 2;
456 break;
457
458 case llvm::Triple::x86:
459 case llvm::Triple::x86_64:
460 breakpoint_size = 1;
461 break;
462
463 default:
464 LLDB_LOG(log, "Unknown breakpoint size for architecture");
465 break;
466 }
467
468 // The current PC is AFTER the BP opcode, on all architectures.
469 pc = register_context->GetPC() - breakpoint_size;
470
472 if (site) {
473 LLDB_LOG(log,
474 "detected breakpoint in process {0} at address {1:x} with "
475 "breakpoint site {2}",
476 m_session_data->m_debugger->GetProcess().GetProcessId(), pc,
477 site->GetID());
478
479 stop_thread->SetThreadHitBreakpointSite();
480 if (site->ValidForThisThread(*stop_thread)) {
481 LLDB_LOG(log,
482 "Breakpoint site {0} is valid for this thread ({1:x}), "
483 "creating stop info.",
484 site->GetID(), stop_thread->GetID());
485
487 *stop_thread, site->GetID());
488 register_context->SetPC(pc);
489 } else {
490 LLDB_LOG(log,
491 "Breakpoint site {0} is not valid for this thread, "
492 "creating empty stop info.",
493 site->GetID());
494 }
495 stop_thread->SetStopInfo(stop_info);
496 return;
497 } else {
498 // The thread hit a hard-coded breakpoint like an `int 3` or
499 // `__debugbreak()`.
500 LLDB_LOG(log,
501 "No breakpoint site matches for this thread. __debugbreak()? "
502 "Creating stop info with the exception.");
503 // FALLTHROUGH: We'll treat this as a generic exception record in the
504 // default case.
505 [[fallthrough]];
506 }
507 }
508
509 default: {
510 std::string desc;
511 llvm::raw_string_ostream desc_stream(desc);
512 desc_stream << "Exception "
513 << llvm::format_hex(active_exception->GetExceptionCode(), 8)
514 << " encountered at address "
515 << llvm::format_hex(active_exception->GetExceptionAddress(), 8);
516 DumpAdditionalExceptionInformation(desc_stream, active_exception);
517
518 stop_info =
519 StopInfo::CreateStopReasonWithException(*stop_thread, desc.c_str());
520 stop_thread->SetStopInfo(stop_info);
521 LLDB_LOG(log, "{0}", desc);
522 return;
523 }
524 }
525}
526
528 bool plugin_specified_by_name) {
529 if (plugin_specified_by_name)
530 return true;
531
532 // For now we are just making sure the file exists for a given module
533 ModuleSP exe_module_sp(target_sp->GetExecutableModule());
534 if (exe_module_sp.get())
535 return FileSystem::Instance().Exists(exe_module_sp->GetFileSpec());
536 // However, if there is no executable module, we return true since we might
537 // be preparing to attach.
538 return true;
539}
540
542 ThreadList &new_thread_list) {
544 // Add all the threads that were previously running and for which we did not
545 // detect a thread exited event.
546 int new_size = 0;
547 int continued_threads = 0;
548 int exited_threads = 0;
549 int new_threads = 0;
550
551 for (ThreadSP old_thread : old_thread_list.Threads()) {
552 lldb::tid_t old_thread_id = old_thread->GetID();
553 auto exited_thread_iter =
554 m_session_data->m_exited_threads.find(old_thread_id);
555 if (exited_thread_iter == m_session_data->m_exited_threads.end()) {
556 new_thread_list.AddThread(old_thread);
557 ++new_size;
558 ++continued_threads;
559 LLDB_LOG_VERBOSE(log, "Thread {0} was running and is still running.",
560 old_thread_id);
561 } else {
562 LLDB_LOG_VERBOSE(log, "Thread {0} was running and has exited.",
563 old_thread_id);
564 ++exited_threads;
565 }
566 }
567
568 // Also add all the threads that are new since the last time we broke into
569 // the debugger.
570 for (const auto &thread_info : m_session_data->m_new_threads) {
571 new_thread_list.AddThread(thread_info.second);
572 ++new_size;
573 ++new_threads;
574 LLDB_LOG_VERBOSE(log, "Thread {0} is new since last update.",
575 thread_info.first);
576 }
577
578 LLDB_LOG(log, "{0} new threads, {1} old threads, {2} exited threads.",
579 new_threads, continued_threads, exited_threads);
580
581 m_session_data->m_new_threads.clear();
582 m_session_data->m_exited_threads.clear();
583
584 return new_size > 0;
585}
586
588 StateType state = GetPrivateState();
589 switch (state) {
590 case eStateCrashed:
591 case eStateDetached:
592 case eStateUnloaded:
593 case eStateExited:
594 case eStateInvalid:
595 return false;
596 default:
597 return true;
598 }
599}
600
602 return HostInfo::GetArchitecture();
603}
604
606 size_t size, Status &error) {
607 size_t bytes_read = 0;
608 error = ProcessDebugger::ReadMemory(vm_addr, buf, size, bytes_read);
609 return bytes_read;
610}
611
612size_t ProcessWindows::DoWriteMemory(lldb::addr_t vm_addr, const void *buf,
613 size_t size, Status &error) {
614 size_t bytes_written = 0;
615 error = ProcessDebugger::WriteMemory(vm_addr, buf, size, bytes_written);
616 return bytes_written;
617}
618
619lldb::addr_t ProcessWindows::DoAllocateMemory(size_t size, uint32_t permissions,
620 Status &error) {
622 error = ProcessDebugger::AllocateMemory(size, permissions, vm_addr);
623 return vm_addr;
624}
625
629
634
636 Target &target = GetTarget();
637 ObjectFile *obj_file = target.GetExecutableModule()->GetObjectFile();
638 Address addr = obj_file->GetImageInfoAddress(&target);
639 if (addr.IsValid())
640 return addr.GetLoadAddress(&target);
641 else
643}
644
651
652void ProcessWindows::OnExitProcess(uint32_t exit_code) {
653 // No need to acquire the lock since m_session_data isn't accessed.
655 LLDB_LOG(log, "Process {0} exited with code {1}", GetID(), exit_code);
656
657 if (m_pty) {
658 m_pty->SetStopping(true);
659 m_stdio_communication.InterruptRead();
660 m_pty->Close();
661 }
662
663 TargetSP target = CalculateTarget();
664 if (target) {
665 ModuleSP executable_module = target->GetExecutableModule();
666 ModuleList unloaded_modules;
667 unloaded_modules.Append(executable_module);
668 target->ModulesDidUnload(unloaded_modules, true);
669 }
670
671 SetExitStatus(exit_code, /*exit_string=*/"");
673
675}
676
678 DebuggerThreadSP debugger = m_session_data->m_debugger;
680 LLDB_LOG(log, "Debugger connected to process {0}. Image base = {1:x}",
681 debugger->GetProcess().GetProcessId(), image_base);
682
683 ModuleSP module;
684 // During attach, we won't have the executable module, so find it now.
685 const DWORD pid = debugger->GetProcess().GetProcessId();
686 const std::string file_name = GetProcessExecutableName(pid);
687 if (file_name.empty()) {
688 return;
689 }
690
691 FileSpec executable_file(file_name);
692 FileSystem::Instance().Resolve(executable_file);
693 ModuleSpec module_spec(executable_file);
695 module =
696 GetTarget().GetOrCreateModule(module_spec, true /* notify */, &error);
697 if (!module) {
698 return;
699 }
700
702
703 if (auto dyld = GetDynamicLoader())
704 dyld->OnLoadModule(module, ModuleSpec(), image_base);
705
706 // Add the main executable module to the list of pending module loads. We
707 // can't call GetTarget().ModulesDidLoad() here because we still haven't
708 // returned from DoLaunch() / DoAttach() yet so the target may not have set
709 // the process instance to `this` yet.
710 llvm::sys::ScopedLock lock(m_mutex);
711
712 const HostThread &host_main_thread = debugger->GetMainThread();
713 ThreadSP main_thread =
714 std::make_shared<TargetThreadWindows>(*this, host_main_thread);
715
716 tid_t id = host_main_thread.GetNativeThread().GetThreadId();
717 main_thread->SetID(id);
718
719 m_session_data->m_new_threads[id] = main_thread;
720}
721
724 const ExceptionRecord &record) {
726 llvm::sys::ScopedLock lock(m_mutex);
727
728 // FIXME: Without this check, occasionally when running the test suite there
729 // is
730 // an issue where m_session_data can be null. It's not clear how this could
731 // happen but it only surfaces while running the test suite. In order to
732 // properly diagnose this, we probably need to first figure allow the test
733 // suite to print out full lldb logs, and then add logging to the process
734 // plugin.
735 if (!m_session_data) {
736 LLDB_LOG(log,
737 "Debugger thread reported exception {0:x} at address {1:x}, "
738 "but there is no session.",
739 record.GetExceptionCode(), record.GetExceptionAddress());
741 }
742
743 if (!first_chance) {
744 // Not any second chance exception is an application crash by definition.
745 // It may be an expression evaluation crash.
747 }
748
750 switch (record.GetExceptionCode()) {
751 case EXCEPTION_BREAKPOINT:
752 // Handle breakpoints at the first chance.
754
755 if (!m_session_data->m_initial_stop_received) {
756 LLDB_LOG(
757 log,
758 "Hit loader breakpoint at address {0:x}, setting initial stop event.",
759 record.GetExceptionAddress());
760 m_session_data->m_initial_stop_received = true;
761 ::SetEvent(m_session_data->m_initial_stop_event);
762 } else {
763 LLDB_LOG(log, "Hit non-loader breakpoint at address {0:x}.",
764 record.GetExceptionAddress());
765 }
767 break;
768 case EXCEPTION_SINGLE_STEP:
771 break;
772 default:
773 LLDB_LOG(log,
774 "Debugger thread reported exception {0:x} at address {1:x} "
775 "(first_chance={2})",
776 record.GetExceptionCode(), record.GetExceptionAddress(),
777 first_chance);
778 // For non-breakpoints, give the application a chance to handle the
779 // exception first.
780 if (first_chance)
782 else
784 }
785
786 return result;
787}
788
790 llvm::sys::ScopedLock lock(m_mutex);
791
792 ThreadSP thread = std::make_shared<TargetThreadWindows>(*this, new_thread);
793
794 const HostNativeThread &native_new_thread = new_thread.GetNativeThread();
795 tid_t id = native_new_thread.GetThreadId();
796 thread->SetID(id);
797
798 m_session_data->m_new_threads[id] = thread;
799
800 for (const std::map<int, WatchpointInfo>::value_type &p : m_watchpoints) {
801 auto *reg_ctx = static_cast<RegisterContextWindows *>(
802 thread->GetRegisterContext().get());
803 reg_ctx->AddHardwareBreakpoint(p.second.slot_id, p.second.address,
804 p.second.size, p.second.read,
805 p.second.write);
806 }
807}
808
809void ProcessWindows::OnExitThread(lldb::tid_t thread_id, uint32_t exit_code) {
810 llvm::sys::ScopedLock lock(m_mutex);
811
812 // On a forced termination, we may get exit thread events after the session
813 // data has been cleaned up.
814 if (!m_session_data)
815 return;
816
817 // A thread may have started and exited before the debugger stopped allowing a
818 // refresh.
819 // Just remove it from the new threads list in that case.
820 auto iter = m_session_data->m_new_threads.find(thread_id);
821 if (iter != m_session_data->m_new_threads.end())
822 m_session_data->m_new_threads.erase(iter);
823 else
824 m_session_data->m_exited_threads.insert(thread_id);
825}
826
827void ProcessWindows::OnLoadDll(const ModuleSpec &module_spec,
828 lldb::addr_t module_addr) {
829 if (auto dyld = GetDynamicLoader())
830 dyld->OnLoadModule(nullptr, module_spec, module_addr);
831}
832
834 if (auto dyld = GetDynamicLoader())
835 dyld->OnUnloadModule(module_addr);
836}
837
838void ProcessWindows::OnDebugString(const std::string &string) {}
839
840void ProcessWindows::OnDebuggerError(const Status &error, uint32_t type) {
841 llvm::sys::ScopedLock lock(m_mutex);
843
844 if (m_session_data->m_initial_stop_received) {
845 // This happened while debugging. Do we shutdown the debugging session,
846 // try to continue, or do something else?
847 LLDB_LOG(log,
848 "Error {0} occurred during debugging. Unexpected behavior "
849 "may result. {1}",
850 error.GetError(), error);
851 } else {
852 // If we haven't actually launched the process yet, this was an error
853 // launching the process. Set the internal error and signal the initial
854 // stop event so that the DoLaunch method wakes up and returns a failure.
855 m_session_data->m_launch_error = error.Clone();
856 ::SetEvent(m_session_data->m_initial_stop_event);
857 LLDB_LOG(
858 log,
859 "Error {0} occurred launching the process before the initial stop. {1}",
860 error.GetError(), error);
861 return;
862 }
863}
864
868
869std::optional<DWORD> ProcessWindows::GetActiveExceptionCode() const {
870 if (!m_session_data || !m_session_data->m_debugger)
871 return std::nullopt;
872 auto exc = m_session_data->m_debugger->GetActiveException().lock();
873 if (!exc)
874 return std::nullopt;
875 return exc->GetExceptionCode();
876}
877
880
881 if (wp_sp->IsEnabled()) {
882 wp_sp->SetEnabled(true, notify);
883 return error;
884 }
885
886 WatchpointInfo info;
887 for (info.slot_id = 0;
889 info.slot_id++)
891 break;
894 "Can't find free slot for watchpoint %i", wp_sp->GetID());
895 return error;
896 }
897 info.address = wp_sp->GetLoadAddress();
898 info.size = wp_sp->GetByteSize();
899 info.read = wp_sp->WatchpointRead();
900 info.write = wp_sp->WatchpointWrite() || wp_sp->WatchpointModify();
901
902 for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) {
903 Thread *thread = m_thread_list.GetThreadAtIndex(i).get();
904 auto *reg_ctx = static_cast<RegisterContextWindows *>(
905 thread->GetRegisterContext().get());
906 if (!reg_ctx->AddHardwareBreakpoint(info.slot_id, info.address, info.size,
907 info.read, info.write)) {
909 "Can't enable watchpoint %i on thread 0x%llx", wp_sp->GetID(),
910 thread->GetID());
911 break;
912 }
913 }
914 if (error.Fail()) {
915 for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) {
916 Thread *thread = m_thread_list.GetThreadAtIndex(i).get();
917 auto *reg_ctx = static_cast<RegisterContextWindows *>(
918 thread->GetRegisterContext().get());
919 reg_ctx->RemoveHardwareBreakpoint(info.slot_id);
920 }
921 return error;
922 }
923
924 m_watchpoints[wp_sp->GetID()] = info;
925 m_watchpoint_ids[info.slot_id] = wp_sp->GetID();
926
927 wp_sp->SetEnabled(true, notify);
928
929 return error;
930}
931
934
935 if (!wp_sp->IsEnabled()) {
936 wp_sp->SetEnabled(false, notify);
937 return error;
938 }
939
940 auto it = m_watchpoints.find(wp_sp->GetID());
941 if (it == m_watchpoints.end()) {
943 "Info about watchpoint %i is not found", wp_sp->GetID());
944 return error;
945 }
946
947 for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) {
948 Thread *thread = m_thread_list.GetThreadAtIndex(i).get();
949 auto *reg_ctx = static_cast<RegisterContextWindows *>(
950 thread->GetRegisterContext().get());
951 if (!reg_ctx->RemoveHardwareBreakpoint(it->second.slot_id)) {
953 "Can't disable watchpoint %i on thread 0x%llx", wp_sp->GetID(),
954 thread->GetID());
955 break;
956 }
957 }
958 if (error.Fail())
959 return error;
960
961 m_watchpoint_ids[it->second.slot_id] = LLDB_INVALID_BREAK_ID;
962 m_watchpoints.erase(it);
963
964 wp_sp->SetEnabled(false, notify);
965
966 return error;
967}
968
970public:
972 : IOHandler(process->GetTarget().GetDebugger(),
974 m_process(process),
975 m_read_file(GetInputFD(), File::eOpenOptionReadOnly, false),
976 m_write_file(conpty_input),
978 CreateEvent(/*lpEventAttributes=*/NULL, /*bManualReset=*/FALSE,
979 /*bInitialState=*/FALSE, /*lpName=*/NULL)) {}
980
982 if (m_interrupt_event != INVALID_HANDLE_VALUE)
983 ::CloseHandle(m_interrupt_event);
984 }
985
986 void SetIsRunning(bool running) {
987 std::lock_guard<std::mutex> guard(m_mutex);
988 SetIsDone(!running);
989 m_is_running = running;
990 }
991
992 /// Peek the console for input. If it has any, drain the pipe until text input
993 /// is found or the pipe is empty.
994 ///
995 /// \param hStdin
996 /// The handle to the standard input's pipe.
997 ///
998 /// \return
999 /// true if the pipe has text input.
1000 llvm::Expected<bool> ConsoleHasTextInput(const HANDLE hStdin) {
1001 // Check if there are already characters buffered. Pressing enter counts as
1002 // 2 characters '\r\n' and only one of them is a keyDown event.
1003 DWORD bytesAvailable = 0;
1004 if (PeekNamedPipe(hStdin, NULL, 0, NULL, &bytesAvailable, NULL)) {
1005 if (bytesAvailable > 0)
1006 return true;
1007 }
1008
1009 while (true) {
1010 INPUT_RECORD inputRecord;
1011 DWORD numRead = 0;
1012 if (!PeekConsoleInput(hStdin, &inputRecord, 1, &numRead))
1013 return llvm::createStringError("Failed to peek standard input.");
1014
1015 if (numRead == 0)
1016 return false;
1017
1018 if (inputRecord.EventType == KEY_EVENT &&
1019 inputRecord.Event.KeyEvent.bKeyDown &&
1020 inputRecord.Event.KeyEvent.uChar.AsciiChar != 0)
1021 return true;
1022
1023 if (!ReadConsoleInput(hStdin, &inputRecord, 1, &numRead))
1024 return llvm::createStringError("Failed to read standard input.");
1025 }
1026 }
1027
1028 void Run() override {
1029 if (!m_read_file.IsValid() || m_write_file == INVALID_HANDLE_VALUE) {
1030 SetIsDone(true);
1031 return;
1032 }
1033
1034 SetIsDone(false);
1035 SetIsRunning(true);
1036
1037 HANDLE hStdin = m_read_file.GetWaitableHandle();
1038 HANDLE waitHandles[2] = {hStdin, m_interrupt_event};
1039
1040 DWORD consoleMode;
1041 bool isConsole = GetConsoleMode(hStdin, &consoleMode) != 0;
1042 // With ENABLE_LINE_INPUT, ReadFile returns only when a carriage return is
1043 // read. This will block lldb in ReadFile until the user hits enter. Save
1044 // the previous console mode to restore it later and remove
1045 // ENABLE_LINE_INPUT.
1046 DWORD oldConsoleMode = consoleMode;
1047 SetConsoleMode(hStdin,
1048 consoleMode & ~ENABLE_LINE_INPUT & ~ENABLE_ECHO_INPUT);
1049
1050 while (true) {
1051 {
1052 std::lock_guard<std::mutex> guard(m_mutex);
1053 if (GetIsDone())
1054 goto exit_loop;
1055 }
1056
1057 DWORD result = WaitForMultipleObjects(2, waitHandles, FALSE, INFINITE);
1058 switch (result) {
1059 case WAIT_FAILED:
1060 goto exit_loop;
1061 case WAIT_OBJECT_0: {
1062 if (isConsole) {
1063 auto hasInputOrErr = ConsoleHasTextInput(hStdin);
1064 if (!hasInputOrErr) {
1066 LLDB_LOG_ERROR(log, hasInputOrErr.takeError(),
1067 "failed to process debuggee's IO: {0}");
1068 goto exit_loop;
1069 }
1070
1071 // If no text input is ready, go back to waiting.
1072 if (!*hasInputOrErr)
1073 continue;
1074 }
1075
1076 char ch = 0;
1077 DWORD read = 0;
1078 if (!ReadFile(hStdin, &ch, 1, &read, nullptr) || read != 1)
1079 goto exit_loop;
1080
1081 DWORD written = 0;
1082 if (!WriteFile(m_write_file, &ch, 1, &written, nullptr) || written != 1)
1083 goto exit_loop;
1084 break;
1085 }
1086 case WAIT_OBJECT_0 + 1: {
1087 ControlOp op = m_pending_op.exchange(eControlOpNone);
1088 if (op == eControlOpQuit)
1089 goto exit_loop;
1090 if (op == eControlOpInterrupt &&
1091 StateIsRunningState(m_process->GetState()))
1092 m_process->SendAsyncInterrupt();
1093 break;
1094 }
1095 default:
1096 goto exit_loop;
1097 }
1098 }
1099
1100 exit_loop:;
1101 SetIsRunning(false);
1102 SetIsDone(true);
1103 SetConsoleMode(hStdin, oldConsoleMode);
1104 }
1105
1106 void Cancel() override {
1107 std::lock_guard<std::mutex> guard(m_mutex);
1108 SetIsDone(true);
1109 if (m_is_running) {
1111 ::SetEvent(m_interrupt_event);
1112 }
1113 }
1114
1115 bool Interrupt() override {
1116 if (m_active) {
1118 ::SetEvent(m_interrupt_event);
1119 return true;
1120 }
1121 if (StateIsRunningState(m_process->GetState())) {
1122 m_process->SendAsyncInterrupt();
1123 return true;
1124 }
1125 return false;
1126 }
1127
1128 void GotEOF() override {}
1129
1130private:
1136
1138 /// Read from this file (usually actual STDIN for LLDB)
1140 /// Write to this file (usually the primary pty for getting io to debuggee)
1141 HANDLE m_write_file = INVALID_HANDLE_VALUE;
1142 HANDLE m_interrupt_event = INVALID_HANDLE_VALUE;
1143 std::atomic<ControlOp> m_pending_op{eControlOpNone};
1144 std::mutex m_mutex;
1145 bool m_is_running = false;
1146};
1147
1149 if (m_pty == nullptr)
1150 return;
1151 m_stdio_communication.SetConnection(
1152 std::make_unique<ConnectionConPTY>(m_pty));
1153 if (m_stdio_communication.IsConnected()) {
1154 m_stdio_communication.SetReadThreadBytesReceivedCallback(
1156 m_stdio_communication.StartReadThread();
1157
1158 // Now read thread is set up, set up input reader.
1159 {
1160 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
1162 m_process_input_reader = std::make_shared<IOHandlerProcessSTDIOWindows>(
1163 this, m_pty->GetSTDINHandle());
1164 }
1165 }
1166}
1167} // namespace lldb_private
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:369
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:399
#define LLDB_LOG_VERBOSE(log,...)
Definition Log.h:376
#define LLDB_PLUGIN_DEFINE_ADV(ClassName, PluginName)
void * HANDLE
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:301
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
An architecture specification class.
Definition ArchSpec.h:32
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:57
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
An abstract base class for files.
Definition File.h:36
HostNativeThread & GetNativeThread()
NativeFile m_read_file
Read from this file (usually actual STDIN for LLDB)
llvm::Expected< bool > ConsoleHasTextInput(const HANDLE hStdin)
Peek the console for input.
HANDLE m_write_file
Write to this file (usually the primary pty for getting io to debuggee)
IOHandlerProcessSTDIOWindows(Process *process, HANDLE conpty_input)
Debugger & GetDebugger()
Definition IOHandler.h:130
IOHandler(Debugger &debugger, IOHandler::Type type)
Definition IOHandler.cpp:55
void SetIsDone(bool b)
Definition IOHandler.h:81
A collection class for Module objects.
Definition ModuleList.h:125
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
A class that describes an executable image and its associated object and symbol files.
Definition Module.h:90
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
virtual lldb_private::Address GetImageInfoAddress(Target *target)
Similar to Process::GetImageInfoAddress().
Definition ObjectFile.h:442
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(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
std::shared_ptr< PTY > TakePTY()
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.
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.
std::shared_ptr< PTY > m_pty
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.
Status DoResume(lldb::RunDirection direction) override
Resumes all of a process's threads as configured using the Thread run control functions.
void OnUnloadDll(lldb::addr_t module_addr) override
DynamicLoaderWindowsDYLD * GetDynamicLoader() override
Get the dynamic loader plug-in for this process.
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.
llvm::StringRef GetPluginName() override
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
std::optional< DWORD > GetActiveExceptionCode() const
Returns the exception code of the active (current) debug exception, or std::nullopt if there is no ac...
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
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:354
lldb::IOHandlerSP m_process_input_reader
Definition Process.h:3411
std::mutex m_process_input_reader_mutex
Definition Process.h:3412
StopPointSiteList< lldb_private::BreakpointSite > & GetBreakpointSiteList()
Definition Process.cpp:1531
virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1805
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
Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
Construct with a shared pointer to a target, and the Process listener.
Definition Process.cpp:425
lldb::StateType GetPrivateState() const
Definition Process.h:3321
lldb::DynamicLoaderUP m_dyld_up
Definition Process.h:3399
lldb::TargetSP CalculateTarget() override
Definition Process.cpp:4607
virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1725
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
Definition Process.h:542
friend class Target
Definition Process.h:360
virtual bool SetExitStatus(int exit_status, llvm::StringRef exit_string)
Set accessor for the process exit status (return code).
Definition Process.cpp:1018
static void STDIOReadThreadBytesReceived(void *baton, const void *src, size_t src_len)
Definition Process.cpp:4741
void SetPrivateState(lldb::StateType state)
Definition Process.cpp:1372
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition Process.h:3372
ThreadedCommunication m_stdio_communication
Definition Process.h:3413
friend class ThreadList
Definition Process.h:361
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1250
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:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static lldb::StopInfoSP CreateStopReasonToTrace(Thread &thread)
static lldb::StopInfoSP CreateStopReasonWithWatchpointID(Thread &thread, lldb::break_id_t watch_id, bool silently_continue=false)
static lldb::StopInfoSP CreateStopReasonWithException(Thread &thread, const char *description)
static lldb::StopInfoSP CreateStopReasonWithBreakpointSiteID(Thread &thread, lldb::break_id_t break_id)
StopPointSiteSP FindByAddress(lldb::addr_t addr)
Returns a shared pointer to the site at address addr.
lldb::break_id_t GetID() const
virtual lldb::addr_t GetLoadAddress() const
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1525
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
Definition Target.cpp:1571
void AddThread(const lldb::ThreadSP &thread_sp)
virtual ThreadIterable Threads()
#define LLDB_INVALID_BREAK_ID
#define LLDB_INVALID_INDEX32
#define LLDB_INVALID_ADDRESS
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:332
void RegisterMSVCRTCFrameRecognizer(ProcessWindows &process)
Registers the MSVC run-time check failure frame recognizer with the target.
std::shared_ptr< ExceptionRecord > ExceptionRecordSP
Definition ForwardDecl.h:37
HostThreadPosix HostNativeThread
bool StateIsRunningState(lldb::StateType state)
Check if a state represents a state where the process or thread is running.
Definition State.cpp:68
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()
std::shared_ptr< lldb_private::BreakpointSite > BreakpointSiteSP
RunDirection
Execution directions.
std::shared_ptr< lldb_private::Thread > ThreadSP
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
uint64_t pid_t
Definition lldb-types.h:83
std::shared_ptr< lldb_private::Watchpoint > WatchpointSP
std::shared_ptr< lldb_private::Listener > ListenerSP
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
uint64_t tid_t
Definition lldb-types.h:84
std::shared_ptr< lldb_private::Module > ModuleSP