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