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
135 if (IsHost()) {
137 "can't connect to the host platform '{0}', always connected",
138 GetPluginName());
139 } else {
143 /*force=*/true, nullptr);
144
146 if (error.Success()) {
148 error = m_remote_platform_sp->ConnectRemote(args);
149 } else {
151 "\"platform connect\" takes a single argument: <connect-url>");
152 }
153 }
154 } else
156 "failed to create a 'remote-gdb-server' platform");
157
158 if (error.Fail())
159 m_remote_platform_sp.reset();
160 }
161
162 return error;
163}
164
166 const FileSpec &remote_file,
167 const std::vector<std::string> *paths,
168 Status &error, FileSpec *loaded_image) {
169 DiagnosticManager diagnostics;
170
171 if (loaded_image)
172 loaded_image->Clear();
173
175 if (!thread) {
177 "LoadLibrary error: no thread available to invoke LoadLibrary");
179 }
180
181 ExecutionContext context;
182 thread->CalculateExecutionContext(context);
183
184 Status status;
185 UtilityFunction *loader =
186 process->GetLoadImageUtilityFunction(this, [&]() -> std::unique_ptr<UtilityFunction> {
187 return MakeLoadImageUtilityFunction(context, status);
188 });
189 if (loader == nullptr)
191
192 FunctionCaller *invocation = loader->GetFunctionCaller();
193 if (!invocation) {
195 "LoadLibrary error: could not get function caller");
197 }
198
199 /* Convert name */
200 llvm::SmallVector<llvm::UTF16, 261> name;
201 if (!llvm::convertUTF8ToUTF16String(remote_file.GetPath(), name)) {
203 "LoadLibrary error: could not convert path to UCS2");
205 }
206 name.emplace_back(L'\0');
207
208 /* Inject name paramter into inferior */
209 lldb::addr_t injected_name =
210 process->AllocateMemory(name.size() * sizeof(llvm::UTF16),
211 ePermissionsReadable | ePermissionsWritable,
212 status);
213 if (injected_name == LLDB_INVALID_ADDRESS) {
215 "LoadLibrary error: unable to allocate memory for name: %s",
216 status.AsCString());
218 }
219
220 llvm::scope_exit name_cleanup(
221 [process, injected_name]() { process->DeallocateMemory(injected_name); });
222
223 process->WriteMemory(injected_name, name.data(),
224 name.size() * sizeof(llvm::UTF16), status);
225 if (status.Fail()) {
227 "LoadLibrary error: unable to write name: %s", status.AsCString());
229 }
230
231 /* Inject paths parameter into inferior */
232 lldb::addr_t injected_paths{0x0};
233 std::optional<llvm::scope_exit<std::function<void()>>> paths_cleanup;
234 if (paths) {
235 llvm::SmallVector<llvm::UTF16, 261> search_paths;
236
237 for (const auto &path : *paths) {
238 if (path.empty())
239 continue;
240
241 llvm::SmallVector<llvm::UTF16, 261> buffer;
242 if (!llvm::convertUTF8ToUTF16String(path, buffer))
243 continue;
244
245 search_paths.append(std::begin(buffer), std::end(buffer));
246 search_paths.emplace_back(L'\0');
247 }
248 search_paths.emplace_back(L'\0');
249
250 injected_paths =
251 process->AllocateMemory(search_paths.size() * sizeof(llvm::UTF16),
252 ePermissionsReadable | ePermissionsWritable,
253 status);
254 if (injected_paths == LLDB_INVALID_ADDRESS) {
256 "LoadLibrary error: unable to allocate memory for paths: %s",
257 status.AsCString());
259 }
260
261 paths_cleanup.emplace([process, injected_paths]() {
262 process->DeallocateMemory(injected_paths);
263 });
264
265 process->WriteMemory(injected_paths, search_paths.data(),
266 search_paths.size() * sizeof(llvm::UTF16), status);
267 if (status.Fail()) {
269 "LoadLibrary error: unable to write paths: %s", status.AsCString());
271 }
272 }
273
274 /* Inject wszModulePath into inferior */
275 // FIXME(compnerd) should do something better for the length?
276 // GetModuleFileNameA is likely limited to PATH_MAX rather than the NT path
277 // limit.
278 unsigned injected_length = 261;
279
280 lldb::addr_t injected_module_path =
281 process->AllocateMemory(injected_length + 1,
282 ePermissionsReadable | ePermissionsWritable,
283 status);
284 if (injected_module_path == LLDB_INVALID_ADDRESS) {
286 "LoadLibrary error: unable to allocate memory for module location: %s",
287 status.AsCString());
289 }
290
291 llvm::scope_exit injected_module_path_cleanup(
292 [process, injected_module_path]() {
293 process->DeallocateMemory(injected_module_path);
294 });
295
296 /* Inject __lldb_LoadLibraryResult into inferior */
297 const uint32_t word_size = process->GetAddressByteSize();
298 lldb::addr_t injected_result =
299 process->AllocateMemory(3 * word_size,
300 ePermissionsReadable | ePermissionsWritable,
301 status);
302 if (status.Fail()) {
304 "LoadLibrary error: could not allocate memory for result: %s",
305 status.AsCString());
307 }
308
309 llvm::scope_exit result_cleanup([process, injected_result]() {
310 process->DeallocateMemory(injected_result);
311 });
312
313 process->WritePointerToMemory(injected_result + word_size,
314 injected_module_path, status);
315 if (status.Fail()) {
317 "LoadLibrary error: could not initialize result: %s",
318 status.AsCString());
320 }
321
322 // XXX(compnerd) should we use the compiler to get the sizeof(unsigned)?
323 process->WriteScalarToMemory(injected_result + 2 * word_size,
324 Scalar{injected_length}, sizeof(unsigned),
325 status);
326 if (status.Fail()) {
328 "LoadLibrary error: could not initialize result: %s",
329 status.AsCString());
331 }
332
333 /* Setup Formal Parameters */
334 ValueList parameters = invocation->GetArgumentValues();
335 parameters.GetValueAtIndex(0)->GetScalar() = injected_name;
336 parameters.GetValueAtIndex(1)->GetScalar() = injected_paths;
337 parameters.GetValueAtIndex(2)->GetScalar() = injected_result;
338
339 lldb::addr_t injected_parameters = LLDB_INVALID_ADDRESS;
340 diagnostics.Clear();
341 if (!invocation->WriteFunctionArguments(context, injected_parameters,
342 parameters, diagnostics)) {
343 error = Status::FromError(diagnostics.GetAsError(
345 "LoadLibrary error: unable to write function parameters:"));
347 }
348
349 llvm::scope_exit parameter_cleanup(
350 [invocation, &context, injected_parameters]() {
351 invocation->DeallocateFunctionResults(context, injected_parameters);
352 });
353
354 TypeSystemClangSP scratch_ts_sp =
356 if (!scratch_ts_sp) {
358 "LoadLibrary error: unable to get (clang) type system");
360 }
361
362 /* Setup Return Type */
363 CompilerType VoidPtrTy =
364 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
365
366 Value value;
367 value.SetCompilerType(VoidPtrTy);
368
369 /* Invoke expression */
373 options.SetIgnoreBreakpoints(true);
374 options.SetUnwindOnError(true);
375 // LoadLibraryEx{A,W}/FreeLibrary cannot raise exceptions which we can handle.
376 // They may potentially throw SEH exceptions which we do not know how to
377 // handle currently.
378 options.SetTrapExceptions(false);
379 options.SetTimeout(process->GetUtilityExpressionTimeout());
380 options.SetIsForUtilityExpr(true);
381
382 ExpressionResults result =
383 invocation->ExecuteFunction(context, &injected_parameters, options,
384 diagnostics, value);
385 if (result != eExpressionCompleted) {
386 error = Status::FromError(diagnostics.GetAsError(
388 "LoadLibrary error: failed to execute LoadLibrary helper:"));
390 }
391
392 /* Read result */
393 lldb::addr_t token = process->ReadPointerFromMemory(injected_result, status);
394 if (status.Fail()) {
396 "LoadLibrary error: could not read the result: %s", status.AsCString());
398 }
399
400 if (!token) {
401 // XXX(compnerd) should we use the compiler to get the sizeof(unsigned)?
402 uint64_t error_code =
403 process->ReadUnsignedIntegerFromMemory(injected_result + 2 * word_size + sizeof(unsigned),
404 word_size, 0, status);
405 if (status.Fail()) {
407 "LoadLibrary error: could not read error status: %s",
408 status.AsCString());
410 }
411
412 error = Status::FromErrorStringWithFormat("LoadLibrary Error: %" PRIu64,
413 error_code);
415 }
416
417 std::string module_path;
418 process->ReadCStringFromMemory(injected_module_path, module_path, status);
419 if (status.Fail()) {
421 "LoadLibrary error: could not read module path: %s",
422 status.AsCString());
424 }
425
426 if (loaded_image)
427 loaded_image->SetFile(module_path, llvm::sys::path::Style::native);
428 return process->AddImageToken(token);
429}
430
431Status PlatformWindows::UnloadImage(Process *process, uint32_t image_token) {
432 const addr_t address = process->GetImagePtrFromToken(image_token);
433 if (address == LLDB_INVALID_IMAGE_TOKEN)
434 return Status::FromErrorString("invalid image token");
435
436 StreamString expression;
437 expression.Printf("FreeLibrary((HMODULE)0x%" PRIx64 ")", address);
438
439 ValueObjectSP value;
440 Status result =
441 EvaluateLoaderExpression(process, expression.GetData(), value);
442 if (result.Fail())
443 return result;
444
445 if (value->GetError().Fail())
446 return value->GetError().Clone();
447
448 Scalar scalar;
449 if (value->ResolveValue(scalar)) {
450 if (scalar.UInt(1))
451 return Status::FromErrorStringWithFormat("expression failed: \"%s\"",
452 expression.GetData());
453 process->ResetImageToken(image_token);
454 }
455
456 return Status();
457}
458
461
462 if (IsHost()) {
464 "can't disconnect from the host platform '{0}', always connected",
465 GetPluginName());
466 } else {
468 error = m_remote_platform_sp->DisconnectRemote();
469 else
470 error =
471 Status::FromErrorString("the platform is not currently connected");
472 }
473 return error;
474}
475
477 Debugger &debugger, Target &target,
478 Status &error) {
479 // Windows has special considerations that must be followed when launching or
480 // attaching to a process. The key requirement is that when launching or
481 // attaching to a process, you must do it from the same the thread that will
482 // go into a permanent loop which will then receive debug events from the
483 // process. In particular, this means we can't use any of LLDB's generic
484 // mechanisms to do it for us, because it doesn't have the special knowledge
485 // required for setting up the background thread or passing the right flags.
486 //
487 // Another problem is that LLDB's standard model for debugging a process
488 // is to first launch it, have it stop at the entry point, and then attach to
489 // it. In Windows this doesn't quite work, you have to specify as an
490 // argument to CreateProcess() that you're going to debug the process. So we
491 // override DebugProcess here to handle this. Launch operations go directly
492 // to the process plugin, and attach operations almost go directly to the
493 // process plugin (but we hijack the events first). In essence, we
494 // encapsulate all the logic of Launching and Attaching in the process
495 // plugin, and PlatformWindows::DebugProcess is just a pass-through to get to
496 // the process plugin.
497
498 if (IsRemote()) {
500 return m_remote_platform_sp->DebugProcess(launch_info, debugger, target,
501 error);
502 else
503 error =
504 Status::FromErrorString("the platform is not currently connected");
505 }
506
507 if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {
508 // This is a process attach. Don't need to launch anything.
509 ProcessAttachInfo attach_info(launch_info);
510 return Attach(attach_info, debugger, &target, error);
511 }
512
513 ProcessSP process_sp =
514 target.CreateProcess(launch_info.GetListener(),
515 launch_info.GetProcessPluginName(), nullptr, false);
516
517 process_sp->HijackProcessEvents(launch_info.GetHijackListener());
518
519 // We need to launch and attach to the process.
520 launch_info.GetFlags().Set(eLaunchFlagDebug);
521 if (!process_sp)
522 return nullptr;
523 error = process_sp->Launch(launch_info);
524#ifdef _WIN32
525 if (error.Success())
526 process_sp->SetPseudoConsoleHandle(launch_info.GetPTYSP());
527 else {
529 LLDB_LOGF(log, "Platform::%s LaunchProcess() failed: %s", __FUNCTION__,
530 error.AsCString());
531 }
532#endif
533
534 return process_sp;
535}
536
538 Debugger &debugger, Target *target,
539 Status &error) {
540 error.Clear();
541 lldb::ProcessSP process_sp;
542 if (!IsHost()) {
544 process_sp =
545 m_remote_platform_sp->Attach(attach_info, debugger, target, error);
546 else
547 error =
548 Status::FromErrorString("the platform is not currently connected");
549 return process_sp;
550 }
551
552 if (target == nullptr) {
553 TargetSP new_target_sp;
554 FileSpec emptyFileSpec;
555 ArchSpec emptyArchSpec;
556
557 error = debugger.GetTargetList().CreateTarget(
558 debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
559 target = new_target_sp.get();
560 }
561
562 if (!target || error.Fail())
563 return process_sp;
564
565 process_sp =
566 target->CreateProcess(attach_info.GetListenerForProcess(debugger),
567 attach_info.GetProcessPluginName(), nullptr, false);
568
569 process_sp->HijackProcessEvents(attach_info.GetHijackListener());
570 if (process_sp)
571 error = process_sp->Attach(attach_info);
572
573 return process_sp;
574}
575
578
579#ifdef _WIN32
580 llvm::VersionTuple version = HostInfo::GetOSVersion();
581 strm << " Host: Windows " << version.getAsString() << '\n';
582#endif
583}
584
585bool PlatformWindows::CanDebugProcess() { return true; }
586
588 if (basename.IsEmpty())
589 return basename;
590
591 StreamString stream;
592 stream.Printf("%s.dll", basename.GetCString());
593 return ConstString(stream.GetString());
594}
595
596size_t
598 BreakpointSite *bp_site) {
599 ArchSpec arch = target.GetArchitecture();
600 assert(arch.IsValid());
601 const uint8_t *trap_opcode = nullptr;
602 size_t trap_opcode_size = 0;
603
604 switch (arch.GetMachine()) {
605 case llvm::Triple::aarch64: {
606 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x3e, 0xd4}; // brk #0xf000
607 trap_opcode = g_aarch64_opcode;
608 trap_opcode_size = sizeof(g_aarch64_opcode);
609
610 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
611 return trap_opcode_size;
612 return 0;
613 } break;
614
615 case llvm::Triple::arm:
616 case llvm::Triple::thumb: {
617 static const uint8_t g_thumb_opcode[] = {0xfe, 0xde}; // udf #0xfe
618 trap_opcode = g_thumb_opcode;
619 trap_opcode_size = sizeof(g_thumb_opcode);
620
621 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
622 return trap_opcode_size;
623 return 0;
624 } break;
625
626 default:
627 return Platform::GetSoftwareBreakpointTrapOpcode(target, bp_site);
628 }
629}
630
631std::unique_ptr<UtilityFunction>
633 Status &status) {
634 // FIXME(compnerd) `-fdeclspec` is not passed to the clang instance?
635 static constexpr const char kLoaderDecls[] = R"(
636extern "C" {
637// errhandlingapi.h
638
639// `LOAD_LIBRARY_SEARCH_APPLICATION_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_USER_DIRS`
640//
641// Directories in the standard search path are not searched. This value cannot
642// be combined with `LOAD_WITH_ALTERED_SEARCH_PATH`.
643//
644// This value represents the recommended maximum number of directories an
645// application should include in its DLL search path.
646#define LOAD_LIBRARY_SEARCH_DEFAULT_DIRS 0x00001000
647
648// WINBASEAPI DWORD WINAPI GetLastError(VOID);
649/* __declspec(dllimport) */ uint32_t __stdcall GetLastError();
650
651// libloaderapi.h
652
653// WINBASEAPI DLL_DIRECTORY_COOKIE WINAPI AddDllDirectory(LPCWSTR);
654/* __declspec(dllimport) */ void * __stdcall AddDllDirectory(const wchar_t *);
655
656// WINBASEAPI BOOL WINAPI FreeModule(HMODULE);
657/* __declspec(dllimport) */ int __stdcall FreeModule(void *hLibModule);
658
659// WINBASEAPI DWORD WINAPI GetModuleFileNameA(HMODULE hModule, LPSTR lpFilename, DWORD nSize);
660/* __declspec(dllimport) */ uint32_t GetModuleFileNameA(void *, char *, uint32_t);
661
662// WINBASEAPI HMODULE WINAPI LoadLibraryExW(LPCWSTR, HANDLE, DWORD);
663/* __declspec(dllimport) */ void * __stdcall LoadLibraryExW(const wchar_t *, void *, uint32_t);
664
665// corecrt_wstring.h
666
667// _ACRTIMP size_t __cdecl wcslen(wchar_t const *_String);
668/* __declspec(dllimport) */ size_t __cdecl wcslen(const wchar_t *);
669
670// lldb specific code
671
672struct __lldb_LoadLibraryResult {
673 void *ImageBase;
674 char *ModulePath;
675 unsigned Length;
676 unsigned ErrorCode;
677};
678
679_Static_assert(sizeof(struct __lldb_LoadLibraryResult) <= 3 * sizeof(void *),
680 "__lldb_LoadLibraryResult size mismatch");
681
682void * __lldb_LoadLibraryHelper(const wchar_t *name, const wchar_t *paths,
683 __lldb_LoadLibraryResult *result) {
684 for (const wchar_t *path = paths; path && *path; ) {
685 (void)AddDllDirectory(path);
686 path += wcslen(path) + 1;
687 }
688
689 result->ImageBase = LoadLibraryExW(name, nullptr,
690 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
691 if (result->ImageBase == nullptr)
692 result->ErrorCode = GetLastError();
693 else
694 result->Length = GetModuleFileNameA(result->ImageBase, result->ModulePath,
695 result->Length);
696
697 return result->ImageBase;
698}
699}
700 )";
701
702 static constexpr const char kName[] = "__lldb_LoadLibraryHelper";
703
704 ProcessSP process = context.GetProcessSP();
705 Target &target = process->GetTarget();
706
707 auto function = target.CreateUtilityFunction(std::string{kLoaderDecls}, kName,
709 context);
710 if (!function) {
711 std::string error = llvm::toString(function.takeError());
713 "LoadLibrary error: could not create utility function: %s",
714 error.c_str());
715 return nullptr;
716 }
717
718 TypeSystemClangSP scratch_ts_sp =
720 if (!scratch_ts_sp)
721 return nullptr;
722
723 CompilerType VoidPtrTy =
724 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
725 CompilerType WCharPtrTy =
726 scratch_ts_sp->GetBasicType(eBasicTypeWChar).GetPointerType();
727
728 ValueList parameters;
729
730 Value value;
732
733 value.SetCompilerType(WCharPtrTy);
734 parameters.PushValue(value); // name
735 parameters.PushValue(value); // paths
736
737 value.SetCompilerType(VoidPtrTy);
738 parameters.PushValue(value); // result
739
741 std::unique_ptr<UtilityFunction> utility{std::move(*function)};
742 utility->MakeFunctionCaller(VoidPtrTy, parameters, context.GetThreadSP(),
743 error);
744 if (error.Fail()) {
746 "LoadLibrary error: could not create function caller: %s",
747 error.AsCString());
748 return nullptr;
749 }
750
751 if (!utility->GetFunctionCaller()) {
753 "LoadLibrary error: could not get function caller");
754 return nullptr;
755 }
756
757 return utility;
758}
759
761 const char *expression,
762 ValueObjectSP &value) {
763 // FIXME(compnerd) `-fdeclspec` is not passed to the clang instance?
764 static constexpr const char kLoaderDecls[] = R"(
765extern "C" {
766// libloaderapi.h
767
768// WINBASEAPI DLL_DIRECTORY_COOKIE WINAPI AddDllDirectory(LPCWSTR);
769/* __declspec(dllimport) */ void * __stdcall AddDllDirectory(const wchar_t *);
770
771// WINBASEAPI BOOL WINAPI FreeModule(HMODULE);
772/* __declspec(dllimport) */ int __stdcall FreeModule(void *);
773
774// WINBASEAPI DWORD WINAPI GetModuleFileNameA(HMODULE, LPSTR, DWORD);
775/* __declspec(dllimport) */ uint32_t GetModuleFileNameA(void *, char *, uint32_t);
776
777// WINBASEAPI HMODULE WINAPI LoadLibraryExW(LPCWSTR, HANDLE, DWORD);
778/* __declspec(dllimport) */ void * __stdcall LoadLibraryExW(const wchar_t *, void *, uint32_t);
779}
780 )";
781
782 if (DynamicLoader *loader = process->GetDynamicLoader()) {
783 Status result = loader->CanLoadImage();
784 if (result.Fail())
785 return result;
786 }
787
789 if (!thread)
790 return Status::FromErrorString("selected thread is invalid");
791
792 StackFrameSP frame = thread->GetStackFrameAtIndex(0);
793 if (!frame)
794 return Status::FromErrorString("frame 0 is invalid");
795
796 ExecutionContext context;
797 frame->CalculateExecutionContext(context);
798
799 EvaluateExpressionOptions options;
800 options.SetUnwindOnError(true);
801 options.SetIgnoreBreakpoints(true);
804 // LoadLibraryEx{A,W}/FreeLibrary cannot raise exceptions which we can handle.
805 // They may potentially throw SEH exceptions which we do not know how to
806 // handle currently.
807 options.SetTrapExceptions(false);
808 options.SetTimeout(process->GetUtilityExpressionTimeout());
809
811 context, options, expression, kLoaderDecls, value);
812 if (result != eExpressionCompleted)
813 return value ? value->GetError().Clone() : Status("unknown error");
814
815 if (value && value->GetError().Fail())
816 return value->GetError().Clone();
817
818 return Status();
819}
static const size_t word_size
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOGF(log,...)
Definition Log.h:376
static uint32_t g_initialize_count
#define LLDB_PLUGIN_DEFINE(PluginName)
static constexpr llvm::StringLiteral kName
An architecture specification class.
Definition ArchSpec.h:31
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:366
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:677
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:80
TargetList & GetTargetList()
Get accessor for the target list.
Definition Debugger.h:204
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:372
void SetExecutionPolicy(ExecutionPolicy policy=eExecutionPolicyAlways)
Definition Target.h:330
void SetLanguage(lldb::LanguageType language_type)
Definition Target.h:336
void SetTimeout(const Timeout< std::micro > &timeout)
Definition Target.h:393
void SetIgnoreBreakpoints(bool ignore=false)
Definition Target.h:376
"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:138
static void SetHostPlatform(const lldb::PlatformSP &platform_sp)
Definition Platform.cpp:145
virtual void GetStatus(Stream &strm)
Report the current status for this platform.
Definition Platform.cpp:247
static void Initialize()
Definition Platform.cpp:136
bool IsRemote() const
Definition Platform.h:507
bool IsHost() const
Definition Platform.h:503
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:3029
llvm::StringRef GetProcessPluginName() const
Definition Process.h:157
lldb::ListenerSP GetHijackListener() const
lldb::pid_t GetProcessID() const
Definition ProcessInfo.h:68
lldb::ListenerSP GetListener() const
llvm::StringRef GetProcessPluginName() const
std::shared_ptr< PTY > GetPTYSP() const
std::chrono::seconds GetUtilityExpressionTimeout() const
Definition Process.cpp:325
A plug-in interface definition class for debugging a process.
Definition Process.h:354
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:6476
void ResetImageToken(size_t token)
Definition Process.cpp:6257
ThreadList & GetThreadList()
Definition Process.h:2275
lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error)
The public interface to allocating memory in the process.
Definition Process.cpp:2535
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:2216
bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value, Status &error)
Definition Process.cpp:2365
size_t AddImageToken(lldb::addr_t image_ptr)
Definition Process.cpp:6246
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:2335
lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error)
Definition Process.cpp:2357
Status DeallocateMemory(lldb::addr_t ptr)
The public interface to deallocating memory in the process.
Definition Process.cpp:2594
lldb::addr_t GetImagePtrFromToken(size_t token) const
Definition Process.cpp:6251
uint32_t GetAddressByteSize() const
Definition Process.cpp:3720
size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Write memory to a process.
Definition Process.cpp:2393
virtual DynamicLoader * GetDynamicLoader()
Get the dynamic loader plug-in for this process.
Definition Process.cpp:2923
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:2474
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1267
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:294
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:195
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:137
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:300
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:2766
const ArchSpec & GetArchitecture() const
Definition Target.h:1153
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:332
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