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