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