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
51namespace {
52
53#define LLDB_PROPERTIES_windows
54#include "PlatformWindowsProperties.inc"
55
56enum {
57#define LLDB_PROPERTIES_windows
58#include "PlatformWindowsPropertiesEnum.inc"
59};
60
61class PluginProperties : public Properties {
62public:
63 PluginProperties() {
64 m_collection_sp = std::make_shared<OptionValueProperties>("windows");
65 m_collection_sp->Initialize(g_windows_properties_def);
66 }
67
68 bool DisableDebugHeap() const {
69 return GetPropertyAtIndexAs<bool>(ePropertyDisableDebugHeap, true);
70 }
71};
72
73static PluginProperties &GetGlobalProperties() {
74 static PluginProperties g_settings;
75 return g_settings;
76}
77
78} // end of anonymous namespace
79
81 const lldb_private::ArchSpec *arch) {
82 // The only time we create an instance is when we are creating a remote
83 // windows platform
84 const bool is_host = false;
85
86 bool create = force;
87 if (!create && arch && arch->IsValid()) {
88 const llvm::Triple &triple = arch->GetTriple();
89 switch (triple.getVendor()) {
90 case llvm::Triple::PC:
91 create = true;
92 break;
93
94 case llvm::Triple::UnknownVendor:
95 create = !arch->TripleVendorWasSpecified();
96 break;
97
98 default:
99 break;
100 }
101
102 if (create) {
103 switch (triple.getOS()) {
104 case llvm::Triple::Win32:
105 break;
106
107 case llvm::Triple::UnknownOS:
108 create = arch->TripleOSWasSpecified();
109 break;
110
111 default:
112 create = false;
113 break;
114 }
115 }
116 }
117 if (create)
118 return PlatformSP(new PlatformWindows(is_host));
119 return PlatformSP();
120}
121
122llvm::StringRef PlatformWindows::GetPluginDescriptionStatic(bool is_host) {
123 return is_host ? "Local Windows user platform plug-in."
124 : "Remote Windows user platform plug-in.";
125}
126
128 if (!PluginManager::GetSettingForPlatformPlugin(debugger, "windows")) {
130 debugger, GetGlobalProperties().GetValueProperties(),
131 "Properties for the Windows platform plugin.",
132 /*is_global_property=*/true);
133 }
134}
135
138
139 if (g_initialize_count++ == 0) {
140#if defined(_WIN32)
141 // Force a host flag to true for the default platform object.
142 PlatformSP default_platform_sp(new PlatformWindows(true));
143 default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture());
144 Platform::SetHostPlatform(default_platform_sp);
145#endif
150 }
151}
152
162
163/// Default Constructor
165 const auto &AddArch = [&](const ArchSpec &spec) {
166 if (llvm::any_of(m_supported_architectures, [spec](const ArchSpec &rhs) {
167 return spec.IsExactMatch(rhs);
168 }))
169 return;
170 if (spec.IsValid())
171 m_supported_architectures.push_back(spec);
172 };
173 AddArch(HostInfo::GetArchitecture(HostInfo::eArchKindDefault));
174 AddArch(HostInfo::GetArchitecture(HostInfo::eArchKind32));
175 AddArch(HostInfo::GetArchitecture(HostInfo::eArchKind64));
176}
177
179 if (IsHost())
181 "can't connect to the host platform '{0}', always connected",
182 GetPluginName());
183
187 /*force=*/true, nullptr);
188
191 "failed to create a 'remote-gdb-server' platform");
192
193 Status error = m_remote_platform_sp->ConnectRemote(args);
194 if (error.Fail())
195 m_remote_platform_sp.reset();
196
197 return error;
198}
199
201 const FileSpec &remote_file,
202 const std::vector<std::string> *paths,
203 Status &error, FileSpec *loaded_image) {
204 DiagnosticManager diagnostics;
205
206 if (loaded_image)
207 loaded_image->Clear();
208
210 if (!thread) {
212 "LoadLibrary error: no thread available to invoke LoadLibrary");
214 }
215
216 ExecutionContext context;
217 thread->CalculateExecutionContext(context);
218
219 Status status;
220 UtilityFunction *loader =
221 process->GetLoadImageUtilityFunction(this, [&]() -> std::unique_ptr<UtilityFunction> {
222 return MakeLoadImageUtilityFunction(context, status);
223 });
224 if (loader == nullptr)
226
227 FunctionCaller *invocation = loader->GetFunctionCaller();
228 if (!invocation) {
230 "LoadLibrary error: could not get function caller");
232 }
233
234 /* Convert name */
235 llvm::SmallVector<llvm::UTF16, 261> name;
236 if (!llvm::convertUTF8ToUTF16String(remote_file.GetPath(), name)) {
238 "LoadLibrary error: could not convert path to UCS2");
240 }
241 name.emplace_back(L'\0');
242
243 /* Inject name paramter into inferior */
244 lldb::addr_t injected_name =
245 process->AllocateMemory(name.size() * sizeof(llvm::UTF16),
246 ePermissionsReadable | ePermissionsWritable,
247 status);
248 if (injected_name == LLDB_INVALID_ADDRESS) {
250 "LoadLibrary error: unable to allocate memory for name: %s",
251 status.AsCString());
253 }
254
255 llvm::scope_exit name_cleanup(
256 [process, injected_name]() { process->DeallocateMemory(injected_name); });
257
258 process->WriteMemory(injected_name, name.data(),
259 name.size() * sizeof(llvm::UTF16), status);
260 if (status.Fail()) {
262 "LoadLibrary error: unable to write name: %s", status.AsCString());
264 }
265
266 /* Inject paths parameter into inferior */
267 lldb::addr_t injected_paths{0x0};
268 std::optional<llvm::scope_exit<std::function<void()>>> paths_cleanup;
269 if (paths) {
270 llvm::SmallVector<llvm::UTF16, 261> search_paths;
271
272 for (const auto &path : *paths) {
273 if (path.empty())
274 continue;
275
276 llvm::SmallVector<llvm::UTF16, 261> buffer;
277 if (!llvm::convertUTF8ToUTF16String(path, buffer))
278 continue;
279
280 search_paths.append(std::begin(buffer), std::end(buffer));
281 search_paths.emplace_back(L'\0');
282 }
283 search_paths.emplace_back(L'\0');
284
285 injected_paths =
286 process->AllocateMemory(search_paths.size() * sizeof(llvm::UTF16),
287 ePermissionsReadable | ePermissionsWritable,
288 status);
289 if (injected_paths == LLDB_INVALID_ADDRESS) {
291 "LoadLibrary error: unable to allocate memory for paths: %s",
292 status.AsCString());
294 }
295
296 paths_cleanup.emplace([process, injected_paths]() {
297 process->DeallocateMemory(injected_paths);
298 });
299
300 process->WriteMemory(injected_paths, search_paths.data(),
301 search_paths.size() * sizeof(llvm::UTF16), status);
302 if (status.Fail()) {
304 "LoadLibrary error: unable to write paths: %s", status.AsCString());
306 }
307 }
308
309 /* Inject wszModulePath into inferior */
310 // Start with a MAX_PATH-sized buffer (enough for the vast majority of module
311 // paths) and grow it on demand if GetModuleFileNameW reports truncation (see
312 // the loop after the helper runs).
313 unsigned injected_length = MAX_PATH;
314
315 lldb::addr_t injected_module_path = process->AllocateMemory(
316 (injected_length + 1) * sizeof(llvm::UTF16),
317 ePermissionsReadable | ePermissionsWritable, status);
318 if (injected_module_path == LLDB_INVALID_ADDRESS) {
320 "LoadLibrary error: unable to allocate memory for module location: %s",
321 status.AsCString());
323 }
324
325 llvm::scope_exit injected_module_path_cleanup(
326 [process, injected_module_path]() {
327 process->DeallocateMemory(injected_module_path);
328 });
329
330 /* Inject __lldb_LoadLibraryResult into inferior */
331 const uint32_t word_size = process->GetAddressByteSize();
332 lldb::addr_t injected_result =
333 process->AllocateMemory(3 * word_size,
334 ePermissionsReadable | ePermissionsWritable,
335 status);
336 if (status.Fail()) {
338 "LoadLibrary error: could not allocate memory for result: %s",
339 status.AsCString());
341 }
342
343 llvm::scope_exit result_cleanup([process, injected_result]() {
344 process->DeallocateMemory(injected_result);
345 });
346
347 std::vector<lldb::addr_t> grown_path_buffers;
348 llvm::scope_exit grown_path_cleanup([&]() {
349 for (lldb::addr_t buffer : grown_path_buffers)
350 process->DeallocateMemory(buffer);
351 });
352
353 process->WritePointerToMemory(injected_result, 0, status);
354 if (status.Fail()) {
356 "LoadLibrary error: could not initialize result: %s",
357 status.AsCString());
359 }
360
361 process->WritePointerToMemory(injected_result + word_size,
362 injected_module_path, status);
363 if (status.Fail()) {
365 "LoadLibrary error: could not initialize result: %s",
366 status.AsCString());
368 }
369
370 // XXX(compnerd) should we use the compiler to get the sizeof(unsigned)?
371 process->WriteScalarToMemory(injected_result + 2 * word_size,
372 Scalar{injected_length}, sizeof(unsigned),
373 status);
374 if (status.Fail()) {
376 "LoadLibrary error: could not initialize result: %s",
377 status.AsCString());
379 }
380
381 /* Setup Formal Parameters */
382 ValueList parameters = invocation->GetArgumentValues();
383 parameters.GetValueAtIndex(0)->GetScalar() = injected_name;
384 parameters.GetValueAtIndex(1)->GetScalar() = injected_paths;
385 parameters.GetValueAtIndex(2)->GetScalar() = injected_result;
386
387 lldb::addr_t injected_parameters = LLDB_INVALID_ADDRESS;
388 diagnostics.Clear();
389 if (!invocation->WriteFunctionArguments(context, injected_parameters,
390 parameters, diagnostics)) {
391 error = Status::FromError(diagnostics.GetAsError(
393 "LoadLibrary error: unable to write function parameters:"));
395 }
396
397 llvm::scope_exit parameter_cleanup(
398 [invocation, &context, injected_parameters]() {
399 invocation->DeallocateFunctionResults(context, injected_parameters);
400 });
401
402 TypeSystemClangSP scratch_ts_sp =
404 if (!scratch_ts_sp) {
406 "LoadLibrary error: unable to get (clang) type system");
408 }
409
410 /* Setup Return Type */
411 CompilerType VoidPtrTy =
412 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
413
414 Value value;
415 value.SetCompilerType(VoidPtrTy);
416
417 /* Invoke expression */
421 options.SetIgnoreBreakpoints(true);
422 options.SetUnwindOnError(true);
423 // LoadLibraryEx{A,W}/FreeLibrary cannot raise exceptions which we can handle.
424 // They may potentially throw SEH exceptions which we do not know how to
425 // handle currently.
426 options.SetTrapExceptions(false);
427 options.SetTimeout(process->GetUtilityExpressionTimeout());
428 options.SetOneThreadTimeout(std::min<std::chrono::microseconds>(
429 std::chrono::seconds(5), process->GetUtilityExpressionTimeout() / 2));
430 options.SetIsForUtilityExpr(true);
431
432 ExpressionResults result =
433 invocation->ExecuteFunction(context, &injected_parameters, options,
434 diagnostics, value);
435 if (result != eExpressionCompleted) {
436 error = Status::FromError(diagnostics.GetAsError(
438 llvm::formatv("failed to execute LoadLibrary helper "
439 "({0}):",
440 toString(result))
441 .str()));
443 }
444
445 /* Read result */
446 lldb::addr_t token = process->ReadPointerFromMemory(injected_result, status);
447 if (status.Fail()) {
449 "LoadLibrary error: could not read the result: %s", status.AsCString());
451 }
452
453 if (!token) {
454 // ErrorCode is a 4-byte `unsigned` field in __lldb_LoadLibraryResult.
455 uint64_t error_code = process->ReadUnsignedIntegerFromMemory(
456 injected_result + 2 * word_size + sizeof(unsigned), sizeof(unsigned), 0,
457 status);
458 if (status.Fail()) {
460 "LoadLibrary error: could not read error status: %s",
461 status.AsCString());
463 }
464
465 error = Status::FromErrorStringWithFormat("LoadLibrary Error: %" PRIu64,
466 error_code);
468 }
469
470 lldb::addr_t module_path_addr = injected_module_path;
471 unsigned capacity = injected_length;
472 uint32_t path_length = process->ReadUnsignedIntegerFromMemory(
473 injected_result + 2 * word_size, sizeof(unsigned), 0, status);
474 while (status.Success() && path_length >= capacity &&
475 capacity < PATHCCH_MAX_CCH) {
476 capacity = std::min<unsigned>(capacity * 2, PATHCCH_MAX_CCH);
477 lldb::addr_t buffer = process->AllocateMemory(
478 (capacity + 1) * sizeof(llvm::UTF16),
479 ePermissionsReadable | ePermissionsWritable, status);
480 if (buffer == LLDB_INVALID_ADDRESS || status.Fail())
481 break;
482 grown_path_buffers.push_back(buffer);
483
484 process->WritePointerToMemory(injected_result + word_size, buffer, status);
485 if (status.Fail())
486 break;
487 process->WriteScalarToMemory(injected_result + 2 * word_size,
488 Scalar{capacity}, sizeof(unsigned), status);
489 if (status.Fail())
490 break;
491
492 diagnostics.Clear();
493 if (invocation->ExecuteFunction(context, &injected_parameters, options,
494 diagnostics, value) != eExpressionCompleted)
495 break;
496 module_path_addr = buffer;
497 path_length = process->ReadUnsignedIntegerFromMemory(
498 injected_result + 2 * word_size, sizeof(unsigned), 0, status);
499 }
500
501 llvm::SmallVector<llvm::UTF16, MAX_PATH> wide_path(path_length);
502 if (path_length)
503 process->ReadMemory(module_path_addr, wide_path.data(),
504 path_length * sizeof(llvm::UTF16), status);
505 if (status.Fail()) {
507 "LoadLibrary error: could not read module path: %s",
508 status.AsCString());
510 }
511
512 std::string module_path;
513 if (!llvm::convertUTF16ToUTF8String(
514 llvm::ArrayRef<llvm::UTF16>(wide_path.data(), wide_path.size()),
515 module_path)) {
517 "LoadLibrary error: could not convert module path to UTF-8");
519 }
520
521 if (loaded_image)
522 loaded_image->SetFile(module_path, llvm::sys::path::Style::native);
523 return process->AddImageToken(token);
524}
525
526Status PlatformWindows::UnloadImage(Process *process, uint32_t image_token) {
527 const addr_t address = process->GetImagePtrFromToken(image_token);
528 if (address == LLDB_INVALID_ADDRESS)
529 return Status::FromErrorString("invalid image token");
530
531 StreamString expression;
532 expression.Printf("FreeLibrary((HMODULE)0x%" PRIx64 ")", address);
533
534 ValueObjectSP value;
535 Status result =
536 EvaluateLoaderExpression(process, expression.GetData(), value);
537 if (result.Fail())
538 return result;
539
540 if (value->GetError().Fail())
541 return value->GetError().Clone();
542
543 Scalar scalar;
544 if (value->ResolveValue(scalar)) {
545 if (scalar.UInt(1))
546 return Status::FromErrorStringWithFormat("expression failed: \"%s\"",
547 expression.GetData());
548 process->ResetImageToken(image_token);
549 }
550
551 return Status();
552}
553
556
557 if (IsHost()) {
559 "can't disconnect from the host platform '{0}', always connected",
560 GetPluginName());
561 } else {
563 error = m_remote_platform_sp->DisconnectRemote();
564 else
565 error =
566 Status::FromErrorString("the platform is not currently connected");
567 }
568 return error;
569}
570
572 Debugger &debugger, Target &target,
573 Status &error) {
574 // Windows has special considerations that must be followed when launching or
575 // attaching to a process. The key requirement is that when launching or
576 // attaching to a process, you must do it from the same the thread that will
577 // go into a permanent loop which will then receive debug events from the
578 // process. In particular, this means we can't use any of LLDB's generic
579 // mechanisms to do it for us, because it doesn't have the special knowledge
580 // required for setting up the background thread or passing the right flags.
581 //
582 // Another problem is that LLDB's standard model for debugging a process
583 // is to first launch it, have it stop at the entry point, and then attach to
584 // it. In Windows this doesn't quite work, you have to specify as an
585 // argument to CreateProcess() that you're going to debug the process. So we
586 // override DebugProcess here to handle this. Launch operations go directly
587 // to the process plugin, and attach operations almost go directly to the
588 // process plugin (but we hijack the events first). In essence, we
589 // encapsulate all the logic of Launching and Attaching in the process
590 // plugin, and PlatformWindows::DebugProcess is just a pass-through to get to
591 // the process plugin.
592
593 if (IsRemote()) {
595 return m_remote_platform_sp->DebugProcess(launch_info, debugger, target,
596 error);
597 else
598 error =
599 Status::FromErrorString("the platform is not currently connected");
600 }
601
602 if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {
603 // This is a process attach. Don't need to launch anything.
604 ProcessAttachInfo attach_info(launch_info);
605 return Attach(attach_info, debugger, &target, error);
606 }
607
608 Environment &env = launch_info.GetEnvironment();
609 if (GetGlobalProperties().DisableDebugHeap() &&
610 !env.contains("_NO_DEBUG_HEAP")) {
611 env.try_emplace("_NO_DEBUG_HEAP", "1");
612 }
613
614 ProcessSP process_sp =
615 target.CreateProcess(launch_info.GetListener(),
616 launch_info.GetProcessPluginName(), nullptr, false);
617 if (!process_sp)
618 return nullptr;
619
620 process_sp->HijackProcessEvents(launch_info.GetHijackListener());
621
622 // We need to launch and attach to the process.
623 launch_info.GetFlags().Set(eLaunchFlagDebug);
624 error = process_sp->Launch(launch_info);
625#ifdef _WIN32
626 if (error.Success()) {
627 process_sp->SetPseudoConsoleHandle();
628 } else {
630 LLDB_LOGF(log, "Platform::%s LaunchProcess() failed: %s", __FUNCTION__,
631 error.AsCString());
632 }
633#endif
634
635 return process_sp;
636}
637
639 Debugger &debugger, Target *target,
640 Status &error) {
641 error.Clear();
642 lldb::ProcessSP process_sp;
643 if (!IsHost()) {
645 process_sp =
646 m_remote_platform_sp->Attach(attach_info, debugger, target, error);
647 else
648 error =
649 Status::FromErrorString("the platform is not currently connected");
650 return process_sp;
651 }
652
653 if (target == nullptr) {
654 TargetSP new_target_sp;
655 error = debugger.GetTargetList().CreateTarget(
656 debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
657 target = new_target_sp.get();
658 }
659
660 if (!target || error.Fail())
661 return process_sp;
662
663 process_sp =
664 target->CreateProcess(attach_info.GetListenerForProcess(debugger),
665 attach_info.GetProcessPluginName(), nullptr, false);
666
667 process_sp->HijackProcessEvents(attach_info.GetHijackListener());
668 if (process_sp)
669 error = process_sp->Attach(attach_info);
670
671 return process_sp;
672}
673
676
677#ifdef _WIN32
678 llvm::VersionTuple version = HostInfo::GetOSVersion();
679 strm << " Host: Windows " << version.getAsString() << '\n';
680#endif
681}
682
683bool PlatformWindows::CanDebugProcess() { return true; }
684
686 if (basename.IsEmpty())
687 return basename;
688
689 StreamString stream;
690 stream.Printf("%s.dll", basename.GetCString());
691 return ConstString(stream.GetString());
692}
693
694size_t
696 BreakpointSite *bp_site) {
697 ArchSpec arch = target.GetArchitecture();
698 assert(arch.IsValid());
699 const uint8_t *trap_opcode = nullptr;
700 size_t trap_opcode_size = 0;
701
702 switch (arch.GetMachine()) {
703 case llvm::Triple::aarch64: {
704 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x3e, 0xd4}; // brk #0xf000
705 trap_opcode = g_aarch64_opcode;
706 trap_opcode_size = sizeof(g_aarch64_opcode);
707
708 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
709 return trap_opcode_size;
710 return 0;
711 } break;
712
713 case llvm::Triple::arm:
714 case llvm::Triple::thumb: {
715 static const uint8_t g_thumb_opcode[] = {0xfe, 0xde}; // udf #0xfe
716 trap_opcode = g_thumb_opcode;
717 trap_opcode_size = sizeof(g_thumb_opcode);
718
719 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
720 return trap_opcode_size;
721 return 0;
722 } break;
723
724 default:
725 return Platform::GetSoftwareBreakpointTrapOpcode(target, bp_site);
726 }
727}
728
729std::unique_ptr<UtilityFunction>
731 Status &status) {
732 // FIXME(compnerd) `-fdeclspec` is not passed to the clang instance?
733 static constexpr const char kLoaderDecls[] = R"(
734extern "C" {
735// errhandlingapi.h
736
737// `LOAD_LIBRARY_SEARCH_APPLICATION_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_USER_DIRS`
738//
739// Directories in the standard search path are not searched. This value cannot
740// be combined with `LOAD_WITH_ALTERED_SEARCH_PATH`.
741//
742// This value represents the recommended maximum number of directories an
743// application should include in its DLL search path.
744#define LOAD_LIBRARY_SEARCH_DEFAULT_DIRS 0x00001000
745
746// If this value is used, and lpFileName specifies an absolute path, the system
747// uses the alternate file search strategy to find associated executable
748// modules.
749#define LOAD_WITH_ALTERED_SEARCH_PATH 0x00000008
750
751// WINBASEAPI DWORD WINAPI GetLastError(VOID);
752/* __declspec(dllimport) */ uint32_t __stdcall GetLastError();
753
754// libloaderapi.h
755
756// WINBASEAPI DLL_DIRECTORY_COOKIE WINAPI AddDllDirectory(LPCWSTR);
757/* __declspec(dllimport) */ void * __stdcall AddDllDirectory(const wchar_t *);
758
759// WINBASEAPI BOOL WINAPI FreeModule(HMODULE);
760/* __declspec(dllimport) */ int __stdcall FreeModule(void *hLibModule);
761
762// WINBASEAPI DWORD WINAPI GetModuleFileNameW(HMODULE hModule, LPWSTR lpFilename, DWORD nSize);
763/* __declspec(dllimport) */ uint32_t GetModuleFileNameW(void *, wchar_t *, uint32_t);
764
765// WINBASEAPI HMODULE WINAPI LoadLibraryExW(LPCWSTR, HANDLE, DWORD);
766/* __declspec(dllimport) */ void * __stdcall LoadLibraryExW(const wchar_t *, void *, uint32_t);
767
768// corecrt_wstring.h
769
770// _ACRTIMP size_t __cdecl wcslen(wchar_t const *_String);
771/* __declspec(dllimport) */ size_t __cdecl wcslen(const wchar_t *);
772
773// lldb specific code
774
775struct __lldb_LoadLibraryResult {
776 void *ImageBase;
777 wchar_t *ModulePath;
778 unsigned Length;
779 unsigned ErrorCode;
780};
781
782_Static_assert(sizeof(struct __lldb_LoadLibraryResult) <= 3 * sizeof(void *),
783 "__lldb_LoadLibraryResult size mismatch");
784
785void * __lldb_LoadLibraryHelper(const wchar_t *name, const wchar_t *paths,
786 __lldb_LoadLibraryResult *result) {
787 // When the caller presets ImageBase the module is already loaded and we are
788 // only re-querying its path with a larger buffer. Skip LoadLibrary in that
789 // case so we do not take an extra reference on the module.
790 if (result->ImageBase == nullptr) {
791 for (const wchar_t *path = paths; path && *path; ) {
792 (void)AddDllDirectory(path);
793 path += wcslen(path) + 1;
794 }
795
796 result->ImageBase = LoadLibraryExW(name, nullptr,
797 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
798
799 // Fallback: if the AddDllDirectory + LOAD_LIBRARY_SEARCH_DEFAULT_DIRS path
800 // failed to find the library, iterate the search paths ourselves and
801 // load by absolute path using LOAD_WITH_ALTERED_SEARCH_PATH, which makes
802 // Windows use the loaded DLL's own directory to resolve its sibling imports.
803 if (result->ImageBase == nullptr) {
804 wchar_t full[4096];
805 for (const wchar_t *path = paths; path && *path; path += wcslen(path) + 1) {
806 size_t plen = wcslen(path);
807 size_t nlen = wcslen(name);
808 // Need room for: path + '\\' + name + '\0'
809 if (plen + 1 + nlen + 1 > 4096)
810 continue;
811 wchar_t *p = full;
812 for (size_t i = 0; i < plen; ++i)
813 *p++ = path[i];
814 *p++ = L'\\';
815 for (size_t i = 0; i <= nlen; ++i) // Copy name including trailing '\0'.
816 *p++ = name[i];
817 result->ImageBase = LoadLibraryExW(full, nullptr,
818 LOAD_WITH_ALTERED_SEARCH_PATH);
819 if (result->ImageBase != nullptr)
820 break;
821 }
822 }
823 }
824
825 if (result->ImageBase == nullptr)
826 result->ErrorCode = GetLastError();
827 else
828 result->Length = GetModuleFileNameW(result->ImageBase, result->ModulePath,
829 result->Length);
830
831 return result->ImageBase;
832}
833}
834 )";
835
836 static constexpr const char kName[] = "__lldb_LoadLibraryHelper";
837
838 ProcessSP process = context.GetProcessSP();
839 Target &target = process->GetTarget();
840
841 auto function = target.CreateUtilityFunction(std::string{kLoaderDecls}, kName,
843 context);
844 if (!function) {
845 std::string error = llvm::toString(function.takeError());
847 "LoadLibrary error: could not create utility function: %s",
848 error.c_str());
849 return nullptr;
850 }
851
852 TypeSystemClangSP scratch_ts_sp =
854 if (!scratch_ts_sp)
855 return nullptr;
856
857 CompilerType VoidPtrTy =
858 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
859 CompilerType WCharPtrTy =
860 scratch_ts_sp->GetBasicType(eBasicTypeWChar).GetPointerType();
861
862 ValueList parameters;
863
864 Value value;
866
867 value.SetCompilerType(WCharPtrTy);
868 parameters.PushValue(value); // name
869 parameters.PushValue(value); // paths
870
871 value.SetCompilerType(VoidPtrTy);
872 parameters.PushValue(value); // result
873
875 std::unique_ptr<UtilityFunction> utility{std::move(*function)};
876 utility->MakeFunctionCaller(VoidPtrTy, parameters, context.GetThreadSP(),
877 error);
878 if (error.Fail()) {
880 "LoadLibrary error: could not create function caller: %s",
881 error.AsCString());
882 return nullptr;
883 }
884
885 if (!utility->GetFunctionCaller()) {
887 "LoadLibrary error: could not get function caller");
888 return nullptr;
889 }
890
891 return utility;
892}
893
895 const char *expression,
896 ValueObjectSP &value) {
897 // FIXME(compnerd) `-fdeclspec` is not passed to the clang instance?
898 static constexpr const char kLoaderDecls[] = R"(
899extern "C" {
900// libloaderapi.h
901
902// WINBASEAPI DLL_DIRECTORY_COOKIE WINAPI AddDllDirectory(LPCWSTR);
903/* __declspec(dllimport) */ void * __stdcall AddDllDirectory(const wchar_t *);
904
905// WINBASEAPI BOOL WINAPI FreeModule(HMODULE);
906/* __declspec(dllimport) */ int __stdcall FreeModule(void *);
907
908// WINBASEAPI DWORD WINAPI GetModuleFileNameW(HMODULE, LPWSTR, DWORD);
909/* __declspec(dllimport) */ uint32_t GetModuleFileNameW(void *, wchar_t *, uint32_t);
910
911// WINBASEAPI HMODULE WINAPI LoadLibraryExW(LPCWSTR, HANDLE, DWORD);
912/* __declspec(dllimport) */ void * __stdcall LoadLibraryExW(const wchar_t *, void *, uint32_t);
913}
914 )";
915
916 if (DynamicLoader *loader = process->GetDynamicLoader()) {
917 Status result = loader->CanLoadImage();
918 if (result.Fail())
919 return result;
920 }
921
923 if (!thread)
924 return Status::FromErrorString("selected thread is invalid");
925
926 StackFrameSP frame = thread->GetStackFrameAtIndex(0);
927 if (!frame)
928 return Status::FromErrorString("frame 0 is invalid");
929
930 ExecutionContext context;
931 frame->CalculateExecutionContext(context);
932
933 EvaluateExpressionOptions options;
934 options.SetUnwindOnError(true);
935 options.SetIgnoreBreakpoints(true);
938 // LoadLibraryEx{A,W}/FreeLibrary cannot raise exceptions which we can handle.
939 // They may potentially throw SEH exceptions which we do not know how to
940 // handle currently.
941 options.SetTrapExceptions(false);
942 options.SetTimeout(process->GetUtilityExpressionTimeout());
943 options.SetOneThreadTimeout(std::min<std::chrono::microseconds>(
944 std::chrono::seconds(5), process->GetUtilityExpressionTimeout() / 2));
945
947 context, options, expression, kLoaderDecls, value);
948 if (result != eExpressionCompleted)
949 return value
950 ? value->GetError().Clone()
952 "failed to execute loader helper ({0})", toString(result));
953
954 if (value && value->GetError().Fail())
955 return value->GetError().Clone();
956
957 return Status();
958}
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
#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 uniqued constant string class.
Definition ConstString.h:40
bool IsEmpty() const
Test for empty string.
const char * GetCString() const
Get the string value as a C string.
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:57
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:376
void Clear()
Clears the object state.
Definition FileSpec.cpp:261
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::unique_ptr< lldb_private::UtilityFunction > MakeLoadImageUtilityFunction(lldb_private::ExecutionContext &context, lldb_private::Status &status)
lldb_private::Status DisconnectRemote() override
ConstString GetFullNameForDylib(ConstString basename) 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:561
bool IsHost() const
Definition Platform.h:557
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
llvm::StringRef GetString() 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:2859
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