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