1 //===-- ClangExpressionDeclMap.cpp -----------------------------*- C++ -*-===// 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 "ClangExpressionDeclMap.h" 10 11 #include "ASTDumper.h" 12 #include "ClangASTSource.h" 13 #include "ClangModulesDeclVendor.h" 14 #include "ClangPersistentVariables.h" 15 16 #include "lldb/Core/Address.h" 17 #include "lldb/Core/Module.h" 18 #include "lldb/Core/ModuleSpec.h" 19 #include "lldb/Core/ValueObjectConstResult.h" 20 #include "lldb/Core/ValueObjectVariable.h" 21 #include "lldb/Expression/Materializer.h" 22 #include "lldb/Symbol/ClangASTContext.h" 23 #include "lldb/Symbol/CompileUnit.h" 24 #include "lldb/Symbol/CompilerDecl.h" 25 #include "lldb/Symbol/CompilerDeclContext.h" 26 #include "lldb/Symbol/Function.h" 27 #include "lldb/Symbol/ObjectFile.h" 28 #include "lldb/Symbol/SymbolContext.h" 29 #include "lldb/Symbol/SymbolFile.h" 30 #include "lldb/Symbol/SymbolVendor.h" 31 #include "lldb/Symbol/Type.h" 32 #include "lldb/Symbol/TypeList.h" 33 #include "lldb/Symbol/Variable.h" 34 #include "lldb/Symbol/VariableList.h" 35 #include "lldb/Target/ExecutionContext.h" 36 #include "lldb/Target/Process.h" 37 #include "lldb/Target/RegisterContext.h" 38 #include "lldb/Target/StackFrame.h" 39 #include "lldb/Target/Target.h" 40 #include "lldb/Target/Thread.h" 41 #include "lldb/Utility/Endian.h" 42 #include "lldb/Utility/Log.h" 43 #include "lldb/Utility/RegisterValue.h" 44 #include "lldb/Utility/Status.h" 45 #include "lldb/lldb-private.h" 46 #include "clang/AST/ASTConsumer.h" 47 #include "clang/AST/ASTContext.h" 48 #include "clang/AST/ASTImporter.h" 49 #include "clang/AST/Decl.h" 50 #include "clang/AST/DeclarationName.h" 51 #include "clang/AST/RecursiveASTVisitor.h" 52 53 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h" 54 #include "Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h" 55 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" 56 57 using namespace lldb; 58 using namespace lldb_private; 59 using namespace clang; 60 61 namespace { 62 const char *g_lldb_local_vars_namespace_cstr = "$__lldb_local_vars"; 63 } // anonymous namespace 64 65 ClangExpressionDeclMap::ClangExpressionDeclMap( 66 bool keep_result_in_memory, 67 Materializer::PersistentVariableDelegate *result_delegate, 68 ExecutionContext &exe_ctx, ValueObject *ctx_obj) 69 : ClangASTSource(exe_ctx.GetTargetSP()), m_found_entities(), 70 m_struct_members(), m_keep_result_in_memory(keep_result_in_memory), 71 m_result_delegate(result_delegate), m_ctx_obj(ctx_obj), m_parser_vars(), 72 m_struct_vars() { 73 EnableStructVars(); 74 } 75 76 ClangExpressionDeclMap::~ClangExpressionDeclMap() { 77 // Note: The model is now that the parser's AST context and all associated 78 // data does not vanish until the expression has been executed. This means 79 // that valuable lookup data (like namespaces) doesn't vanish, but 80 81 DidParse(); 82 DisableStructVars(); 83 } 84 85 bool ClangExpressionDeclMap::WillParse(ExecutionContext &exe_ctx, 86 Materializer *materializer) { 87 ClangASTMetrics::ClearLocalCounters(); 88 89 EnableParserVars(); 90 m_parser_vars->m_exe_ctx = exe_ctx; 91 92 Target *target = exe_ctx.GetTargetPtr(); 93 if (exe_ctx.GetFramePtr()) 94 m_parser_vars->m_sym_ctx = 95 exe_ctx.GetFramePtr()->GetSymbolContext(lldb::eSymbolContextEverything); 96 else if (exe_ctx.GetThreadPtr() && 97 exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(0)) 98 m_parser_vars->m_sym_ctx = 99 exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(0)->GetSymbolContext( 100 lldb::eSymbolContextEverything); 101 else if (exe_ctx.GetProcessPtr()) { 102 m_parser_vars->m_sym_ctx.Clear(true); 103 m_parser_vars->m_sym_ctx.target_sp = exe_ctx.GetTargetSP(); 104 } else if (target) { 105 m_parser_vars->m_sym_ctx.Clear(true); 106 m_parser_vars->m_sym_ctx.target_sp = exe_ctx.GetTargetSP(); 107 } 108 109 if (target) { 110 m_parser_vars->m_persistent_vars = llvm::cast<ClangPersistentVariables>( 111 target->GetPersistentExpressionStateForLanguage(eLanguageTypeC)); 112 113 if (!target->GetScratchClangASTContext()) 114 return false; 115 } 116 117 m_parser_vars->m_target_info = GetTargetInfo(); 118 m_parser_vars->m_materializer = materializer; 119 120 return true; 121 } 122 123 void ClangExpressionDeclMap::InstallCodeGenerator( 124 clang::ASTConsumer *code_gen) { 125 assert(m_parser_vars); 126 m_parser_vars->m_code_gen = code_gen; 127 } 128 129 void ClangExpressionDeclMap::DidParse() { 130 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 131 132 if (log) 133 ClangASTMetrics::DumpCounters(log); 134 135 if (m_parser_vars) { 136 for (size_t entity_index = 0, num_entities = m_found_entities.GetSize(); 137 entity_index < num_entities; ++entity_index) { 138 ExpressionVariableSP var_sp( 139 m_found_entities.GetVariableAtIndex(entity_index)); 140 if (var_sp) 141 llvm::cast<ClangExpressionVariable>(var_sp.get()) 142 ->DisableParserVars(GetParserID()); 143 } 144 145 for (size_t pvar_index = 0, 146 num_pvars = m_parser_vars->m_persistent_vars->GetSize(); 147 pvar_index < num_pvars; ++pvar_index) { 148 ExpressionVariableSP pvar_sp( 149 m_parser_vars->m_persistent_vars->GetVariableAtIndex(pvar_index)); 150 if (ClangExpressionVariable *clang_var = 151 llvm::dyn_cast<ClangExpressionVariable>(pvar_sp.get())) 152 clang_var->DisableParserVars(GetParserID()); 153 } 154 155 DisableParserVars(); 156 } 157 } 158 159 // Interface for IRForTarget 160 161 ClangExpressionDeclMap::TargetInfo ClangExpressionDeclMap::GetTargetInfo() { 162 assert(m_parser_vars.get()); 163 164 TargetInfo ret; 165 166 ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx; 167 168 Process *process = exe_ctx.GetProcessPtr(); 169 if (process) { 170 ret.byte_order = process->GetByteOrder(); 171 ret.address_byte_size = process->GetAddressByteSize(); 172 } else { 173 Target *target = exe_ctx.GetTargetPtr(); 174 if (target) { 175 ret.byte_order = target->GetArchitecture().GetByteOrder(); 176 ret.address_byte_size = target->GetArchitecture().GetAddressByteSize(); 177 } 178 } 179 180 return ret; 181 } 182 183 namespace { 184 /// This class walks an AST and ensures that all DeclContexts defined inside the 185 /// current source file are properly complete. 186 /// 187 /// This is used to ensure that persistent types defined in the current source 188 /// file migrate completely to the persistent AST context before they are 189 /// reused. If that didn't happen, it would be impoossible to complete them 190 /// because their origin would be gone. 191 /// 192 /// The stragtegy used by this class is to check the SourceLocation (to be 193 /// specific, the FileID) and see if it's the FileID for the current expression. 194 /// Alternate strategies could include checking whether an ExternalASTMerger, 195 /// set up to not have the current context as a source, can find an original for 196 /// the type. 197 class Completer : public clang::RecursiveASTVisitor<Completer> { 198 private: 199 /// Used to import Decl contents 200 clang::ASTImporter &m_exporter; 201 /// The file that's going away 202 clang::FileID m_file; 203 /// Visited Decls, to avoid cycles 204 llvm::DenseSet<clang::Decl *> m_completed; 205 206 bool ImportAndCheckCompletable(clang::Decl *decl) { 207 llvm::Expected<clang::Decl *> imported_decl = m_exporter.Import(decl); 208 if (!imported_decl) { 209 llvm::consumeError(imported_decl.takeError()); 210 return false; 211 } 212 if (m_completed.count(decl)) 213 return false; 214 if (!llvm::isa<DeclContext>(decl)) 215 return false; 216 const clang::SourceLocation loc = decl->getLocation(); 217 if (!loc.isValid()) 218 return false; 219 const clang::FileID file = 220 m_exporter.getFromContext().getSourceManager().getFileID(loc); 221 if (file != m_file) 222 return false; 223 // We are assuming the Decl was parsed in this very expression, so it 224 // should not have external storage. 225 lldbassert(!llvm::cast<DeclContext>(decl)->hasExternalLexicalStorage()); 226 return true; 227 } 228 229 void Complete(clang::Decl *decl) { 230 m_completed.insert(decl); 231 auto *decl_context = llvm::cast<DeclContext>(decl); 232 llvm::Expected<clang::Decl *> imported_decl = m_exporter.Import(decl); 233 if (!imported_decl) { 234 llvm::consumeError(imported_decl.takeError()); 235 return; 236 } 237 m_exporter.CompleteDecl(decl); 238 for (Decl *child : decl_context->decls()) 239 if (ImportAndCheckCompletable(child)) 240 Complete(child); 241 } 242 243 void MaybeComplete(clang::Decl *decl) { 244 if (ImportAndCheckCompletable(decl)) 245 Complete(decl); 246 } 247 248 public: 249 Completer(clang::ASTImporter &exporter, clang::FileID file) 250 : m_exporter(exporter), m_file(file) {} 251 252 // Implements the RecursiveASTVisitor's core API. It is called on each Decl 253 // that the RecursiveASTVisitor encounters, and returns true if the traversal 254 // should continue. 255 bool VisitDecl(clang::Decl *decl) { 256 MaybeComplete(decl); 257 return true; 258 } 259 }; 260 } // namespace 261 262 static void CompleteAllDeclContexts(clang::ASTImporter &exporter, 263 clang::FileID file, clang::QualType root) { 264 clang::QualType canonical_type = root.getCanonicalType(); 265 if (clang::TagDecl *tag_decl = canonical_type->getAsTagDecl()) { 266 Completer(exporter, file).TraverseDecl(tag_decl); 267 } else if (auto interface_type = llvm::dyn_cast<ObjCInterfaceType>( 268 canonical_type.getTypePtr())) { 269 Completer(exporter, file).TraverseDecl(interface_type->getDecl()); 270 } else { 271 Completer(exporter, file).TraverseType(canonical_type); 272 } 273 } 274 275 static clang::QualType ExportAllDeclaredTypes( 276 clang::ExternalASTMerger &merger, clang::ASTContext &source, 277 clang::FileManager &source_file_manager, 278 const clang::ExternalASTMerger::OriginMap &source_origin_map, 279 clang::FileID file, clang::QualType root) { 280 clang::ExternalASTMerger::ImporterSource importer_source = { 281 source, source_file_manager, source_origin_map}; 282 merger.AddSources(importer_source); 283 clang::ASTImporter &exporter = merger.ImporterForOrigin(source); 284 CompleteAllDeclContexts(exporter, file, root); 285 llvm::Expected<clang::QualType> ret_or_error = exporter.Import(root); 286 merger.RemoveSources(importer_source); 287 if (ret_or_error) { 288 return *ret_or_error; 289 } else { 290 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); 291 LLDB_LOG_ERROR(log, ret_or_error.takeError(), "Couldn't import type: {0}"); 292 return clang::QualType(); 293 } 294 } 295 296 TypeFromUser ClangExpressionDeclMap::DeportType(ClangASTContext &target, 297 ClangASTContext &source, 298 TypeFromParser parser_type) { 299 assert(&target == m_target->GetScratchClangASTContext()); 300 assert((TypeSystem *)&source == parser_type.GetTypeSystem()); 301 assert(source.getASTContext() == m_ast_context); 302 303 if (m_ast_importer_sp) { 304 return TypeFromUser(m_ast_importer_sp->DeportType( 305 target.getASTContext(), source.getASTContext(), 306 parser_type.GetOpaqueQualType()), 307 &target); 308 } else if (m_merger_up) { 309 clang::FileID source_file = 310 source.getASTContext()->getSourceManager().getFileID( 311 source.getASTContext()->getTranslationUnitDecl()->getLocation()); 312 auto scratch_ast_context = static_cast<ClangASTContextForExpressions *>( 313 m_target->GetScratchClangASTContext()); 314 clang::QualType exported_type = ExportAllDeclaredTypes( 315 scratch_ast_context->GetMergerUnchecked(), *source.getASTContext(), 316 *source.getFileManager(), m_merger_up->GetOrigins(), source_file, 317 clang::QualType::getFromOpaquePtr(parser_type.GetOpaqueQualType())); 318 return TypeFromUser(exported_type.getAsOpaquePtr(), &target); 319 } else { 320 lldbassert(0 && "No mechanism for deporting a type!"); 321 return TypeFromUser(); 322 } 323 } 324 325 bool ClangExpressionDeclMap::AddPersistentVariable(const NamedDecl *decl, 326 ConstString name, 327 TypeFromParser parser_type, 328 bool is_result, 329 bool is_lvalue) { 330 assert(m_parser_vars.get()); 331 332 ClangASTContext *ast = 333 llvm::dyn_cast_or_null<ClangASTContext>(parser_type.GetTypeSystem()); 334 if (ast == nullptr) 335 return false; 336 337 if (m_parser_vars->m_materializer && is_result) { 338 Status err; 339 340 ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx; 341 Target *target = exe_ctx.GetTargetPtr(); 342 if (target == nullptr) 343 return false; 344 345 TypeFromUser user_type = 346 DeportType(*target->GetScratchClangASTContext(), *ast, parser_type); 347 348 uint32_t offset = m_parser_vars->m_materializer->AddResultVariable( 349 user_type, is_lvalue, m_keep_result_in_memory, m_result_delegate, err); 350 351 ClangExpressionVariable *var = new ClangExpressionVariable( 352 exe_ctx.GetBestExecutionContextScope(), name, user_type, 353 m_parser_vars->m_target_info.byte_order, 354 m_parser_vars->m_target_info.address_byte_size); 355 356 m_found_entities.AddNewlyConstructedVariable(var); 357 358 var->EnableParserVars(GetParserID()); 359 360 ClangExpressionVariable::ParserVars *parser_vars = 361 var->GetParserVars(GetParserID()); 362 363 parser_vars->m_named_decl = decl; 364 parser_vars->m_parser_type = parser_type; 365 366 var->EnableJITVars(GetParserID()); 367 368 ClangExpressionVariable::JITVars *jit_vars = var->GetJITVars(GetParserID()); 369 370 jit_vars->m_offset = offset; 371 372 return true; 373 } 374 375 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 376 ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx; 377 Target *target = exe_ctx.GetTargetPtr(); 378 if (target == nullptr) 379 return false; 380 381 ClangASTContext *context(target->GetScratchClangASTContext()); 382 383 TypeFromUser user_type = DeportType(*context, *ast, parser_type); 384 385 if (!user_type.GetOpaqueQualType()) { 386 LLDB_LOGF(log, "Persistent variable's type wasn't copied successfully"); 387 return false; 388 } 389 390 if (!m_parser_vars->m_target_info.IsValid()) 391 return false; 392 393 ClangExpressionVariable *var = llvm::cast<ClangExpressionVariable>( 394 m_parser_vars->m_persistent_vars 395 ->CreatePersistentVariable( 396 exe_ctx.GetBestExecutionContextScope(), name, user_type, 397 m_parser_vars->m_target_info.byte_order, 398 m_parser_vars->m_target_info.address_byte_size) 399 .get()); 400 401 if (!var) 402 return false; 403 404 var->m_frozen_sp->SetHasCompleteType(); 405 406 if (is_result) 407 var->m_flags |= ClangExpressionVariable::EVNeedsFreezeDry; 408 else 409 var->m_flags |= 410 ClangExpressionVariable::EVKeepInTarget; // explicitly-declared 411 // persistent variables should 412 // persist 413 414 if (is_lvalue) { 415 var->m_flags |= ClangExpressionVariable::EVIsProgramReference; 416 } else { 417 var->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated; 418 var->m_flags |= ClangExpressionVariable::EVNeedsAllocation; 419 } 420 421 if (m_keep_result_in_memory) { 422 var->m_flags |= ClangExpressionVariable::EVKeepInTarget; 423 } 424 425 LLDB_LOGF(log, "Created persistent variable with flags 0x%hx", var->m_flags); 426 427 var->EnableParserVars(GetParserID()); 428 429 ClangExpressionVariable::ParserVars *parser_vars = 430 var->GetParserVars(GetParserID()); 431 432 parser_vars->m_named_decl = decl; 433 parser_vars->m_parser_type = parser_type; 434 435 return true; 436 } 437 438 bool ClangExpressionDeclMap::AddValueToStruct(const NamedDecl *decl, 439 ConstString name, 440 llvm::Value *value, size_t size, 441 lldb::offset_t alignment) { 442 assert(m_struct_vars.get()); 443 assert(m_parser_vars.get()); 444 445 bool is_persistent_variable = false; 446 447 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 448 449 m_struct_vars->m_struct_laid_out = false; 450 451 if (ClangExpressionVariable::FindVariableInList(m_struct_members, decl, 452 GetParserID())) 453 return true; 454 455 ClangExpressionVariable *var(ClangExpressionVariable::FindVariableInList( 456 m_found_entities, decl, GetParserID())); 457 458 if (!var) { 459 var = ClangExpressionVariable::FindVariableInList( 460 *m_parser_vars->m_persistent_vars, decl, GetParserID()); 461 is_persistent_variable = true; 462 } 463 464 if (!var) 465 return false; 466 467 LLDB_LOGF(log, "Adding value for (NamedDecl*)%p [%s - %s] to the structure", 468 static_cast<const void *>(decl), name.GetCString(), 469 var->GetName().GetCString()); 470 471 // We know entity->m_parser_vars is valid because we used a parser variable 472 // to find it 473 474 ClangExpressionVariable::ParserVars *parser_vars = 475 llvm::cast<ClangExpressionVariable>(var)->GetParserVars(GetParserID()); 476 477 parser_vars->m_llvm_value = value; 478 479 if (ClangExpressionVariable::JITVars *jit_vars = 480 llvm::cast<ClangExpressionVariable>(var)->GetJITVars(GetParserID())) { 481 // We already laid this out; do not touch 482 483 LLDB_LOGF(log, "Already placed at 0x%llx", 484 (unsigned long long)jit_vars->m_offset); 485 } 486 487 llvm::cast<ClangExpressionVariable>(var)->EnableJITVars(GetParserID()); 488 489 ClangExpressionVariable::JITVars *jit_vars = 490 llvm::cast<ClangExpressionVariable>(var)->GetJITVars(GetParserID()); 491 492 jit_vars->m_alignment = alignment; 493 jit_vars->m_size = size; 494 495 m_struct_members.AddVariable(var->shared_from_this()); 496 497 if (m_parser_vars->m_materializer) { 498 uint32_t offset = 0; 499 500 Status err; 501 502 if (is_persistent_variable) { 503 ExpressionVariableSP var_sp(var->shared_from_this()); 504 offset = m_parser_vars->m_materializer->AddPersistentVariable( 505 var_sp, nullptr, err); 506 } else { 507 if (const lldb_private::Symbol *sym = parser_vars->m_lldb_sym) 508 offset = m_parser_vars->m_materializer->AddSymbol(*sym, err); 509 else if (const RegisterInfo *reg_info = var->GetRegisterInfo()) 510 offset = m_parser_vars->m_materializer->AddRegister(*reg_info, err); 511 else if (parser_vars->m_lldb_var) 512 offset = m_parser_vars->m_materializer->AddVariable( 513 parser_vars->m_lldb_var, err); 514 } 515 516 if (!err.Success()) 517 return false; 518 519 LLDB_LOGF(log, "Placed at 0x%llx", (unsigned long long)offset); 520 521 jit_vars->m_offset = 522 offset; // TODO DoStructLayout() should not change this. 523 } 524 525 return true; 526 } 527 528 bool ClangExpressionDeclMap::DoStructLayout() { 529 assert(m_struct_vars.get()); 530 531 if (m_struct_vars->m_struct_laid_out) 532 return true; 533 534 if (!m_parser_vars->m_materializer) 535 return false; 536 537 m_struct_vars->m_struct_alignment = 538 m_parser_vars->m_materializer->GetStructAlignment(); 539 m_struct_vars->m_struct_size = 540 m_parser_vars->m_materializer->GetStructByteSize(); 541 m_struct_vars->m_struct_laid_out = true; 542 return true; 543 } 544 545 bool ClangExpressionDeclMap::GetStructInfo(uint32_t &num_elements, size_t &size, 546 lldb::offset_t &alignment) { 547 assert(m_struct_vars.get()); 548 549 if (!m_struct_vars->m_struct_laid_out) 550 return false; 551 552 num_elements = m_struct_members.GetSize(); 553 size = m_struct_vars->m_struct_size; 554 alignment = m_struct_vars->m_struct_alignment; 555 556 return true; 557 } 558 559 bool ClangExpressionDeclMap::GetStructElement(const NamedDecl *&decl, 560 llvm::Value *&value, 561 lldb::offset_t &offset, 562 ConstString &name, 563 uint32_t index) { 564 assert(m_struct_vars.get()); 565 566 if (!m_struct_vars->m_struct_laid_out) 567 return false; 568 569 if (index >= m_struct_members.GetSize()) 570 return false; 571 572 ExpressionVariableSP member_sp(m_struct_members.GetVariableAtIndex(index)); 573 574 if (!member_sp) 575 return false; 576 577 ClangExpressionVariable::ParserVars *parser_vars = 578 llvm::cast<ClangExpressionVariable>(member_sp.get()) 579 ->GetParserVars(GetParserID()); 580 ClangExpressionVariable::JITVars *jit_vars = 581 llvm::cast<ClangExpressionVariable>(member_sp.get()) 582 ->GetJITVars(GetParserID()); 583 584 if (!parser_vars || !jit_vars || !member_sp->GetValueObject()) 585 return false; 586 587 decl = parser_vars->m_named_decl; 588 value = parser_vars->m_llvm_value; 589 offset = jit_vars->m_offset; 590 name = member_sp->GetName(); 591 592 return true; 593 } 594 595 bool ClangExpressionDeclMap::GetFunctionInfo(const NamedDecl *decl, 596 uint64_t &ptr) { 597 ClangExpressionVariable *entity(ClangExpressionVariable::FindVariableInList( 598 m_found_entities, decl, GetParserID())); 599 600 if (!entity) 601 return false; 602 603 // We know m_parser_vars is valid since we searched for the variable by its 604 // NamedDecl 605 606 ClangExpressionVariable::ParserVars *parser_vars = 607 entity->GetParserVars(GetParserID()); 608 609 ptr = parser_vars->m_lldb_value.GetScalar().ULongLong(); 610 611 return true; 612 } 613 614 addr_t ClangExpressionDeclMap::GetSymbolAddress(Target &target, 615 Process *process, 616 ConstString name, 617 lldb::SymbolType symbol_type, 618 lldb_private::Module *module) { 619 SymbolContextList sc_list; 620 621 if (module) 622 module->FindSymbolsWithNameAndType(name, symbol_type, sc_list); 623 else 624 target.GetImages().FindSymbolsWithNameAndType(name, symbol_type, sc_list); 625 626 const uint32_t num_matches = sc_list.GetSize(); 627 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS; 628 629 for (uint32_t i = 0; 630 i < num_matches && 631 (symbol_load_addr == 0 || symbol_load_addr == LLDB_INVALID_ADDRESS); 632 i++) { 633 SymbolContext sym_ctx; 634 sc_list.GetContextAtIndex(i, sym_ctx); 635 636 const Address sym_address = sym_ctx.symbol->GetAddress(); 637 638 if (!sym_address.IsValid()) 639 continue; 640 641 switch (sym_ctx.symbol->GetType()) { 642 case eSymbolTypeCode: 643 case eSymbolTypeTrampoline: 644 symbol_load_addr = sym_address.GetCallableLoadAddress(&target); 645 break; 646 647 case eSymbolTypeResolver: 648 symbol_load_addr = sym_address.GetCallableLoadAddress(&target, true); 649 break; 650 651 case eSymbolTypeReExported: { 652 ConstString reexport_name = sym_ctx.symbol->GetReExportedSymbolName(); 653 if (reexport_name) { 654 ModuleSP reexport_module_sp; 655 ModuleSpec reexport_module_spec; 656 reexport_module_spec.GetPlatformFileSpec() = 657 sym_ctx.symbol->GetReExportedSymbolSharedLibrary(); 658 if (reexport_module_spec.GetPlatformFileSpec()) { 659 reexport_module_sp = 660 target.GetImages().FindFirstModule(reexport_module_spec); 661 if (!reexport_module_sp) { 662 reexport_module_spec.GetPlatformFileSpec().GetDirectory().Clear(); 663 reexport_module_sp = 664 target.GetImages().FindFirstModule(reexport_module_spec); 665 } 666 } 667 symbol_load_addr = GetSymbolAddress( 668 target, process, sym_ctx.symbol->GetReExportedSymbolName(), 669 symbol_type, reexport_module_sp.get()); 670 } 671 } break; 672 673 case eSymbolTypeData: 674 case eSymbolTypeRuntime: 675 case eSymbolTypeVariable: 676 case eSymbolTypeLocal: 677 case eSymbolTypeParam: 678 case eSymbolTypeInvalid: 679 case eSymbolTypeAbsolute: 680 case eSymbolTypeException: 681 case eSymbolTypeSourceFile: 682 case eSymbolTypeHeaderFile: 683 case eSymbolTypeObjectFile: 684 case eSymbolTypeCommonBlock: 685 case eSymbolTypeBlock: 686 case eSymbolTypeVariableType: 687 case eSymbolTypeLineEntry: 688 case eSymbolTypeLineHeader: 689 case eSymbolTypeScopeBegin: 690 case eSymbolTypeScopeEnd: 691 case eSymbolTypeAdditional: 692 case eSymbolTypeCompiler: 693 case eSymbolTypeInstrumentation: 694 case eSymbolTypeUndefined: 695 case eSymbolTypeObjCClass: 696 case eSymbolTypeObjCMetaClass: 697 case eSymbolTypeObjCIVar: 698 symbol_load_addr = sym_address.GetLoadAddress(&target); 699 break; 700 } 701 } 702 703 if (symbol_load_addr == LLDB_INVALID_ADDRESS && process) { 704 ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process); 705 706 if (runtime) { 707 symbol_load_addr = runtime->LookupRuntimeSymbol(name); 708 } 709 } 710 711 return symbol_load_addr; 712 } 713 714 addr_t ClangExpressionDeclMap::GetSymbolAddress(ConstString name, 715 lldb::SymbolType symbol_type) { 716 assert(m_parser_vars.get()); 717 718 if (!m_parser_vars->m_exe_ctx.GetTargetPtr()) 719 return false; 720 721 return GetSymbolAddress(m_parser_vars->m_exe_ctx.GetTargetRef(), 722 m_parser_vars->m_exe_ctx.GetProcessPtr(), name, 723 symbol_type); 724 } 725 726 lldb::VariableSP ClangExpressionDeclMap::FindGlobalVariable( 727 Target &target, ModuleSP &module, ConstString name, 728 CompilerDeclContext *namespace_decl, TypeFromUser *type) { 729 VariableList vars; 730 731 if (module && namespace_decl) 732 module->FindGlobalVariables(name, namespace_decl, -1, vars); 733 else 734 target.GetImages().FindGlobalVariables(name, -1, vars); 735 736 if (vars.GetSize()) { 737 if (type) { 738 for (size_t i = 0; i < vars.GetSize(); ++i) { 739 VariableSP var_sp = vars.GetVariableAtIndex(i); 740 741 if (ClangASTContext::AreTypesSame( 742 *type, var_sp->GetType()->GetFullCompilerType())) 743 return var_sp; 744 } 745 } else { 746 return vars.GetVariableAtIndex(0); 747 } 748 } 749 750 return VariableSP(); 751 } 752 753 ClangASTContext *ClangExpressionDeclMap::GetClangASTContext() { 754 StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr(); 755 if (frame == nullptr) 756 return nullptr; 757 758 SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction | 759 lldb::eSymbolContextBlock); 760 if (sym_ctx.block == nullptr) 761 return nullptr; 762 763 CompilerDeclContext frame_decl_context = sym_ctx.block->GetDeclContext(); 764 if (!frame_decl_context) 765 return nullptr; 766 767 return llvm::dyn_cast_or_null<ClangASTContext>( 768 frame_decl_context.GetTypeSystem()); 769 } 770 771 // Interface for ClangASTSource 772 773 void ClangExpressionDeclMap::FindExternalVisibleDecls( 774 NameSearchContext &context) { 775 assert(m_ast_context); 776 777 ClangASTMetrics::RegisterVisibleQuery(); 778 779 const ConstString name(context.m_decl_name.getAsString().c_str()); 780 781 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 782 783 if (GetImportInProgress()) { 784 if (log && log->GetVerbose()) 785 LLDB_LOGF(log, "Ignoring a query during an import"); 786 return; 787 } 788 789 static unsigned int invocation_id = 0; 790 unsigned int current_id = invocation_id++; 791 792 if (log) { 793 if (!context.m_decl_context) 794 LLDB_LOGF(log, 795 "ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for " 796 "'%s' in a NULL DeclContext", 797 current_id, name.GetCString()); 798 else if (const NamedDecl *context_named_decl = 799 dyn_cast<NamedDecl>(context.m_decl_context)) 800 LLDB_LOGF(log, 801 "ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for " 802 "'%s' in '%s'", 803 current_id, name.GetCString(), 804 context_named_decl->getNameAsString().c_str()); 805 else 806 LLDB_LOGF(log, 807 "ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for " 808 "'%s' in a '%s'", 809 current_id, name.GetCString(), 810 context.m_decl_context->getDeclKindName()); 811 } 812 813 if (const NamespaceDecl *namespace_context = 814 dyn_cast<NamespaceDecl>(context.m_decl_context)) { 815 if (namespace_context->getName().str() == 816 std::string(g_lldb_local_vars_namespace_cstr)) { 817 CompilerDeclContext compiler_decl_ctx( 818 GetClangASTContext(), const_cast<void *>(static_cast<const void *>( 819 context.m_decl_context))); 820 FindExternalVisibleDecls(context, lldb::ModuleSP(), compiler_decl_ctx, 821 current_id); 822 return; 823 } 824 825 ClangASTImporter::NamespaceMapSP namespace_map = 826 m_ast_importer_sp 827 ? m_ast_importer_sp->GetNamespaceMap(namespace_context) 828 : ClangASTImporter::NamespaceMapSP(); 829 830 if (!namespace_map) 831 return; 832 833 if (log && log->GetVerbose()) 834 log->Printf(" CEDM::FEVD[%u] Inspecting (NamespaceMap*)%p (%d entries)", 835 current_id, static_cast<void *>(namespace_map.get()), 836 (int)namespace_map->size()); 837 838 for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(), 839 e = namespace_map->end(); 840 i != e; ++i) { 841 if (log) 842 log->Printf(" CEDM::FEVD[%u] Searching namespace %s in module %s", 843 current_id, i->second.GetName().AsCString(), 844 i->first->GetFileSpec().GetFilename().GetCString()); 845 846 FindExternalVisibleDecls(context, i->first, i->second, current_id); 847 } 848 } else if (isa<TranslationUnitDecl>(context.m_decl_context)) { 849 CompilerDeclContext namespace_decl; 850 851 if (log) 852 log->Printf(" CEDM::FEVD[%u] Searching the root namespace", current_id); 853 854 FindExternalVisibleDecls(context, lldb::ModuleSP(), namespace_decl, 855 current_id); 856 } 857 858 ClangASTSource::FindExternalVisibleDecls(context); 859 } 860 861 void ClangExpressionDeclMap::FindExternalVisibleDecls( 862 NameSearchContext &context, lldb::ModuleSP module_sp, 863 CompilerDeclContext &namespace_decl, unsigned int current_id) { 864 assert(m_ast_context); 865 866 std::function<void(clang::FunctionDecl *)> MaybeRegisterFunctionBody = 867 [this](clang::FunctionDecl *copied_function_decl) { 868 if (copied_function_decl->getBody() && m_parser_vars->m_code_gen) { 869 DeclGroupRef decl_group_ref(copied_function_decl); 870 m_parser_vars->m_code_gen->HandleTopLevelDecl(decl_group_ref); 871 } 872 }; 873 874 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 875 876 SymbolContextList sc_list; 877 878 const ConstString name(context.m_decl_name.getAsString().c_str()); 879 if (IgnoreName(name, false)) 880 return; 881 882 // Only look for functions by name out in our symbols if the function doesn't 883 // start with our phony prefix of '$' 884 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr(); 885 StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr(); 886 SymbolContext sym_ctx; 887 if (frame != nullptr) 888 sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction | 889 lldb::eSymbolContextBlock); 890 891 // Try the persistent decls, which take precedence over all else. 892 if (!namespace_decl) { 893 do { 894 if (!target) 895 break; 896 897 ClangASTContext *scratch_clang_ast_context = 898 target->GetScratchClangASTContext(); 899 900 if (!scratch_clang_ast_context) 901 break; 902 903 ASTContext *scratch_ast_context = 904 scratch_clang_ast_context->getASTContext(); 905 906 if (!scratch_ast_context) 907 break; 908 909 NamedDecl *persistent_decl = 910 m_parser_vars->m_persistent_vars->GetPersistentDecl(name); 911 912 if (!persistent_decl) 913 break; 914 915 Decl *parser_persistent_decl = CopyDecl(persistent_decl); 916 917 if (!parser_persistent_decl) 918 break; 919 920 NamedDecl *parser_named_decl = 921 dyn_cast<NamedDecl>(parser_persistent_decl); 922 923 if (!parser_named_decl) 924 break; 925 926 if (clang::FunctionDecl *parser_function_decl = 927 llvm::dyn_cast<clang::FunctionDecl>(parser_named_decl)) { 928 MaybeRegisterFunctionBody(parser_function_decl); 929 } 930 931 LLDB_LOGF(log, " CEDM::FEVD[%u] Found persistent decl %s", current_id, 932 name.GetCString()); 933 934 context.AddNamedDecl(parser_named_decl); 935 } while (false); 936 } 937 938 if (name.GetCString()[0] == '$' && !namespace_decl) { 939 static ConstString g_lldb_class_name("$__lldb_class"); 940 941 if (name == g_lldb_class_name) { 942 if (m_ctx_obj) { 943 Status status; 944 lldb::ValueObjectSP ctx_obj_ptr = m_ctx_obj->AddressOf(status); 945 if (!ctx_obj_ptr || status.Fail()) 946 return; 947 948 AddThisType(context, TypeFromUser(m_ctx_obj->GetCompilerType()), 949 current_id); 950 951 m_struct_vars->m_object_pointer_type = 952 TypeFromUser(ctx_obj_ptr->GetCompilerType()); 953 954 return; 955 } 956 957 // Clang is looking for the type of "this" 958 959 if (frame == nullptr) 960 return; 961 962 // Find the block that defines the function represented by "sym_ctx" 963 Block *function_block = sym_ctx.GetFunctionBlock(); 964 965 if (!function_block) 966 return; 967 968 CompilerDeclContext function_decl_ctx = function_block->GetDeclContext(); 969 970 if (!function_decl_ctx) 971 return; 972 973 clang::CXXMethodDecl *method_decl = 974 ClangASTContext::DeclContextGetAsCXXMethodDecl(function_decl_ctx); 975 976 if (method_decl) { 977 clang::CXXRecordDecl *class_decl = method_decl->getParent(); 978 979 QualType class_qual_type(class_decl->getTypeForDecl(), 0); 980 981 TypeFromUser class_user_type( 982 class_qual_type.getAsOpaquePtr(), 983 ClangASTContext::GetASTContext(&class_decl->getASTContext())); 984 985 if (log) { 986 ASTDumper ast_dumper(class_qual_type); 987 LLDB_LOGF(log, " CEDM::FEVD[%u] Adding type for $__lldb_class: %s", 988 current_id, ast_dumper.GetCString()); 989 } 990 991 AddThisType(context, class_user_type, current_id); 992 993 if (method_decl->isInstance()) { 994 // self is a pointer to the object 995 996 QualType class_pointer_type = 997 method_decl->getASTContext().getPointerType(class_qual_type); 998 999 TypeFromUser self_user_type( 1000 class_pointer_type.getAsOpaquePtr(), 1001 ClangASTContext::GetASTContext(&method_decl->getASTContext())); 1002 1003 m_struct_vars->m_object_pointer_type = self_user_type; 1004 } 1005 } else { 1006 // This branch will get hit if we are executing code in the context of 1007 // a function that claims to have an object pointer (through 1008 // DW_AT_object_pointer?) but is not formally a method of the class. 1009 // In that case, just look up the "this" variable in the current scope 1010 // and use its type. 1011 // FIXME: This code is formally correct, but clang doesn't currently 1012 // emit DW_AT_object_pointer 1013 // for C++ so it hasn't actually been tested. 1014 1015 VariableList *vars = frame->GetVariableList(false); 1016 1017 lldb::VariableSP this_var = vars->FindVariable(ConstString("this")); 1018 1019 if (this_var && this_var->IsInScope(frame) && 1020 this_var->LocationIsValidForFrame(frame)) { 1021 Type *this_type = this_var->GetType(); 1022 1023 if (!this_type) 1024 return; 1025 1026 TypeFromUser pointee_type = 1027 this_type->GetForwardCompilerType().GetPointeeType(); 1028 1029 if (pointee_type.IsValid()) { 1030 if (log) { 1031 ASTDumper ast_dumper(pointee_type); 1032 LLDB_LOGF(log, " FEVD[%u] Adding type for $__lldb_class: %s", 1033 current_id, ast_dumper.GetCString()); 1034 } 1035 1036 AddThisType(context, pointee_type, current_id); 1037 TypeFromUser this_user_type(this_type->GetFullCompilerType()); 1038 m_struct_vars->m_object_pointer_type = this_user_type; 1039 return; 1040 } 1041 } 1042 } 1043 1044 return; 1045 } 1046 1047 static ConstString g_lldb_objc_class_name("$__lldb_objc_class"); 1048 if (name == g_lldb_objc_class_name) { 1049 if (m_ctx_obj) { 1050 Status status; 1051 lldb::ValueObjectSP ctx_obj_ptr = m_ctx_obj->AddressOf(status); 1052 if (!ctx_obj_ptr || status.Fail()) 1053 return; 1054 1055 AddOneType(context, TypeFromUser(m_ctx_obj->GetCompilerType()), 1056 current_id); 1057 1058 m_struct_vars->m_object_pointer_type = 1059 TypeFromUser(ctx_obj_ptr->GetCompilerType()); 1060 1061 return; 1062 } 1063 1064 // Clang is looking for the type of "*self" 1065 1066 if (!frame) 1067 return; 1068 1069 SymbolContext sym_ctx = frame->GetSymbolContext( 1070 lldb::eSymbolContextFunction | lldb::eSymbolContextBlock); 1071 1072 // Find the block that defines the function represented by "sym_ctx" 1073 Block *function_block = sym_ctx.GetFunctionBlock(); 1074 1075 if (!function_block) 1076 return; 1077 1078 CompilerDeclContext function_decl_ctx = function_block->GetDeclContext(); 1079 1080 if (!function_decl_ctx) 1081 return; 1082 1083 clang::ObjCMethodDecl *method_decl = 1084 ClangASTContext::DeclContextGetAsObjCMethodDecl(function_decl_ctx); 1085 1086 if (method_decl) { 1087 ObjCInterfaceDecl *self_interface = method_decl->getClassInterface(); 1088 1089 if (!self_interface) 1090 return; 1091 1092 const clang::Type *interface_type = self_interface->getTypeForDecl(); 1093 1094 if (!interface_type) 1095 return; // This is unlikely, but we have seen crashes where this 1096 // occurred 1097 1098 TypeFromUser class_user_type( 1099 QualType(interface_type, 0).getAsOpaquePtr(), 1100 ClangASTContext::GetASTContext(&method_decl->getASTContext())); 1101 1102 if (log) { 1103 ASTDumper ast_dumper(interface_type); 1104 LLDB_LOGF(log, " FEVD[%u] Adding type for $__lldb_objc_class: %s", 1105 current_id, ast_dumper.GetCString()); 1106 } 1107 1108 AddOneType(context, class_user_type, current_id); 1109 1110 if (method_decl->isInstanceMethod()) { 1111 // self is a pointer to the object 1112 1113 QualType class_pointer_type = 1114 method_decl->getASTContext().getObjCObjectPointerType( 1115 QualType(interface_type, 0)); 1116 1117 TypeFromUser self_user_type( 1118 class_pointer_type.getAsOpaquePtr(), 1119 ClangASTContext::GetASTContext(&method_decl->getASTContext())); 1120 1121 m_struct_vars->m_object_pointer_type = self_user_type; 1122 } else { 1123 // self is a Class pointer 1124 QualType class_type = method_decl->getASTContext().getObjCClassType(); 1125 1126 TypeFromUser self_user_type( 1127 class_type.getAsOpaquePtr(), 1128 ClangASTContext::GetASTContext(&method_decl->getASTContext())); 1129 1130 m_struct_vars->m_object_pointer_type = self_user_type; 1131 } 1132 1133 return; 1134 } else { 1135 // This branch will get hit if we are executing code in the context of 1136 // a function that claims to have an object pointer (through 1137 // DW_AT_object_pointer?) but is not formally a method of the class. 1138 // In that case, just look up the "self" variable in the current scope 1139 // and use its type. 1140 1141 VariableList *vars = frame->GetVariableList(false); 1142 1143 lldb::VariableSP self_var = vars->FindVariable(ConstString("self")); 1144 1145 if (self_var && self_var->IsInScope(frame) && 1146 self_var->LocationIsValidForFrame(frame)) { 1147 Type *self_type = self_var->GetType(); 1148 1149 if (!self_type) 1150 return; 1151 1152 CompilerType self_clang_type = self_type->GetFullCompilerType(); 1153 1154 if (ClangASTContext::IsObjCClassType(self_clang_type)) { 1155 return; 1156 } else if (ClangASTContext::IsObjCObjectPointerType( 1157 self_clang_type)) { 1158 self_clang_type = self_clang_type.GetPointeeType(); 1159 1160 if (!self_clang_type) 1161 return; 1162 1163 if (log) { 1164 ASTDumper ast_dumper(self_type->GetFullCompilerType()); 1165 LLDB_LOGF(log, 1166 " FEVD[%u] Adding type for $__lldb_objc_class: %s", 1167 current_id, ast_dumper.GetCString()); 1168 } 1169 1170 TypeFromUser class_user_type(self_clang_type); 1171 1172 AddOneType(context, class_user_type, current_id); 1173 1174 TypeFromUser self_user_type(self_type->GetFullCompilerType()); 1175 1176 m_struct_vars->m_object_pointer_type = self_user_type; 1177 return; 1178 } 1179 } 1180 } 1181 1182 return; 1183 } 1184 1185 if (name == ConstString(g_lldb_local_vars_namespace_cstr)) { 1186 CompilerDeclContext frame_decl_context = 1187 sym_ctx.block != nullptr ? sym_ctx.block->GetDeclContext() 1188 : CompilerDeclContext(); 1189 1190 if (frame_decl_context) { 1191 ClangASTContext *ast = llvm::dyn_cast_or_null<ClangASTContext>( 1192 frame_decl_context.GetTypeSystem()); 1193 1194 if (ast) { 1195 clang::NamespaceDecl *namespace_decl = 1196 ClangASTContext::GetUniqueNamespaceDeclaration( 1197 m_ast_context, name.GetCString(), nullptr); 1198 if (namespace_decl) { 1199 context.AddNamedDecl(namespace_decl); 1200 clang::DeclContext *clang_decl_ctx = 1201 clang::Decl::castToDeclContext(namespace_decl); 1202 clang_decl_ctx->setHasExternalVisibleStorage(true); 1203 context.m_found.local_vars_nsp = true; 1204 } 1205 } 1206 } 1207 1208 return; 1209 } 1210 1211 // any other $__lldb names should be weeded out now 1212 if (name.GetStringRef().startswith("$__lldb")) 1213 return; 1214 1215 ExpressionVariableSP pvar_sp( 1216 m_parser_vars->m_persistent_vars->GetVariable(name)); 1217 1218 if (pvar_sp) { 1219 AddOneVariable(context, pvar_sp, current_id); 1220 return; 1221 } 1222 1223 const char *reg_name(&name.GetCString()[1]); 1224 1225 if (m_parser_vars->m_exe_ctx.GetRegisterContext()) { 1226 const RegisterInfo *reg_info( 1227 m_parser_vars->m_exe_ctx.GetRegisterContext()->GetRegisterInfoByName( 1228 reg_name)); 1229 1230 if (reg_info) { 1231 LLDB_LOGF(log, " CEDM::FEVD[%u] Found register %s", current_id, 1232 reg_info->name); 1233 1234 AddOneRegister(context, reg_info, current_id); 1235 } 1236 } 1237 } else { 1238 ValueObjectSP valobj; 1239 VariableSP var; 1240 1241 bool local_var_lookup = 1242 !namespace_decl || (namespace_decl.GetName() == 1243 ConstString(g_lldb_local_vars_namespace_cstr)); 1244 if (frame && local_var_lookup) { 1245 CompilerDeclContext compiler_decl_context = 1246 sym_ctx.block != nullptr ? sym_ctx.block->GetDeclContext() 1247 : CompilerDeclContext(); 1248 1249 if (compiler_decl_context) { 1250 // Make sure that the variables are parsed so that we have the 1251 // declarations. 1252 VariableListSP vars = frame->GetInScopeVariableList(true); 1253 for (size_t i = 0; i < vars->GetSize(); i++) 1254 vars->GetVariableAtIndex(i)->GetDecl(); 1255 1256 // Search for declarations matching the name. Do not include imported 1257 // decls in the search if we are looking for decls in the artificial 1258 // namespace $__lldb_local_vars. 1259 std::vector<CompilerDecl> found_decls = 1260 compiler_decl_context.FindDeclByName(name, 1261 namespace_decl.IsValid()); 1262 1263 bool variable_found = false; 1264 for (CompilerDecl decl : found_decls) { 1265 for (size_t vi = 0, ve = vars->GetSize(); vi != ve; ++vi) { 1266 VariableSP candidate_var = vars->GetVariableAtIndex(vi); 1267 if (candidate_var->GetDecl() == decl) { 1268 var = candidate_var; 1269 break; 1270 } 1271 } 1272 1273 if (var && !variable_found) { 1274 variable_found = true; 1275 valobj = ValueObjectVariable::Create(frame, var); 1276 AddOneVariable(context, var, valobj, current_id); 1277 context.m_found.variable = true; 1278 } 1279 } 1280 if (variable_found) 1281 return; 1282 } 1283 } 1284 if (target) { 1285 var = FindGlobalVariable(*target, module_sp, name, &namespace_decl, 1286 nullptr); 1287 1288 if (var) { 1289 valobj = ValueObjectVariable::Create(target, var); 1290 AddOneVariable(context, var, valobj, current_id); 1291 context.m_found.variable = true; 1292 return; 1293 } 1294 } 1295 1296 std::vector<clang::NamedDecl *> decls_from_modules; 1297 1298 if (target) { 1299 if (ClangModulesDeclVendor *decl_vendor = 1300 target->GetClangModulesDeclVendor()) { 1301 decl_vendor->FindDecls(name, false, UINT32_MAX, decls_from_modules); 1302 } 1303 } 1304 1305 const bool include_inlines = false; 1306 const bool append = false; 1307 1308 if (namespace_decl && module_sp) { 1309 const bool include_symbols = false; 1310 1311 module_sp->FindFunctions(name, &namespace_decl, eFunctionNameTypeBase, 1312 include_symbols, include_inlines, append, 1313 sc_list); 1314 } else if (target && !namespace_decl) { 1315 const bool include_symbols = true; 1316 1317 // TODO Fix FindFunctions so that it doesn't return 1318 // instance methods for eFunctionNameTypeBase. 1319 1320 target->GetImages().FindFunctions(name, eFunctionNameTypeFull, 1321 include_symbols, include_inlines, 1322 append, sc_list); 1323 } 1324 1325 // If we found more than one function, see if we can use the frame's decl 1326 // context to remove functions that are shadowed by other functions which 1327 // match in type but are nearer in scope. 1328 // 1329 // AddOneFunction will not add a function whose type has already been 1330 // added, so if there's another function in the list with a matching type, 1331 // check to see if their decl context is a parent of the current frame's or 1332 // was imported via a and using statement, and pick the best match 1333 // according to lookup rules. 1334 if (sc_list.GetSize() > 1) { 1335 // Collect some info about our frame's context. 1336 StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr(); 1337 SymbolContext frame_sym_ctx; 1338 if (frame != nullptr) 1339 frame_sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction | 1340 lldb::eSymbolContextBlock); 1341 CompilerDeclContext frame_decl_context = 1342 frame_sym_ctx.block != nullptr ? frame_sym_ctx.block->GetDeclContext() 1343 : CompilerDeclContext(); 1344 1345 // We can't do this without a compiler decl context for our frame. 1346 if (frame_decl_context) { 1347 clang::DeclContext *frame_decl_ctx = 1348 (clang::DeclContext *)frame_decl_context.GetOpaqueDeclContext(); 1349 ClangASTContext *ast = llvm::dyn_cast_or_null<ClangASTContext>( 1350 frame_decl_context.GetTypeSystem()); 1351 1352 // Structure to hold the info needed when comparing function 1353 // declarations. 1354 struct FuncDeclInfo { 1355 ConstString m_name; 1356 CompilerType m_copied_type; 1357 uint32_t m_decl_lvl; 1358 SymbolContext m_sym_ctx; 1359 }; 1360 1361 // First, symplify things by looping through the symbol contexts to 1362 // remove unwanted functions and separate out the functions we want to 1363 // compare and prune into a separate list. Cache the info needed about 1364 // the function declarations in a vector for efficiency. 1365 SymbolContextList sc_sym_list; 1366 uint32_t num_indices = sc_list.GetSize(); 1367 std::vector<FuncDeclInfo> fdi_cache; 1368 fdi_cache.reserve(num_indices); 1369 for (uint32_t index = 0; index < num_indices; ++index) { 1370 FuncDeclInfo fdi; 1371 SymbolContext sym_ctx; 1372 sc_list.GetContextAtIndex(index, sym_ctx); 1373 1374 // We don't know enough about symbols to compare them, but we should 1375 // keep them in the list. 1376 Function *function = sym_ctx.function; 1377 if (!function) { 1378 sc_sym_list.Append(sym_ctx); 1379 continue; 1380 } 1381 // Filter out functions without declaration contexts, as well as 1382 // class/instance methods, since they'll be skipped in the code that 1383 // follows anyway. 1384 CompilerDeclContext func_decl_context = function->GetDeclContext(); 1385 if (!func_decl_context || 1386 func_decl_context.IsClassMethod(nullptr, nullptr, nullptr)) 1387 continue; 1388 // We can only prune functions for which we can copy the type. 1389 CompilerType func_clang_type = 1390 function->GetType()->GetFullCompilerType(); 1391 CompilerType copied_func_type = GuardedCopyType(func_clang_type); 1392 if (!copied_func_type) { 1393 sc_sym_list.Append(sym_ctx); 1394 continue; 1395 } 1396 1397 fdi.m_sym_ctx = sym_ctx; 1398 fdi.m_name = function->GetName(); 1399 fdi.m_copied_type = copied_func_type; 1400 fdi.m_decl_lvl = LLDB_INVALID_DECL_LEVEL; 1401 if (fdi.m_copied_type && func_decl_context) { 1402 // Call CountDeclLevels to get the number of parent scopes we have 1403 // to look through before we find the function declaration. When 1404 // comparing functions of the same type, the one with a lower count 1405 // will be closer to us in the lookup scope and shadows the other. 1406 clang::DeclContext *func_decl_ctx = 1407 (clang::DeclContext *)func_decl_context.GetOpaqueDeclContext(); 1408 fdi.m_decl_lvl = ast->CountDeclLevels( 1409 frame_decl_ctx, func_decl_ctx, &fdi.m_name, &fdi.m_copied_type); 1410 } 1411 fdi_cache.emplace_back(fdi); 1412 } 1413 1414 // Loop through the functions in our cache looking for matching types, 1415 // then compare their scope levels to see which is closer. 1416 std::multimap<CompilerType, const FuncDeclInfo *> matches; 1417 for (const FuncDeclInfo &fdi : fdi_cache) { 1418 const CompilerType t = fdi.m_copied_type; 1419 auto q = matches.find(t); 1420 if (q != matches.end()) { 1421 if (q->second->m_decl_lvl > fdi.m_decl_lvl) 1422 // This function is closer; remove the old set. 1423 matches.erase(t); 1424 else if (q->second->m_decl_lvl < fdi.m_decl_lvl) 1425 // The functions in our set are closer - skip this one. 1426 continue; 1427 } 1428 matches.insert(std::make_pair(t, &fdi)); 1429 } 1430 1431 // Loop through our matches and add their symbol contexts to our list. 1432 SymbolContextList sc_func_list; 1433 for (const auto &q : matches) 1434 sc_func_list.Append(q.second->m_sym_ctx); 1435 1436 // Rejoin the lists with the functions in front. 1437 sc_list = sc_func_list; 1438 sc_list.Append(sc_sym_list); 1439 } 1440 } 1441 1442 if (sc_list.GetSize()) { 1443 Symbol *extern_symbol = nullptr; 1444 Symbol *non_extern_symbol = nullptr; 1445 1446 for (uint32_t index = 0, num_indices = sc_list.GetSize(); 1447 index < num_indices; ++index) { 1448 SymbolContext sym_ctx; 1449 sc_list.GetContextAtIndex(index, sym_ctx); 1450 1451 if (sym_ctx.function) { 1452 CompilerDeclContext decl_ctx = sym_ctx.function->GetDeclContext(); 1453 1454 if (!decl_ctx) 1455 continue; 1456 1457 // Filter out class/instance methods. 1458 if (decl_ctx.IsClassMethod(nullptr, nullptr, nullptr)) 1459 continue; 1460 1461 AddOneFunction(context, sym_ctx.function, nullptr, current_id); 1462 context.m_found.function_with_type_info = true; 1463 context.m_found.function = true; 1464 } else if (sym_ctx.symbol) { 1465 if (sym_ctx.symbol->GetType() == eSymbolTypeReExported && target) { 1466 sym_ctx.symbol = sym_ctx.symbol->ResolveReExportedSymbol(*target); 1467 if (sym_ctx.symbol == nullptr) 1468 continue; 1469 } 1470 1471 if (sym_ctx.symbol->IsExternal()) 1472 extern_symbol = sym_ctx.symbol; 1473 else 1474 non_extern_symbol = sym_ctx.symbol; 1475 } 1476 } 1477 1478 if (!context.m_found.function_with_type_info) { 1479 for (clang::NamedDecl *decl : decls_from_modules) { 1480 if (llvm::isa<clang::FunctionDecl>(decl)) { 1481 clang::NamedDecl *copied_decl = 1482 llvm::cast_or_null<FunctionDecl>(CopyDecl(decl)); 1483 if (copied_decl) { 1484 context.AddNamedDecl(copied_decl); 1485 context.m_found.function_with_type_info = true; 1486 } 1487 } 1488 } 1489 } 1490 1491 if (!context.m_found.function_with_type_info) { 1492 if (extern_symbol) { 1493 AddOneFunction(context, nullptr, extern_symbol, current_id); 1494 context.m_found.function = true; 1495 } else if (non_extern_symbol) { 1496 AddOneFunction(context, nullptr, non_extern_symbol, current_id); 1497 context.m_found.function = true; 1498 } 1499 } 1500 } 1501 1502 if (!context.m_found.function_with_type_info) { 1503 // Try the modules next. 1504 1505 do { 1506 if (ClangModulesDeclVendor *modules_decl_vendor = 1507 m_target->GetClangModulesDeclVendor()) { 1508 bool append = false; 1509 uint32_t max_matches = 1; 1510 std::vector<clang::NamedDecl *> decls; 1511 1512 if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls)) 1513 break; 1514 1515 clang::NamedDecl *const decl_from_modules = decls[0]; 1516 1517 if (llvm::isa<clang::FunctionDecl>(decl_from_modules)) { 1518 if (log) { 1519 LLDB_LOGF(log, 1520 " CAS::FEVD[%u] Matching function found for " 1521 "\"%s\" in the modules", 1522 current_id, name.GetCString()); 1523 } 1524 1525 clang::Decl *copied_decl = CopyDecl(decl_from_modules); 1526 clang::FunctionDecl *copied_function_decl = 1527 copied_decl ? dyn_cast<clang::FunctionDecl>(copied_decl) 1528 : nullptr; 1529 1530 if (!copied_function_decl) { 1531 LLDB_LOGF(log, 1532 " CAS::FEVD[%u] - Couldn't export a function " 1533 "declaration from the modules", 1534 current_id); 1535 1536 break; 1537 } 1538 1539 MaybeRegisterFunctionBody(copied_function_decl); 1540 1541 context.AddNamedDecl(copied_function_decl); 1542 1543 context.m_found.function_with_type_info = true; 1544 context.m_found.function = true; 1545 } else if (llvm::isa<clang::VarDecl>(decl_from_modules)) { 1546 if (log) { 1547 LLDB_LOGF(log, 1548 " CAS::FEVD[%u] Matching variable found for " 1549 "\"%s\" in the modules", 1550 current_id, name.GetCString()); 1551 } 1552 1553 clang::Decl *copied_decl = CopyDecl(decl_from_modules); 1554 clang::VarDecl *copied_var_decl = 1555 copied_decl ? dyn_cast_or_null<clang::VarDecl>(copied_decl) 1556 : nullptr; 1557 1558 if (!copied_var_decl) { 1559 LLDB_LOGF(log, 1560 " CAS::FEVD[%u] - Couldn't export a variable " 1561 "declaration from the modules", 1562 current_id); 1563 1564 break; 1565 } 1566 1567 context.AddNamedDecl(copied_var_decl); 1568 1569 context.m_found.variable = true; 1570 } 1571 } 1572 } while (false); 1573 } 1574 1575 if (target && !context.m_found.variable && !namespace_decl) { 1576 // We couldn't find a non-symbol variable for this. Now we'll hunt for a 1577 // generic data symbol, and -- if it is found -- treat it as a variable. 1578 Status error; 1579 1580 const Symbol *data_symbol = 1581 m_parser_vars->m_sym_ctx.FindBestGlobalDataSymbol(name, error); 1582 1583 if (!error.Success()) { 1584 const unsigned diag_id = 1585 m_ast_context->getDiagnostics().getCustomDiagID( 1586 clang::DiagnosticsEngine::Level::Error, "%0"); 1587 m_ast_context->getDiagnostics().Report(diag_id) << error.AsCString(); 1588 } 1589 1590 if (data_symbol) { 1591 std::string warning("got name from symbols: "); 1592 warning.append(name.AsCString()); 1593 const unsigned diag_id = 1594 m_ast_context->getDiagnostics().getCustomDiagID( 1595 clang::DiagnosticsEngine::Level::Warning, "%0"); 1596 m_ast_context->getDiagnostics().Report(diag_id) << warning.c_str(); 1597 AddOneGenericVariable(context, *data_symbol, current_id); 1598 context.m_found.variable = true; 1599 } 1600 } 1601 } 1602 } 1603 1604 bool ClangExpressionDeclMap::GetVariableValue(VariableSP &var, 1605 lldb_private::Value &var_location, 1606 TypeFromUser *user_type, 1607 TypeFromParser *parser_type) { 1608 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1609 1610 Type *var_type = var->GetType(); 1611 1612 if (!var_type) { 1613 if (log) 1614 log->PutCString("Skipped a definition because it has no type"); 1615 return false; 1616 } 1617 1618 CompilerType var_clang_type = var_type->GetFullCompilerType(); 1619 1620 if (!var_clang_type) { 1621 if (log) 1622 log->PutCString("Skipped a definition because it has no Clang type"); 1623 return false; 1624 } 1625 1626 ClangASTContext *clang_ast = llvm::dyn_cast_or_null<ClangASTContext>( 1627 var_type->GetForwardCompilerType().GetTypeSystem()); 1628 1629 if (!clang_ast) { 1630 if (log) 1631 log->PutCString("Skipped a definition because it has no Clang AST"); 1632 return false; 1633 } 1634 1635 ASTContext *ast = clang_ast->getASTContext(); 1636 1637 if (!ast) { 1638 if (log) 1639 log->PutCString( 1640 "There is no AST context for the current execution context"); 1641 return false; 1642 } 1643 1644 DWARFExpression &var_location_expr = var->LocationExpression(); 1645 1646 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr(); 1647 Status err; 1648 1649 if (var->GetLocationIsConstantValueData()) { 1650 DataExtractor const_value_extractor; 1651 1652 if (var_location_expr.GetExpressionData(const_value_extractor)) { 1653 var_location = Value(const_value_extractor.GetDataStart(), 1654 const_value_extractor.GetByteSize()); 1655 var_location.SetValueType(Value::eValueTypeHostAddress); 1656 } else { 1657 LLDB_LOGF(log, "Error evaluating constant variable: %s", err.AsCString()); 1658 return false; 1659 } 1660 } 1661 1662 CompilerType type_to_use = GuardedCopyType(var_clang_type); 1663 1664 if (!type_to_use) { 1665 LLDB_LOGF(log, 1666 "Couldn't copy a variable's type into the parser's AST context"); 1667 1668 return false; 1669 } 1670 1671 if (parser_type) 1672 *parser_type = TypeFromParser(type_to_use); 1673 1674 if (var_location.GetContextType() == Value::eContextTypeInvalid) 1675 var_location.SetCompilerType(type_to_use); 1676 1677 if (var_location.GetValueType() == Value::eValueTypeFileAddress) { 1678 SymbolContext var_sc; 1679 var->CalculateSymbolContext(&var_sc); 1680 1681 if (!var_sc.module_sp) 1682 return false; 1683 1684 Address so_addr(var_location.GetScalar().ULongLong(), 1685 var_sc.module_sp->GetSectionList()); 1686 1687 lldb::addr_t load_addr = so_addr.GetLoadAddress(target); 1688 1689 if (load_addr != LLDB_INVALID_ADDRESS) { 1690 var_location.GetScalar() = load_addr; 1691 var_location.SetValueType(Value::eValueTypeLoadAddress); 1692 } 1693 } 1694 1695 if (user_type) 1696 *user_type = TypeFromUser(var_clang_type); 1697 1698 return true; 1699 } 1700 1701 void ClangExpressionDeclMap::AddOneVariable(NameSearchContext &context, 1702 VariableSP var, 1703 ValueObjectSP valobj, 1704 unsigned int current_id) { 1705 assert(m_parser_vars.get()); 1706 1707 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1708 1709 TypeFromUser ut; 1710 TypeFromParser pt; 1711 Value var_location; 1712 1713 if (!GetVariableValue(var, var_location, &ut, &pt)) 1714 return; 1715 1716 clang::QualType parser_opaque_type = 1717 QualType::getFromOpaquePtr(pt.GetOpaqueQualType()); 1718 1719 if (parser_opaque_type.isNull()) 1720 return; 1721 1722 if (const clang::Type *parser_type = parser_opaque_type.getTypePtr()) { 1723 if (const TagType *tag_type = dyn_cast<TagType>(parser_type)) 1724 CompleteType(tag_type->getDecl()); 1725 if (const ObjCObjectPointerType *objc_object_ptr_type = 1726 dyn_cast<ObjCObjectPointerType>(parser_type)) 1727 CompleteType(objc_object_ptr_type->getInterfaceDecl()); 1728 } 1729 1730 bool is_reference = pt.IsReferenceType(); 1731 1732 NamedDecl *var_decl = nullptr; 1733 if (is_reference) 1734 var_decl = context.AddVarDecl(pt); 1735 else 1736 var_decl = context.AddVarDecl(pt.GetLValueReferenceType()); 1737 1738 std::string decl_name(context.m_decl_name.getAsString()); 1739 ConstString entity_name(decl_name.c_str()); 1740 ClangExpressionVariable *entity(new ClangExpressionVariable(valobj)); 1741 m_found_entities.AddNewlyConstructedVariable(entity); 1742 1743 assert(entity); 1744 entity->EnableParserVars(GetParserID()); 1745 ClangExpressionVariable::ParserVars *parser_vars = 1746 entity->GetParserVars(GetParserID()); 1747 parser_vars->m_parser_type = pt; 1748 parser_vars->m_named_decl = var_decl; 1749 parser_vars->m_llvm_value = nullptr; 1750 parser_vars->m_lldb_value = var_location; 1751 parser_vars->m_lldb_var = var; 1752 1753 if (is_reference) 1754 entity->m_flags |= ClangExpressionVariable::EVTypeIsReference; 1755 1756 if (log) { 1757 ASTDumper orig_dumper(ut.GetOpaqueQualType()); 1758 ASTDumper ast_dumper(var_decl); 1759 LLDB_LOGF(log, 1760 " CEDM::FEVD[%u] Found variable %s, returned %s (original %s)", 1761 current_id, decl_name.c_str(), ast_dumper.GetCString(), 1762 orig_dumper.GetCString()); 1763 } 1764 } 1765 1766 void ClangExpressionDeclMap::AddOneVariable(NameSearchContext &context, 1767 ExpressionVariableSP &pvar_sp, 1768 unsigned int current_id) { 1769 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1770 1771 TypeFromUser user_type( 1772 llvm::cast<ClangExpressionVariable>(pvar_sp.get())->GetTypeFromUser()); 1773 1774 TypeFromParser parser_type(GuardedCopyType(user_type)); 1775 1776 if (!parser_type.GetOpaqueQualType()) { 1777 LLDB_LOGF(log, " CEDM::FEVD[%u] Couldn't import type for pvar %s", 1778 current_id, pvar_sp->GetName().GetCString()); 1779 return; 1780 } 1781 1782 NamedDecl *var_decl = 1783 context.AddVarDecl(parser_type.GetLValueReferenceType()); 1784 1785 llvm::cast<ClangExpressionVariable>(pvar_sp.get()) 1786 ->EnableParserVars(GetParserID()); 1787 ClangExpressionVariable::ParserVars *parser_vars = 1788 llvm::cast<ClangExpressionVariable>(pvar_sp.get()) 1789 ->GetParserVars(GetParserID()); 1790 parser_vars->m_parser_type = parser_type; 1791 parser_vars->m_named_decl = var_decl; 1792 parser_vars->m_llvm_value = nullptr; 1793 parser_vars->m_lldb_value.Clear(); 1794 1795 if (log) { 1796 ASTDumper ast_dumper(var_decl); 1797 LLDB_LOGF(log, " CEDM::FEVD[%u] Added pvar %s, returned %s", current_id, 1798 pvar_sp->GetName().GetCString(), ast_dumper.GetCString()); 1799 } 1800 } 1801 1802 void ClangExpressionDeclMap::AddOneGenericVariable(NameSearchContext &context, 1803 const Symbol &symbol, 1804 unsigned int current_id) { 1805 assert(m_parser_vars.get()); 1806 1807 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1808 1809 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr(); 1810 1811 if (target == nullptr) 1812 return; 1813 1814 ASTContext *scratch_ast_context = 1815 target->GetScratchClangASTContext()->getASTContext(); 1816 1817 TypeFromUser user_type( 1818 ClangASTContext::GetBasicType(scratch_ast_context, eBasicTypeVoid) 1819 .GetPointerType() 1820 .GetLValueReferenceType()); 1821 TypeFromParser parser_type( 1822 ClangASTContext::GetBasicType(m_ast_context, eBasicTypeVoid) 1823 .GetPointerType() 1824 .GetLValueReferenceType()); 1825 NamedDecl *var_decl = context.AddVarDecl(parser_type); 1826 1827 std::string decl_name(context.m_decl_name.getAsString()); 1828 ConstString entity_name(decl_name.c_str()); 1829 ClangExpressionVariable *entity(new ClangExpressionVariable( 1830 m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(), entity_name, 1831 user_type, m_parser_vars->m_target_info.byte_order, 1832 m_parser_vars->m_target_info.address_byte_size)); 1833 m_found_entities.AddNewlyConstructedVariable(entity); 1834 1835 entity->EnableParserVars(GetParserID()); 1836 ClangExpressionVariable::ParserVars *parser_vars = 1837 entity->GetParserVars(GetParserID()); 1838 1839 const Address symbol_address = symbol.GetAddress(); 1840 lldb::addr_t symbol_load_addr = symbol_address.GetLoadAddress(target); 1841 1842 // parser_vars->m_lldb_value.SetContext(Value::eContextTypeClangType, 1843 // user_type.GetOpaqueQualType()); 1844 parser_vars->m_lldb_value.SetCompilerType(user_type); 1845 parser_vars->m_lldb_value.GetScalar() = symbol_load_addr; 1846 parser_vars->m_lldb_value.SetValueType(Value::eValueTypeLoadAddress); 1847 1848 parser_vars->m_parser_type = parser_type; 1849 parser_vars->m_named_decl = var_decl; 1850 parser_vars->m_llvm_value = nullptr; 1851 parser_vars->m_lldb_sym = &symbol; 1852 1853 if (log) { 1854 ASTDumper ast_dumper(var_decl); 1855 1856 LLDB_LOGF(log, " CEDM::FEVD[%u] Found variable %s, returned %s", 1857 current_id, decl_name.c_str(), ast_dumper.GetCString()); 1858 } 1859 } 1860 1861 bool ClangExpressionDeclMap::ResolveUnknownTypes() { 1862 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1863 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr(); 1864 1865 ClangASTContextForExpressions *scratch_ast_context = 1866 static_cast<ClangASTContextForExpressions *>( 1867 target->GetScratchClangASTContext()); 1868 1869 for (size_t index = 0, num_entities = m_found_entities.GetSize(); 1870 index < num_entities; ++index) { 1871 ExpressionVariableSP entity = m_found_entities.GetVariableAtIndex(index); 1872 1873 ClangExpressionVariable::ParserVars *parser_vars = 1874 llvm::cast<ClangExpressionVariable>(entity.get()) 1875 ->GetParserVars(GetParserID()); 1876 1877 if (entity->m_flags & ClangExpressionVariable::EVUnknownType) { 1878 const NamedDecl *named_decl = parser_vars->m_named_decl; 1879 const VarDecl *var_decl = dyn_cast<VarDecl>(named_decl); 1880 1881 if (!var_decl) { 1882 LLDB_LOGF(log, "Entity of unknown type does not have a VarDecl"); 1883 return false; 1884 } 1885 1886 if (log) { 1887 ASTDumper ast_dumper(const_cast<VarDecl *>(var_decl)); 1888 LLDB_LOGF(log, "Variable of unknown type now has Decl %s", 1889 ast_dumper.GetCString()); 1890 } 1891 1892 QualType var_type = var_decl->getType(); 1893 TypeFromParser parser_type( 1894 var_type.getAsOpaquePtr(), 1895 ClangASTContext::GetASTContext(&var_decl->getASTContext())); 1896 1897 lldb::opaque_compiler_type_t copied_type = nullptr; 1898 if (m_ast_importer_sp) { 1899 copied_type = m_ast_importer_sp->CopyType( 1900 scratch_ast_context->getASTContext(), &var_decl->getASTContext(), 1901 var_type.getAsOpaquePtr()); 1902 } else if (HasMerger()) { 1903 copied_type = CopyTypeWithMerger( 1904 var_decl->getASTContext(), 1905 scratch_ast_context->GetMergerUnchecked(), var_type) 1906 .getAsOpaquePtr(); 1907 } else { 1908 lldbassert(0 && "No mechanism to copy a resolved unknown type!"); 1909 return false; 1910 } 1911 1912 if (!copied_type) { 1913 LLDB_LOGF(log, "ClangExpressionDeclMap::ResolveUnknownType - Couldn't " 1914 "import the type for a variable"); 1915 1916 return (bool)lldb::ExpressionVariableSP(); 1917 } 1918 1919 TypeFromUser user_type(copied_type, scratch_ast_context); 1920 1921 // parser_vars->m_lldb_value.SetContext(Value::eContextTypeClangType, 1922 // user_type.GetOpaqueQualType()); 1923 parser_vars->m_lldb_value.SetCompilerType(user_type); 1924 parser_vars->m_parser_type = parser_type; 1925 1926 entity->SetCompilerType(user_type); 1927 1928 entity->m_flags &= ~(ClangExpressionVariable::EVUnknownType); 1929 } 1930 } 1931 1932 return true; 1933 } 1934 1935 void ClangExpressionDeclMap::AddOneRegister(NameSearchContext &context, 1936 const RegisterInfo *reg_info, 1937 unsigned int current_id) { 1938 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1939 1940 CompilerType clang_type = 1941 ClangASTContext::GetBuiltinTypeForEncodingAndBitSize( 1942 m_ast_context, reg_info->encoding, reg_info->byte_size * 8); 1943 1944 if (!clang_type) { 1945 LLDB_LOGF(log, " Tried to add a type for %s, but couldn't get one", 1946 context.m_decl_name.getAsString().c_str()); 1947 return; 1948 } 1949 1950 TypeFromParser parser_clang_type(clang_type); 1951 1952 NamedDecl *var_decl = context.AddVarDecl(parser_clang_type); 1953 1954 ClangExpressionVariable *entity(new ClangExpressionVariable( 1955 m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(), 1956 m_parser_vars->m_target_info.byte_order, 1957 m_parser_vars->m_target_info.address_byte_size)); 1958 m_found_entities.AddNewlyConstructedVariable(entity); 1959 1960 std::string decl_name(context.m_decl_name.getAsString()); 1961 entity->SetName(ConstString(decl_name.c_str())); 1962 entity->SetRegisterInfo(reg_info); 1963 entity->EnableParserVars(GetParserID()); 1964 ClangExpressionVariable::ParserVars *parser_vars = 1965 entity->GetParserVars(GetParserID()); 1966 parser_vars->m_parser_type = parser_clang_type; 1967 parser_vars->m_named_decl = var_decl; 1968 parser_vars->m_llvm_value = nullptr; 1969 parser_vars->m_lldb_value.Clear(); 1970 entity->m_flags |= ClangExpressionVariable::EVBareRegister; 1971 1972 if (log) { 1973 ASTDumper ast_dumper(var_decl); 1974 LLDB_LOGF(log, " CEDM::FEVD[%d] Added register %s, returned %s", 1975 current_id, context.m_decl_name.getAsString().c_str(), 1976 ast_dumper.GetCString()); 1977 } 1978 } 1979 1980 void ClangExpressionDeclMap::AddOneFunction(NameSearchContext &context, 1981 Function *function, Symbol *symbol, 1982 unsigned int current_id) { 1983 assert(m_parser_vars.get()); 1984 1985 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1986 1987 NamedDecl *function_decl = nullptr; 1988 Address fun_address; 1989 CompilerType function_clang_type; 1990 1991 bool is_indirect_function = false; 1992 1993 if (function) { 1994 Type *function_type = function->GetType(); 1995 1996 const auto lang = function->GetCompileUnit()->GetLanguage(); 1997 const auto name = function->GetMangled().GetMangledName().AsCString(); 1998 const bool extern_c = (Language::LanguageIsC(lang) && 1999 !CPlusPlusLanguage::IsCPPMangledName(name)) || 2000 (Language::LanguageIsObjC(lang) && 2001 !Language::LanguageIsCPlusPlus(lang)); 2002 2003 if (!extern_c) { 2004 TypeSystem *type_system = function->GetDeclContext().GetTypeSystem(); 2005 if (llvm::isa<ClangASTContext>(type_system)) { 2006 clang::DeclContext *src_decl_context = 2007 (clang::DeclContext *)function->GetDeclContext() 2008 .GetOpaqueDeclContext(); 2009 clang::FunctionDecl *src_function_decl = 2010 llvm::dyn_cast_or_null<clang::FunctionDecl>(src_decl_context); 2011 if (src_function_decl && 2012 src_function_decl->getTemplateSpecializationInfo()) { 2013 clang::FunctionTemplateDecl *function_template = 2014 src_function_decl->getTemplateSpecializationInfo()->getTemplate(); 2015 clang::FunctionTemplateDecl *copied_function_template = 2016 llvm::dyn_cast_or_null<clang::FunctionTemplateDecl>( 2017 CopyDecl(function_template)); 2018 if (copied_function_template) { 2019 if (log) { 2020 ASTDumper ast_dumper((clang::Decl *)copied_function_template); 2021 2022 StreamString ss; 2023 2024 function->DumpSymbolContext(&ss); 2025 2026 log->Printf(" CEDM::FEVD[%u] Imported decl for function template" 2027 " %s (description %s), returned %s", 2028 current_id, 2029 copied_function_template->getNameAsString().c_str(), 2030 ss.GetData(), ast_dumper.GetCString()); 2031 } 2032 2033 context.AddNamedDecl(copied_function_template); 2034 } 2035 } else if (src_function_decl) { 2036 if (clang::FunctionDecl *copied_function_decl = 2037 llvm::dyn_cast_or_null<clang::FunctionDecl>( 2038 CopyDecl(src_function_decl))) { 2039 if (log) { 2040 ASTDumper ast_dumper((clang::Decl *)copied_function_decl); 2041 2042 StreamString ss; 2043 2044 function->DumpSymbolContext(&ss); 2045 2046 LLDB_LOGF(log, 2047 " CEDM::FEVD[%u] Imported decl for function %s " 2048 "(description %s), returned %s", 2049 current_id, 2050 copied_function_decl->getNameAsString().c_str(), 2051 ss.GetData(), ast_dumper.GetCString()); 2052 } 2053 2054 context.AddNamedDecl(copied_function_decl); 2055 return; 2056 } else { 2057 if (log) { 2058 LLDB_LOGF(log, " Failed to import the function decl for '%s'", 2059 src_function_decl->getName().str().c_str()); 2060 } 2061 } 2062 } 2063 } 2064 } 2065 2066 if (!function_type) { 2067 if (log) 2068 log->PutCString(" Skipped a function because it has no type"); 2069 return; 2070 } 2071 2072 function_clang_type = function_type->GetFullCompilerType(); 2073 2074 if (!function_clang_type) { 2075 if (log) 2076 log->PutCString(" Skipped a function because it has no Clang type"); 2077 return; 2078 } 2079 2080 fun_address = function->GetAddressRange().GetBaseAddress(); 2081 2082 CompilerType copied_function_type = GuardedCopyType(function_clang_type); 2083 if (copied_function_type) { 2084 function_decl = context.AddFunDecl(copied_function_type, extern_c); 2085 2086 if (!function_decl) { 2087 if (log) { 2088 LLDB_LOGF( 2089 log, 2090 " Failed to create a function decl for '%s' {0x%8.8" PRIx64 "}", 2091 function_type->GetName().GetCString(), function_type->GetID()); 2092 } 2093 2094 return; 2095 } 2096 } else { 2097 // We failed to copy the type we found 2098 if (log) { 2099 LLDB_LOGF(log, 2100 " Failed to import the function type '%s' {0x%8.8" PRIx64 2101 "} into the expression parser AST contenxt", 2102 function_type->GetName().GetCString(), 2103 function_type->GetID()); 2104 } 2105 2106 return; 2107 } 2108 } else if (symbol) { 2109 fun_address = symbol->GetAddress(); 2110 function_decl = context.AddGenericFunDecl(); 2111 is_indirect_function = symbol->IsIndirect(); 2112 } else { 2113 if (log) 2114 log->PutCString(" AddOneFunction called with no function and no symbol"); 2115 return; 2116 } 2117 2118 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr(); 2119 2120 lldb::addr_t load_addr = 2121 fun_address.GetCallableLoadAddress(target, is_indirect_function); 2122 2123 ClangExpressionVariable *entity(new ClangExpressionVariable( 2124 m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(), 2125 m_parser_vars->m_target_info.byte_order, 2126 m_parser_vars->m_target_info.address_byte_size)); 2127 m_found_entities.AddNewlyConstructedVariable(entity); 2128 2129 std::string decl_name(context.m_decl_name.getAsString()); 2130 entity->SetName(ConstString(decl_name.c_str())); 2131 entity->SetCompilerType(function_clang_type); 2132 entity->EnableParserVars(GetParserID()); 2133 2134 ClangExpressionVariable::ParserVars *parser_vars = 2135 entity->GetParserVars(GetParserID()); 2136 2137 if (load_addr != LLDB_INVALID_ADDRESS) { 2138 parser_vars->m_lldb_value.SetValueType(Value::eValueTypeLoadAddress); 2139 parser_vars->m_lldb_value.GetScalar() = load_addr; 2140 } else { 2141 // We have to try finding a file address. 2142 2143 lldb::addr_t file_addr = fun_address.GetFileAddress(); 2144 2145 parser_vars->m_lldb_value.SetValueType(Value::eValueTypeFileAddress); 2146 parser_vars->m_lldb_value.GetScalar() = file_addr; 2147 } 2148 2149 parser_vars->m_named_decl = function_decl; 2150 parser_vars->m_llvm_value = nullptr; 2151 2152 if (log) { 2153 std::string function_str = 2154 function_decl ? ASTDumper(function_decl).GetCString() : "nullptr"; 2155 2156 StreamString ss; 2157 2158 fun_address.Dump(&ss, 2159 m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(), 2160 Address::DumpStyleResolvedDescription); 2161 2162 LLDB_LOGF( 2163 log, 2164 " CEDM::FEVD[%u] Found %s function %s (description %s), returned %s", 2165 current_id, (function ? "specific" : "generic"), decl_name.c_str(), 2166 ss.GetData(), function_str.c_str()); 2167 } 2168 } 2169 2170 void ClangExpressionDeclMap::AddThisType(NameSearchContext &context, 2171 const TypeFromUser &ut, 2172 unsigned int current_id) { 2173 CompilerType copied_clang_type = GuardedCopyType(ut); 2174 2175 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 2176 2177 if (!copied_clang_type) { 2178 if (log) 2179 LLDB_LOGF( 2180 log, 2181 "ClangExpressionDeclMap::AddThisType - Couldn't import the type"); 2182 2183 return; 2184 } 2185 2186 if (copied_clang_type.IsAggregateType() && 2187 copied_clang_type.GetCompleteType()) { 2188 CompilerType void_clang_type = 2189 ClangASTContext::GetBasicType(m_ast_context, eBasicTypeVoid); 2190 CompilerType void_ptr_clang_type = void_clang_type.GetPointerType(); 2191 2192 CompilerType method_type = ClangASTContext::CreateFunctionType( 2193 m_ast_context, void_clang_type, &void_ptr_clang_type, 1, false, 0); 2194 2195 const bool is_virtual = false; 2196 const bool is_static = false; 2197 const bool is_inline = false; 2198 const bool is_explicit = false; 2199 const bool is_attr_used = true; 2200 const bool is_artificial = false; 2201 2202 CXXMethodDecl *method_decl = 2203 ClangASTContext::GetASTContext(m_ast_context) 2204 ->AddMethodToCXXRecordType( 2205 copied_clang_type.GetOpaqueQualType(), "$__lldb_expr", nullptr, 2206 method_type, lldb::eAccessPublic, is_virtual, is_static, 2207 is_inline, is_explicit, is_attr_used, is_artificial); 2208 2209 if (log) { 2210 ASTDumper method_ast_dumper((clang::Decl *)method_decl); 2211 ASTDumper type_ast_dumper(copied_clang_type); 2212 2213 LLDB_LOGF(log, 2214 " CEDM::AddThisType Added function $__lldb_expr " 2215 "(description %s) for this type %s", 2216 method_ast_dumper.GetCString(), type_ast_dumper.GetCString()); 2217 } 2218 } 2219 2220 if (!copied_clang_type.IsValid()) 2221 return; 2222 2223 TypeSourceInfo *type_source_info = m_ast_context->getTrivialTypeSourceInfo( 2224 QualType::getFromOpaquePtr(copied_clang_type.GetOpaqueQualType())); 2225 2226 if (!type_source_info) 2227 return; 2228 2229 // Construct a typedef type because if "*this" is a templated type we can't 2230 // just return ClassTemplateSpecializationDecls in response to name queries. 2231 // Using a typedef makes this much more robust. 2232 2233 TypedefDecl *typedef_decl = TypedefDecl::Create( 2234 *m_ast_context, m_ast_context->getTranslationUnitDecl(), SourceLocation(), 2235 SourceLocation(), context.m_decl_name.getAsIdentifierInfo(), 2236 type_source_info); 2237 2238 if (!typedef_decl) 2239 return; 2240 2241 context.AddNamedDecl(typedef_decl); 2242 2243 return; 2244 } 2245 2246 void ClangExpressionDeclMap::AddOneType(NameSearchContext &context, 2247 const TypeFromUser &ut, 2248 unsigned int current_id) { 2249 CompilerType copied_clang_type = GuardedCopyType(ut); 2250 2251 if (!copied_clang_type) { 2252 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 2253 2254 if (log) 2255 LLDB_LOGF( 2256 log, "ClangExpressionDeclMap::AddOneType - Couldn't import the type"); 2257 2258 return; 2259 } 2260 2261 context.AddTypeDecl(copied_clang_type); 2262 } 2263