LLDB mainline
MicrosoftABIRuntime.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
10
13#include "clang/AST/RecordLayout.h"
14#include "llvm/Demangle/MicrosoftDemangle.h"
15#include "llvm/Demangle/MicrosoftDemangleNodes.h"
16
17#include <deque>
18#include <mutex>
19
20using namespace lldb;
21using namespace lldb_private;
22
23static const llvm::StringRef s_vtable_demangled_indicator = "::`vftable'";
24static const llvm::StringRef s_rtti_complete_object_locator_indicator =
25 "::`RTTI Complete Object Locator'";
26
27static llvm::StringRef StripDemangledVTableSuffix(llvm::StringRef demangled) {
28 llvm::StringRef name = demangled.split(s_vtable_demangled_indicator).first;
29 name.consume_front("const ");
30 return name;
31}
32
33static bool
34SplitVTableComponents(llvm::StringRef demangled,
36 llvm::StringRef suffix = demangled.split(s_vtable_demangled_indicator).second;
37 if (suffix.empty())
38 return true; // e.g. MyClass::`vftable'
39
40 // Otherwise, suffix looks like "{for `MyBase2's `MyBase1'}" or
41 // "{for `MyBase'}".
42 if (!suffix.consume_front("{for `") || !suffix.consume_back("'}"))
43 return false;
44
45 suffix.split(components, "'s `");
46 return true;
47}
48
51
53 ValueObject &in_value, lldb::DynamicValueType use_dynamic,
54 const LanguageRuntime::VTableInfo &vtable_info,
55 TypeAndOrName &class_type_or_name, Address &dynamic_address) {
56 std::optional<int64_t> offset_to_top =
57 GetOffsetToTop(in_value, class_type_or_name, vtable_info);
58 if (!offset_to_top)
59 return false;
60
61 lldb::addr_t dynamic_addr =
62 in_value.GetPointerValue().address - *offset_to_top;
63 if (!m_process->GetTarget().ResolveLoadAddress(dynamic_addr, dynamic_address))
64 dynamic_address.SetRawAddress(dynamic_addr);
65
66 return true;
67}
68
70 return mangled.GetDemangledName().GetStringRef().contains(
72}
73
75 ValueObject &in_value, const LanguageRuntime::VTableInfo &vtable_info,
76 llvm::SmallVectorImpl<llvm::StringRef> &vtable_components) {
77 if (!vtable_info.addr.IsSectionOffset() || !vtable_info.symbol)
78 return {};
79
80 // See if we have cached info for this type already.
81 TypeAndOrName type_info = GetDynamicTypeInfo(vtable_info.addr);
82 if (type_info)
83 return type_info;
84
86 Mangled &mangled = vtable_info.symbol->GetMangled();
87 llvm::StringRef symbol_name = mangled.GetDemangledName().GetStringRef();
88 if (!SplitVTableComponents(symbol_name, vtable_components)) {
89 LLDB_LOG(log, "{0:x16}: '{1}' is not a valid vtable symbol",
90 in_value.GetPointerValue().address, symbol_name);
91 return {};
92 }
93
94 bool any_found = false;
95 auto [type_sp, class_name] = LookupTypeByMangled(
96 mangled, vtable_info.symbol->CalculateSymbolContextModule(), any_found);
97 if (!any_found)
98 return TypeAndOrName(); // Type is not dynamic.
99
100 type_info.SetName(class_name);
101 if (type_sp) {
102 LLDB_LOG(log,
103 "static-type = '{0}' has dynamic type: uid={1:x}, type-name='{2}'",
104 in_value.GetTypeName(), type_sp->GetID(), type_sp->GetName());
105 type_info.SetTypeSP(std::move(type_sp));
106 }
107
108 if (type_info)
109 SetDynamicTypeInfo(vtable_info.addr, type_info);
110 return type_info;
111}
112
114 ValueObject &in_value, TypeAndOrName &class_type_or_name,
115 const LanguageRuntime::VTableInfo &vtable_info) {
116 Log *log = GetLog(LLDBLog::Object);
117
118 llvm::SmallVector<llvm::StringRef, 2> vtable_components;
119 class_type_or_name = GetTypeInfo(in_value, vtable_info, vtable_components);
120 if (!class_type_or_name) {
121 LLDB_LOG(log, "{0:x16}: failed to get type info",
122 in_value.GetPointerValue().address);
123 return std::nullopt;
124 }
125
126 CompilerType type = class_type_or_name.GetCompilerType();
127 if (!type) {
128 LLDB_LOG(log, "{0:x16}: failed to get type info (no compiler type)",
129 in_value.GetPointerValue().address);
130 return std::nullopt;
131 }
132
133 CompilerType in_type = in_value.GetCompilerType();
134 if (in_type.IsPointerOrReferenceType())
135 in_type = in_type.GetPointeeType();
136 if (!in_type.GetCompleteType()) {
137 LLDB_LOG(log, "{0:x16}: {1} is not a complete type",
138 in_value.GetPointerValue().address, in_type.GetTypeName());
139 return std::nullopt;
140 }
141 if (!type.GetCompleteType()) {
142 LLDB_LOG(log, "{0:x16}: {1} is not a complete type",
143 in_value.GetPointerValue().address,
144 type.GetTypeName().GetCString());
145 return std::nullopt;
146 }
147
148 if (TypeSystemClang::AreTypesSame(in_type, type)) {
149 LLDB_LOG(log, "{0:x16}: in type is the same as the dynamic type",
150 in_value.GetPointerValue().address);
151
152 // The dynamic type we found was the same type, so we don't have a
153 // dynamic type here, but if a derived type encounters this vtable symbol,
154 // remember that it has offset 0.
155 std::scoped_lock<std::mutex> g(m_mutex);
156 m_offset_to_top_map[vtable_info.addr] = 0;
157 return std::nullopt;
158 }
159
160 {
161 std::scoped_lock<std::mutex> g(m_mutex);
162 auto offset_to_top_it = m_offset_to_top_map.find(vtable_info.addr);
163 if (offset_to_top_it != m_offset_to_top_map.end())
164 return offset_to_top_it->second;
165 }
166
167 // Unlike in the Itanium ABI, the VTable itself doesn't have a field telling
168 // us the offset to the dynamic type.
169 // When compiled with RTTI, we can use the complete object locator to get this
170 // offset. This is preferred, because it can resolve types across different
171 // modules and handle virtual bases with PDB.
172 // If this fails (e.g. no RTTI available), the offset is determined from the
173 // AST. This requires the types to be from the same type system. Because PDB
174 // doesn't include the offsets of virtual bases, we don't attempt to resolve
175 // these. They're technically present in the AST, but they often have
176 // incorrect offsets.
177 std::optional<int64_t> offset = GetOffsetToTopFromRTTI(vtable_info, type);
178 llvm::StringRef strategy = "RTTI";
179 if (!offset) {
180 offset = GetOffsetToTopFromAST(in_type, in_value, type, vtable_info,
181 vtable_components);
182 strategy = "AST";
183 }
184
185 if (offset) {
187 "{0:x16}: [{1}] '{2}' has offset {3} in '{4}'",
188 in_value.GetPointerValue().address, strategy,
189 in_type.GetTypeName(), *offset, type.GetTypeName());
190
191 // TODO: Ideally, we could also store the case where we can't find the
192 // offset. This would need to be invalidated when new modules or debug info
193 // is loaded, as those could contain info about the vtables.
194 std::scoped_lock<std::mutex> g(m_mutex);
195 m_offset_to_top_map[vtable_info.addr] = *offset;
196 }
197
198 return offset;
199}
200
202 const LanguageRuntime::VTableInfo &vtable_info,
203 const CompilerType &dynamic_type) {
204 // The pointer to the RTTI complete object locator sits one pointer size above
205 // the vftable.
206 Target &target = m_process->GetTarget();
207 const addr_t vtable_load_addr = vtable_info.addr.GetLoadAddress(&target);
208 if (vtable_load_addr == LLDB_INVALID_ADDRESS)
209 return std::nullopt;
210 const uint32_t addr_byte_size = m_process->GetAddressByteSize();
211 const lldb::addr_t complete_object_locator_load_addr =
212 vtable_load_addr - addr_byte_size;
213 // Check for underflow.
214 if (complete_object_locator_load_addr >= vtable_load_addr)
215 return std::nullopt;
216
217 Log *log = GetLog(LLDBLog::Object);
218 // Pointer to the RTTI complete object locator.
219 llvm::Expected<lldb::addr_t> rtti_locator_base_load_addr =
220 m_process->ReadPointerFromMemory(complete_object_locator_load_addr);
221 if (!rtti_locator_base_load_addr ||
222 *rtti_locator_base_load_addr == LLDB_INVALID_ADDRESS) {
223 LLDB_LOG_ERROR(log, rtti_locator_base_load_addr.takeError(),
224 "Failed to read address of RTTI complete object locator at "
225 "{1:x16}: {0}",
226 complete_object_locator_load_addr);
227 return std::nullopt;
228 }
229
231 Address rtti_locator_base_addr;
232 if (!m_process->GetTarget().ResolveLoadAddress(*rtti_locator_base_load_addr,
233 rtti_locator_base_addr)) {
234 LLDB_LOG_ERROR(log, error.takeError(),
235 "Failed to resolve load address of RTTI complete object "
236 "locator at {1:x16}: {0}",
237 *rtti_locator_base_load_addr);
238 return std::nullopt;
239 }
240
241 // Check if we're actually looking at the RTTI complete object locator.
242 Symbol *symbol = rtti_locator_base_addr.CalculateSymbolContextSymbol();
243 if (symbol == nullptr)
244 return std::nullopt;
245 if (!symbol->GetName().GetStringRef().contains(
247 return std::nullopt;
248
249 LLDB_LOG(log, "Found RTTI complete object locator: {0:x16}",
250 *rtti_locator_base_load_addr);
251
252 auto ts = dynamic_type.GetTypeSystem();
253 if (!ts)
254 return std::nullopt;
255
256 // On all supported platforms running the MS ABI, `int` is four bytes.
257 constexpr uint32_t int_size = 4;
258
259 // See MSRTTIBuilder::getCompleteObjectLocator in Clang for the layout.
260 // We're interested in the offset which is the second int in the struct.
261 Address offset_from_top_addr = rtti_locator_base_addr;
262 offset_from_top_addr.Slide(int_size);
263
264 error.Clear();
265 const int64_t offset_from_top = target.ReadSignedIntegerFromMemory(
266 offset_from_top_addr, int_size, INT64_MIN, error);
267 if (offset_from_top == INT64_MIN || error.Fail()) {
268 LLDB_LOG_ERROR(log, error.takeError(),
269 "Failed to read 'offset from top' from RTTI complete object "
270 "locator at {1:x16}: {0}",
271 offset_from_top_addr.GetOffset());
272 return std::nullopt;
273 }
274
275 return offset_from_top;
276}
277
278/// Try to find the offset of `target_base` inside `haystack` while visiting all
279/// `checkpoints`.
280static std::optional<size_t>
281GetOffsetOfBaseFromAST(clang::ASTContext &ast,
282 const clang::CXXRecordDecl *haystack,
283 const clang::CXXRecordDecl *target_base,
284 const llvm::ArrayRef<llvm::StringRef> checkpoints) {
285 struct BaseEntry {
286 const clang::CXXRecordDecl *decl;
287 /// If this is `std::nullopt`, then this entry is on a path where we can't
288 /// determine the offset.
289 std::optional<size_t> offset;
290 /// Remaining checkpoints on this path.
291 llvm::ArrayRef<llvm::StringRef> checkpoints;
292 /// Was `target_base` found on this path?
293 bool found_target = false;
294 };
295
296 // This does a breadth-first search over all bases. Starting point is the root
297 // (`haystack`).
298 std::deque<BaseEntry> bases;
299 bases.emplace_back(BaseEntry{
300 /*decl=*/haystack,
301 /*offset=*/0,
302 /*checkpoints=*/checkpoints,
303 });
304
305 // Go through virtual bases first.
306 std::string base_name;
307 for (const clang::CXXBaseSpecifier &base : haystack->vbases()) {
308 const clang::CXXRecordDecl *base_decl = llvm::cast<clang::CXXRecordDecl>(
309 base.getType()->castAs<clang::RecordType>()->getDecl());
310 // Although clang gives us some offset here, this offset is not from the
311 // debug info and thus likely wrong. Neither PDB nor DWARF include it.
312 if (!checkpoints.empty()) {
313 base_name = base_decl->getDeclName().getAsString();
314 if (base_name == checkpoints.back())
315 return std::nullopt;
316 } else if (base_decl == target_base) {
317 return std::nullopt;
318 }
319
320 // We still need to keep track of this class as `target_base` might be
321 // inside this base.
322 bases.emplace_back(BaseEntry{
323 /*decl=*/base_decl,
324 /*offset=*/std::nullopt,
325 /*checkpoints=*/checkpoints,
326 });
327 }
328
329 while (!bases.empty()) {
330 BaseEntry current = bases.front();
331 assert(
332 (!current.found_target || !current.checkpoints.empty()) &&
333 "if we found the target we should only need to check the checkpoints");
334 bases.pop_front();
335 const clang::ASTRecordLayout &record_layout =
336 ast.getASTRecordLayout(current.decl);
337
338 for (const clang::CXXBaseSpecifier &base : current.decl->bases()) {
339 if (base.isVirtual())
340 continue; // We already looked through virtual bases.
341
342 const clang::CXXRecordDecl *base_decl = llvm::cast<clang::CXXRecordDecl>(
343 base.getType()->castAs<clang::RecordType>()->getDecl());
344 bool found_target = base_decl == target_base || current.found_target;
345 std::optional<size_t> offset = current.offset;
346 if (offset)
347 *offset += record_layout.getBaseClassOffset(base_decl).getQuantity();
348
349 if (!current.checkpoints.empty()) {
350 base_name = base_decl->getDeclName().getAsString();
351 if (base_name == current.checkpoints.back()) {
352 // Last component was the base we were looking for.
353 if (found_target && current.checkpoints.size() == 1)
354 return offset;
355
356 // Found a checkpoint, so we have to take this path.
357 bases.clear();
358 bases.emplace_back(BaseEntry{
359 /*decl=*/base_decl,
360 /*offset=*/offset,
361 /*checkpoints=*/current.checkpoints.drop_back(),
362 /*found_target=*/found_target,
363 });
364 continue;
365 }
366 } else if (found_target) {
367 return offset;
368 }
369
370 bases.emplace_back(BaseEntry{
371 /*decl=*/base_decl,
372 /*offset=*/offset,
373 /*checkpoints=*/current.checkpoints,
374 /*found_target=*/found_target,
375 });
376 }
377 }
378
379 return std::nullopt;
380}
381
383 const CompilerType &in_type, ValueObject &in_value,
384 const CompilerType &dyn_type,
385 const LanguageRuntime::VTableInfo &vtable_info,
386 llvm::ArrayRef<llvm::StringRef> vtable_components) {
387 Log *log = GetLog(LLDBLog::Object);
388
389 CompilerType in_base_type = in_type;
390
391 clang::CXXRecordDecl *in_decl =
393 clang::CXXRecordDecl *target_decl =
395 if (!in_decl || !target_decl) {
396 LLDB_LOG(log, "{0:x16}: types are not record types (in={1}, target={2})",
397 in_value.GetPointerValue().address, in_base_type.GetTypeName(),
398 dyn_type.GetTypeName());
399 return std::nullopt;
400 }
401
403 if (!ts || ts != in_base_type.GetTypeSystem<TypeSystemClang>()) {
404 LLDB_LOG(log, "{0:x16}: '{1}' and '{2}' are from different type systems",
405 in_value.GetPointerValue().address,
406 in_decl->getDeclName().getAsString(),
407 target_decl->getDeclName().getAsString());
408 return std::nullopt;
409 }
410
411 std::optional<size_t> offset = GetOffsetOfBaseFromAST(
412 ts->getASTContext(), target_decl, in_decl, vtable_components);
413 if (!offset) {
414 LLDB_LOG(log, "{0:x16}: failed to find offset of '{1}' in '{2}'",
415 in_value.GetPointerValue().address,
416 in_decl->getDeclName().getAsString(),
417 target_decl->getDeclName().getAsString());
418 return std::nullopt;
419 }
420
421 return offset;
422}
423
424std::pair<lldb::TypeSP, ConstString> MicrosoftABIRuntime::LookupTypeByMangled(
425 Mangled &mangled, lldb::ModuleSP preferred_module, bool &any_found) {
426 llvm::StringRef preferred_name = mangled.GetDemangledName().GetStringRef();
427 llvm::StringRef class_name = StripDemangledVTableSuffix(preferred_name);
428
429 bool has_nested_template = class_name.contains(">>");
430 bool has_typename_list = class_name.contains(", ");
431
432 if (!has_nested_template && !has_typename_list) {
433 TypeSP type_sp = LookupTypeByName(class_name, preferred_module, any_found);
434 if (any_found)
435 return {type_sp, ConstString(class_name)};
436 }
437
438 std::string_view mangled_name = mangled.GetMangledName().GetStringRef();
439
440 // We need to match the way the compiler spelled the types when it put them
441 // into the TPI stream. For PDB, it does not insert spaces between template
442 // arguments and nested closing braces have a space in-between.
443 llvm::MSDemangleFlags flags = llvm::MSDemangleFlags(
444 llvm::MSDF_CompactTemplateLists | llvm::MSDF_SplitTemplateClosers |
445 llvm::MSDF_NoTagSpecifier);
446 char *demangled =
447 llvm::microsoftDemangle(mangled_name, nullptr, nullptr, flags);
448 if (!demangled)
449 return {};
450 llvm::scope_exit guard([&] { std::free(demangled); });
451
452 llvm::StringRef demangled_ref = StripDemangledVTableSuffix(demangled);
453 TypeSP type_sp = LookupTypeByName(demangled_ref, preferred_module, any_found);
454 if (any_found)
455 return {type_sp, ConstString(demangled_ref)};
456
457 if (!has_typename_list)
458 return {};
459
460 // DWARF has spaces between template
461 // parameters, so try again but with spaces.
462 flags = llvm::MSDemangleFlags(flags & ~llvm::MSDF_CompactTemplateLists);
463 std::free(demangled);
464 demangled = llvm::microsoftDemangle(mangled_name, nullptr, nullptr, flags);
465 if (!demangled)
466 return {};
467
468 demangled_ref = StripDemangledVTableSuffix(demangled);
469
470 type_sp = LookupTypeByName(llvm::StringRef(demangled_ref), preferred_module,
471 any_found);
472 if (any_found)
473 return {type_sp, ConstString(demangled_ref)};
474
475 return {};
476}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
static std::optional< size_t > GetOffsetOfBaseFromAST(clang::ASTContext &ast, const clang::CXXRecordDecl *haystack, const clang::CXXRecordDecl *target_base, const llvm::ArrayRef< llvm::StringRef > checkpoints)
Try to find the offset of target_base inside haystack while visiting all checkpoints.
static bool SplitVTableComponents(llvm::StringRef demangled, llvm::SmallVectorImpl< llvm::StringRef > &components)
static const llvm::StringRef s_rtti_complete_object_locator_indicator
static const llvm::StringRef s_vtable_demangled_indicator
static llvm::StringRef StripDemangledVTableSuffix(llvm::StringRef demangled)
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:303
void SetRawAddress(lldb::addr_t addr)
Definition Address.h:441
bool Slide(int64_t offset)
Definition Address.h:446
lldb::addr_t GetOffset() const
Get the section relative offset value.
Definition Address.h:329
bool IsSectionOffset() const
Check if an address is section offset.
Definition Address.h:342
Symbol * CalculateSymbolContextSymbol() const
Definition Address.cpp:888
void SetDynamicTypeInfo(const lldb_private::Address &vtable_addr, const TypeAndOrName &type_info)
lldb::TypeSP LookupTypeByName(llvm::StringRef type_name, lldb::ModuleSP preferred_module, bool &any_found) const
Find a type by its name, preferably in preferred_module.
TypeAndOrName GetDynamicTypeInfo(const lldb_private::Address &vtable_addr)
Generic representation of a type in a programming language.
TypeSystemSPWrapper GetTypeSystem() const
Accessors.
lldb::opaque_compiler_type_t GetOpaqueQualType() const
ConstString GetTypeName(bool BaseOnly=false) const
CompilerType GetPointeeType() const
If this type is a pointer type, return the type that the pointer points to, else return an invalid ty...
bool GetCompleteType() const
Type Completion.
bool IsPointerOrReferenceType(CompilerType *pointee_type=nullptr) const
A uniqued constant string class.
Definition ConstString.h:40
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
const char * GetCString() const
Get the string value as a C string.
A class that handles mangled names.
Definition Mangled.h:36
ConstString GetMangledName() const
Mangled name get accessor.
Definition Mangled.h:169
ConstString GetDemangledName() const
Demangled name get accessor.
Definition Mangled.cpp:238
bool GetDynamicTypeAndAddress(ValueObject &in_value, lldb::DynamicValueType use_dynamic, const LanguageRuntime::VTableInfo &vtable_info, TypeAndOrName &class_type_or_name, Address &dynamic_address) override
std::pair< lldb::TypeSP, ConstString > LookupTypeByMangled(Mangled &mangled, lldb::ModuleSP preferred_module, bool &any_found)
std::optional< int64_t > GetOffsetToTopFromAST(const CompilerType &in_type, ValueObject &in_value, const CompilerType &dyn_type, const LanguageRuntime::VTableInfo &vtable_info, llvm::ArrayRef< llvm::StringRef > vtable_components)
std::optional< int64_t > GetOffsetToTopFromRTTI(const LanguageRuntime::VTableInfo &vtable_info, const CompilerType &dynamic_type)
std::optional< int64_t > GetOffsetToTop(ValueObject &in_value, TypeAndOrName &class_type_or_name, const LanguageRuntime::VTableInfo &vtable_info)
bool IsVTableSymbol(Mangled &mangled) const override
TypeAndOrName GetTypeInfo(ValueObject &in_value, const LanguageRuntime::VTableInfo &vtable_info, llvm::SmallVectorImpl< llvm::StringRef > &vtable_components)
A plug-in interface definition class for debugging a process.
Definition Process.h:370
An error handling class.
Definition Status.h:118
lldb::ModuleSP CalculateSymbolContextModule() override
Definition Symbol.cpp:447
Mangled & GetMangled()
Definition Symbol.h:162
ConstString GetName() const
Definition Symbol.cpp:615
int64_t ReadSignedIntegerFromMemory(const Address &addr, size_t integer_byte_size, int64_t fail_value, Status &error, bool force_live_memory=false)
Definition Target.cpp:2474
Sometimes you can find the name of the type corresponding to an object, but we don't have debug infor...
void SetName(ConstString type_name)
void SetTypeSP(lldb::TypeSP type_sp)
A TypeSystem implementation based on Clang.
static bool AreTypesSame(CompilerType type1, CompilerType type2, bool ignore_qualifiers=false)
static clang::CXXRecordDecl * GetAsCXXRecordDecl(lldb::opaque_compiler_type_t type)
virtual ConstString GetTypeName()
CompilerType GetCompilerType()
#define LLDB_INVALID_ADDRESS
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::shared_ptr< lldb_private::Type > TypeSP
std::shared_ptr< lldb_private::TypeSystemClang > TypeSystemClangSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Module > ModuleSP
Symbol * symbol
Address of the vtable's virtual function table.