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 <dbghelp.h>
14#include <excpt.h>
15#include <psapi.h>
16
18#include "lldb/Core/Address.h"
19#include "lldb/Core/IOHandler.h"
20#include "lldb/Core/Module.h"
23#include "lldb/Core/Section.h"
24#include "lldb/Host/Config.h"
26#include "lldb/Host/HostInfo.h"
29#include "lldb/Host/Pipe.h"
38#include "lldb/Target/Target.h"
40#include "lldb/Utility/Log.h"
41#include "lldb/Utility/State.h"
42
43#include "llvm/Support/ConvertUTF.h"
44#include "llvm/Support/ErrorExtras.h"
45#include "llvm/Support/Format.h"
46#include "llvm/Support/Threading.h"
47#include "llvm/Support/raw_ostream.h"
48
49#include "DebuggerThread.h"
50#include "ExceptionRecord.h"
51#include "ForwardDecl.h"
52#include "LocalDebugDelegate.h"
53#include "ProcessWindowsLog.h"
54#include "TargetThreadWindows.h"
55
56using namespace lldb;
57using namespace lldb_private;
58
59LLDB_PLUGIN_DEFINE_ADV(ProcessWindows, ProcessWindowsCommon)
60
61namespace {
62std::string GetProcessExecutableName(HANDLE process_handle) {
63 std::vector<wchar_t> file_name;
64 DWORD file_name_size = MAX_PATH; // first guess, not an absolute limit
65 DWORD copied = 0;
66 do {
67 file_name_size *= 2;
68 file_name.resize(file_name_size);
69 copied = ::GetModuleFileNameExW(process_handle, nullptr, file_name.data(),
70 file_name_size);
71 } while (copied >= file_name_size);
72 file_name.resize(copied);
73 std::string result;
74 llvm::convertWideToUTF8(file_name.data(), result);
75 return result;
76}
77
78std::string GetProcessExecutableName(DWORD pid) {
79 std::string file_name;
80 HANDLE process_handle =
81 ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
82 if (process_handle != nullptr) {
83 file_name = GetProcessExecutableName(process_handle);
84 ::CloseHandle(process_handle);
85 }
86 return file_name;
87}
88} // anonymous namespace
89
90namespace lldb_private {
91
93 lldb::ListenerSP listener_sp,
94 const FileSpec *crash_file_path,
95 bool can_connect) {
96 if (crash_file_path)
97 return nullptr; // Cannot create a Windows process from a crash_file.
98 return ProcessSP(new ProcessWindows(target_sp, listener_sp));
99}
100
101static bool ShouldUseLLDBServer() {
102 if (const char *env = ::getenv("LLDB_USE_LLDB_SERVER")) {
103 llvm::StringRef use_lldb_server(env);
104 return use_lldb_server.equals_insensitive("on") ||
105 use_lldb_server.equals_insensitive("yes") ||
106 use_lldb_server.equals_insensitive("1") ||
107 use_lldb_server.equals_insensitive("true");
108 }
109 return LLDB_ENABLE_LIBXML2;
110}
111
118
123
125 return "Process plugin for Windows";
126}
127
128// Constructors and destructors.
129
131 lldb::ListenerSP listener_sp)
132 : lldb_private::Process(target_sp, listener_sp),
134 RegisterContextWindows::GetNumHardwareBreakpointSlots(),
136
138
140 if (bp_site->HardwareRequired())
141 return Status::FromErrorString("Hardware breakpoints are not supported.");
142
144 LLDB_LOG(log, "bp_site = {0:x}, id={1}, addr={2:x}", bp_site,
145 bp_site->GetID(), bp_site->GetLoadAddress());
146
148 if (!error.Success())
149 LLDB_LOG(log, "error: {0}", error);
150 return error;
151}
152
155 LLDB_LOG(log, "bp_site = {0:x}, id={1}, addr={2:x}", bp_site,
156 bp_site->GetID(), bp_site->GetLoadAddress());
157
159
160 if (!error.Success())
161 LLDB_LOG(log, "error: {0}", error);
162 return error;
163}
164
168 StateType private_state = GetPrivateState();
169 if (private_state != eStateExited && private_state != eStateDetached) {
170 if (!keep_stopped) {
171 // if the thread is suspended by lldb, we have to resume threads before
172 // detaching process. When we do after DetachProcess(), thread handles
173 // become invalid so we do before detach.
174 if (private_state == eStateStopped || private_state == eStateCrashed) {
175 LLDB_LOG(log, "process {0} is in state {1}. Resuming for detach...",
176 m_session_data->m_debugger->GetProcess().GetProcessId(),
178
179 LLDB_LOG(log, "resuming {0} threads for detach.",
180 m_thread_list.GetSize());
181
182 bool failed = false;
183 for (uint32_t i = 0; i < m_thread_list.GetSize(); ++i) {
184 auto thread = std::static_pointer_cast<TargetThreadWindows>(
185 m_thread_list.GetThreadAtIndex(i));
186 Status result = thread->DoResume();
187 if (result.Fail()) {
188 failed = true;
189 LLDB_LOG(log,
190 "Trying to resume thread at index {0}, but failed with "
191 "error {1}.",
192 i, result);
193 }
194 }
195
196 if (failed) {
197 error = Status::FromErrorString("Resuming Threads for Detach failed");
198 }
199 }
200 }
201
203 if (error.Success())
205 else
206 LLDB_LOG(log, "Detaching process error: {0}", error);
207 } else {
209 "error: process {0} in state = {1}, but "
210 "cannot detach it in this state.",
211 GetID(), private_state);
212 LLDB_LOG(log, "error: {0}", error);
213 }
214 return error;
215}
216
218 ProcessLaunchInfo &launch_info) {
220 DebugDelegateSP delegate(new LocalDebugDelegate(shared_from_this()));
221 error = LaunchProcess(launch_info, delegate);
222 if (error.Success())
223 SetID(launch_info.GetProcessID());
224 m_pty = launch_info.TakePTY();
225 return error;
226}
227
228Status
230 const ProcessAttachInfo &attach_info) {
231 DebugDelegateSP delegate(new LocalDebugDelegate(shared_from_this()));
232 Status error = AttachProcess(pid, attach_info, delegate);
233 if (error.Success())
235
237
238 return error;
239}
240
243 llvm::sys::ScopedLock lock(m_mutex);
244
245 if (direction == RunDirection::eRunReverse) {
247 "{0} does not support reverse execution of processes", GetPluginName());
248 }
249
251
252 StateType private_state = GetPrivateState();
253 if (private_state == eStateStopped || private_state == eStateCrashed) {
254 LLDB_LOG(log, "process {0} is in state {1}. Resuming...",
255 m_session_data->m_debugger->GetProcess().GetProcessId(),
257
258 LLDB_LOG(log, "resuming {0} threads.", m_thread_list.GetSize());
259
260 bool failed = false;
261 for (uint32_t i = 0; i < m_thread_list.GetSize(); ++i) {
262 auto thread = std::static_pointer_cast<TargetThreadWindows>(
263 m_thread_list.GetThreadAtIndex(i));
264 Status result = thread->DoResume();
265 if (result.Fail()) {
266 failed = true;
267 LLDB_LOG(
268 log,
269 "Trying to resume thread at index {0}, but failed with error {1}.",
270 i, result);
271 }
272 }
273
274 if (failed) {
275 error = Status::FromErrorString("ProcessWindows::DoResume failed");
276 } else {
278 }
279
280 ExceptionRecordSP active_exception =
281 m_session_data->m_debugger->GetActiveException().lock();
282 if (active_exception) {
283 // Resume the process and continue processing debug events. Mask the
284 // exception so that from the process's view, there is no indication that
285 // anything happened.
286 m_session_data->m_debugger->ContinueAsyncException(
288 }
289 } else {
290 LLDB_LOG(log, "error: process {0} is in state {1}. Returning...",
291 m_session_data->m_debugger->GetProcess().GetProcessId(),
293 }
294 return error;
295}
296
298 StateType private_state = GetPrivateState();
299 return DestroyProcess(private_state);
300}
301
302Status ProcessWindows::DoHalt(bool &caused_stop) {
303 StateType state = GetPrivateState();
304 if (state != eStateStopped) {
305 m_pending_halt = true;
306 Status error = HaltProcess(caused_stop);
307 if (error.Fail() || !caused_stop)
308 m_pending_halt = false;
309 }
310 caused_stop = false;
311 return Status();
312}
313
315 ArchSpec arch_spec;
316 DidAttach(arch_spec);
317}
318
320 llvm::sys::ScopedLock lock(m_mutex);
321
322 // The initial stop won't broadcast the state change event, so account for
323 // that here.
325 m_session_data->m_stop_at_entry)
327}
328
331 llvm::sys::ScopedLock lock(m_mutex);
332
333 if (!m_session_data) {
334 LLDB_LOG(log, "no active session. Returning...");
335 return;
336 }
337
338 m_thread_list.RefreshStateAfterStop();
339
340 std::weak_ptr<ExceptionRecord> exception_record =
341 m_session_data->m_debugger->GetActiveException();
342 ExceptionRecordSP active_exception = exception_record.lock();
343 if (!active_exception) {
344 LLDB_LOG(log,
345 "there is no active exception in process {0}. Why is the "
346 "process stopped?",
347 m_session_data->m_debugger->GetProcess().GetProcessId());
348 return;
349 }
350
351 StopInfoSP stop_info;
352 m_thread_list.SetSelectedThreadByID(active_exception->GetThreadID());
353 ThreadSP stop_thread = m_thread_list.GetSelectedThread();
354 if (!stop_thread)
355 return;
356
357 RegisterContextSP register_context = stop_thread->GetRegisterContext();
358 uint64_t pc = register_context->GetPC();
359
360 // If we're at a BreakpointSite, mark this as an Unexecuted Breakpoint.
361 // We'll clear that state if we've actually executed the breakpoint.
362 BreakpointSiteSP site(GetBreakpointSiteList().FindByAddress(pc));
363 if (site && IsBreakpointSitePhysicallyEnabled(*site))
364 stop_thread->SetThreadStoppedAtUnexecutedBP(pc);
365
366 switch (active_exception->GetExceptionValue()) {
367 case EXCEPTION_SINGLE_STEP: {
368 auto *reg_ctx = static_cast<RegisterContextWindows *>(
369 stop_thread->GetRegisterContext().get());
370 uint32_t slot_id = reg_ctx->GetTriggeredHardwareBreakpointSlotId();
371 if (slot_id != LLDB_INVALID_INDEX32) {
372 int id = m_watchpoint_ids[slot_id];
373 LLDB_LOG(log,
374 "Single-stepped onto a watchpoint in process {0} at address "
375 "{1:x} with watchpoint {2}",
376 m_session_data->m_debugger->GetProcess().GetProcessId(), pc, id);
377
378 stop_info = StopInfo::CreateStopReasonWithWatchpointID(*stop_thread, id);
379 stop_thread->SetStopInfo(stop_info);
380
381 return;
382 }
383
384 LLDB_LOG(log, "single stepping thread {0}", stop_thread->GetID());
385 stop_info = StopInfo::CreateStopReasonToTrace(*stop_thread);
386 stop_thread->SetStopInfo(stop_info);
387
388 return;
389 }
390
391 case EXCEPTION_BREAKPOINT: {
392 int breakpoint_size = 1;
393 switch (GetTarget().GetArchitecture().GetMachine()) {
394 case llvm::Triple::aarch64:
395 breakpoint_size = 4;
396 break;
397
398 case llvm::Triple::arm:
399 case llvm::Triple::thumb:
400 breakpoint_size = 2;
401 break;
402
403 case llvm::Triple::x86:
404 case llvm::Triple::x86_64:
405 breakpoint_size = 1;
406 break;
407
408 default:
409 LLDB_LOG(log, "Unknown breakpoint size for architecture");
410 break;
411 }
412
413 // The current PC is AFTER the BP opcode, on all architectures.
414 pc = register_context->GetPC() - breakpoint_size;
415
417 if (site) {
418 LLDB_LOG(log,
419 "detected breakpoint in process {0} at address {1:x} with "
420 "breakpoint site {2}",
421 m_session_data->m_debugger->GetProcess().GetProcessId(), pc,
422 site->GetID());
423
424 stop_thread->SetThreadHitBreakpointSite();
425 if (site->ValidForThisThread(*stop_thread)) {
426 LLDB_LOG(log,
427 "Breakpoint site {0} is valid for this thread ({1:x}), "
428 "creating stop info.",
429 site->GetID(), stop_thread->GetID());
430
432 *stop_thread, site->GetID());
433 register_context->SetPC(pc);
434 } else {
435 LLDB_LOG(log,
436 "Breakpoint site {0} is not valid for this thread, "
437 "creating empty stop info.",
438 site->GetID());
439 }
440 stop_thread->SetStopInfo(stop_info);
441 return;
442 } else {
443 // The thread hit a hard-coded breakpoint like an `int 3` or
444 // `__debugbreak()`.
445 LLDB_LOG(log,
446 "No breakpoint site matches for this thread. __debugbreak()? "
447 "Creating stop info with the exception.");
448 // FALLTHROUGH: We'll treat this as a generic exception record in the
449 // default case.
450 [[fallthrough]];
451 }
452 }
453
454 default: {
455 std::string desc;
456 llvm::raw_string_ostream desc_stream(desc);
457 desc_stream << "Exception "
458 << llvm::format_hex(active_exception->GetExceptionValue(), 8)
459 << " encountered at address "
460 << llvm::format_hex(active_exception->GetExceptionAddress(), 8);
461 active_exception->Dump(desc_stream);
462
463 stop_info =
464 StopInfo::CreateStopReasonWithException(*stop_thread, desc.c_str());
465 stop_thread->SetStopInfo(stop_info);
466 LLDB_LOG(log, "{0}", desc);
467 return;
468 }
469 }
470}
471
473 bool plugin_specified_by_name) {
474 if (plugin_specified_by_name)
475 return true;
476
477 // For now we are just making sure the file exists for a given module
478 ModuleSP exe_module_sp(target_sp->GetExecutableModule());
479 if (exe_module_sp.get())
480 return FileSystem::Instance().Exists(exe_module_sp->GetFileSpec());
481 // However, if there is no executable module, we return true since we might
482 // be preparing to attach.
483 return true;
484}
485
487 ThreadList &new_thread_list) {
489 // Add all the threads that were previously running and for which we did not
490 // detect a thread exited event.
491 int new_size = 0;
492 int continued_threads = 0;
493 int exited_threads = 0;
494 int new_threads = 0;
495
496 for (ThreadSP old_thread : old_thread_list.Threads()) {
497 lldb::tid_t old_thread_id = old_thread->GetID();
498 auto exited_thread_iter =
499 m_session_data->m_exited_threads.find(old_thread_id);
500 if (exited_thread_iter == m_session_data->m_exited_threads.end()) {
501 new_thread_list.AddThread(old_thread);
502 ++new_size;
503 ++continued_threads;
504 LLDB_LOG_VERBOSE(log, "Thread {0} was running and is still running.",
505 old_thread_id);
506 } else {
507 LLDB_LOG_VERBOSE(log, "Thread {0} was running and has exited.",
508 old_thread_id);
509 ++exited_threads;
510 }
511 }
512
513 // Also add all the threads that are new since the last time we broke into
514 // the debugger.
515 for (const auto &thread_info : m_session_data->m_new_threads) {
516 new_thread_list.AddThread(thread_info.second);
517 ++new_size;
518 ++new_threads;
519 LLDB_LOG_VERBOSE(log, "Thread {0} is new since last update.",
520 thread_info.first);
521 }
522
523 LLDB_LOG(log, "{0} new threads, {1} old threads, {2} exited threads.",
524 new_threads, continued_threads, exited_threads);
525
526 m_session_data->m_new_threads.clear();
527 m_session_data->m_exited_threads.clear();
528
529 return new_size > 0;
530}
531
533 StateType state = GetPrivateState();
534 switch (state) {
535 case eStateCrashed:
536 case eStateDetached:
537 case eStateUnloaded:
538 case eStateExited:
539 case eStateInvalid:
540 return false;
541 default:
542 return true;
543 }
544}
545
547 return HostInfo::GetArchitecture();
548}
549
551 size_t size, Status &error) {
552 size_t bytes_read = 0;
553 error = ProcessDebugger::ReadMemory(vm_addr, buf, size, bytes_read);
554 return bytes_read;
555}
556
557size_t ProcessWindows::DoWriteMemory(lldb::addr_t vm_addr, const void *buf,
558 size_t size, Status &error) {
559 size_t bytes_written = 0;
560 error = ProcessDebugger::WriteMemory(vm_addr, buf, size, bytes_written);
561 return bytes_written;
562}
563
564lldb::addr_t ProcessWindows::DoAllocateMemory(size_t size, uint32_t permissions,
565 Status &error) {
567 error = ProcessDebugger::AllocateMemory(size, permissions, vm_addr);
568 return vm_addr;
569}
570
574
579
581 Target &target = GetTarget();
582 ObjectFile *obj_file = target.GetExecutableModule()->GetObjectFile();
583 Address addr = obj_file->GetImageInfoAddress(&target);
584 if (addr.IsValid())
585 return addr.GetLoadAddress(&target);
586 else
588}
589
596
597void ProcessWindows::OnExitProcess(uint32_t exit_code) {
598 // No need to acquire the lock since m_session_data isn't accessed.
600 LLDB_LOG(log, "Process {0} exited with code {1}", GetID(), exit_code);
601
602 if (m_pty) {
604 m_pty->SetStopping(true);
605 m_pty->Close();
606 m_stdio_communication.InterruptRead();
607 m_stdio_communication.StopReadThread();
608 }
609
610 TargetSP target = CalculateTarget();
611 if (target) {
612 ModuleSP executable_module = target->GetExecutableModule();
613 ModuleList unloaded_modules;
614 unloaded_modules.Append(executable_module);
615 target->ModulesDidUnload(unloaded_modules, false);
616 }
617
618 SetExitStatus(exit_code, /*exit_string=*/"");
620
622}
623
625 if (!m_stdio_communication.ReadThreadIsRunning())
626 return;
627 m_stdio_communication.SynchronizeWithReadThread();
628 if (!m_pty || m_pty->GetMode() != PseudoConsole::Mode::ConPTY)
629 return;
630
631 HANDLE pipe = m_pty->GetSTDOUTHandle();
632 for (int consec_empty = 0; consec_empty < 3;) {
633 if (!m_stdio_communication.ReadThreadIsRunning())
634 break;
635 DWORD avail = 0;
636 // PeekNamedPipe is thread safe.
637 if (!::PeekNamedPipe(pipe, nullptr, 0, nullptr, &avail, nullptr))
638 break;
639 if (avail > 0) {
640 consec_empty = 0;
641 m_stdio_communication.SynchronizeWithReadThread();
642 } else {
643 ++consec_empty;
644 if (consec_empty < 3)
645 ::SleepEx(1, FALSE);
646 }
647 }
648}
649
651 DebuggerThreadSP debugger = m_session_data->m_debugger;
653 LLDB_LOG(log, "Debugger connected to process {0}. Image base = {1:x}",
654 debugger->GetProcess().GetProcessId(), image_base);
655
657 if (!module) {
658 const DWORD pid = debugger->GetProcess().GetProcessId();
659 const std::string file_name = GetProcessExecutableName(pid);
660 if (file_name.empty())
661 return;
662
663 FileSpec executable_file(file_name);
664 FileSystem::Instance().Resolve(executable_file);
665 ModuleSpec module_spec(executable_file);
667 module =
668 GetTarget().GetOrCreateModule(module_spec, /*notify=*/true, &error);
669 if (!module)
670 return;
672 }
673
674 if (auto dyld = GetDynamicLoader())
675 dyld->OnLoadModule(module, ModuleSpec(), image_base);
676
677 // Add the main executable module to the list of pending module loads. We
678 // can't call GetTarget().ModulesDidLoad() here because we still haven't
679 // returned from DoLaunch() / DoAttach() yet so the target may not have set
680 // the process instance to `this` yet.
681 llvm::sys::ScopedLock lock(m_mutex);
682
683 const HostThread &host_main_thread = debugger->GetMainThread();
684 ThreadSP main_thread =
685 std::make_shared<TargetThreadWindows>(*this, host_main_thread);
686
687 tid_t id = host_main_thread.GetNativeThread().GetThreadId();
688 main_thread->SetID(id);
689
690 m_session_data->m_new_threads[id] = main_thread;
691}
692
695 const ExceptionRecord &record) {
697 llvm::sys::ScopedLock lock(m_mutex);
698
699 // FIXME: Without this check, occasionally when running the test suite there
700 // is
701 // an issue where m_session_data can be null. It's not clear how this could
702 // happen but it only surfaces while running the test suite. In order to
703 // properly diagnose this, we probably need to first figure allow the test
704 // suite to print out full lldb logs, and then add logging to the process
705 // plugin.
706 if (!m_session_data) {
707 LLDB_LOG(log,
708 "Debugger thread reported exception {0:x} at address {1:x}, "
709 "but there is no session.",
710 record.GetExceptionValue(), record.GetExceptionAddress());
712 }
713
714 if (!first_chance) {
715 // Not any second chance exception is an application crash by definition.
716 // It may be an expression evaluation crash.
719 }
720
722 switch (record.GetExceptionValue()) {
723 case EXCEPTION_BREAKPOINT: {
724 const lldb::addr_t bp_addr = record.GetExceptionAddress();
725 if (m_pending_halt) {
726 m_pending_halt = false;
727 } else if (m_expecting_loader_int3 && first_chance &&
728 m_session_data->m_initial_stop_received &&
729 !GetBreakpointSiteList().FindByAddress(bp_addr) &&
730 IsSystemModuleAddress(bp_addr)) {
732 LLDB_LOG(log,
733 "Skipping expected loader breakpoint at address {0:x} in a "
734 "system module.",
735 bp_addr);
737 }
738
739 // Handle breakpoints at the first chance.
741
742 if (!m_session_data->m_initial_stop_received) {
743 LLDB_LOG(
744 log,
745 "Hit loader breakpoint at address {0:x}, setting initial stop event.",
746 record.GetExceptionAddress());
747 m_session_data->m_initial_stop_received = true;
748 ::SetEvent(m_session_data->m_initial_stop_event);
749 } else {
750 LLDB_LOG(log, "Hit non-loader breakpoint at address {0:x}.",
751 record.GetExceptionAddress());
752 }
753 // Drain any in-flight process output before announcing the stop. The I/O
754 // reader thread and this debug-event thread run concurrently. Without
755 // synchronization the eBroadcastBitStateChanged(Stopped) event can reach
756 // the Debugger event thread before the preceding eBroadcastBitSTDOUT
757 // events.
760 break;
761 }
762 case EXCEPTION_SINGLE_STEP:
766 break;
767 default:
768 LLDB_LOG(log,
769 "Debugger thread reported exception {0:x} at address {1:x} "
770 "(first_chance={2})",
771 record.GetExceptionValue(), record.GetExceptionAddress(),
772 first_chance);
773 // For non-breakpoints, give the application a chance to handle the
774 // exception first.
775 if (first_chance)
777 else
779 }
780
781 return result;
782}
783
785 llvm::sys::ScopedLock lock(m_mutex);
786
787 ThreadSP thread = std::make_shared<TargetThreadWindows>(*this, new_thread);
788
789 const HostNativeThread &native_new_thread = new_thread.GetNativeThread();
790 tid_t id = native_new_thread.GetThreadId();
791 thread->SetID(id);
792
793 m_session_data->m_new_threads[id] = thread;
794
795 for (const std::map<int, WatchpointInfo>::value_type &p : m_watchpoints) {
796 auto *reg_ctx = static_cast<RegisterContextWindows *>(
797 thread->GetRegisterContext().get());
798 reg_ctx->AddHardwareBreakpoint(p.second.slot_id, p.second.address,
799 p.second.size, p.second.read,
800 p.second.write);
801 }
802}
803
804void ProcessWindows::OnExitThread(lldb::tid_t thread_id, uint32_t exit_code) {
805 llvm::sys::ScopedLock lock(m_mutex);
806
807 // On a forced termination, we may get exit thread events after the session
808 // data has been cleaned up.
809 if (!m_session_data)
810 return;
811
812 // A thread may have started and exited before the debugger stopped allowing a
813 // refresh.
814 // Just remove it from the new threads list in that case.
815 auto iter = m_session_data->m_new_threads.find(thread_id);
816 if (iter != m_session_data->m_new_threads.end())
817 m_session_data->m_new_threads.erase(iter);
818 else
819 m_session_data->m_exited_threads.insert(thread_id);
820}
821
823 lldb::addr_t module_addr,
824 lldb::tid_t thread_id) {
825 if (auto dyld = GetDynamicLoader())
826 dyld->OnLoadModule(nullptr, module_spec, module_addr);
828}
829
831 lldb::tid_t thread_id) {
832 if (auto dyld = GetDynamicLoader())
833 dyld->OnUnloadModule(module_addr);
835}
836
838 bool is_unicode,
839 uint16_t length_lower_word) {
841
842 llvm::SmallVector<char, 256> buffer;
843 llvm::Error err =
844 ReadDebugString(debug_string_addr, is_unicode, length_lower_word, buffer);
845 if (err) {
846 LLDB_LOG_ERROR(log, std::move(err),
847 "Failed to read debug string at {1:x} (size & 0xffff={2}, "
848 "unicode={3}): {0}",
849 debug_string_addr, length_lower_word, is_unicode);
850 return;
851 }
852 if (buffer.empty())
853 return;
854
855 if (is_unicode) {
856 assert(buffer.size() % 2 == 0);
857 llvm::ArrayRef<unsigned short> utf16(
858 reinterpret_cast<const unsigned short *>(buffer.data()),
859 buffer.size() / 2);
860 std::string out;
861 if (!llvm::convertUTF16ToUTF8String(utf16, out)) {
862 LLDB_LOG(log, "Debug string is not valid Utf 16");
863 return;
864 }
865
866 AppendSTDOUT(out.data(), out.size());
867 } else {
868 AppendSTDOUT(buffer.data(), buffer.size());
869 }
870}
871
872void ProcessWindows::OnDebuggerError(const Status &error, uint32_t type) {
873 llvm::sys::ScopedLock lock(m_mutex);
875
876 if (m_session_data->m_initial_stop_received) {
877 // This happened while debugging. Do we shutdown the debugging session,
878 // try to continue, or do something else?
879 LLDB_LOG(log,
880 "Error {0} occurred during debugging. Unexpected behavior "
881 "may result. {1}",
882 error.GetError(), error);
883 } else {
884 // If we haven't actually launched the process yet, this was an error
885 // launching the process. Set the internal error and signal the initial
886 // stop event so that the DoLaunch method wakes up and returns a failure.
887 m_session_data->m_launch_error = error.Clone();
888 ::SetEvent(m_session_data->m_initial_stop_event);
889 LLDB_LOG(
890 log,
891 "Error {0} occurred launching the process before the initial stop. {1}",
892 error.GetError(), error);
893 return;
894 }
895}
896
900
901std::optional<DWORD> ProcessWindows::GetActiveExceptionCode() const {
902 if (!m_session_data || !m_session_data->m_debugger)
903 return std::nullopt;
904 auto exc = m_session_data->m_debugger->GetActiveException().lock();
905 if (!exc)
906 return std::nullopt;
907 return exc->GetExceptionValue();
908}
909
912
913 if (wp_sp->IsEnabled()) {
914 wp_sp->SetEnabled(true, notify);
915 return error;
916 }
917
918 WatchpointInfo info;
919 for (info.slot_id = 0;
921 info.slot_id++)
923 break;
926 "Can't find free slot for watchpoint %i", wp_sp->GetID());
927 return error;
928 }
929 info.address = wp_sp->GetLoadAddress();
930 info.size = wp_sp->GetByteSize();
931 info.read = wp_sp->WatchpointRead();
932 info.write = wp_sp->WatchpointWrite() || wp_sp->WatchpointModify();
933
934 for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) {
935 Thread *thread = m_thread_list.GetThreadAtIndex(i).get();
936 auto *reg_ctx = static_cast<RegisterContextWindows *>(
937 thread->GetRegisterContext().get());
938 if (!reg_ctx->AddHardwareBreakpoint(info.slot_id, info.address, info.size,
939 info.read, info.write)) {
941 "Can't enable watchpoint %i on thread 0x%llx", wp_sp->GetID(),
942 thread->GetID());
943 break;
944 }
945 }
946 if (error.Fail()) {
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 reg_ctx->RemoveHardwareBreakpoint(info.slot_id);
952 }
953 return error;
954 }
955
956 m_watchpoints[wp_sp->GetID()] = info;
957 m_watchpoint_ids[info.slot_id] = wp_sp->GetID();
958
959 wp_sp->SetEnabled(true, notify);
960
961 return error;
962}
963
966
967 if (!wp_sp->IsEnabled()) {
968 wp_sp->SetEnabled(false, notify);
969 return error;
970 }
971
972 auto it = m_watchpoints.find(wp_sp->GetID());
973 if (it == m_watchpoints.end()) {
975 "Info about watchpoint %i is not found", wp_sp->GetID());
976 return error;
977 }
978
979 for (unsigned i = 0U; i < m_thread_list.GetSize(); i++) {
980 Thread *thread = m_thread_list.GetThreadAtIndex(i).get();
981 auto *reg_ctx = static_cast<RegisterContextWindows *>(
982 thread->GetRegisterContext().get());
983 if (!reg_ctx->RemoveHardwareBreakpoint(it->second.slot_id)) {
985 "Can't disable watchpoint %i on thread 0x%llx", wp_sp->GetID(),
986 thread->GetID());
987 break;
988 }
989 }
990 if (error.Fail())
991 return error;
992
993 m_watchpoint_ids[it->second.slot_id] = LLDB_INVALID_BREAK_ID;
994 m_watchpoints.erase(it);
995
996 wp_sp->SetEnabled(false, notify);
997
998 return error;
999}
1000
1001size_t ProcessWindows::PutSTDIN(const char *src, size_t src_len,
1002 Status &error) {
1003 if (!m_stdio_communication.IsConnected()) {
1004 error = Status::FromErrorString("stdin not connected");
1005 return 0;
1006 }
1007 ConnectionStatus status;
1008 return m_stdio_communication.WriteAll(src, src_len, status, &error);
1009}
1010
1012 if (m_pty == nullptr)
1013 return;
1014 m_stdio_communication.SetConnection(
1015 std::make_unique<ConnectionConPTY>(m_pty));
1016 if (m_stdio_communication.IsConnected()) {
1017 m_stdio_communication.SetReadThreadBytesReceivedCallback(
1019 m_stdio_communication.StartReadThread();
1020
1021 // Now read thread is set up, set up input reader.
1022 {
1023 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
1026 std::make_shared<IOHandlerProcessSTDIOWindows>(this);
1027 }
1028 }
1029}
1030} // namespace lldb_private
static llvm::raw_ostream & error(Stream &strm)
DllEventAction
Definition ForwardDecl.h:29
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
#define LLDB_LOG_VERBOSE(log,...)
Definition Log.h:382
#define MAX_PATH
#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.
unsigned long GetExceptionValue() const
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.
HostNativeThread & GetNativeThread()
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:91
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)
bool IsSystemModuleAddress(lldb::addr_t addr)
virtual void OnExitProcess(uint32_t exit_code)
llvm::Error ReadDebugString(lldb::addr_t debug_string_addr, bool is_unicode, uint16_t length_lower_word, llvm::SmallVectorImpl< char > &output)
Read an OUTPUT_DEBUG_STRING_INFO payload from the inferior.
Status HaltProcess(bool &caused_stop)
Status DeallocateMemory(lldb::addr_t addr)
lldb::pid_t GetProcessID() const
Definition ProcessInfo.h:66
std::shared_ptr< PTY > TakePTY()
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.
DllEventAction OnUnloadDll(lldb::addr_t module_addr, lldb::tid_t thread_id) override
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 DrainProcessStdout()
Block until the stdio read thread has surfaced everything currently buffered in the ConPTY/pipe to th...
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.
DynamicLoaderWindowsDYLD * GetDynamicLoader() override
Get the dynamic loader plug-in for this process.
void OnDebugString(lldb::addr_t debug_string_addr, bool is_unicode, uint16_t length_lower_word) 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
DllEventAction OnLoadDll(const ModuleSpec &module_spec, lldb::addr_t module_addr, lldb::tid_t thread_id) 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.
size_t PutSTDIN(const char *src, size_t src_len, Status &error) override
Puts data into this process's STDIN.
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
lldb::IOHandlerSP m_process_input_reader
Definition Process.h:3547
std::mutex m_process_input_reader_mutex
Definition Process.h:3548
StopPointSiteList< lldb_private::BreakpointSite > & GetBreakpointSiteList()
Definition Process.cpp:1571
virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1941
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:543
Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
Construct with a shared pointer to a target, and the Process listener.
Definition Process.cpp:453
lldb::StateType GetPrivateState() const
Definition Process.h:3457
lldb::DynamicLoaderUP m_dyld_up
Definition Process.h:3535
bool IsBreakpointSitePhysicallyEnabled(const BreakpointSite &site)
Definition Process.cpp:1676
void AppendSTDOUT(const char *s, size_t len)
Definition Process.cpp:4873
lldb::TargetSP CalculateTarget() override
Definition Process.cpp:4839
virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1861
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
Definition Process.h:548
friend class Target
Definition Process.h:365
virtual bool SetExitStatus(int exit_status, llvm::StringRef exit_string)
Set accessor for the process exit status (return code).
Definition Process.cpp:1048
static void STDIOReadThreadBytesReceived(void *baton, const void *src, size_t src_len)
Definition Process.cpp:4973
void SetPrivateState(lldb::StateType state)
Definition Process.cpp:1411
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition Process.h:3508
ThreadedCommunication m_stdio_communication
Definition Process.h:3549
friend class ThreadList
Definition Process.h:366
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1258
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:1624
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
Definition Target.cpp:1657
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:338
HostThreadPosix HostNativeThread
std::shared_ptr< DebuggerThread > DebuggerThreadSP
Definition ForwardDecl.h:46
std::shared_ptr< IDebugDelegate > DebugDelegateSP
Definition ForwardDecl.h:45
std::shared_ptr< ExceptionRecord > ExceptionRecordSP
Definition ForwardDecl.h:47
static bool ShouldUseLLDBServer()
std::shared_ptr< lldb_private::BreakpointSite > BreakpointSiteSP
RunDirection
Execution directions.
std::shared_ptr< lldb_private::Thread > ThreadSP
ConnectionStatus
Connection Status Types.
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