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 <cstdio>
12#include <optional>
13#if defined(_WIN32)
15#include <winsock2.h>
16#endif
17
22#include "lldb/Core/Debugger.h"
23#include "lldb/Core/Module.h"
29#include "lldb/Host/HostInfo.h"
31#include "lldb/Target/Process.h"
32#include "lldb/Utility/Status.h"
33
34#include "llvm/ADT/ScopeExit.h"
35#include "llvm/Support/ConvertUTF.h"
36
37using namespace lldb;
38using namespace lldb_private;
39
41
42static uint32_t g_initialize_count = 0;
43
45 const lldb_private::ArchSpec *arch) {
46 // The only time we create an instance is when we are creating a remote
47 // windows platform
48 const bool is_host = false;
49
50 bool create = force;
51 if (!create && arch && arch->IsValid()) {
52 const llvm::Triple &triple = arch->GetTriple();
53 switch (triple.getVendor()) {
54 case llvm::Triple::PC:
55 create = true;
56 break;
57
58 case llvm::Triple::UnknownVendor:
59 create = !arch->TripleVendorWasSpecified();
60 break;
61
62 default:
63 break;
64 }
65
66 if (create) {
67 switch (triple.getOS()) {
68 case llvm::Triple::Win32:
69 break;
70
71 case llvm::Triple::UnknownOS:
72 create = arch->TripleOSWasSpecified();
73 break;
74
75 default:
76 create = false;
77 break;
78 }
79 }
80 }
81 if (create)
82 return PlatformSP(new PlatformWindows(is_host));
83 return PlatformSP();
84}
85
86llvm::StringRef PlatformWindows::GetPluginDescriptionStatic(bool is_host) {
87 return is_host ? "Local Windows user platform plug-in."
88 : "Remote Windows user platform plug-in.";
89}
90
93
94 if (g_initialize_count++ == 0) {
95#if defined(_WIN32)
96 // Force a host flag to true for the default platform object.
97 PlatformSP default_platform_sp(new PlatformWindows(true));
98 default_platform_sp->SetSystemArchitecture(HostInfo::GetArchitecture());
99 Platform::SetHostPlatform(default_platform_sp);
100#endif
105 }
106}
107
117
118/// Default Constructor
120 const auto &AddArch = [&](const ArchSpec &spec) {
121 if (llvm::any_of(m_supported_architectures, [spec](const ArchSpec &rhs) {
122 return spec.IsExactMatch(rhs);
123 }))
124 return;
125 if (spec.IsValid())
126 m_supported_architectures.push_back(spec);
127 };
128 AddArch(HostInfo::GetArchitecture(HostInfo::eArchKindDefault));
129 AddArch(HostInfo::GetArchitecture(HostInfo::eArchKind32));
130 AddArch(HostInfo::GetArchitecture(HostInfo::eArchKind64));
131}
132
134 if (IsHost())
136 "can't connect to the host platform '{0}', always connected",
137 GetPluginName());
138
142 /*force=*/true, nullptr);
143
146 "failed to create a 'remote-gdb-server' platform");
147
148 Status error = m_remote_platform_sp->ConnectRemote(args);
149 if (error.Fail())
150 m_remote_platform_sp.reset();
151
152 return error;
153}
154
156 const FileSpec &remote_file,
157 const std::vector<std::string> *paths,
158 Status &error, FileSpec *loaded_image) {
159 DiagnosticManager diagnostics;
160
161 if (loaded_image)
162 loaded_image->Clear();
163
165 if (!thread) {
167 "LoadLibrary error: no thread available to invoke LoadLibrary");
169 }
170
171 ExecutionContext context;
172 thread->CalculateExecutionContext(context);
173
174 Status status;
175 UtilityFunction *loader =
176 process->GetLoadImageUtilityFunction(this, [&]() -> std::unique_ptr<UtilityFunction> {
177 return MakeLoadImageUtilityFunction(context, status);
178 });
179 if (loader == nullptr)
181
182 FunctionCaller *invocation = loader->GetFunctionCaller();
183 if (!invocation) {
185 "LoadLibrary error: could not get function caller");
187 }
188
189 /* Convert name */
190 llvm::SmallVector<llvm::UTF16, 261> name;
191 if (!llvm::convertUTF8ToUTF16String(remote_file.GetPath(), name)) {
193 "LoadLibrary error: could not convert path to UCS2");
195 }
196 name.emplace_back(L'\0');
197
198 /* Inject name paramter into inferior */
199 lldb::addr_t injected_name =
200 process->AllocateMemory(name.size() * sizeof(llvm::UTF16),
201 ePermissionsReadable | ePermissionsWritable,
202 status);
203 if (injected_name == LLDB_INVALID_ADDRESS) {
205 "LoadLibrary error: unable to allocate memory for name: %s",
206 status.AsCString());
208 }
209
210 llvm::scope_exit name_cleanup(
211 [process, injected_name]() { process->DeallocateMemory(injected_name); });
212
213 process->WriteMemory(injected_name, name.data(),
214 name.size() * sizeof(llvm::UTF16), status);
215 if (status.Fail()) {
217 "LoadLibrary error: unable to write name: %s", status.AsCString());
219 }
220
221 /* Inject paths parameter into inferior */
222 lldb::addr_t injected_paths{0x0};
223 std::optional<llvm::scope_exit<std::function<void()>>> paths_cleanup;
224 if (paths) {
225 llvm::SmallVector<llvm::UTF16, 261> search_paths;
226
227 for (const auto &path : *paths) {
228 if (path.empty())
229 continue;
230
231 llvm::SmallVector<llvm::UTF16, 261> buffer;
232 if (!llvm::convertUTF8ToUTF16String(path, buffer))
233 continue;
234
235 search_paths.append(std::begin(buffer), std::end(buffer));
236 search_paths.emplace_back(L'\0');
237 }
238 search_paths.emplace_back(L'\0');
239
240 injected_paths =
241 process->AllocateMemory(search_paths.size() * sizeof(llvm::UTF16),
242 ePermissionsReadable | ePermissionsWritable,
243 status);
244 if (injected_paths == LLDB_INVALID_ADDRESS) {
246 "LoadLibrary error: unable to allocate memory for paths: %s",
247 status.AsCString());
249 }
250
251 paths_cleanup.emplace([process, injected_paths]() {
252 process->DeallocateMemory(injected_paths);
253 });
254
255 process->WriteMemory(injected_paths, search_paths.data(),
256 search_paths.size() * sizeof(llvm::UTF16), status);
257 if (status.Fail()) {
259 "LoadLibrary error: unable to write paths: %s", status.AsCString());
261 }
262 }
263
264 /* Inject wszModulePath into inferior */
265 // FIXME(compnerd) should do something better for the length?
266 // GetModuleFileNameA is likely limited to PATH_MAX rather than the NT path
267 // limit.
268 unsigned injected_length = 261;
269
270 lldb::addr_t injected_module_path =
271 process->AllocateMemory(injected_length + 1,
272 ePermissionsReadable | ePermissionsWritable,
273 status);
274 if (injected_module_path == LLDB_INVALID_ADDRESS) {
276 "LoadLibrary error: unable to allocate memory for module location: %s",
277 status.AsCString());
279 }
280
281 llvm::scope_exit injected_module_path_cleanup(
282 [process, injected_module_path]() {
283 process->DeallocateMemory(injected_module_path);
284 });
285
286 /* Inject __lldb_LoadLibraryResult into inferior */
287 const uint32_t word_size = process->GetAddressByteSize();
288 lldb::addr_t injected_result =
289 process->AllocateMemory(3 * word_size,
290 ePermissionsReadable | ePermissionsWritable,
291 status);
292 if (status.Fail()) {
294 "LoadLibrary error: could not allocate memory for result: %s",
295 status.AsCString());
297 }
298
299 llvm::scope_exit result_cleanup([process, injected_result]() {
300 process->DeallocateMemory(injected_result);
301 });
302
303 process->WritePointerToMemory(injected_result + word_size,
304 injected_module_path, status);
305 if (status.Fail()) {
307 "LoadLibrary error: could not initialize result: %s",
308 status.AsCString());
310 }
311
312 // XXX(compnerd) should we use the compiler to get the sizeof(unsigned)?
313 process->WriteScalarToMemory(injected_result + 2 * word_size,
314 Scalar{injected_length}, sizeof(unsigned),
315 status);
316 if (status.Fail()) {
318 "LoadLibrary error: could not initialize result: %s",
319 status.AsCString());
321 }
322
323 /* Setup Formal Parameters */
324 ValueList parameters = invocation->GetArgumentValues();
325 parameters.GetValueAtIndex(0)->GetScalar() = injected_name;
326 parameters.GetValueAtIndex(1)->GetScalar() = injected_paths;
327 parameters.GetValueAtIndex(2)->GetScalar() = injected_result;
328
329 lldb::addr_t injected_parameters = LLDB_INVALID_ADDRESS;
330 diagnostics.Clear();
331 if (!invocation->WriteFunctionArguments(context, injected_parameters,
332 parameters, diagnostics)) {
333 error = Status::FromError(diagnostics.GetAsError(
335 "LoadLibrary error: unable to write function parameters:"));
337 }
338
339 llvm::scope_exit parameter_cleanup(
340 [invocation, &context, injected_parameters]() {
341 invocation->DeallocateFunctionResults(context, injected_parameters);
342 });
343
344 TypeSystemClangSP scratch_ts_sp =
346 if (!scratch_ts_sp) {
348 "LoadLibrary error: unable to get (clang) type system");
350 }
351
352 /* Setup Return Type */
353 CompilerType VoidPtrTy =
354 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
355
356 Value value;
357 value.SetCompilerType(VoidPtrTy);
358
359 /* Invoke expression */
363 options.SetIgnoreBreakpoints(true);
364 options.SetUnwindOnError(true);
365 // LoadLibraryEx{A,W}/FreeLibrary cannot raise exceptions which we can handle.
366 // They may potentially throw SEH exceptions which we do not know how to
367 // handle currently.
368 options.SetTrapExceptions(false);
369 options.SetTimeout(process->GetUtilityExpressionTimeout());
370 options.SetIsForUtilityExpr(true);
371
372 ExpressionResults result =
373 invocation->ExecuteFunction(context, &injected_parameters, options,
374 diagnostics, value);
375 if (result != eExpressionCompleted) {
376 error = Status::FromError(diagnostics.GetAsError(
378 "LoadLibrary error: failed to execute LoadLibrary helper:"));
380 }
381
382 /* Read result */
383 lldb::addr_t token = process->ReadPointerFromMemory(injected_result, status);
384 if (status.Fail()) {
386 "LoadLibrary error: could not read the result: %s", status.AsCString());
388 }
389
390 if (!token) {
391 // ErrorCode is a 4-byte `unsigned` field in __lldb_LoadLibraryResult.
392 uint64_t error_code = process->ReadUnsignedIntegerFromMemory(
393 injected_result + 2 * word_size + sizeof(unsigned), sizeof(unsigned), 0,
394 status);
395 if (status.Fail()) {
397 "LoadLibrary error: could not read error status: %s",
398 status.AsCString());
400 }
401
402 error = Status::FromErrorStringWithFormat("LoadLibrary Error: %" PRIu64,
403 error_code);
405 }
406
407 std::string module_path;
408 process->ReadCStringFromMemory(injected_module_path, module_path, status);
409 if (status.Fail()) {
411 "LoadLibrary error: could not read module path: %s",
412 status.AsCString());
414 }
415
416 if (loaded_image)
417 loaded_image->SetFile(module_path, llvm::sys::path::Style::native);
418 return process->AddImageToken(token);
419}
420
421Status PlatformWindows::UnloadImage(Process *process, uint32_t image_token) {
422 const addr_t address = process->GetImagePtrFromToken(image_token);
423 if (address == LLDB_INVALID_ADDRESS)
424 return Status::FromErrorString("invalid image token");
425
426 StreamString expression;
427 expression.Printf("FreeLibrary((HMODULE)0x%" PRIx64 ")", address);
428
429 ValueObjectSP value;
430 Status result =
431 EvaluateLoaderExpression(process, expression.GetData(), value);
432 if (result.Fail())
433 return result;
434
435 if (value->GetError().Fail())
436 return value->GetError().Clone();
437
438 Scalar scalar;
439 if (value->ResolveValue(scalar)) {
440 if (scalar.UInt(1))
441 return Status::FromErrorStringWithFormat("expression failed: \"%s\"",
442 expression.GetData());
443 process->ResetImageToken(image_token);
444 }
445
446 return Status();
447}
448
451
452 if (IsHost()) {
454 "can't disconnect from the host platform '{0}', always connected",
455 GetPluginName());
456 } else {
458 error = m_remote_platform_sp->DisconnectRemote();
459 else
460 error =
461 Status::FromErrorString("the platform is not currently connected");
462 }
463 return error;
464}
465
467 Debugger &debugger, Target &target,
468 Status &error) {
469 // Windows has special considerations that must be followed when launching or
470 // attaching to a process. The key requirement is that when launching or
471 // attaching to a process, you must do it from the same the thread that will
472 // go into a permanent loop which will then receive debug events from the
473 // process. In particular, this means we can't use any of LLDB's generic
474 // mechanisms to do it for us, because it doesn't have the special knowledge
475 // required for setting up the background thread or passing the right flags.
476 //
477 // Another problem is that LLDB's standard model for debugging a process
478 // is to first launch it, have it stop at the entry point, and then attach to
479 // it. In Windows this doesn't quite work, you have to specify as an
480 // argument to CreateProcess() that you're going to debug the process. So we
481 // override DebugProcess here to handle this. Launch operations go directly
482 // to the process plugin, and attach operations almost go directly to the
483 // process plugin (but we hijack the events first). In essence, we
484 // encapsulate all the logic of Launching and Attaching in the process
485 // plugin, and PlatformWindows::DebugProcess is just a pass-through to get to
486 // the process plugin.
487
488 if (IsRemote()) {
490 return m_remote_platform_sp->DebugProcess(launch_info, debugger, target,
491 error);
492 else
493 error =
494 Status::FromErrorString("the platform is not currently connected");
495 }
496
497 if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {
498 // This is a process attach. Don't need to launch anything.
499 ProcessAttachInfo attach_info(launch_info);
500 return Attach(attach_info, debugger, &target, error);
501 }
502
503 ProcessSP process_sp =
504 target.CreateProcess(launch_info.GetListener(),
505 launch_info.GetProcessPluginName(), nullptr, false);
506 if (!process_sp)
507 return nullptr;
508
509 process_sp->HijackProcessEvents(launch_info.GetHijackListener());
510
511 // We need to launch and attach to the process.
512 launch_info.GetFlags().Set(eLaunchFlagDebug);
513 error = process_sp->Launch(launch_info);
514#ifdef _WIN32
515 if (error.Success()) {
516 process_sp->SetPseudoConsoleHandle();
517 } else {
519 LLDB_LOGF(log, "Platform::%s LaunchProcess() failed: %s", __FUNCTION__,
520 error.AsCString());
521 }
522#endif
523
524 return process_sp;
525}
526
528 Debugger &debugger, Target *target,
529 Status &error) {
530 error.Clear();
531 lldb::ProcessSP process_sp;
532 if (!IsHost()) {
534 process_sp =
535 m_remote_platform_sp->Attach(attach_info, debugger, target, error);
536 else
537 error =
538 Status::FromErrorString("the platform is not currently connected");
539 return process_sp;
540 }
541
542 if (target == nullptr) {
543 TargetSP new_target_sp;
544 error = debugger.GetTargetList().CreateTarget(
545 debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
546 target = new_target_sp.get();
547 }
548
549 if (!target || error.Fail())
550 return process_sp;
551
552 process_sp =
553 target->CreateProcess(attach_info.GetListenerForProcess(debugger),
554 attach_info.GetProcessPluginName(), nullptr, false);
555
556 process_sp->HijackProcessEvents(attach_info.GetHijackListener());
557 if (process_sp)
558 error = process_sp->Attach(attach_info);
559
560 return process_sp;
561}
562
565
566#ifdef _WIN32
567 llvm::VersionTuple version = HostInfo::GetOSVersion();
568 strm << " Host: Windows " << version.getAsString() << '\n';
569#endif
570}
571
572bool PlatformWindows::CanDebugProcess() { return true; }
573
575 if (basename.IsEmpty())
576 return basename;
577
578 StreamString stream;
579 stream.Printf("%s.dll", basename.GetCString());
580 return ConstString(stream.GetString());
581}
582
583size_t
585 BreakpointSite *bp_site) {
586 ArchSpec arch = target.GetArchitecture();
587 assert(arch.IsValid());
588 const uint8_t *trap_opcode = nullptr;
589 size_t trap_opcode_size = 0;
590
591 switch (arch.GetMachine()) {
592 case llvm::Triple::aarch64: {
593 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x3e, 0xd4}; // brk #0xf000
594 trap_opcode = g_aarch64_opcode;
595 trap_opcode_size = sizeof(g_aarch64_opcode);
596
597 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
598 return trap_opcode_size;
599 return 0;
600 } break;
601
602 case llvm::Triple::arm:
603 case llvm::Triple::thumb: {
604 static const uint8_t g_thumb_opcode[] = {0xfe, 0xde}; // udf #0xfe
605 trap_opcode = g_thumb_opcode;
606 trap_opcode_size = sizeof(g_thumb_opcode);
607
608 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
609 return trap_opcode_size;
610 return 0;
611 } break;
612
613 default:
614 return Platform::GetSoftwareBreakpointTrapOpcode(target, bp_site);
615 }
616}
617
618std::unique_ptr<UtilityFunction>
620 Status &status) {
621 // FIXME(compnerd) `-fdeclspec` is not passed to the clang instance?
622 static constexpr const char kLoaderDecls[] = R"(
623extern "C" {
624// errhandlingapi.h
625
626// `LOAD_LIBRARY_SEARCH_APPLICATION_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_USER_DIRS`
627//
628// Directories in the standard search path are not searched. This value cannot
629// be combined with `LOAD_WITH_ALTERED_SEARCH_PATH`.
630//
631// This value represents the recommended maximum number of directories an
632// application should include in its DLL search path.
633#define LOAD_LIBRARY_SEARCH_DEFAULT_DIRS 0x00001000
634
635// If this value is used, and lpFileName specifies an absolute path, the system
636// uses the alternate file search strategy to find associated executable
637// modules.
638#define LOAD_WITH_ALTERED_SEARCH_PATH 0x00000008
639
640// WINBASEAPI DWORD WINAPI GetLastError(VOID);
641/* __declspec(dllimport) */ uint32_t __stdcall GetLastError();
642
643// libloaderapi.h
644
645// WINBASEAPI DLL_DIRECTORY_COOKIE WINAPI AddDllDirectory(LPCWSTR);
646/* __declspec(dllimport) */ void * __stdcall AddDllDirectory(const wchar_t *);
647
648// WINBASEAPI BOOL WINAPI FreeModule(HMODULE);
649/* __declspec(dllimport) */ int __stdcall FreeModule(void *hLibModule);
650
651// WINBASEAPI DWORD WINAPI GetModuleFileNameA(HMODULE hModule, LPSTR lpFilename, DWORD nSize);
652/* __declspec(dllimport) */ uint32_t GetModuleFileNameA(void *, char *, uint32_t);
653
654// WINBASEAPI HMODULE WINAPI LoadLibraryExW(LPCWSTR, HANDLE, DWORD);
655/* __declspec(dllimport) */ void * __stdcall LoadLibraryExW(const wchar_t *, void *, uint32_t);
656
657// corecrt_wstring.h
658
659// _ACRTIMP size_t __cdecl wcslen(wchar_t const *_String);
660/* __declspec(dllimport) */ size_t __cdecl wcslen(const wchar_t *);
661
662// lldb specific code
663
664struct __lldb_LoadLibraryResult {
665 void *ImageBase;
666 char *ModulePath;
667 unsigned Length;
668 unsigned ErrorCode;
669};
670
671_Static_assert(sizeof(struct __lldb_LoadLibraryResult) <= 3 * sizeof(void *),
672 "__lldb_LoadLibraryResult size mismatch");
673
674void * __lldb_LoadLibraryHelper(const wchar_t *name, const wchar_t *paths,
675 __lldb_LoadLibraryResult *result) {
676 for (const wchar_t *path = paths; path && *path; ) {
677 (void)AddDllDirectory(path);
678 path += wcslen(path) + 1;
679 }
680
681 result->ImageBase = LoadLibraryExW(name, nullptr,
682 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
683
684 // Fallback: if the AddDllDirectory + LOAD_LIBRARY_SEARCH_DEFAULT_DIRS path
685 // failed to find the library, iterate the search paths ourselves and
686 // load by absolute path using LOAD_WITH_ALTERED_SEARCH_PATH, which makes
687 // Windows use the loaded DLL's own directory to resolve its sibling imports.
688 if (result->ImageBase == nullptr) {
689 wchar_t full[4096];
690 for (const wchar_t *path = paths; path && *path; path += wcslen(path) + 1) {
691 size_t plen = wcslen(path);
692 size_t nlen = wcslen(name);
693 // Need room for: path + '\\' + name + '\0'
694 if (plen + 1 + nlen + 1 > 4096)
695 continue;
696 wchar_t *p = full;
697 for (size_t i = 0; i < plen; ++i)
698 *p++ = path[i];
699 *p++ = L'\\';
700 for (size_t i = 0; i <= nlen; ++i) // Copy name including trailing '\0'.
701 *p++ = name[i];
702 result->ImageBase = LoadLibraryExW(full, nullptr,
703 LOAD_WITH_ALTERED_SEARCH_PATH);
704 if (result->ImageBase != nullptr)
705 break;
706 }
707 }
708
709 if (result->ImageBase == nullptr)
710 result->ErrorCode = GetLastError();
711 else
712 result->Length = GetModuleFileNameA(result->ImageBase, result->ModulePath,
713 result->Length);
714
715 return result->ImageBase;
716}
717}
718 )";
719
720 static constexpr const char kName[] = "__lldb_LoadLibraryHelper";
721
722 ProcessSP process = context.GetProcessSP();
723 Target &target = process->GetTarget();
724
725 auto function = target.CreateUtilityFunction(std::string{kLoaderDecls}, kName,
727 context);
728 if (!function) {
729 std::string error = llvm::toString(function.takeError());
731 "LoadLibrary error: could not create utility function: %s",
732 error.c_str());
733 return nullptr;
734 }
735
736 TypeSystemClangSP scratch_ts_sp =
738 if (!scratch_ts_sp)
739 return nullptr;
740
741 CompilerType VoidPtrTy =
742 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
743 CompilerType WCharPtrTy =
744 scratch_ts_sp->GetBasicType(eBasicTypeWChar).GetPointerType();
745
746 ValueList parameters;
747
748 Value value;
750
751 value.SetCompilerType(WCharPtrTy);
752 parameters.PushValue(value); // name
753 parameters.PushValue(value); // paths
754
755 value.SetCompilerType(VoidPtrTy);
756 parameters.PushValue(value); // result
757
759 std::unique_ptr<UtilityFunction> utility{std::move(*function)};
760 utility->MakeFunctionCaller(VoidPtrTy, parameters, context.GetThreadSP(),
761 error);
762 if (error.Fail()) {
764 "LoadLibrary error: could not create function caller: %s",
765 error.AsCString());
766 return nullptr;
767 }
768
769 if (!utility->GetFunctionCaller()) {
771 "LoadLibrary error: could not get function caller");
772 return nullptr;
773 }
774
775 return utility;
776}
777
779 const char *expression,
780 ValueObjectSP &value) {
781 // FIXME(compnerd) `-fdeclspec` is not passed to the clang instance?
782 static constexpr const char kLoaderDecls[] = R"(
783extern "C" {
784// libloaderapi.h
785
786// WINBASEAPI DLL_DIRECTORY_COOKIE WINAPI AddDllDirectory(LPCWSTR);
787/* __declspec(dllimport) */ void * __stdcall AddDllDirectory(const wchar_t *);
788
789// WINBASEAPI BOOL WINAPI FreeModule(HMODULE);
790/* __declspec(dllimport) */ int __stdcall FreeModule(void *);
791
792// WINBASEAPI DWORD WINAPI GetModuleFileNameA(HMODULE, LPSTR, DWORD);
793/* __declspec(dllimport) */ uint32_t GetModuleFileNameA(void *, char *, uint32_t);
794
795// WINBASEAPI HMODULE WINAPI LoadLibraryExW(LPCWSTR, HANDLE, DWORD);
796/* __declspec(dllimport) */ void * __stdcall LoadLibraryExW(const wchar_t *, void *, uint32_t);
797}
798 )";
799
800 if (DynamicLoader *loader = process->GetDynamicLoader()) {
801 Status result = loader->CanLoadImage();
802 if (result.Fail())
803 return result;
804 }
805
807 if (!thread)
808 return Status::FromErrorString("selected thread is invalid");
809
810 StackFrameSP frame = thread->GetStackFrameAtIndex(0);
811 if (!frame)
812 return Status::FromErrorString("frame 0 is invalid");
813
814 ExecutionContext context;
815 frame->CalculateExecutionContext(context);
816
817 EvaluateExpressionOptions options;
818 options.SetUnwindOnError(true);
819 options.SetIgnoreBreakpoints(true);
822 // LoadLibraryEx{A,W}/FreeLibrary cannot raise exceptions which we can handle.
823 // They may potentially throw SEH exceptions which we do not know how to
824 // handle currently.
825 options.SetTrapExceptions(false);
826 options.SetTimeout(process->GetUtilityExpressionTimeout());
827
829 context, options, expression, kLoaderDecls, value);
830 if (result != eExpressionCompleted)
831 return value ? value->GetError().Clone() : Status("unknown error");
832
833 if (value && value->GetError().Fail())
834 return value->GetError().Clone();
835
836 return Status();
837}
static const size_t word_size
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOGF(log,...)
Definition Log.h:378
static uint32_t g_initialize_count
#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:370
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:682
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 SetUnwindOnError(bool unwind=false)
Definition Target.h:396
void SetExecutionPolicy(ExecutionPolicy policy=eExecutionPolicyAlways)
Definition Target.h:354
void SetLanguage(lldb::LanguageType language_type)
Definition Target.h:360
void SetTimeout(const Timeout< std::micro > &timeout)
Definition Target.h:417
void SetIgnoreBreakpoints(bool ignore=false)
Definition Target.h:400
"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:374
void Clear()
Clears the object state.
Definition FileSpec.cpp:259
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
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 bool UnregisterPlugin(ABICreateInstance create_callback)
lldb::ListenerSP GetListenerForProcess(Debugger &debugger)
Definition Process.cpp:3196
llvm::StringRef GetProcessPluginName() const
Definition Process.h:160
lldb::ListenerSP GetHijackListener() const
lldb::pid_t GetProcessID() const
Definition ProcessInfo.h:68
lldb::ListenerSP GetListener() const
llvm::StringRef GetProcessPluginName() const
std::chrono::seconds GetUtilityExpressionTimeout() const
Definition Process.cpp:344
A plug-in interface definition class for debugging a process.
Definition Process.h:357
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:6789
void ResetImageToken(size_t token)
Definition Process.cpp:6573
ThreadList & GetThreadList()
Definition Process.h:2380
lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error)
The public interface to allocating memory in the process.
Definition Process.cpp:2689
size_t ReadCStringFromMemory(lldb::addr_t vm_addr, char *cstr, size_t cstr_max_len, Status &error)
Read a NULL terminated C string from memory.
Definition Process.cpp:2325
bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value, Status &error)
Definition Process.cpp:2519
size_t AddImageToken(lldb::addr_t image_ptr)
Definition Process.cpp:6562
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:2444
lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error)
Definition Process.cpp:2505
Status DeallocateMemory(lldb::addr_t ptr)
The public interface to deallocating memory in the process.
Definition Process.cpp:2748
lldb::addr_t GetImagePtrFromToken(size_t token) const
Definition Process.cpp:6567
uint32_t GetAddressByteSize() const
Definition Process.cpp:3913
size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Write memory to a process.
Definition Process.cpp:2547
virtual DynamicLoader * GetDynamicLoader()
Get the dynamic loader plug-in for this process.
Definition Process.cpp:3090
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:2628
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1255
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
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:2826
const ArchSpec & GetArchitecture() const
Definition Target.h:1283
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:113
@ Scalar
A raw scalar value.
Definition Value.h:45
void SetCompilerType(const CompilerType &compiler_type)
Definition Value.cpp:276
void SetValueType(ValueType value_type)
Definition Value.h:89
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:327
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