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