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