[Go to site: main page, start]

LLDB mainline
PlatformWindows.cpp
Go to the documentation of this file.
1//===-- PlatformWindows.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 "PlatformWindows.h"
10
11#include <chrono>
12#include <cstdio>
13#include <optional>
14#if defined(_WIN32)
16#include <pathcch.h>
17#include <winsock2.h>
18#else
19#define MAX_PATH 260
20#define PATHCCH_MAX_CCH 0x8000
21#endif
22
27#include "lldb/Core/Debugger.h"
28#include "lldb/Core/Module.h"
34#include "lldb/Host/HostInfo.h"
36#include "lldb/Target/Process.h"
38#include "lldb/Utility/Status.h"
39
40#include "llvm/ADT/ScopeExit.h"
41#include "llvm/Support/ConvertUTF.h"
42#include "llvm/Support/FormatVariadic.h"
43
44using namespace lldb;
45using namespace lldb_private;
46
48
49static uint32_t g_initialize_count = 0;
50
51// Upper bound on the timeout used when running a utility expression with
52// only one thread allowed to run.
53static std::chrono::microseconds GetLoaderOneThreadTimeout(Process *process) {
54 return std::chrono::microseconds(process->GetUtilityExpressionTimeout()) / 2;
55}
56
57namespace {
58
59#define LLDB_PROPERTIES_windows
60#include "PlatformWindowsProperties.inc"
61
62enum {
63#define LLDB_PROPERTIES_windows
64#include "PlatformWindowsPropertiesEnum.inc"
65};
66
67class PluginProperties : public Properties {
68public:
69 PluginProperties() {
70 m_collection_sp = std::make_shared<OptionValueProperties>("windows");
71 m_collection_sp->Initialize(g_windows_properties_def);
72 }
73
74 bool DisableDebugHeap() const {
75 return GetPropertyAtIndexAs<bool>(ePropertyDisableDebugHeap, true);
76 }
77};
78
79static PluginProperties &GetGlobalProperties() {
80 static PluginProperties g_settings;
81 return g_settings;
82}
83
84} // end of anonymous namespace
85
87 const lldb_private::ArchSpec *arch) {
88 // The only time we create an instance is when we are creating a remote
89 // windows platform
90 const bool is_host = false;
91
92 bool create = force;
93 if (!create && arch && arch->IsValid()) {
94 const llvm::Triple &triple = arch->GetTriple();
95 switch (triple.getVendor()) {
96 case llvm::Triple::PC:
97 create = true;
98 break;
99
100 case llvm::Triple::UnknownVendor:
101 create = !arch->TripleVendorWasSpecified();
102 break;
103
104 default:
105 break;
106 }
107
108 if (create) {
109 switch (triple.getOS()) {
110 case llvm::Triple::Win32:
111 break;
112
113 case llvm::Triple::UnknownOS:
114 create = arch->TripleOSWasSpecified();
115 break;
116
117 default:
118 create = false;
119 break;
120 }
121 }
122 }
123 if (create)
124 return PlatformSP(new PlatformWindows(is_host));
125 return PlatformSP();
126}
127
128llvm::StringRef PlatformWindows::GetPluginDescriptionStatic(bool is_host) {
129 return is_host ? "Local Windows user platform plug-in."
130 : "Remote Windows user platform plug-in.";
131}
132
134 if (!PluginManager::GetSettingForPlatformPlugin(debugger, "windows")) {
136 debugger, GetGlobalProperties().GetValueProperties(),
137 "Properties for the Windows platform plugin.",
138 /*is_global_property=*/true);
139 }
140}
141
144
145 if (g_initialize_count++ == 0) {
146#if defined(_WIN32)
147 // Force a host flag to true for the default platform object.
148 PlatformSP default_platform_sp(new PlatformWindows(true));
149 default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture());
150 Platform::SetHostPlatform(default_platform_sp);
151#endif
156 }
157}
158
168
169/// Default Constructor
171 const auto &AddArch = [&](const ArchSpec &spec) {
172 if (llvm::any_of(m_supported_architectures, [spec](const ArchSpec &rhs) {
173 return spec.IsExactMatch(rhs);
174 }))
175 return;
176 if (spec.IsValid())
177 m_supported_architectures.push_back(spec);
178 };
179 AddArch(HostInfo::GetArchitecture(HostInfo::eArchKindDefault));
180 AddArch(HostInfo::GetArchitecture(HostInfo::eArchKind32));
181 AddArch(HostInfo::GetArchitecture(HostInfo::eArchKind64));
182}
183
185 if (IsHost())
187 "can't connect to the host platform '{0}', always connected",
188 GetPluginName());
189
193 /*force=*/true, nullptr);
194
197 "failed to create a 'remote-gdb-server' platform");
198
199 Status error = m_remote_platform_sp->ConnectRemote(args);
200 if (error.Fail())
201 m_remote_platform_sp.reset();
202
203 return error;
204}
205
207 const FileSpec &remote_file,
208 const std::vector<std::string> *paths,
209 Status &error, FileSpec *loaded_image) {
210 DiagnosticManager diagnostics;
211
212 if (loaded_image)
213 loaded_image->Clear();
214
216 if (!thread) {
218 "LoadLibrary error: no thread available to invoke LoadLibrary");
220 }
221
222 ExecutionContext context;
223 thread->CalculateExecutionContext(context);
224
225 Status status;
226 UtilityFunction *loader =
227 process->GetLoadImageUtilityFunction(this, [&]() -> std::unique_ptr<UtilityFunction> {
228 return MakeLoadImageUtilityFunction(context, status);
229 });
230 if (loader == nullptr)
232
233 FunctionCaller *invocation = loader->GetFunctionCaller();
234 if (!invocation) {
236 "LoadLibrary error: could not get function caller");
238 }
239
240 /* Convert name */
241 llvm::SmallVector<llvm::UTF16, 261> name;
242 if (!llvm::convertUTF8ToUTF16String(remote_file.GetPath(), name)) {
244 "LoadLibrary error: could not convert path to UCS2");
246 }
247 name.emplace_back(L'\0');
248
249 /* Inject name paramter into inferior */
250 lldb::addr_t injected_name =
251 process->AllocateMemory(name.size() * sizeof(llvm::UTF16),
252 ePermissionsReadable | ePermissionsWritable,
253 status);
254 if (injected_name == LLDB_INVALID_ADDRESS) {
256 "LoadLibrary error: unable to allocate memory for name: %s",
257 status.AsCString());
259 }
260
261 llvm::scope_exit name_cleanup(
262 [process, injected_name]() { process->DeallocateMemory(injected_name); });
263
264 process->WriteMemory(injected_name, name.data(),
265 name.size() * sizeof(llvm::UTF16), status);
266 if (status.Fail()) {
268 "LoadLibrary error: unable to write name: %s", status.AsCString());
270 }
271
272 /* Inject paths parameter into inferior */
273 lldb::addr_t injected_paths{0x0};
274 std::optional<llvm::scope_exit<std::function<void()>>> paths_cleanup;
275 if (paths) {
276 llvm::SmallVector<llvm::UTF16, 261> search_paths;
277
278 for (const auto &path : *paths) {
279 if (path.empty())
280 continue;
281
282 llvm::SmallVector<llvm::UTF16, 261> buffer;
283 if (!llvm::convertUTF8ToUTF16String(path, buffer))
284 continue;
285
286 search_paths.append(std::begin(buffer), std::end(buffer));
287 search_paths.emplace_back(L'\0');
288 }
289 search_paths.emplace_back(L'\0');
290
291 injected_paths =
292 process->AllocateMemory(search_paths.size() * sizeof(llvm::UTF16),
293 ePermissionsReadable | ePermissionsWritable,
294 status);
295 if (injected_paths == LLDB_INVALID_ADDRESS) {
297 "LoadLibrary error: unable to allocate memory for paths: %s",
298 status.AsCString());
300 }
301
302 paths_cleanup.emplace([process, injected_paths]() {
303 process->DeallocateMemory(injected_paths);
304 });
305
306 process->WriteMemory(injected_paths, search_paths.data(),
307 search_paths.size() * sizeof(llvm::UTF16), status);
308 if (status.Fail()) {
310 "LoadLibrary error: unable to write paths: %s", status.AsCString());
312 }
313 }
314
315 /* Inject wszModulePath into inferior */
316 // Start with a MAX_PATH-sized buffer (enough for the vast majority of module
317 // paths) and grow it on demand if GetModuleFileNameW reports truncation (see
318 // the loop after the helper runs).
319 unsigned injected_length = MAX_PATH;
320
321 lldb::addr_t injected_module_path = process->AllocateMemory(
322 (injected_length + 1) * sizeof(llvm::UTF16),
323 ePermissionsReadable | ePermissionsWritable, status);
324 if (injected_module_path == LLDB_INVALID_ADDRESS) {
326 "LoadLibrary error: unable to allocate memory for module location: %s",
327 status.AsCString());
329 }
330
331 llvm::scope_exit injected_module_path_cleanup(
332 [process, injected_module_path]() {
333 process->DeallocateMemory(injected_module_path);
334 });
335
336 /* Inject __lldb_LoadLibraryResult into inferior */
337 const uint32_t word_size = process->GetAddressByteSize();
338 lldb::addr_t injected_result =
339 process->AllocateMemory(3 * word_size,
340 ePermissionsReadable | ePermissionsWritable,
341 status);
342 if (status.Fail()) {
344 "LoadLibrary error: could not allocate memory for result: %s",
345 status.AsCString());
347 }
348
349 llvm::scope_exit result_cleanup([process, injected_result]() {
350 process->DeallocateMemory(injected_result);
351 });
352
353 std::vector<lldb::addr_t> grown_path_buffers;
354 llvm::scope_exit grown_path_cleanup([&]() {
355 for (lldb::addr_t buffer : grown_path_buffers)
356 process->DeallocateMemory(buffer);
357 });
358
359 process->WritePointerToMemory(injected_result, 0, status);
360 if (status.Fail()) {
362 "LoadLibrary error: could not initialize result: %s",
363 status.AsCString());
365 }
366
367 process->WritePointerToMemory(injected_result + word_size,
368 injected_module_path, status);
369 if (status.Fail()) {
371 "LoadLibrary error: could not initialize result: %s",
372 status.AsCString());
374 }
375
376 // XXX(compnerd) should we use the compiler to get the sizeof(unsigned)?
377 process->WriteScalarToMemory(injected_result + 2 * word_size,
378 Scalar{injected_length}, sizeof(unsigned),
379 status);
380 if (status.Fail()) {
382 "LoadLibrary error: could not initialize result: %s",
383 status.AsCString());
385 }
386
387 /* Setup Formal Parameters */
388 ValueList parameters = invocation->GetArgumentValues();
389 parameters.GetValueAtIndex(0)->GetScalar() = injected_name;
390 parameters.GetValueAtIndex(1)->GetScalar() = injected_paths;
391 parameters.GetValueAtIndex(2)->GetScalar() = injected_result;
392
393 lldb::addr_t injected_parameters = LLDB_INVALID_ADDRESS;
394 diagnostics.Clear();
395 if (!invocation->WriteFunctionArguments(context, injected_parameters,
396 parameters, diagnostics)) {
397 error = Status::FromError(diagnostics.GetAsError(
399 "LoadLibrary error: unable to write function parameters:"));
401 }
402
403 llvm::scope_exit parameter_cleanup(
404 [invocation, &context, injected_parameters]() {
405 invocation->DeallocateFunctionResults(context, injected_parameters);
406 });
407
408 TypeSystemClangSP scratch_ts_sp =
410 if (!scratch_ts_sp) {
412 "LoadLibrary error: unable to get (clang) type system");
414 }
415
416 /* Setup Return Type */
417 CompilerType VoidPtrTy =
418 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
419
420 Value value;
421 value.SetCompilerType(VoidPtrTy);
422
423 /* Invoke expression */
427 options.SetIgnoreBreakpoints(true);
428 options.SetUnwindOnError(true);
429 // LoadLibraryEx{A,W}/FreeLibrary cannot raise exceptions which we can handle.
430 // They may potentially throw SEH exceptions which we do not know how to
431 // handle currently.
432 options.SetTrapExceptions(false);
433 options.SetTimeout(process->GetUtilityExpressionTimeout());
435 options.SetIsForUtilityExpr(true);
436
437 ExpressionResults result =
438 invocation->ExecuteFunction(context, &injected_parameters, options,
439 diagnostics, value);
440 if (result != eExpressionCompleted) {
441 error = Status::FromError(diagnostics.GetAsError(
443 llvm::formatv("failed to execute LoadLibrary helper "
444 "({0}):",
445 toString(result))
446 .str()));
448 }
449
450 /* Read result */
451 lldb::addr_t token = process->ReadPointerFromMemory(injected_result, status);
452 if (status.Fail()) {
454 "LoadLibrary error: could not read the result: %s", status.AsCString());
456 }
457
458 if (!token) {
459 // ErrorCode is a 4-byte `unsigned` field in __lldb_LoadLibraryResult.
460 uint64_t error_code = process->ReadUnsignedIntegerFromMemory(
461 injected_result + 2 * word_size + sizeof(unsigned), sizeof(unsigned), 0,
462 status);
463 if (status.Fail()) {
465 "LoadLibrary error: could not read error status: %s",
466 status.AsCString());
468 }
469
470 error = Status::FromErrorStringWithFormat("LoadLibrary Error: %" PRIu64,
471 error_code);
473 }
474
475 lldb::addr_t module_path_addr = injected_module_path;
476 unsigned capacity = injected_length;
477 uint32_t path_length = process->ReadUnsignedIntegerFromMemory(
478 injected_result + 2 * word_size, sizeof(unsigned), 0, status);
479 while (status.Success() && path_length >= capacity &&
480 capacity < PATHCCH_MAX_CCH) {
481 capacity = std::min<unsigned>(capacity * 2, PATHCCH_MAX_CCH);
482 lldb::addr_t buffer = process->AllocateMemory(
483 (capacity + 1) * sizeof(llvm::UTF16),
484 ePermissionsReadable | ePermissionsWritable, status);
485 if (buffer == LLDB_INVALID_ADDRESS || status.Fail())
486 break;
487 grown_path_buffers.push_back(buffer);
488
489 process->WritePointerToMemory(injected_result + word_size, buffer, status);
490 if (status.Fail())
491 break;
492 process->WriteScalarToMemory(injected_result + 2 * word_size,
493 Scalar{capacity}, sizeof(unsigned), status);
494 if (status.Fail())
495 break;
496
497 diagnostics.Clear();
498 if (invocation->ExecuteFunction(context, &injected_parameters, options,
499 diagnostics, value) != eExpressionCompleted)
500 break;
501 module_path_addr = buffer;
502 path_length = process->ReadUnsignedIntegerFromMemory(
503 injected_result + 2 * word_size, sizeof(unsigned), 0, status);
504 }
505
506 llvm::SmallVector<llvm::UTF16, MAX_PATH> wide_path(path_length);
507 if (path_length)
508 process->ReadMemory(module_path_addr, wide_path.data(),
509 path_length * sizeof(llvm::UTF16), status);
510 if (status.Fail()) {
512 "LoadLibrary error: could not read module path: %s",
513 status.AsCString());
515 }
516
517 std::string module_path;
518 if (!llvm::convertUTF16ToUTF8String(
519 llvm::ArrayRef<llvm::UTF16>(wide_path.data(), wide_path.size()),
520 module_path)) {
522 "LoadLibrary error: could not convert module path to UTF-8");
524 }
525
526 if (loaded_image)
527 loaded_image->SetFile(module_path, llvm::sys::path::Style::native);
528 return process->AddImageToken(token);
529}
530
531Status PlatformWindows::UnloadImage(Process *process, uint32_t image_token) {
532 const addr_t address = process->GetImagePtrFromToken(image_token);
533 if (address == LLDB_INVALID_ADDRESS)
534 return Status::FromErrorString("invalid image token");
535
536 StreamString expression;
537 expression.Printf("FreeLibrary((HMODULE)0x%" PRIx64 ")", address);
538
539 ValueObjectSP value;
540 Status result =
541 EvaluateLoaderExpression(process, expression.GetData(), value);
542 if (result.Fail())
543 return result;
544
545 if (value->GetError().Fail())
546 return value->GetError().Clone();
547
548 Scalar scalar;
549 if (value->ResolveValue(scalar)) {
550 if (scalar.UInt(1))
551 return Status::FromErrorStringWithFormat("expression failed: \"%s\"",
552 expression.GetData());
553 process->ResetImageToken(image_token);
554 }
555
556 return Status();
557}
558
561
562 if (IsHost()) {
564 "can't disconnect from the host platform '{0}', always connected",
565 GetPluginName());
566 } else {
568 error = m_remote_platform_sp->DisconnectRemote();
569 else
570 error =
571 Status::FromErrorString("the platform is not currently connected");
572 }
573 return error;
574}
575
577 Debugger &debugger, Target &target,
578 Status &error) {
579 // Windows has special considerations that must be followed when launching or
580 // attaching to a process. The key requirement is that when launching or
581 // attaching to a process, you must do it from the same the thread that will
582 // go into a permanent loop which will then receive debug events from the
583 // process. In particular, this means we can't use any of LLDB's generic
584 // mechanisms to do it for us, because it doesn't have the special knowledge
585 // required for setting up the background thread or passing the right flags.
586 //
587 // Another problem is that LLDB's standard model for debugging a process
588 // is to first launch it, have it stop at the entry point, and then attach to
589 // it. In Windows this doesn't quite work, you have to specify as an
590 // argument to CreateProcess() that you're going to debug the process. So we
591 // override DebugProcess here to handle this. Launch operations go directly
592 // to the process plugin, and attach operations almost go directly to the
593 // process plugin (but we hijack the events first). In essence, we
594 // encapsulate all the logic of Launching and Attaching in the process
595 // plugin, and PlatformWindows::DebugProcess is just a pass-through to get to
596 // the process plugin.
597
598 if (IsRemote()) {
600 return m_remote_platform_sp->DebugProcess(launch_info, debugger, target,
601 error);
602 else
603 error =
604 Status::FromErrorString("the platform is not currently connected");
605 }
606
607 if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {
608 // This is a process attach. Don't need to launch anything.
609 ProcessAttachInfo attach_info(launch_info);
610 return Attach(attach_info, debugger, &target, error);
611 }
612
613 Environment &env = launch_info.GetEnvironment();
614 if (GetGlobalProperties().DisableDebugHeap() &&
615 !env.contains("_NO_DEBUG_HEAP")) {
616 env.try_emplace("_NO_DEBUG_HEAP", "1");
617 }
618
619 ProcessSP process_sp =
620 target.CreateProcess(launch_info.GetListener(),
621 launch_info.GetProcessPluginName(), nullptr, false);
622 if (!process_sp)
623 return nullptr;
624
625 process_sp->HijackProcessEvents(launch_info.GetHijackListener());
626
627 // We need to launch and attach to the process.
628 launch_info.GetFlags().Set(eLaunchFlagDebug);
629 error = process_sp->Launch(launch_info);
630#ifdef _WIN32
631 if (error.Success()) {
632 process_sp->SetPseudoConsoleHandle();
633 } else {
635 LLDB_LOGF(log, "Platform::%s LaunchProcess() failed: %s", __FUNCTION__,
636 error.AsCString());
637 }
638#endif
639
640 return process_sp;
641}
642
644 Debugger &debugger, Target *target,
645 Status &error) {
646 error.Clear();
647 lldb::ProcessSP process_sp;
648 if (!IsHost()) {
650 process_sp =
651 m_remote_platform_sp->Attach(attach_info, debugger, target, error);
652 else
653 error =
654 Status::FromErrorString("the platform is not currently connected");
655 return process_sp;
656 }
657
658 if (target == nullptr) {
659 TargetSP new_target_sp;
660 error = debugger.GetTargetList().CreateTarget(
661 debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
662 target = new_target_sp.get();
663 }
664
665 if (!target || error.Fail())
666 return process_sp;
667
668 process_sp =
669 target->CreateProcess(attach_info.GetListenerForProcess(debugger),
670 attach_info.GetProcessPluginName(), nullptr, false);
671
672 process_sp->HijackProcessEvents(attach_info.GetHijackListener());
673 if (process_sp)
674 error = process_sp->Attach(attach_info);
675
676 return process_sp;
677}
678
681
682#ifdef _WIN32
683 llvm::VersionTuple version = HostInfo::GetOSVersion();
684 strm << " Host: Windows " << version.getAsString() << '\n';
685#endif
686}
687
688bool PlatformWindows::CanDebugProcess() { return true; }
689
690std::string PlatformWindows::GetFullNameForDylib(llvm::StringRef basename) {
691 if (basename.empty())
692 return basename.str();
693
694 return llvm::formatv("{0}.dll", basename).str();
695}
696
697size_t
699 BreakpointSite *bp_site) {
700 ArchSpec arch = target.GetArchitecture();
701 assert(arch.IsValid());
702 const uint8_t *trap_opcode = nullptr;
703 size_t trap_opcode_size = 0;
704
705 switch (arch.GetMachine()) {
706 case llvm::Triple::aarch64: {
707 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x3e, 0xd4}; // brk #0xf000
708 trap_opcode = g_aarch64_opcode;
709 trap_opcode_size = sizeof(g_aarch64_opcode);
710
711 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
712 return trap_opcode_size;
713 return 0;
714 } break;
715
716 case llvm::Triple::arm:
717 case llvm::Triple::thumb: {
718 static const uint8_t g_thumb_opcode[] = {0xfe, 0xde}; // udf #0xfe
719 trap_opcode = g_thumb_opcode;
720 trap_opcode_size = sizeof(g_thumb_opcode);
721
722 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
723 return trap_opcode_size;
724 return 0;
725 } break;
726
727 default:
728 return Platform::GetSoftwareBreakpointTrapOpcode(target, bp_site);
729 }
730}
731
732std::unique_ptr<UtilityFunction>
734 Status &status) {
735 // FIXME(compnerd) `-fdeclspec` is not passed to the clang instance?
736 static constexpr const char kLoaderDecls[] = R"(
737extern "C" {
738// errhandlingapi.h
739
740// `LOAD_LIBRARY_SEARCH_APPLICATION_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_USER_DIRS`
741//
742// Directories in the standard search path are not searched. This value cannot
743// be combined with `LOAD_WITH_ALTERED_SEARCH_PATH`.
744//
745// This value represents the recommended maximum number of directories an
746// application should include in its DLL search path.
747#define LOAD_LIBRARY_SEARCH_DEFAULT_DIRS 0x00001000
748
749// If this value is used, and lpFileName specifies an absolute path, the system
750// uses the alternate file search strategy to find associated executable
751// modules.
752#define LOAD_WITH_ALTERED_SEARCH_PATH 0x00000008
753
754// WINBASEAPI DWORD WINAPI GetLastError(VOID);
755/* __declspec(dllimport) */ uint32_t __stdcall GetLastError();
756
757// libloaderapi.h
758
759// WINBASEAPI DLL_DIRECTORY_COOKIE WINAPI AddDllDirectory(LPCWSTR);
760/* __declspec(dllimport) */ void * __stdcall AddDllDirectory(const wchar_t *);
761
762// WINBASEAPI BOOL WINAPI FreeModule(HMODULE);
763/* __declspec(dllimport) */ int __stdcall FreeModule(void *hLibModule);
764
765// WINBASEAPI DWORD WINAPI GetModuleFileNameW(HMODULE hModule, LPWSTR lpFilename, DWORD nSize);
766/* __declspec(dllimport) */ uint32_t GetModuleFileNameW(void *, wchar_t *, uint32_t);
767
768// WINBASEAPI HMODULE WINAPI LoadLibraryExW(LPCWSTR, HANDLE, DWORD);
769/* __declspec(dllimport) */ void * __stdcall LoadLibraryExW(const wchar_t *, void *, uint32_t);
770
771// corecrt_wstring.h
772
773// _ACRTIMP size_t __cdecl wcslen(wchar_t const *_String);
774/* __declspec(dllimport) */ size_t __cdecl wcslen(const wchar_t *);
775
776// lldb specific code
777
778struct __lldb_LoadLibraryResult {
779 void *ImageBase;
780 wchar_t *ModulePath;
781 unsigned Length;
782 unsigned ErrorCode;
783};
784
785_Static_assert(sizeof(struct __lldb_LoadLibraryResult) <= 3 * sizeof(void *),
786 "__lldb_LoadLibraryResult size mismatch");
787
788void * __lldb_LoadLibraryHelper(const wchar_t *name, const wchar_t *paths,
789 __lldb_LoadLibraryResult *result) {
790 // When the caller presets ImageBase the module is already loaded and we are
791 // only re-querying its path with a larger buffer. Skip LoadLibrary in that
792 // case so we do not take an extra reference on the module.
793 if (result->ImageBase == nullptr) {
794 for (const wchar_t *path = paths; path && *path; ) {
795 (void)AddDllDirectory(path);
796 path += wcslen(path) + 1;
797 }
798
799 result->ImageBase = LoadLibraryExW(name, nullptr,
800 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
801
802 // Fallback: if the AddDllDirectory + LOAD_LIBRARY_SEARCH_DEFAULT_DIRS path
803 // failed to find the library, iterate the search paths ourselves and
804 // load by absolute path using LOAD_WITH_ALTERED_SEARCH_PATH, which makes
805 // Windows use the loaded DLL's own directory to resolve its sibling imports.
806 if (result->ImageBase == nullptr) {
807 wchar_t full[4096];
808 for (const wchar_t *path = paths; path && *path; path += wcslen(path) + 1) {
809 size_t plen = wcslen(path);
810 size_t nlen = wcslen(name);
811 // Need room for: path + '\\' + name + '\0'
812 if (plen + 1 + nlen + 1 > 4096)
813 continue;
814 wchar_t *p = full;
815 for (size_t i = 0; i < plen; ++i)
816 *p++ = path[i];
817 *p++ = L'\\';
818 for (size_t i = 0; i <= nlen; ++i) // Copy name including trailing '\0'.
819 *p++ = name[i];
820 result->ImageBase = LoadLibraryExW(full, nullptr,
821 LOAD_WITH_ALTERED_SEARCH_PATH);
822 if (result->ImageBase != nullptr)
823 break;
824 }
825 }
826 }
827
828 if (result->ImageBase == nullptr)
829 result->ErrorCode = GetLastError();
830 else
831 result->Length = GetModuleFileNameW(result->ImageBase, result->ModulePath,
832 result->Length);
833
834 return result->ImageBase;
835}
836}
837 )";
838
839 static constexpr const char kName[] = "__lldb_LoadLibraryHelper";
840
841 ProcessSP process = context.GetProcessSP();
842 Target &target = process->GetTarget();
843
844 auto function = target.CreateUtilityFunction(std::string{kLoaderDecls}, kName,
846 context);
847 if (!function) {
848 std::string error = llvm::toString(function.takeError());
850 "LoadLibrary error: could not create utility function: %s",
851 error.c_str());
852 return nullptr;
853 }
854
855 TypeSystemClangSP scratch_ts_sp =
857 if (!scratch_ts_sp)
858 return nullptr;
859
860 CompilerType VoidPtrTy =
861 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
862 CompilerType WCharPtrTy =
863 scratch_ts_sp->GetBasicType(eBasicTypeWChar).GetPointerType();
864
865 ValueList parameters;
866
867 Value value;
869
870 value.SetCompilerType(WCharPtrTy);
871 parameters.PushValue(value); // name
872 parameters.PushValue(value); // paths
873
874 value.SetCompilerType(VoidPtrTy);
875 parameters.PushValue(value); // result
876
878 std::unique_ptr<UtilityFunction> utility{std::move(*function)};
879 utility->MakeFunctionCaller(VoidPtrTy, parameters, context.GetThreadSP(),
880 error);
881 if (error.Fail()) {
883 "LoadLibrary error: could not create function caller: %s",
884 error.AsCString());
885 return nullptr;
886 }
887
888 if (!utility->GetFunctionCaller()) {
890 "LoadLibrary error: could not get function caller");
891 return nullptr;
892 }
893
894 return utility;
895}
896
898 const char *expression,
899 ValueObjectSP &value) {
900 // FIXME(compnerd) `-fdeclspec` is not passed to the clang instance?
901 static constexpr const char kLoaderDecls[] = R"(
902extern "C" {
903// libloaderapi.h
904
905// WINBASEAPI DLL_DIRECTORY_COOKIE WINAPI AddDllDirectory(LPCWSTR);
906/* __declspec(dllimport) */ void * __stdcall AddDllDirectory(const wchar_t *);
907
908// WINBASEAPI BOOL WINAPI FreeModule(HMODULE);
909/* __declspec(dllimport) */ int __stdcall FreeModule(void *);
910
911// WINBASEAPI DWORD WINAPI GetModuleFileNameW(HMODULE, LPWSTR, DWORD);
912/* __declspec(dllimport) */ uint32_t GetModuleFileNameW(void *, wchar_t *, uint32_t);
913
914// WINBASEAPI HMODULE WINAPI LoadLibraryExW(LPCWSTR, HANDLE, DWORD);
915/* __declspec(dllimport) */ void * __stdcall LoadLibraryExW(const wchar_t *, void *, uint32_t);
916}
917 )";
918
919 if (DynamicLoader *loader = process->GetDynamicLoader()) {
920 Status result = loader->CanLoadImage();
921 if (result.Fail())
922 return result;
923 }
924
926 if (!thread)
927 return Status::FromErrorString("selected thread is invalid");
928
929 StackFrameSP frame = thread->GetStackFrameAtIndex(0);
930 if (!frame)
931 return Status::FromErrorString("frame 0 is invalid");
932
933 ExecutionContext context;
934 frame->CalculateExecutionContext(context);
935
936 EvaluateExpressionOptions options;
937 options.SetUnwindOnError(true);
938 options.SetIgnoreBreakpoints(true);
941 // LoadLibraryEx{A,W}/FreeLibrary cannot raise exceptions which we can handle.
942 // They may potentially throw SEH exceptions which we do not know how to
943 // handle currently.
944 options.SetTrapExceptions(false);
945 options.SetTimeout(process->GetUtilityExpressionTimeout());
947
949 context, options, expression, kLoaderDecls, value);
950 if (result != eExpressionCompleted)
951 return value
952 ? value->GetError().Clone()
954 "failed to execute loader helper ({0})", toString(result));
955
956 if (value && value->GetError().Fail())
957 return value->GetError().Clone();
958
959 return Status();
960}
static const size_t word_size
static llvm::raw_ostream & error(Stream &strm)
static DynamicLoaderDarwinKernelProperties & GetGlobalProperties()
#define LLDB_LOGF(log,...)
Definition Log.h:389
static uint32_t g_initialize_count
static std::chrono::microseconds GetLoaderOneThreadTimeout(Process *process)
#define PATHCCH_MAX_CCH
#define MAX_PATH
#define LLDB_PLUGIN_DEFINE(PluginName)
static constexpr llvm::StringLiteral kName
An architecture specification class.
Definition ArchSpec.h:32
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:452
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:544
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:881
bool TripleVendorWasSpecified() const
Definition ArchSpec.h:457
bool TripleOSWasSpecified() const
Definition ArchSpec.h:461
A command line argument class.
Definition Args.h:33
Class that manages the actual breakpoint that will be inserted into the running program.
bool SetTrapOpcode(const uint8_t *trap_opcode, uint32_t trap_opcode_size)
Sets the trap opcode.
Generic representation of a type in a programming language.
CompilerType GetPointerType() const
Return a new CompilerType that is a pointer to this type.
A class to manage flag bits.
Definition Debugger.h:100
TargetList & GetTargetList()
Get accessor for the target list.
Definition Debugger.h:220
llvm::Error GetAsError(lldb::ExpressionResults result, llvm::Twine message={}) const
Returns an ExpressionError with arg as error code.
void SetOneThreadTimeout(const Timeout< std::micro > &timeout)
Definition Target.h:427
void SetUnwindOnError(bool unwind=false)
Definition Target.h:400
void SetExecutionPolicy(ExecutionPolicy policy=eExecutionPolicyAlways)
Definition Target.h:358
void SetLanguage(lldb::LanguageType language_type)
Definition Target.h:364
void SetTimeout(const Timeout< std::micro > &timeout)
Definition Target.h:421
void SetIgnoreBreakpoints(bool ignore=false)
Definition Target.h:404
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
const lldb::ProcessSP & GetProcessSP() const
Get accessor to get the process shared pointer.
const lldb::ThreadSP & GetThreadSP() const
Get accessor to get the thread shared pointer.
A file utility class.
Definition FileSpec.h:56
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition FileSpec.cpp:174
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
void Clear()
Clears the object state.
Definition FileSpec.cpp:265
ValueType Set(ValueType mask)
Set one or more flags by logical OR'ing mask with the current flags.
Definition Flags.h:73
Encapsulates a function that can be called.
ValueList GetArgumentValues() const
void DeallocateFunctionResults(ExecutionContext &exe_ctx, lldb::addr_t args_addr)
Deallocate the arguments structure.
lldb::ExpressionResults ExecuteFunction(ExecutionContext &exe_ctx, lldb::addr_t *args_addr_ptr, const EvaluateExpressionOptions &options, DiagnosticManager &diagnostic_manager, Value &results)
Run the function this FunctionCaller was created with.
bool WriteFunctionArguments(ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, DiagnosticManager &diagnostic_manager)
Insert the default function argument struct.
PlatformWindows(bool is_host)
Default Constructor.
lldb_private::Status UnloadImage(lldb_private::Process *process, uint32_t image_token) override
llvm::StringRef GetPluginName() override
std::string GetFullNameForDylib(llvm::StringRef basename) override
std::unique_ptr< lldb_private::UtilityFunction > MakeLoadImageUtilityFunction(lldb_private::ExecutionContext &context, lldb_private::Status &status)
lldb_private::Status DisconnectRemote() override
lldb::ProcessSP Attach(lldb_private::ProcessAttachInfo &attach_info, lldb_private::Debugger &debugger, lldb_private::Target *target, lldb_private::Status &error) override
Attach to an existing process using a process ID.
static llvm::StringRef GetPluginDescriptionStatic(bool is_host)
void GetStatus(lldb_private::Stream &strm) override
Report the current status for this platform.
std::vector< ArchSpec > m_supported_architectures
lldb_private::Status ConnectRemote(lldb_private::Args &args) override
lldb::ProcessSP DebugProcess(lldb_private::ProcessLaunchInfo &launch_info, lldb_private::Debugger &debugger, lldb_private::Target &target, lldb_private::Status &error) override
Subclasses do not need to implement this function as it uses the Platform::LaunchProcess() followed b...
static llvm::StringRef GetPluginNameStatic(bool is_host)
static lldb::PlatformSP CreateInstance(bool force, const lldb_private::ArchSpec *arch)
uint32_t DoLoadImage(lldb_private::Process *process, const lldb_private::FileSpec &remote_file, const std::vector< std::string > *paths, lldb_private::Status &error, lldb_private::FileSpec *loaded_path) override
static void DebuggerInitialize(Debugger &debugger)
lldb_private::Status EvaluateLoaderExpression(lldb_private::Process *process, const char *expression, lldb::ValueObjectSP &value)
bool CanDebugProcess() override
Not all platforms will support debugging a process by spawning somehow halted for a debugger (specifi...
size_t GetSoftwareBreakpointTrapOpcode(Target &target, BreakpointSite *bp_site) override
virtual size_t GetSoftwareBreakpointTrapOpcode(Target &target, BreakpointSite *bp_site)
static void Terminate()
Definition Platform.cpp:143
static void SetHostPlatform(const lldb::PlatformSP &platform_sp)
Definition Platform.cpp:150
virtual void GetStatus(Stream &strm)
Report the current status for this platform.
Definition Platform.cpp:342
static void Initialize()
Definition Platform.cpp:141
bool IsRemote() const
Definition Platform.h:557
bool IsHost() const
Definition Platform.h:553
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static lldb::OptionValuePropertiesSP GetSettingForPlatformPlugin(Debugger &debugger, llvm::StringRef setting_name)
static bool CreateSettingForPlatformPlugin(Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, llvm::StringRef description, bool is_global_property)
static bool UnregisterPlugin(ABICreateInstance create_callback)
lldb::ListenerSP GetListenerForProcess(Debugger &debugger)
Definition Process.cpp:3213
llvm::StringRef GetProcessPluginName() const
Definition Process.h:162
lldb::ListenerSP GetHijackListener() const
lldb::pid_t GetProcessID() const
Definition ProcessInfo.h:66
lldb::ListenerSP GetListener() const
Environment & GetEnvironment()
Definition ProcessInfo.h:86
llvm::StringRef GetProcessPluginName() const
std::chrono::seconds GetUtilityExpressionTimeout() const
Definition Process.cpp:346
A plug-in interface definition class for debugging a process.
Definition Process.h:359
UtilityFunction * GetLoadImageUtilityFunction(Platform *platform, llvm::function_ref< std::unique_ptr< UtilityFunction >()> factory)
Get the cached UtilityFunction that assists in loading binary images into the process.
Definition Process.cpp:6657
void ResetImageToken(size_t token)
Definition Process.cpp:6429
ThreadList & GetThreadList()
Definition Process.h:2394
lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error)
The public interface to allocating memory in the process.
Definition Process.cpp:2701
bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value, Status &error)
Definition Process.cpp:2531
virtual size_t ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition Process.cpp:2038
size_t AddImageToken(lldb::addr_t image_ptr)
Definition Process.cpp:6418
uint64_t ReadUnsignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size, uint64_t fail_value, Status &error)
Reads an unsigned integer of the specified byte size from process memory.
Definition Process.cpp:2456
lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error)
Definition Process.cpp:2517
Status DeallocateMemory(lldb::addr_t ptr)
The public interface to deallocating memory in the process.
Definition Process.cpp:2764
lldb::addr_t GetImagePtrFromToken(size_t token) const
Definition Process.cpp:6423
uint32_t GetAddressByteSize() const
Definition Process.cpp:3930
size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Write memory to a process.
Definition Process.cpp:2559
virtual DynamicLoader * GetDynamicLoader()
Get the dynamic loader plug-in for this process.
Definition Process.cpp:3107
size_t WriteScalarToMemory(lldb::addr_t vm_addr, const Scalar &scalar, size_t size, Status &error)
Write all or part of a scalar value to memory.
Definition Process.cpp:2640
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1258
A base class for platforms which automatically want to be able to forward operations to a remote plat...
unsigned int UInt(unsigned int fail_value=0) const
Definition Scalar.cpp:351
static lldb::TypeSystemClangSP GetForTarget(Target &target, std::optional< IsolatedASTKind > ast_kind=DefaultAST, bool create_on_demand=true)
Returns the scratch TypeSystemClang for the given target.
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
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:194
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
bool Success() const
Test for success condition.
Definition Status.cpp:303
const char * GetData() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
Status CreateTarget(Debugger &debugger, llvm::StringRef user_exe_path, llvm::StringRef triple_str, LoadDependentFiles get_dependent_modules, const OptionGroupPlatform *platform_options, lldb::TargetSP &target_sp)
Create a new Target.
const lldb::ProcessSP & CreateProcess(lldb::ListenerSP listener_sp, llvm::StringRef plugin_name, const FileSpec *crash_file, bool can_connect)
Definition Target.cpp:316
llvm::Expected< std::unique_ptr< UtilityFunction > > CreateUtilityFunction(std::string expression, std::string name, lldb::LanguageType language, ExecutionContext &exe_ctx)
Creates and installs a UtilityFunction for the given language.
Definition Target.cpp:2866
const ArchSpec & GetArchitecture() const
Definition Target.h:1289
lldb::ThreadSP GetExpressionExecutionThread()
static lldb::ExpressionResults Evaluate(ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, llvm::StringRef expr_cstr, llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp, std::string *fixed_expression=nullptr, ValueObject *ctx_obj=nullptr)
Evaluate one expression in the scratch context of the target passed in the exe_ctx and return its res...
"lldb/Expression/UtilityFunction.h" Encapsulates a bit of source code that provides a function that i...
FunctionCaller * GetFunctionCaller()
void PushValue(const Value &value)
Definition Value.cpp:694
Value * GetValueAtIndex(size_t idx)
Definition Value.cpp:698
const Scalar & GetScalar() const
See comment on m_scalar to understand what GetScalar returns.
Definition Value.h:114
@ Scalar
A raw scalar value.
Definition Value.h:46
void SetCompilerType(const CompilerType &compiler_type)
Definition Value.cpp:276
void SetValueType(ValueType value_type)
Definition Value.h:90
static lldb::PlatformSP CreateInstance(bool force, const ArchSpec *arch)
#define LLDB_INVALID_IMAGE_TOKEN
#define LLDB_INVALID_ADDRESS
#define LLDB_INVALID_PROCESS_ID
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
std::string toString(FormatterBytecode::OpCodes op)
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
std::shared_ptr< lldb_private::Platform > PlatformSP
@ eLanguageTypeC_plus_plus
ISO C++:1998.
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
@ eExpressionSetupError
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::TypeSystemClang > TypeSystemClangSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP