• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- Type.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 <stdio.h>
10 
11 #include "lldb/Core/Module.h"
12 #include "lldb/Utility/DataBufferHeap.h"
13 #include "lldb/Utility/DataExtractor.h"
14 #include "lldb/Utility/Log.h"
15 #include "lldb/Utility/Scalar.h"
16 #include "lldb/Utility/StreamString.h"
17 
18 #include "lldb/Symbol/CompilerType.h"
19 #include "lldb/Symbol/ObjectFile.h"
20 #include "lldb/Symbol/SymbolContextScope.h"
21 #include "lldb/Symbol/SymbolFile.h"
22 #include "lldb/Symbol/SymbolVendor.h"
23 #include "lldb/Symbol/Type.h"
24 #include "lldb/Symbol/TypeList.h"
25 #include "lldb/Symbol/TypeSystem.h"
26 
27 #include "lldb/Target/ExecutionContext.h"
28 #include "lldb/Target/Process.h"
29 #include "lldb/Target/Target.h"
30 
31 #include "llvm/ADT/StringRef.h"
32 
33 using namespace lldb;
34 using namespace lldb_private;
35 
contextMatches(llvm::ArrayRef<CompilerContext> context_chain,llvm::ArrayRef<CompilerContext> pattern)36 bool lldb_private::contextMatches(llvm::ArrayRef<CompilerContext> context_chain,
37                                   llvm::ArrayRef<CompilerContext> pattern) {
38   auto ctx = context_chain.begin();
39   auto ctx_end = context_chain.end();
40   for (const CompilerContext &pat : pattern) {
41     // Early exit if the pattern is too long.
42     if (ctx == ctx_end)
43       return false;
44     if (*ctx != pat) {
45       // Skip any number of module matches.
46       if (pat.kind == CompilerContextKind::AnyModule) {
47         // Greedily match 0..n modules.
48         ctx = std::find_if(ctx, ctx_end, [](const CompilerContext &ctx) {
49           return ctx.kind != CompilerContextKind::Module;
50         });
51         continue;
52       }
53       // See if there is a kind mismatch; they should have 1 bit in common.
54       if (((uint16_t)ctx->kind & (uint16_t)pat.kind) == 0)
55         return false;
56       // The name is ignored for AnyModule, but not for AnyType.
57       if (pat.kind != CompilerContextKind::AnyModule && ctx->name != pat.name)
58         return false;
59     }
60     ++ctx;
61   }
62   return true;
63 }
64 
Dump() const65 void CompilerContext::Dump() const {
66   switch (kind) {
67   default:
68     printf("Invalid");
69     break;
70   case CompilerContextKind::TranslationUnit:
71     printf("TranslationUnit");
72     break;
73   case CompilerContextKind::Module:
74     printf("Module");
75     break;
76   case CompilerContextKind::Namespace:
77     printf("Namespace");
78     break;
79   case CompilerContextKind::Class:
80     printf("Class");
81     break;
82   case CompilerContextKind::Struct:
83     printf("Structure");
84     break;
85   case CompilerContextKind::Union:
86     printf("Union");
87     break;
88   case CompilerContextKind::Function:
89     printf("Function");
90     break;
91   case CompilerContextKind::Variable:
92     printf("Variable");
93     break;
94   case CompilerContextKind::Enum:
95     printf("Enumeration");
96     break;
97   case CompilerContextKind::Typedef:
98     printf("Typedef");
99     break;
100   case CompilerContextKind::AnyModule:
101     printf("AnyModule");
102     break;
103   case CompilerContextKind::AnyType:
104     printf("AnyType");
105     break;
106   }
107   printf("(\"%s\")\n", name.GetCString());
108 }
109 
110 class TypeAppendVisitor {
111 public:
TypeAppendVisitor(TypeListImpl & type_list)112   TypeAppendVisitor(TypeListImpl &type_list) : m_type_list(type_list) {}
113 
operator ()(const lldb::TypeSP & type)114   bool operator()(const lldb::TypeSP &type) {
115     m_type_list.Append(TypeImplSP(new TypeImpl(type)));
116     return true;
117   }
118 
119 private:
120   TypeListImpl &m_type_list;
121 };
122 
Append(const lldb_private::TypeList & type_list)123 void TypeListImpl::Append(const lldb_private::TypeList &type_list) {
124   TypeAppendVisitor cb(*this);
125   type_list.ForEach(cb);
126 }
127 
SymbolFileType(SymbolFile & symbol_file,const lldb::TypeSP & type_sp)128 SymbolFileType::SymbolFileType(SymbolFile &symbol_file,
129                                const lldb::TypeSP &type_sp)
130     : UserID(type_sp ? type_sp->GetID() : LLDB_INVALID_UID),
131       m_symbol_file(symbol_file), m_type_sp(type_sp) {}
132 
GetType()133 Type *SymbolFileType::GetType() {
134   if (!m_type_sp) {
135     Type *resolved_type = m_symbol_file.ResolveTypeUID(GetID());
136     if (resolved_type)
137       m_type_sp = resolved_type->shared_from_this();
138   }
139   return m_type_sp.get();
140 }
141 
Type(lldb::user_id_t uid,SymbolFile * symbol_file,ConstString name,llvm::Optional<uint64_t> byte_size,SymbolContextScope * context,user_id_t encoding_uid,EncodingDataType encoding_uid_type,const Declaration & decl,const CompilerType & compiler_type,ResolveState compiler_type_resolve_state,uint32_t opaque_payload)142 Type::Type(lldb::user_id_t uid, SymbolFile *symbol_file, ConstString name,
143            llvm::Optional<uint64_t> byte_size, SymbolContextScope *context,
144            user_id_t encoding_uid, EncodingDataType encoding_uid_type,
145            const Declaration &decl, const CompilerType &compiler_type,
146            ResolveState compiler_type_resolve_state, uint32_t opaque_payload)
147     : std::enable_shared_from_this<Type>(), UserID(uid), m_name(name),
148       m_symbol_file(symbol_file), m_context(context), m_encoding_type(nullptr),
149       m_encoding_uid(encoding_uid), m_encoding_uid_type(encoding_uid_type),
150       m_decl(decl), m_compiler_type(compiler_type),
151       m_compiler_type_resolve_state(compiler_type ? compiler_type_resolve_state
152                                                   : ResolveState::Unresolved),
153       m_payload(opaque_payload) {
154   if (byte_size) {
155     m_byte_size = *byte_size;
156     m_byte_size_has_value = true;
157   } else {
158     m_byte_size = 0;
159     m_byte_size_has_value = false;
160   }
161 }
162 
Type()163 Type::Type()
164     : std::enable_shared_from_this<Type>(), UserID(0), m_name("<INVALID TYPE>"),
165       m_symbol_file(nullptr), m_context(nullptr), m_encoding_type(nullptr),
166       m_encoding_uid(LLDB_INVALID_UID), m_encoding_uid_type(eEncodingInvalid),
167       m_compiler_type_resolve_state(ResolveState::Unresolved) {
168   m_byte_size = 0;
169   m_byte_size_has_value = false;
170 }
171 
GetDescription(Stream * s,lldb::DescriptionLevel level,bool show_name,ExecutionContextScope * exe_scope)172 void Type::GetDescription(Stream *s, lldb::DescriptionLevel level,
173                           bool show_name, ExecutionContextScope *exe_scope) {
174   *s << "id = " << (const UserID &)*this;
175 
176   // Call the name accessor to make sure we resolve the type name
177   if (show_name) {
178     ConstString type_name = GetName();
179     if (type_name) {
180       *s << ", name = \"" << type_name << '"';
181       ConstString qualified_type_name(GetQualifiedName());
182       if (qualified_type_name != type_name) {
183         *s << ", qualified = \"" << qualified_type_name << '"';
184       }
185     }
186   }
187 
188   // Call the get byte size accesor so we resolve our byte size
189   if (GetByteSize(exe_scope))
190     s->Printf(", byte-size = %" PRIu64, m_byte_size);
191   bool show_fullpaths = (level == lldb::eDescriptionLevelVerbose);
192   m_decl.Dump(s, show_fullpaths);
193 
194   if (m_compiler_type.IsValid()) {
195     *s << ", compiler_type = \"";
196     GetForwardCompilerType().DumpTypeDescription(s);
197     *s << '"';
198   } else if (m_encoding_uid != LLDB_INVALID_UID) {
199     s->Printf(", type_uid = 0x%8.8" PRIx64, m_encoding_uid);
200     switch (m_encoding_uid_type) {
201     case eEncodingInvalid:
202       break;
203     case eEncodingIsUID:
204       s->PutCString(" (unresolved type)");
205       break;
206     case eEncodingIsConstUID:
207       s->PutCString(" (unresolved const type)");
208       break;
209     case eEncodingIsRestrictUID:
210       s->PutCString(" (unresolved restrict type)");
211       break;
212     case eEncodingIsVolatileUID:
213       s->PutCString(" (unresolved volatile type)");
214       break;
215     case eEncodingIsAtomicUID:
216       s->PutCString(" (unresolved atomic type)");
217       break;
218     case eEncodingIsTypedefUID:
219       s->PutCString(" (unresolved typedef)");
220       break;
221     case eEncodingIsPointerUID:
222       s->PutCString(" (unresolved pointer)");
223       break;
224     case eEncodingIsLValueReferenceUID:
225       s->PutCString(" (unresolved L value reference)");
226       break;
227     case eEncodingIsRValueReferenceUID:
228       s->PutCString(" (unresolved R value reference)");
229       break;
230     case eEncodingIsSyntheticUID:
231       s->PutCString(" (synthetic type)");
232       break;
233     }
234   }
235 }
236 
Dump(Stream * s,bool show_context,lldb::DescriptionLevel level)237 void Type::Dump(Stream *s, bool show_context, lldb::DescriptionLevel level) {
238   s->Printf("%p: ", static_cast<void *>(this));
239   s->Indent();
240   *s << "Type" << static_cast<const UserID &>(*this) << ' ';
241   if (m_name)
242     *s << ", name = \"" << m_name << "\"";
243 
244   if (m_byte_size_has_value)
245     s->Printf(", size = %" PRIu64, m_byte_size);
246 
247   if (show_context && m_context != nullptr) {
248     s->PutCString(", context = ( ");
249     m_context->DumpSymbolContext(s);
250     s->PutCString(" )");
251   }
252 
253   bool show_fullpaths = false;
254   m_decl.Dump(s, show_fullpaths);
255 
256   if (m_compiler_type.IsValid()) {
257     *s << ", compiler_type = " << m_compiler_type.GetOpaqueQualType() << ' ';
258     GetForwardCompilerType().DumpTypeDescription(s, level);
259   } else if (m_encoding_uid != LLDB_INVALID_UID) {
260     s->Format(", type_data = {0:x-16}", m_encoding_uid);
261     switch (m_encoding_uid_type) {
262     case eEncodingInvalid:
263       break;
264     case eEncodingIsUID:
265       s->PutCString(" (unresolved type)");
266       break;
267     case eEncodingIsConstUID:
268       s->PutCString(" (unresolved const type)");
269       break;
270     case eEncodingIsRestrictUID:
271       s->PutCString(" (unresolved restrict type)");
272       break;
273     case eEncodingIsVolatileUID:
274       s->PutCString(" (unresolved volatile type)");
275       break;
276     case eEncodingIsAtomicUID:
277       s->PutCString(" (unresolved atomic type)");
278       break;
279     case eEncodingIsTypedefUID:
280       s->PutCString(" (unresolved typedef)");
281       break;
282     case eEncodingIsPointerUID:
283       s->PutCString(" (unresolved pointer)");
284       break;
285     case eEncodingIsLValueReferenceUID:
286       s->PutCString(" (unresolved L value reference)");
287       break;
288     case eEncodingIsRValueReferenceUID:
289       s->PutCString(" (unresolved R value reference)");
290       break;
291     case eEncodingIsSyntheticUID:
292       s->PutCString(" (synthetic type)");
293       break;
294     }
295   }
296 
297   //
298   //  if (m_access)
299   //      s->Printf(", access = %u", m_access);
300   s->EOL();
301 }
302 
GetName()303 ConstString Type::GetName() {
304   if (!m_name)
305     m_name = GetForwardCompilerType().GetTypeName();
306   return m_name;
307 }
308 
DumpTypeName(Stream * s)309 void Type::DumpTypeName(Stream *s) { GetName().Dump(s, "<invalid-type-name>"); }
310 
DumpValue(ExecutionContext * exe_ctx,Stream * s,const DataExtractor & data,uint32_t data_byte_offset,bool show_types,bool show_summary,bool verbose,lldb::Format format)311 void Type::DumpValue(ExecutionContext *exe_ctx, Stream *s,
312                      const DataExtractor &data, uint32_t data_byte_offset,
313                      bool show_types, bool show_summary, bool verbose,
314                      lldb::Format format) {
315   if (ResolveCompilerType(ResolveState::Forward)) {
316     if (show_types) {
317       s->PutChar('(');
318       if (verbose)
319         s->Printf("Type{0x%8.8" PRIx64 "} ", GetID());
320       DumpTypeName(s);
321       s->PutCString(") ");
322     }
323 
324     GetForwardCompilerType().DumpValue(
325         exe_ctx, s, format == lldb::eFormatDefault ? GetFormat() : format, data,
326         data_byte_offset,
327         GetByteSize(exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr)
328             .getValueOr(0),
329         0, // Bitfield bit size
330         0, // Bitfield bit offset
331         show_types, show_summary, verbose, 0);
332   }
333 }
334 
GetEncodingType()335 Type *Type::GetEncodingType() {
336   if (m_encoding_type == nullptr && m_encoding_uid != LLDB_INVALID_UID)
337     m_encoding_type = m_symbol_file->ResolveTypeUID(m_encoding_uid);
338   return m_encoding_type;
339 }
340 
GetByteSize(ExecutionContextScope * exe_scope)341 llvm::Optional<uint64_t> Type::GetByteSize(ExecutionContextScope *exe_scope) {
342   if (m_byte_size_has_value)
343     return m_byte_size;
344 
345   switch (m_encoding_uid_type) {
346   case eEncodingInvalid:
347   case eEncodingIsSyntheticUID:
348     break;
349   case eEncodingIsUID:
350   case eEncodingIsConstUID:
351   case eEncodingIsRestrictUID:
352   case eEncodingIsVolatileUID:
353   case eEncodingIsAtomicUID:
354   case eEncodingIsTypedefUID: {
355     Type *encoding_type = GetEncodingType();
356     if (encoding_type)
357       if (llvm::Optional<uint64_t> size = encoding_type->GetByteSize(exe_scope)) {
358         m_byte_size = *size;
359         m_byte_size_has_value = true;
360         return m_byte_size;
361       }
362 
363     if (llvm::Optional<uint64_t> size =
364             GetLayoutCompilerType().GetByteSize(exe_scope)) {
365       m_byte_size = *size;
366       m_byte_size_has_value = true;
367         return m_byte_size;
368     }
369   } break;
370 
371     // If we are a pointer or reference, then this is just a pointer size;
372     case eEncodingIsPointerUID:
373     case eEncodingIsLValueReferenceUID:
374     case eEncodingIsRValueReferenceUID: {
375       if (ArchSpec arch = m_symbol_file->GetObjectFile()->GetArchitecture()) {
376         m_byte_size = arch.GetAddressByteSize();
377         m_byte_size_has_value = true;
378         return m_byte_size;
379       }
380     } break;
381   }
382   return {};
383 }
384 
GetNumChildren(bool omit_empty_base_classes)385 uint32_t Type::GetNumChildren(bool omit_empty_base_classes) {
386   return GetForwardCompilerType().GetNumChildren(omit_empty_base_classes, nullptr);
387 }
388 
IsAggregateType()389 bool Type::IsAggregateType() {
390   return GetForwardCompilerType().IsAggregateType();
391 }
392 
GetTypedefType()393 lldb::TypeSP Type::GetTypedefType() {
394   lldb::TypeSP type_sp;
395   if (IsTypedef()) {
396     Type *typedef_type = m_symbol_file->ResolveTypeUID(m_encoding_uid);
397     if (typedef_type)
398       type_sp = typedef_type->shared_from_this();
399   }
400   return type_sp;
401 }
402 
GetFormat()403 lldb::Format Type::GetFormat() { return GetForwardCompilerType().GetFormat(); }
404 
GetEncoding(uint64_t & count)405 lldb::Encoding Type::GetEncoding(uint64_t &count) {
406   // Make sure we resolve our type if it already hasn't been.
407   return GetForwardCompilerType().GetEncoding(count);
408 }
409 
DumpValueInMemory(ExecutionContext * exe_ctx,Stream * s,lldb::addr_t address,AddressType address_type,bool show_types,bool show_summary,bool verbose)410 bool Type::DumpValueInMemory(ExecutionContext *exe_ctx, Stream *s,
411                              lldb::addr_t address, AddressType address_type,
412                              bool show_types, bool show_summary, bool verbose) {
413   if (address != LLDB_INVALID_ADDRESS) {
414     DataExtractor data;
415     Target *target = nullptr;
416     if (exe_ctx)
417       target = exe_ctx->GetTargetPtr();
418     if (target)
419       data.SetByteOrder(target->GetArchitecture().GetByteOrder());
420     if (ReadFromMemory(exe_ctx, address, address_type, data)) {
421       DumpValue(exe_ctx, s, data, 0, show_types, show_summary, verbose);
422       return true;
423     }
424   }
425   return false;
426 }
427 
ReadFromMemory(ExecutionContext * exe_ctx,lldb::addr_t addr,AddressType address_type,DataExtractor & data)428 bool Type::ReadFromMemory(ExecutionContext *exe_ctx, lldb::addr_t addr,
429                           AddressType address_type, DataExtractor &data) {
430   if (address_type == eAddressTypeFile) {
431     // Can't convert a file address to anything valid without more context
432     // (which Module it came from)
433     return false;
434   }
435 
436   const uint64_t byte_size =
437       GetByteSize(exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr)
438           .getValueOr(0);
439   if (data.GetByteSize() < byte_size) {
440     lldb::DataBufferSP data_sp(new DataBufferHeap(byte_size, '\0'));
441     data.SetData(data_sp);
442   }
443 
444   uint8_t *dst = const_cast<uint8_t *>(data.PeekData(0, byte_size));
445   if (dst != nullptr) {
446     if (address_type == eAddressTypeHost) {
447       // The address is an address in this process, so just copy it
448       if (addr == 0)
449         return false;
450       memcpy(dst, reinterpret_cast<uint8_t *>(addr), byte_size);
451       return true;
452     } else {
453       if (exe_ctx) {
454         Process *process = exe_ctx->GetProcessPtr();
455         if (process) {
456           Status error;
457           return exe_ctx->GetProcessPtr()->ReadMemory(addr, dst, byte_size,
458                                                       error) == byte_size;
459         }
460       }
461     }
462   }
463   return false;
464 }
465 
WriteToMemory(ExecutionContext * exe_ctx,lldb::addr_t addr,AddressType address_type,DataExtractor & data)466 bool Type::WriteToMemory(ExecutionContext *exe_ctx, lldb::addr_t addr,
467                          AddressType address_type, DataExtractor &data) {
468   return false;
469 }
470 
GetDeclaration() const471 const Declaration &Type::GetDeclaration() const { return m_decl; }
472 
ResolveCompilerType(ResolveState compiler_type_resolve_state)473 bool Type::ResolveCompilerType(ResolveState compiler_type_resolve_state) {
474   // TODO: This needs to consider the correct type system to use.
475   Type *encoding_type = nullptr;
476   if (!m_compiler_type.IsValid()) {
477     encoding_type = GetEncodingType();
478     if (encoding_type) {
479       switch (m_encoding_uid_type) {
480       case eEncodingIsUID: {
481         CompilerType encoding_compiler_type =
482             encoding_type->GetForwardCompilerType();
483         if (encoding_compiler_type.IsValid()) {
484           m_compiler_type = encoding_compiler_type;
485           m_compiler_type_resolve_state =
486               encoding_type->m_compiler_type_resolve_state;
487         }
488       } break;
489 
490       case eEncodingIsConstUID:
491         m_compiler_type =
492             encoding_type->GetForwardCompilerType().AddConstModifier();
493         break;
494 
495       case eEncodingIsRestrictUID:
496         m_compiler_type =
497             encoding_type->GetForwardCompilerType().AddRestrictModifier();
498         break;
499 
500       case eEncodingIsVolatileUID:
501         m_compiler_type =
502             encoding_type->GetForwardCompilerType().AddVolatileModifier();
503         break;
504 
505       case eEncodingIsAtomicUID:
506         m_compiler_type =
507             encoding_type->GetForwardCompilerType().GetAtomicType();
508         break;
509 
510       case eEncodingIsTypedefUID:
511         m_compiler_type = encoding_type->GetForwardCompilerType().CreateTypedef(
512             m_name.AsCString("__lldb_invalid_typedef_name"),
513             GetSymbolFile()->GetDeclContextContainingUID(GetID()), m_payload);
514         m_name.Clear();
515         break;
516 
517       case eEncodingIsPointerUID:
518         m_compiler_type =
519             encoding_type->GetForwardCompilerType().GetPointerType();
520         break;
521 
522       case eEncodingIsLValueReferenceUID:
523         m_compiler_type =
524             encoding_type->GetForwardCompilerType().GetLValueReferenceType();
525         break;
526 
527       case eEncodingIsRValueReferenceUID:
528         m_compiler_type =
529             encoding_type->GetForwardCompilerType().GetRValueReferenceType();
530         break;
531 
532       default:
533         llvm_unreachable("Unhandled encoding_data_type.");
534       }
535     } else {
536       // We have no encoding type, return void?
537       auto type_system_or_err =
538           m_symbol_file->GetTypeSystemForLanguage(eLanguageTypeC);
539       if (auto err = type_system_or_err.takeError()) {
540         LLDB_LOG_ERROR(
541             lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
542             std::move(err),
543             "Unable to construct void type from TypeSystemClang");
544       } else {
545         CompilerType void_compiler_type =
546             type_system_or_err->GetBasicTypeFromAST(eBasicTypeVoid);
547         switch (m_encoding_uid_type) {
548         case eEncodingIsUID:
549           m_compiler_type = void_compiler_type;
550           break;
551 
552         case eEncodingIsConstUID:
553           m_compiler_type = void_compiler_type.AddConstModifier();
554           break;
555 
556         case eEncodingIsRestrictUID:
557           m_compiler_type = void_compiler_type.AddRestrictModifier();
558           break;
559 
560         case eEncodingIsVolatileUID:
561           m_compiler_type = void_compiler_type.AddVolatileModifier();
562           break;
563 
564         case eEncodingIsAtomicUID:
565           m_compiler_type = void_compiler_type.GetAtomicType();
566           break;
567 
568         case eEncodingIsTypedefUID:
569           m_compiler_type = void_compiler_type.CreateTypedef(
570               m_name.AsCString("__lldb_invalid_typedef_name"),
571               GetSymbolFile()->GetDeclContextContainingUID(GetID()), m_payload);
572           break;
573 
574         case eEncodingIsPointerUID:
575           m_compiler_type = void_compiler_type.GetPointerType();
576           break;
577 
578         case eEncodingIsLValueReferenceUID:
579           m_compiler_type = void_compiler_type.GetLValueReferenceType();
580           break;
581 
582         case eEncodingIsRValueReferenceUID:
583           m_compiler_type = void_compiler_type.GetRValueReferenceType();
584           break;
585 
586         default:
587           llvm_unreachable("Unhandled encoding_data_type.");
588         }
589       }
590     }
591 
592     // When we have a EncodingUID, our "m_flags.compiler_type_resolve_state" is
593     // set to eResolveStateUnresolved so we need to update it to say that we
594     // now have a forward declaration since that is what we created above.
595     if (m_compiler_type.IsValid())
596       m_compiler_type_resolve_state = ResolveState::Forward;
597   }
598 
599   // Check if we have a forward reference to a class/struct/union/enum?
600   if (compiler_type_resolve_state == ResolveState::Layout ||
601       compiler_type_resolve_state == ResolveState::Full) {
602     // Check if we have a forward reference to a class/struct/union/enum?
603     if (m_compiler_type.IsValid() &&
604         m_compiler_type_resolve_state < compiler_type_resolve_state) {
605       m_compiler_type_resolve_state = ResolveState::Full;
606       if (!m_compiler_type.IsDefined()) {
607         // We have a forward declaration, we need to resolve it to a complete
608         // definition.
609         m_symbol_file->CompleteType(m_compiler_type);
610       }
611     }
612   }
613 
614   // If we have an encoding type, then we need to make sure it is resolved
615   // appropriately.
616   if (m_encoding_uid != LLDB_INVALID_UID) {
617     if (encoding_type == nullptr)
618       encoding_type = GetEncodingType();
619     if (encoding_type) {
620       ResolveState encoding_compiler_type_resolve_state =
621           compiler_type_resolve_state;
622 
623       if (compiler_type_resolve_state == ResolveState::Layout) {
624         switch (m_encoding_uid_type) {
625         case eEncodingIsPointerUID:
626         case eEncodingIsLValueReferenceUID:
627         case eEncodingIsRValueReferenceUID:
628           encoding_compiler_type_resolve_state = ResolveState::Forward;
629           break;
630         default:
631           break;
632         }
633       }
634       encoding_type->ResolveCompilerType(encoding_compiler_type_resolve_state);
635     }
636   }
637   return m_compiler_type.IsValid();
638 }
GetEncodingMask()639 uint32_t Type::GetEncodingMask() {
640   uint32_t encoding_mask = 1u << m_encoding_uid_type;
641   Type *encoding_type = GetEncodingType();
642   assert(encoding_type != this);
643   if (encoding_type)
644     encoding_mask |= encoding_type->GetEncodingMask();
645   return encoding_mask;
646 }
647 
GetFullCompilerType()648 CompilerType Type::GetFullCompilerType() {
649   ResolveCompilerType(ResolveState::Full);
650   return m_compiler_type;
651 }
652 
GetLayoutCompilerType()653 CompilerType Type::GetLayoutCompilerType() {
654   ResolveCompilerType(ResolveState::Layout);
655   return m_compiler_type;
656 }
657 
GetForwardCompilerType()658 CompilerType Type::GetForwardCompilerType() {
659   ResolveCompilerType(ResolveState::Forward);
660   return m_compiler_type;
661 }
662 
GetQualifiedName()663 ConstString Type::GetQualifiedName() {
664   return GetForwardCompilerType().GetTypeName();
665 }
666 
GetTypeScopeAndBasename(const llvm::StringRef & name,llvm::StringRef & scope,llvm::StringRef & basename,TypeClass & type_class)667 bool Type::GetTypeScopeAndBasename(const llvm::StringRef& name,
668                                    llvm::StringRef &scope,
669                                    llvm::StringRef &basename,
670                                    TypeClass &type_class) {
671   type_class = eTypeClassAny;
672 
673   if (name.empty())
674     return false;
675 
676   basename = name;
677   if (basename.consume_front("struct "))
678     type_class = eTypeClassStruct;
679   else if (basename.consume_front("class "))
680     type_class = eTypeClassClass;
681   else if (basename.consume_front("union "))
682     type_class = eTypeClassUnion;
683   else if (basename.consume_front("enum "))
684     type_class = eTypeClassEnumeration;
685   else if (basename.consume_front("typedef "))
686     type_class = eTypeClassTypedef;
687 
688   size_t namespace_separator = basename.find("::");
689   if (namespace_separator == llvm::StringRef::npos)
690     return false;
691 
692   size_t template_begin = basename.find('<');
693   while (namespace_separator != llvm::StringRef::npos) {
694     if (template_begin != llvm::StringRef::npos &&
695         namespace_separator > template_begin) {
696       size_t template_depth = 1;
697       llvm::StringRef template_arg =
698           basename.drop_front(template_begin + 1);
699       while (template_depth > 0 && !template_arg.empty()) {
700         if (template_arg.front() == '<')
701           template_depth++;
702         else if (template_arg.front() == '>')
703           template_depth--;
704         template_arg = template_arg.drop_front(1);
705       }
706       if (template_depth != 0)
707         return false; // We have an invalid type name. Bail out.
708       if (template_arg.empty())
709         break; // The template ends at the end of the full name.
710       basename = template_arg;
711     } else {
712       basename = basename.drop_front(namespace_separator + 2);
713     }
714     template_begin = basename.find('<');
715     namespace_separator = basename.find("::");
716   }
717   if (basename.size() < name.size()) {
718     scope = name.take_front(name.size() - basename.size());
719     return true;
720   }
721   return false;
722 }
723 
GetModule()724 ModuleSP Type::GetModule() {
725   if (m_symbol_file)
726     return m_symbol_file->GetObjectFile()->GetModule();
727   return ModuleSP();
728 }
729 
GetExeModule()730 ModuleSP Type::GetExeModule() {
731   if (m_compiler_type) {
732     SymbolFile *symbol_file = m_compiler_type.GetTypeSystem()->GetSymbolFile();
733     return symbol_file->GetObjectFile()->GetModule();
734   }
735   return ModuleSP();
736 }
737 
TypeAndOrName(TypeSP & in_type_sp)738 TypeAndOrName::TypeAndOrName(TypeSP &in_type_sp) {
739   if (in_type_sp) {
740     m_compiler_type = in_type_sp->GetForwardCompilerType();
741     m_type_name = in_type_sp->GetName();
742   }
743 }
744 
TypeAndOrName(const char * in_type_str)745 TypeAndOrName::TypeAndOrName(const char *in_type_str)
746     : m_type_name(in_type_str) {}
747 
TypeAndOrName(ConstString & in_type_const_string)748 TypeAndOrName::TypeAndOrName(ConstString &in_type_const_string)
749     : m_type_name(in_type_const_string) {}
750 
operator ==(const TypeAndOrName & other) const751 bool TypeAndOrName::operator==(const TypeAndOrName &other) const {
752   if (m_compiler_type != other.m_compiler_type)
753     return false;
754   if (m_type_name != other.m_type_name)
755     return false;
756   return true;
757 }
758 
operator !=(const TypeAndOrName & other) const759 bool TypeAndOrName::operator!=(const TypeAndOrName &other) const {
760   return !(*this == other);
761 }
762 
GetName() const763 ConstString TypeAndOrName::GetName() const {
764   if (m_type_name)
765     return m_type_name;
766   if (m_compiler_type)
767     return m_compiler_type.GetTypeName();
768   return ConstString("<invalid>");
769 }
770 
SetName(ConstString type_name)771 void TypeAndOrName::SetName(ConstString type_name) {
772   m_type_name = type_name;
773 }
774 
SetName(const char * type_name_cstr)775 void TypeAndOrName::SetName(const char *type_name_cstr) {
776   m_type_name.SetCString(type_name_cstr);
777 }
778 
SetTypeSP(lldb::TypeSP type_sp)779 void TypeAndOrName::SetTypeSP(lldb::TypeSP type_sp) {
780   if (type_sp) {
781     m_compiler_type = type_sp->GetForwardCompilerType();
782     m_type_name = type_sp->GetName();
783   } else
784     Clear();
785 }
786 
SetCompilerType(CompilerType compiler_type)787 void TypeAndOrName::SetCompilerType(CompilerType compiler_type) {
788   m_compiler_type = compiler_type;
789   if (m_compiler_type)
790     m_type_name = m_compiler_type.GetTypeName();
791 }
792 
IsEmpty() const793 bool TypeAndOrName::IsEmpty() const {
794   return !((bool)m_type_name || (bool)m_compiler_type);
795 }
796 
Clear()797 void TypeAndOrName::Clear() {
798   m_type_name.Clear();
799   m_compiler_type.Clear();
800 }
801 
HasName() const802 bool TypeAndOrName::HasName() const { return (bool)m_type_name; }
803 
HasCompilerType() const804 bool TypeAndOrName::HasCompilerType() const {
805   return m_compiler_type.IsValid();
806 }
807 
TypeImpl(const lldb::TypeSP & type_sp)808 TypeImpl::TypeImpl(const lldb::TypeSP &type_sp)
809     : m_module_wp(), m_static_type(), m_dynamic_type() {
810   SetType(type_sp);
811 }
812 
TypeImpl(const CompilerType & compiler_type)813 TypeImpl::TypeImpl(const CompilerType &compiler_type)
814     : m_module_wp(), m_static_type(), m_dynamic_type() {
815   SetType(compiler_type);
816 }
817 
TypeImpl(const lldb::TypeSP & type_sp,const CompilerType & dynamic)818 TypeImpl::TypeImpl(const lldb::TypeSP &type_sp, const CompilerType &dynamic)
819     : m_module_wp(), m_static_type(), m_dynamic_type(dynamic) {
820   SetType(type_sp, dynamic);
821 }
822 
TypeImpl(const CompilerType & static_type,const CompilerType & dynamic_type)823 TypeImpl::TypeImpl(const CompilerType &static_type,
824                    const CompilerType &dynamic_type)
825     : m_module_wp(), m_static_type(), m_dynamic_type() {
826   SetType(static_type, dynamic_type);
827 }
828 
SetType(const lldb::TypeSP & type_sp)829 void TypeImpl::SetType(const lldb::TypeSP &type_sp) {
830   if (type_sp) {
831     m_static_type = type_sp->GetForwardCompilerType();
832     m_exe_module_wp = type_sp->GetExeModule();
833     m_module_wp = type_sp->GetModule();
834   } else {
835     m_static_type.Clear();
836     m_module_wp = lldb::ModuleWP();
837   }
838 }
839 
SetType(const CompilerType & compiler_type)840 void TypeImpl::SetType(const CompilerType &compiler_type) {
841   m_module_wp = lldb::ModuleWP();
842   m_static_type = compiler_type;
843 }
844 
SetType(const lldb::TypeSP & type_sp,const CompilerType & dynamic)845 void TypeImpl::SetType(const lldb::TypeSP &type_sp,
846                        const CompilerType &dynamic) {
847   SetType(type_sp);
848   m_dynamic_type = dynamic;
849 }
850 
SetType(const CompilerType & compiler_type,const CompilerType & dynamic)851 void TypeImpl::SetType(const CompilerType &compiler_type,
852                        const CompilerType &dynamic) {
853   m_module_wp = lldb::ModuleWP();
854   m_static_type = compiler_type;
855   m_dynamic_type = dynamic;
856 }
857 
CheckModule(lldb::ModuleSP & module_sp) const858 bool TypeImpl::CheckModule(lldb::ModuleSP &module_sp) const {
859   return CheckModuleCommon(m_module_wp, module_sp);
860 }
861 
CheckExeModule(lldb::ModuleSP & module_sp) const862 bool TypeImpl::CheckExeModule(lldb::ModuleSP &module_sp) const {
863   return CheckModuleCommon(m_exe_module_wp, module_sp);
864 }
865 
CheckModuleCommon(const lldb::ModuleWP & input_module_wp,lldb::ModuleSP & module_sp) const866 bool TypeImpl::CheckModuleCommon(const lldb::ModuleWP &input_module_wp,
867                                  lldb::ModuleSP &module_sp) const {
868   // Check if we have a module for this type. If we do and the shared pointer
869   // is can be successfully initialized with m_module_wp, return true. Else
870   // return false if we didn't have a module, or if we had a module and it has
871   // been deleted. Any functions doing anything with a TypeSP in this TypeImpl
872   // class should call this function and only do anything with the ivars if
873   // this function returns true. If we have a module, the "module_sp" will be
874   // filled in with a strong reference to the module so that the module will at
875   // least stay around long enough for the type query to succeed.
876   module_sp = input_module_wp.lock();
877   if (!module_sp) {
878     lldb::ModuleWP empty_module_wp;
879     // If either call to "std::weak_ptr::owner_before(...) value returns true,
880     // this indicates that m_module_wp once contained (possibly still does) a
881     // reference to a valid shared pointer. This helps us know if we had a
882     // valid reference to a section which is now invalid because the module it
883     // was in was deleted
884     if (empty_module_wp.owner_before(input_module_wp) ||
885         input_module_wp.owner_before(empty_module_wp)) {
886       // input_module_wp had a valid reference to a module, but all strong
887       // references have been released and the module has been deleted
888       return false;
889     }
890   }
891   // We either successfully locked the module, or didn't have one to begin with
892   return true;
893 }
894 
operator ==(const TypeImpl & rhs) const895 bool TypeImpl::operator==(const TypeImpl &rhs) const {
896   return m_static_type == rhs.m_static_type &&
897          m_dynamic_type == rhs.m_dynamic_type;
898 }
899 
operator !=(const TypeImpl & rhs) const900 bool TypeImpl::operator!=(const TypeImpl &rhs) const {
901   return !(*this == rhs);
902 }
903 
IsValid() const904 bool TypeImpl::IsValid() const {
905   // just a name is not valid
906   ModuleSP module_sp;
907   if (CheckModule(module_sp))
908     return m_static_type.IsValid() || m_dynamic_type.IsValid();
909   return false;
910 }
911 
operator bool() const912 TypeImpl::operator bool() const { return IsValid(); }
913 
Clear()914 void TypeImpl::Clear() {
915   m_module_wp = lldb::ModuleWP();
916   m_static_type.Clear();
917   m_dynamic_type.Clear();
918 }
919 
GetModule() const920 ModuleSP TypeImpl::GetModule() const {
921   lldb::ModuleSP module_sp;
922   if (CheckExeModule(module_sp))
923     return module_sp;
924   return nullptr;
925 }
926 
GetName() const927 ConstString TypeImpl::GetName() const {
928   ModuleSP module_sp;
929   if (CheckModule(module_sp)) {
930     if (m_dynamic_type)
931       return m_dynamic_type.GetTypeName();
932     return m_static_type.GetTypeName();
933   }
934   return ConstString();
935 }
936 
GetDisplayTypeName() const937 ConstString TypeImpl::GetDisplayTypeName() const {
938   ModuleSP module_sp;
939   if (CheckModule(module_sp)) {
940     if (m_dynamic_type)
941       return m_dynamic_type.GetDisplayTypeName();
942     return m_static_type.GetDisplayTypeName();
943   }
944   return ConstString();
945 }
946 
GetPointerType() const947 TypeImpl TypeImpl::GetPointerType() const {
948   ModuleSP module_sp;
949   if (CheckModule(module_sp)) {
950     if (m_dynamic_type.IsValid()) {
951       return TypeImpl(m_static_type.GetPointerType(),
952                       m_dynamic_type.GetPointerType());
953     }
954     return TypeImpl(m_static_type.GetPointerType());
955   }
956   return TypeImpl();
957 }
958 
GetPointeeType() const959 TypeImpl TypeImpl::GetPointeeType() const {
960   ModuleSP module_sp;
961   if (CheckModule(module_sp)) {
962     if (m_dynamic_type.IsValid()) {
963       return TypeImpl(m_static_type.GetPointeeType(),
964                       m_dynamic_type.GetPointeeType());
965     }
966     return TypeImpl(m_static_type.GetPointeeType());
967   }
968   return TypeImpl();
969 }
970 
GetReferenceType() const971 TypeImpl TypeImpl::GetReferenceType() const {
972   ModuleSP module_sp;
973   if (CheckModule(module_sp)) {
974     if (m_dynamic_type.IsValid()) {
975       return TypeImpl(m_static_type.GetLValueReferenceType(),
976                       m_dynamic_type.GetLValueReferenceType());
977     }
978     return TypeImpl(m_static_type.GetLValueReferenceType());
979   }
980   return TypeImpl();
981 }
982 
GetTypedefedType() const983 TypeImpl TypeImpl::GetTypedefedType() const {
984   ModuleSP module_sp;
985   if (CheckModule(module_sp)) {
986     if (m_dynamic_type.IsValid()) {
987       return TypeImpl(m_static_type.GetTypedefedType(),
988                       m_dynamic_type.GetTypedefedType());
989     }
990     return TypeImpl(m_static_type.GetTypedefedType());
991   }
992   return TypeImpl();
993 }
994 
GetDereferencedType() const995 TypeImpl TypeImpl::GetDereferencedType() const {
996   ModuleSP module_sp;
997   if (CheckModule(module_sp)) {
998     if (m_dynamic_type.IsValid()) {
999       return TypeImpl(m_static_type.GetNonReferenceType(),
1000                       m_dynamic_type.GetNonReferenceType());
1001     }
1002     return TypeImpl(m_static_type.GetNonReferenceType());
1003   }
1004   return TypeImpl();
1005 }
1006 
GetUnqualifiedType() const1007 TypeImpl TypeImpl::GetUnqualifiedType() const {
1008   ModuleSP module_sp;
1009   if (CheckModule(module_sp)) {
1010     if (m_dynamic_type.IsValid()) {
1011       return TypeImpl(m_static_type.GetFullyUnqualifiedType(),
1012                       m_dynamic_type.GetFullyUnqualifiedType());
1013     }
1014     return TypeImpl(m_static_type.GetFullyUnqualifiedType());
1015   }
1016   return TypeImpl();
1017 }
1018 
GetCanonicalType() const1019 TypeImpl TypeImpl::GetCanonicalType() const {
1020   ModuleSP module_sp;
1021   if (CheckModule(module_sp)) {
1022     if (m_dynamic_type.IsValid()) {
1023       return TypeImpl(m_static_type.GetCanonicalType(),
1024                       m_dynamic_type.GetCanonicalType());
1025     }
1026     return TypeImpl(m_static_type.GetCanonicalType());
1027   }
1028   return TypeImpl();
1029 }
1030 
GetCompilerType(bool prefer_dynamic)1031 CompilerType TypeImpl::GetCompilerType(bool prefer_dynamic) {
1032   ModuleSP module_sp;
1033   if (CheckModule(module_sp)) {
1034     if (prefer_dynamic) {
1035       if (m_dynamic_type.IsValid())
1036         return m_dynamic_type;
1037     }
1038     return m_static_type;
1039   }
1040   return CompilerType();
1041 }
1042 
GetTypeSystem(bool prefer_dynamic)1043 TypeSystem *TypeImpl::GetTypeSystem(bool prefer_dynamic) {
1044   ModuleSP module_sp;
1045   if (CheckModule(module_sp)) {
1046     if (prefer_dynamic) {
1047       if (m_dynamic_type.IsValid())
1048         return m_dynamic_type.GetTypeSystem();
1049     }
1050     return m_static_type.GetTypeSystem();
1051   }
1052   return nullptr;
1053 }
1054 
GetDescription(lldb_private::Stream & strm,lldb::DescriptionLevel description_level)1055 bool TypeImpl::GetDescription(lldb_private::Stream &strm,
1056                               lldb::DescriptionLevel description_level) {
1057   ModuleSP module_sp;
1058   if (CheckModule(module_sp)) {
1059     if (m_dynamic_type.IsValid()) {
1060       strm.Printf("Dynamic:\n");
1061       m_dynamic_type.DumpTypeDescription(&strm);
1062       strm.Printf("\nStatic:\n");
1063     }
1064     m_static_type.DumpTypeDescription(&strm);
1065   } else {
1066     strm.PutCString("Invalid TypeImpl module for type has been deleted\n");
1067   }
1068   return true;
1069 }
1070 
IsValid()1071 bool TypeMemberFunctionImpl::IsValid() {
1072   return m_type.IsValid() && m_kind != lldb::eMemberFunctionKindUnknown;
1073 }
1074 
GetName() const1075 ConstString TypeMemberFunctionImpl::GetName() const { return m_name; }
1076 
GetMangledName() const1077 ConstString TypeMemberFunctionImpl::GetMangledName() const {
1078   return m_decl.GetMangledName();
1079 }
1080 
GetType() const1081 CompilerType TypeMemberFunctionImpl::GetType() const { return m_type; }
1082 
GetKind() const1083 lldb::MemberFunctionKind TypeMemberFunctionImpl::GetKind() const {
1084   return m_kind;
1085 }
1086 
GetDescription(Stream & stream)1087 bool TypeMemberFunctionImpl::GetDescription(Stream &stream) {
1088   switch (m_kind) {
1089   case lldb::eMemberFunctionKindUnknown:
1090     return false;
1091   case lldb::eMemberFunctionKindConstructor:
1092     stream.Printf("constructor for %s",
1093                   m_type.GetTypeName().AsCString("<unknown>"));
1094     break;
1095   case lldb::eMemberFunctionKindDestructor:
1096     stream.Printf("destructor for %s",
1097                   m_type.GetTypeName().AsCString("<unknown>"));
1098     break;
1099   case lldb::eMemberFunctionKindInstanceMethod:
1100     stream.Printf("instance method %s of type %s", m_name.AsCString(),
1101                   m_decl.GetDeclContext().GetName().AsCString());
1102     break;
1103   case lldb::eMemberFunctionKindStaticMethod:
1104     stream.Printf("static method %s of type %s", m_name.AsCString(),
1105                   m_decl.GetDeclContext().GetName().AsCString());
1106     break;
1107   }
1108   return true;
1109 }
1110 
GetReturnType() const1111 CompilerType TypeMemberFunctionImpl::GetReturnType() const {
1112   if (m_type)
1113     return m_type.GetFunctionReturnType();
1114   return m_decl.GetFunctionReturnType();
1115 }
1116 
GetNumArguments() const1117 size_t TypeMemberFunctionImpl::GetNumArguments() const {
1118   if (m_type)
1119     return m_type.GetNumberOfFunctionArguments();
1120   else
1121     return m_decl.GetNumFunctionArguments();
1122 }
1123 
GetArgumentAtIndex(size_t idx) const1124 CompilerType TypeMemberFunctionImpl::GetArgumentAtIndex(size_t idx) const {
1125   if (m_type)
1126     return m_type.GetFunctionArgumentAtIndex(idx);
1127   else
1128     return m_decl.GetFunctionArgumentType(idx);
1129 }
1130 
TypeEnumMemberImpl(const lldb::TypeImplSP & integer_type_sp,ConstString name,const llvm::APSInt & value)1131 TypeEnumMemberImpl::TypeEnumMemberImpl(const lldb::TypeImplSP &integer_type_sp,
1132                                        ConstString name,
1133                                        const llvm::APSInt &value)
1134     : m_integer_type_sp(integer_type_sp), m_name(name), m_value(value),
1135       m_valid((bool)name && (bool)integer_type_sp)
1136 
1137 {}
1138