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"
47#include "ProcessWindowsLog.h"
48#include "TargetThreadWindows.h"
49
50using namespace lldb;
51using namespace lldb_private;
52
53LLDB_PLUGIN_DEFINE_ADV(ProcessWindows, ProcessWindowsCommon)
54
55namespace {
56std::string GetProcessExecutableName(HANDLE process_handle) {
57 std::vector<wchar_t> file_name;
58 DWORD file_name_size = MAX_PATH; // first guess, not an absolute limit
59 DWORD copied = 0;
60 do {
61 file_name_size *= 2;
62 file_name.resize(file_name_size);
63 copied = ::GetModuleFileNameExW(process_handle, NULL, file_name.data(),
64 file_name_size);
65 } while (copied >= file_name_size);
66 file_name.resize(copied);
67 std::string result;
68 llvm::convertWideToUTF8(file_name.data(), result);
69 return result;
70}
71
72std::string GetProcessExecutableName(DWORD pid) {
73 std::string file_name;
74 HANDLE process_handle =
75 ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
76 if (process_handle != NULL) {
77 file_name = GetProcessExecutableName(process_handle);
78 ::CloseHandle(process_handle);
79 }
80 return file_name;
81}
82} // anonymous namespace
83
84namespace lldb_private {
85
87 lldb::ListenerSP listener_sp,
88 const FileSpec *crash_file_path,
89 bool can_connect) {
90 if (crash_file_path)
91 return nullptr; // Cannot create a Windows process from a crash_file.
92 return ProcessSP(new ProcessWindows(target_sp, listener_sp));
93}
94
95static bool ShouldUseLLDBServer() {
96 llvm::StringRef use_lldb_server = ::getenv("LLDB_USE_LLDB_SERVER");
97 return use_lldb_server.equals_insensitive("on") ||
98 use_lldb_server.equals_insensitive("yes") ||
99 use_lldb_server.equals_insensitive("1") ||
100 use_lldb_server.equals_insensitive("true");
101}
102
104 if (!ShouldUseLLDBServer()) {
105 static llvm::once_flag g_once_flag;
106
107 llvm::call_once(g_once_flag, []() {
111 });
112 }
113}
114
116
118 return "Process plugin for Windows";
119}
120
121// Constructors and destructors.
122
124 lldb::ListenerSP listener_sp)
125 : lldb_private::Process(target_sp, listener_sp),
127 RegisterContextWindows::GetNumHardwareBreakpointSlots(),
129
131
133 if (bp_site->HardwareRequired())
134 return Status::FromErrorString("Hardware breakpoints are not supported.");
135
137 LLDB_LOG(log, "bp_site = {0:x}, id={1}, addr={2:x}", bp_site,
138 bp_site->GetID(), bp_site->GetLoadAddress());
139
141 if (!error.Success())
142 LLDB_LOG(log, "error: {0}", error);
143 return error;
144}
145
148 LLDB_LOG(log, "bp_site = {0:x}, id={1}, addr={2:x}", bp_site,
149 bp_site->GetID(), bp_site->GetLoadAddress());
150
152
153 if (!error.Success())
154 LLDB_LOG(log, "error: {0}", error);
155 return error;
156}
157
161 StateType private_state = GetPrivateState();
162 if (private_state != eStateExited && private_state != eStateDetached) {
163 if (!keep_stopped) {
164 // if the thread is suspended by lldb, we have to resume threads before
165 // detaching process. When we do after DetachProcess(), thread handles
166 // become invalid so we do before detach.
167 if (private_state == eStateStopped || private_state == eStateCrashed) {
168 LLDB_LOG(log, "process {0} is in state {1}. Resuming for detach...",
169 m_session_data->m_debugger->GetProcess().GetProcessId(),
171
172 LLDB_LOG(log, "resuming {0} threads for detach.",
173 m_thread_list.GetSize());
174
175 bool failed = false;
176 for (uint32_t i = 0; i < m_thread_list.GetSize(); ++i) {
177 auto thread = std::static_pointer_cast<TargetThreadWindows>(
178 m_thread_list.GetThreadAtIndex(i));
179 Status result = thread->DoResume();
180 if (result.Fail()) {
181 failed = true;
182 LLDB_LOG(log,
183 "Trying to resume thread at index {0}, but failed with "
184 "error {1}.",
185 i, result);
186 }
187 }
188
189 if (failed) {
190 error = Status::FromErrorString("Resuming Threads for Detach failed");
191 }
192 }
193 }
194
196 if (error.Success())
198 else
199 LLDB_LOG(log, "Detaching process error: {0}", error);
200 } else {
202 "error: process {0} in state = {1}, but "
203 "cannot detach it in this state.",
204 GetID(), private_state);
205 LLDB_LOG(log, "error: {0}", error);
206 }
207 return error;
208}
209
211 ProcessLaunchInfo &launch_info) {
213 DebugDelegateSP delegate(new LocalDebugDelegate(shared_from_this()));
214 error = LaunchProcess(launch_info, delegate);
215 if (error.Success())
216 SetID(launch_info.GetProcessID());
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
307 // The initial stop won't broadcast the state change event, so account for
308 // that here.
310 m_session_data->m_stop_at_entry)
312}
313
314static void
315DumpAdditionalExceptionInformation(llvm::raw_ostream &stream,
316 const ExceptionRecordSP &exception) {
317 // Decode additional exception information for specific exception types based
318 // on
319 // https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_exception_record
320
321 const int addr_min_width = 2 + 8; // "0x" + 4 address bytes
322
323 const std::vector<ULONG_PTR> &args = exception->GetExceptionArguments();
324 switch (exception->GetExceptionCode()) {
325 case EXCEPTION_ACCESS_VIOLATION: {
326 if (args.size() < 2)
327 break;
328
329 stream << ": ";
330 const int access_violation_code = args[0];
331 const lldb::addr_t access_violation_address = args[1];
332 switch (access_violation_code) {
333 case 0:
334 stream << "Access violation reading";
335 break;
336 case 1:
337 stream << "Access violation writing";
338 break;
339 case 8:
340 stream << "User-mode data execution prevention (DEP) violation at";
341 break;
342 default:
343 stream << "Unknown access violation (code " << access_violation_code
344 << ") at";
345 break;
346 }
347 stream << " location "
348 << llvm::format_hex(access_violation_address, addr_min_width);
349 break;
350 }
351 case EXCEPTION_IN_PAGE_ERROR: {
352 if (args.size() < 3)
353 break;
354
355 stream << ": ";
356 const int page_load_error_code = args[0];
357 const lldb::addr_t page_load_error_address = args[1];
358 const DWORD underlying_code = args[2];
359 switch (page_load_error_code) {
360 case 0:
361 stream << "In page error reading";
362 break;
363 case 1:
364 stream << "In page error writing";
365 break;
366 case 8:
367 stream << "User-mode data execution prevention (DEP) violation at";
368 break;
369 default:
370 stream << "Unknown page loading error (code " << page_load_error_code
371 << ") at";
372 break;
373 }
374 stream << " location "
375 << llvm::format_hex(page_load_error_address, addr_min_width)
376 << " (status code " << llvm::format_hex(underlying_code, 8) << ")";
377 break;
378 }
379 }
380}
381
384 llvm::sys::ScopedLock lock(m_mutex);
385
386 if (!m_session_data) {
387 LLDB_LOG(log, "no active session. Returning...");
388 return;
389 }
390
391 m_thread_list.RefreshStateAfterStop();
392
393 std::weak_ptr<ExceptionRecord> exception_record =
394 m_session_data->m_debugger->GetActiveException();
395 ExceptionRecordSP active_exception = exception_record.lock();
396 if (!active_exception) {
397 LLDB_LOG(log,
398 "there is no active exception in process {0}. Why is the "
399 "process stopped?",
400 m_session_data->m_debugger->GetProcess().GetProcessId());
401 return;
402 }
403
404 StopInfoSP stop_info;
405 m_thread_list.SetSelectedThreadByID(active_exception->GetThreadID());
406 ThreadSP stop_thread = m_thread_list.GetSelectedThread();
407 if (!stop_thread)
408 return;
409
410 RegisterContextSP register_context = stop_thread->GetRegisterContext();
411 uint64_t pc = register_context->GetPC();
412
413 // If we're at a BreakpointSite, mark this as an Unexecuted Breakpoint.
414 // We'll clear that state if we've actually executed the breakpoint.
415 BreakpointSiteSP site(GetBreakpointSiteList().FindByAddress(pc));
416 if (site && site->IsEnabled())
417 stop_thread->SetThreadStoppedAtUnexecutedBP(pc);
418
419 switch (active_exception->GetExceptionCode()) {
420 case EXCEPTION_SINGLE_STEP: {
421 auto *reg_ctx = static_cast<RegisterContextWindows *>(
422 stop_thread->GetRegisterContext().get());
423 uint32_t slot_id = reg_ctx->GetTriggeredHardwareBreakpointSlotId();
424 if (slot_id != LLDB_INVALID_INDEX32) {
425 int id = m_watchpoint_ids[slot_id];
426 LLDB_LOG(log,
427 "Single-stepped onto a watchpoint in process {0} at address "
428 "{1:x} with watchpoint {2}",
429 m_session_data->m_debugger->GetProcess().GetProcessId(), pc, id);
430
431 stop_info = StopInfo::CreateStopReasonWithWatchpointID(*stop_thread, id);
432 stop_thread->SetStopInfo(stop_info);
433
434 return;
435 }
436
437 LLDB_LOG(log, "single stepping thread {0}", stop_thread->GetID());
438 stop_info = StopInfo::CreateStopReasonToTrace(*stop_thread);
439 stop_thread->SetStopInfo(stop_info);
440
441 return;
442 }
443
444 case EXCEPTION_BREAKPOINT: {
445 int breakpoint_size = 1;
446 switch (GetTarget().GetArchitecture().GetMachine()) {
447 case llvm::Triple::aarch64:
448 breakpoint_size = 4;
449 break;
450
451 case llvm::Triple::arm:
452 case llvm::Triple::thumb:
453 breakpoint_size = 2;
454 break;
455
456 case llvm::Triple::x86:
457 case llvm::Triple::x86_64:
458 breakpoint_size = 1;
459 break;
460
461 default:
462 LLDB_LOG(log, "Unknown breakpoint size for architecture");
463 break;
464 }
465
466 // The current PC is AFTER the BP opcode, on all architectures.
467 pc = register_context->GetPC() - breakpoint_size;
468
470 if (site) {
471 LLDB_LOG(log,
472 "detected breakpoint in process {0} at address {1:x} with "
473 "breakpoint site {2}",
474 m_session_data->m_debugger->GetProcess().GetProcessId(), pc,
475 site->GetID());
476
477 stop_thread->SetThreadHitBreakpointSite();
478 if (site->ValidForThisThread(*stop_thread)) {
479 LLDB_LOG(log,
480 "Breakpoint site {0} is valid for this thread ({1:x}), "
481 "creating stop info.",
482 site->GetID(), stop_thread->GetID());
483
485 *stop_thread, site->GetID());
486 register_context->SetPC(pc);
487 } else {
488 LLDB_LOG(log,
489 "Breakpoint site {0} is not valid for this thread, "
490 "creating empty stop info.",
491 site->GetID());
492 }
493 stop_thread->SetStopInfo(stop_info);
494 return;
495 } else {
496 // The thread hit a hard-coded breakpoint like an `int 3` or
497 // `__debugbreak()`.
498 LLDB_LOG(log,
499 "No breakpoint site matches for this thread. __debugbreak()? "
500 "Creating stop info with the exception.");
501 // FALLTHROUGH: We'll treat this as a generic exception record in the
502 // default case.
503 [[fallthrough]];
504 }
505 }
506
507 default: {
508 std::string desc;
509 llvm::raw_string_ostream desc_stream(desc);
510 desc_stream << "Exception "
511 << llvm::format_hex(active_exception->GetExceptionCode(), 8)
512 << " encountered at address "
513 << llvm::format_hex(active_exception->GetExceptionAddress(), 8);
514 DumpAdditionalExceptionInformation(desc_stream, active_exception);
515
516 stop_info =
517 StopInfo::CreateStopReasonWithException(*stop_thread, desc.c_str());
518 stop_thread->SetStopInfo(stop_info);
519 LLDB_LOG(log, "{0}", desc);
520 return;
521 }
522 }
523}
524
526 bool plugin_specified_by_name) {
527 if (plugin_specified_by_name)
528 return true;
529
530 // For now we are just making sure the file exists for a given module
531 ModuleSP exe_module_sp(target_sp->GetExecutableModule());
532 if (exe_module_sp.get())
533 return FileSystem::Instance().Exists(exe_module_sp->GetFileSpec());
534 // However, if there is no executable module, we return true since we might
535 // be preparing to attach.
536 return true;
537}
538
540 ThreadList &new_thread_list) {
542 // Add all the threads that were previously running and for which we did not
543 // detect a thread exited event.
544 int new_size = 0;
545 int continued_threads = 0;
546 int exited_threads = 0;
547 int new_threads = 0;
548
549 for (ThreadSP old_thread : old_thread_list.Threads()) {
550 lldb::tid_t old_thread_id = old_thread->GetID();
551 auto exited_thread_iter =
552 m_session_data->m_exited_threads.find(old_thread_id);
553 if (exited_thread_iter == m_session_data->m_exited_threads.end()) {
554 new_thread_list.AddThread(old_thread);
555 ++new_size;
556 ++continued_threads;
557 LLDB_LOGV(log, "Thread {0} was running and is still running.",
558 old_thread_id);
559 } else {
560 LLDB_LOGV(log, "Thread {0} was running and has exited.", old_thread_id);
561 ++exited_threads;
562 }
563 }
564
565 // Also add all the threads that are new since the last time we broke into
566 // the debugger.
567 for (const auto &thread_info : m_session_data->m_new_threads) {
568 new_thread_list.AddThread(thread_info.second);
569 ++new_size;
570 ++new_threads;
571 LLDB_LOGV(log, "Thread {0} is new since last update.", thread_info.first);
572 }
573
574 LLDB_LOG(log, "{0} new threads, {1} old threads, {2} exited threads.",
575 new_threads, continued_threads, exited_threads);
576
577 m_session_data->m_new_threads.clear();
578 m_session_data->m_exited_threads.clear();
579
580 return new_size > 0;
581}
582
584 StateType state = GetPrivateState();
585 switch (state) {
586 case eStateCrashed:
587 case eStateDetached:
588 case eStateUnloaded:
589 case eStateExited:
590 case eStateInvalid:
591 return false;
592 default:
593 return true;
594 }
595}
596
598 return HostInfo::GetArchitecture();
599}
600
602 size_t size, Status &error) {
603 size_t bytes_read = 0;
604 error = ProcessDebugger::ReadMemory(vm_addr, buf, size, bytes_read);
605 return bytes_read;
606}
607
608size_t ProcessWindows::DoWriteMemory(lldb::addr_t vm_addr, const void *buf,
609 size_t size, Status &error) {
610 size_t bytes_written = 0;
611 error = ProcessDebugger::WriteMemory(vm_addr, buf, size, bytes_written);
612 return bytes_written;
613}
614
615lldb::addr_t ProcessWindows::DoAllocateMemory(size_t size, uint32_t permissions,
616 Status &error) {
618 error = ProcessDebugger::AllocateMemory(size, permissions, vm_addr);
619 return vm_addr;
620}
621
625
630
632 Target &target = GetTarget();
633 ObjectFile *obj_file = target.GetExecutableModule()->GetObjectFile();
634 Address addr = obj_file->GetImageInfoAddress(&target);
635 if (addr.IsValid())
636 return addr.GetLoadAddress(&target);
637 else
639}
640
647
648void ProcessWindows::OnExitProcess(uint32_t exit_code) {
649 // No need to acquire the lock since m_session_data isn't accessed.
651 LLDB_LOG(log, "Process {0} exited with code {1}", GetID(), exit_code);
652
653 TargetSP target = CalculateTarget();
654 target->GetProcessLaunchInfo().GetPTY().Close();
655 if (target) {
656 ModuleSP executable_module = target->GetExecutableModule();
657 ModuleList unloaded_modules;
658 unloaded_modules.Append(executable_module);
659 target->ModulesDidUnload(unloaded_modules, true);
660 }
661
662 SetExitStatus(exit_code, /*exit_string=*/"");
664
666}
667
669 DebuggerThreadSP debugger = m_session_data->m_debugger;
671 LLDB_LOG(log, "Debugger connected to process {0}. Image base = {1:x}",
672 debugger->GetProcess().GetProcessId(), image_base);
673
674 ModuleSP module;
675 // During attach, we won't have the executable module, so find it now.
676 const DWORD pid = debugger->GetProcess().GetProcessId();
677 const std::string file_name = GetProcessExecutableName(pid);
678 if (file_name.empty()) {
679 return;
680 }
681
682 FileSpec executable_file(file_name);
683 FileSystem::Instance().Resolve(executable_file);
684 ModuleSpec module_spec(executable_file);
686 module =
687 GetTarget().GetOrCreateModule(module_spec, true /* notify */, &error);
688 if (!module) {
689 return;
690 }
691
693
694 if (auto dyld = GetDynamicLoader())
695 dyld->OnLoadModule(module, ModuleSpec(), image_base);
696
697 // Add the main executable module to the list of pending module loads. We
698 // can't call GetTarget().ModulesDidLoad() here because we still haven't
699 // returned from DoLaunch() / DoAttach() yet so the target may not have set
700 // the process instance to `this` yet.
701 llvm::sys::ScopedLock lock(m_mutex);
702
703 const HostThread &host_main_thread = debugger->GetMainThread();
704 ThreadSP main_thread =
705 std::make_shared<TargetThreadWindows>(*this, host_main_thread);
706
707 tid_t id = host_main_thread.GetNativeThread().GetThreadId();
708 main_thread->SetID(id);
709
710 m_session_data->m_new_threads[id] = main_thread;
711}
712
715 const ExceptionRecord &record) {
717 llvm::sys::ScopedLock lock(m_mutex);
718
719 // FIXME: Without this check, occasionally when running the test suite there
720 // is
721 // an issue where m_session_data can be null. It's not clear how this could
722 // happen but it only surfaces while running the test suite. In order to
723 // properly diagnose this, we probably need to first figure allow the test
724 // suite to print out full lldb logs, and then add logging to the process
725 // plugin.
726 if (!m_session_data) {
727 LLDB_LOG(log,
728 "Debugger thread reported exception {0:x} at address {1:x}, "
729 "but there is no session.",
730 record.GetExceptionCode(), record.GetExceptionAddress());
732 }
733
734 if (!first_chance) {
735 // Not any second chance exception is an application crash by definition.
736 // It may be an expression evaluation crash.
738 }
739
741 switch (record.GetExceptionCode()) {
742 case EXCEPTION_BREAKPOINT:
743 // Handle breakpoints at the first chance.
745
746 if (!m_session_data->m_initial_stop_received) {
747 LLDB_LOG(
748 log,
749 "Hit loader breakpoint at address {0:x}, setting initial stop event.",
750 record.GetExceptionAddress());
751 m_session_data->m_initial_stop_received = true;
752 ::SetEvent(m_session_data->m_initial_stop_event);
753 } else {
754 LLDB_LOG(log, "Hit non-loader breakpoint at address {0:x}.",
755 record.GetExceptionAddress());
756 }
758 break;
759 case EXCEPTION_SINGLE_STEP:
762 break;
763 default:
764 LLDB_LOG(log,
765 "Debugger thread reported exception {0:x} at address {1:x} "
766 "(first_chance={2})",
767 record.GetExceptionCode(), record.GetExceptionAddress(),
768 first_chance);
769 // For non-breakpoints, give the application a chance to handle the
770 // exception first.
771 if (first_chance)
773 else
775 }
776
777 return result;
778}
779
781 llvm::sys::ScopedLock lock(m_mutex);
782
783 ThreadSP thread = std::make_shared<TargetThreadWindows>(*this, new_thread);
784
785 const HostNativeThread &native_new_thread = new_thread.GetNativeThread();
786 tid_t id = native_new_thread.GetThreadId();
787 thread->SetID(id);
788
789 m_session_data->m_new_threads[id] = thread;
790
791 for (const std::map<int, WatchpointInfo>::value_type &p : m_watchpoints) {
792 auto *reg_ctx = static_cast<RegisterContextWindows *>(
793 thread->GetRegisterContext().get());
794 reg_ctx->AddHardwareBreakpoint(p.second.slot_id, p.second.address,
795 p.second.size, p.second.read,
796 p.second.write);
797 }
798}
799
800void ProcessWindows::OnExitThread(lldb::tid_t thread_id, uint32_t exit_code) {
801 llvm::sys::ScopedLock lock(m_mutex);
802
803 // On a forced termination, we may get exit thread events after the session
804 // data has been cleaned up.
805 if (!m_session_data)
806 return;
807
808 // A thread may have started and exited before the debugger stopped allowing a
809 // refresh.
810 // Just remove it from the new threads list in that case.
811 auto iter = m_session_data->m_new_threads.find(thread_id);
812 if (iter != m_session_data->m_new_threads.end())
813 m_session_data->m_new_threads.erase(iter);
814 else
815 m_session_data->m_exited_threads.insert(thread_id);
816}
817
818void ProcessWindows::OnLoadDll(const ModuleSpec &module_spec,
819 lldb::addr_t module_addr) {
820 if (auto dyld = GetDynamicLoader())
821 dyld->OnLoadModule(nullptr, module_spec, module_addr);
822}
823
825 if (auto dyld = GetDynamicLoader())
826 dyld->OnUnloadModule(module_addr);
827}
828
829void ProcessWindows::OnDebugString(const std::string &string) {}
830
831void ProcessWindows::OnDebuggerError(const Status &error, uint32_t type) {
832 llvm::sys::ScopedLock lock(m_mutex);
834
835 if (m_session_data->m_initial_stop_received) {
836 // This happened while debugging. Do we shutdown the debugging session,
837 // try to continue, or do something else?
838 LLDB_LOG(log,
839 "Error {0} occurred during debugging. Unexpected behavior "
840 "may result. {1}",
841 error.GetError(), error);
842 } else {
843 // If we haven't actually launched the process yet, this was an error
844 // launching the process. Set the internal error and signal the initial
845 // stop event so that the DoLaunch method wakes up and returns a failure.
846 m_session_data->m_launch_error = error.Clone();
847 ::SetEvent(m_session_data->m_initial_stop_event);
848 LLDB_LOG(
849 log,
850 "Error {0} occurred launching the process before the initial stop. {1}",
851 error.GetError(), error);
852 return;
853 }
854}
855
859
862
863 if (wp_sp->IsEnabled()) {
864 wp_sp->SetEnabled(true, notify);
865 return error;
866 }
867
868 WatchpointInfo info;
869 for (info.slot_id = 0;
871 info.slot_id++)
873 break;
876 "Can't find free slot for watchpoint %i", wp_sp->GetID());
877 return error;
878 }
879 info.address = wp_sp->GetLoadAddress();
880 info.size = wp_sp->GetByteSize();
881 info.read = wp_sp->WatchpointRead();
882 info.write = wp_sp->WatchpointWrite() || wp_sp->WatchpointModify();
883
884 for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) {
885 Thread *thread = m_thread_list.GetThreadAtIndex(i).get();
886 auto *reg_ctx = static_cast<RegisterContextWindows *>(
887 thread->GetRegisterContext().get());
888 if (!reg_ctx->AddHardwareBreakpoint(info.slot_id, info.address, info.size,
889 info.read, info.write)) {
891 "Can't enable watchpoint %i on thread 0x%llx", wp_sp->GetID(),
892 thread->GetID());
893 break;
894 }
895 }
896 if (error.Fail()) {
897 for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) {
898 Thread *thread = m_thread_list.GetThreadAtIndex(i).get();
899 auto *reg_ctx = static_cast<RegisterContextWindows *>(
900 thread->GetRegisterContext().get());
901 reg_ctx->RemoveHardwareBreakpoint(info.slot_id);
902 }
903 return error;
904 }
905
906 m_watchpoints[wp_sp->GetID()] = info;
907 m_watchpoint_ids[info.slot_id] = wp_sp->GetID();
908
909 wp_sp->SetEnabled(true, notify);
910
911 return error;
912}
913
916
917 if (!wp_sp->IsEnabled()) {
918 wp_sp->SetEnabled(false, notify);
919 return error;
920 }
921
922 auto it = m_watchpoints.find(wp_sp->GetID());
923 if (it == m_watchpoints.end()) {
925 "Info about watchpoint %i is not found", wp_sp->GetID());
926 return error;
927 }
928
929 for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) {
930 Thread *thread = m_thread_list.GetThreadAtIndex(i).get();
931 auto *reg_ctx = static_cast<RegisterContextWindows *>(
932 thread->GetRegisterContext().get());
933 if (!reg_ctx->RemoveHardwareBreakpoint(it->second.slot_id)) {
935 "Can't disable watchpoint %i on thread 0x%llx", wp_sp->GetID(),
936 thread->GetID());
937 break;
938 }
939 }
940 if (error.Fail())
941 return error;
942
943 m_watchpoint_ids[it->second.slot_id] = LLDB_INVALID_BREAK_ID;
944 m_watchpoints.erase(it);
945
946 wp_sp->SetEnabled(false, notify);
947
948 return error;
949}
950
952public:
954 : IOHandler(process->GetTarget().GetDebugger(),
956 m_process(process),
957 m_read_file(GetInputFD(), File::eOpenOptionReadOnly, false),
958 m_write_file(conpty_input) {
959 m_pipe.CreateNew();
960 }
961
962 ~IOHandlerProcessSTDIOWindows() override = default;
963
964 void SetIsRunning(bool running) {
965 std::lock_guard<std::mutex> guard(m_mutex);
966 SetIsDone(!running);
967 m_is_running = running;
968 }
969
970 void Run() override {
971 if (!m_read_file.IsValid() || m_write_file == INVALID_HANDLE_VALUE ||
972 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
973 SetIsDone(true);
974 return;
975 }
976
977 SetIsDone(false);
978 SetIsRunning(true);
979
980 HANDLE hStdin = (HANDLE)_get_osfhandle(m_read_file.GetDescriptor());
981 HANDLE hInterrupt = (HANDLE)_get_osfhandle(m_pipe.GetReadFileDescriptor());
982 HANDLE waitHandles[2] = {hStdin, hInterrupt};
983
984 while (true) {
985 {
986 std::lock_guard<std::mutex> guard(m_mutex);
987 if (GetIsDone())
988 goto exit_loop;
989 }
990
991 DWORD result = WaitForMultipleObjects(2, waitHandles, FALSE, INFINITE);
992 switch (result) {
993 case WAIT_FAILED:
994 goto exit_loop;
995 case WAIT_OBJECT_0: {
996 char ch = 0;
997 DWORD read = 0;
998 if (!ReadFile(hStdin, &ch, 1, &read, nullptr) || read != 1)
999 goto exit_loop;
1000
1001 DWORD written = 0;
1002 if (!WriteFile(m_write_file, &ch, 1, &written, nullptr) || written != 1)
1003 goto exit_loop;
1004 break;
1005 }
1006 case WAIT_OBJECT_0 + 1: {
1007 char ch = 0;
1008 DWORD read = 0;
1009 if (!ReadFile(hInterrupt, &ch, 1, &read, nullptr) || read != 1)
1010 goto exit_loop;
1011
1012 if (ch == eControlOpQuit)
1013 goto exit_loop;
1014 if (ch == eControlOpInterrupt &&
1015 StateIsRunningState(m_process->GetState()))
1016 m_process->SendAsyncInterrupt();
1017 break;
1018 }
1019 default:
1020 goto exit_loop;
1021 }
1022 }
1023
1024 exit_loop:;
1025 SetIsRunning(false);
1026 }
1027
1028 void Cancel() override {
1029 std::lock_guard<std::mutex> guard(m_mutex);
1030 SetIsDone(true);
1031 if (m_is_running) {
1032 char ch = eControlOpQuit;
1033 if (llvm::Error err = m_pipe.Write(&ch, 1).takeError()) {
1034 LLDB_LOG_ERROR(GetLog(LLDBLog::Process), std::move(err),
1035 "Pipe write failed: {0}");
1036 }
1037 }
1038 }
1039
1040 bool Interrupt() override {
1041 if (m_active) {
1042 char ch = eControlOpInterrupt;
1043 return !errorToBool(m_pipe.Write(&ch, 1).takeError());
1044 }
1045 if (StateIsRunningState(m_process->GetState())) {
1046 m_process->SendAsyncInterrupt();
1047 return true;
1048 }
1049 return false;
1050 }
1051
1052 void GotEOF() override {}
1053
1054private:
1056 NativeFile m_read_file; // Read from this file (usually actual STDIN for LLDB
1058 INVALID_HANDLE_VALUE; // Write to this file (usually the primary pty for
1059 // getting io to debuggee)
1061 std::mutex m_mutex;
1062 bool m_is_running = false;
1063
1064 enum ControlOp : char {
1067 };
1068};
1069
1071 const std::shared_ptr<PseudoConsole> &pty) {
1072 m_stdio_communication.SetConnection(
1073 std::make_unique<ConnectionGenericFile>(pty->GetSTDOUTHandle(), false));
1074 if (m_stdio_communication.IsConnected()) {
1075 m_stdio_communication.SetReadThreadBytesReceivedCallback(
1077 m_stdio_communication.StartReadThread();
1078
1079 // Now read thread is set up, set up input reader.
1080 {
1081 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
1083 m_process_input_reader = std::make_shared<IOHandlerProcessSTDIOWindows>(
1084 this, pty->GetSTDINHandle());
1085 }
1086 }
1087}
1088} // 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:392
#define LLDB_LOGV(log,...)
Definition Log.h:383
#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: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:57
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()
An abstract base class for files.
Definition File.h:36
HostNativeThread & GetNativeThread()
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:104
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:467
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.
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.
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.
void SetPseudoConsoleHandle(const std::shared_ptr< PseudoConsole > &pty) override
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
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:3256
std::mutex m_process_input_reader_mutex
Definition Process.h:3257
StopPointSiteList< lldb_private::BreakpointSite > & GetBreakpointSiteList()
Definition Process.cpp:1558
virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1831
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:553
Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
Construct with a shared pointer to a target, and the Process listener.
Definition Process.cpp:426
lldb::StateType GetPrivateState()
Definition Process.cpp:1400
lldb::DynamicLoaderUP m_dyld_up
Definition Process.h:3244
lldb::TargetSP CalculateTarget() override
Definition Process.cpp:4536
virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1751
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
Definition Process.h:558
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:1022
static void STDIOReadThreadBytesReceived(void *baton, const void *src, size_t src_len)
Definition Process.cpp:4670
void SetPrivateState(lldb::StateType state)
Definition Process.cpp:1402
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition Process.h:3217
ThreadedCommunication m_stdio_communication
Definition Process.h:3258
friend class ThreadList
Definition Process.h:361
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1267
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:294
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:1524
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
Definition Target.cpp:1575
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
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
PipePosix Pipe
Definition Pipe.h:20
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