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