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