ClangExpressionDeclMap.cpp revision 67bbb1103c5a49b7c994750e90ae7ed130daa3ae
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
12// C Includes
13// C++ Includes
14// Other libraries and framework includes
15// Project includes
16#include "clang/AST/DeclarationName.h"
17#include "clang/AST/Decl.h"
18#include "lldb/lldb-private.h"
19#include "lldb/Core/Address.h"
20#include "lldb/Core/Error.h"
21#include "lldb/Core/Log.h"
22#include "lldb/Core/Module.h"
23#include "lldb/Core/RegisterValue.h"
24#include "lldb/Core/ValueObjectConstResult.h"
25#include "lldb/Expression/ASTDumper.h"
26#include "lldb/Expression/ClangASTSource.h"
27#include "lldb/Expression/ClangPersistentVariables.h"
28#include "lldb/Host/Endian.h"
29#include "lldb/Symbol/ClangASTContext.h"
30#include "lldb/Symbol/ClangNamespaceDecl.h"
31#include "lldb/Symbol/CompileUnit.h"
32#include "lldb/Symbol/Function.h"
33#include "lldb/Symbol/ObjectFile.h"
34#include "lldb/Symbol/SymbolContext.h"
35#include "lldb/Symbol/SymbolVendor.h"
36#include "lldb/Symbol/Type.h"
37#include "lldb/Symbol/TypeList.h"
38#include "lldb/Symbol/Variable.h"
39#include "lldb/Symbol/VariableList.h"
40#include "lldb/Target/ExecutionContext.h"
41#include "lldb/Target/Process.h"
42#include "lldb/Target/RegisterContext.h"
43#include "lldb/Target/StackFrame.h"
44#include "lldb/Target/Target.h"
45#include "lldb/Target/Thread.h"
46#include "llvm/Support/raw_ostream.h"
47
48using namespace lldb;
49using namespace lldb_private;
50using namespace clang;
51
52ClangExpressionDeclMap::ClangExpressionDeclMap (bool keep_result_in_memory) :
53    m_found_entities (),
54    m_struct_members (),
55    m_keep_result_in_memory (keep_result_in_memory),
56    m_parser_vars (),
57    m_struct_vars ()
58{
59    EnableStructVars();
60}
61
62ClangExpressionDeclMap::~ClangExpressionDeclMap()
63{
64    // Note: The model is now that the parser's AST context and all associated
65    //   data does not vanish until the expression has been executed.  This means
66    //   that valuable lookup data (like namespaces) doesn't vanish, but
67
68    DidParse();
69    DidDematerialize();
70    DisableStructVars();
71}
72
73bool
74ClangExpressionDeclMap::WillParse(ExecutionContext &exe_ctx)
75{
76    EnableParserVars();
77    m_parser_vars->m_exe_ctx = &exe_ctx;
78
79    Target *target = exe_ctx.GetTargetPtr();
80    if (exe_ctx.GetFramePtr())
81        m_parser_vars->m_sym_ctx = exe_ctx.GetFramePtr()->GetSymbolContext(lldb::eSymbolContextEverything);
82    else if (exe_ctx.GetThreadPtr())
83        m_parser_vars->m_sym_ctx = exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(0)->GetSymbolContext(lldb::eSymbolContextEverything);
84    else if (exe_ctx.GetProcessPtr())
85    {
86        m_parser_vars->m_sym_ctx.Clear();
87        m_parser_vars->m_sym_ctx.target_sp = exe_ctx.GetTargetSP();
88    }
89    else if (target)
90    {
91        m_parser_vars->m_sym_ctx.Clear();
92        m_parser_vars->m_sym_ctx.target_sp = exe_ctx.GetTargetSP();
93    }
94
95    if (target)
96    {
97        m_parser_vars->m_persistent_vars = &target->GetPersistentVariables();
98
99        if (!target->GetScratchClangASTContext())
100            return false;
101    }
102
103    m_parser_vars->m_target_info = GetTargetInfo();
104
105    return true;
106}
107
108void
109ClangExpressionDeclMap::DidParse()
110{
111    if (m_parser_vars.get())
112    {
113        for (size_t entity_index = 0, num_entities = m_found_entities.GetSize();
114             entity_index < num_entities;
115             ++entity_index)
116        {
117            ClangExpressionVariableSP var_sp(m_found_entities.GetVariableAtIndex(entity_index));
118            if (var_sp &&
119                var_sp->m_parser_vars.get() &&
120                var_sp->m_parser_vars->m_lldb_value)
121                delete var_sp->m_parser_vars->m_lldb_value;
122
123            var_sp->DisableParserVars();
124        }
125
126        for (size_t pvar_index = 0, num_pvars = m_parser_vars->m_persistent_vars->GetSize();
127             pvar_index < num_pvars;
128             ++pvar_index)
129        {
130            ClangExpressionVariableSP pvar_sp(m_parser_vars->m_persistent_vars->GetVariableAtIndex(pvar_index));
131            if (pvar_sp)
132                pvar_sp->DisableParserVars();
133        }
134
135        DisableParserVars();
136    }
137}
138
139// Interface for IRForTarget
140
141ClangExpressionDeclMap::TargetInfo
142ClangExpressionDeclMap::GetTargetInfo()
143{
144    assert (m_parser_vars.get());
145
146    TargetInfo ret;
147
148    ExecutionContext *exe_ctx = m_parser_vars->m_exe_ctx;
149    if (exe_ctx)
150    {
151        Process *process = exe_ctx->GetProcessPtr();
152        if (process)
153        {
154            ret.byte_order = process->GetByteOrder();
155            ret.address_byte_size = process->GetAddressByteSize();
156        }
157        else
158        {
159            Target *target = exe_ctx->GetTargetPtr();
160            if (target)
161            {
162                ret.byte_order = target->GetArchitecture().GetByteOrder();
163                ret.address_byte_size = target->GetArchitecture().GetAddressByteSize();
164            }
165        }
166    }
167
168    return ret;
169}
170
171const ConstString &
172ClangExpressionDeclMap::GetPersistentResultName ()
173{
174    assert (m_struct_vars.get());
175    assert (m_parser_vars.get());
176    if (!m_struct_vars->m_result_name)
177    {
178        Target *target = m_parser_vars->GetTarget();
179        assert (target);
180        m_struct_vars->m_result_name = target->GetPersistentVariables().GetNextPersistentVariableName();
181    }
182    return m_struct_vars->m_result_name;
183}
184
185lldb::ClangExpressionVariableSP
186ClangExpressionDeclMap::BuildIntegerVariable (const ConstString &name,
187                                              lldb_private::TypeFromParser type,
188                                              const llvm::APInt& value)
189{
190    assert (m_parser_vars.get());
191
192    ExecutionContext *exe_ctx = m_parser_vars->m_exe_ctx;
193    if (exe_ctx == NULL)
194        return lldb::ClangExpressionVariableSP();
195    Target *target = exe_ctx->GetTargetPtr();
196
197    ASTContext *context(target->GetScratchClangASTContext()->getASTContext());
198
199    TypeFromUser user_type(ClangASTContext::CopyType(context,
200                                                     type.GetASTContext(),
201                                                     type.GetOpaqueQualType()),
202                           context);
203
204    if (!m_parser_vars->m_persistent_vars->CreatePersistentVariable (exe_ctx->GetBestExecutionContextScope (),
205                                                                     name,
206                                                                     user_type,
207                                                                     m_parser_vars->m_target_info.byte_order,
208                                                                     m_parser_vars->m_target_info.address_byte_size))
209        return lldb::ClangExpressionVariableSP();
210
211    ClangExpressionVariableSP pvar_sp (m_parser_vars->m_persistent_vars->GetVariable(name));
212
213    if (!pvar_sp)
214        return lldb::ClangExpressionVariableSP();
215
216    uint8_t *pvar_data = pvar_sp->GetValueBytes();
217    if (pvar_data == NULL)
218        return lldb::ClangExpressionVariableSP();
219
220    uint64_t value64 = value.getLimitedValue();
221
222    size_t num_val_bytes = sizeof(value64);
223    size_t num_data_bytes = pvar_sp->GetByteSize();
224
225    size_t num_bytes = num_val_bytes;
226    if (num_bytes > num_data_bytes)
227        num_bytes = num_data_bytes;
228
229    for (size_t byte_idx = 0;
230         byte_idx < num_bytes;
231         ++byte_idx)
232    {
233        uint64_t shift = byte_idx * 8;
234        uint64_t mask = 0xffll << shift;
235        uint8_t cur_byte = (uint8_t)((value64 & mask) >> shift);
236
237        switch (m_parser_vars->m_target_info.byte_order)
238        {
239            case eByteOrderBig:
240                //                    High         Low
241                // Original:         |AABBCCDDEEFFGGHH|
242                // Target:                   |EEFFGGHH|
243
244                pvar_data[num_data_bytes - (1 + byte_idx)] = cur_byte;
245                break;
246            case eByteOrderLittle:
247                // Target:                   |HHGGFFEE|
248                pvar_data[byte_idx] = cur_byte;
249                break;
250            default:
251                return lldb::ClangExpressionVariableSP();
252        }
253    }
254
255    pvar_sp->m_flags |= ClangExpressionVariable::EVIsFreezeDried;
256    pvar_sp->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
257    pvar_sp->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
258
259    return pvar_sp;
260}
261
262lldb::ClangExpressionVariableSP
263ClangExpressionDeclMap::BuildCastVariable (const ConstString &name,
264                                           VarDecl *decl,
265                                           lldb_private::TypeFromParser type)
266{
267    assert (m_parser_vars.get());
268
269    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
270
271    ExecutionContext *exe_ctx = m_parser_vars->m_exe_ctx;
272    if (exe_ctx == NULL)
273        return lldb::ClangExpressionVariableSP();
274    Target *target = exe_ctx->GetTargetPtr();
275    if (target == NULL)
276        return lldb::ClangExpressionVariableSP();
277
278    ASTContext *context(target->GetScratchClangASTContext()->getASTContext());
279
280    ClangExpressionVariableSP var_sp (m_found_entities.GetVariable(decl));
281
282    if (!var_sp)
283        var_sp = m_parser_vars->m_persistent_vars->GetVariable(decl);
284
285    if (!var_sp)
286        return ClangExpressionVariableSP();
287
288    TypeFromUser user_type(ClangASTContext::CopyType(context,
289                                                     type.GetASTContext(),
290                                                     type.GetOpaqueQualType()),
291                           context);
292
293    TypeFromUser var_type = var_sp->GetTypeFromUser();
294
295    StackFrame *frame = exe_ctx->GetFramePtr();
296    if (frame == NULL)
297        return lldb::ClangExpressionVariableSP();
298
299    VariableSP var = FindVariableInScope (*frame, var_sp->GetName(), &var_type);
300
301    if (!var)
302        return lldb::ClangExpressionVariableSP(); // but we should handle this; it may be a persistent variable
303
304    ValueObjectSP var_valobj = frame->GetValueObjectForFrameVariable(var, lldb::eNoDynamicValues);
305
306    if (!var_valobj)
307        return lldb::ClangExpressionVariableSP();
308
309    ValueObjectSP var_casted_valobj = var_valobj->CastPointerType(name.GetCString(), user_type);
310
311    if (!var_casted_valobj)
312        return lldb::ClangExpressionVariableSP();
313
314    if (log)
315    {
316        StreamString my_stream_string;
317
318        ClangASTType::DumpTypeDescription (var_type.GetASTContext(),
319                                           var_type.GetOpaqueQualType(),
320                                           &my_stream_string);
321
322
323        log->Printf("Building cast variable to type: %s", my_stream_string.GetString().c_str());
324    }
325
326    ClangExpressionVariableSP pvar_sp = m_parser_vars->m_persistent_vars->CreatePersistentVariable (var_casted_valobj);
327
328    if (!pvar_sp)
329        return lldb::ClangExpressionVariableSP();
330
331    if (pvar_sp != m_parser_vars->m_persistent_vars->GetVariable(name))
332        return lldb::ClangExpressionVariableSP();
333
334    pvar_sp->m_flags |= ClangExpressionVariable::EVIsFreezeDried;
335    pvar_sp->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
336    pvar_sp->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
337
338    return pvar_sp;
339}
340
341bool
342ClangExpressionDeclMap::ResultIsReference (const ConstString &name)
343{
344    ClangExpressionVariableSP pvar_sp = m_parser_vars->m_persistent_vars->GetVariable(name);
345
346    return (pvar_sp->m_flags & ClangExpressionVariable::EVIsProgramReference);
347}
348
349bool
350ClangExpressionDeclMap::CompleteResultVariable (lldb::ClangExpressionVariableSP &valobj,
351                                                lldb_private::Value &value,
352                                                const ConstString &name,
353                                                lldb_private::TypeFromParser type,
354                                                bool transient)
355{
356    assert (m_parser_vars.get());
357
358    ClangExpressionVariableSP pvar_sp = m_parser_vars->m_persistent_vars->GetVariable(name);
359
360    if (!pvar_sp)
361        return false;
362
363    if (pvar_sp->m_flags & ClangExpressionVariable::EVIsProgramReference &&
364        !pvar_sp->m_live_sp &&
365        !transient)
366    {
367        // The reference comes from the program.  We need to set up a live SP for it.
368
369        pvar_sp->m_live_sp = ValueObjectConstResult::Create(m_parser_vars->m_exe_ctx->GetBestExecutionContextScope(),
370                                                            pvar_sp->GetTypeFromUser().GetASTContext(),
371                                                            pvar_sp->GetTypeFromUser().GetOpaqueQualType(),
372                                                            pvar_sp->GetName(),
373                                                            value.GetScalar().ULongLong(),
374                                                            value.GetValueAddressType(),
375                                                            pvar_sp->GetByteSize());
376    }
377
378    if (pvar_sp->m_flags & ClangExpressionVariable::EVNeedsFreezeDry)
379    {
380        pvar_sp->ValueUpdated();
381
382        const size_t pvar_byte_size = pvar_sp->GetByteSize();
383        uint8_t *pvar_data = pvar_sp->GetValueBytes();
384
385        if (!ReadTarget(pvar_data, value, pvar_byte_size))
386            return false;
387
388        pvar_sp->m_flags &= ~(ClangExpressionVariable::EVNeedsFreezeDry);
389    }
390
391    valobj = pvar_sp;
392
393    return true;
394}
395
396bool
397ClangExpressionDeclMap::AddPersistentVariable
398(
399    const NamedDecl *decl,
400    const ConstString &name,
401    TypeFromParser parser_type,
402    bool is_result,
403    bool is_lvalue
404)
405{
406    assert (m_parser_vars.get());
407
408    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
409    ExecutionContext *exe_ctx = m_parser_vars->m_exe_ctx;
410    if (exe_ctx == NULL)
411        return false;
412    Target *target = exe_ctx->GetTargetPtr();
413    if (target == NULL)
414        return false;
415
416    ASTContext *context(target->GetScratchClangASTContext()->getASTContext());
417
418    TypeFromUser user_type(ClangASTContext::CopyType(context,
419                                                     parser_type.GetASTContext(),
420                                                     parser_type.GetOpaqueQualType()),
421                           context);
422
423    if (!m_parser_vars->m_target_info.IsValid())
424        return false;
425
426    if (!m_parser_vars->m_persistent_vars->CreatePersistentVariable (exe_ctx->GetBestExecutionContextScope (),
427                                                                     name,
428                                                                     user_type,
429                                                                     m_parser_vars->m_target_info.byte_order,
430                                                                     m_parser_vars->m_target_info.address_byte_size))
431        return false;
432
433    ClangExpressionVariableSP var_sp (m_parser_vars->m_persistent_vars->GetVariable(name));
434
435    if (!var_sp)
436        return false;
437
438    if (is_result)
439        var_sp->m_flags |= ClangExpressionVariable::EVNeedsFreezeDry;
440    else
441        var_sp->m_flags |= ClangExpressionVariable::EVKeepInTarget; // explicitly-declared persistent variables should persist
442
443    if (is_lvalue)
444    {
445        var_sp->m_flags |= ClangExpressionVariable::EVIsProgramReference;
446    }
447    else
448    {
449        var_sp->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
450        var_sp->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
451    }
452
453    if (log)
454        log->Printf("Created persistent variable with flags 0x%hx", var_sp->m_flags);
455
456    var_sp->EnableParserVars();
457
458    var_sp->m_parser_vars->m_named_decl = decl;
459    var_sp->m_parser_vars->m_parser_type = parser_type;
460
461    return true;
462}
463
464bool
465ClangExpressionDeclMap::AddValueToStruct
466(
467    const NamedDecl *decl,
468    const ConstString &name,
469    llvm::Value *value,
470    size_t size,
471    off_t alignment
472)
473{
474    assert (m_struct_vars.get());
475    assert (m_parser_vars.get());
476
477    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
478
479    m_struct_vars->m_struct_laid_out = false;
480
481    if (m_struct_members.GetVariable(decl))
482        return true;
483
484    ClangExpressionVariableSP var_sp (m_found_entities.GetVariable(decl));
485
486    if (!var_sp)
487        var_sp = m_parser_vars->m_persistent_vars->GetVariable(decl);
488
489    if (!var_sp)
490        return false;
491
492    if (log)
493        log->Printf("Adding value for decl %p [%s - %s] to the structure",
494                    decl,
495                    name.GetCString(),
496                    var_sp->GetName().GetCString());
497
498    // We know entity->m_parser_vars is valid because we used a parser variable
499    // to find it
500    var_sp->m_parser_vars->m_llvm_value = value;
501
502    var_sp->EnableJITVars();
503    var_sp->m_jit_vars->m_alignment = alignment;
504    var_sp->m_jit_vars->m_size = size;
505
506    m_struct_members.AddVariable(var_sp);
507
508    return true;
509}
510
511bool
512ClangExpressionDeclMap::DoStructLayout ()
513{
514    assert (m_struct_vars.get());
515
516    if (m_struct_vars->m_struct_laid_out)
517        return true;
518
519    off_t cursor = 0;
520
521    m_struct_vars->m_struct_alignment = 0;
522    m_struct_vars->m_struct_size = 0;
523
524    for (size_t member_index = 0, num_members = m_struct_members.GetSize();
525         member_index < num_members;
526         ++member_index)
527    {
528        ClangExpressionVariableSP member_sp(m_struct_members.GetVariableAtIndex(member_index));
529        if (!member_sp)
530            return false;
531
532        if (!member_sp->m_jit_vars.get())
533            return false;
534
535        if (member_index == 0)
536            m_struct_vars->m_struct_alignment = member_sp->m_jit_vars->m_alignment;
537
538        if (cursor % member_sp->m_jit_vars->m_alignment)
539            cursor += (member_sp->m_jit_vars->m_alignment - (cursor % member_sp->m_jit_vars->m_alignment));
540
541        member_sp->m_jit_vars->m_offset = cursor;
542        cursor += member_sp->m_jit_vars->m_size;
543    }
544
545    m_struct_vars->m_struct_size = cursor;
546
547    m_struct_vars->m_struct_laid_out = true;
548    return true;
549}
550
551bool ClangExpressionDeclMap::GetStructInfo
552(
553    uint32_t &num_elements,
554    size_t &size,
555    off_t &alignment
556)
557{
558    assert (m_struct_vars.get());
559
560    if (!m_struct_vars->m_struct_laid_out)
561        return false;
562
563    num_elements = m_struct_members.GetSize();
564    size = m_struct_vars->m_struct_size;
565    alignment = m_struct_vars->m_struct_alignment;
566
567    return true;
568}
569
570bool
571ClangExpressionDeclMap::GetStructElement
572(
573    const NamedDecl *&decl,
574    llvm::Value *&value,
575    off_t &offset,
576    ConstString &name,
577    uint32_t index
578)
579{
580    assert (m_struct_vars.get());
581
582    if (!m_struct_vars->m_struct_laid_out)
583        return false;
584
585    if (index >= m_struct_members.GetSize())
586        return false;
587
588    ClangExpressionVariableSP member_sp(m_struct_members.GetVariableAtIndex(index));
589
590    if (!member_sp ||
591        !member_sp->m_parser_vars.get() ||
592        !member_sp->m_jit_vars.get())
593        return false;
594
595    decl = member_sp->m_parser_vars->m_named_decl;
596    value = member_sp->m_parser_vars->m_llvm_value;
597    offset = member_sp->m_jit_vars->m_offset;
598    name = member_sp->GetName();
599
600    return true;
601}
602
603bool
604ClangExpressionDeclMap::GetFunctionInfo
605(
606    const NamedDecl *decl,
607    llvm::Value**& value,
608    uint64_t &ptr
609)
610{
611    ClangExpressionVariableSP entity_sp(m_found_entities.GetVariable(decl));
612
613    if (!entity_sp)
614        return false;
615
616    // We know m_parser_vars is valid since we searched for the variable by
617    // its NamedDecl
618
619    value = &entity_sp->m_parser_vars->m_llvm_value;
620    ptr = entity_sp->m_parser_vars->m_lldb_value->GetScalar().ULongLong();
621
622    return true;
623}
624
625static void
626FindCodeSymbolInContext
627(
628    const ConstString &name,
629    SymbolContext &sym_ctx,
630    SymbolContextList &sc_list
631)
632{
633    if (sym_ctx.module_sp)
634       sym_ctx.module_sp->FindSymbolsWithNameAndType(name, eSymbolTypeCode, sc_list);
635
636    if (!sc_list.GetSize())
637        sym_ctx.target_sp->GetImages().FindSymbolsWithNameAndType(name, eSymbolTypeCode, sc_list);
638}
639
640bool
641ClangExpressionDeclMap::GetFunctionAddress
642(
643    const ConstString &name,
644    uint64_t &func_addr
645)
646{
647    assert (m_parser_vars.get());
648
649    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
650    ExecutionContext *exe_ctx = m_parser_vars->m_exe_ctx;
651    if (exe_ctx == NULL)
652        return false;
653    Target *target = exe_ctx->GetTargetPtr();
654    // Back out in all cases where we're not fully initialized
655    if (target == NULL)
656        return false;
657    if (!m_parser_vars->m_sym_ctx.target_sp)
658        return false;
659
660    SymbolContextList sc_list;
661
662    FindCodeSymbolInContext(name, m_parser_vars->m_sym_ctx, sc_list);
663
664    if (!sc_list.GetSize())
665    {
666        // We occasionally get debug information in which a const function is reported
667        // as non-const, so the mangled name is wrong.  This is a hack to compensate.
668
669        Mangled mangled(name.GetCString(), true);
670
671        ConstString demangled_name = mangled.GetDemangledName();
672
673        if (strlen(demangled_name.GetCString()))
674        {
675            std::string const_name_scratch(demangled_name.GetCString());
676
677            const_name_scratch.append(" const");
678
679            ConstString const_name(const_name_scratch.c_str());
680
681            FindCodeSymbolInContext(name, m_parser_vars->m_sym_ctx, sc_list);
682
683            if (log)
684                log->Printf("Found %d results with const name %s", sc_list.GetSize(), const_name.GetCString());
685        }
686    }
687
688    if (!sc_list.GetSize())
689        return false;
690
691    SymbolContext sym_ctx;
692    sc_list.GetContextAtIndex(0, sym_ctx);
693
694    const Address *func_so_addr = NULL;
695
696    if (sym_ctx.function)
697        func_so_addr = &sym_ctx.function->GetAddressRange().GetBaseAddress();
698    else if (sym_ctx.symbol)
699        func_so_addr = &sym_ctx.symbol->GetAddressRangeRef().GetBaseAddress();
700    else
701        return false;
702
703    if (!func_so_addr || !func_so_addr->IsValid())
704        return false;
705
706    func_addr = func_so_addr->GetCallableLoadAddress (target);
707
708    return true;
709}
710
711addr_t
712ClangExpressionDeclMap::GetSymbolAddress (Target &target, const ConstString &name)
713{
714    SymbolContextList sc_list;
715
716    target.GetImages().FindSymbolsWithNameAndType(name, eSymbolTypeAny, sc_list);
717
718    const uint32_t num_matches = sc_list.GetSize();
719    addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
720
721    for (uint32_t i=0; i<num_matches && symbol_load_addr == LLDB_INVALID_ADDRESS; i++)
722    {
723        SymbolContext sym_ctx;
724        sc_list.GetContextAtIndex(i, sym_ctx);
725
726        const Address *sym_address = &sym_ctx.symbol->GetAddressRangeRef().GetBaseAddress();
727
728        if (!sym_address || !sym_address->IsValid())
729            return LLDB_INVALID_ADDRESS;
730
731        if (sym_address)
732        {
733            switch (sym_ctx.symbol->GetType())
734            {
735                case eSymbolTypeCode:
736                case eSymbolTypeTrampoline:
737                    symbol_load_addr = sym_address->GetCallableLoadAddress (&target);
738                    break;
739
740                case eSymbolTypeData:
741                case eSymbolTypeRuntime:
742                case eSymbolTypeVariable:
743                case eSymbolTypeLocal:
744                case eSymbolTypeParam:
745                case eSymbolTypeInvalid:
746                case eSymbolTypeAbsolute:
747                case eSymbolTypeExtern:
748                case eSymbolTypeException:
749                case eSymbolTypeSourceFile:
750                case eSymbolTypeHeaderFile:
751                case eSymbolTypeObjectFile:
752                case eSymbolTypeCommonBlock:
753                case eSymbolTypeBlock:
754                case eSymbolTypeVariableType:
755                case eSymbolTypeLineEntry:
756                case eSymbolTypeLineHeader:
757                case eSymbolTypeScopeBegin:
758                case eSymbolTypeScopeEnd:
759                case eSymbolTypeAdditional:
760                case eSymbolTypeCompiler:
761                case eSymbolTypeInstrumentation:
762                case eSymbolTypeUndefined:
763                    symbol_load_addr = sym_address->GetLoadAddress (&target);
764                    break;
765            }
766        }
767    }
768
769    return symbol_load_addr;
770}
771
772addr_t
773ClangExpressionDeclMap::GetSymbolAddress (const ConstString &name)
774{
775    assert (m_parser_vars.get());
776
777    if (!m_parser_vars->m_exe_ctx ||
778        !m_parser_vars->m_exe_ctx->GetTargetPtr())
779        return false;
780
781    return GetSymbolAddress(m_parser_vars->m_exe_ctx->GetTargetRef(), name);
782}
783
784// Interface for IRInterpreter
785
786bool
787ClangExpressionDeclMap::WriteTarget (lldb_private::Value &value,
788                                     const uint8_t *data,
789                                     size_t length)
790{
791    assert (m_parser_vars.get());
792
793    ExecutionContext *exe_ctx = m_parser_vars->m_exe_ctx;
794
795    Process *process = exe_ctx->GetProcessPtr();
796    if (value.GetContextType() == Value::eContextTypeRegisterInfo)
797    {
798        if (!process)
799            return false;
800
801        RegisterContext *reg_ctx = exe_ctx->GetRegisterContext();
802        RegisterInfo *reg_info = value.GetRegisterInfo();
803
804        if (!reg_ctx)
805            return false;
806
807        lldb_private::RegisterValue reg_value;
808        Error err;
809
810        if (!reg_value.SetFromMemoryData (reg_info, data, length, process->GetByteOrder(), err))
811            return false;
812
813        return reg_ctx->WriteRegister(reg_info, reg_value);
814    }
815    else
816    {
817        switch (value.GetValueType())
818        {
819        default:
820            return false;
821        case Value::eValueTypeFileAddress:
822            {
823                if (!process)
824                    return false;
825
826                Target *target = exe_ctx->GetTargetPtr();
827                Address file_addr;
828
829                if (!target->GetImages().ResolveFileAddress((lldb::addr_t)value.GetScalar().ULongLong(), file_addr))
830                    return false;
831
832                lldb::addr_t load_addr = file_addr.GetLoadAddress(target);
833
834                Error err;
835                process->WriteMemory(load_addr, data, length, err);
836
837                return err.Success();
838            }
839        case Value::eValueTypeLoadAddress:
840            {
841                if (!process)
842                    return false;
843
844                Error err;
845                process->WriteMemory((lldb::addr_t)value.GetScalar().ULongLong(), data, length, err);
846
847                return err.Success();
848            }
849        case Value::eValueTypeHostAddress:
850            memcpy ((void *)value.GetScalar().ULongLong(), data, length);
851            return true;
852        case Value::eValueTypeScalar:
853            return false;
854        }
855    }
856}
857
858bool
859ClangExpressionDeclMap::ReadTarget (uint8_t *data,
860                                    lldb_private::Value &value,
861                                    size_t length)
862{
863    assert (m_parser_vars.get());
864
865    ExecutionContext *exe_ctx = m_parser_vars->m_exe_ctx;
866
867    Process *process = exe_ctx->GetProcessPtr();
868
869    if (value.GetContextType() == Value::eContextTypeRegisterInfo)
870    {
871        if (!process)
872            return false;
873
874        RegisterContext *reg_ctx = exe_ctx->GetRegisterContext();
875        RegisterInfo *reg_info = value.GetRegisterInfo();
876
877        if (!reg_ctx)
878            return false;
879
880        lldb_private::RegisterValue reg_value;
881        Error err;
882
883        if (!reg_ctx->ReadRegister(reg_info, reg_value))
884            return false;
885
886        return reg_value.GetAsMemoryData(reg_info, data, length, process->GetByteOrder(), err);
887    }
888    else
889    {
890        switch (value.GetValueType())
891        {
892            default:
893                return false;
894            case Value::eValueTypeFileAddress:
895            {
896                Target *target = exe_ctx->GetTargetPtr();
897                if (target == NULL)
898                    return false;
899
900                Address file_addr;
901
902                if (!target->GetImages().ResolveFileAddress((lldb::addr_t)value.GetScalar().ULongLong(), file_addr))
903                    return false;
904
905                Error err;
906                target->ReadMemory(file_addr, true, data, length, err);
907
908                return err.Success();
909            }
910            case Value::eValueTypeLoadAddress:
911            {
912                if (!process)
913                    return false;
914
915                Error err;
916                process->ReadMemory((lldb::addr_t)value.GetScalar().ULongLong(), data, length, err);
917
918                return err.Success();
919            }
920            case Value::eValueTypeHostAddress:
921                memcpy (data, (const void *)value.GetScalar().ULongLong(), length);
922                return true;
923            case Value::eValueTypeScalar:
924                return false;
925        }
926    }
927}
928
929lldb_private::Value
930ClangExpressionDeclMap::LookupDecl (clang::NamedDecl *decl)
931{
932    assert (m_parser_vars.get());
933
934    ExecutionContext exe_ctx = *m_parser_vars->m_exe_ctx;
935
936    ClangExpressionVariableSP expr_var_sp (m_found_entities.GetVariable(decl));
937    ClangExpressionVariableSP persistent_var_sp (m_parser_vars->m_persistent_vars->GetVariable(decl));
938
939    if (expr_var_sp)
940    {
941        if (!expr_var_sp->m_parser_vars.get() || !expr_var_sp->m_parser_vars->m_lldb_var)
942            return Value();
943
944        return *GetVariableValue(exe_ctx, expr_var_sp->m_parser_vars->m_lldb_var, NULL);
945    }
946    else if (persistent_var_sp)
947    {
948        if ((persistent_var_sp->m_flags & ClangExpressionVariable::EVIsProgramReference ||
949             persistent_var_sp->m_flags & ClangExpressionVariable::EVIsLLDBAllocated) &&
950            persistent_var_sp->m_live_sp)
951        {
952            return persistent_var_sp->m_live_sp->GetValue();
953        }
954        else
955        {
956            lldb_private::Value ret;
957            ret.SetValueType(Value::eValueTypeHostAddress);
958            ret.SetContext(Value::eContextTypeInvalid, NULL);
959            ret.GetScalar() = (lldb::addr_t)persistent_var_sp->GetValueBytes();
960            return ret;
961        }
962    }
963    else
964    {
965        return Value();
966    }
967}
968
969// Interface for CommandObjectExpression
970
971bool
972ClangExpressionDeclMap::Materialize
973(
974    ExecutionContext &exe_ctx,
975    lldb::addr_t &struct_address,
976    Error &err
977)
978{
979    EnableMaterialVars();
980
981    m_material_vars->m_process = exe_ctx.GetProcessPtr();
982
983    bool result = DoMaterialize(false /* dematerialize */,
984                                exe_ctx,
985                                LLDB_INVALID_ADDRESS /* top of stack frame */,
986                                LLDB_INVALID_ADDRESS /* bottom of stack frame */,
987                                NULL, /* result SP */
988                                err);
989
990    if (result)
991        struct_address = m_material_vars->m_materialized_location;
992
993    return result;
994}
995
996bool
997ClangExpressionDeclMap::GetObjectPointer
998(
999    lldb::addr_t &object_ptr,
1000    ConstString &object_name,
1001    ExecutionContext &exe_ctx,
1002    Error &err,
1003    bool suppress_type_check
1004)
1005{
1006    assert (m_struct_vars.get());
1007
1008    Target *target = exe_ctx.GetTargetPtr();
1009    Process *process = exe_ctx.GetProcessPtr();
1010    StackFrame *frame = exe_ctx.GetFramePtr();
1011
1012    if (frame == NULL || process == NULL || target == NULL)
1013    {
1014        err.SetErrorString("Couldn't load 'this' because the context is incomplete");
1015        return false;
1016    }
1017
1018    if (!m_struct_vars->m_object_pointer_type.GetOpaqueQualType())
1019    {
1020        err.SetErrorString("Couldn't load 'this' because its type is unknown");
1021        return false;
1022    }
1023
1024    VariableSP object_ptr_var = FindVariableInScope (*frame,
1025                                                     object_name,
1026                                                     (suppress_type_check ? NULL : &m_struct_vars->m_object_pointer_type));
1027
1028    if (!object_ptr_var)
1029    {
1030        err.SetErrorStringWithFormat("Couldn't find '%s' with appropriate type in scope", object_name.GetCString());
1031        return false;
1032    }
1033
1034    std::auto_ptr<lldb_private::Value> location_value(GetVariableValue(exe_ctx,
1035                                                                       object_ptr_var,
1036                                                                       NULL));
1037
1038    if (!location_value.get())
1039    {
1040        err.SetErrorStringWithFormat("Couldn't get the location for '%s'", object_name.GetCString());
1041        return false;
1042    }
1043
1044    switch (location_value->GetValueType())
1045    {
1046    default:
1047        err.SetErrorStringWithFormat("'%s' is not in memory; LLDB must be extended to handle registers", object_name.GetCString());
1048        return false;
1049    case Value::eValueTypeLoadAddress:
1050        {
1051            lldb::addr_t value_addr = location_value->GetScalar().ULongLong();
1052            uint32_t address_byte_size = target->GetArchitecture().GetAddressByteSize();
1053
1054            if (ClangASTType::GetClangTypeBitWidth(m_struct_vars->m_object_pointer_type.GetASTContext(),
1055                                                   m_struct_vars->m_object_pointer_type.GetOpaqueQualType()) != address_byte_size * 8)
1056            {
1057                err.SetErrorStringWithFormat("'%s' is not of an expected pointer size", object_name.GetCString());
1058                return false;
1059            }
1060
1061            Error read_error;
1062            object_ptr = process->ReadPointerFromMemory (value_addr, read_error);
1063            if (read_error.Fail() || object_ptr == LLDB_INVALID_ADDRESS)
1064            {
1065                err.SetErrorStringWithFormat("Coldn't read '%s' from the target: %s", object_name.GetCString(), read_error.AsCString());
1066                return false;
1067            }
1068            return true;
1069        }
1070    case Value::eValueTypeScalar:
1071        {
1072            if (location_value->GetContextType() != Value::eContextTypeRegisterInfo)
1073            {
1074                StreamString ss;
1075                location_value->Dump(&ss);
1076
1077                err.SetErrorStringWithFormat("%s is a scalar of unhandled type: %s", object_name.GetCString(), ss.GetString().c_str());
1078                return false;
1079            }
1080
1081            RegisterInfo *reg_info = location_value->GetRegisterInfo();
1082
1083            if (!reg_info)
1084            {
1085                err.SetErrorStringWithFormat("Couldn't get the register information for %s", object_name.GetCString());
1086                return false;
1087            }
1088
1089            RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
1090
1091            if (!reg_ctx)
1092            {
1093                err.SetErrorStringWithFormat("Couldn't read register context to read %s from %s", object_name.GetCString(), reg_info->name);
1094                return false;
1095            }
1096
1097            uint32_t register_number = reg_info->kinds[lldb::eRegisterKindLLDB];
1098
1099            object_ptr = reg_ctx->ReadRegisterAsUnsigned(register_number, 0x0);
1100
1101            return true;
1102        }
1103    }
1104}
1105
1106bool
1107ClangExpressionDeclMap::Dematerialize
1108(
1109    ExecutionContext &exe_ctx,
1110    ClangExpressionVariableSP &result_sp,
1111    lldb::addr_t stack_frame_top,
1112    lldb::addr_t stack_frame_bottom,
1113    Error &err
1114)
1115{
1116    return DoMaterialize(true, exe_ctx, stack_frame_top, stack_frame_bottom, &result_sp, err);
1117
1118    DidDematerialize();
1119}
1120
1121void
1122ClangExpressionDeclMap::DidDematerialize()
1123{
1124    if (m_material_vars.get())
1125    {
1126        if (m_material_vars->m_materialized_location)
1127        {
1128            //#define SINGLE_STEP_EXPRESSIONS
1129
1130#ifndef SINGLE_STEP_EXPRESSIONS
1131            m_material_vars->m_process->DeallocateMemory(m_material_vars->m_materialized_location);
1132#endif
1133            m_material_vars->m_materialized_location = 0;
1134        }
1135
1136        DisableMaterialVars();
1137    }
1138}
1139
1140bool
1141ClangExpressionDeclMap::DumpMaterializedStruct
1142(
1143    ExecutionContext &exe_ctx,
1144    Stream &s,
1145    Error &err
1146)
1147{
1148    assert (m_struct_vars.get());
1149    assert (m_material_vars.get());
1150
1151    if (!m_struct_vars->m_struct_laid_out)
1152    {
1153        err.SetErrorString("Structure hasn't been laid out yet");
1154        return false;
1155    }
1156    Process *process = exe_ctx.GetProcessPtr();
1157
1158    if (!process)
1159    {
1160        err.SetErrorString("Couldn't find the process");
1161        return false;
1162    }
1163
1164    Target *target = exe_ctx.GetTargetPtr();
1165    if (!target)
1166    {
1167        err.SetErrorString("Couldn't find the target");
1168        return false;
1169    }
1170
1171    if (!m_material_vars->m_materialized_location)
1172    {
1173        err.SetErrorString("No materialized location");
1174        return false;
1175    }
1176
1177    lldb::DataBufferSP data_sp(new DataBufferHeap(m_struct_vars->m_struct_size, 0));
1178
1179    Error error;
1180    if (process->ReadMemory (m_material_vars->m_materialized_location,
1181                                     data_sp->GetBytes(),
1182                                     data_sp->GetByteSize(), error) != data_sp->GetByteSize())
1183    {
1184        err.SetErrorStringWithFormat ("Couldn't read struct from the target: %s", error.AsCString());
1185        return false;
1186    }
1187
1188    DataExtractor extractor(data_sp, process->GetByteOrder(), target->GetArchitecture().GetAddressByteSize());
1189
1190    for (size_t member_idx = 0, num_members = m_struct_members.GetSize();
1191         member_idx < num_members;
1192         ++member_idx)
1193    {
1194        ClangExpressionVariableSP member_sp(m_struct_members.GetVariableAtIndex(member_idx));
1195
1196        if (!member_sp)
1197            return false;
1198
1199        s.Printf("[%s]\n", member_sp->GetName().GetCString());
1200
1201        if (!member_sp->m_jit_vars.get())
1202            return false;
1203
1204        extractor.Dump (&s,                                                                          // stream
1205                        member_sp->m_jit_vars->m_offset,                                             // offset
1206                        lldb::eFormatBytesWithASCII,                                                 // format
1207                        1,                                                                           // byte size of individual entries
1208                        member_sp->m_jit_vars->m_size,                                               // number of entries
1209                        16,                                                                          // entries per line
1210                        m_material_vars->m_materialized_location + member_sp->m_jit_vars->m_offset,  // address to print
1211                        0,                                                                           // bit size (bitfields only; 0 means ignore)
1212                        0);                                                                          // bit alignment (bitfields only; 0 means ignore)
1213
1214        s.PutChar('\n');
1215    }
1216
1217    return true;
1218}
1219
1220bool
1221ClangExpressionDeclMap::DoMaterialize
1222(
1223    bool dematerialize,
1224    ExecutionContext &exe_ctx,
1225    lldb::addr_t stack_frame_top,
1226    lldb::addr_t stack_frame_bottom,
1227    lldb::ClangExpressionVariableSP *result_sp_ptr,
1228    Error &err
1229)
1230{
1231    if (result_sp_ptr)
1232        result_sp_ptr->reset();
1233
1234    assert (m_struct_vars.get());
1235
1236    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1237
1238    if (!m_struct_vars->m_struct_laid_out)
1239    {
1240        err.SetErrorString("Structure hasn't been laid out yet");
1241        return false;
1242    }
1243
1244    StackFrame *frame = exe_ctx.GetFramePtr();
1245    if (!frame)
1246    {
1247        err.SetErrorString("Received null execution frame");
1248        return false;
1249    }
1250    Target *target = exe_ctx.GetTargetPtr();
1251
1252    ClangPersistentVariables &persistent_vars = target->GetPersistentVariables();
1253
1254    if (!m_struct_vars->m_struct_size)
1255    {
1256        if (log)
1257            log->PutCString("Not bothering to allocate a struct because no arguments are needed");
1258
1259        m_material_vars->m_allocated_area = NULL;
1260
1261        return true;
1262    }
1263
1264    const SymbolContext &sym_ctx(frame->GetSymbolContext(lldb::eSymbolContextEverything));
1265
1266    if (!dematerialize)
1267    {
1268        Process *process = exe_ctx.GetProcessPtr();
1269        if (m_material_vars->m_materialized_location)
1270        {
1271            process->DeallocateMemory(m_material_vars->m_materialized_location);
1272            m_material_vars->m_materialized_location = 0;
1273        }
1274
1275        if (log)
1276            log->PutCString("Allocating memory for materialized argument struct");
1277
1278        lldb::addr_t mem = process->AllocateMemory(m_struct_vars->m_struct_alignment + m_struct_vars->m_struct_size,
1279                                                           lldb::ePermissionsReadable | lldb::ePermissionsWritable,
1280                                                           err);
1281
1282        if (mem == LLDB_INVALID_ADDRESS)
1283            return false;
1284
1285        m_material_vars->m_allocated_area = mem;
1286    }
1287
1288    m_material_vars->m_materialized_location = m_material_vars->m_allocated_area;
1289
1290    if (m_material_vars->m_materialized_location % m_struct_vars->m_struct_alignment)
1291        m_material_vars->m_materialized_location += (m_struct_vars->m_struct_alignment - (m_material_vars->m_materialized_location % m_struct_vars->m_struct_alignment));
1292
1293    for (uint64_t member_index = 0, num_members = m_struct_members.GetSize();
1294         member_index < num_members;
1295         ++member_index)
1296    {
1297        ClangExpressionVariableSP member_sp(m_struct_members.GetVariableAtIndex(member_index));
1298
1299        if (m_found_entities.ContainsVariable (member_sp))
1300        {
1301            RegisterInfo *reg_info = member_sp->GetRegisterInfo ();
1302            if (reg_info)
1303            {
1304                // This is a register variable
1305
1306                RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
1307
1308                if (!reg_ctx)
1309                    return false;
1310
1311                if (!DoMaterializeOneRegister (dematerialize,
1312                                               exe_ctx,
1313                                               *reg_ctx,
1314                                               *reg_info,
1315                                               m_material_vars->m_materialized_location + member_sp->m_jit_vars->m_offset,
1316                                               err))
1317                    return false;
1318            }
1319            else
1320            {
1321                if (!member_sp->m_jit_vars.get())
1322                    return false;
1323
1324                if (!DoMaterializeOneVariable (dematerialize,
1325                                               exe_ctx,
1326                                               sym_ctx,
1327                                               member_sp,
1328                                               m_material_vars->m_materialized_location + member_sp->m_jit_vars->m_offset,
1329                                               err))
1330                    return false;
1331            }
1332        }
1333        else
1334        {
1335            // No need to look for presistent variables if the name doesn't start
1336            // with with a '$' character...
1337            if (member_sp->GetName().AsCString ("!")[0] == '$' && persistent_vars.ContainsVariable(member_sp))
1338            {
1339
1340                if (member_sp->GetName() == m_struct_vars->m_result_name)
1341                {
1342                    if (log)
1343                        log->PutCString("Found result member in the struct");
1344
1345                    if (result_sp_ptr)
1346                        *result_sp_ptr = member_sp;
1347
1348                }
1349
1350                if (!DoMaterializeOnePersistentVariable (dematerialize,
1351                                                         exe_ctx,
1352                                                         member_sp,
1353                                                         m_material_vars->m_materialized_location + member_sp->m_jit_vars->m_offset,
1354                                                         stack_frame_top,
1355                                                         stack_frame_bottom,
1356                                                         err))
1357                    return false;
1358            }
1359            else
1360            {
1361                err.SetErrorStringWithFormat("Unexpected variable %s", member_sp->GetName().GetCString());
1362                return false;
1363            }
1364        }
1365    }
1366
1367    return true;
1368}
1369
1370bool
1371ClangExpressionDeclMap::DoMaterializeOnePersistentVariable
1372(
1373    bool dematerialize,
1374    ExecutionContext &exe_ctx,
1375    ClangExpressionVariableSP &var_sp,
1376    lldb::addr_t addr,
1377    lldb::addr_t stack_frame_top,
1378    lldb::addr_t stack_frame_bottom,
1379    Error &err
1380)
1381{
1382    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1383
1384    if (!var_sp)
1385    {
1386        err.SetErrorString("Invalid persistent variable");
1387        return LLDB_INVALID_ADDRESS;
1388    }
1389
1390    const size_t pvar_byte_size = var_sp->GetByteSize();
1391
1392    uint8_t *pvar_data = var_sp->GetValueBytes();
1393    if (pvar_data == NULL)
1394        return false;
1395
1396    Error error;
1397    Process *process = exe_ctx.GetProcessPtr();
1398
1399    lldb::addr_t mem; // The address of a spare memory area used to hold the persistent variable.
1400
1401    if (dematerialize)
1402    {
1403        if (log)
1404            log->Printf("Dematerializing persistent variable with flags 0x%hx", var_sp->m_flags);
1405
1406        if ((var_sp->m_flags & ClangExpressionVariable::EVIsLLDBAllocated) ||
1407            (var_sp->m_flags & ClangExpressionVariable::EVIsProgramReference))
1408        {
1409            // Get the location of the target out of the struct.
1410
1411            Error read_error;
1412            mem = process->ReadPointerFromMemory (addr, read_error);
1413
1414            if (mem == LLDB_INVALID_ADDRESS)
1415            {
1416                err.SetErrorStringWithFormat("Couldn't read address of %s from struct: %s", var_sp->GetName().GetCString(), error.AsCString());
1417                return false;
1418            }
1419
1420            if (var_sp->m_flags & ClangExpressionVariable::EVIsProgramReference &&
1421                !var_sp->m_live_sp)
1422            {
1423                // If the reference comes from the program, then the ClangExpressionVariable's
1424                // live variable data hasn't been set up yet.  Do this now.
1425
1426                var_sp->m_live_sp = ValueObjectConstResult::Create (exe_ctx.GetBestExecutionContextScope (),
1427                                                                    var_sp->GetTypeFromUser().GetASTContext(),
1428                                                                    var_sp->GetTypeFromUser().GetOpaqueQualType(),
1429                                                                    var_sp->GetName(),
1430                                                                    mem,
1431                                                                    eAddressTypeLoad,
1432                                                                    pvar_byte_size);
1433            }
1434
1435            if (!var_sp->m_live_sp)
1436            {
1437                err.SetErrorStringWithFormat("Couldn't find the memory area used to store %s", var_sp->GetName().GetCString());
1438                return false;
1439            }
1440
1441            if (var_sp->m_live_sp->GetValue().GetValueAddressType() != eAddressTypeLoad)
1442            {
1443                err.SetErrorStringWithFormat("The address of the memory area for %s is in an incorrect format", var_sp->GetName().GetCString());
1444                return false;
1445            }
1446
1447            if (var_sp->m_flags & ClangExpressionVariable::EVNeedsFreezeDry ||
1448                var_sp->m_flags & ClangExpressionVariable::EVKeepInTarget)
1449            {
1450                mem = var_sp->m_live_sp->GetValue().GetScalar().ULongLong();
1451
1452                if (log)
1453                    log->Printf("Dematerializing %s from 0x%llx", var_sp->GetName().GetCString(), (uint64_t)mem);
1454
1455                // Read the contents of the spare memory area
1456
1457                var_sp->ValueUpdated ();
1458                if (process->ReadMemory (mem, pvar_data, pvar_byte_size, error) != pvar_byte_size)
1459                {
1460                    err.SetErrorStringWithFormat ("Couldn't read a composite type from the target: %s", error.AsCString());
1461                    return false;
1462                }
1463
1464                if (stack_frame_top != LLDB_INVALID_ADDRESS &&
1465                    stack_frame_bottom != LLDB_INVALID_ADDRESS &&
1466                    mem >= stack_frame_bottom &&
1467                    mem <= stack_frame_top)
1468                {
1469                    // If the variable is resident in the stack frame created by the expression,
1470                    // then it cannot be relied upon to stay around.  We treat it as needing
1471                    // reallocation.
1472
1473                    var_sp->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
1474                    var_sp->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
1475                    var_sp->m_flags &= ~ClangExpressionVariable::EVIsProgramReference;
1476                }
1477
1478                var_sp->m_flags &= ~ClangExpressionVariable::EVNeedsFreezeDry;
1479            }
1480
1481            if (var_sp->m_flags & ClangExpressionVariable::EVNeedsAllocation &&
1482                !(var_sp->m_flags & ClangExpressionVariable::EVKeepInTarget))
1483            {
1484                if (m_keep_result_in_memory)
1485                {
1486                    var_sp->m_flags |= ClangExpressionVariable::EVKeepInTarget;
1487                }
1488                else
1489                {
1490                    Error deallocate_error = process->DeallocateMemory(mem);
1491
1492                    if (!err.Success())
1493                    {
1494                        err.SetErrorStringWithFormat ("Couldn't deallocate memory for %s: %s", var_sp->GetName().GetCString(), deallocate_error.AsCString());
1495                        return false;
1496                    }
1497                }
1498            }
1499        }
1500        else
1501        {
1502            err.SetErrorStringWithFormat("Persistent variables without separate allocations are not currently supported.");
1503            return false;
1504        }
1505    }
1506    else
1507    {
1508        if (log)
1509            log->Printf("Materializing persistent variable with flags 0x%hx", var_sp->m_flags);
1510
1511        if (var_sp->m_flags & ClangExpressionVariable::EVNeedsAllocation)
1512        {
1513            // Allocate a spare memory area to store the persistent variable's contents.
1514
1515            Error allocate_error;
1516
1517            mem = process->AllocateMemory(pvar_byte_size,
1518                                                  lldb::ePermissionsReadable | lldb::ePermissionsWritable,
1519                                                  allocate_error);
1520
1521            if (mem == LLDB_INVALID_ADDRESS)
1522            {
1523                err.SetErrorStringWithFormat("Couldn't allocate a memory area to store %s: %s", var_sp->GetName().GetCString(), allocate_error.AsCString());
1524                return false;
1525            }
1526
1527            if (log)
1528                log->Printf("Allocated %s (0x%llx) sucessfully", var_sp->GetName().GetCString(), mem);
1529
1530            // Put the location of the spare memory into the live data of the ValueObject.
1531
1532            var_sp->m_live_sp = ValueObjectConstResult::Create (exe_ctx.GetBestExecutionContextScope(),
1533                                                                var_sp->GetTypeFromUser().GetASTContext(),
1534                                                                var_sp->GetTypeFromUser().GetOpaqueQualType(),
1535                                                                var_sp->GetName(),
1536                                                                mem,
1537                                                                eAddressTypeLoad,
1538                                                                pvar_byte_size);
1539
1540            // Clear the flag if the variable will never be deallocated.
1541
1542            if (var_sp->m_flags & ClangExpressionVariable::EVKeepInTarget)
1543                var_sp->m_flags &= ~ClangExpressionVariable::EVNeedsAllocation;
1544
1545            // Write the contents of the variable to the area.
1546
1547            if (process->WriteMemory (mem, pvar_data, pvar_byte_size, error) != pvar_byte_size)
1548            {
1549                err.SetErrorStringWithFormat ("Couldn't write a composite type to the target: %s", error.AsCString());
1550                return false;
1551            }
1552        }
1553
1554        if ((var_sp->m_flags & ClangExpressionVariable::EVIsProgramReference && var_sp->m_live_sp) ||
1555            var_sp->m_flags & ClangExpressionVariable::EVIsLLDBAllocated)
1556        {
1557            // Now write the location of the area into the struct.
1558            Error write_error;
1559            if (!process->WriteScalarToMemory (addr,
1560                                                       var_sp->m_live_sp->GetValue().GetScalar(),
1561                                                       process->GetAddressByteSize(),
1562                                                       write_error))
1563            {
1564                err.SetErrorStringWithFormat ("Couldn't write %s to the target: %s", var_sp->GetName().GetCString(), write_error.AsCString());
1565                return false;
1566            }
1567
1568            if (log)
1569                log->Printf("Materialized %s into 0x%llx", var_sp->GetName().GetCString(), var_sp->m_live_sp->GetValue().GetScalar().ULongLong());
1570        }
1571        else if (!(var_sp->m_flags & ClangExpressionVariable::EVIsProgramReference))
1572        {
1573            err.SetErrorStringWithFormat("Persistent variables without separate allocations are not currently supported.");
1574            return false;
1575        }
1576    }
1577
1578    return true;
1579}
1580
1581bool
1582ClangExpressionDeclMap::DoMaterializeOneVariable
1583(
1584    bool dematerialize,
1585    ExecutionContext &exe_ctx,
1586    const SymbolContext &sym_ctx,
1587    ClangExpressionVariableSP &expr_var,
1588    lldb::addr_t addr,
1589    Error &err
1590)
1591{
1592    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1593    Target *target = exe_ctx.GetTargetPtr();
1594    Process *process = exe_ctx.GetProcessPtr();
1595    StackFrame *frame = exe_ctx.GetFramePtr();
1596
1597    if (!frame || !process || !target || !m_parser_vars.get() || !expr_var->m_parser_vars.get())
1598        return false;
1599
1600    // Vital information about the value
1601
1602    const ConstString &name(expr_var->GetName());
1603    TypeFromUser type(expr_var->GetTypeFromUser());
1604
1605    VariableSP &var(expr_var->m_parser_vars->m_lldb_var);
1606    lldb_private::Symbol *sym(expr_var->m_parser_vars->m_lldb_sym);
1607
1608    std::auto_ptr<lldb_private::Value> location_value;
1609
1610    if (var)
1611    {
1612        location_value.reset(GetVariableValue(exe_ctx,
1613                                              var,
1614                                              NULL));
1615    }
1616    else if (sym)
1617    {
1618        addr_t location_load_addr = GetSymbolAddress(*target, name);
1619
1620        if (location_load_addr == LLDB_INVALID_ADDRESS)
1621        {
1622            if (log)
1623                err.SetErrorStringWithFormat ("Couldn't find value for global symbol %s",
1624                                              name.GetCString());
1625        }
1626
1627        location_value.reset(new Value);
1628
1629        location_value->SetValueType(Value::eValueTypeLoadAddress);
1630        location_value->GetScalar() = location_load_addr;
1631    }
1632    else
1633    {
1634        err.SetErrorStringWithFormat ("Couldn't find %s with appropriate type",
1635                                      name.GetCString());
1636        return false;
1637    }
1638
1639    if (log)
1640    {
1641        StreamString my_stream_string;
1642
1643        ClangASTType::DumpTypeDescription (type.GetASTContext(),
1644                                           type.GetOpaqueQualType(),
1645                                           &my_stream_string);
1646
1647        log->Printf ("%s %s with type %s",
1648                     dematerialize ? "Dematerializing" : "Materializing",
1649                     name.GetCString(),
1650                     my_stream_string.GetString().c_str());
1651    }
1652
1653    if (!location_value.get())
1654    {
1655        err.SetErrorStringWithFormat("Couldn't get value for %s", name.GetCString());
1656        return false;
1657    }
1658
1659    // The size of the type contained in addr
1660
1661    size_t value_bit_size = ClangASTType::GetClangTypeBitWidth(type.GetASTContext(), type.GetOpaqueQualType());
1662    size_t value_byte_size = value_bit_size % 8 ? ((value_bit_size + 8) / 8) : (value_bit_size / 8);
1663
1664    Value::ValueType value_type = location_value->GetValueType();
1665
1666    switch (value_type)
1667    {
1668    default:
1669        {
1670            StreamString ss;
1671
1672            location_value->Dump(&ss);
1673
1674            err.SetErrorStringWithFormat ("%s has a value of unhandled type: %s",
1675                                          name.GetCString(),
1676                                          ss.GetString().c_str());
1677            return false;
1678        }
1679        break;
1680    case Value::eValueTypeLoadAddress:
1681        {
1682            if (!dematerialize)
1683            {
1684                Error write_error;
1685
1686                if (!process->WriteScalarToMemory (addr,
1687                                                           location_value->GetScalar(),
1688                                                           process->GetAddressByteSize(),
1689                                                           write_error))
1690                {
1691                    err.SetErrorStringWithFormat ("Couldn't write %s to the target: %s",
1692                                                  name.GetCString(),
1693                                                  write_error.AsCString());
1694                    return false;
1695                }
1696            }
1697        }
1698        break;
1699    case Value::eValueTypeScalar:
1700        {
1701            if (location_value->GetContextType() != Value::eContextTypeRegisterInfo)
1702            {
1703                StreamString ss;
1704                location_value->Dump(&ss);
1705
1706                err.SetErrorStringWithFormat ("%s is a scalar of unhandled type: %s",
1707                                              name.GetCString(),
1708                                              ss.GetString().c_str());
1709                return false;
1710            }
1711
1712            RegisterInfo *reg_info = location_value->GetRegisterInfo();
1713
1714            if (!reg_info)
1715            {
1716                err.SetErrorStringWithFormat ("Couldn't get the register information for %s",
1717                                              name.GetCString());
1718                return false;
1719            }
1720
1721            RegisterValue reg_value;
1722
1723            RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
1724
1725            if (!reg_ctx)
1726            {
1727                err.SetErrorStringWithFormat ("Couldn't read register context to read %s from %s",
1728                                              name.GetCString(),
1729                                              reg_info->name);
1730                return false;
1731            }
1732
1733            uint32_t register_byte_size = reg_info->byte_size;
1734
1735            if (dematerialize)
1736            {
1737                // Get the location of the spare memory area out of the variable's live data.
1738
1739                if (!expr_var->m_live_sp)
1740                {
1741                    err.SetErrorStringWithFormat("Couldn't find the memory area used to store %s", name.GetCString());
1742                    return false;
1743                }
1744
1745                if (expr_var->m_live_sp->GetValue().GetValueAddressType() != eAddressTypeLoad)
1746                {
1747                    err.SetErrorStringWithFormat("The address of the memory area for %s is in an incorrect format", name.GetCString());
1748                    return false;
1749                }
1750
1751                Scalar &reg_addr = expr_var->m_live_sp->GetValue().GetScalar();
1752
1753                err = reg_ctx->ReadRegisterValueFromMemory (reg_info,
1754                                                            reg_addr.ULongLong(),
1755                                                            value_byte_size,
1756                                                            reg_value);
1757                if (err.Fail())
1758                    return false;
1759
1760                if (!reg_ctx->WriteRegister (reg_info, reg_value))
1761                {
1762                    err.SetErrorStringWithFormat ("Couldn't write %s to register %s",
1763                                                  name.GetCString(),
1764                                                  reg_info->name);
1765                    return false;
1766                }
1767
1768                // Deallocate the spare area and clear the variable's live data.
1769
1770                Error deallocate_error = process->DeallocateMemory(reg_addr.ULongLong());
1771
1772                if (!deallocate_error.Success())
1773                {
1774                    err.SetErrorStringWithFormat ("Couldn't deallocate spare memory area for %s: %s",
1775                                                  name.GetCString(),
1776                                                  deallocate_error.AsCString());
1777                    return false;
1778                }
1779
1780                expr_var->m_live_sp.reset();
1781            }
1782            else
1783            {
1784                // Allocate a spare memory area to place the register's contents into.  This memory area will be pointed to by the slot in the
1785                // struct.
1786
1787                Error allocate_error;
1788
1789                Scalar reg_addr (process->AllocateMemory (value_byte_size,
1790                                                                  lldb::ePermissionsReadable | lldb::ePermissionsWritable,
1791                                                                  allocate_error));
1792
1793                if (reg_addr.ULongLong() == LLDB_INVALID_ADDRESS)
1794                {
1795                    err.SetErrorStringWithFormat ("Couldn't allocate a memory area to store %s: %s",
1796                                                  name.GetCString(),
1797                                                  allocate_error.AsCString());
1798                    return false;
1799                }
1800
1801                // Put the location of the spare memory into the live data of the ValueObject.
1802
1803                expr_var->m_live_sp = ValueObjectConstResult::Create (exe_ctx.GetBestExecutionContextScope(),
1804                                                                      type.GetASTContext(),
1805                                                                      type.GetOpaqueQualType(),
1806                                                                      name,
1807                                                                      reg_addr.ULongLong(),
1808                                                                      eAddressTypeLoad,
1809                                                                      value_byte_size);
1810
1811                // Now write the location of the area into the struct.
1812
1813                Error write_error;
1814
1815                if (!process->WriteScalarToMemory (addr,
1816                                                           reg_addr,
1817                                                           process->GetAddressByteSize(),
1818                                                           write_error))
1819                {
1820                    err.SetErrorStringWithFormat ("Couldn't write %s to the target: %s",
1821                                                  name.GetCString(),
1822                                                  write_error.AsCString());
1823                    return false;
1824                }
1825
1826                if (value_byte_size > register_byte_size)
1827                {
1828                    err.SetErrorStringWithFormat ("%s is too big to store in %s",
1829                                                  name.GetCString(),
1830                                                  reg_info->name);
1831                    return false;
1832                }
1833
1834                RegisterValue reg_value;
1835
1836                if (!reg_ctx->ReadRegister (reg_info, reg_value))
1837                {
1838                    err.SetErrorStringWithFormat ("Couldn't read %s from %s",
1839                                                  name.GetCString(),
1840                                                  reg_info->name);
1841                    return false;
1842                }
1843
1844                err = reg_ctx->WriteRegisterValueToMemory (reg_info,
1845                                                           reg_addr.ULongLong(),
1846                                                           value_byte_size,
1847                                                           reg_value);
1848                if (err.Fail())
1849                    return false;
1850            }
1851        }
1852    }
1853
1854    return true;
1855}
1856
1857bool
1858ClangExpressionDeclMap::DoMaterializeOneRegister
1859(
1860    bool dematerialize,
1861    ExecutionContext &exe_ctx,
1862    RegisterContext &reg_ctx,
1863    const RegisterInfo &reg_info,
1864    lldb::addr_t addr,
1865    Error &err
1866)
1867{
1868    uint32_t register_byte_size = reg_info.byte_size;
1869    RegisterValue reg_value;
1870    if (dematerialize)
1871    {
1872        Error read_error (reg_ctx.ReadRegisterValueFromMemory(&reg_info, addr, register_byte_size, reg_value));
1873        if (read_error.Fail())
1874        {
1875            err.SetErrorStringWithFormat ("Couldn't read %s from the target: %s", reg_info.name, read_error.AsCString());
1876            return false;
1877        }
1878
1879        if (!reg_ctx.WriteRegister (&reg_info, reg_value))
1880        {
1881            err.SetErrorStringWithFormat("Couldn't write register %s (dematerialize)", reg_info.name);
1882            return false;
1883        }
1884    }
1885    else
1886    {
1887
1888        if (!reg_ctx.ReadRegister(&reg_info, reg_value))
1889        {
1890            err.SetErrorStringWithFormat("Couldn't read %s (materialize)", reg_info.name);
1891            return false;
1892        }
1893
1894        Error write_error (reg_ctx.WriteRegisterValueToMemory(&reg_info, addr, register_byte_size, reg_value));
1895        if (write_error.Fail())
1896        {
1897            err.SetErrorStringWithFormat ("Couldn't write %s to the target: %s", reg_info.name, write_error.AsCString());
1898            return false;
1899        }
1900    }
1901
1902    return true;
1903}
1904
1905lldb::VariableSP
1906ClangExpressionDeclMap::FindVariableInScope
1907(
1908    StackFrame &frame,
1909    const ConstString &name,
1910    TypeFromUser *type
1911)
1912{
1913    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1914
1915    ValueObjectSP valobj;
1916    VariableSP var_sp;
1917    Error err;
1918
1919    valobj = frame.GetValueForVariableExpressionPath(name.GetCString(),
1920                                                     eNoDynamicValues,
1921                                                     StackFrame::eExpressionPathOptionCheckPtrVsMember,
1922                                                     var_sp,
1923                                                     err);
1924
1925    if (!err.Success() ||
1926        !var_sp ||
1927        !var_sp->IsInScope(&frame) ||
1928        !var_sp->LocationIsValidForFrame (&frame))
1929        return lldb::VariableSP();
1930
1931    if (var_sp && type)
1932    {
1933        if (type->GetASTContext() == var_sp->GetType()->GetClangAST())
1934        {
1935            if (!ClangASTContext::AreTypesSame(type->GetASTContext(), type->GetOpaqueQualType(), var_sp->GetType()->GetClangFullType()))
1936                return lldb::VariableSP();
1937        }
1938        else
1939        {
1940            if (log)
1941                log->PutCString("Skipping a candidate variable because of different AST contexts");
1942            return lldb::VariableSP();
1943        }
1944    }
1945
1946    return var_sp;
1947}
1948
1949Symbol *
1950ClangExpressionDeclMap::FindGlobalDataSymbol
1951(
1952    Target &target,
1953    const ConstString &name
1954)
1955{
1956    SymbolContextList sc_list;
1957
1958    target.GetImages().FindSymbolsWithNameAndType(name,
1959                                                  eSymbolTypeData,
1960                                                  sc_list);
1961
1962    if (sc_list.GetSize())
1963    {
1964        SymbolContext sym_ctx;
1965        sc_list.GetContextAtIndex(0, sym_ctx);
1966
1967        return sym_ctx.symbol;
1968    }
1969
1970    return NULL;
1971}
1972
1973lldb::VariableSP
1974ClangExpressionDeclMap::FindGlobalVariable
1975(
1976    Target &target,
1977    ModuleSP &module,
1978    const ConstString &name,
1979    ClangNamespaceDecl *namespace_decl,
1980    TypeFromUser *type
1981)
1982{
1983    VariableList vars;
1984
1985    if (module && namespace_decl)
1986        module->FindGlobalVariables (name, namespace_decl, true, -1, vars);
1987    else
1988        target.GetImages().FindGlobalVariables(name, true, -1, vars);
1989
1990    if (vars.GetSize())
1991    {
1992        if (type)
1993        {
1994            for (size_t i = 0; i < vars.GetSize(); ++i)
1995            {
1996                VariableSP var_sp = vars.GetVariableAtIndex(i);
1997
1998                if (type->GetASTContext() == var_sp->GetType()->GetClangAST())
1999                {
2000                    if (ClangASTContext::AreTypesSame(type->GetASTContext(), type->GetOpaqueQualType(), var_sp->GetType()->GetClangFullType()))
2001                        return var_sp;
2002                }
2003            }
2004        }
2005        else
2006        {
2007            return vars.GetVariableAtIndex(0);
2008        }
2009    }
2010
2011    return VariableSP();
2012}
2013
2014// Interface for ClangASTSource
2015
2016void
2017ClangExpressionDeclMap::FindExternalVisibleDecls (NameSearchContext &context, const ConstString &name)
2018{
2019    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2020
2021    if (m_parser_vars->m_ignore_lookups)
2022    {
2023        if (log && log->GetVerbose())
2024            log->Printf("Ignoring a query during an import");
2025        return;
2026    }
2027
2028    static unsigned int invocation_id = 0;
2029    unsigned int current_id = invocation_id++;
2030
2031    if (log)
2032    {
2033        if (!context.m_decl_context)
2034            log->Printf("FindExternalVisibleDecls[%u] for '%s' in a NULL DeclContext", current_id, name.GetCString());
2035        else if (const NamedDecl *context_named_decl = dyn_cast<NamedDecl>(context.m_decl_context))
2036            log->Printf("FindExternalVisibleDecls[%u] for '%s' in '%s'", current_id, name.GetCString(), context_named_decl->getNameAsString().c_str());
2037        else
2038            log->Printf("FindExternalVisibleDecls[%u] for '%s' in a '%s'", current_id, name.GetCString(), context.m_decl_context->getDeclKindName());
2039    }
2040
2041    context.m_namespace_map.reset(new ClangASTImporter::NamespaceMap);
2042
2043    if (const NamespaceDecl *namespace_context = dyn_cast<NamespaceDecl>(context.m_decl_context))
2044    {
2045        ClangASTImporter::NamespaceMapSP namespace_map = m_parser_vars->m_ast_importer->GetNamespaceMap(namespace_context);
2046
2047        if (log && log->GetVerbose())
2048            log->Printf("  FEVD[%u] Inspecting namespace map %p (%d entries)",
2049                        current_id,
2050                        namespace_map.get(),
2051                        (int)namespace_map->size());
2052
2053        for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(), e = namespace_map->end();
2054             i != e;
2055             ++i)
2056        {
2057            if (log)
2058                log->Printf("  FEVD[%u] Searching namespace %s in module %s",
2059                            current_id,
2060                            i->second.GetNamespaceDecl()->getNameAsString().c_str(),
2061                            i->first->GetFileSpec().GetFilename().GetCString());
2062
2063            FindExternalVisibleDecls(context,
2064                                     i->first,
2065                                     i->second,
2066                                     name,
2067                                     current_id);
2068        }
2069    }
2070    else if (!isa<TranslationUnitDecl>(context.m_decl_context))
2071    {
2072        // we shouldn't be getting FindExternalVisibleDecls calls for these
2073        return;
2074    }
2075    else
2076    {
2077        ClangNamespaceDecl namespace_decl;
2078
2079        if (log)
2080            log->Printf("  FEVD[%u] Searching the root namespace", current_id);
2081
2082        FindExternalVisibleDecls(context,
2083                                 lldb::ModuleSP(),
2084                                 namespace_decl,
2085                                 name,
2086                                 current_id);
2087    }
2088
2089    if (!context.m_namespace_map->empty())
2090    {
2091        if (log && log->GetVerbose())
2092            log->Printf("  FEVD[%u] Registering namespace map %p (%d entries)",
2093                        current_id,
2094                        context.m_namespace_map.get(),
2095                        (int)context.m_namespace_map->size());
2096
2097        NamespaceDecl *clang_namespace_decl = AddNamespace(context, context.m_namespace_map);
2098
2099        if (clang_namespace_decl)
2100            clang_namespace_decl->setHasExternalVisibleStorage();
2101    }
2102}
2103
2104void
2105ClangExpressionDeclMap::FindExternalVisibleDecls (NameSearchContext &context,
2106                                                  lldb::ModuleSP module_sp,
2107                                                  ClangNamespaceDecl &namespace_decl,
2108                                                  const ConstString &name,
2109                                                  unsigned int current_id)
2110{
2111    assert (m_struct_vars.get());
2112    assert (m_parser_vars.get());
2113
2114    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2115
2116    SymbolContextList sc_list;
2117
2118    const char *name_unique_cstr = name.GetCString();
2119
2120    if (name_unique_cstr == NULL)
2121        return;
2122
2123    // Only look for functions by name out in our symbols if the function
2124    // doesn't start with our phony prefix of '$'
2125    Target *target = m_parser_vars->m_exe_ctx->GetTargetPtr();
2126    StackFrame *frame = m_parser_vars->m_exe_ctx->GetFramePtr();
2127    if (name_unique_cstr[0] == '$' && !namespace_decl)
2128    {
2129        static ConstString g_lldb_class_name ("$__lldb_class");
2130
2131        if (name == g_lldb_class_name)
2132        {
2133            // Clang is looking for the type of "this"
2134
2135            if (!frame)
2136                return;
2137
2138            VariableList *vars = frame->GetVariableList(false);
2139
2140            if (!vars)
2141                return;
2142
2143            lldb::VariableSP this_var = vars->FindVariable(ConstString("this"));
2144
2145            if (!this_var ||
2146                !this_var->IsInScope(frame) ||
2147                !this_var->LocationIsValidForFrame (frame))
2148                return;
2149
2150            Type *this_type = this_var->GetType();
2151
2152            if (!this_type)
2153                return;
2154
2155            if (log && log->GetVerbose())
2156            {
2157                log->Printf ("  FEVD[%u] Type for \"this\" is: ", current_id);
2158                StreamString strm;
2159                this_type->Dump(&strm, true);
2160                log->PutCString (strm.GetData());
2161            }
2162
2163            TypeFromUser this_user_type(this_type->GetClangFullType(),
2164                                        this_type->GetClangAST());
2165
2166            m_struct_vars->m_object_pointer_type = this_user_type;
2167
2168            void *pointer_target_type = NULL;
2169
2170            if (!ClangASTContext::IsPointerType(this_user_type.GetOpaqueQualType(),
2171                                                &pointer_target_type))
2172                return;
2173
2174            clang::QualType pointer_target_qual_type = QualType::getFromOpaquePtr(pointer_target_type);
2175
2176            if (pointer_target_qual_type.isConstQualified())
2177                pointer_target_qual_type.removeLocalConst();
2178
2179            TypeFromUser class_user_type(pointer_target_qual_type.getAsOpaquePtr(),
2180                                         this_type->GetClangAST());
2181
2182            if (log)
2183            {
2184                StreamString type_stream;
2185                class_user_type.DumpTypeCode(&type_stream);
2186                type_stream.Flush();
2187                log->Printf("  FEVD[%u] Adding type for $__lldb_class: %s", current_id, type_stream.GetString().c_str());
2188            }
2189
2190            AddOneType(context, class_user_type, true);
2191
2192            return;
2193        }
2194
2195        static ConstString g_lldb_objc_class_name ("$__lldb_objc_class");
2196        if (name == g_lldb_objc_class_name)
2197        {
2198            // Clang is looking for the type of "*self"
2199
2200            if (!frame)
2201                return;
2202
2203            VariableList *vars = frame->GetVariableList(false);
2204
2205            if (!vars)
2206                return;
2207
2208            lldb::VariableSP self_var = vars->FindVariable(ConstString("self"));
2209
2210            if (!self_var ||
2211                !self_var->IsInScope(frame) ||
2212                !self_var->LocationIsValidForFrame (frame))
2213                return;
2214
2215            Type *self_type = self_var->GetType();
2216
2217            if (!self_type)
2218                return;
2219
2220            TypeFromUser self_user_type(self_type->GetClangFullType(),
2221                                        self_type->GetClangAST());
2222
2223            m_struct_vars->m_object_pointer_type = self_user_type;
2224
2225            void *pointer_target_type = NULL;
2226
2227            if (!ClangASTContext::IsPointerType(self_user_type.GetOpaqueQualType(),
2228                                                &pointer_target_type)
2229                || pointer_target_type == NULL)
2230                return;
2231
2232            TypeFromUser class_user_type(pointer_target_type,
2233                                         self_type->GetClangAST());
2234
2235            if (log)
2236            {
2237                StreamString type_stream;
2238                class_user_type.DumpTypeCode(&type_stream);
2239                type_stream.Flush();
2240                log->Printf("  FEVD[%u] Adding type for $__lldb_objc_class: %s", current_id, type_stream.GetString().c_str());
2241            }
2242
2243            AddOneType(context, class_user_type, false);
2244
2245            return;
2246        }
2247
2248        // any other $__lldb names should be weeded out now
2249        if (!::strncmp(name_unique_cstr, "$__lldb", sizeof("$__lldb") - 1))
2250            return;
2251
2252        do
2253        {
2254            if (!target)
2255                break;
2256
2257            ClangASTContext *scratch_clang_ast_context = target->GetScratchClangASTContext();
2258
2259            if (!scratch_clang_ast_context)
2260                break;
2261
2262            ASTContext *scratch_ast_context = scratch_clang_ast_context->getASTContext();
2263
2264            if (!scratch_ast_context)
2265                break;
2266
2267            TypeDecl *ptype_type_decl = m_parser_vars->m_persistent_vars->GetPersistentType(name);
2268
2269            if (!ptype_type_decl)
2270                break;
2271
2272            Decl *parser_ptype_decl = ClangASTContext::CopyDecl(context.GetASTContext(), scratch_ast_context, ptype_type_decl);
2273
2274            if (!parser_ptype_decl)
2275                break;
2276
2277            TypeDecl *parser_ptype_type_decl = dyn_cast<TypeDecl>(parser_ptype_decl);
2278
2279            if (!parser_ptype_type_decl)
2280                break;
2281
2282            if (log)
2283                log->Printf("  FEVD[%u] Found persistent type %s", current_id, name.GetCString());
2284
2285            context.AddNamedDecl(parser_ptype_type_decl);
2286        } while (0);
2287
2288        ClangExpressionVariableSP pvar_sp(m_parser_vars->m_persistent_vars->GetVariable(name));
2289
2290        if (pvar_sp)
2291        {
2292            AddOneVariable(context, pvar_sp, current_id);
2293            return;
2294        }
2295
2296        const char *reg_name(&name.GetCString()[1]);
2297
2298        if (m_parser_vars->m_exe_ctx->GetRegisterContext())
2299        {
2300            const RegisterInfo *reg_info(m_parser_vars->m_exe_ctx->GetRegisterContext()->GetRegisterInfoByName(reg_name));
2301
2302            if (log)
2303                log->Printf("  FEVD[%u] Found register %s", current_id, reg_info->name);
2304
2305            if (reg_info)
2306                AddOneRegister(context, reg_info, current_id);
2307        }
2308    }
2309    else
2310    {
2311        ValueObjectSP valobj;
2312        VariableSP var;
2313        Error err;
2314
2315        if (frame && !namespace_decl)
2316        {
2317            valobj = frame->GetValueForVariableExpressionPath(name_unique_cstr,
2318                                                              eNoDynamicValues,
2319                                                              StackFrame::eExpressionPathOptionCheckPtrVsMember,
2320                                                              var,
2321                                                              err);
2322
2323            // If we found a variable in scope, no need to pull up function names
2324            if (err.Success() && var != NULL)
2325            {
2326                AddOneVariable(context, var, current_id);
2327                context.m_found.variable = true;
2328            }
2329        }
2330        else if (target)
2331        {
2332            var = FindGlobalVariable (*target,
2333                                      module_sp,
2334                                      name,
2335                                      &namespace_decl,
2336                                      NULL);
2337
2338            if (var)
2339            {
2340                AddOneVariable(context, var, current_id);
2341                context.m_found.variable = true;
2342            }
2343        }
2344
2345        if (!context.m_found.variable)
2346        {
2347            const bool include_symbols = true;
2348            const bool append = false;
2349
2350            if (namespace_decl && module_sp)
2351            {
2352                module_sp->FindFunctions(name,
2353                                         &namespace_decl,
2354                                         eFunctionNameTypeBase,
2355                                         include_symbols,
2356                                         append,
2357                                         sc_list);
2358            }
2359            else
2360            {
2361                target->GetImages().FindFunctions(name,
2362                                                  eFunctionNameTypeBase,
2363                                                  include_symbols,
2364                                                  append,
2365                                                  sc_list);
2366            }
2367
2368            if (sc_list.GetSize())
2369            {
2370                Symbol *generic_symbol = NULL;
2371                Symbol *non_extern_symbol = NULL;
2372
2373                for (uint32_t index = 0, num_indices = sc_list.GetSize();
2374                     index < num_indices;
2375                     ++index)
2376                {
2377                    SymbolContext sym_ctx;
2378                    sc_list.GetContextAtIndex(index, sym_ctx);
2379
2380                    if (sym_ctx.function)
2381                    {
2382                        // TODO only do this if it's a C function; C++ functions may be
2383                        // overloaded
2384                        if (!context.m_found.function_with_type_info)
2385                            AddOneFunction(context, sym_ctx.function, NULL, current_id);
2386                        context.m_found.function_with_type_info = true;
2387                        context.m_found.function = true;
2388                    }
2389                    else if (sym_ctx.symbol)
2390                    {
2391                        if (sym_ctx.symbol->IsExternal())
2392                            generic_symbol = sym_ctx.symbol;
2393                        else
2394                            non_extern_symbol = sym_ctx.symbol;
2395                    }
2396                }
2397
2398                if (!context.m_found.function_with_type_info)
2399                {
2400                    if (generic_symbol)
2401                    {
2402                        AddOneFunction (context, NULL, generic_symbol, current_id);
2403                        context.m_found.function = true;
2404                    }
2405                    else if (non_extern_symbol)
2406                    {
2407                        AddOneFunction (context, NULL, non_extern_symbol, current_id);
2408                        context.m_found.function = true;
2409                    }
2410                }
2411            }
2412
2413            if (!context.m_found.variable)
2414            {
2415                // We couldn't find a non-symbol variable for this.  Now we'll hunt for a generic
2416                // data symbol, and -- if it is found -- treat it as a variable.
2417
2418                Symbol *data_symbol = FindGlobalDataSymbol(*target, name);
2419
2420                if (data_symbol)
2421                {
2422                    AddOneGenericVariable(context, *data_symbol, current_id);
2423                    context.m_found.variable = true;
2424                }
2425            }
2426        }
2427
2428        if (module_sp && namespace_decl)
2429        {
2430            ClangNamespaceDecl found_namespace_decl;
2431
2432            SymbolVendor *symbol_vendor = module_sp->GetSymbolVendor();
2433
2434            if (symbol_vendor)
2435            {
2436                SymbolContext null_sc;
2437
2438                found_namespace_decl = symbol_vendor->FindNamespace(null_sc, name, &namespace_decl);
2439
2440                if (found_namespace_decl)
2441                {
2442                    context.m_namespace_map->push_back(std::pair<ModuleSP, ClangNamespaceDecl>(module_sp, found_namespace_decl));
2443
2444                    if (log)
2445                        log->Printf("  FEVD[%u] Found namespace %s in module %s",
2446                                    current_id,
2447                                    name.GetCString(),
2448                                    module_sp->GetFileSpec().GetFilename().GetCString());
2449                }
2450            }
2451        }
2452        else
2453        {
2454            ModuleList &images = m_parser_vars->m_sym_ctx.target_sp->GetImages();
2455
2456            for (uint32_t i = 0, e = images.GetSize();
2457                 i != e;
2458                 ++i)
2459            {
2460                ModuleSP image = images.GetModuleAtIndex(i);
2461
2462                if (!image)
2463                    continue;
2464
2465                ClangNamespaceDecl found_namespace_decl;
2466
2467                SymbolVendor *symbol_vendor = image->GetSymbolVendor();
2468
2469                if (!symbol_vendor)
2470                    continue;
2471
2472                SymbolContext null_sc;
2473
2474                found_namespace_decl = symbol_vendor->FindNamespace(null_sc, name, &namespace_decl);
2475
2476                if (found_namespace_decl)
2477                {
2478                    context.m_namespace_map->push_back(std::pair<ModuleSP, ClangNamespaceDecl>(image, found_namespace_decl));
2479
2480                    if (log)
2481                        log->Printf("  FEVD[%u] Found namespace %s in module %s",
2482                                    current_id,
2483                                    name.GetCString(),
2484                                    image->GetFileSpec().GetFilename().GetCString());
2485                }
2486            }
2487        }
2488    }
2489
2490    TypeList types;
2491    SymbolContext null_sc;
2492
2493    if (module_sp && namespace_decl)
2494        module_sp->FindTypes(null_sc, name, &namespace_decl, true, 1, types);
2495    else
2496        target->GetImages().FindTypes (null_sc, name, true, 1, types);
2497
2498    if (types.GetSize())
2499    {
2500        TypeSP type_sp = types.GetTypeAtIndex(0);
2501
2502        if (log)
2503        {
2504            const char *name_string = type_sp->GetName().GetCString();
2505
2506            log->Printf("  FEVD[%u] Matching type found for \"%s\": %s",
2507                        current_id,
2508                        name.GetCString(),
2509                        (name_string ? name_string : "<anonymous>"));
2510        }
2511
2512        TypeFromUser user_type(type_sp->GetClangFullType(),
2513                               type_sp->GetClangAST());
2514
2515        AddOneType(context, user_type, false);
2516    }
2517}
2518
2519clang::ExternalLoadResult
2520ClangExpressionDeclMap::FindExternalLexicalDecls (const DeclContext *decl_context,
2521                                                  bool (*predicate)(Decl::Kind),
2522                                                  llvm::SmallVectorImpl<Decl*> &decls)
2523{
2524    assert (m_parser_vars.get());
2525
2526    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2527
2528    const Decl *context_decl = dyn_cast<Decl>(decl_context);
2529
2530    if (!context_decl)
2531        return ELR_Failure;
2532
2533    ASTContext *ast_context = &context_decl->getASTContext();
2534
2535    static unsigned int invocation_id = 0;
2536    unsigned int current_id = invocation_id++;
2537
2538    if (log)
2539    {
2540        if (const NamedDecl *context_named_decl = dyn_cast<NamedDecl>(context_decl))
2541            log->Printf("FindExternalLexicalDecls[%u] in '%s' (a %s) with %s predicate",
2542                        current_id,
2543                        context_named_decl->getNameAsString().c_str(),
2544                        context_decl->getDeclKindName(),
2545                        (predicate ? "non-null" : "null"));
2546        else if(context_decl)
2547            log->Printf("FindExternalLexicalDecls[%u] in a %s with %s predicate",
2548                        current_id,
2549                        context_decl->getDeclKindName(),
2550                        (predicate ? "non-null" : "null"));
2551        else
2552            log->Printf("FindExternalLexicalDecls[%u] in a NULL context with %s predicate",
2553                        current_id,
2554                        (predicate ? "non-null" : "null"));
2555    }
2556
2557    Decl *original_decl = NULL;
2558    ASTContext *original_ctx = NULL;
2559
2560    ClangASTImporter *ast_importer = m_parser_vars->GetASTImporter(ast_context);
2561
2562    if (!ast_importer)
2563        return ELR_Failure;
2564
2565    if (!ast_importer->ResolveDeclOrigin(context_decl, &original_decl, &original_ctx))
2566        return ELR_Failure;
2567
2568    if (log)
2569    {
2570        std::string decl_print_string;
2571        llvm::raw_string_ostream decl_print_stream(decl_print_string);
2572        original_decl->print(decl_print_stream);
2573        decl_print_stream.flush();
2574        log->Printf("  FELD[%u] Original decl:\n%s", current_id, decl_print_string.c_str());
2575    }
2576
2577    if (TagDecl *original_tag_decl = dyn_cast<TagDecl>(original_decl))
2578    {
2579        ExternalASTSource *external_source = original_ctx->getExternalSource();
2580
2581        if (external_source)
2582            external_source->CompleteType (original_tag_decl);
2583    }
2584
2585    DeclContext *original_decl_context = dyn_cast<DeclContext>(original_decl);
2586
2587    if (!original_decl_context)
2588        return ELR_Failure;
2589
2590    for (TagDecl::decl_iterator iter = original_decl_context->decls_begin();
2591         iter != original_decl_context->decls_end();
2592         ++iter)
2593    {
2594        Decl *decl = *iter;
2595
2596        if (!predicate || predicate(decl->getKind()))
2597        {
2598            if (log)
2599            {
2600                std::string decl_print_string;
2601                llvm::raw_string_ostream decl_print_stream(decl_print_string);
2602                decl->print(decl_print_stream);
2603                decl_print_stream.flush();
2604
2605                if (const NamedDecl *context_named_decl = dyn_cast<NamedDecl>(context_decl))
2606                    log->Printf("  FELD[%d] Adding [to %s] lexical decl %s", current_id, context_named_decl->getNameAsString().c_str(), decl_print_string.c_str());
2607                else
2608                    log->Printf("  FELD[%d] Adding lexical decl %s", current_id, decl_print_string.c_str());
2609            }
2610
2611            Decl *copied_decl = ast_importer->CopyDecl(original_ctx, decl);
2612
2613            decls.push_back(copied_decl);
2614        }
2615    }
2616
2617    return ELR_AlreadyLoaded;
2618}
2619
2620void
2621ClangExpressionDeclMap::CompleteTagDecl (TagDecl *tag_decl)
2622{
2623    assert (m_parser_vars.get());
2624
2625    m_parser_vars->GetASTImporter(&tag_decl->getASTContext())->CompleteTagDecl (tag_decl);
2626}
2627
2628void
2629ClangExpressionDeclMap::CompleteObjCInterfaceDecl (clang::ObjCInterfaceDecl *interface_decl)
2630{
2631    assert (m_parser_vars.get());
2632
2633    m_parser_vars->GetASTImporter(&interface_decl->getASTContext())->CompleteObjCInterfaceDecl (interface_decl);
2634}
2635
2636Value *
2637ClangExpressionDeclMap::GetVariableValue
2638(
2639    ExecutionContext &exe_ctx,
2640    VariableSP &var,
2641    ASTContext *parser_ast_context,
2642    TypeFromUser *user_type,
2643    TypeFromParser *parser_type
2644)
2645{
2646    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2647
2648    Type *var_type = var->GetType();
2649
2650    if (!var_type)
2651    {
2652        if (log)
2653            log->PutCString("Skipped a definition because it has no type");
2654        return NULL;
2655    }
2656
2657    clang_type_t var_opaque_type = var_type->GetClangFullType();
2658
2659    if (!var_opaque_type)
2660    {
2661        if (log)
2662            log->PutCString("Skipped a definition because it has no Clang type");
2663        return NULL;
2664    }
2665
2666    ASTContext *ast = var_type->GetClangASTContext().getASTContext();
2667
2668    if (!ast)
2669    {
2670        if (log)
2671            log->PutCString("There is no AST context for the current execution context");
2672        return NULL;
2673    }
2674
2675    DWARFExpression &var_location_expr = var->LocationExpression();
2676
2677    std::auto_ptr<Value> var_location(new Value);
2678
2679    lldb::addr_t loclist_base_load_addr = LLDB_INVALID_ADDRESS;
2680
2681    Target *target = exe_ctx.GetTargetPtr();
2682
2683    if (var_location_expr.IsLocationList())
2684    {
2685        SymbolContext var_sc;
2686        var->CalculateSymbolContext (&var_sc);
2687        loclist_base_load_addr = var_sc.function->GetAddressRange().GetBaseAddress().GetLoadAddress (target);
2688    }
2689    Error err;
2690
2691    if (!var_location_expr.Evaluate(&exe_ctx, ast, NULL, NULL, NULL, loclist_base_load_addr, NULL, *var_location.get(), &err))
2692    {
2693        if (log)
2694            log->Printf("Error evaluating location: %s", err.AsCString());
2695        return NULL;
2696    }
2697
2698    void *type_to_use = NULL;
2699
2700    if (parser_ast_context)
2701    {
2702        type_to_use = GuardedCopyType(parser_ast_context, ast, var_opaque_type);
2703
2704        if (!type_to_use)
2705        {
2706            if (log)
2707                log->Printf("Couldn't copy a variable's type into the parser's AST context");
2708
2709            return NULL;
2710        }
2711
2712        if (parser_type)
2713            *parser_type = TypeFromParser(type_to_use, parser_ast_context);
2714    }
2715    else
2716        type_to_use = var_opaque_type;
2717
2718    if (var_location.get()->GetContextType() == Value::eContextTypeInvalid)
2719        var_location.get()->SetContext(Value::eContextTypeClangType, type_to_use);
2720
2721    if (var_location.get()->GetValueType() == Value::eValueTypeFileAddress)
2722    {
2723        SymbolContext var_sc;
2724        var->CalculateSymbolContext(&var_sc);
2725
2726        if (!var_sc.module_sp)
2727            return NULL;
2728
2729        ObjectFile *object_file = var_sc.module_sp->GetObjectFile();
2730
2731        if (!object_file)
2732            return NULL;
2733
2734        Address so_addr(var_location->GetScalar().ULongLong(), object_file->GetSectionList());
2735
2736        lldb::addr_t load_addr = so_addr.GetLoadAddress(target);
2737
2738        if (load_addr != LLDB_INVALID_ADDRESS)
2739        {
2740            var_location->GetScalar() = load_addr;
2741            var_location->SetValueType(Value::eValueTypeLoadAddress);
2742        }
2743    }
2744
2745    if (user_type)
2746        *user_type = TypeFromUser(var_opaque_type, ast);
2747
2748    return var_location.release();
2749}
2750
2751void
2752ClangExpressionDeclMap::AddOneVariable (NameSearchContext &context, VariableSP var, unsigned int current_id)
2753{
2754    assert (m_parser_vars.get());
2755
2756    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2757
2758    TypeFromUser ut;
2759    TypeFromParser pt;
2760
2761    Value *var_location = GetVariableValue (*m_parser_vars->m_exe_ctx,
2762                                            var,
2763                                            context.GetASTContext(),
2764                                            &ut,
2765                                            &pt);
2766
2767    if (!var_location)
2768        return;
2769
2770    NamedDecl *var_decl = context.AddVarDecl(ClangASTContext::CreateLValueReferenceType(pt.GetASTContext(), pt.GetOpaqueQualType()));
2771    std::string decl_name(context.m_decl_name.getAsString());
2772    ConstString entity_name(decl_name.c_str());
2773    ClangExpressionVariableSP entity(m_found_entities.CreateVariable (m_parser_vars->m_exe_ctx->GetBestExecutionContextScope (),
2774                                                                      entity_name,
2775                                                                      ut,
2776                                                                      m_parser_vars->m_target_info.byte_order,
2777                                                                      m_parser_vars->m_target_info.address_byte_size));
2778    assert (entity.get());
2779    entity->EnableParserVars();
2780    entity->m_parser_vars->m_parser_type = pt;
2781    entity->m_parser_vars->m_named_decl  = var_decl;
2782    entity->m_parser_vars->m_llvm_value  = NULL;
2783    entity->m_parser_vars->m_lldb_value  = var_location;
2784    entity->m_parser_vars->m_lldb_var    = var;
2785
2786    if (log)
2787    {
2788        std::string var_decl_print_string;
2789        llvm::raw_string_ostream var_decl_print_stream(var_decl_print_string);
2790        var_decl->print(var_decl_print_stream);
2791        var_decl_print_stream.flush();
2792
2793        log->Printf("  FEVD[%u] Found variable %s, returned %s", current_id, decl_name.c_str(), var_decl_print_string.c_str());
2794
2795        //if (log->GetVerbose())
2796        //{
2797        //    StreamString var_decl_dump_string;
2798        //    ASTDumper::DumpDecl(var_decl_dump_string, var_decl);
2799        //    log->Printf("%s\n", var_decl_dump_string.GetData());
2800        //}
2801    }
2802}
2803
2804void
2805ClangExpressionDeclMap::AddOneVariable(NameSearchContext &context,
2806                                       ClangExpressionVariableSP &pvar_sp,
2807                                       unsigned int current_id)
2808{
2809    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2810
2811    TypeFromUser user_type (pvar_sp->GetTypeFromUser());
2812
2813    TypeFromParser parser_type (GuardedCopyType(context.GetASTContext(),
2814                                                user_type.GetASTContext(),
2815                                                user_type.GetOpaqueQualType()),
2816                                context.GetASTContext());
2817
2818    NamedDecl *var_decl = context.AddVarDecl(ClangASTContext::CreateLValueReferenceType(parser_type.GetASTContext(), parser_type.GetOpaqueQualType()));
2819
2820    pvar_sp->EnableParserVars();
2821    pvar_sp->m_parser_vars->m_parser_type = parser_type;
2822    pvar_sp->m_parser_vars->m_named_decl  = var_decl;
2823    pvar_sp->m_parser_vars->m_llvm_value  = NULL;
2824    pvar_sp->m_parser_vars->m_lldb_value  = NULL;
2825
2826    if (log)
2827    {
2828        std::string var_decl_print_string;
2829        llvm::raw_string_ostream var_decl_print_stream(var_decl_print_string);
2830        var_decl->print(var_decl_print_stream);
2831        var_decl_print_stream.flush();
2832
2833        log->Printf("  FEVD[%u] Added pvar %s, returned %s", current_id, pvar_sp->GetName().GetCString(), var_decl_print_string.c_str());
2834    }
2835}
2836
2837void
2838ClangExpressionDeclMap::AddOneGenericVariable(NameSearchContext &context,
2839                                              Symbol &symbol,
2840                                              unsigned int current_id)
2841{
2842    assert(m_parser_vars.get());
2843
2844    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2845
2846    Target *target = m_parser_vars->m_exe_ctx->GetTargetPtr();
2847
2848    if (target == NULL)
2849        return;
2850
2851    ASTContext *scratch_ast_context = target->GetScratchClangASTContext()->getASTContext();
2852
2853    TypeFromUser user_type (ClangASTContext::CreateLValueReferenceType(scratch_ast_context, ClangASTContext::GetVoidPtrType(scratch_ast_context, true)),
2854                            scratch_ast_context);
2855
2856    TypeFromParser parser_type (ClangASTContext::CreateLValueReferenceType(scratch_ast_context, ClangASTContext::GetVoidPtrType(context.GetASTContext(), true)),
2857                                context.GetASTContext());
2858
2859    NamedDecl *var_decl = context.AddVarDecl(parser_type.GetOpaqueQualType());
2860
2861    std::string decl_name(context.m_decl_name.getAsString());
2862    ConstString entity_name(decl_name.c_str());
2863    ClangExpressionVariableSP entity(m_found_entities.CreateVariable (m_parser_vars->m_exe_ctx->GetBestExecutionContextScope (),
2864                                                                      entity_name,
2865                                                                      user_type,
2866                                                                      m_parser_vars->m_target_info.byte_order,
2867                                                                      m_parser_vars->m_target_info.address_byte_size));
2868    assert (entity.get());
2869
2870    std::auto_ptr<Value> symbol_location(new Value);
2871
2872    AddressRange &symbol_range = symbol.GetAddressRangeRef();
2873    Address &symbol_address = symbol_range.GetBaseAddress();
2874    lldb::addr_t symbol_load_addr = symbol_address.GetLoadAddress(target);
2875
2876    symbol_location->SetContext(Value::eContextTypeClangType, user_type.GetOpaqueQualType());
2877    symbol_location->GetScalar() = symbol_load_addr;
2878    symbol_location->SetValueType(Value::eValueTypeLoadAddress);
2879
2880    entity->EnableParserVars();
2881    entity->m_parser_vars->m_parser_type = parser_type;
2882    entity->m_parser_vars->m_named_decl  = var_decl;
2883    entity->m_parser_vars->m_llvm_value  = NULL;
2884    entity->m_parser_vars->m_lldb_value  = symbol_location.release();
2885    entity->m_parser_vars->m_lldb_sym    = &symbol;
2886    //entity->m_flags                      |= ClangExpressionVariable::EVUnknownType;
2887
2888    if (log)
2889    {
2890        std::string var_decl_print_string;
2891        llvm::raw_string_ostream var_decl_print_stream(var_decl_print_string);
2892        var_decl->print(var_decl_print_stream);
2893        var_decl_print_stream.flush();
2894
2895        log->Printf("  FEVD[%u] Found variable %s, returned %s", current_id, decl_name.c_str(), var_decl_print_string.c_str());
2896
2897        //if (log->GetVerbose())
2898        //{
2899        //    StreamString var_decl_dump_string;
2900        //    ASTDumper::DumpDecl(var_decl_dump_string, var_decl);
2901        //    log->Printf("%s\n", var_decl_dump_string.GetData());
2902        //}
2903    }
2904}
2905
2906bool
2907ClangExpressionDeclMap::ResolveUnknownTypes()
2908{
2909    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2910    Target *target = m_parser_vars->m_exe_ctx->GetTargetPtr();
2911
2912    ASTContext *scratch_ast_context = target->GetScratchClangASTContext()->getASTContext();
2913
2914    for (size_t index = 0, num_entities = m_found_entities.GetSize();
2915         index < num_entities;
2916         ++index)
2917    {
2918        ClangExpressionVariableSP entity = m_found_entities.GetVariableAtIndex(index);
2919
2920        if (entity->m_flags & ClangExpressionVariable::EVUnknownType)
2921        {
2922            const NamedDecl *named_decl = entity->m_parser_vars->m_named_decl;
2923            const VarDecl *var_decl = dyn_cast<VarDecl>(named_decl);
2924
2925            if (!var_decl)
2926            {
2927                if (log)
2928                    log->Printf("Entity of unknown type does not have a VarDecl");
2929                return false;
2930            }
2931
2932            if (log)
2933            {
2934                std::string var_decl_print_string;
2935                llvm::raw_string_ostream var_decl_print_stream(var_decl_print_string);
2936                var_decl->print(var_decl_print_stream);
2937                var_decl_print_stream.flush();
2938
2939                log->Printf("Variable of unknown type now has Decl %s", var_decl_print_string.c_str());
2940            }
2941
2942            QualType var_type = var_decl->getType();
2943            TypeFromParser parser_type(var_type.getAsOpaquePtr(), &var_decl->getASTContext());
2944
2945            lldb::clang_type_t copied_type = ClangASTContext::CopyType(scratch_ast_context, &var_decl->getASTContext(), var_type.getAsOpaquePtr());
2946
2947            TypeFromUser user_type(copied_type, scratch_ast_context);
2948
2949            entity->m_parser_vars->m_lldb_value->SetContext(Value::eContextTypeClangType, user_type.GetOpaqueQualType());
2950            entity->m_parser_vars->m_parser_type = parser_type;
2951
2952            entity->SetClangAST(user_type.GetASTContext());
2953            entity->SetClangType(user_type.GetOpaqueQualType());
2954
2955            entity->m_flags &= ~(ClangExpressionVariable::EVUnknownType);
2956        }
2957    }
2958
2959    return true;
2960}
2961
2962void
2963ClangExpressionDeclMap::AddOneRegister (NameSearchContext &context,
2964                                        const RegisterInfo *reg_info,
2965                                        unsigned int current_id)
2966{
2967    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2968
2969    void *ast_type = ClangASTContext::GetBuiltinTypeForEncodingAndBitSize(context.GetASTContext(),
2970                                                                          reg_info->encoding,
2971                                                                          reg_info->byte_size * 8);
2972
2973    if (!ast_type)
2974    {
2975        if (log)
2976            log->Printf("  Tried to add a type for %s, but couldn't get one", context.m_decl_name.getAsString().c_str());
2977        return;
2978    }
2979
2980    TypeFromParser parser_type (ast_type,
2981                                context.GetASTContext());
2982
2983    NamedDecl *var_decl = context.AddVarDecl(parser_type.GetOpaqueQualType());
2984
2985    ClangExpressionVariableSP entity(m_found_entities.CreateVariable (m_parser_vars->m_exe_ctx->GetBestExecutionContextScope(),
2986                                                                      m_parser_vars->m_target_info.byte_order,
2987                                                                      m_parser_vars->m_target_info.address_byte_size));
2988    assert (entity.get());
2989    std::string decl_name(context.m_decl_name.getAsString());
2990    entity->SetName (ConstString (decl_name.c_str()));
2991    entity->SetRegisterInfo (reg_info);
2992    entity->EnableParserVars();
2993    entity->m_parser_vars->m_parser_type = parser_type;
2994    entity->m_parser_vars->m_named_decl  = var_decl;
2995    entity->m_parser_vars->m_llvm_value  = NULL;
2996    entity->m_parser_vars->m_lldb_value  = NULL;
2997
2998    if (log && log->GetVerbose())
2999    {
3000        std::string var_decl_print_string;
3001        llvm::raw_string_ostream var_decl_print_stream(var_decl_print_string);
3002        var_decl->print(var_decl_print_stream);
3003        var_decl_print_stream.flush();
3004
3005        log->Printf("  FEVD[%d] Added register %s, returned %s", current_id, context.m_decl_name.getAsString().c_str(), var_decl_print_string.c_str());
3006    }
3007}
3008
3009NamespaceDecl *
3010ClangExpressionDeclMap::AddNamespace (NameSearchContext &context, ClangASTImporter::NamespaceMapSP &namespace_decls)
3011{
3012    if (namespace_decls.empty())
3013        return NULL;
3014
3015    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
3016
3017    assert (m_parser_vars.get());
3018
3019    const ClangNamespaceDecl &namespace_decl = namespace_decls->begin()->second;
3020
3021    Decl *copied_decl = m_parser_vars->GetASTImporter(context.GetASTContext())->CopyDecl(namespace_decl.GetASTContext(),
3022                                                                                         namespace_decl.GetNamespaceDecl());
3023
3024    NamespaceDecl *copied_namespace_decl = dyn_cast<NamespaceDecl>(copied_decl);
3025
3026    m_parser_vars->GetASTImporter(context.GetASTContext())->RegisterNamespaceMap(copied_namespace_decl, namespace_decls);
3027
3028    return dyn_cast<NamespaceDecl>(copied_decl);
3029}
3030
3031void
3032ClangExpressionDeclMap::AddOneFunction (NameSearchContext &context,
3033                                        Function* fun,
3034                                        Symbol* symbol,
3035                                        unsigned int current_id)
3036{
3037    assert (m_parser_vars.get());
3038
3039    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
3040
3041    NamedDecl *fun_decl = NULL;
3042    std::auto_ptr<Value> fun_location(new Value);
3043    const Address *fun_address = NULL;
3044
3045    // only valid for Functions, not for Symbols
3046    void *fun_opaque_type = NULL;
3047    ASTContext *fun_ast_context = NULL;
3048
3049    if (fun)
3050    {
3051        Type *fun_type = fun->GetType();
3052
3053        if (!fun_type)
3054        {
3055            if (log)
3056                log->PutCString("  Skipped a function because it has no type");
3057            return;
3058        }
3059
3060        fun_opaque_type = fun_type->GetClangFullType();
3061
3062        if (!fun_opaque_type)
3063        {
3064            if (log)
3065                log->PutCString("  Skipped a function because it has no Clang type");
3066            return;
3067        }
3068
3069        fun_address = &fun->GetAddressRange().GetBaseAddress();
3070
3071        fun_ast_context = fun_type->GetClangASTContext().getASTContext();
3072        void *copied_type = GuardedCopyType(context.GetASTContext(), fun_ast_context, fun_opaque_type);
3073
3074        fun_decl = context.AddFunDecl(copied_type);
3075    }
3076    else if (symbol)
3077    {
3078        fun_address = &symbol->GetAddressRangeRef().GetBaseAddress();
3079
3080        fun_decl = context.AddGenericFunDecl();
3081    }
3082    else
3083    {
3084        if (log)
3085            log->PutCString("  AddOneFunction called with no function and no symbol");
3086        return;
3087    }
3088
3089    Target *target = m_parser_vars->m_exe_ctx->GetTargetPtr();
3090
3091    lldb::addr_t load_addr = fun_address->GetCallableLoadAddress(target);
3092    fun_location->SetValueType(Value::eValueTypeLoadAddress);
3093    fun_location->GetScalar() = load_addr;
3094
3095    ClangExpressionVariableSP entity(m_found_entities.CreateVariable (m_parser_vars->m_exe_ctx->GetBestExecutionContextScope (),
3096                                                                      m_parser_vars->m_target_info.byte_order,
3097                                                                      m_parser_vars->m_target_info.address_byte_size));
3098    assert (entity.get());
3099    std::string decl_name(context.m_decl_name.getAsString());
3100    entity->SetName(ConstString(decl_name.c_str()));
3101    entity->SetClangType (fun_opaque_type);
3102    entity->SetClangAST (fun_ast_context);
3103
3104    entity->EnableParserVars();
3105    entity->m_parser_vars->m_named_decl  = fun_decl;
3106    entity->m_parser_vars->m_llvm_value  = NULL;
3107    entity->m_parser_vars->m_lldb_value  = fun_location.release();
3108
3109    if (log)
3110    {
3111        std::string fun_decl_print_string;
3112        llvm::raw_string_ostream fun_decl_print_stream(fun_decl_print_string);
3113        fun_decl->print(fun_decl_print_stream);
3114        fun_decl_print_stream.flush();
3115
3116        log->Printf("  FEVD[%u] Found %s function %s, returned %s",
3117                    current_id,
3118                    (fun ? "specific" : "generic"),
3119                    decl_name.c_str(),
3120                    fun_decl_print_string.c_str());
3121    }
3122}
3123
3124void
3125ClangExpressionDeclMap::AddOneType(NameSearchContext &context,
3126                                   TypeFromUser &ut,
3127                                   unsigned int current_id,
3128                                   bool add_method)
3129{
3130    ASTContext *parser_ast_context = context.GetASTContext();
3131    ASTContext *user_ast_context = ut.GetASTContext();
3132
3133    void *copied_type = GuardedCopyType(parser_ast_context, user_ast_context, ut.GetOpaqueQualType());
3134
3135    TypeFromParser parser_type(copied_type, parser_ast_context);
3136
3137    if (add_method && ClangASTContext::IsAggregateType(copied_type))
3138    {
3139        void *args[1];
3140
3141        args[0] = ClangASTContext::GetVoidPtrType(parser_ast_context, false);
3142
3143        void *method_type = ClangASTContext::CreateFunctionType (parser_ast_context,
3144                                                                 ClangASTContext::GetBuiltInType_void(parser_ast_context),
3145                                                                 args,
3146                                                                 1,
3147                                                                 false,
3148                                                                 ClangASTContext::GetTypeQualifiers(copied_type));
3149
3150        const bool is_virtual = false;
3151        const bool is_static = false;
3152        const bool is_inline = false;
3153        const bool is_explicit = false;
3154
3155        ClangASTContext::AddMethodToCXXRecordType (parser_ast_context,
3156                                                   copied_type,
3157                                                   "$__lldb_expr",
3158                                                   method_type,
3159                                                   lldb::eAccessPublic,
3160                                                   is_virtual,
3161                                                   is_static,
3162                                                   is_inline,
3163                                                   is_explicit);
3164    }
3165
3166    context.AddTypeDecl(copied_type);
3167}
3168
3169void *
3170ClangExpressionDeclMap::GuardedCopyType (ASTContext *dest_context,
3171                                         ASTContext *source_context,
3172                                         void *clang_type)
3173{
3174    assert (m_parser_vars.get());
3175
3176    m_parser_vars->m_ignore_lookups = true;
3177
3178    lldb_private::ClangASTImporter *importer = m_parser_vars->GetASTImporter(dest_context);
3179
3180    QualType ret_qual_type = importer->CopyType (source_context,
3181                                                 QualType::getFromOpaquePtr(clang_type));
3182
3183    void *ret = ret_qual_type.getAsOpaquePtr();
3184
3185    m_parser_vars->m_ignore_lookups = false;
3186
3187    return ret;
3188}
3189