ValueObject.cpp revision 1328b1410eb0f5e03c3b3ee302e9adca3e1b0361
1//===-- ValueObject.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/Core/ValueObject.h"
11
12// C Includes
13#include <stdlib.h>
14
15// C++ Includes
16// Other libraries and framework includes
17#include "llvm/Support/raw_ostream.h"
18#include "clang/AST/Type.h"
19
20// Project includes
21#include "lldb/Core/DataBufferHeap.h"
22#include "lldb/Core/DataVisualization.h"
23#include "lldb/Core/Debugger.h"
24#include "lldb/Core/Log.h"
25#include "lldb/Core/StreamString.h"
26#include "lldb/Core/ValueObjectChild.h"
27#include "lldb/Core/ValueObjectConstResult.h"
28#include "lldb/Core/ValueObjectDynamicValue.h"
29#include "lldb/Core/ValueObjectList.h"
30#include "lldb/Core/ValueObjectMemory.h"
31#include "lldb/Core/ValueObjectSyntheticFilter.h"
32
33#include "lldb/Host/Endian.h"
34
35#include "lldb/Interpreter/CommandInterpreter.h"
36#include "lldb/Interpreter/ScriptInterpreterPython.h"
37
38#include "lldb/Symbol/ClangASTType.h"
39#include "lldb/Symbol/ClangASTContext.h"
40#include "lldb/Symbol/Type.h"
41
42#include "lldb/Target/ExecutionContext.h"
43#include "lldb/Target/LanguageRuntime.h"
44#include "lldb/Target/ObjCLanguageRuntime.h"
45#include "lldb/Target/Process.h"
46#include "lldb/Target/RegisterContext.h"
47#include "lldb/Target/Target.h"
48#include "lldb/Target/Thread.h"
49
50#include "lldb/Utility/RefCounter.h"
51
52using namespace lldb;
53using namespace lldb_private;
54using namespace lldb_utility;
55
56static user_id_t g_value_obj_uid = 0;
57
58//----------------------------------------------------------------------
59// ValueObject constructor
60//----------------------------------------------------------------------
61ValueObject::ValueObject (ValueObject &parent) :
62    UserID (++g_value_obj_uid), // Unique identifier for every value object
63    m_parent (&parent),
64    m_update_point (parent.GetUpdatePoint ()),
65    m_name (),
66    m_data (),
67    m_value (),
68    m_error (),
69    m_value_str (),
70    m_old_value_str (),
71    m_location_str (),
72    m_summary_str (),
73    m_object_desc_str (),
74    m_manager(parent.GetManager()),
75    m_children (),
76    m_synthetic_children (),
77    m_dynamic_value (NULL),
78    m_synthetic_value(NULL),
79    m_deref_valobj(NULL),
80    m_format (eFormatDefault),
81    m_last_format_mgr_revision(0),
82    m_last_format_mgr_dynamic(parent.m_last_format_mgr_dynamic),
83    m_last_summary_format(),
84    m_forced_summary_format(),
85    m_last_value_format(),
86    m_last_synthetic_filter(),
87    m_user_id_of_forced_summary(),
88    m_address_type_of_ptr_or_ref_children(eAddressTypeInvalid),
89    m_value_is_valid (false),
90    m_value_did_change (false),
91    m_children_count_valid (false),
92    m_old_value_valid (false),
93    m_is_deref_of_parent (false),
94    m_is_array_item_for_pointer(false),
95    m_is_bitfield_for_scalar(false),
96    m_is_expression_path_child(false),
97    m_is_child_at_offset(false),
98    m_is_getting_summary(false),
99    m_did_calculate_complete_objc_class_type(false)
100{
101    m_manager->ManageObject(this);
102}
103
104//----------------------------------------------------------------------
105// ValueObject constructor
106//----------------------------------------------------------------------
107ValueObject::ValueObject (ExecutionContextScope *exe_scope,
108                          AddressType child_ptr_or_ref_addr_type) :
109    UserID (++g_value_obj_uid), // Unique identifier for every value object
110    m_parent (NULL),
111    m_update_point (exe_scope),
112    m_name (),
113    m_data (),
114    m_value (),
115    m_error (),
116    m_value_str (),
117    m_old_value_str (),
118    m_location_str (),
119    m_summary_str (),
120    m_object_desc_str (),
121    m_manager(),
122    m_children (),
123    m_synthetic_children (),
124    m_dynamic_value (NULL),
125    m_synthetic_value(NULL),
126    m_deref_valobj(NULL),
127    m_format (eFormatDefault),
128    m_last_format_mgr_revision(0),
129    m_last_format_mgr_dynamic(eNoDynamicValues),
130    m_last_summary_format(),
131    m_forced_summary_format(),
132    m_last_value_format(),
133    m_last_synthetic_filter(),
134    m_user_id_of_forced_summary(),
135    m_address_type_of_ptr_or_ref_children(child_ptr_or_ref_addr_type),
136    m_value_is_valid (false),
137    m_value_did_change (false),
138    m_children_count_valid (false),
139    m_old_value_valid (false),
140    m_is_deref_of_parent (false),
141    m_is_array_item_for_pointer(false),
142    m_is_bitfield_for_scalar(false),
143    m_is_expression_path_child(false),
144    m_is_child_at_offset(false),
145    m_is_getting_summary(false),
146    m_did_calculate_complete_objc_class_type(false)
147{
148    m_manager = new ValueObjectManager();
149    m_manager->ManageObject (this);
150}
151
152//----------------------------------------------------------------------
153// Destructor
154//----------------------------------------------------------------------
155ValueObject::~ValueObject ()
156{
157}
158
159bool
160ValueObject::UpdateValueIfNeeded (bool update_format)
161{
162    return UpdateValueIfNeeded(m_last_format_mgr_dynamic, update_format);
163}
164
165bool
166ValueObject::UpdateValueIfNeeded (DynamicValueType use_dynamic, bool update_format)
167{
168
169    bool did_change_formats = false;
170
171    if (update_format)
172        did_change_formats = UpdateFormatsIfNeeded(use_dynamic);
173
174    // If this is a constant value, then our success is predicated on whether
175    // we have an error or not
176    if (GetIsConstant())
177    {
178        // if you were asked to update your formatters, but did not get a chance to do it
179        // clear your own values (this serves the purpose of faking a stop-id for frozen
180        // objects (which are regarded as constant, but could have changes behind their backs
181        // because of the frozen-pointer depth limit)
182		// TODO: decouple summary from value and then remove this code and only force-clear the summary
183        if (update_format && !did_change_formats)
184            m_summary_str.clear();
185        return m_error.Success();
186    }
187
188    bool first_update = m_update_point.IsFirstEvaluation();
189
190    if (m_update_point.NeedsUpdating())
191    {
192        m_update_point.SetUpdated();
193
194        // Save the old value using swap to avoid a string copy which
195        // also will clear our m_value_str
196        if (m_value_str.empty())
197        {
198            m_old_value_valid = false;
199        }
200        else
201        {
202            m_old_value_valid = true;
203            m_old_value_str.swap (m_value_str);
204            m_value_str.clear();
205        }
206
207        ClearUserVisibleData();
208
209        const bool value_was_valid = GetValueIsValid();
210        SetValueDidChange (false);
211
212        m_error.Clear();
213
214        // Call the pure virtual function to update the value
215        bool success = UpdateValue ();
216
217        SetValueIsValid (success);
218
219        if (first_update)
220            SetValueDidChange (false);
221        else if (!m_value_did_change && success == false)
222        {
223            // The value wasn't gotten successfully, so we mark this
224            // as changed if the value used to be valid and now isn't
225            SetValueDidChange (value_was_valid);
226        }
227    }
228    return m_error.Success();
229}
230
231bool
232ValueObject::UpdateFormatsIfNeeded(DynamicValueType use_dynamic)
233{
234    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
235    if (log)
236        log->Printf("checking for FormatManager revisions. VO named %s is at revision %d, while the format manager is at revision %d",
237           GetName().GetCString(),
238           m_last_format_mgr_revision,
239           DataVisualization::GetCurrentRevision());
240
241    bool any_change = false;
242
243    if (HasCustomSummaryFormat() && m_update_point.GetModID() != m_user_id_of_forced_summary)
244    {
245        ClearCustomSummaryFormat();
246
247        any_change = true;
248    }
249
250    if ( (m_last_format_mgr_revision != DataVisualization::GetCurrentRevision()) ||
251          m_last_format_mgr_dynamic != use_dynamic)
252    {
253        SetValueFormat(DataVisualization::ValueFormats::GetFormat (*this, eNoDynamicValues));
254        SetSummaryFormat(DataVisualization::GetSummaryFormat (*this, use_dynamic));
255        SetSyntheticChildren(DataVisualization::GetSyntheticChildren (*this, use_dynamic));
256
257        m_last_format_mgr_revision = DataVisualization::GetCurrentRevision();
258        m_last_format_mgr_dynamic = use_dynamic;
259
260        any_change = true;
261    }
262
263    return any_change;
264
265}
266
267void
268ValueObject::SetNeedsUpdate ()
269{
270    m_update_point.SetNeedsUpdate();
271    // We have to clear the value string here so ConstResult children will notice if their values are
272    // changed by hand (i.e. with SetValueAsCString).
273    m_value_str.clear();
274}
275
276ClangASTType
277ValueObject::MaybeCalculateCompleteType ()
278{
279    ClangASTType ret(GetClangASTImpl(), GetClangTypeImpl());
280
281    if (m_did_calculate_complete_objc_class_type)
282    {
283        if (m_override_type.IsValid())
284            return m_override_type;
285        else
286            return ret;
287    }
288
289    clang_type_t ast_type(GetClangTypeImpl());
290    clang_type_t class_type;
291    bool is_pointer_type;
292
293    if (ClangASTContext::IsObjCObjectPointerType(ast_type, &class_type))
294    {
295        is_pointer_type = true;
296    }
297    else if (ClangASTContext::IsObjCClassType(ast_type))
298    {
299        is_pointer_type = false;
300        class_type = ast_type;
301    }
302    else
303    {
304        return ret;
305    }
306
307    m_did_calculate_complete_objc_class_type = true;
308
309    if (!class_type)
310        return ret;
311
312    std::string class_name;
313
314    if (!ClangASTContext::GetObjCClassName(class_type, class_name))
315        return ret;
316
317    ProcessSP process_sp(GetUpdatePoint().GetExecutionContextRef().GetProcessSP());
318
319    if (!process_sp)
320        return ret;
321
322    ObjCLanguageRuntime *objc_language_runtime(process_sp->GetObjCLanguageRuntime());
323
324    if (!objc_language_runtime)
325        return ret;
326
327    ConstString class_name_cs(class_name.c_str());
328
329    TypeSP complete_objc_class_type_sp = objc_language_runtime->LookupInCompleteClassCache(class_name_cs);
330
331    if (!complete_objc_class_type_sp)
332        return ret;
333
334    ClangASTType complete_class(complete_objc_class_type_sp->GetClangAST(),
335                                complete_objc_class_type_sp->GetClangFullType());
336
337    if (!ClangASTContext::GetCompleteType(complete_class.GetASTContext(),
338                                          complete_class.GetOpaqueQualType()))
339        return ret;
340
341    if (is_pointer_type)
342    {
343        clang_type_t pointer_type = ClangASTContext::CreatePointerType(complete_class.GetASTContext(),
344                                                                       complete_class.GetOpaqueQualType());
345
346        m_override_type = ClangASTType(complete_class.GetASTContext(),
347                                       pointer_type);
348    }
349    else
350    {
351        m_override_type = complete_class;
352    }
353
354    return m_override_type;
355}
356
357clang::ASTContext *
358ValueObject::GetClangAST ()
359{
360    ClangASTType type = MaybeCalculateCompleteType();
361
362    return type.GetASTContext();
363}
364
365lldb::clang_type_t
366ValueObject::GetClangType ()
367{
368    ClangASTType type = MaybeCalculateCompleteType();
369
370    return type.GetOpaqueQualType();
371}
372
373DataExtractor &
374ValueObject::GetDataExtractor ()
375{
376    UpdateValueIfNeeded(false);
377    return m_data;
378}
379
380const Error &
381ValueObject::GetError()
382{
383    UpdateValueIfNeeded(false);
384    return m_error;
385}
386
387const ConstString &
388ValueObject::GetName() const
389{
390    return m_name;
391}
392
393const char *
394ValueObject::GetLocationAsCString ()
395{
396    if (UpdateValueIfNeeded(false))
397    {
398        if (m_location_str.empty())
399        {
400            StreamString sstr;
401
402            switch (m_value.GetValueType())
403            {
404            default:
405                break;
406
407            case Value::eValueTypeScalar:
408                if (m_value.GetContextType() == Value::eContextTypeRegisterInfo)
409                {
410                    RegisterInfo *reg_info = m_value.GetRegisterInfo();
411                    if (reg_info)
412                    {
413                        if (reg_info->name)
414                            m_location_str = reg_info->name;
415                        else if (reg_info->alt_name)
416                            m_location_str = reg_info->alt_name;
417                        break;
418                    }
419                }
420                m_location_str = "scalar";
421                break;
422
423            case Value::eValueTypeLoadAddress:
424            case Value::eValueTypeFileAddress:
425            case Value::eValueTypeHostAddress:
426                {
427                    uint32_t addr_nibble_size = m_data.GetAddressByteSize() * 2;
428                    sstr.Printf("0x%*.*llx", addr_nibble_size, addr_nibble_size, m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS));
429                    m_location_str.swap(sstr.GetString());
430                }
431                break;
432            }
433        }
434    }
435    return m_location_str.c_str();
436}
437
438Value &
439ValueObject::GetValue()
440{
441    return m_value;
442}
443
444const Value &
445ValueObject::GetValue() const
446{
447    return m_value;
448}
449
450bool
451ValueObject::ResolveValue (Scalar &scalar)
452{
453    if (UpdateValueIfNeeded(false)) // make sure that you are up to date before returning anything
454    {
455        ExecutionContext exe_ctx (GetExecutionContextRef());
456        Value tmp_value(m_value);
457        scalar = tmp_value.ResolveValue(&exe_ctx, GetClangAST ());
458        if (scalar.IsValid())
459        {
460            const uint32_t bitfield_bit_size = GetBitfieldBitSize();
461            if (bitfield_bit_size)
462                return scalar.ExtractBitfield (bitfield_bit_size, GetBitfieldBitOffset());
463            return true;
464        }
465    }
466    return false;
467}
468
469bool
470ValueObject::GetValueIsValid () const
471{
472    return m_value_is_valid;
473}
474
475
476void
477ValueObject::SetValueIsValid (bool b)
478{
479    m_value_is_valid = b;
480}
481
482bool
483ValueObject::GetValueDidChange ()
484{
485    GetValueAsCString ();
486    return m_value_did_change;
487}
488
489void
490ValueObject::SetValueDidChange (bool value_changed)
491{
492    m_value_did_change = value_changed;
493}
494
495ValueObjectSP
496ValueObject::GetChildAtIndex (uint32_t idx, bool can_create)
497{
498    ValueObjectSP child_sp;
499    // We may need to update our value if we are dynamic
500    if (IsPossibleDynamicType ())
501        UpdateValueIfNeeded(false);
502    if (idx < GetNumChildren())
503    {
504        // Check if we have already made the child value object?
505        if (can_create && m_children[idx] == NULL)
506        {
507            // No we haven't created the child at this index, so lets have our
508            // subclass do it and cache the result for quick future access.
509            m_children[idx] = CreateChildAtIndex (idx, false, 0);
510        }
511
512        if (m_children[idx] != NULL)
513            return m_children[idx]->GetSP();
514    }
515    return child_sp;
516}
517
518uint32_t
519ValueObject::GetIndexOfChildWithName (const ConstString &name)
520{
521    bool omit_empty_base_classes = true;
522    return ClangASTContext::GetIndexOfChildWithName (GetClangAST(),
523                                                     GetClangType(),
524                                                     name.GetCString(),
525                                                     omit_empty_base_classes);
526}
527
528ValueObjectSP
529ValueObject::GetChildMemberWithName (const ConstString &name, bool can_create)
530{
531    // when getting a child by name, it could be buried inside some base
532    // classes (which really aren't part of the expression path), so we
533    // need a vector of indexes that can get us down to the correct child
534    ValueObjectSP child_sp;
535
536    // We may need to update our value if we are dynamic
537    if (IsPossibleDynamicType ())
538        UpdateValueIfNeeded(false);
539
540    std::vector<uint32_t> child_indexes;
541    clang::ASTContext *clang_ast = GetClangAST();
542    void *clang_type = GetClangType();
543    bool omit_empty_base_classes = true;
544    const size_t num_child_indexes =  ClangASTContext::GetIndexOfChildMemberWithName (clang_ast,
545                                                                                      clang_type,
546                                                                                      name.GetCString(),
547                                                                                      omit_empty_base_classes,
548                                                                                      child_indexes);
549    if (num_child_indexes > 0)
550    {
551        std::vector<uint32_t>::const_iterator pos = child_indexes.begin ();
552        std::vector<uint32_t>::const_iterator end = child_indexes.end ();
553
554        child_sp = GetChildAtIndex(*pos, can_create);
555        for (++pos; pos != end; ++pos)
556        {
557            if (child_sp)
558            {
559                ValueObjectSP new_child_sp(child_sp->GetChildAtIndex (*pos, can_create));
560                child_sp = new_child_sp;
561            }
562            else
563            {
564                child_sp.reset();
565            }
566
567        }
568    }
569    return child_sp;
570}
571
572
573uint32_t
574ValueObject::GetNumChildren ()
575{
576    if (!m_children_count_valid)
577    {
578        SetNumChildren (CalculateNumChildren());
579    }
580    return m_children.size();
581}
582void
583ValueObject::SetNumChildren (uint32_t num_children)
584{
585    m_children_count_valid = true;
586    m_children.resize(num_children);
587}
588
589void
590ValueObject::SetName (const ConstString &name)
591{
592    m_name = name;
593}
594
595ValueObject *
596ValueObject::CreateChildAtIndex (uint32_t idx, bool synthetic_array_member, int32_t synthetic_index)
597{
598    ValueObject *valobj = NULL;
599
600    bool omit_empty_base_classes = true;
601    bool ignore_array_bounds = synthetic_array_member;
602    std::string child_name_str;
603    uint32_t child_byte_size = 0;
604    int32_t child_byte_offset = 0;
605    uint32_t child_bitfield_bit_size = 0;
606    uint32_t child_bitfield_bit_offset = 0;
607    bool child_is_base_class = false;
608    bool child_is_deref_of_parent = false;
609
610    const bool transparent_pointers = synthetic_array_member == false;
611    clang::ASTContext *clang_ast = GetClangAST();
612    clang_type_t clang_type = GetClangType();
613    clang_type_t child_clang_type;
614
615    ExecutionContext exe_ctx (GetExecutionContextRef());
616
617    child_clang_type = ClangASTContext::GetChildClangTypeAtIndex (&exe_ctx,
618                                                                  clang_ast,
619                                                                  GetName().GetCString(),
620                                                                  clang_type,
621                                                                  idx,
622                                                                  transparent_pointers,
623                                                                  omit_empty_base_classes,
624                                                                  ignore_array_bounds,
625                                                                  child_name_str,
626                                                                  child_byte_size,
627                                                                  child_byte_offset,
628                                                                  child_bitfield_bit_size,
629                                                                  child_bitfield_bit_offset,
630                                                                  child_is_base_class,
631                                                                  child_is_deref_of_parent);
632    if (child_clang_type && child_byte_size)
633    {
634        if (synthetic_index)
635            child_byte_offset += child_byte_size * synthetic_index;
636
637        ConstString child_name;
638        if (!child_name_str.empty())
639            child_name.SetCString (child_name_str.c_str());
640
641        valobj = new ValueObjectChild (*this,
642                                       clang_ast,
643                                       child_clang_type,
644                                       child_name,
645                                       child_byte_size,
646                                       child_byte_offset,
647                                       child_bitfield_bit_size,
648                                       child_bitfield_bit_offset,
649                                       child_is_base_class,
650                                       child_is_deref_of_parent,
651                                       eAddressTypeInvalid);
652        //if (valobj)
653        //    valobj->SetAddressTypeOfChildren(eAddressTypeInvalid);
654   }
655
656    return valobj;
657}
658
659const char *
660ValueObject::GetSummaryAsCString ()
661{
662    // Watch for recursion which can happen with summary strings and other
663    // variable formatting options.
664    if (m_is_getting_summary)
665        return NULL;
666
667    m_is_getting_summary = true;
668
669    if (UpdateValueIfNeeded (true))
670    {
671        if (m_summary_str.empty())
672        {
673            TypeSummaryImpl *summary_format = GetSummaryFormat().get();
674
675            if (summary_format)
676            {
677                 summary_format->FormatObject(GetSP(),
678                                              m_summary_str);
679            }
680            else
681            {
682                clang_type_t clang_type = GetClangType();
683
684                // Do some default printout for function pointers
685                if (clang_type)
686                {
687                    StreamString sstr;
688                    clang_type_t elem_or_pointee_clang_type;
689                    const Flags type_flags (ClangASTContext::GetTypeInfo (clang_type,
690                                                                          GetClangAST(),
691                                                                          &elem_or_pointee_clang_type));
692
693                    if (ClangASTContext::IsFunctionPointerType (clang_type))
694                    {
695                        AddressType func_ptr_address_type = eAddressTypeInvalid;
696                        addr_t func_ptr_address = GetPointerValue (&func_ptr_address_type);
697                        if (func_ptr_address != 0 && func_ptr_address != LLDB_INVALID_ADDRESS)
698                        {
699                            switch (func_ptr_address_type)
700                            {
701                            case eAddressTypeInvalid:
702                            case eAddressTypeFile:
703                                break;
704
705                            case eAddressTypeLoad:
706                                {
707                                    ExecutionContext exe_ctx (GetExecutionContextRef());
708
709                                    Address so_addr;
710                                    Target *target = exe_ctx.GetTargetPtr();
711                                    if (target && target->GetSectionLoadList().IsEmpty() == false)
712                                    {
713                                        if (target->GetSectionLoadList().ResolveLoadAddress(func_ptr_address, so_addr))
714                                        {
715                                            so_addr.Dump (&sstr,
716                                                          exe_ctx.GetBestExecutionContextScope(),
717                                                          Address::DumpStyleResolvedDescription,
718                                                          Address::DumpStyleSectionNameOffset);
719                                        }
720                                    }
721                                }
722                                break;
723
724                            case eAddressTypeHost:
725                                break;
726                            }
727                        }
728                        if (sstr.GetSize() > 0)
729                        {
730                            m_summary_str.assign (1, '(');
731                            m_summary_str.append (sstr.GetData(), sstr.GetSize());
732                            m_summary_str.append (1, ')');
733                        }
734                    }
735                }
736            }
737        }
738    }
739    m_is_getting_summary = false;
740    if (m_summary_str.empty())
741        return NULL;
742    return m_summary_str.c_str();
743}
744
745bool
746ValueObject::IsCStringContainer(bool check_pointer)
747{
748    clang_type_t elem_or_pointee_clang_type;
749    const Flags type_flags (ClangASTContext::GetTypeInfo (GetClangType(),
750                                                          GetClangAST(),
751                                                          &elem_or_pointee_clang_type));
752    bool is_char_arr_ptr (type_flags.AnySet (ClangASTContext::eTypeIsArray | ClangASTContext::eTypeIsPointer) &&
753            ClangASTContext::IsCharType (elem_or_pointee_clang_type));
754    if (!is_char_arr_ptr)
755        return false;
756    if (!check_pointer)
757        return true;
758    if (type_flags.Test(ClangASTContext::eTypeIsArray))
759        return true;
760    addr_t cstr_address = LLDB_INVALID_ADDRESS;
761    AddressType cstr_address_type = eAddressTypeInvalid;
762    cstr_address = GetAddressOf (true, &cstr_address_type);
763    return (cstr_address != LLDB_INVALID_ADDRESS);
764}
765
766size_t
767ValueObject::GetPointeeData (DataExtractor& data,
768                             uint32_t item_idx,
769                             uint32_t item_count)
770{
771    if (!IsPointerType() && !IsArrayType())
772        return 0;
773
774    if (item_count == 0)
775        return 0;
776
777    uint32_t stride = 0;
778
779    ClangASTType type(GetClangAST(),
780                      GetClangType());
781
782    const uint64_t item_type_size = (IsPointerType() ? ClangASTType::GetTypeByteSize(GetClangAST(), type.GetPointeeType()) :
783                                     ClangASTType::GetTypeByteSize(GetClangAST(), type.GetArrayElementType(stride)));
784
785    const uint64_t bytes = item_count * item_type_size;
786
787    const uint64_t offset = item_idx * item_type_size;
788
789    if (item_idx == 0 && item_count == 1) // simply a deref
790    {
791        if (IsPointerType())
792        {
793            Error error;
794            ValueObjectSP pointee_sp = Dereference(error);
795            if (error.Fail() || pointee_sp.get() == NULL)
796                return 0;
797            return pointee_sp->GetDataExtractor().Copy(data);
798        }
799        else
800        {
801            ValueObjectSP child_sp = GetChildAtIndex(0, true);
802            if (child_sp.get() == NULL)
803                return 0;
804            return child_sp->GetDataExtractor().Copy(data);
805        }
806        return true;
807    }
808    else /* (items > 1) */
809    {
810        Error error;
811        lldb_private::DataBufferHeap* heap_buf_ptr = NULL;
812        lldb::DataBufferSP data_sp(heap_buf_ptr = new lldb_private::DataBufferHeap());
813
814        AddressType addr_type;
815        lldb::addr_t addr = IsPointerType() ? GetPointerValue(&addr_type) : GetAddressOf(true, &addr_type);
816
817        switch (addr_type)
818        {
819            case eAddressTypeFile:
820                {
821                    ModuleSP module_sp (GetModule());
822                    if (module_sp)
823                    {
824                        Address so_addr;
825                        module_sp->ResolveFileAddress(addr, so_addr);
826                        ExecutionContext exe_ctx (GetExecutionContextRef());
827                        Target* target = exe_ctx.GetTargetPtr();
828                        if (target)
829                        {
830                            heap_buf_ptr->SetByteSize(bytes);
831                            size_t bytes_read = target->ReadMemory(so_addr, false, heap_buf_ptr->GetBytes(), bytes, error);
832                            if (error.Success())
833                            {
834                                data.SetData(data_sp);
835                                return bytes_read;
836                            }
837                        }
838                    }
839                }
840                break;
841            case eAddressTypeLoad:
842                {
843                    ExecutionContext exe_ctx (GetExecutionContextRef());
844                    Process *process = exe_ctx.GetProcessPtr();
845                    if (process)
846                    {
847                        heap_buf_ptr->SetByteSize(bytes);
848                        size_t bytes_read = process->ReadMemory(addr + offset, heap_buf_ptr->GetBytes(), bytes, error);
849                        if (error.Success())
850                        {
851                            data.SetData(data_sp);
852                            return bytes_read;
853                        }
854                    }
855                }
856                break;
857            case eAddressTypeHost:
858                {
859                    heap_buf_ptr->CopyData((uint8_t*)(addr + offset), bytes);
860                    data.SetData(data_sp);
861                    return bytes;
862                }
863                break;
864            case eAddressTypeInvalid:
865            default:
866                break;
867        }
868    }
869    return 0;
870}
871
872size_t
873ValueObject::GetData (DataExtractor& data)
874{
875    UpdateValueIfNeeded(false);
876    ExecutionContext exe_ctx (GetExecutionContextRef());
877    Error error = m_value.GetValueAsData(&exe_ctx, GetClangAST(), data, 0, GetModule().get());
878    if (error.Fail())
879        return 0;
880    data.SetAddressByteSize(m_data.GetAddressByteSize());
881    data.SetByteOrder(m_data.GetByteOrder());
882    return data.GetByteSize();
883}
884
885// will compute strlen(str), but without consuming more than
886// maxlen bytes out of str (this serves the purpose of reading
887// chunks of a string without having to worry about
888// missing NULL terminators in the chunk)
889// of course, if strlen(str) > maxlen, the function will return
890// maxlen_value (which should be != maxlen, because that allows you
891// to know whether strlen(str) == maxlen or strlen(str) > maxlen)
892static uint32_t
893strlen_or_inf (const char* str,
894               uint32_t maxlen,
895               uint32_t maxlen_value)
896{
897    uint32_t len = 0;
898    if (str)
899    {
900        while(*str)
901        {
902            len++;str++;
903            if (len > maxlen)
904                return maxlen_value;
905        }
906    }
907    return len;
908}
909
910void
911ValueObject::ReadPointedString (Stream& s,
912                                Error& error,
913                                uint32_t max_length,
914                                bool honor_array,
915                                Format item_format)
916{
917    ExecutionContext exe_ctx (GetExecutionContextRef());
918    Target* target = exe_ctx.GetTargetPtr();
919
920    if (target && max_length == 0)
921        max_length = target->GetMaximumSizeOfStringSummary();
922
923    clang_type_t clang_type = GetClangType();
924    clang_type_t elem_or_pointee_clang_type;
925    const Flags type_flags (ClangASTContext::GetTypeInfo (clang_type,
926                                                          GetClangAST(),
927                                                          &elem_or_pointee_clang_type));
928    if (type_flags.AnySet (ClangASTContext::eTypeIsArray | ClangASTContext::eTypeIsPointer) &&
929        ClangASTContext::IsCharType (elem_or_pointee_clang_type))
930    {
931        if (target == NULL)
932        {
933            s << "<no target to read from>";
934        }
935        else
936        {
937            addr_t cstr_address = LLDB_INVALID_ADDRESS;
938            AddressType cstr_address_type = eAddressTypeInvalid;
939
940            size_t cstr_len = 0;
941            bool capped_data = false;
942            if (type_flags.Test (ClangASTContext::eTypeIsArray))
943            {
944                // We have an array
945                cstr_len = ClangASTContext::GetArraySize (clang_type);
946                if (cstr_len > max_length)
947                {
948                    capped_data = true;
949                    cstr_len = max_length;
950                }
951                cstr_address = GetAddressOf (true, &cstr_address_type);
952            }
953            else
954            {
955                // We have a pointer
956                cstr_address = GetPointerValue (&cstr_address_type);
957            }
958            if (cstr_address != 0 && cstr_address != LLDB_INVALID_ADDRESS)
959            {
960                Address cstr_so_addr (cstr_address);
961                DataExtractor data;
962                size_t bytes_read = 0;
963                if (cstr_len > 0 && honor_array)
964                {
965                    // I am using GetPointeeData() here to abstract the fact that some ValueObjects are actually frozen pointers in the host
966                    // but the pointed-to data lives in the debuggee, and GetPointeeData() automatically takes care of this
967                    GetPointeeData(data, 0, cstr_len);
968
969                    if ((bytes_read = data.GetByteSize()) > 0)
970                    {
971                        s << '"';
972                        data.Dump (&s,
973                                   0,                 // Start offset in "data"
974                                   item_format,
975                                   1,                 // Size of item (1 byte for a char!)
976                                   bytes_read,        // How many bytes to print?
977                                   UINT32_MAX,        // num per line
978                                   LLDB_INVALID_ADDRESS,// base address
979                                   0,                 // bitfield bit size
980                                   0);                // bitfield bit offset
981                        if (capped_data)
982                            s << "...";
983                        s << '"';
984                    }
985                }
986                else
987                {
988                    cstr_len = max_length;
989                    const size_t k_max_buf_size = 64;
990
991                    size_t offset = 0;
992
993                    int cstr_len_displayed = -1;
994                    bool capped_cstr = false;
995                    // I am using GetPointeeData() here to abstract the fact that some ValueObjects are actually frozen pointers in the host
996                    // but the pointed-to data lives in the debuggee, and GetPointeeData() automatically takes care of this
997                    while ((bytes_read = GetPointeeData(data, offset, k_max_buf_size)) > 0)
998                    {
999                        const char *cstr = data.PeekCStr(0);
1000                        size_t len = strlen_or_inf (cstr, k_max_buf_size, k_max_buf_size+1);
1001                        if (len > k_max_buf_size)
1002                            len = k_max_buf_size;
1003                        if (cstr && cstr_len_displayed < 0)
1004                            s << '"';
1005
1006                        if (cstr_len_displayed < 0)
1007                            cstr_len_displayed = len;
1008
1009                        if (len == 0)
1010                            break;
1011                        cstr_len_displayed += len;
1012                        if (len > bytes_read)
1013                            len = bytes_read;
1014                        if (len > cstr_len)
1015                            len = cstr_len;
1016
1017                        data.Dump (&s,
1018                                   0,                 // Start offset in "data"
1019                                   item_format,
1020                                   1,                 // Size of item (1 byte for a char!)
1021                                   len,               // How many bytes to print?
1022                                   UINT32_MAX,        // num per line
1023                                   LLDB_INVALID_ADDRESS,// base address
1024                                   0,                 // bitfield bit size
1025                                   0);                // bitfield bit offset
1026
1027                        if (len < k_max_buf_size)
1028                            break;
1029
1030                        if (len >= cstr_len)
1031                        {
1032                            capped_cstr = true;
1033                            break;
1034                        }
1035
1036                        cstr_len -= len;
1037                        offset += len;
1038                    }
1039
1040                    if (cstr_len_displayed >= 0)
1041                    {
1042                        s << '"';
1043                        if (capped_cstr)
1044                            s << "...";
1045                    }
1046                }
1047            }
1048        }
1049    }
1050    else
1051    {
1052        error.SetErrorString("impossible to read a string from this object");
1053        s << "<not a string object>";
1054    }
1055}
1056
1057const char *
1058ValueObject::GetObjectDescription ()
1059{
1060
1061    if (!UpdateValueIfNeeded (true))
1062        return NULL;
1063
1064    if (!m_object_desc_str.empty())
1065        return m_object_desc_str.c_str();
1066
1067    ExecutionContext exe_ctx (GetExecutionContextRef());
1068    Process *process = exe_ctx.GetProcessPtr();
1069    if (process == NULL)
1070        return NULL;
1071
1072    StreamString s;
1073
1074    LanguageType language = GetObjectRuntimeLanguage();
1075    LanguageRuntime *runtime = process->GetLanguageRuntime(language);
1076
1077    if (runtime == NULL)
1078    {
1079        // Aw, hell, if the things a pointer, or even just an integer, let's try ObjC anyway...
1080        clang_type_t opaque_qual_type = GetClangType();
1081        if (opaque_qual_type != NULL)
1082        {
1083            bool is_signed;
1084            if (ClangASTContext::IsIntegerType (opaque_qual_type, is_signed)
1085                || ClangASTContext::IsPointerType (opaque_qual_type))
1086            {
1087                runtime = process->GetLanguageRuntime(eLanguageTypeObjC);
1088            }
1089        }
1090    }
1091
1092    if (runtime && runtime->GetObjectDescription(s, *this))
1093    {
1094        m_object_desc_str.append (s.GetData());
1095    }
1096
1097    if (m_object_desc_str.empty())
1098        return NULL;
1099    else
1100        return m_object_desc_str.c_str();
1101}
1102
1103const char *
1104ValueObject::GetValueAsCString ()
1105{
1106    // If our byte size is zero this is an aggregate type that has children
1107    if (ClangASTContext::IsAggregateType (GetClangType()) == false)
1108    {
1109        if (UpdateValueIfNeeded(true))
1110        {
1111            if (m_value_str.empty())
1112            {
1113                const Value::ContextType context_type = m_value.GetContextType();
1114
1115                switch (context_type)
1116                {
1117                case Value::eContextTypeClangType:
1118                case Value::eContextTypeLLDBType:
1119                case Value::eContextTypeVariable:
1120                    {
1121                        lldb::Format my_format = GetFormat();
1122                        clang_type_t clang_type = GetClangType ();
1123                        if (clang_type)
1124                        {
1125                            if (m_format == lldb::eFormatDefault)
1126                            {
1127                                if (m_last_value_format)
1128                                    my_format = m_last_value_format->GetFormat();
1129                                else
1130                                {
1131                                    if (m_is_bitfield_for_scalar)
1132                                        my_format = eFormatUnsigned;
1133                                    else
1134                                        my_format = ClangASTType::GetFormat(clang_type);
1135                                }
1136                            }
1137                            StreamString sstr;
1138                            ExecutionContext exe_ctx (GetExecutionContextRef());
1139                            ClangASTType::DumpTypeValue (GetClangAST(),             // The clang AST
1140                                                         clang_type,                // The clang type to display
1141                                                         &sstr,
1142                                                         my_format,                 // Format to display this type with
1143                                                         m_data,                    // Data to extract from
1144                                                         0,                         // Byte offset into "m_data"
1145                                                         GetByteSize(),             // Byte size of item in "m_data"
1146                                                         GetBitfieldBitSize(),      // Bitfield bit size
1147                                                         GetBitfieldBitOffset(),    // Bitfield bit offset
1148                                                         exe_ctx.GetBestExecutionContextScope());
1149                            // Don't set the m_error to anything here otherwise
1150                            // we won't be able to re-format as anything else. The
1151                            // code for ClangASTType::DumpTypeValue() should always
1152                            // return something, even if that something contains
1153                            // an error messsage. "m_error" is used to detect errors
1154                            // when reading the valid object, not for formatting errors.
1155                            if (sstr.GetString().empty())
1156                                m_value_str.clear();
1157                            else
1158                                m_value_str.swap(sstr.GetString());
1159                        }
1160                    }
1161                    break;
1162
1163                case Value::eContextTypeRegisterInfo:
1164                    {
1165                        const RegisterInfo *reg_info = m_value.GetRegisterInfo();
1166                        if (reg_info)
1167                        {
1168                            lldb::Format my_format = GetFormat();
1169                            if (m_format == lldb::eFormatDefault)
1170                            {
1171                                if (m_last_value_format)
1172                                    my_format = m_last_value_format->GetFormat();
1173                                else
1174                                    my_format = reg_info->format;
1175                            }
1176
1177                            ExecutionContext exe_ctx (GetExecutionContextRef());
1178
1179                            StreamString reg_sstr;
1180                            m_data.Dump (&reg_sstr,
1181                                         0,
1182                                         my_format,
1183                                         reg_info->byte_size,
1184                                         1,
1185                                         UINT32_MAX,
1186                                         LLDB_INVALID_ADDRESS,
1187                                         0,
1188                                         0,
1189                                         exe_ctx.GetBestExecutionContextScope());
1190                            m_value_str.swap(reg_sstr.GetString());
1191                        }
1192                    }
1193                    break;
1194
1195                default:
1196                    break;
1197                }
1198            }
1199
1200            if (!m_value_did_change && m_old_value_valid)
1201            {
1202                // The value was gotten successfully, so we consider the
1203                // value as changed if the value string differs
1204                SetValueDidChange (m_old_value_str != m_value_str);
1205            }
1206        }
1207    }
1208    if (m_value_str.empty())
1209        return NULL;
1210    return m_value_str.c_str();
1211}
1212
1213// if > 8bytes, 0 is returned. this method should mostly be used
1214// to read address values out of pointers
1215uint64_t
1216ValueObject::GetValueAsUnsigned (uint64_t fail_value)
1217{
1218    // If our byte size is zero this is an aggregate type that has children
1219    if (ClangASTContext::IsAggregateType (GetClangType()) == false)
1220    {
1221        Scalar scalar;
1222        if (ResolveValue (scalar))
1223            return scalar.GetRawBits64(fail_value);
1224    }
1225    return fail_value;
1226}
1227
1228bool
1229ValueObject::GetPrintableRepresentation(Stream& s,
1230                                        ValueObjectRepresentationStyle val_obj_display,
1231                                        Format custom_format)
1232{
1233
1234    if (custom_format != eFormatInvalid)
1235        SetFormat(custom_format);
1236
1237    const char * return_value;
1238    std::string alloc_mem;
1239
1240    switch(val_obj_display)
1241    {
1242        case eDisplayValue:
1243            return_value = GetValueAsCString();
1244            break;
1245
1246        case eDisplaySummary:
1247            return_value = GetSummaryAsCString();
1248            break;
1249
1250        case eDisplayLanguageSpecific:
1251            return_value = GetObjectDescription();
1252            break;
1253
1254        case eDisplayLocation:
1255            return_value = GetLocationAsCString();
1256            break;
1257
1258        case eDisplayChildrenCount:
1259            {
1260                alloc_mem.resize(512);
1261                return_value = &alloc_mem[0];
1262                int count = GetNumChildren();
1263                snprintf((char*)return_value, 512, "%d", count);
1264            }
1265            break;
1266
1267        case eDisplayType:
1268            return_value = GetTypeName().AsCString();
1269            break;
1270
1271        default:
1272            break;
1273    }
1274
1275    if (!return_value)
1276    {
1277        if (val_obj_display == eDisplayValue)
1278            return_value = GetSummaryAsCString();
1279        else if (val_obj_display == eDisplaySummary)
1280        {
1281            if (ClangASTContext::IsAggregateType (GetClangType()) == true)
1282            {
1283                // this thing has no value, and it seems to have no summary
1284                // some combination of unitialized data and other factors can also
1285                // raise this condition, so let's print a nice generic description
1286                {
1287                    alloc_mem.resize(684);
1288                    return_value = &alloc_mem[0];
1289                    snprintf((char*)return_value, 684, "%s @ %s", GetTypeName().AsCString(), GetLocationAsCString());
1290                }
1291            }
1292            else
1293                return_value = GetValueAsCString();
1294        }
1295    }
1296
1297    if (return_value)
1298        s.PutCString(return_value);
1299    else
1300    {
1301        if (m_error.Fail())
1302            s.Printf("<%s>", m_error.AsCString());
1303        else if (val_obj_display == eDisplaySummary)
1304            s.PutCString("<no summary available>");
1305        else if (val_obj_display == eDisplayValue)
1306            s.PutCString("<no value available>");
1307        else if (val_obj_display == eDisplayLanguageSpecific)
1308            s.PutCString("<not a valid Objective-C object>"); // edit this if we have other runtimes that support a description
1309        else
1310            s.PutCString("<no printable representation>");
1311    }
1312
1313    // we should only return false here if we could not do *anything*
1314    // even if we have an error message as output, that's a success
1315    // from our callers' perspective, so return true
1316    return true;
1317
1318}
1319
1320// if any more "special cases" are added to ValueObject::DumpPrintableRepresentation() please keep
1321// this call up to date by returning true for your new special cases. We will eventually move
1322// to checking this call result before trying to display special cases
1323bool
1324ValueObject::HasSpecialCasesForPrintableRepresentation(ValueObjectRepresentationStyle val_obj_display,
1325                                                       Format custom_format)
1326{
1327    clang_type_t elem_or_pointee_type;
1328    Flags flags(ClangASTContext::GetTypeInfo(GetClangType(), GetClangAST(), &elem_or_pointee_type));
1329
1330    if (flags.AnySet(ClangASTContext::eTypeIsArray | ClangASTContext::eTypeIsPointer)
1331        && val_obj_display == ValueObject::eDisplayValue)
1332    {
1333        if (IsCStringContainer(true) &&
1334            (custom_format == eFormatCString ||
1335             custom_format == eFormatCharArray ||
1336             custom_format == eFormatChar ||
1337             custom_format == eFormatVectorOfChar))
1338            return true;
1339
1340        if (flags.Test(ClangASTContext::eTypeIsArray))
1341        {
1342            if ((custom_format == eFormatBytes) ||
1343                (custom_format == eFormatBytesWithASCII))
1344                return true;
1345
1346            if ((custom_format == eFormatVectorOfChar) ||
1347                (custom_format == eFormatVectorOfFloat32) ||
1348                (custom_format == eFormatVectorOfFloat64) ||
1349                (custom_format == eFormatVectorOfSInt16) ||
1350                (custom_format == eFormatVectorOfSInt32) ||
1351                (custom_format == eFormatVectorOfSInt64) ||
1352                (custom_format == eFormatVectorOfSInt8) ||
1353                (custom_format == eFormatVectorOfUInt128) ||
1354                (custom_format == eFormatVectorOfUInt16) ||
1355                (custom_format == eFormatVectorOfUInt32) ||
1356                (custom_format == eFormatVectorOfUInt64) ||
1357                (custom_format == eFormatVectorOfUInt8))
1358                return true;
1359        }
1360    }
1361    return false;
1362}
1363
1364bool
1365ValueObject::DumpPrintableRepresentation(Stream& s,
1366                                         ValueObjectRepresentationStyle val_obj_display,
1367                                         Format custom_format,
1368                                         bool only_special)
1369{
1370
1371    clang_type_t elem_or_pointee_type;
1372    Flags flags(ClangASTContext::GetTypeInfo(GetClangType(), GetClangAST(), &elem_or_pointee_type));
1373
1374    if (flags.AnySet(ClangASTContext::eTypeIsArray | ClangASTContext::eTypeIsPointer)
1375         && val_obj_display == ValueObject::eDisplayValue)
1376    {
1377        // when being asked to get a printable display an array or pointer type directly,
1378        // try to "do the right thing"
1379
1380        if (IsCStringContainer(true) &&
1381            (custom_format == eFormatCString ||
1382             custom_format == eFormatCharArray ||
1383             custom_format == eFormatChar ||
1384             custom_format == eFormatVectorOfChar)) // print char[] & char* directly
1385        {
1386            Error error;
1387            ReadPointedString(s,
1388                              error,
1389                              0,
1390                              (custom_format == eFormatVectorOfChar) ||
1391                              (custom_format == eFormatCharArray));
1392            return !error.Fail();
1393        }
1394
1395        if (custom_format == eFormatEnum)
1396            return false;
1397
1398        // this only works for arrays, because I have no way to know when
1399        // the pointed memory ends, and no special \0 end of data marker
1400        if (flags.Test(ClangASTContext::eTypeIsArray))
1401        {
1402            if ((custom_format == eFormatBytes) ||
1403                (custom_format == eFormatBytesWithASCII))
1404            {
1405                uint32_t count = GetNumChildren();
1406
1407                s << '[';
1408                for (uint32_t low = 0; low < count; low++)
1409                {
1410
1411                    if (low)
1412                        s << ',';
1413
1414                    ValueObjectSP child = GetChildAtIndex(low,true);
1415                    if (!child.get())
1416                    {
1417                        s << "<invalid child>";
1418                        continue;
1419                    }
1420                    child->DumpPrintableRepresentation(s, ValueObject::eDisplayValue, custom_format);
1421                }
1422
1423                s << ']';
1424
1425                return true;
1426            }
1427
1428            if ((custom_format == eFormatVectorOfChar) ||
1429                (custom_format == eFormatVectorOfFloat32) ||
1430                (custom_format == eFormatVectorOfFloat64) ||
1431                (custom_format == eFormatVectorOfSInt16) ||
1432                (custom_format == eFormatVectorOfSInt32) ||
1433                (custom_format == eFormatVectorOfSInt64) ||
1434                (custom_format == eFormatVectorOfSInt8) ||
1435                (custom_format == eFormatVectorOfUInt128) ||
1436                (custom_format == eFormatVectorOfUInt16) ||
1437                (custom_format == eFormatVectorOfUInt32) ||
1438                (custom_format == eFormatVectorOfUInt64) ||
1439                (custom_format == eFormatVectorOfUInt8)) // arrays of bytes, bytes with ASCII or any vector format should be printed directly
1440            {
1441                uint32_t count = GetNumChildren();
1442
1443                Format format = FormatManager::GetSingleItemFormat(custom_format);
1444
1445                s << '[';
1446                for (uint32_t low = 0; low < count; low++)
1447                {
1448
1449                    if (low)
1450                        s << ',';
1451
1452                    ValueObjectSP child = GetChildAtIndex(low,true);
1453                    if (!child.get())
1454                    {
1455                        s << "<invalid child>";
1456                        continue;
1457                    }
1458                    child->DumpPrintableRepresentation(s, ValueObject::eDisplayValue, format);
1459                }
1460
1461                s << ']';
1462
1463                return true;
1464            }
1465        }
1466
1467        if ((custom_format == eFormatBoolean) ||
1468            (custom_format == eFormatBinary) ||
1469            (custom_format == eFormatChar) ||
1470            (custom_format == eFormatCharPrintable) ||
1471            (custom_format == eFormatComplexFloat) ||
1472            (custom_format == eFormatDecimal) ||
1473            (custom_format == eFormatHex) ||
1474            (custom_format == eFormatFloat) ||
1475            (custom_format == eFormatOctal) ||
1476            (custom_format == eFormatOSType) ||
1477            (custom_format == eFormatUnicode16) ||
1478            (custom_format == eFormatUnicode32) ||
1479            (custom_format == eFormatUnsigned) ||
1480            (custom_format == eFormatPointer) ||
1481            (custom_format == eFormatComplexInteger) ||
1482            (custom_format == eFormatComplex) ||
1483            (custom_format == eFormatDefault)) // use the [] operator
1484            return false;
1485    }
1486
1487    if (only_special)
1488        return false;
1489
1490    bool var_success = GetPrintableRepresentation(s, val_obj_display, custom_format);
1491    if (custom_format != eFormatInvalid)
1492        SetFormat(eFormatDefault);
1493    return var_success;
1494}
1495
1496addr_t
1497ValueObject::GetAddressOf (bool scalar_is_load_address, AddressType *address_type)
1498{
1499    if (!UpdateValueIfNeeded(false))
1500        return LLDB_INVALID_ADDRESS;
1501
1502    switch (m_value.GetValueType())
1503    {
1504    case Value::eValueTypeScalar:
1505        if (scalar_is_load_address)
1506        {
1507            if(address_type)
1508                *address_type = eAddressTypeLoad;
1509            return m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1510        }
1511        break;
1512
1513    case Value::eValueTypeLoadAddress:
1514    case Value::eValueTypeFileAddress:
1515    case Value::eValueTypeHostAddress:
1516        {
1517            if(address_type)
1518                *address_type = m_value.GetValueAddressType ();
1519            return m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1520        }
1521        break;
1522    }
1523    if (address_type)
1524        *address_type = eAddressTypeInvalid;
1525    return LLDB_INVALID_ADDRESS;
1526}
1527
1528addr_t
1529ValueObject::GetPointerValue (AddressType *address_type)
1530{
1531    addr_t address = LLDB_INVALID_ADDRESS;
1532    if(address_type)
1533        *address_type = eAddressTypeInvalid;
1534
1535    if (!UpdateValueIfNeeded(false))
1536        return address;
1537
1538    switch (m_value.GetValueType())
1539    {
1540    case Value::eValueTypeScalar:
1541        address = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1542        break;
1543
1544    case Value::eValueTypeHostAddress:
1545    case Value::eValueTypeLoadAddress:
1546    case Value::eValueTypeFileAddress:
1547        {
1548            uint32_t data_offset = 0;
1549            address = m_data.GetPointer(&data_offset);
1550        }
1551        break;
1552    }
1553
1554    if (address_type)
1555        *address_type = GetAddressTypeOfChildren();
1556
1557    return address;
1558}
1559
1560bool
1561ValueObject::SetValueFromCString (const char *value_str)
1562{
1563    // Make sure our value is up to date first so that our location and location
1564    // type is valid.
1565    if (!UpdateValueIfNeeded(false))
1566        return false;
1567
1568    uint32_t count = 0;
1569    Encoding encoding = ClangASTType::GetEncoding (GetClangType(), count);
1570
1571    const size_t byte_size = GetByteSize();
1572
1573    Value::ValueType value_type = m_value.GetValueType();
1574
1575    if (value_type == Value::eValueTypeScalar)
1576    {
1577        // If the value is already a scalar, then let the scalar change itself:
1578        m_value.GetScalar().SetValueFromCString (value_str, encoding, byte_size);
1579    }
1580    else if (byte_size <= Scalar::GetMaxByteSize())
1581    {
1582        // If the value fits in a scalar, then make a new scalar and again let the
1583        // scalar code do the conversion, then figure out where to put the new value.
1584        Scalar new_scalar;
1585        Error error;
1586        error = new_scalar.SetValueFromCString (value_str, encoding, byte_size);
1587        if (error.Success())
1588        {
1589            switch (value_type)
1590            {
1591            case Value::eValueTypeLoadAddress:
1592                {
1593                    // If it is a load address, then the scalar value is the storage location
1594                    // of the data, and we have to shove this value down to that load location.
1595                    ExecutionContext exe_ctx (GetExecutionContextRef());
1596                    Process *process = exe_ctx.GetProcessPtr();
1597                    if (process)
1598                    {
1599                        addr_t target_addr = m_value.GetScalar().GetRawBits64(LLDB_INVALID_ADDRESS);
1600                        size_t bytes_written = process->WriteScalarToMemory (target_addr,
1601                                                                             new_scalar,
1602                                                                             byte_size,
1603                                                                             error);
1604                        if (!error.Success() || bytes_written != byte_size)
1605                            return false;
1606                    }
1607                }
1608                break;
1609            case Value::eValueTypeHostAddress:
1610                {
1611                    // If it is a host address, then we stuff the scalar as a DataBuffer into the Value's data.
1612                    DataExtractor new_data;
1613                    new_data.SetByteOrder (m_data.GetByteOrder());
1614
1615                    DataBufferSP buffer_sp (new DataBufferHeap(byte_size, 0));
1616                    m_data.SetData(buffer_sp, 0);
1617                    bool success = new_scalar.GetData(new_data);
1618                    if (success)
1619                    {
1620                        new_data.CopyByteOrderedData (0,
1621                                                      byte_size,
1622                                                      const_cast<uint8_t *>(m_data.GetDataStart()),
1623                                                      byte_size,
1624                                                      m_data.GetByteOrder());
1625                    }
1626                    m_value.GetScalar() = (uintptr_t)m_data.GetDataStart();
1627
1628                }
1629                break;
1630            case Value::eValueTypeFileAddress:
1631            case Value::eValueTypeScalar:
1632                break;
1633            }
1634        }
1635        else
1636        {
1637            return false;
1638        }
1639    }
1640    else
1641    {
1642        // We don't support setting things bigger than a scalar at present.
1643        return false;
1644    }
1645
1646    // If we have reached this point, then we have successfully changed the value.
1647    SetNeedsUpdate();
1648    return true;
1649}
1650
1651bool
1652ValueObject::GetDeclaration (Declaration &decl)
1653{
1654    decl.Clear();
1655    return false;
1656}
1657
1658LanguageType
1659ValueObject::GetObjectRuntimeLanguage ()
1660{
1661    return ClangASTType::GetMinimumLanguage (GetClangAST(),
1662                                             GetClangType());
1663}
1664
1665void
1666ValueObject::AddSyntheticChild (const ConstString &key, ValueObject *valobj)
1667{
1668    m_synthetic_children[key] = valobj;
1669}
1670
1671ValueObjectSP
1672ValueObject::GetSyntheticChild (const ConstString &key) const
1673{
1674    ValueObjectSP synthetic_child_sp;
1675    std::map<ConstString, ValueObject *>::const_iterator pos = m_synthetic_children.find (key);
1676    if (pos != m_synthetic_children.end())
1677        synthetic_child_sp = pos->second->GetSP();
1678    return synthetic_child_sp;
1679}
1680
1681bool
1682ValueObject::IsPointerType ()
1683{
1684    return ClangASTContext::IsPointerType (GetClangType());
1685}
1686
1687bool
1688ValueObject::IsArrayType ()
1689{
1690    return ClangASTContext::IsArrayType (GetClangType());
1691}
1692
1693bool
1694ValueObject::IsScalarType ()
1695{
1696    return ClangASTContext::IsScalarType (GetClangType());
1697}
1698
1699bool
1700ValueObject::IsIntegerType (bool &is_signed)
1701{
1702    return ClangASTContext::IsIntegerType (GetClangType(), is_signed);
1703}
1704
1705bool
1706ValueObject::IsPointerOrReferenceType ()
1707{
1708    return ClangASTContext::IsPointerOrReferenceType (GetClangType());
1709}
1710
1711bool
1712ValueObject::IsPossibleCPlusPlusDynamicType ()
1713{
1714    return ClangASTContext::IsPossibleCPlusPlusDynamicType (GetClangAST (), GetClangType());
1715}
1716
1717bool
1718ValueObject::IsPossibleDynamicType ()
1719{
1720    return ClangASTContext::IsPossibleDynamicType (GetClangAST (), GetClangType());
1721}
1722
1723ValueObjectSP
1724ValueObject::GetSyntheticArrayMember (int32_t index, bool can_create)
1725{
1726    if (IsArrayType())
1727        return GetSyntheticArrayMemberFromArray(index, can_create);
1728
1729    if (IsPointerType())
1730        return GetSyntheticArrayMemberFromPointer(index, can_create);
1731
1732    return ValueObjectSP();
1733
1734}
1735
1736ValueObjectSP
1737ValueObject::GetSyntheticArrayMemberFromPointer (int32_t index, bool can_create)
1738{
1739    ValueObjectSP synthetic_child_sp;
1740    if (IsPointerType ())
1741    {
1742        char index_str[64];
1743        snprintf(index_str, sizeof(index_str), "[%i]", index);
1744        ConstString index_const_str(index_str);
1745        // Check if we have already created a synthetic array member in this
1746        // valid object. If we have we will re-use it.
1747        synthetic_child_sp = GetSyntheticChild (index_const_str);
1748        if (!synthetic_child_sp)
1749        {
1750            ValueObject *synthetic_child;
1751            // We haven't made a synthetic array member for INDEX yet, so
1752            // lets make one and cache it for any future reference.
1753            synthetic_child = CreateChildAtIndex(0, true, index);
1754
1755            // Cache the value if we got one back...
1756            if (synthetic_child)
1757            {
1758                AddSyntheticChild(index_const_str, synthetic_child);
1759                synthetic_child_sp = synthetic_child->GetSP();
1760                synthetic_child_sp->SetName(ConstString(index_str));
1761                synthetic_child_sp->m_is_array_item_for_pointer = true;
1762            }
1763        }
1764    }
1765    return synthetic_child_sp;
1766}
1767
1768// This allows you to create an array member using and index
1769// that doesn't not fall in the normal bounds of the array.
1770// Many times structure can be defined as:
1771// struct Collection
1772// {
1773//     uint32_t item_count;
1774//     Item item_array[0];
1775// };
1776// The size of the "item_array" is 1, but many times in practice
1777// there are more items in "item_array".
1778
1779ValueObjectSP
1780ValueObject::GetSyntheticArrayMemberFromArray (int32_t index, bool can_create)
1781{
1782    ValueObjectSP synthetic_child_sp;
1783    if (IsArrayType ())
1784    {
1785        char index_str[64];
1786        snprintf(index_str, sizeof(index_str), "[%i]", index);
1787        ConstString index_const_str(index_str);
1788        // Check if we have already created a synthetic array member in this
1789        // valid object. If we have we will re-use it.
1790        synthetic_child_sp = GetSyntheticChild (index_const_str);
1791        if (!synthetic_child_sp)
1792        {
1793            ValueObject *synthetic_child;
1794            // We haven't made a synthetic array member for INDEX yet, so
1795            // lets make one and cache it for any future reference.
1796            synthetic_child = CreateChildAtIndex(0, true, index);
1797
1798            // Cache the value if we got one back...
1799            if (synthetic_child)
1800            {
1801                AddSyntheticChild(index_const_str, synthetic_child);
1802                synthetic_child_sp = synthetic_child->GetSP();
1803                synthetic_child_sp->SetName(ConstString(index_str));
1804                synthetic_child_sp->m_is_array_item_for_pointer = true;
1805            }
1806        }
1807    }
1808    return synthetic_child_sp;
1809}
1810
1811ValueObjectSP
1812ValueObject::GetSyntheticBitFieldChild (uint32_t from, uint32_t to, bool can_create)
1813{
1814    ValueObjectSP synthetic_child_sp;
1815    if (IsScalarType ())
1816    {
1817        char index_str[64];
1818        snprintf(index_str, sizeof(index_str), "[%i-%i]", from, to);
1819        ConstString index_const_str(index_str);
1820        // Check if we have already created a synthetic array member in this
1821        // valid object. If we have we will re-use it.
1822        synthetic_child_sp = GetSyntheticChild (index_const_str);
1823        if (!synthetic_child_sp)
1824        {
1825            ValueObjectChild *synthetic_child;
1826            // We haven't made a synthetic array member for INDEX yet, so
1827            // lets make one and cache it for any future reference.
1828            synthetic_child = new ValueObjectChild(*this,
1829                                                      GetClangAST(),
1830                                                      GetClangType(),
1831                                                      index_const_str,
1832                                                      GetByteSize(),
1833                                                      0,
1834                                                      to-from+1,
1835                                                      from,
1836                                                      false,
1837                                                      false,
1838                                                      eAddressTypeInvalid);
1839
1840            // Cache the value if we got one back...
1841            if (synthetic_child)
1842            {
1843                AddSyntheticChild(index_const_str, synthetic_child);
1844                synthetic_child_sp = synthetic_child->GetSP();
1845                synthetic_child_sp->SetName(ConstString(index_str));
1846                synthetic_child_sp->m_is_bitfield_for_scalar = true;
1847            }
1848        }
1849    }
1850    return synthetic_child_sp;
1851}
1852
1853ValueObjectSP
1854ValueObject::GetSyntheticArrayRangeChild (uint32_t from, uint32_t to, bool can_create)
1855{
1856    ValueObjectSP synthetic_child_sp;
1857    if (IsArrayType () || IsPointerType ())
1858    {
1859        char index_str[64];
1860        snprintf(index_str, sizeof(index_str), "[%i-%i]", from, to);
1861        ConstString index_const_str(index_str);
1862        // Check if we have already created a synthetic array member in this
1863        // valid object. If we have we will re-use it.
1864        synthetic_child_sp = GetSyntheticChild (index_const_str);
1865        if (!synthetic_child_sp)
1866        {
1867            ValueObjectSynthetic *synthetic_child;
1868
1869            // We haven't made a synthetic array member for INDEX yet, so
1870            // lets make one and cache it for any future reference.
1871            SyntheticArrayView *view = new SyntheticArrayView(SyntheticChildren::Flags());
1872            view->AddRange(from,to);
1873            SyntheticChildrenSP view_sp(view);
1874            synthetic_child = new ValueObjectSynthetic(*this, view_sp);
1875
1876            // Cache the value if we got one back...
1877            if (synthetic_child)
1878            {
1879                AddSyntheticChild(index_const_str, synthetic_child);
1880                synthetic_child_sp = synthetic_child->GetSP();
1881                synthetic_child_sp->SetName(ConstString(index_str));
1882                synthetic_child_sp->m_is_bitfield_for_scalar = true;
1883            }
1884        }
1885    }
1886    return synthetic_child_sp;
1887}
1888
1889ValueObjectSP
1890ValueObject::GetSyntheticChildAtOffset(uint32_t offset, const ClangASTType& type, bool can_create)
1891{
1892
1893    ValueObjectSP synthetic_child_sp;
1894
1895    char name_str[64];
1896    snprintf(name_str, sizeof(name_str), "@%i", offset);
1897    ConstString name_const_str(name_str);
1898
1899    // Check if we have already created a synthetic array member in this
1900    // valid object. If we have we will re-use it.
1901    synthetic_child_sp = GetSyntheticChild (name_const_str);
1902
1903    if (synthetic_child_sp.get())
1904        return synthetic_child_sp;
1905
1906    if (!can_create)
1907        return ValueObjectSP();
1908
1909    ValueObjectChild *synthetic_child = new ValueObjectChild(*this,
1910                                                             type.GetASTContext(),
1911                                                             type.GetOpaqueQualType(),
1912                                                             name_const_str,
1913                                                             type.GetTypeByteSize(),
1914                                                             offset,
1915                                                             0,
1916                                                             0,
1917                                                             false,
1918                                                             false,
1919                                                             eAddressTypeInvalid);
1920    if (synthetic_child)
1921    {
1922        AddSyntheticChild(name_const_str, synthetic_child);
1923        synthetic_child_sp = synthetic_child->GetSP();
1924        synthetic_child_sp->SetName(name_const_str);
1925        synthetic_child_sp->m_is_child_at_offset = true;
1926    }
1927    return synthetic_child_sp;
1928}
1929
1930// your expression path needs to have a leading . or ->
1931// (unless it somehow "looks like" an array, in which case it has
1932// a leading [ symbol). while the [ is meaningful and should be shown
1933// to the user, . and -> are just parser design, but by no means
1934// added information for the user.. strip them off
1935static const char*
1936SkipLeadingExpressionPathSeparators(const char* expression)
1937{
1938    if (!expression || !expression[0])
1939        return expression;
1940    if (expression[0] == '.')
1941        return expression+1;
1942    if (expression[0] == '-' && expression[1] == '>')
1943        return expression+2;
1944    return expression;
1945}
1946
1947ValueObjectSP
1948ValueObject::GetSyntheticExpressionPathChild(const char* expression, bool can_create)
1949{
1950    ValueObjectSP synthetic_child_sp;
1951    ConstString name_const_string(expression);
1952    // Check if we have already created a synthetic array member in this
1953    // valid object. If we have we will re-use it.
1954    synthetic_child_sp = GetSyntheticChild (name_const_string);
1955    if (!synthetic_child_sp)
1956    {
1957        // We haven't made a synthetic array member for expression yet, so
1958        // lets make one and cache it for any future reference.
1959        synthetic_child_sp = GetValueForExpressionPath(expression);
1960
1961        // Cache the value if we got one back...
1962        if (synthetic_child_sp.get())
1963        {
1964            AddSyntheticChild(name_const_string, synthetic_child_sp.get());
1965            synthetic_child_sp->SetName(ConstString(SkipLeadingExpressionPathSeparators(expression)));
1966            synthetic_child_sp->m_is_expression_path_child = true;
1967        }
1968    }
1969    return synthetic_child_sp;
1970}
1971
1972void
1973ValueObject::CalculateSyntheticValue (SyntheticValueType use_synthetic)
1974{
1975    if (use_synthetic == eNoSyntheticFilter)
1976        return;
1977
1978    UpdateFormatsIfNeeded(m_last_format_mgr_dynamic);
1979
1980    if (m_last_synthetic_filter.get() == NULL)
1981        return;
1982
1983    if (m_synthetic_value == NULL)
1984        m_synthetic_value = new ValueObjectSynthetic(*this, m_last_synthetic_filter);
1985
1986}
1987
1988void
1989ValueObject::CalculateDynamicValue (DynamicValueType use_dynamic)
1990{
1991    if (use_dynamic == eNoDynamicValues)
1992        return;
1993
1994    if (!m_dynamic_value && !IsDynamic())
1995    {
1996        ExecutionContext exe_ctx (GetExecutionContextRef());
1997        Process *process = exe_ctx.GetProcessPtr();
1998        if (process)
1999        {
2000            bool worth_having_dynamic_value = false;
2001
2002
2003            // FIXME: Process should have some kind of "map over Runtimes" so we don't have to
2004            // hard code this everywhere.
2005            LanguageType known_type = GetObjectRuntimeLanguage();
2006            if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2007            {
2008                LanguageRuntime *runtime = process->GetLanguageRuntime (known_type);
2009                if (runtime)
2010                    worth_having_dynamic_value = runtime->CouldHaveDynamicValue(*this);
2011            }
2012            else
2013            {
2014                LanguageRuntime *cpp_runtime = process->GetLanguageRuntime (eLanguageTypeC_plus_plus);
2015                if (cpp_runtime)
2016                    worth_having_dynamic_value = cpp_runtime->CouldHaveDynamicValue(*this);
2017
2018                if (!worth_having_dynamic_value)
2019                {
2020                    LanguageRuntime *objc_runtime = process->GetLanguageRuntime (eLanguageTypeObjC);
2021                    if (objc_runtime)
2022                        worth_having_dynamic_value = objc_runtime->CouldHaveDynamicValue(*this);
2023                }
2024            }
2025
2026            if (worth_having_dynamic_value)
2027                m_dynamic_value = new ValueObjectDynamicValue (*this, use_dynamic);
2028        }
2029    }
2030}
2031
2032ValueObjectSP
2033ValueObject::GetDynamicValue (DynamicValueType use_dynamic)
2034{
2035    if (use_dynamic == eNoDynamicValues)
2036        return ValueObjectSP();
2037
2038    if (!IsDynamic() && m_dynamic_value == NULL)
2039    {
2040        CalculateDynamicValue(use_dynamic);
2041    }
2042    if (m_dynamic_value)
2043        return m_dynamic_value->GetSP();
2044    else
2045        return ValueObjectSP();
2046}
2047
2048ValueObjectSP
2049ValueObject::GetStaticValue()
2050{
2051    return GetSP();
2052}
2053
2054// GetDynamicValue() returns a NULL SharedPointer if the object is not dynamic
2055// or we do not really want a dynamic VO. this method instead returns this object
2056// itself when making it synthetic has no meaning. this makes it much simpler
2057// to replace the SyntheticValue for the ValueObject
2058ValueObjectSP
2059ValueObject::GetSyntheticValue (SyntheticValueType use_synthetic)
2060{
2061    if (use_synthetic == eNoSyntheticFilter)
2062        return GetSP();
2063
2064    UpdateFormatsIfNeeded(m_last_format_mgr_dynamic);
2065
2066    if (m_last_synthetic_filter.get() == NULL)
2067        return GetSP();
2068
2069    CalculateSyntheticValue(use_synthetic);
2070
2071    if (m_synthetic_value)
2072        return m_synthetic_value->GetSP();
2073    else
2074        return GetSP();
2075}
2076
2077bool
2078ValueObject::HasSyntheticValue()
2079{
2080    UpdateFormatsIfNeeded(m_last_format_mgr_dynamic);
2081
2082    if (m_last_synthetic_filter.get() == NULL)
2083        return false;
2084
2085    CalculateSyntheticValue(eUseSyntheticFilter);
2086
2087    if (m_synthetic_value)
2088        return true;
2089    else
2090        return false;
2091}
2092
2093bool
2094ValueObject::GetBaseClassPath (Stream &s)
2095{
2096    if (IsBaseClass())
2097    {
2098        bool parent_had_base_class = GetParent() && GetParent()->GetBaseClassPath (s);
2099        clang_type_t clang_type = GetClangType();
2100        std::string cxx_class_name;
2101        bool this_had_base_class = ClangASTContext::GetCXXClassName (clang_type, cxx_class_name);
2102        if (this_had_base_class)
2103        {
2104            if (parent_had_base_class)
2105                s.PutCString("::");
2106            s.PutCString(cxx_class_name.c_str());
2107        }
2108        return parent_had_base_class || this_had_base_class;
2109    }
2110    return false;
2111}
2112
2113
2114ValueObject *
2115ValueObject::GetNonBaseClassParent()
2116{
2117    if (GetParent())
2118    {
2119        if (GetParent()->IsBaseClass())
2120            return GetParent()->GetNonBaseClassParent();
2121        else
2122            return GetParent();
2123    }
2124    return NULL;
2125}
2126
2127void
2128ValueObject::GetExpressionPath (Stream &s, bool qualify_cxx_base_classes, GetExpressionPathFormat epformat)
2129{
2130    const bool is_deref_of_parent = IsDereferenceOfParent ();
2131
2132    if (is_deref_of_parent && epformat == eDereferencePointers)
2133    {
2134        // this is the original format of GetExpressionPath() producing code like *(a_ptr).memberName, which is entirely
2135        // fine, until you put this into StackFrame::GetValueForVariableExpressionPath() which prefers to see a_ptr->memberName.
2136        // the eHonorPointers mode is meant to produce strings in this latter format
2137        s.PutCString("*(");
2138    }
2139
2140    ValueObject* parent = GetParent();
2141
2142    if (parent)
2143        parent->GetExpressionPath (s, qualify_cxx_base_classes, epformat);
2144
2145    // if we are a deref_of_parent just because we are synthetic array
2146    // members made up to allow ptr[%d] syntax to work in variable
2147    // printing, then add our name ([%d]) to the expression path
2148    if (m_is_array_item_for_pointer && epformat == eHonorPointers)
2149        s.PutCString(m_name.AsCString());
2150
2151    if (!IsBaseClass())
2152    {
2153        if (!is_deref_of_parent)
2154        {
2155            ValueObject *non_base_class_parent = GetNonBaseClassParent();
2156            if (non_base_class_parent)
2157            {
2158                clang_type_t non_base_class_parent_clang_type = non_base_class_parent->GetClangType();
2159                if (non_base_class_parent_clang_type)
2160                {
2161                    const uint32_t non_base_class_parent_type_info = ClangASTContext::GetTypeInfo (non_base_class_parent_clang_type, NULL, NULL);
2162
2163                    if (parent && parent->IsDereferenceOfParent() && epformat == eHonorPointers)
2164                    {
2165                        s.PutCString("->");
2166                    }
2167                    else
2168                    {
2169                        if (non_base_class_parent_type_info & ClangASTContext::eTypeIsPointer)
2170                        {
2171                            s.PutCString("->");
2172                        }
2173                        else if ((non_base_class_parent_type_info & ClangASTContext::eTypeHasChildren) &&
2174                                 !(non_base_class_parent_type_info & ClangASTContext::eTypeIsArray))
2175                        {
2176                            s.PutChar('.');
2177                        }
2178                    }
2179                }
2180            }
2181
2182            const char *name = GetName().GetCString();
2183            if (name)
2184            {
2185                if (qualify_cxx_base_classes)
2186                {
2187                    if (GetBaseClassPath (s))
2188                        s.PutCString("::");
2189                }
2190                s.PutCString(name);
2191            }
2192        }
2193    }
2194
2195    if (is_deref_of_parent && epformat == eDereferencePointers)
2196    {
2197        s.PutChar(')');
2198    }
2199}
2200
2201ValueObjectSP
2202ValueObject::GetValueForExpressionPath(const char* expression,
2203                                       const char** first_unparsed,
2204                                       ExpressionPathScanEndReason* reason_to_stop,
2205                                       ExpressionPathEndResultType* final_value_type,
2206                                       const GetValueForExpressionPathOptions& options,
2207                                       ExpressionPathAftermath* final_task_on_target)
2208{
2209
2210    const char* dummy_first_unparsed;
2211    ExpressionPathScanEndReason dummy_reason_to_stop;
2212    ExpressionPathEndResultType dummy_final_value_type;
2213    ExpressionPathAftermath dummy_final_task_on_target = ValueObject::eNothing;
2214
2215    ValueObjectSP ret_val = GetValueForExpressionPath_Impl(expression,
2216                                                           first_unparsed ? first_unparsed : &dummy_first_unparsed,
2217                                                           reason_to_stop ? reason_to_stop : &dummy_reason_to_stop,
2218                                                           final_value_type ? final_value_type : &dummy_final_value_type,
2219                                                           options,
2220                                                           final_task_on_target ? final_task_on_target : &dummy_final_task_on_target);
2221
2222    if (!final_task_on_target || *final_task_on_target == ValueObject::eNothing)
2223    {
2224        return ret_val;
2225    }
2226    if (ret_val.get() && *final_value_type == ePlain) // I can only deref and takeaddress of plain objects
2227    {
2228        if (*final_task_on_target == ValueObject::eDereference)
2229        {
2230            Error error;
2231            ValueObjectSP final_value = ret_val->Dereference(error);
2232            if (error.Fail() || !final_value.get())
2233            {
2234                *reason_to_stop = ValueObject::eDereferencingFailed;
2235                *final_value_type = ValueObject::eInvalid;
2236                return ValueObjectSP();
2237            }
2238            else
2239            {
2240                *final_task_on_target = ValueObject::eNothing;
2241                return final_value;
2242            }
2243        }
2244        if (*final_task_on_target == ValueObject::eTakeAddress)
2245        {
2246            Error error;
2247            ValueObjectSP final_value = ret_val->AddressOf(error);
2248            if (error.Fail() || !final_value.get())
2249            {
2250                *reason_to_stop = ValueObject::eTakingAddressFailed;
2251                *final_value_type = ValueObject::eInvalid;
2252                return ValueObjectSP();
2253            }
2254            else
2255            {
2256                *final_task_on_target = ValueObject::eNothing;
2257                return final_value;
2258            }
2259        }
2260    }
2261    return ret_val; // final_task_on_target will still have its original value, so you know I did not do it
2262}
2263
2264int
2265ValueObject::GetValuesForExpressionPath(const char* expression,
2266                                        ValueObjectListSP& list,
2267                                        const char** first_unparsed,
2268                                        ExpressionPathScanEndReason* reason_to_stop,
2269                                        ExpressionPathEndResultType* final_value_type,
2270                                        const GetValueForExpressionPathOptions& options,
2271                                        ExpressionPathAftermath* final_task_on_target)
2272{
2273    const char* dummy_first_unparsed;
2274    ExpressionPathScanEndReason dummy_reason_to_stop;
2275    ExpressionPathEndResultType dummy_final_value_type;
2276    ExpressionPathAftermath dummy_final_task_on_target = ValueObject::eNothing;
2277
2278    ValueObjectSP ret_val = GetValueForExpressionPath_Impl(expression,
2279                                                           first_unparsed ? first_unparsed : &dummy_first_unparsed,
2280                                                           reason_to_stop ? reason_to_stop : &dummy_reason_to_stop,
2281                                                           final_value_type ? final_value_type : &dummy_final_value_type,
2282                                                           options,
2283                                                           final_task_on_target ? final_task_on_target : &dummy_final_task_on_target);
2284
2285    if (!ret_val.get()) // if there are errors, I add nothing to the list
2286        return 0;
2287
2288    if (*reason_to_stop != eArrayRangeOperatorMet)
2289    {
2290        // I need not expand a range, just post-process the final value and return
2291        if (!final_task_on_target || *final_task_on_target == ValueObject::eNothing)
2292        {
2293            list->Append(ret_val);
2294            return 1;
2295        }
2296        if (ret_val.get() && *final_value_type == ePlain) // I can only deref and takeaddress of plain objects
2297        {
2298            if (*final_task_on_target == ValueObject::eDereference)
2299            {
2300                Error error;
2301                ValueObjectSP final_value = ret_val->Dereference(error);
2302                if (error.Fail() || !final_value.get())
2303                {
2304                    *reason_to_stop = ValueObject::eDereferencingFailed;
2305                    *final_value_type = ValueObject::eInvalid;
2306                    return 0;
2307                }
2308                else
2309                {
2310                    *final_task_on_target = ValueObject::eNothing;
2311                    list->Append(final_value);
2312                    return 1;
2313                }
2314            }
2315            if (*final_task_on_target == ValueObject::eTakeAddress)
2316            {
2317                Error error;
2318                ValueObjectSP final_value = ret_val->AddressOf(error);
2319                if (error.Fail() || !final_value.get())
2320                {
2321                    *reason_to_stop = ValueObject::eTakingAddressFailed;
2322                    *final_value_type = ValueObject::eInvalid;
2323                    return 0;
2324                }
2325                else
2326                {
2327                    *final_task_on_target = ValueObject::eNothing;
2328                    list->Append(final_value);
2329                    return 1;
2330                }
2331            }
2332        }
2333    }
2334    else
2335    {
2336        return ExpandArraySliceExpression(first_unparsed ? *first_unparsed : dummy_first_unparsed,
2337                                          first_unparsed ? first_unparsed : &dummy_first_unparsed,
2338                                          ret_val,
2339                                          list,
2340                                          reason_to_stop ? reason_to_stop : &dummy_reason_to_stop,
2341                                          final_value_type ? final_value_type : &dummy_final_value_type,
2342                                          options,
2343                                          final_task_on_target ? final_task_on_target : &dummy_final_task_on_target);
2344    }
2345    // in any non-covered case, just do the obviously right thing
2346    list->Append(ret_val);
2347    return 1;
2348}
2349
2350ValueObjectSP
2351ValueObject::GetValueForExpressionPath_Impl(const char* expression_cstr,
2352                                            const char** first_unparsed,
2353                                            ExpressionPathScanEndReason* reason_to_stop,
2354                                            ExpressionPathEndResultType* final_result,
2355                                            const GetValueForExpressionPathOptions& options,
2356                                            ExpressionPathAftermath* what_next)
2357{
2358    ValueObjectSP root = GetSP();
2359
2360    if (!root.get())
2361        return ValueObjectSP();
2362
2363    *first_unparsed = expression_cstr;
2364
2365    while (true)
2366    {
2367
2368        const char* expression_cstr = *first_unparsed; // hide the top level expression_cstr
2369
2370        clang_type_t root_clang_type = root->GetClangType();
2371        clang_type_t pointee_clang_type;
2372        Flags root_clang_type_info,pointee_clang_type_info;
2373
2374        root_clang_type_info = Flags(ClangASTContext::GetTypeInfo(root_clang_type, GetClangAST(), &pointee_clang_type));
2375        if (pointee_clang_type)
2376            pointee_clang_type_info = Flags(ClangASTContext::GetTypeInfo(pointee_clang_type, GetClangAST(), NULL));
2377
2378        if (!expression_cstr || *expression_cstr == '\0')
2379        {
2380            *reason_to_stop = ValueObject::eEndOfString;
2381            return root;
2382        }
2383
2384        switch (*expression_cstr)
2385        {
2386            case '-':
2387            {
2388                if (options.m_check_dot_vs_arrow_syntax &&
2389                    root_clang_type_info.Test(ClangASTContext::eTypeIsPointer) ) // if you are trying to use -> on a non-pointer and I must catch the error
2390                {
2391                    *first_unparsed = expression_cstr;
2392                    *reason_to_stop = ValueObject::eArrowInsteadOfDot;
2393                    *final_result = ValueObject::eInvalid;
2394                    return ValueObjectSP();
2395                }
2396                if (root_clang_type_info.Test(ClangASTContext::eTypeIsObjC) &&  // if yo are trying to extract an ObjC IVar when this is forbidden
2397                    root_clang_type_info.Test(ClangASTContext::eTypeIsPointer) &&
2398                    options.m_no_fragile_ivar)
2399                {
2400                    *first_unparsed = expression_cstr;
2401                    *reason_to_stop = ValueObject::eFragileIVarNotAllowed;
2402                    *final_result = ValueObject::eInvalid;
2403                    return ValueObjectSP();
2404                }
2405                if (expression_cstr[1] != '>')
2406                {
2407                    *first_unparsed = expression_cstr;
2408                    *reason_to_stop = ValueObject::eUnexpectedSymbol;
2409                    *final_result = ValueObject::eInvalid;
2410                    return ValueObjectSP();
2411                }
2412                expression_cstr++; // skip the -
2413            }
2414            case '.': // or fallthrough from ->
2415            {
2416                if (options.m_check_dot_vs_arrow_syntax && *expression_cstr == '.' &&
2417                    root_clang_type_info.Test(ClangASTContext::eTypeIsPointer)) // if you are trying to use . on a pointer and I must catch the error
2418                {
2419                    *first_unparsed = expression_cstr;
2420                    *reason_to_stop = ValueObject::eDotInsteadOfArrow;
2421                    *final_result = ValueObject::eInvalid;
2422                    return ValueObjectSP();
2423                }
2424                expression_cstr++; // skip .
2425                const char *next_separator = strpbrk(expression_cstr+1,"-.[");
2426                ConstString child_name;
2427                if (!next_separator) // if no other separator just expand this last layer
2428                {
2429                    child_name.SetCString (expression_cstr);
2430                    ValueObjectSP child_valobj_sp = root->GetChildMemberWithName(child_name, true);
2431
2432                    if (child_valobj_sp.get()) // we know we are done, so just return
2433                    {
2434                        *first_unparsed = '\0';
2435                        *reason_to_stop = ValueObject::eEndOfString;
2436                        *final_result = ValueObject::ePlain;
2437                        return child_valobj_sp;
2438                    }
2439                    else if (options.m_no_synthetic_children == false) // let's try with synthetic children
2440                    {
2441                        child_valobj_sp = root->GetSyntheticValue(eNoSyntheticFilter)->GetChildMemberWithName(child_name, true);
2442                    }
2443
2444                    // if we are here and options.m_no_synthetic_children is true, child_valobj_sp is going to be a NULL SP,
2445                    // so we hit the "else" branch, and return an error
2446                    if(child_valobj_sp.get()) // if it worked, just return
2447                    {
2448                        *first_unparsed = '\0';
2449                        *reason_to_stop = ValueObject::eEndOfString;
2450                        *final_result = ValueObject::ePlain;
2451                        return child_valobj_sp;
2452                    }
2453                    else
2454                    {
2455                        *first_unparsed = expression_cstr;
2456                        *reason_to_stop = ValueObject::eNoSuchChild;
2457                        *final_result = ValueObject::eInvalid;
2458                        return ValueObjectSP();
2459                    }
2460                }
2461                else // other layers do expand
2462                {
2463                    child_name.SetCStringWithLength(expression_cstr, next_separator - expression_cstr);
2464                    ValueObjectSP child_valobj_sp = root->GetChildMemberWithName(child_name, true);
2465                    if (child_valobj_sp.get()) // store the new root and move on
2466                    {
2467                        root = child_valobj_sp;
2468                        *first_unparsed = next_separator;
2469                        *final_result = ValueObject::ePlain;
2470                        continue;
2471                    }
2472                    else if (options.m_no_synthetic_children == false) // let's try with synthetic children
2473                    {
2474                        child_valobj_sp = root->GetSyntheticValue(eUseSyntheticFilter)->GetChildMemberWithName(child_name, true);
2475                    }
2476
2477                    // if we are here and options.m_no_synthetic_children is true, child_valobj_sp is going to be a NULL SP,
2478                    // so we hit the "else" branch, and return an error
2479                    if(child_valobj_sp.get()) // if it worked, move on
2480                    {
2481                        root = child_valobj_sp;
2482                        *first_unparsed = next_separator;
2483                        *final_result = ValueObject::ePlain;
2484                        continue;
2485                    }
2486                    else
2487                    {
2488                        *first_unparsed = expression_cstr;
2489                        *reason_to_stop = ValueObject::eNoSuchChild;
2490                        *final_result = ValueObject::eInvalid;
2491                        return ValueObjectSP();
2492                    }
2493                }
2494                break;
2495            }
2496            case '[':
2497            {
2498                if (!root_clang_type_info.Test(ClangASTContext::eTypeIsArray) && !root_clang_type_info.Test(ClangASTContext::eTypeIsPointer)) // if this is not a T[] nor a T*
2499                {
2500                    if (!root_clang_type_info.Test(ClangASTContext::eTypeIsScalar)) // if this is not even a scalar...
2501                    {
2502                        if (options.m_no_synthetic_children) // ...only chance left is synthetic
2503                        {
2504                            *first_unparsed = expression_cstr;
2505                            *reason_to_stop = ValueObject::eRangeOperatorInvalid;
2506                            *final_result = ValueObject::eInvalid;
2507                            return ValueObjectSP();
2508                        }
2509                    }
2510                    else if (!options.m_allow_bitfields_syntax) // if this is a scalar, check that we can expand bitfields
2511                    {
2512                        *first_unparsed = expression_cstr;
2513                        *reason_to_stop = ValueObject::eRangeOperatorNotAllowed;
2514                        *final_result = ValueObject::eInvalid;
2515                        return ValueObjectSP();
2516                    }
2517                }
2518                if (*(expression_cstr+1) == ']') // if this is an unbounded range it only works for arrays
2519                {
2520                    if (!root_clang_type_info.Test(ClangASTContext::eTypeIsArray))
2521                    {
2522                        *first_unparsed = expression_cstr;
2523                        *reason_to_stop = ValueObject::eEmptyRangeNotAllowed;
2524                        *final_result = ValueObject::eInvalid;
2525                        return ValueObjectSP();
2526                    }
2527                    else // even if something follows, we cannot expand unbounded ranges, just let the caller do it
2528                    {
2529                        *first_unparsed = expression_cstr+2;
2530                        *reason_to_stop = ValueObject::eArrayRangeOperatorMet;
2531                        *final_result = ValueObject::eUnboundedRange;
2532                        return root;
2533                    }
2534                }
2535                const char *separator_position = ::strchr(expression_cstr+1,'-');
2536                const char *close_bracket_position = ::strchr(expression_cstr+1,']');
2537                if (!close_bracket_position) // if there is no ], this is a syntax error
2538                {
2539                    *first_unparsed = expression_cstr;
2540                    *reason_to_stop = ValueObject::eUnexpectedSymbol;
2541                    *final_result = ValueObject::eInvalid;
2542                    return ValueObjectSP();
2543                }
2544                if (!separator_position || separator_position > close_bracket_position) // if no separator, this is either [] or [N]
2545                {
2546                    char *end = NULL;
2547                    unsigned long index = ::strtoul (expression_cstr+1, &end, 0);
2548                    if (!end || end != close_bracket_position) // if something weird is in our way return an error
2549                    {
2550                        *first_unparsed = expression_cstr;
2551                        *reason_to_stop = ValueObject::eUnexpectedSymbol;
2552                        *final_result = ValueObject::eInvalid;
2553                        return ValueObjectSP();
2554                    }
2555                    if (end - expression_cstr == 1) // if this is [], only return a valid value for arrays
2556                    {
2557                        if (root_clang_type_info.Test(ClangASTContext::eTypeIsArray))
2558                        {
2559                            *first_unparsed = expression_cstr+2;
2560                            *reason_to_stop = ValueObject::eArrayRangeOperatorMet;
2561                            *final_result = ValueObject::eUnboundedRange;
2562                            return root;
2563                        }
2564                        else
2565                        {
2566                            *first_unparsed = expression_cstr;
2567                            *reason_to_stop = ValueObject::eEmptyRangeNotAllowed;
2568                            *final_result = ValueObject::eInvalid;
2569                            return ValueObjectSP();
2570                        }
2571                    }
2572                    // from here on we do have a valid index
2573                    if (root_clang_type_info.Test(ClangASTContext::eTypeIsArray))
2574                    {
2575                        ValueObjectSP child_valobj_sp = root->GetChildAtIndex(index, true);
2576                        if (!child_valobj_sp)
2577                            child_valobj_sp = root->GetSyntheticArrayMemberFromArray(index, true);
2578                        if (!child_valobj_sp)
2579                            if (root->HasSyntheticValue() && root->GetSyntheticValue(eUseSyntheticFilter)->GetNumChildren() > index)
2580                                child_valobj_sp = root->GetSyntheticValue(eUseSyntheticFilter)->GetChildAtIndex(index, true);
2581                        if (child_valobj_sp)
2582                        {
2583                            root = child_valobj_sp;
2584                            *first_unparsed = end+1; // skip ]
2585                            *final_result = ValueObject::ePlain;
2586                            continue;
2587                        }
2588                        else
2589                        {
2590                            *first_unparsed = expression_cstr;
2591                            *reason_to_stop = ValueObject::eNoSuchChild;
2592                            *final_result = ValueObject::eInvalid;
2593                            return ValueObjectSP();
2594                        }
2595                    }
2596                    else if (root_clang_type_info.Test(ClangASTContext::eTypeIsPointer))
2597                    {
2598                        if (*what_next == ValueObject::eDereference &&  // if this is a ptr-to-scalar, I am accessing it by index and I would have deref'ed anyway, then do it now and use this as a bitfield
2599                            pointee_clang_type_info.Test(ClangASTContext::eTypeIsScalar))
2600                        {
2601                            Error error;
2602                            root = root->Dereference(error);
2603                            if (error.Fail() || !root.get())
2604                            {
2605                                *first_unparsed = expression_cstr;
2606                                *reason_to_stop = ValueObject::eDereferencingFailed;
2607                                *final_result = ValueObject::eInvalid;
2608                                return ValueObjectSP();
2609                            }
2610                            else
2611                            {
2612                                *what_next = eNothing;
2613                                continue;
2614                            }
2615                        }
2616                        else
2617                        {
2618                            if (ClangASTType::GetMinimumLanguage(root->GetClangAST(),
2619                                                                    root->GetClangType()) == eLanguageTypeObjC
2620                                &&
2621                                ClangASTContext::IsPointerType(ClangASTType::GetPointeeType(root->GetClangType())) == false
2622                                &&
2623                                root->HasSyntheticValue()
2624                                &&
2625                                options.m_no_synthetic_children == false)
2626                            {
2627                                root = root->GetSyntheticValue(eUseSyntheticFilter)->GetChildAtIndex(index, true);
2628                            }
2629                            else
2630                                root = root->GetSyntheticArrayMemberFromPointer(index, true);
2631                            if (!root.get())
2632                            {
2633                                *first_unparsed = expression_cstr;
2634                                *reason_to_stop = ValueObject::eNoSuchChild;
2635                                *final_result = ValueObject::eInvalid;
2636                                return ValueObjectSP();
2637                            }
2638                            else
2639                            {
2640                                *first_unparsed = end+1; // skip ]
2641                                *final_result = ValueObject::ePlain;
2642                                continue;
2643                            }
2644                        }
2645                    }
2646                    else if (ClangASTContext::IsScalarType(root_clang_type))
2647                    {
2648                        root = root->GetSyntheticBitFieldChild(index, index, true);
2649                        if (!root.get())
2650                        {
2651                            *first_unparsed = expression_cstr;
2652                            *reason_to_stop = ValueObject::eNoSuchChild;
2653                            *final_result = ValueObject::eInvalid;
2654                            return ValueObjectSP();
2655                        }
2656                        else // we do not know how to expand members of bitfields, so we just return and let the caller do any further processing
2657                        {
2658                            *first_unparsed = end+1; // skip ]
2659                            *reason_to_stop = ValueObject::eBitfieldRangeOperatorMet;
2660                            *final_result = ValueObject::eBitfield;
2661                            return root;
2662                        }
2663                    }
2664                    else if (root->HasSyntheticValue() && options.m_no_synthetic_children == false)
2665                    {
2666                        root = root->GetSyntheticValue(eUseSyntheticFilter)->GetChildAtIndex(index, true);
2667                        if (!root.get())
2668                        {
2669                            *first_unparsed = expression_cstr;
2670                            *reason_to_stop = ValueObject::eNoSuchChild;
2671                            *final_result = ValueObject::eInvalid;
2672                            return ValueObjectSP();
2673                        }
2674                        else
2675                        {
2676                            *first_unparsed = end+1; // skip ]
2677                            *final_result = ValueObject::ePlain;
2678                            continue;
2679                        }
2680                    }
2681                    else
2682                    {
2683                        *first_unparsed = expression_cstr;
2684                        *reason_to_stop = ValueObject::eNoSuchChild;
2685                        *final_result = ValueObject::eInvalid;
2686                        return ValueObjectSP();
2687                    }
2688                }
2689                else // we have a low and a high index
2690                {
2691                    char *end = NULL;
2692                    unsigned long index_lower = ::strtoul (expression_cstr+1, &end, 0);
2693                    if (!end || end != separator_position) // if something weird is in our way return an error
2694                    {
2695                        *first_unparsed = expression_cstr;
2696                        *reason_to_stop = ValueObject::eUnexpectedSymbol;
2697                        *final_result = ValueObject::eInvalid;
2698                        return ValueObjectSP();
2699                    }
2700                    unsigned long index_higher = ::strtoul (separator_position+1, &end, 0);
2701                    if (!end || end != close_bracket_position) // if something weird is in our way return an error
2702                    {
2703                        *first_unparsed = expression_cstr;
2704                        *reason_to_stop = ValueObject::eUnexpectedSymbol;
2705                        *final_result = ValueObject::eInvalid;
2706                        return ValueObjectSP();
2707                    }
2708                    if (index_lower > index_higher) // swap indices if required
2709                    {
2710                        unsigned long temp = index_lower;
2711                        index_lower = index_higher;
2712                        index_higher = temp;
2713                    }
2714                    if (root_clang_type_info.Test(ClangASTContext::eTypeIsScalar)) // expansion only works for scalars
2715                    {
2716                        root = root->GetSyntheticBitFieldChild(index_lower, index_higher, true);
2717                        if (!root.get())
2718                        {
2719                            *first_unparsed = expression_cstr;
2720                            *reason_to_stop = ValueObject::eNoSuchChild;
2721                            *final_result = ValueObject::eInvalid;
2722                            return ValueObjectSP();
2723                        }
2724                        else
2725                        {
2726                            *first_unparsed = end+1; // skip ]
2727                            *reason_to_stop = ValueObject::eBitfieldRangeOperatorMet;
2728                            *final_result = ValueObject::eBitfield;
2729                            return root;
2730                        }
2731                    }
2732                    else if (root_clang_type_info.Test(ClangASTContext::eTypeIsPointer) && // if this is a ptr-to-scalar, I am accessing it by index and I would have deref'ed anyway, then do it now and use this as a bitfield
2733                             *what_next == ValueObject::eDereference &&
2734                             pointee_clang_type_info.Test(ClangASTContext::eTypeIsScalar))
2735                    {
2736                        Error error;
2737                        root = root->Dereference(error);
2738                        if (error.Fail() || !root.get())
2739                        {
2740                            *first_unparsed = expression_cstr;
2741                            *reason_to_stop = ValueObject::eDereferencingFailed;
2742                            *final_result = ValueObject::eInvalid;
2743                            return ValueObjectSP();
2744                        }
2745                        else
2746                        {
2747                            *what_next = ValueObject::eNothing;
2748                            continue;
2749                        }
2750                    }
2751                    else
2752                    {
2753                        *first_unparsed = expression_cstr;
2754                        *reason_to_stop = ValueObject::eArrayRangeOperatorMet;
2755                        *final_result = ValueObject::eBoundedRange;
2756                        return root;
2757                    }
2758                }
2759                break;
2760            }
2761            default: // some non-separator is in the way
2762            {
2763                *first_unparsed = expression_cstr;
2764                *reason_to_stop = ValueObject::eUnexpectedSymbol;
2765                *final_result = ValueObject::eInvalid;
2766                return ValueObjectSP();
2767                break;
2768            }
2769        }
2770    }
2771}
2772
2773int
2774ValueObject::ExpandArraySliceExpression(const char* expression_cstr,
2775                                        const char** first_unparsed,
2776                                        ValueObjectSP root,
2777                                        ValueObjectListSP& list,
2778                                        ExpressionPathScanEndReason* reason_to_stop,
2779                                        ExpressionPathEndResultType* final_result,
2780                                        const GetValueForExpressionPathOptions& options,
2781                                        ExpressionPathAftermath* what_next)
2782{
2783    if (!root.get())
2784        return 0;
2785
2786    *first_unparsed = expression_cstr;
2787
2788    while (true)
2789    {
2790
2791        const char* expression_cstr = *first_unparsed; // hide the top level expression_cstr
2792
2793        clang_type_t root_clang_type = root->GetClangType();
2794        clang_type_t pointee_clang_type;
2795        Flags root_clang_type_info,pointee_clang_type_info;
2796
2797        root_clang_type_info = Flags(ClangASTContext::GetTypeInfo(root_clang_type, GetClangAST(), &pointee_clang_type));
2798        if (pointee_clang_type)
2799            pointee_clang_type_info = Flags(ClangASTContext::GetTypeInfo(pointee_clang_type, GetClangAST(), NULL));
2800
2801        if (!expression_cstr || *expression_cstr == '\0')
2802        {
2803            *reason_to_stop = ValueObject::eEndOfString;
2804            list->Append(root);
2805            return 1;
2806        }
2807
2808        switch (*expression_cstr)
2809        {
2810            case '[':
2811            {
2812                if (!root_clang_type_info.Test(ClangASTContext::eTypeIsArray) && !root_clang_type_info.Test(ClangASTContext::eTypeIsPointer)) // if this is not a T[] nor a T*
2813                {
2814                    if (!root_clang_type_info.Test(ClangASTContext::eTypeIsScalar)) // if this is not even a scalar, this syntax is just plain wrong!
2815                    {
2816                        *first_unparsed = expression_cstr;
2817                        *reason_to_stop = ValueObject::eRangeOperatorInvalid;
2818                        *final_result = ValueObject::eInvalid;
2819                        return 0;
2820                    }
2821                    else if (!options.m_allow_bitfields_syntax) // if this is a scalar, check that we can expand bitfields
2822                    {
2823                        *first_unparsed = expression_cstr;
2824                        *reason_to_stop = ValueObject::eRangeOperatorNotAllowed;
2825                        *final_result = ValueObject::eInvalid;
2826                        return 0;
2827                    }
2828                }
2829                if (*(expression_cstr+1) == ']') // if this is an unbounded range it only works for arrays
2830                {
2831                    if (!root_clang_type_info.Test(ClangASTContext::eTypeIsArray))
2832                    {
2833                        *first_unparsed = expression_cstr;
2834                        *reason_to_stop = ValueObject::eEmptyRangeNotAllowed;
2835                        *final_result = ValueObject::eInvalid;
2836                        return 0;
2837                    }
2838                    else // expand this into list
2839                    {
2840                        int max_index = root->GetNumChildren() - 1;
2841                        for (int index = 0; index < max_index; index++)
2842                        {
2843                            ValueObjectSP child =
2844                                root->GetChildAtIndex(index, true);
2845                            list->Append(child);
2846                        }
2847                        *first_unparsed = expression_cstr+2;
2848                        *reason_to_stop = ValueObject::eRangeOperatorExpanded;
2849                        *final_result = ValueObject::eValueObjectList;
2850                        return max_index; // tell me number of items I added to the VOList
2851                    }
2852                }
2853                const char *separator_position = ::strchr(expression_cstr+1,'-');
2854                const char *close_bracket_position = ::strchr(expression_cstr+1,']');
2855                if (!close_bracket_position) // if there is no ], this is a syntax error
2856                {
2857                    *first_unparsed = expression_cstr;
2858                    *reason_to_stop = ValueObject::eUnexpectedSymbol;
2859                    *final_result = ValueObject::eInvalid;
2860                    return 0;
2861                }
2862                if (!separator_position || separator_position > close_bracket_position) // if no separator, this is either [] or [N]
2863                {
2864                    char *end = NULL;
2865                    unsigned long index = ::strtoul (expression_cstr+1, &end, 0);
2866                    if (!end || end != close_bracket_position) // if something weird is in our way return an error
2867                    {
2868                        *first_unparsed = expression_cstr;
2869                        *reason_to_stop = ValueObject::eUnexpectedSymbol;
2870                        *final_result = ValueObject::eInvalid;
2871                        return 0;
2872                    }
2873                    if (end - expression_cstr == 1) // if this is [], only return a valid value for arrays
2874                    {
2875                        if (root_clang_type_info.Test(ClangASTContext::eTypeIsArray))
2876                        {
2877                            int max_index = root->GetNumChildren() - 1;
2878                            for (int index = 0; index < max_index; index++)
2879                            {
2880                                ValueObjectSP child =
2881                                root->GetChildAtIndex(index, true);
2882                                list->Append(child);
2883                            }
2884                            *first_unparsed = expression_cstr+2;
2885                            *reason_to_stop = ValueObject::eRangeOperatorExpanded;
2886                            *final_result = ValueObject::eValueObjectList;
2887                            return max_index; // tell me number of items I added to the VOList
2888                        }
2889                        else
2890                        {
2891                            *first_unparsed = expression_cstr;
2892                            *reason_to_stop = ValueObject::eEmptyRangeNotAllowed;
2893                            *final_result = ValueObject::eInvalid;
2894                            return 0;
2895                        }
2896                    }
2897                    // from here on we do have a valid index
2898                    if (root_clang_type_info.Test(ClangASTContext::eTypeIsArray))
2899                    {
2900                        root = root->GetChildAtIndex(index, true);
2901                        if (!root.get())
2902                        {
2903                            *first_unparsed = expression_cstr;
2904                            *reason_to_stop = ValueObject::eNoSuchChild;
2905                            *final_result = ValueObject::eInvalid;
2906                            return 0;
2907                        }
2908                        else
2909                        {
2910                            list->Append(root);
2911                            *first_unparsed = end+1; // skip ]
2912                            *reason_to_stop = ValueObject::eRangeOperatorExpanded;
2913                            *final_result = ValueObject::eValueObjectList;
2914                            return 1;
2915                        }
2916                    }
2917                    else if (root_clang_type_info.Test(ClangASTContext::eTypeIsPointer))
2918                    {
2919                        if (*what_next == ValueObject::eDereference &&  // if this is a ptr-to-scalar, I am accessing it by index and I would have deref'ed anyway, then do it now and use this as a bitfield
2920                            pointee_clang_type_info.Test(ClangASTContext::eTypeIsScalar))
2921                        {
2922                            Error error;
2923                            root = root->Dereference(error);
2924                            if (error.Fail() || !root.get())
2925                            {
2926                                *first_unparsed = expression_cstr;
2927                                *reason_to_stop = ValueObject::eDereferencingFailed;
2928                                *final_result = ValueObject::eInvalid;
2929                                return 0;
2930                            }
2931                            else
2932                            {
2933                                *what_next = eNothing;
2934                                continue;
2935                            }
2936                        }
2937                        else
2938                        {
2939                            root = root->GetSyntheticArrayMemberFromPointer(index, true);
2940                            if (!root.get())
2941                            {
2942                                *first_unparsed = expression_cstr;
2943                                *reason_to_stop = ValueObject::eNoSuchChild;
2944                                *final_result = ValueObject::eInvalid;
2945                                return 0;
2946                            }
2947                            else
2948                            {
2949                                list->Append(root);
2950                                *first_unparsed = end+1; // skip ]
2951                                *reason_to_stop = ValueObject::eRangeOperatorExpanded;
2952                                *final_result = ValueObject::eValueObjectList;
2953                                return 1;
2954                            }
2955                        }
2956                    }
2957                    else /*if (ClangASTContext::IsScalarType(root_clang_type))*/
2958                    {
2959                        root = root->GetSyntheticBitFieldChild(index, index, true);
2960                        if (!root.get())
2961                        {
2962                            *first_unparsed = expression_cstr;
2963                            *reason_to_stop = ValueObject::eNoSuchChild;
2964                            *final_result = ValueObject::eInvalid;
2965                            return 0;
2966                        }
2967                        else // we do not know how to expand members of bitfields, so we just return and let the caller do any further processing
2968                        {
2969                            list->Append(root);
2970                            *first_unparsed = end+1; // skip ]
2971                            *reason_to_stop = ValueObject::eRangeOperatorExpanded;
2972                            *final_result = ValueObject::eValueObjectList;
2973                            return 1;
2974                        }
2975                    }
2976                }
2977                else // we have a low and a high index
2978                {
2979                    char *end = NULL;
2980                    unsigned long index_lower = ::strtoul (expression_cstr+1, &end, 0);
2981                    if (!end || end != separator_position) // if something weird is in our way return an error
2982                    {
2983                        *first_unparsed = expression_cstr;
2984                        *reason_to_stop = ValueObject::eUnexpectedSymbol;
2985                        *final_result = ValueObject::eInvalid;
2986                        return 0;
2987                    }
2988                    unsigned long index_higher = ::strtoul (separator_position+1, &end, 0);
2989                    if (!end || end != close_bracket_position) // if something weird is in our way return an error
2990                    {
2991                        *first_unparsed = expression_cstr;
2992                        *reason_to_stop = ValueObject::eUnexpectedSymbol;
2993                        *final_result = ValueObject::eInvalid;
2994                        return 0;
2995                    }
2996                    if (index_lower > index_higher) // swap indices if required
2997                    {
2998                        unsigned long temp = index_lower;
2999                        index_lower = index_higher;
3000                        index_higher = temp;
3001                    }
3002                    if (root_clang_type_info.Test(ClangASTContext::eTypeIsScalar)) // expansion only works for scalars
3003                    {
3004                        root = root->GetSyntheticBitFieldChild(index_lower, index_higher, true);
3005                        if (!root.get())
3006                        {
3007                            *first_unparsed = expression_cstr;
3008                            *reason_to_stop = ValueObject::eNoSuchChild;
3009                            *final_result = ValueObject::eInvalid;
3010                            return 0;
3011                        }
3012                        else
3013                        {
3014                            list->Append(root);
3015                            *first_unparsed = end+1; // skip ]
3016                            *reason_to_stop = ValueObject::eRangeOperatorExpanded;
3017                            *final_result = ValueObject::eValueObjectList;
3018                            return 1;
3019                        }
3020                    }
3021                    else if (root_clang_type_info.Test(ClangASTContext::eTypeIsPointer) && // if this is a ptr-to-scalar, I am accessing it by index and I would have deref'ed anyway, then do it now and use this as a bitfield
3022                             *what_next == ValueObject::eDereference &&
3023                             pointee_clang_type_info.Test(ClangASTContext::eTypeIsScalar))
3024                    {
3025                        Error error;
3026                        root = root->Dereference(error);
3027                        if (error.Fail() || !root.get())
3028                        {
3029                            *first_unparsed = expression_cstr;
3030                            *reason_to_stop = ValueObject::eDereferencingFailed;
3031                            *final_result = ValueObject::eInvalid;
3032                            return 0;
3033                        }
3034                        else
3035                        {
3036                            *what_next = ValueObject::eNothing;
3037                            continue;
3038                        }
3039                    }
3040                    else
3041                    {
3042                        for (unsigned long index = index_lower;
3043                             index <= index_higher; index++)
3044                        {
3045                            ValueObjectSP child =
3046                                root->GetChildAtIndex(index, true);
3047                            list->Append(child);
3048                        }
3049                        *first_unparsed = end+1;
3050                        *reason_to_stop = ValueObject::eRangeOperatorExpanded;
3051                        *final_result = ValueObject::eValueObjectList;
3052                        return index_higher-index_lower+1; // tell me number of items I added to the VOList
3053                    }
3054                }
3055                break;
3056            }
3057            default: // some non-[ separator, or something entirely wrong, is in the way
3058            {
3059                *first_unparsed = expression_cstr;
3060                *reason_to_stop = ValueObject::eUnexpectedSymbol;
3061                *final_result = ValueObject::eInvalid;
3062                return 0;
3063                break;
3064            }
3065        }
3066    }
3067}
3068
3069void
3070ValueObject::DumpValueObject
3071(
3072    Stream &s,
3073    ValueObject *valobj,
3074    const char *root_valobj_name,
3075    uint32_t ptr_depth,
3076    uint32_t curr_depth,
3077    uint32_t max_depth,
3078    bool show_types,
3079    bool show_location,
3080    bool use_objc,
3081    DynamicValueType use_dynamic,
3082    bool use_synth,
3083    bool scope_already_checked,
3084    bool flat_output,
3085    uint32_t omit_summary_depth,
3086    bool ignore_cap,
3087    Format format_override       // Normally the format is in the valobj, but we might want to override this
3088)
3089{
3090    if (valobj)
3091    {
3092        bool update_success = valobj->UpdateValueIfNeeded (use_dynamic, true);
3093
3094        if (update_success && use_dynamic != eNoDynamicValues)
3095        {
3096            ValueObject *dynamic_value = valobj->GetDynamicValue(use_dynamic).get();
3097            if (dynamic_value)
3098                valobj = dynamic_value;
3099        }
3100
3101        clang_type_t clang_type = valobj->GetClangType();
3102
3103        const Flags type_flags (ClangASTContext::GetTypeInfo (clang_type, NULL, NULL));
3104        const char *err_cstr = NULL;
3105        const bool has_children = type_flags.Test (ClangASTContext::eTypeHasChildren);
3106        const bool has_value = type_flags.Test (ClangASTContext::eTypeHasValue);
3107
3108        const bool print_valobj = flat_output == false || has_value;
3109
3110        if (print_valobj)
3111        {
3112            if (show_location)
3113            {
3114                s.Printf("%s: ", valobj->GetLocationAsCString());
3115            }
3116
3117            s.Indent();
3118
3119            // Always show the type for the top level items.
3120            if (show_types || (curr_depth == 0 && !flat_output))
3121            {
3122                const char* typeName = valobj->GetTypeName().AsCString("<invalid type>");
3123                s.Printf("(%s", typeName);
3124                // only show dynamic types if the user really wants to see types
3125                if (show_types && use_dynamic != eNoDynamicValues &&
3126                    (/*strstr(typeName, "id") == typeName ||*/
3127                     ClangASTType::GetMinimumLanguage(valobj->GetClangAST(), valobj->GetClangType()) == eLanguageTypeObjC))
3128                {
3129                    ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
3130                    Process *process = exe_ctx.GetProcessPtr();
3131                    if (process == NULL)
3132                        s.Printf(", dynamic type: unknown) ");
3133                    else
3134                    {
3135                        ObjCLanguageRuntime *runtime = process->GetObjCLanguageRuntime();
3136                        if (runtime == NULL)
3137                            s.Printf(", dynamic type: unknown) ");
3138                        else
3139                        {
3140                            ObjCLanguageRuntime::ObjCISA isa = runtime->GetISA(*valobj);
3141                            if (!runtime->IsValidISA(isa))
3142                                s.Printf(", dynamic type: unknown) ");
3143                            else
3144                                s.Printf(", dynamic type: %s) ",
3145                                         runtime->GetActualTypeName(isa).GetCString());
3146                        }
3147                    }
3148                }
3149                else
3150                    s.Printf(") ");
3151            }
3152
3153
3154            if (flat_output)
3155            {
3156                // If we are showing types, also qualify the C++ base classes
3157                const bool qualify_cxx_base_classes = show_types;
3158                valobj->GetExpressionPath(s, qualify_cxx_base_classes);
3159                s.PutCString(" =");
3160            }
3161            else
3162            {
3163                const char *name_cstr = root_valobj_name ? root_valobj_name : valobj->GetName().AsCString("");
3164                s.Printf ("%s =", name_cstr);
3165            }
3166
3167            if (!scope_already_checked && !valobj->IsInScope())
3168            {
3169                err_cstr = "out of scope";
3170            }
3171        }
3172
3173        std::string value_str;
3174        const char *val_cstr = NULL;
3175        const char *sum_cstr = NULL;
3176        TypeSummaryImpl* entry = valobj->GetSummaryFormat().get();
3177
3178        if (omit_summary_depth > 0)
3179            entry = NULL;
3180
3181        Format orig_format = kNumFormats;
3182        if (err_cstr == NULL)
3183        {
3184            if (format_override != eFormatDefault)
3185            {
3186                orig_format = valobj->GetFormat();
3187                valobj->SetFormat (format_override);
3188            }
3189            val_cstr = valobj->GetValueAsCString();
3190            if (val_cstr)
3191            {
3192                // Cache the value in our own storage as running summaries might
3193                // change our value from underneath us
3194                value_str = val_cstr;
3195            }
3196            if (orig_format != kNumFormats && orig_format != format_override)
3197            {
3198                valobj->SetFormat (orig_format);
3199                orig_format = kNumFormats;
3200            }
3201            err_cstr = valobj->GetError().AsCString();
3202        }
3203
3204        if (err_cstr)
3205        {
3206            s.Printf (" <%s>\n", err_cstr);
3207        }
3208        else
3209        {
3210            const bool is_ref = type_flags.Test (ClangASTContext::eTypeIsReference);
3211            if (print_valobj)
3212            {
3213                if (omit_summary_depth == 0)
3214                    sum_cstr = valobj->GetSummaryAsCString();
3215
3216                // Make sure we have a value and make sure the summary didn't
3217                // specify that the value should not be printed
3218                if (!value_str.empty() && (entry == NULL || entry->DoesPrintValue() || sum_cstr == NULL))
3219                    s.Printf(" %s", value_str.c_str());
3220
3221                if (sum_cstr)
3222                {
3223                    // for some reason, using %@ (ObjC description) in a summary string, makes
3224                    // us believe we need to reset ourselves, thus invalidating the content of
3225                    // sum_cstr. Thus, IF we had a valid sum_cstr before, but it is now empty
3226                    // let us recalculate it!
3227                    if (sum_cstr[0] == '\0')
3228                        s.Printf(" %s", valobj->GetSummaryAsCString());
3229                    else
3230                        s.Printf(" %s", sum_cstr);
3231                }
3232
3233                if (use_objc)
3234                {
3235                    const char *object_desc = valobj->GetObjectDescription();
3236                    if (object_desc)
3237                        s.Printf(" %s\n", object_desc);
3238                    else
3239                        s.Printf (" [no Objective-C description available]\n");
3240                    return;
3241                }
3242            }
3243
3244            if (curr_depth < max_depth)
3245            {
3246                // We will show children for all concrete types. We won't show
3247                // pointer contents unless a pointer depth has been specified.
3248                // We won't reference contents unless the reference is the
3249                // root object (depth of zero).
3250                bool print_children = true;
3251
3252                // Use a new temporary pointer depth in case we override the
3253                // current pointer depth below...
3254                uint32_t curr_ptr_depth = ptr_depth;
3255
3256                const bool is_ptr = type_flags.Test (ClangASTContext::eTypeIsPointer);
3257                if (is_ptr || is_ref)
3258                {
3259                    // We have a pointer or reference whose value is an address.
3260                    // Make sure that address is not NULL
3261                    AddressType ptr_address_type;
3262                    if (valobj->GetPointerValue (&ptr_address_type) == 0)
3263                        print_children = false;
3264
3265                    else if (is_ref && curr_depth == 0)
3266                    {
3267                        // If this is the root object (depth is zero) that we are showing
3268                        // and it is a reference, and no pointer depth has been supplied
3269                        // print out what it references. Don't do this at deeper depths
3270                        // otherwise we can end up with infinite recursion...
3271                        curr_ptr_depth = 1;
3272                    }
3273
3274                    if (curr_ptr_depth == 0)
3275                        print_children = false;
3276                }
3277
3278                if (print_children && (!entry || entry->DoesPrintChildren() || !sum_cstr))
3279                {
3280                    ValueObjectSP synth_valobj = valobj->GetSyntheticValue (use_synth ?
3281                                                                            eUseSyntheticFilter :
3282                                                                            eNoSyntheticFilter);
3283                    uint32_t num_children = synth_valobj->GetNumChildren();
3284                    bool print_dotdotdot = false;
3285                    if (num_children)
3286                    {
3287                        if (flat_output)
3288                        {
3289                            if (print_valobj)
3290                                s.EOL();
3291                        }
3292                        else
3293                        {
3294                            if (print_valobj)
3295                                s.PutCString(is_ref ? ": {\n" : " {\n");
3296                            s.IndentMore();
3297                        }
3298
3299                        uint32_t max_num_children = valobj->GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();
3300
3301                        if (num_children > max_num_children && !ignore_cap)
3302                        {
3303                            num_children = max_num_children;
3304                            print_dotdotdot = true;
3305                        }
3306
3307                        for (uint32_t idx=0; idx<num_children; ++idx)
3308                        {
3309                            ValueObjectSP child_sp(synth_valobj->GetChildAtIndex(idx, true));
3310                            if (child_sp.get())
3311                            {
3312                                DumpValueObject (s,
3313                                                 child_sp.get(),
3314                                                 NULL,
3315                                                 (is_ptr || is_ref) ? curr_ptr_depth - 1 : curr_ptr_depth,
3316                                                 curr_depth + 1,
3317                                                 max_depth,
3318                                                 show_types,
3319                                                 show_location,
3320                                                 false,
3321                                                 use_dynamic,
3322                                                 use_synth,
3323                                                 true,
3324                                                 flat_output,
3325                                                 omit_summary_depth > 1 ? omit_summary_depth - 1 : 0,
3326                                                 ignore_cap,
3327                                                 format_override);
3328                            }
3329                        }
3330
3331                        if (!flat_output)
3332                        {
3333                            if (print_dotdotdot)
3334                            {
3335                                ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
3336                                Target *target = exe_ctx.GetTargetPtr();
3337                                if (target)
3338                                    target->GetDebugger().GetCommandInterpreter().ChildrenTruncated();
3339                                s.Indent("...\n");
3340                            }
3341                            s.IndentLess();
3342                            s.Indent("}\n");
3343                        }
3344                    }
3345                    else if (has_children)
3346                    {
3347                        // Aggregate, no children...
3348                        if (print_valobj)
3349                            s.PutCString(" {}\n");
3350                    }
3351                    else
3352                    {
3353                        if (print_valobj)
3354                            s.EOL();
3355                    }
3356
3357                }
3358                else
3359                {
3360                    s.EOL();
3361                }
3362            }
3363            else
3364            {
3365                if (has_children && print_valobj)
3366                {
3367                    s.PutCString("{...}\n");
3368                }
3369            }
3370        }
3371    }
3372}
3373
3374
3375ValueObjectSP
3376ValueObject::CreateConstantValue (const ConstString &name)
3377{
3378    ValueObjectSP valobj_sp;
3379
3380    if (UpdateValueIfNeeded(false) && m_error.Success())
3381    {
3382        ExecutionContext exe_ctx (GetExecutionContextRef());
3383        clang::ASTContext *ast = GetClangAST ();
3384
3385        DataExtractor data;
3386        data.SetByteOrder (m_data.GetByteOrder());
3387        data.SetAddressByteSize(m_data.GetAddressByteSize());
3388
3389        m_error = m_value.GetValueAsData (&exe_ctx, ast, data, 0, GetModule().get());
3390
3391        valobj_sp = ValueObjectConstResult::Create (exe_ctx.GetBestExecutionContextScope(),
3392                                                    ast,
3393                                                    GetClangType(),
3394                                                    name,
3395                                                    data,
3396                                                    GetAddressOf());
3397    }
3398
3399    if (!valobj_sp)
3400    {
3401        valobj_sp = ValueObjectConstResult::Create (NULL, m_error);
3402    }
3403    return valobj_sp;
3404}
3405
3406ValueObjectSP
3407ValueObject::Dereference (Error &error)
3408{
3409    if (m_deref_valobj)
3410        return m_deref_valobj->GetSP();
3411
3412    const bool is_pointer_type = IsPointerType();
3413    if (is_pointer_type)
3414    {
3415        bool omit_empty_base_classes = true;
3416        bool ignore_array_bounds = false;
3417
3418        std::string child_name_str;
3419        uint32_t child_byte_size = 0;
3420        int32_t child_byte_offset = 0;
3421        uint32_t child_bitfield_bit_size = 0;
3422        uint32_t child_bitfield_bit_offset = 0;
3423        bool child_is_base_class = false;
3424        bool child_is_deref_of_parent = false;
3425        const bool transparent_pointers = false;
3426        clang::ASTContext *clang_ast = GetClangAST();
3427        clang_type_t clang_type = GetClangType();
3428        clang_type_t child_clang_type;
3429
3430        ExecutionContext exe_ctx (GetExecutionContextRef());
3431
3432        child_clang_type = ClangASTContext::GetChildClangTypeAtIndex (&exe_ctx,
3433                                                                      clang_ast,
3434                                                                      GetName().GetCString(),
3435                                                                      clang_type,
3436                                                                      0,
3437                                                                      transparent_pointers,
3438                                                                      omit_empty_base_classes,
3439                                                                      ignore_array_bounds,
3440                                                                      child_name_str,
3441                                                                      child_byte_size,
3442                                                                      child_byte_offset,
3443                                                                      child_bitfield_bit_size,
3444                                                                      child_bitfield_bit_offset,
3445                                                                      child_is_base_class,
3446                                                                      child_is_deref_of_parent);
3447        if (child_clang_type && child_byte_size)
3448        {
3449            ConstString child_name;
3450            if (!child_name_str.empty())
3451                child_name.SetCString (child_name_str.c_str());
3452
3453            m_deref_valobj = new ValueObjectChild (*this,
3454                                                   clang_ast,
3455                                                   child_clang_type,
3456                                                   child_name,
3457                                                   child_byte_size,
3458                                                   child_byte_offset,
3459                                                   child_bitfield_bit_size,
3460                                                   child_bitfield_bit_offset,
3461                                                   child_is_base_class,
3462                                                   child_is_deref_of_parent,
3463                                                   eAddressTypeInvalid);
3464        }
3465    }
3466
3467    if (m_deref_valobj)
3468    {
3469        error.Clear();
3470        return m_deref_valobj->GetSP();
3471    }
3472    else
3473    {
3474        StreamString strm;
3475        GetExpressionPath(strm, true);
3476
3477        if (is_pointer_type)
3478            error.SetErrorStringWithFormat("dereference failed: (%s) %s", GetTypeName().AsCString("<invalid type>"), strm.GetString().c_str());
3479        else
3480            error.SetErrorStringWithFormat("not a pointer type: (%s) %s", GetTypeName().AsCString("<invalid type>"), strm.GetString().c_str());
3481        return ValueObjectSP();
3482    }
3483}
3484
3485ValueObjectSP
3486ValueObject::AddressOf (Error &error)
3487{
3488    if (m_addr_of_valobj_sp)
3489        return m_addr_of_valobj_sp;
3490
3491    AddressType address_type = eAddressTypeInvalid;
3492    const bool scalar_is_load_address = false;
3493    addr_t addr = GetAddressOf (scalar_is_load_address, &address_type);
3494    error.Clear();
3495    if (addr != LLDB_INVALID_ADDRESS)
3496    {
3497        switch (address_type)
3498        {
3499        default:
3500        case eAddressTypeInvalid:
3501            {
3502                StreamString expr_path_strm;
3503                GetExpressionPath(expr_path_strm, true);
3504                error.SetErrorStringWithFormat("'%s' is not in memory", expr_path_strm.GetString().c_str());
3505            }
3506            break;
3507
3508        case eAddressTypeFile:
3509        case eAddressTypeLoad:
3510        case eAddressTypeHost:
3511            {
3512                clang::ASTContext *ast = GetClangAST();
3513                clang_type_t clang_type = GetClangType();
3514                if (ast && clang_type)
3515                {
3516                    std::string name (1, '&');
3517                    name.append (m_name.AsCString(""));
3518                    ExecutionContext exe_ctx (GetExecutionContextRef());
3519                    m_addr_of_valobj_sp = ValueObjectConstResult::Create (exe_ctx.GetBestExecutionContextScope(),
3520                                                                          ast,
3521                                                                          ClangASTContext::CreatePointerType (ast, clang_type),
3522                                                                          ConstString (name.c_str()),
3523                                                                          addr,
3524                                                                          eAddressTypeInvalid,
3525                                                                          m_data.GetAddressByteSize());
3526                }
3527            }
3528            break;
3529        }
3530    }
3531    return m_addr_of_valobj_sp;
3532}
3533
3534ValueObjectSP
3535ValueObject::Cast (const ClangASTType &clang_ast_type)
3536{
3537    return ValueObjectCast::Create (*this, GetName(), clang_ast_type);
3538}
3539
3540ValueObjectSP
3541ValueObject::CastPointerType (const char *name, ClangASTType &clang_ast_type)
3542{
3543    ValueObjectSP valobj_sp;
3544    AddressType address_type;
3545    addr_t ptr_value = GetPointerValue (&address_type);
3546
3547    if (ptr_value != LLDB_INVALID_ADDRESS)
3548    {
3549        Address ptr_addr (ptr_value);
3550        ExecutionContext exe_ctx (GetExecutionContextRef());
3551        valobj_sp = ValueObjectMemory::Create (exe_ctx.GetBestExecutionContextScope(),
3552                                               name,
3553                                               ptr_addr,
3554                                               clang_ast_type);
3555    }
3556    return valobj_sp;
3557}
3558
3559ValueObjectSP
3560ValueObject::CastPointerType (const char *name, TypeSP &type_sp)
3561{
3562    ValueObjectSP valobj_sp;
3563    AddressType address_type;
3564    addr_t ptr_value = GetPointerValue (&address_type);
3565
3566    if (ptr_value != LLDB_INVALID_ADDRESS)
3567    {
3568        Address ptr_addr (ptr_value);
3569        ExecutionContext exe_ctx (GetExecutionContextRef());
3570        valobj_sp = ValueObjectMemory::Create (exe_ctx.GetBestExecutionContextScope(),
3571                                               name,
3572                                               ptr_addr,
3573                                               type_sp);
3574    }
3575    return valobj_sp;
3576}
3577
3578ValueObject::EvaluationPoint::EvaluationPoint () :
3579    m_mod_id(),
3580    m_exe_ctx_ref(),
3581    m_needs_update (true),
3582    m_first_update (true)
3583{
3584}
3585
3586ValueObject::EvaluationPoint::EvaluationPoint (ExecutionContextScope *exe_scope, bool use_selected):
3587    m_mod_id(),
3588    m_exe_ctx_ref(),
3589    m_needs_update (true),
3590    m_first_update (true)
3591{
3592    ExecutionContext exe_ctx(exe_scope);
3593    TargetSP target_sp (exe_ctx.GetTargetSP());
3594    if (target_sp)
3595    {
3596        m_exe_ctx_ref.SetTargetSP (target_sp);
3597        ProcessSP process_sp (exe_ctx.GetProcessSP());
3598        if (!process_sp)
3599            process_sp = target_sp->GetProcessSP();
3600
3601        if (process_sp)
3602        {
3603            m_mod_id = process_sp->GetModID();
3604            m_exe_ctx_ref.SetProcessSP (process_sp);
3605
3606            ThreadSP thread_sp (exe_ctx.GetThreadSP());
3607
3608            if (!thread_sp)
3609            {
3610                if (use_selected)
3611                    thread_sp = process_sp->GetThreadList().GetSelectedThread();
3612            }
3613
3614            if (thread_sp)
3615            {
3616                m_exe_ctx_ref.SetThreadSP(thread_sp);
3617
3618                StackFrameSP frame_sp (exe_ctx.GetFrameSP());
3619                if (!frame_sp)
3620                {
3621                    if (use_selected)
3622                        frame_sp = thread_sp->GetSelectedFrame();
3623                }
3624                if (frame_sp)
3625                    m_exe_ctx_ref.SetFrameSP(frame_sp);
3626            }
3627        }
3628    }
3629}
3630
3631ValueObject::EvaluationPoint::EvaluationPoint (const ValueObject::EvaluationPoint &rhs) :
3632    m_mod_id(),
3633    m_exe_ctx_ref(rhs.m_exe_ctx_ref),
3634    m_needs_update (true),
3635    m_first_update (true)
3636{
3637}
3638
3639ValueObject::EvaluationPoint::~EvaluationPoint ()
3640{
3641}
3642
3643// This function checks the EvaluationPoint against the current process state.  If the current
3644// state matches the evaluation point, or the evaluation point is already invalid, then we return
3645// false, meaning "no change".  If the current state is different, we update our state, and return
3646// true meaning "yes, change".  If we did see a change, we also set m_needs_update to true, so
3647// future calls to NeedsUpdate will return true.
3648// exe_scope will be set to the current execution context scope.
3649
3650bool
3651ValueObject::EvaluationPoint::SyncWithProcessState()
3652{
3653
3654    // Start with the target, if it is NULL, then we're obviously not going to get any further:
3655    ExecutionContext exe_ctx(m_exe_ctx_ref.Lock());
3656
3657    if (exe_ctx.GetTargetPtr() == NULL)
3658        return false;
3659
3660    // If we don't have a process nothing can change.
3661    Process *process = exe_ctx.GetProcessPtr();
3662    if (process == NULL)
3663        return false;
3664
3665    // If our stop id is the current stop ID, nothing has changed:
3666    ProcessModID current_mod_id = process->GetModID();
3667
3668    // If the current stop id is 0, either we haven't run yet, or the process state has been cleared.
3669    // In either case, we aren't going to be able to sync with the process state.
3670    if (current_mod_id.GetStopID() == 0)
3671        return false;
3672
3673    bool changed;
3674
3675    if (m_mod_id.IsValid())
3676    {
3677        if (m_mod_id == current_mod_id)
3678        {
3679            // Everything is already up to date in this object, no need to
3680            // update the execution context scope.
3681            changed = false;
3682        }
3683        else
3684        {
3685            m_mod_id = current_mod_id;
3686            m_needs_update = true;
3687            changed = true;
3688        }
3689    }
3690
3691    // Now re-look up the thread and frame in case the underlying objects have gone away & been recreated.
3692    // That way we'll be sure to return a valid exe_scope.
3693    // If we used to have a thread or a frame but can't find it anymore, then mark ourselves as invalid.
3694
3695    if (m_exe_ctx_ref.HasThreadRef())
3696    {
3697        ThreadSP thread_sp (m_exe_ctx_ref.GetThreadSP());
3698        if (thread_sp)
3699        {
3700            if (m_exe_ctx_ref.HasFrameRef())
3701            {
3702                StackFrameSP frame_sp (m_exe_ctx_ref.GetFrameSP());
3703                if (!frame_sp)
3704                {
3705                    // We used to have a frame, but now it is gone
3706                    SetInvalid();
3707                }
3708            }
3709        }
3710        else
3711        {
3712            // We used to have a thread, but now it is gone
3713            SetInvalid();
3714        }
3715
3716    }
3717    return changed;
3718}
3719
3720void
3721ValueObject::EvaluationPoint::SetUpdated ()
3722{
3723    ProcessSP process_sp(m_exe_ctx_ref.GetProcessSP());
3724    if (process_sp)
3725        m_mod_id = process_sp->GetModID();
3726    m_first_update = false;
3727    m_needs_update = false;
3728}
3729
3730
3731//bool
3732//ValueObject::EvaluationPoint::SetContext (ExecutionContextScope *exe_scope)
3733//{
3734//    if (!IsValid())
3735//        return false;
3736//
3737//    bool needs_update = false;
3738//
3739//    // The target has to be non-null, and the
3740//    Target *target = exe_scope->CalculateTarget();
3741//    if (target != NULL)
3742//    {
3743//        Target *old_target = m_target_sp.get();
3744//        assert (target == old_target);
3745//        Process *process = exe_scope->CalculateProcess();
3746//        if (process != NULL)
3747//        {
3748//            // FOR NOW - assume you can't update variable objects across process boundaries.
3749//            Process *old_process = m_process_sp.get();
3750//            assert (process == old_process);
3751//            ProcessModID current_mod_id = process->GetModID();
3752//            if (m_mod_id != current_mod_id)
3753//            {
3754//                needs_update = true;
3755//                m_mod_id = current_mod_id;
3756//            }
3757//            // See if we're switching the thread or stack context.  If no thread is given, this is
3758//            // being evaluated in a global context.
3759//            Thread *thread = exe_scope->CalculateThread();
3760//            if (thread != NULL)
3761//            {
3762//                user_id_t new_thread_index = thread->GetIndexID();
3763//                if (new_thread_index != m_thread_id)
3764//                {
3765//                    needs_update = true;
3766//                    m_thread_id = new_thread_index;
3767//                    m_stack_id.Clear();
3768//                }
3769//
3770//                StackFrame *new_frame = exe_scope->CalculateStackFrame();
3771//                if (new_frame != NULL)
3772//                {
3773//                    if (new_frame->GetStackID() != m_stack_id)
3774//                    {
3775//                        needs_update = true;
3776//                        m_stack_id = new_frame->GetStackID();
3777//                    }
3778//                }
3779//                else
3780//                {
3781//                    m_stack_id.Clear();
3782//                    needs_update = true;
3783//                }
3784//            }
3785//            else
3786//            {
3787//                // If this had been given a thread, and now there is none, we should update.
3788//                // Otherwise we don't have to do anything.
3789//                if (m_thread_id != LLDB_INVALID_UID)
3790//                {
3791//                    m_thread_id = LLDB_INVALID_UID;
3792//                    m_stack_id.Clear();
3793//                    needs_update = true;
3794//                }
3795//            }
3796//        }
3797//        else
3798//        {
3799//            // If there is no process, then we don't need to update anything.
3800//            // But if we're switching from having a process to not, we should try to update.
3801//            if (m_process_sp.get() != NULL)
3802//            {
3803//                needs_update = true;
3804//                m_process_sp.reset();
3805//                m_thread_id = LLDB_INVALID_UID;
3806//                m_stack_id.Clear();
3807//            }
3808//        }
3809//    }
3810//    else
3811//    {
3812//        // If there's no target, nothing can change so we don't need to update anything.
3813//        // But if we're switching from having a target to not, we should try to update.
3814//        if (m_target_sp.get() != NULL)
3815//        {
3816//            needs_update = true;
3817//            m_target_sp.reset();
3818//            m_process_sp.reset();
3819//            m_thread_id = LLDB_INVALID_UID;
3820//            m_stack_id.Clear();
3821//        }
3822//    }
3823//    if (!m_needs_update)
3824//        m_needs_update = needs_update;
3825//
3826//    return needs_update;
3827//}
3828
3829void
3830ValueObject::ClearUserVisibleData()
3831{
3832    m_location_str.clear();
3833    m_value_str.clear();
3834    m_summary_str.clear();
3835    m_object_desc_str.clear();
3836    m_is_getting_summary = false;
3837}
3838
3839SymbolContextScope *
3840ValueObject::GetSymbolContextScope()
3841{
3842    if (m_parent)
3843    {
3844        if (!m_parent->IsPointerOrReferenceType())
3845            return m_parent->GetSymbolContextScope();
3846    }
3847    return NULL;
3848}
3849