ValueObject.cpp revision 86e7c3ecb82655e77581ec042aa6b31753a42afc
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/Debugger.h"
23#include "lldb/Core/StreamString.h"
24#include "lldb/Core/ValueObjectChild.h"
25#include "lldb/Core/ValueObjectConstResult.h"
26#include "lldb/Core/ValueObjectDynamicValue.h"
27#include "lldb/Core/ValueObjectList.h"
28#include "lldb/Core/ValueObjectMemory.h"
29
30#include "lldb/Host/Endian.h"
31
32#include "lldb/Symbol/ClangASTType.h"
33#include "lldb/Symbol/ClangASTContext.h"
34#include "lldb/Symbol/Type.h"
35
36#include "lldb/Target/ExecutionContext.h"
37#include "lldb/Target/LanguageRuntime.h"
38#include "lldb/Target/Process.h"
39#include "lldb/Target/RegisterContext.h"
40#include "lldb/Target/Target.h"
41#include "lldb/Target/Thread.h"
42
43#include "lldb/Utility/RefCounter.h"
44
45using namespace lldb;
46using namespace lldb_private;
47using namespace lldb_utility;
48
49static lldb::user_id_t g_value_obj_uid = 0;
50
51//----------------------------------------------------------------------
52// ValueObject constructor
53//----------------------------------------------------------------------
54ValueObject::ValueObject (ValueObject &parent) :
55    UserID (++g_value_obj_uid), // Unique identifier for every value object
56    m_parent (&parent),
57    m_update_point (parent.GetUpdatePoint ()),
58    m_name (),
59    m_data (),
60    m_value (),
61    m_error (),
62    m_value_str (),
63    m_old_value_str (),
64    m_location_str (),
65    m_summary_str (),
66    m_object_desc_str (),
67    m_manager(parent.GetManager()),
68    m_children (),
69    m_synthetic_children (),
70    m_dynamic_value (NULL),
71    m_deref_valobj(NULL),
72    m_format (eFormatDefault),
73    m_value_is_valid (false),
74    m_value_did_change (false),
75    m_children_count_valid (false),
76    m_old_value_valid (false),
77    m_pointers_point_to_load_addrs (false),
78    m_is_deref_of_parent (false),
79    m_is_array_item_for_pointer(false),
80    m_is_bitfield_for_scalar(false),
81    m_last_format_mgr_revision(0),
82    m_last_summary_format(),
83    m_last_value_format(),
84    m_forced_summary_format(),
85    m_dump_printable_counter(0)
86{
87    m_manager->ManageObject(this);
88}
89
90//----------------------------------------------------------------------
91// ValueObject constructor
92//----------------------------------------------------------------------
93ValueObject::ValueObject (ExecutionContextScope *exe_scope) :
94    UserID (++g_value_obj_uid), // Unique identifier for every value object
95    m_parent (NULL),
96    m_update_point (exe_scope),
97    m_name (),
98    m_data (),
99    m_value (),
100    m_error (),
101    m_value_str (),
102    m_old_value_str (),
103    m_location_str (),
104    m_summary_str (),
105    m_object_desc_str (),
106    m_manager(),
107    m_children (),
108    m_synthetic_children (),
109    m_dynamic_value (NULL),
110    m_deref_valobj(NULL),
111    m_format (eFormatDefault),
112    m_value_is_valid (false),
113    m_value_did_change (false),
114    m_children_count_valid (false),
115    m_old_value_valid (false),
116    m_pointers_point_to_load_addrs (false),
117    m_is_deref_of_parent (false),
118    m_is_array_item_for_pointer(false),
119    m_is_bitfield_for_scalar(false),
120    m_last_format_mgr_revision(0),
121    m_last_summary_format(),
122    m_last_value_format(),
123    m_forced_summary_format(),
124    m_dump_printable_counter(0)
125{
126    m_manager = new ValueObjectManager();
127    m_manager->ManageObject (this);
128}
129
130//----------------------------------------------------------------------
131// Destructor
132//----------------------------------------------------------------------
133ValueObject::~ValueObject ()
134{
135}
136
137bool
138ValueObject::UpdateValueIfNeeded (bool update_format)
139{
140
141    if (update_format)
142        UpdateFormatsIfNeeded();
143
144    // If this is a constant value, then our success is predicated on whether
145    // we have an error or not
146    if (GetIsConstant())
147        return m_error.Success();
148
149    bool first_update = m_update_point.IsFirstEvaluation();
150
151    if (m_update_point.NeedsUpdating())
152    {
153        m_update_point.SetUpdated();
154
155        // Save the old value using swap to avoid a string copy which
156        // also will clear our m_value_str
157        if (m_value_str.empty())
158        {
159            m_old_value_valid = false;
160        }
161        else
162        {
163            m_old_value_valid = true;
164            m_old_value_str.swap (m_value_str);
165            m_value_str.clear();
166        }
167        m_location_str.clear();
168        m_summary_str.clear();
169        m_object_desc_str.clear();
170
171        const bool value_was_valid = GetValueIsValid();
172        SetValueDidChange (false);
173
174        m_error.Clear();
175
176        // Call the pure virtual function to update the value
177        bool success = UpdateValue ();
178
179        SetValueIsValid (success);
180
181        if (first_update)
182            SetValueDidChange (false);
183        else if (!m_value_did_change && success == false)
184        {
185            // The value wasn't gotten successfully, so we mark this
186            // as changed if the value used to be valid and now isn't
187            SetValueDidChange (value_was_valid);
188        }
189    }
190    return m_error.Success();
191}
192
193void
194ValueObject::UpdateFormatsIfNeeded()
195{
196    /*printf("CHECKING FOR UPDATES. I am at revision %d, while the format manager is at revision %d\n",
197           m_last_format_mgr_revision,
198           Debugger::ValueFormats::GetCurrentRevision());*/
199    if (HasCustomSummaryFormat() && m_update_point.GetUpdateID() != m_user_id_of_forced_summary)
200    {
201        ClearCustomSummaryFormat();
202        m_summary_str.clear();
203    }
204    if (m_last_format_mgr_revision != Debugger::ValueFormats::GetCurrentRevision())
205    {
206        if (m_last_summary_format.get())
207            m_last_summary_format.reset((SummaryFormat*)NULL);
208        if (m_last_value_format.get())
209            m_last_value_format.reset((ValueFormat*)NULL);
210        Debugger::ValueFormats::Get(*this, m_last_value_format);
211        if (!Debugger::SummaryFormats::Get(*this, m_last_summary_format))
212            Debugger::RegexSummaryFormats::Get(*this, m_last_summary_format);
213        m_last_format_mgr_revision = Debugger::ValueFormats::GetCurrentRevision();
214        m_value_str.clear();
215        m_summary_str.clear();
216    }
217}
218
219DataExtractor &
220ValueObject::GetDataExtractor ()
221{
222    UpdateValueIfNeeded();
223    return m_data;
224}
225
226const Error &
227ValueObject::GetError()
228{
229    UpdateValueIfNeeded();
230    return m_error;
231}
232
233const ConstString &
234ValueObject::GetName() const
235{
236    return m_name;
237}
238
239const char *
240ValueObject::GetLocationAsCString ()
241{
242    if (UpdateValueIfNeeded())
243    {
244        if (m_location_str.empty())
245        {
246            StreamString sstr;
247
248            switch (m_value.GetValueType())
249            {
250            default:
251                break;
252
253            case Value::eValueTypeScalar:
254                if (m_value.GetContextType() == Value::eContextTypeRegisterInfo)
255                {
256                    RegisterInfo *reg_info = m_value.GetRegisterInfo();
257                    if (reg_info)
258                    {
259                        if (reg_info->name)
260                            m_location_str = reg_info->name;
261                        else if (reg_info->alt_name)
262                            m_location_str = reg_info->alt_name;
263                        break;
264                    }
265                }
266                m_location_str = "scalar";
267                break;
268
269            case Value::eValueTypeLoadAddress:
270            case Value::eValueTypeFileAddress:
271            case Value::eValueTypeHostAddress:
272                {
273                    uint32_t addr_nibble_size = m_data.GetAddressByteSize() * 2;
274                    sstr.Printf("0x%*.*llx", addr_nibble_size, addr_nibble_size, m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS));
275                    m_location_str.swap(sstr.GetString());
276                }
277                break;
278            }
279        }
280    }
281    return m_location_str.c_str();
282}
283
284Value &
285ValueObject::GetValue()
286{
287    return m_value;
288}
289
290const Value &
291ValueObject::GetValue() const
292{
293    return m_value;
294}
295
296bool
297ValueObject::ResolveValue (Scalar &scalar)
298{
299    ExecutionContext exe_ctx;
300    ExecutionContextScope *exe_scope = GetExecutionContextScope();
301    if (exe_scope)
302        exe_scope->CalculateExecutionContext(exe_ctx);
303    scalar = m_value.ResolveValue(&exe_ctx, GetClangAST ());
304    return scalar.IsValid();
305}
306
307bool
308ValueObject::GetValueIsValid () const
309{
310    return m_value_is_valid;
311}
312
313
314void
315ValueObject::SetValueIsValid (bool b)
316{
317    m_value_is_valid = b;
318}
319
320bool
321ValueObject::GetValueDidChange ()
322{
323    GetValueAsCString ();
324    return m_value_did_change;
325}
326
327void
328ValueObject::SetValueDidChange (bool value_changed)
329{
330    m_value_did_change = value_changed;
331}
332
333ValueObjectSP
334ValueObject::GetChildAtIndex (uint32_t idx, bool can_create)
335{
336    ValueObjectSP child_sp;
337    // We may need to update our value if we are dynamic
338    if (IsPossibleDynamicType ())
339        UpdateValueIfNeeded();
340    if (idx < GetNumChildren())
341    {
342        // Check if we have already made the child value object?
343        if (can_create && m_children[idx] == NULL)
344        {
345            // No we haven't created the child at this index, so lets have our
346            // subclass do it and cache the result for quick future access.
347            m_children[idx] = CreateChildAtIndex (idx, false, 0);
348        }
349
350        if (m_children[idx] != NULL)
351            return m_children[idx]->GetSP();
352    }
353    return child_sp;
354}
355
356uint32_t
357ValueObject::GetIndexOfChildWithName (const ConstString &name)
358{
359    bool omit_empty_base_classes = true;
360    return ClangASTContext::GetIndexOfChildWithName (GetClangAST(),
361                                                     GetClangType(),
362                                                     name.GetCString(),
363                                                     omit_empty_base_classes);
364}
365
366ValueObjectSP
367ValueObject::GetChildMemberWithName (const ConstString &name, bool can_create)
368{
369    // when getting a child by name, it could be buried inside some base
370    // classes (which really aren't part of the expression path), so we
371    // need a vector of indexes that can get us down to the correct child
372    ValueObjectSP child_sp;
373
374    // We may need to update our value if we are dynamic
375    if (IsPossibleDynamicType ())
376        UpdateValueIfNeeded();
377
378    std::vector<uint32_t> child_indexes;
379    clang::ASTContext *clang_ast = GetClangAST();
380    void *clang_type = GetClangType();
381    bool omit_empty_base_classes = true;
382    const size_t num_child_indexes =  ClangASTContext::GetIndexOfChildMemberWithName (clang_ast,
383                                                                                      clang_type,
384                                                                                      name.GetCString(),
385                                                                                      omit_empty_base_classes,
386                                                                                      child_indexes);
387    if (num_child_indexes > 0)
388    {
389        std::vector<uint32_t>::const_iterator pos = child_indexes.begin ();
390        std::vector<uint32_t>::const_iterator end = child_indexes.end ();
391
392        child_sp = GetChildAtIndex(*pos, can_create);
393        for (++pos; pos != end; ++pos)
394        {
395            if (child_sp)
396            {
397                ValueObjectSP new_child_sp(child_sp->GetChildAtIndex (*pos, can_create));
398                child_sp = new_child_sp;
399            }
400            else
401            {
402                child_sp.reset();
403            }
404
405        }
406    }
407    return child_sp;
408}
409
410
411uint32_t
412ValueObject::GetNumChildren ()
413{
414    if (!m_children_count_valid)
415    {
416        SetNumChildren (CalculateNumChildren());
417    }
418    return m_children.size();
419}
420void
421ValueObject::SetNumChildren (uint32_t num_children)
422{
423    m_children_count_valid = true;
424    m_children.resize(num_children);
425}
426
427void
428ValueObject::SetName (const char *name)
429{
430    m_name.SetCString(name);
431}
432
433void
434ValueObject::SetName (const ConstString &name)
435{
436    m_name = name;
437}
438
439ValueObject *
440ValueObject::CreateChildAtIndex (uint32_t idx, bool synthetic_array_member, int32_t synthetic_index)
441{
442    ValueObject *valobj = NULL;
443
444    bool omit_empty_base_classes = true;
445    bool ignore_array_bounds = synthetic_array_member;
446    std::string child_name_str;
447    uint32_t child_byte_size = 0;
448    int32_t child_byte_offset = 0;
449    uint32_t child_bitfield_bit_size = 0;
450    uint32_t child_bitfield_bit_offset = 0;
451    bool child_is_base_class = false;
452    bool child_is_deref_of_parent = false;
453
454    const bool transparent_pointers = synthetic_array_member == false;
455    clang::ASTContext *clang_ast = GetClangAST();
456    clang_type_t clang_type = GetClangType();
457    clang_type_t child_clang_type;
458
459    ExecutionContext exe_ctx;
460    GetExecutionContextScope()->CalculateExecutionContext (exe_ctx);
461
462    child_clang_type = ClangASTContext::GetChildClangTypeAtIndex (&exe_ctx,
463                                                                  clang_ast,
464                                                                  GetName().GetCString(),
465                                                                  clang_type,
466                                                                  idx,
467                                                                  transparent_pointers,
468                                                                  omit_empty_base_classes,
469                                                                  ignore_array_bounds,
470                                                                  child_name_str,
471                                                                  child_byte_size,
472                                                                  child_byte_offset,
473                                                                  child_bitfield_bit_size,
474                                                                  child_bitfield_bit_offset,
475                                                                  child_is_base_class,
476                                                                  child_is_deref_of_parent);
477    if (child_clang_type && child_byte_size)
478    {
479        if (synthetic_index)
480            child_byte_offset += child_byte_size * synthetic_index;
481
482        ConstString child_name;
483        if (!child_name_str.empty())
484            child_name.SetCString (child_name_str.c_str());
485
486        valobj = new ValueObjectChild (*this,
487                                       clang_ast,
488                                       child_clang_type,
489                                       child_name,
490                                       child_byte_size,
491                                       child_byte_offset,
492                                       child_bitfield_bit_size,
493                                       child_bitfield_bit_offset,
494                                       child_is_base_class,
495                                       child_is_deref_of_parent);
496        if (m_pointers_point_to_load_addrs)
497            valobj->SetPointersPointToLoadAddrs (m_pointers_point_to_load_addrs);
498    }
499
500    return valobj;
501}
502
503const char *
504ValueObject::GetSummaryAsCString ()
505{
506    if (UpdateValueIfNeeded ())
507    {
508        if (m_summary_str.empty())
509        {
510            SummaryFormat* summary_format = GetSummaryFormat().get();
511
512            if (summary_format)
513            {
514                StreamString s;
515                ExecutionContext exe_ctx;
516                this->GetExecutionContextScope()->CalculateExecutionContext(exe_ctx);
517                SymbolContext sc;
518                if (exe_ctx.frame)
519                    sc = exe_ctx.frame->GetSymbolContext(eSymbolContextEverything);
520
521                if (summary_format->m_show_members_oneliner)
522                {
523                    const uint32_t num_children = GetNumChildren();
524                    if (num_children)
525                    {
526
527                        s.PutChar('(');
528
529                        for (uint32_t idx=0; idx<num_children; ++idx)
530                        {
531                            ValueObjectSP child_sp(GetChildAtIndex(idx, true));
532                            if (child_sp.get())
533                            {
534                                if (idx)
535                                    s.PutCString(", ");
536                                s.PutCString(child_sp.get()->GetName().AsCString());
537                                s.PutChar('=');
538                                s.PutCString(child_sp.get()->GetPrintableRepresentation());
539                            }
540                        }
541
542                        s.PutChar(')');
543
544                        m_summary_str.swap(s.GetString());
545                        return m_summary_str.c_str();
546                    }
547                    else
548                        return "()";
549
550                }
551                else
552                {
553                    if (Debugger::FormatPrompt(summary_format->m_format.c_str(), &sc, &exe_ctx, &sc.line_entry.range.GetBaseAddress(), s, NULL, this))
554                    {
555                        m_summary_str.swap(s.GetString());
556                        return m_summary_str.c_str();
557                    }
558                    else
559                        return NULL;
560                }
561            }
562
563            clang_type_t clang_type = GetClangType();
564
565            // See if this is a pointer to a C string?
566            if (clang_type)
567            {
568                StreamString sstr;
569                clang_type_t elem_or_pointee_clang_type;
570                const Flags type_flags (ClangASTContext::GetTypeInfo (clang_type,
571                                                                      GetClangAST(),
572                                                                      &elem_or_pointee_clang_type));
573
574                ExecutionContextScope *exe_scope = GetExecutionContextScope();
575                if (exe_scope)
576                {
577                    if (type_flags.AnySet (ClangASTContext::eTypeIsArray | ClangASTContext::eTypeIsPointer) &&
578                        ClangASTContext::IsCharType (elem_or_pointee_clang_type))
579                    {
580                        Target *target = exe_scope->CalculateTarget();
581                        if (target != NULL)
582                        {
583                            lldb::addr_t cstr_address = LLDB_INVALID_ADDRESS;
584                            AddressType cstr_address_type = eAddressTypeInvalid;
585
586                            size_t cstr_len = 0;
587                            bool capped_data = false;
588                            if (type_flags.Test (ClangASTContext::eTypeIsArray))
589                            {
590                                // We have an array
591                                cstr_len = ClangASTContext::GetArraySize (clang_type);
592                                if (cstr_len > 512) // TODO: make cap a setting
593                                {
594                                    cstr_len = ClangASTContext::GetArraySize (clang_type);
595                                    if (cstr_len > 512) // TODO: make cap a setting
596                                    {
597                                        capped_data = true;
598                                        cstr_len = 512;
599                                    }
600                                }
601                                cstr_address = GetAddressOf (cstr_address_type, true);
602                            }
603                            else
604                            {
605                                // We have a pointer
606                                cstr_address = GetPointerValue (cstr_address_type, true);
607                            }
608                            if (cstr_address != LLDB_INVALID_ADDRESS)
609                            {
610                                Address cstr_so_addr (NULL, cstr_address);
611                                DataExtractor data;
612                                size_t bytes_read = 0;
613                                std::vector<char> data_buffer;
614                                Error error;
615                                bool prefer_file_cache = false;
616                                if (cstr_len > 0)
617                                {
618                                    data_buffer.resize(cstr_len);
619                                    data.SetData (&data_buffer.front(), data_buffer.size(), lldb::endian::InlHostByteOrder());
620                                    bytes_read = target->ReadMemory (cstr_so_addr,
621                                                                     prefer_file_cache,
622                                                                     &data_buffer.front(),
623                                                                     cstr_len,
624                                                                     error);
625                                    if (bytes_read > 0)
626                                    {
627                                        sstr << '"';
628                                        data.Dump (&sstr,
629                                                   0,                 // Start offset in "data"
630                                                   eFormatCharArray,  // Print as characters
631                                                   1,                 // Size of item (1 byte for a char!)
632                                                   bytes_read,        // How many bytes to print?
633                                                   UINT32_MAX,        // num per line
634                                                   LLDB_INVALID_ADDRESS,// base address
635                                                   0,                 // bitfield bit size
636                                                   0);                // bitfield bit offset
637                                        if (capped_data)
638                                            sstr << "...";
639                                        sstr << '"';
640                                    }
641                                }
642                                else
643                                {
644                                    const size_t k_max_buf_size = 256;
645                                    data_buffer.resize (k_max_buf_size + 1);
646                                    // NULL terminate in case we don't get the entire C string
647                                    data_buffer.back() = '\0';
648
649                                    sstr << '"';
650
651                                    data.SetData (&data_buffer.front(), data_buffer.size(), endian::InlHostByteOrder());
652                                    while ((bytes_read = target->ReadMemory (cstr_so_addr,
653                                                                             prefer_file_cache,
654                                                                             &data_buffer.front(),
655                                                                             k_max_buf_size,
656                                                                             error)) > 0)
657                                    {
658                                        size_t len = strlen(&data_buffer.front());
659                                        if (len == 0)
660                                            break;
661                                        if (len > bytes_read)
662                                            len = bytes_read;
663
664                                        data.Dump (&sstr,
665                                                   0,                 // Start offset in "data"
666                                                   eFormatCharArray,  // Print as characters
667                                                   1,                 // Size of item (1 byte for a char!)
668                                                   len,               // How many bytes to print?
669                                                   UINT32_MAX,        // num per line
670                                                   LLDB_INVALID_ADDRESS,// base address
671                                                   0,                 // bitfield bit size
672                                                   0);                // bitfield bit offset
673
674                                        if (len < k_max_buf_size)
675                                            break;
676                                        cstr_so_addr.Slide (k_max_buf_size);
677                                    }
678                                    sstr << '"';
679                                }
680                            }
681                        }
682
683                        if (sstr.GetSize() > 0)
684                            m_summary_str.assign (sstr.GetData(), sstr.GetSize());
685                    }
686                    else if (ClangASTContext::IsFunctionPointerType (clang_type))
687                    {
688                        AddressType func_ptr_address_type = eAddressTypeInvalid;
689                        lldb::addr_t func_ptr_address = GetPointerValue (func_ptr_address_type, true);
690
691                        if (func_ptr_address != 0 && func_ptr_address != LLDB_INVALID_ADDRESS)
692                        {
693                            switch (func_ptr_address_type)
694                            {
695                            case eAddressTypeInvalid:
696                            case eAddressTypeFile:
697                                break;
698
699                            case eAddressTypeLoad:
700                                {
701                                    Address so_addr;
702                                    Target *target = exe_scope->CalculateTarget();
703                                    if (target && target->GetSectionLoadList().IsEmpty() == false)
704                                    {
705                                        if (target->GetSectionLoadList().ResolveLoadAddress(func_ptr_address, so_addr))
706                                        {
707                                            so_addr.Dump (&sstr,
708                                                          exe_scope,
709                                                          Address::DumpStyleResolvedDescription,
710                                                          Address::DumpStyleSectionNameOffset);
711                                        }
712                                    }
713                                }
714                                break;
715
716                            case eAddressTypeHost:
717                                break;
718                            }
719                        }
720                        if (sstr.GetSize() > 0)
721                        {
722                            m_summary_str.assign (1, '(');
723                            m_summary_str.append (sstr.GetData(), sstr.GetSize());
724                            m_summary_str.append (1, ')');
725                        }
726                    }
727                }
728            }
729        }
730    }
731    if (m_summary_str.empty())
732        return NULL;
733    return m_summary_str.c_str();
734}
735
736bool
737ValueObject::IsCStringContainer(bool check_pointer)
738{
739    clang_type_t elem_or_pointee_clang_type;
740    const Flags type_flags (ClangASTContext::GetTypeInfo (GetClangType(),
741                                                          GetClangAST(),
742                                                          &elem_or_pointee_clang_type));
743    bool is_char_arr_ptr (type_flags.AnySet (ClangASTContext::eTypeIsArray | ClangASTContext::eTypeIsPointer) &&
744            ClangASTContext::IsCharType (elem_or_pointee_clang_type));
745    if (!is_char_arr_ptr)
746        return false;
747    if (!check_pointer)
748        return true;
749    if (type_flags.Test(ClangASTContext::eTypeIsArray))
750        return true;
751    lldb::addr_t cstr_address = LLDB_INVALID_ADDRESS;
752    AddressType cstr_address_type = eAddressTypeInvalid;
753    cstr_address = GetAddressOf (cstr_address_type, true);
754    return (cstr_address != LLDB_INVALID_ADDRESS);
755}
756
757void
758ValueObject::ReadPointedString(Stream& s,
759                               Error& error,
760                               uint32_t max_length,
761                               bool honor_array,
762                               lldb::Format item_format)
763{
764
765    if (max_length == 0)
766        max_length = 128;   // FIXME this should be a setting, or a formatting parameter
767
768    clang_type_t clang_type = GetClangType();
769    clang_type_t elem_or_pointee_clang_type;
770    const Flags type_flags (ClangASTContext::GetTypeInfo (clang_type,
771                                                          GetClangAST(),
772                                                          &elem_or_pointee_clang_type));
773    if (type_flags.AnySet (ClangASTContext::eTypeIsArray | ClangASTContext::eTypeIsPointer) &&
774        ClangASTContext::IsCharType (elem_or_pointee_clang_type))
775    {
776        ExecutionContextScope *exe_scope = GetExecutionContextScope();
777            if (exe_scope)
778            {
779                Target *target = exe_scope->CalculateTarget();
780                if (target != NULL)
781                {
782                    lldb::addr_t cstr_address = LLDB_INVALID_ADDRESS;
783                    AddressType cstr_address_type = eAddressTypeInvalid;
784
785                    size_t cstr_len = 0;
786                    bool capped_data = false;
787                    if (type_flags.Test (ClangASTContext::eTypeIsArray))
788                    {
789                        // We have an array
790                        cstr_len = ClangASTContext::GetArraySize (clang_type);
791                        if (cstr_len > max_length)
792                        {
793                            capped_data = true;
794                            cstr_len = max_length;
795                        }
796                        cstr_address = GetAddressOf (cstr_address_type, true);
797                    }
798                    else
799                    {
800                        // We have a pointer
801                        cstr_address = GetPointerValue (cstr_address_type, true);
802                    }
803                    if (cstr_address != LLDB_INVALID_ADDRESS)
804                    {
805                        Address cstr_so_addr (NULL, cstr_address);
806                        DataExtractor data;
807                        size_t bytes_read = 0;
808                        std::vector<char> data_buffer;
809                        bool prefer_file_cache = false;
810                        if (cstr_len > 0 && honor_array)
811                        {
812                            data_buffer.resize(cstr_len);
813                            data.SetData (&data_buffer.front(), data_buffer.size(), lldb::endian::InlHostByteOrder());
814                            bytes_read = target->ReadMemory (cstr_so_addr,
815                                                             prefer_file_cache,
816                                                             &data_buffer.front(),
817                                                             cstr_len,
818                                                             error);
819                            if (bytes_read > 0)
820                            {
821                                s << '"';
822                                data.Dump (&s,
823                                           0,                 // Start offset in "data"
824                                           item_format,
825                                           1,                 // Size of item (1 byte for a char!)
826                                           bytes_read,        // How many bytes to print?
827                                           UINT32_MAX,        // num per line
828                                           LLDB_INVALID_ADDRESS,// base address
829                                           0,                 // bitfield bit size
830                                           0);                // bitfield bit offset
831                                if (capped_data)
832                                    s << "...";
833                                s << '"';
834                            }
835                        }
836                        else
837                        {
838                            cstr_len = max_length;
839                            const size_t k_max_buf_size = 64;
840                            data_buffer.resize (k_max_buf_size + 1);
841                            // NULL terminate in case we don't get the entire C string
842                            data_buffer.back() = '\0';
843
844                            s << '"';
845
846                            data.SetData (&data_buffer.front(), data_buffer.size(), endian::InlHostByteOrder());
847                            while ((bytes_read = target->ReadMemory (cstr_so_addr,
848                                                                     prefer_file_cache,
849                                                                     &data_buffer.front(),
850                                                                     k_max_buf_size,
851                                                                     error)) > 0)
852                            {
853                                size_t len = strlen(&data_buffer.front());
854                                if (len == 0)
855                                    break;
856                                if (len > bytes_read)
857                                    len = bytes_read;
858                                if (len > cstr_len)
859                                    len = cstr_len;
860
861                                data.Dump (&s,
862                                           0,                 // Start offset in "data"
863                                           item_format,
864                                           1,                 // Size of item (1 byte for a char!)
865                                           len,               // How many bytes to print?
866                                           UINT32_MAX,        // num per line
867                                           LLDB_INVALID_ADDRESS,// base address
868                                           0,                 // bitfield bit size
869                                           0);                // bitfield bit offset
870
871                                if (len < k_max_buf_size)
872                                    break;
873                                if (len >= cstr_len)
874                                {
875                                    s << "...";
876                                    break;
877                                }
878                                cstr_len -= len;
879                                cstr_so_addr.Slide (k_max_buf_size);
880                            }
881                            s << '"';
882                        }
883                    }
884                }
885            }
886    }
887    else
888    {
889        error.SetErrorString("impossible to read a string from this object");
890    }
891}
892
893const char *
894ValueObject::GetObjectDescription ()
895{
896
897    if (!UpdateValueIfNeeded ())
898        return NULL;
899
900    if (!m_object_desc_str.empty())
901        return m_object_desc_str.c_str();
902
903    ExecutionContextScope *exe_scope = GetExecutionContextScope();
904    if (exe_scope == NULL)
905        return NULL;
906
907    Process *process = exe_scope->CalculateProcess();
908    if (process == NULL)
909        return NULL;
910
911    StreamString s;
912
913    lldb::LanguageType language = GetObjectRuntimeLanguage();
914    LanguageRuntime *runtime = process->GetLanguageRuntime(language);
915
916    if (runtime == NULL)
917    {
918        // Aw, hell, if the things a pointer, or even just an integer, let's try ObjC anyway...
919        clang_type_t opaque_qual_type = GetClangType();
920        if (opaque_qual_type != NULL)
921        {
922            bool is_signed;
923            if (ClangASTContext::IsIntegerType (opaque_qual_type, is_signed)
924                || ClangASTContext::IsPointerType (opaque_qual_type))
925            {
926                runtime = process->GetLanguageRuntime(lldb::eLanguageTypeObjC);
927            }
928        }
929    }
930
931    if (runtime && runtime->GetObjectDescription(s, *this))
932    {
933        m_object_desc_str.append (s.GetData());
934    }
935
936    if (m_object_desc_str.empty())
937        return NULL;
938    else
939        return m_object_desc_str.c_str();
940}
941
942const char *
943ValueObject::GetValueAsCString ()
944{
945    // If our byte size is zero this is an aggregate type that has children
946    if (ClangASTContext::IsAggregateType (GetClangType()) == false)
947    {
948        if (UpdateValueIfNeeded())
949        {
950            if (m_value_str.empty())
951            {
952                const Value::ContextType context_type = m_value.GetContextType();
953
954                switch (context_type)
955                {
956                case Value::eContextTypeClangType:
957                case Value::eContextTypeLLDBType:
958                case Value::eContextTypeVariable:
959                    {
960                        clang_type_t clang_type = GetClangType ();
961                        if (clang_type)
962                        {
963                            StreamString sstr;
964                            Format format = GetFormat();
965                            if (format == eFormatDefault)
966                            {
967                                if (m_last_value_format)
968                                    format = m_last_value_format->m_format;
969                                else
970                                    // force the system into using unsigned integers for bitfields
971                                    format = (m_is_bitfield_for_scalar ? eFormatUnsigned :
972                                    ClangASTType::GetFormat(clang_type));
973                            }
974
975                            if (ClangASTType::DumpTypeValue (GetClangAST(),            // The clang AST
976                                                             clang_type,               // The clang type to display
977                                                             &sstr,
978                                                             format,                   // Format to display this type with
979                                                             m_data,                   // Data to extract from
980                                                             0,                        // Byte offset into "m_data"
981                                                             GetByteSize(),            // Byte size of item in "m_data"
982                                                             GetBitfieldBitSize(),     // Bitfield bit size
983                                                             GetBitfieldBitOffset()))  // Bitfield bit offset
984                                m_value_str.swap(sstr.GetString());
985                            else
986                            {
987                                m_error.SetErrorStringWithFormat ("unsufficient data for value (only %u of %u bytes available)",
988                                                                  m_data.GetByteSize(),
989                                                                  GetByteSize());
990                                m_value_str.clear();
991                            }
992                        }
993                    }
994                    break;
995
996                case Value::eContextTypeRegisterInfo:
997                    {
998                        const RegisterInfo *reg_info = m_value.GetRegisterInfo();
999                        if (reg_info)
1000                        {
1001                            StreamString reg_sstr;
1002                            m_data.Dump(&reg_sstr, 0, reg_info->format, reg_info->byte_size, 1, UINT32_MAX, LLDB_INVALID_ADDRESS, 0, 0);
1003                            m_value_str.swap(reg_sstr.GetString());
1004                        }
1005                    }
1006                    break;
1007
1008                default:
1009                    break;
1010                }
1011            }
1012
1013            if (!m_value_did_change && m_old_value_valid)
1014            {
1015                // The value was gotten successfully, so we consider the
1016                // value as changed if the value string differs
1017                SetValueDidChange (m_old_value_str != m_value_str);
1018            }
1019        }
1020    }
1021    if (m_value_str.empty())
1022        return NULL;
1023    return m_value_str.c_str();
1024}
1025
1026const char *
1027ValueObject::GetPrintableRepresentation(ValueObjectRepresentationStyle val_obj_display,
1028                                        lldb::Format custom_format)
1029{
1030
1031    RefCounter ref(&m_dump_printable_counter);
1032
1033    if(custom_format != lldb::eFormatInvalid)
1034        SetFormat(custom_format);
1035
1036    const char * return_value;
1037
1038    switch(val_obj_display)
1039    {
1040        case eDisplayValue:
1041            return_value = GetValueAsCString();
1042            break;
1043        case eDisplaySummary:
1044            return_value = GetSummaryAsCString();
1045            break;
1046        case eDisplayLanguageSpecific:
1047            return_value = GetObjectDescription();
1048            break;
1049    }
1050
1051    // this code snippet might lead to endless recursion, thus we use a RefCounter here to
1052    // check that we are not looping endlessly
1053    if (!return_value && (m_dump_printable_counter < 3))
1054    {
1055        // try to pick the other choice
1056        if (val_obj_display == eDisplayValue)
1057            return_value = GetSummaryAsCString();
1058        else if (val_obj_display == eDisplaySummary)
1059            return_value = GetValueAsCString();
1060    }
1061
1062    return (return_value ? return_value : "<error>");
1063
1064}
1065
1066bool
1067ValueObject::DumpPrintableRepresentation(Stream& s,
1068                                         ValueObjectRepresentationStyle val_obj_display,
1069                                         lldb::Format custom_format)
1070{
1071
1072    clang_type_t elem_or_pointee_type;
1073    Flags flags(ClangASTContext::GetTypeInfo(GetClangType(), GetClangAST(), &elem_or_pointee_type));
1074
1075    if (flags.AnySet(ClangASTContext::eTypeIsArray | ClangASTContext::eTypeIsPointer)
1076         && val_obj_display == ValueObject::eDisplayValue)
1077    {
1078        // when being asked to get a printable display an array or pointer type directly,
1079        // try to "do the right thing"
1080
1081        if (IsCStringContainer(true) &&
1082            (custom_format == lldb::eFormatCString ||
1083             custom_format == lldb::eFormatCharArray ||
1084             custom_format == lldb::eFormatChar ||
1085             custom_format == lldb::eFormatVectorOfChar)) // print char[] & char* directly
1086        {
1087            Error error;
1088            ReadPointedString(s,
1089                              error,
1090                              0,
1091                              (custom_format == lldb::eFormatVectorOfChar) ||
1092                              (custom_format == lldb::eFormatCharArray));
1093            return !error.Fail();
1094        }
1095
1096        if (custom_format == lldb::eFormatEnum)
1097            return false;
1098
1099        // this only works for arrays, because I have no way to know when
1100        // the pointed memory ends, and no special \0 end of data marker
1101        if (flags.Test(ClangASTContext::eTypeIsArray))
1102        {
1103            if ((custom_format == lldb::eFormatBytes) ||
1104                (custom_format == lldb::eFormatBytesWithASCII))
1105            {
1106                uint32_t count = GetNumChildren();
1107
1108                s << '[';
1109                for (uint32_t low = 0; low < count; low++)
1110                {
1111
1112                    if (low)
1113                        s << ',';
1114
1115                    ValueObjectSP child = GetChildAtIndex(low,true);
1116                    if (!child.get())
1117                    {
1118                        s << "<error>";
1119                        continue;
1120                    }
1121                    child->DumpPrintableRepresentation(s, ValueObject::eDisplayValue, custom_format);
1122                }
1123
1124                s << ']';
1125
1126                return true;
1127            }
1128
1129            if ((custom_format == lldb::eFormatVectorOfChar) ||
1130                (custom_format == lldb::eFormatVectorOfFloat32) ||
1131                (custom_format == lldb::eFormatVectorOfFloat64) ||
1132                (custom_format == lldb::eFormatVectorOfSInt16) ||
1133                (custom_format == lldb::eFormatVectorOfSInt32) ||
1134                (custom_format == lldb::eFormatVectorOfSInt64) ||
1135                (custom_format == lldb::eFormatVectorOfSInt8) ||
1136                (custom_format == lldb::eFormatVectorOfUInt128) ||
1137                (custom_format == lldb::eFormatVectorOfUInt16) ||
1138                (custom_format == lldb::eFormatVectorOfUInt32) ||
1139                (custom_format == lldb::eFormatVectorOfUInt64) ||
1140                (custom_format == lldb::eFormatVectorOfUInt8)) // arrays of bytes, bytes with ASCII or any vector format should be printed directly
1141            {
1142                uint32_t count = GetNumChildren();
1143
1144                lldb::Format format = FormatManager::GetSingleItemFormat(custom_format);
1145
1146                s << '[';
1147                for (uint32_t low = 0; low < count; low++)
1148                {
1149
1150                    if (low)
1151                        s << ',';
1152
1153                    ValueObjectSP child = GetChildAtIndex(low,true);
1154                    if (!child.get())
1155                    {
1156                        s << "<error>";
1157                        continue;
1158                    }
1159                    child->DumpPrintableRepresentation(s, ValueObject::eDisplayValue, format);
1160                }
1161
1162                s << ']';
1163
1164                return true;
1165            }
1166        }
1167
1168        if ((custom_format == lldb::eFormatBoolean) ||
1169            (custom_format == lldb::eFormatBinary) ||
1170            (custom_format == lldb::eFormatChar) ||
1171            (custom_format == lldb::eFormatCharPrintable) ||
1172            (custom_format == lldb::eFormatComplexFloat) ||
1173            (custom_format == lldb::eFormatDecimal) ||
1174            (custom_format == lldb::eFormatHex) ||
1175            (custom_format == lldb::eFormatFloat) ||
1176            (custom_format == lldb::eFormatOctal) ||
1177            (custom_format == lldb::eFormatOSType) ||
1178            (custom_format == lldb::eFormatUnicode16) ||
1179            (custom_format == lldb::eFormatUnicode32) ||
1180            (custom_format == lldb::eFormatUnsigned) ||
1181            (custom_format == lldb::eFormatPointer) ||
1182            (custom_format == lldb::eFormatComplexInteger) ||
1183            (custom_format == lldb::eFormatComplex) ||
1184            (custom_format == lldb::eFormatDefault)) // use the [] operator
1185            return false;
1186    }
1187    const char *targetvalue = GetPrintableRepresentation(val_obj_display, custom_format);
1188    if(targetvalue)
1189        s.PutCString(targetvalue);
1190    bool var_success = (targetvalue != NULL);
1191    if(custom_format != eFormatInvalid)
1192        SetFormat(eFormatDefault);
1193    return var_success;
1194}
1195
1196addr_t
1197ValueObject::GetAddressOf (AddressType &address_type, bool scalar_is_load_address)
1198{
1199    if (!UpdateValueIfNeeded())
1200        return LLDB_INVALID_ADDRESS;
1201
1202    switch (m_value.GetValueType())
1203    {
1204    case Value::eValueTypeScalar:
1205        if (scalar_is_load_address)
1206        {
1207            address_type = eAddressTypeLoad;
1208            return m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1209        }
1210        break;
1211
1212    case Value::eValueTypeLoadAddress:
1213    case Value::eValueTypeFileAddress:
1214    case Value::eValueTypeHostAddress:
1215        {
1216            address_type = m_value.GetValueAddressType ();
1217            return m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1218        }
1219        break;
1220    }
1221    address_type = eAddressTypeInvalid;
1222    return LLDB_INVALID_ADDRESS;
1223}
1224
1225addr_t
1226ValueObject::GetPointerValue (AddressType &address_type, bool scalar_is_load_address)
1227{
1228    lldb::addr_t address = LLDB_INVALID_ADDRESS;
1229    address_type = eAddressTypeInvalid;
1230
1231    if (!UpdateValueIfNeeded())
1232        return address;
1233
1234    switch (m_value.GetValueType())
1235    {
1236    case Value::eValueTypeScalar:
1237        if (scalar_is_load_address)
1238        {
1239            address = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1240            address_type = eAddressTypeLoad;
1241        }
1242        break;
1243
1244    case Value::eValueTypeLoadAddress:
1245    case Value::eValueTypeFileAddress:
1246    case Value::eValueTypeHostAddress:
1247        {
1248            uint32_t data_offset = 0;
1249            address = m_data.GetPointer(&data_offset);
1250            address_type = m_value.GetValueAddressType();
1251            if (address_type == eAddressTypeInvalid)
1252                address_type = eAddressTypeLoad;
1253        }
1254        break;
1255    }
1256
1257    if (m_pointers_point_to_load_addrs)
1258        address_type = eAddressTypeLoad;
1259
1260    return address;
1261}
1262
1263bool
1264ValueObject::SetValueFromCString (const char *value_str)
1265{
1266    // Make sure our value is up to date first so that our location and location
1267    // type is valid.
1268    if (!UpdateValueIfNeeded())
1269        return false;
1270
1271    uint32_t count = 0;
1272    lldb::Encoding encoding = ClangASTType::GetEncoding (GetClangType(), count);
1273
1274    char *end = NULL;
1275    const size_t byte_size = GetByteSize();
1276    switch (encoding)
1277    {
1278    case eEncodingInvalid:
1279        return false;
1280
1281    case eEncodingUint:
1282        if (byte_size > sizeof(unsigned long long))
1283        {
1284            return false;
1285        }
1286        else
1287        {
1288            unsigned long long ull_val = strtoull(value_str, &end, 0);
1289            if (end && *end != '\0')
1290                return false;
1291            m_value.GetScalar() = ull_val;
1292            // Limit the bytes in our m_data appropriately.
1293            m_value.GetScalar().GetData (m_data, byte_size);
1294        }
1295        break;
1296
1297    case eEncodingSint:
1298        if (byte_size > sizeof(long long))
1299        {
1300            return false;
1301        }
1302        else
1303        {
1304            long long sll_val = strtoll(value_str, &end, 0);
1305            if (end && *end != '\0')
1306                return false;
1307            m_value.GetScalar() = sll_val;
1308            // Limit the bytes in our m_data appropriately.
1309            m_value.GetScalar().GetData (m_data, byte_size);
1310        }
1311        break;
1312
1313    case eEncodingIEEE754:
1314        {
1315            const off_t byte_offset = GetByteOffset();
1316            uint8_t *dst = const_cast<uint8_t *>(m_data.PeekData(byte_offset, byte_size));
1317            if (dst != NULL)
1318            {
1319                // We are decoding a float into host byte order below, so make
1320                // sure m_data knows what it contains.
1321                m_data.SetByteOrder(lldb::endian::InlHostByteOrder());
1322                const size_t converted_byte_size = ClangASTContext::ConvertStringToFloatValue (
1323                                                        GetClangAST(),
1324                                                        GetClangType(),
1325                                                        value_str,
1326                                                        dst,
1327                                                        byte_size);
1328
1329                if (converted_byte_size == byte_size)
1330                {
1331                }
1332            }
1333        }
1334        break;
1335
1336    case eEncodingVector:
1337        return false;
1338
1339    default:
1340        return false;
1341    }
1342
1343    // If we have made it here the value is in m_data and we should write it
1344    // out to the target
1345    return Write ();
1346}
1347
1348bool
1349ValueObject::Write ()
1350{
1351    // Clear the update ID so the next time we try and read the value
1352    // we try and read it again.
1353    m_update_point.SetNeedsUpdate();
1354
1355    // TODO: when Value has a method to write a value back, call it from here.
1356    return false;
1357
1358}
1359
1360lldb::LanguageType
1361ValueObject::GetObjectRuntimeLanguage ()
1362{
1363    clang_type_t opaque_qual_type = GetClangType();
1364    if (opaque_qual_type == NULL)
1365        return lldb::eLanguageTypeC;
1366
1367    // If the type is a reference, then resolve it to what it refers to first:
1368    clang::QualType qual_type (clang::QualType::getFromOpaquePtr(opaque_qual_type).getNonReferenceType());
1369    if (qual_type->isAnyPointerType())
1370    {
1371        if (qual_type->isObjCObjectPointerType())
1372            return lldb::eLanguageTypeObjC;
1373
1374        clang::QualType pointee_type (qual_type->getPointeeType());
1375        if (pointee_type->getCXXRecordDeclForPointerType() != NULL)
1376            return lldb::eLanguageTypeC_plus_plus;
1377        if (pointee_type->isObjCObjectOrInterfaceType())
1378            return lldb::eLanguageTypeObjC;
1379        if (pointee_type->isObjCClassType())
1380            return lldb::eLanguageTypeObjC;
1381    }
1382    else
1383    {
1384        if (ClangASTContext::IsObjCClassType (opaque_qual_type))
1385            return lldb::eLanguageTypeObjC;
1386        if (ClangASTContext::IsCXXClassType (opaque_qual_type))
1387            return lldb::eLanguageTypeC_plus_plus;
1388    }
1389
1390    return lldb::eLanguageTypeC;
1391}
1392
1393void
1394ValueObject::AddSyntheticChild (const ConstString &key, ValueObject *valobj)
1395{
1396    m_synthetic_children[key] = valobj;
1397}
1398
1399ValueObjectSP
1400ValueObject::GetSyntheticChild (const ConstString &key) const
1401{
1402    ValueObjectSP synthetic_child_sp;
1403    std::map<ConstString, ValueObject *>::const_iterator pos = m_synthetic_children.find (key);
1404    if (pos != m_synthetic_children.end())
1405        synthetic_child_sp = pos->second->GetSP();
1406    return synthetic_child_sp;
1407}
1408
1409bool
1410ValueObject::IsPointerType ()
1411{
1412    return ClangASTContext::IsPointerType (GetClangType());
1413}
1414
1415bool
1416ValueObject::IsArrayType ()
1417{
1418    return ClangASTContext::IsArrayType (GetClangType());
1419}
1420
1421bool
1422ValueObject::IsScalarType ()
1423{
1424    return ClangASTContext::IsScalarType (GetClangType());
1425}
1426
1427bool
1428ValueObject::IsIntegerType (bool &is_signed)
1429{
1430    return ClangASTContext::IsIntegerType (GetClangType(), is_signed);
1431}
1432
1433bool
1434ValueObject::IsPointerOrReferenceType ()
1435{
1436    return ClangASTContext::IsPointerOrReferenceType (GetClangType());
1437}
1438
1439bool
1440ValueObject::IsPossibleCPlusPlusDynamicType ()
1441{
1442    return ClangASTContext::IsPossibleCPlusPlusDynamicType (GetClangAST (), GetClangType());
1443}
1444
1445bool
1446ValueObject::IsPossibleDynamicType ()
1447{
1448    return ClangASTContext::IsPossibleDynamicType (GetClangAST (), GetClangType());
1449}
1450
1451ValueObjectSP
1452ValueObject::GetSyntheticArrayMemberFromPointer (int32_t index, bool can_create)
1453{
1454    ValueObjectSP synthetic_child_sp;
1455    if (IsPointerType ())
1456    {
1457        char index_str[64];
1458        snprintf(index_str, sizeof(index_str), "[%i]", index);
1459        ConstString index_const_str(index_str);
1460        // Check if we have already created a synthetic array member in this
1461        // valid object. If we have we will re-use it.
1462        synthetic_child_sp = GetSyntheticChild (index_const_str);
1463        if (!synthetic_child_sp)
1464        {
1465            ValueObject *synthetic_child;
1466            // We haven't made a synthetic array member for INDEX yet, so
1467            // lets make one and cache it for any future reference.
1468            synthetic_child = CreateChildAtIndex(0, true, index);
1469
1470            // Cache the value if we got one back...
1471            if (synthetic_child)
1472            {
1473                AddSyntheticChild(index_const_str, synthetic_child);
1474                synthetic_child_sp = synthetic_child->GetSP();
1475                synthetic_child_sp->SetName(index_str);
1476                synthetic_child_sp->m_is_array_item_for_pointer = true;
1477            }
1478        }
1479    }
1480    return synthetic_child_sp;
1481}
1482
1483// This allows you to create an array member using and index
1484// that doesn't not fall in the normal bounds of the array.
1485// Many times structure can be defined as:
1486// struct Collection
1487// {
1488//     uint32_t item_count;
1489//     Item item_array[0];
1490// };
1491// The size of the "item_array" is 1, but many times in practice
1492// there are more items in "item_array".
1493
1494ValueObjectSP
1495ValueObject::GetSyntheticArrayMemberFromArray (int32_t index, bool can_create)
1496{
1497    ValueObjectSP synthetic_child_sp;
1498    if (IsArrayType ())
1499    {
1500        char index_str[64];
1501        snprintf(index_str, sizeof(index_str), "[%i]", index);
1502        ConstString index_const_str(index_str);
1503        // Check if we have already created a synthetic array member in this
1504        // valid object. If we have we will re-use it.
1505        synthetic_child_sp = GetSyntheticChild (index_const_str);
1506        if (!synthetic_child_sp)
1507        {
1508            ValueObject *synthetic_child;
1509            // We haven't made a synthetic array member for INDEX yet, so
1510            // lets make one and cache it for any future reference.
1511            synthetic_child = CreateChildAtIndex(0, true, index);
1512
1513            // Cache the value if we got one back...
1514            if (synthetic_child)
1515            {
1516                AddSyntheticChild(index_const_str, synthetic_child);
1517                synthetic_child_sp = synthetic_child->GetSP();
1518                synthetic_child_sp->SetName(index_str);
1519                synthetic_child_sp->m_is_array_item_for_pointer = true;
1520            }
1521        }
1522    }
1523    return synthetic_child_sp;
1524}
1525
1526ValueObjectSP
1527ValueObject::GetSyntheticBitFieldChild (uint32_t from, uint32_t to, bool can_create)
1528{
1529    ValueObjectSP synthetic_child_sp;
1530    if (IsScalarType ())
1531    {
1532        char index_str[64];
1533        snprintf(index_str, sizeof(index_str), "[%i-%i]", from, to);
1534        ConstString index_const_str(index_str);
1535        // Check if we have already created a synthetic array member in this
1536        // valid object. If we have we will re-use it.
1537        synthetic_child_sp = GetSyntheticChild (index_const_str);
1538        if (!synthetic_child_sp)
1539        {
1540            ValueObjectChild *synthetic_child;
1541            // We haven't made a synthetic array member for INDEX yet, so
1542            // lets make one and cache it for any future reference.
1543            synthetic_child = new ValueObjectChild(*this,
1544                                                      GetClangAST(),
1545                                                      GetClangType(),
1546                                                      index_const_str,
1547                                                      GetByteSize(),
1548                                                      0,
1549                                                      to-from+1,
1550                                                      from,
1551                                                      false,
1552                                                      false);
1553
1554            // Cache the value if we got one back...
1555            if (synthetic_child)
1556            {
1557                AddSyntheticChild(index_const_str, synthetic_child);
1558                synthetic_child_sp = synthetic_child->GetSP();
1559                synthetic_child_sp->SetName(index_str);
1560                synthetic_child_sp->m_is_bitfield_for_scalar = true;
1561            }
1562        }
1563    }
1564    return synthetic_child_sp;
1565}
1566
1567void
1568ValueObject::CalculateDynamicValue (lldb::DynamicValueType use_dynamic)
1569{
1570    if (use_dynamic == lldb::eNoDynamicValues)
1571        return;
1572
1573    if (!m_dynamic_value && !IsDynamic())
1574    {
1575        Process *process = m_update_point.GetProcess();
1576        bool worth_having_dynamic_value = false;
1577
1578
1579        // FIXME: Process should have some kind of "map over Runtimes" so we don't have to
1580        // hard code this everywhere.
1581        lldb::LanguageType known_type = GetObjectRuntimeLanguage();
1582        if (known_type != lldb::eLanguageTypeUnknown && known_type != lldb::eLanguageTypeC)
1583        {
1584            LanguageRuntime *runtime = process->GetLanguageRuntime (known_type);
1585            if (runtime)
1586                worth_having_dynamic_value = runtime->CouldHaveDynamicValue(*this);
1587        }
1588        else
1589        {
1590            LanguageRuntime *cpp_runtime = process->GetLanguageRuntime (lldb::eLanguageTypeC_plus_plus);
1591            if (cpp_runtime)
1592                worth_having_dynamic_value = cpp_runtime->CouldHaveDynamicValue(*this);
1593
1594            if (!worth_having_dynamic_value)
1595            {
1596                LanguageRuntime *objc_runtime = process->GetLanguageRuntime (lldb::eLanguageTypeObjC);
1597                if (objc_runtime)
1598                    worth_having_dynamic_value = objc_runtime->CouldHaveDynamicValue(*this);
1599            }
1600        }
1601
1602        if (worth_having_dynamic_value)
1603            m_dynamic_value = new ValueObjectDynamicValue (*this, use_dynamic);
1604
1605//        if (worth_having_dynamic_value)
1606//            printf ("Adding dynamic value %s (%p) to (%p) - manager %p.\n", m_name.GetCString(), m_dynamic_value, this, m_manager);
1607
1608    }
1609}
1610
1611ValueObjectSP
1612ValueObject::GetDynamicValue (DynamicValueType use_dynamic)
1613{
1614    if (use_dynamic == lldb::eNoDynamicValues)
1615        return ValueObjectSP();
1616
1617    if (!IsDynamic() && m_dynamic_value == NULL)
1618    {
1619        CalculateDynamicValue(use_dynamic);
1620    }
1621    if (m_dynamic_value)
1622        return m_dynamic_value->GetSP();
1623    else
1624        return ValueObjectSP();
1625}
1626
1627bool
1628ValueObject::GetBaseClassPath (Stream &s)
1629{
1630    if (IsBaseClass())
1631    {
1632        bool parent_had_base_class = GetParent() && GetParent()->GetBaseClassPath (s);
1633        clang_type_t clang_type = GetClangType();
1634        std::string cxx_class_name;
1635        bool this_had_base_class = ClangASTContext::GetCXXClassName (clang_type, cxx_class_name);
1636        if (this_had_base_class)
1637        {
1638            if (parent_had_base_class)
1639                s.PutCString("::");
1640            s.PutCString(cxx_class_name.c_str());
1641        }
1642        return parent_had_base_class || this_had_base_class;
1643    }
1644    return false;
1645}
1646
1647
1648ValueObject *
1649ValueObject::GetNonBaseClassParent()
1650{
1651    if (GetParent())
1652    {
1653        if (GetParent()->IsBaseClass())
1654            return GetParent()->GetNonBaseClassParent();
1655        else
1656            return GetParent();
1657    }
1658    return NULL;
1659}
1660
1661void
1662ValueObject::GetExpressionPath (Stream &s, bool qualify_cxx_base_classes, GetExpressionPathFormat epformat)
1663{
1664    const bool is_deref_of_parent = IsDereferenceOfParent ();
1665
1666    if(is_deref_of_parent && epformat == eDereferencePointers) {
1667        // this is the original format of GetExpressionPath() producing code like *(a_ptr).memberName, which is entirely
1668        // fine, until you put this into StackFrame::GetValueForVariableExpressionPath() which prefers to see a_ptr->memberName.
1669        // the eHonorPointers mode is meant to produce strings in this latter format
1670        s.PutCString("*(");
1671    }
1672
1673    ValueObject* parent = GetParent();
1674
1675    if (parent)
1676        parent->GetExpressionPath (s, qualify_cxx_base_classes, epformat);
1677
1678    // if we are a deref_of_parent just because we are synthetic array
1679    // members made up to allow ptr[%d] syntax to work in variable
1680    // printing, then add our name ([%d]) to the expression path
1681    if(m_is_array_item_for_pointer && epformat == eHonorPointers)
1682        s.PutCString(m_name.AsCString());
1683
1684    if (!IsBaseClass())
1685    {
1686        if (!is_deref_of_parent)
1687        {
1688            ValueObject *non_base_class_parent = GetNonBaseClassParent();
1689            if (non_base_class_parent)
1690            {
1691                clang_type_t non_base_class_parent_clang_type = non_base_class_parent->GetClangType();
1692                if (non_base_class_parent_clang_type)
1693                {
1694                    const uint32_t non_base_class_parent_type_info = ClangASTContext::GetTypeInfo (non_base_class_parent_clang_type, NULL, NULL);
1695
1696                    if(parent && parent->IsDereferenceOfParent() && epformat == eHonorPointers)
1697                    {
1698                        s.PutCString("->");
1699                    }
1700                    else
1701                    {
1702                        if (non_base_class_parent_type_info & ClangASTContext::eTypeIsPointer)
1703                        {
1704                            s.PutCString("->");
1705                        }
1706                        else if ((non_base_class_parent_type_info & ClangASTContext::eTypeHasChildren) &&
1707                                 !(non_base_class_parent_type_info & ClangASTContext::eTypeIsArray))
1708                        {
1709                            s.PutChar('.');
1710                        }
1711                    }
1712                }
1713            }
1714
1715            const char *name = GetName().GetCString();
1716            if (name)
1717            {
1718                if (qualify_cxx_base_classes)
1719                {
1720                    if (GetBaseClassPath (s))
1721                        s.PutCString("::");
1722                }
1723                s.PutCString(name);
1724            }
1725        }
1726    }
1727
1728    if (is_deref_of_parent && epformat == eDereferencePointers) {
1729        s.PutChar(')');
1730    }
1731}
1732
1733lldb::ValueObjectSP
1734ValueObject::GetValueForExpressionPath(const char* expression,
1735                                       const char** first_unparsed,
1736                                       ExpressionPathScanEndReason* reason_to_stop,
1737                                       ExpressionPathEndResultType* final_value_type,
1738                                       const GetValueForExpressionPathOptions& options,
1739                                       ExpressionPathAftermath* final_task_on_target)
1740{
1741
1742    const char* dummy_first_unparsed;
1743    ExpressionPathScanEndReason dummy_reason_to_stop;
1744    ExpressionPathEndResultType dummy_final_value_type;
1745    ExpressionPathAftermath dummy_final_task_on_target = ValueObject::eNothing;
1746
1747    ValueObjectSP ret_val = GetValueForExpressionPath_Impl(expression,
1748                                                           first_unparsed ? first_unparsed : &dummy_first_unparsed,
1749                                                           reason_to_stop ? reason_to_stop : &dummy_reason_to_stop,
1750                                                           final_value_type ? final_value_type : &dummy_final_value_type,
1751                                                           options,
1752                                                           final_task_on_target ? final_task_on_target : &dummy_final_task_on_target);
1753
1754    if (!final_task_on_target || *final_task_on_target == ValueObject::eNothing)
1755    {
1756        return ret_val;
1757    }
1758    if (ret_val.get() && *final_value_type == ePlain) // I can only deref and takeaddress of plain objects
1759    {
1760        if (*final_task_on_target == ValueObject::eDereference)
1761        {
1762            Error error;
1763            ValueObjectSP final_value = ret_val->Dereference(error);
1764            if (error.Fail() || !final_value.get())
1765            {
1766                *reason_to_stop = ValueObject::eDereferencingFailed;
1767                *final_value_type = ValueObject::eInvalid;
1768                return ValueObjectSP();
1769            }
1770            else
1771            {
1772                *final_task_on_target = ValueObject::eNothing;
1773                return final_value;
1774            }
1775        }
1776        if (*final_task_on_target == ValueObject::eTakeAddress)
1777        {
1778            Error error;
1779            ValueObjectSP final_value = ret_val->AddressOf(error);
1780            if (error.Fail() || !final_value.get())
1781            {
1782                *reason_to_stop = ValueObject::eTakingAddressFailed;
1783                *final_value_type = ValueObject::eInvalid;
1784                return ValueObjectSP();
1785            }
1786            else
1787            {
1788                *final_task_on_target = ValueObject::eNothing;
1789                return final_value;
1790            }
1791        }
1792    }
1793    return ret_val; // final_task_on_target will still have its original value, so you know I did not do it
1794}
1795
1796int
1797ValueObject::GetValuesForExpressionPath(const char* expression,
1798                                        lldb::ValueObjectListSP& list,
1799                                        const char** first_unparsed,
1800                                        ExpressionPathScanEndReason* reason_to_stop,
1801                                        ExpressionPathEndResultType* final_value_type,
1802                                        const GetValueForExpressionPathOptions& options,
1803                                        ExpressionPathAftermath* final_task_on_target)
1804{
1805    const char* dummy_first_unparsed;
1806    ExpressionPathScanEndReason dummy_reason_to_stop;
1807    ExpressionPathEndResultType dummy_final_value_type;
1808    ExpressionPathAftermath dummy_final_task_on_target = ValueObject::eNothing;
1809
1810    ValueObjectSP ret_val = GetValueForExpressionPath_Impl(expression,
1811                                                           first_unparsed ? first_unparsed : &dummy_first_unparsed,
1812                                                           reason_to_stop ? reason_to_stop : &dummy_reason_to_stop,
1813                                                           final_value_type ? final_value_type : &dummy_final_value_type,
1814                                                           options,
1815                                                           final_task_on_target ? final_task_on_target : &dummy_final_task_on_target);
1816
1817    if (!ret_val.get()) // if there are errors, I add nothing to the list
1818        return 0;
1819
1820    if (*reason_to_stop != eArrayRangeOperatorMet)
1821    {
1822        // I need not expand a range, just post-process the final value and return
1823        if (!final_task_on_target || *final_task_on_target == ValueObject::eNothing)
1824        {
1825            list->Append(ret_val);
1826            return 1;
1827        }
1828        if (ret_val.get() && *final_value_type == ePlain) // I can only deref and takeaddress of plain objects
1829        {
1830            if (*final_task_on_target == ValueObject::eDereference)
1831            {
1832                Error error;
1833                ValueObjectSP final_value = ret_val->Dereference(error);
1834                if (error.Fail() || !final_value.get())
1835                {
1836                    *reason_to_stop = ValueObject::eDereferencingFailed;
1837                    *final_value_type = ValueObject::eInvalid;
1838                    return 0;
1839                }
1840                else
1841                {
1842                    *final_task_on_target = ValueObject::eNothing;
1843                    list->Append(final_value);
1844                    return 1;
1845                }
1846            }
1847            if (*final_task_on_target == ValueObject::eTakeAddress)
1848            {
1849                Error error;
1850                ValueObjectSP final_value = ret_val->AddressOf(error);
1851                if (error.Fail() || !final_value.get())
1852                {
1853                    *reason_to_stop = ValueObject::eTakingAddressFailed;
1854                    *final_value_type = ValueObject::eInvalid;
1855                    return 0;
1856                }
1857                else
1858                {
1859                    *final_task_on_target = ValueObject::eNothing;
1860                    list->Append(final_value);
1861                    return 1;
1862                }
1863            }
1864        }
1865    }
1866    else
1867    {
1868        return ExpandArraySliceExpression(first_unparsed ? *first_unparsed : dummy_first_unparsed,
1869                                          first_unparsed ? first_unparsed : &dummy_first_unparsed,
1870                                          ret_val,
1871                                          list,
1872                                          reason_to_stop ? reason_to_stop : &dummy_reason_to_stop,
1873                                          final_value_type ? final_value_type : &dummy_final_value_type,
1874                                          options,
1875                                          final_task_on_target ? final_task_on_target : &dummy_final_task_on_target);
1876    }
1877    // in any non-covered case, just do the obviously right thing
1878    list->Append(ret_val);
1879    return 1;
1880}
1881
1882lldb::ValueObjectSP
1883ValueObject::GetValueForExpressionPath_Impl(const char* expression_cstr,
1884                                            const char** first_unparsed,
1885                                            ExpressionPathScanEndReason* reason_to_stop,
1886                                            ExpressionPathEndResultType* final_result,
1887                                            const GetValueForExpressionPathOptions& options,
1888                                            ExpressionPathAftermath* what_next)
1889{
1890    ValueObjectSP root = GetSP();
1891
1892    if (!root.get())
1893        return ValueObjectSP();
1894
1895    *first_unparsed = expression_cstr;
1896
1897    while (true)
1898    {
1899
1900        const char* expression_cstr = *first_unparsed; // hide the top level expression_cstr
1901
1902        lldb::clang_type_t root_clang_type = root->GetClangType();
1903        lldb::clang_type_t pointee_clang_type;
1904        Flags root_clang_type_info,pointee_clang_type_info;
1905
1906        root_clang_type_info = Flags(ClangASTContext::GetTypeInfo(root_clang_type, GetClangAST(), &pointee_clang_type));
1907        if (pointee_clang_type)
1908            pointee_clang_type_info = Flags(ClangASTContext::GetTypeInfo(pointee_clang_type, GetClangAST(), NULL));
1909
1910        if (!expression_cstr || *expression_cstr == '\0')
1911        {
1912            *reason_to_stop = ValueObject::eEndOfString;
1913            return root;
1914        }
1915
1916        switch (*expression_cstr)
1917        {
1918            case '-':
1919            {
1920                if (options.m_check_dot_vs_arrow_syntax &&
1921                    root_clang_type_info.Test(ClangASTContext::eTypeIsPointer) ) // if you are trying to use -> on a non-pointer and I must catch the error
1922                {
1923                    *first_unparsed = expression_cstr;
1924                    *reason_to_stop = ValueObject::eArrowInsteadOfDot;
1925                    *final_result = ValueObject::eInvalid;
1926                    return ValueObjectSP();
1927                }
1928                if (root_clang_type_info.Test(ClangASTContext::eTypeIsObjC) &&  // if yo are trying to extract an ObjC IVar when this is forbidden
1929                    root_clang_type_info.Test(ClangASTContext::eTypeIsPointer) &&
1930                    options.m_no_fragile_ivar)
1931                {
1932                    *first_unparsed = expression_cstr;
1933                    *reason_to_stop = ValueObject::eFragileIVarNotAllowed;
1934                    *final_result = ValueObject::eInvalid;
1935                    return ValueObjectSP();
1936                }
1937                if (expression_cstr[1] != '>')
1938                {
1939                    *first_unparsed = expression_cstr;
1940                    *reason_to_stop = ValueObject::eUnexpectedSymbol;
1941                    *final_result = ValueObject::eInvalid;
1942                    return ValueObjectSP();
1943                }
1944                expression_cstr++; // skip the -
1945            }
1946            case '.': // or fallthrough from ->
1947            {
1948                if (options.m_check_dot_vs_arrow_syntax && *expression_cstr == '.' &&
1949                    root_clang_type_info.Test(ClangASTContext::eTypeIsPointer)) // if you are trying to use . on a pointer and I must catch the error
1950                {
1951                    *first_unparsed = expression_cstr;
1952                    *reason_to_stop = ValueObject::eDotInsteadOfArrow;
1953                    *final_result = ValueObject::eInvalid;
1954                    return ValueObjectSP();
1955                }
1956                expression_cstr++; // skip .
1957                const char *next_separator = strpbrk(expression_cstr+1,"-.[");
1958                ConstString child_name;
1959                if (!next_separator) // if no other separator just expand this last layer
1960                {
1961                    child_name.SetCString (expression_cstr);
1962                    root = root->GetChildMemberWithName(child_name, true);
1963                    if (root.get()) // we know we are done, so just return
1964                    {
1965                        *first_unparsed = '\0';
1966                        *reason_to_stop = ValueObject::eEndOfString;
1967                        *final_result = ValueObject::ePlain;
1968                        return root;
1969                    }
1970                    else
1971                    {
1972                        *first_unparsed = expression_cstr;
1973                        *reason_to_stop = ValueObject::eNoSuchChild;
1974                        *final_result = ValueObject::eInvalid;
1975                        return ValueObjectSP();
1976                    }
1977                }
1978                else // other layers do expand
1979                {
1980                    child_name.SetCStringWithLength(expression_cstr, next_separator - expression_cstr);
1981                    root = root->GetChildMemberWithName(child_name, true);
1982                    if (root.get()) // store the new root and move on
1983                    {
1984                        *first_unparsed = next_separator;
1985                        *final_result = ValueObject::ePlain;
1986                        continue;
1987                    }
1988                    else
1989                    {
1990                        *first_unparsed = expression_cstr;
1991                        *reason_to_stop = ValueObject::eNoSuchChild;
1992                        *final_result = ValueObject::eInvalid;
1993                        return ValueObjectSP();
1994                    }
1995                }
1996                break;
1997            }
1998            case '[':
1999            {
2000                if (!root_clang_type_info.Test(ClangASTContext::eTypeIsArray) && !root_clang_type_info.Test(ClangASTContext::eTypeIsPointer)) // if this is not a T[] nor a T*
2001                {
2002                    if (!root_clang_type_info.Test(ClangASTContext::eTypeIsScalar)) // if this is not even a scalar, this syntax is just plain wrong!
2003                    {
2004                        *first_unparsed = expression_cstr;
2005                        *reason_to_stop = ValueObject::eRangeOperatorInvalid;
2006                        *final_result = ValueObject::eInvalid;
2007                        return ValueObjectSP();
2008                    }
2009                    else if (!options.m_allow_bitfields_syntax) // if this is a scalar, check that we can expand bitfields
2010                    {
2011                        *first_unparsed = expression_cstr;
2012                        *reason_to_stop = ValueObject::eRangeOperatorNotAllowed;
2013                        *final_result = ValueObject::eInvalid;
2014                        return ValueObjectSP();
2015                    }
2016                }
2017                if (*(expression_cstr+1) == ']') // if this is an unbounded range it only works for arrays
2018                {
2019                    if (!root_clang_type_info.Test(ClangASTContext::eTypeIsArray))
2020                    {
2021                        *first_unparsed = expression_cstr;
2022                        *reason_to_stop = ValueObject::eEmptyRangeNotAllowed;
2023                        *final_result = ValueObject::eInvalid;
2024                        return ValueObjectSP();
2025                    }
2026                    else // even if something follows, we cannot expand unbounded ranges, just let the caller do it
2027                    {
2028                        *first_unparsed = expression_cstr+2;
2029                        *reason_to_stop = ValueObject::eArrayRangeOperatorMet;
2030                        *final_result = ValueObject::eUnboundedRange;
2031                        return root;
2032                    }
2033                }
2034                const char *separator_position = ::strchr(expression_cstr+1,'-');
2035                const char *close_bracket_position = ::strchr(expression_cstr+1,']');
2036                if (!close_bracket_position) // if there is no ], this is a syntax error
2037                {
2038                    *first_unparsed = expression_cstr;
2039                    *reason_to_stop = ValueObject::eUnexpectedSymbol;
2040                    *final_result = ValueObject::eInvalid;
2041                    return ValueObjectSP();
2042                }
2043                if (!separator_position || separator_position > close_bracket_position) // if no separator, this is either [] or [N]
2044                {
2045                    char *end = NULL;
2046                    unsigned long index = ::strtoul (expression_cstr+1, &end, 0);
2047                    if (!end || end != close_bracket_position) // if something weird is in our way return an error
2048                    {
2049                        *first_unparsed = expression_cstr;
2050                        *reason_to_stop = ValueObject::eUnexpectedSymbol;
2051                        *final_result = ValueObject::eInvalid;
2052                        return ValueObjectSP();
2053                    }
2054                    if (end - expression_cstr == 1) // if this is [], only return a valid value for arrays
2055                    {
2056                        if (root_clang_type_info.Test(ClangASTContext::eTypeIsArray))
2057                        {
2058                            *first_unparsed = expression_cstr+2;
2059                            *reason_to_stop = ValueObject::eArrayRangeOperatorMet;
2060                            *final_result = ValueObject::eUnboundedRange;
2061                            return root;
2062                        }
2063                        else
2064                        {
2065                            *first_unparsed = expression_cstr;
2066                            *reason_to_stop = ValueObject::eEmptyRangeNotAllowed;
2067                            *final_result = ValueObject::eInvalid;
2068                            return ValueObjectSP();
2069                        }
2070                    }
2071                    // from here on we do have a valid index
2072                    if (root_clang_type_info.Test(ClangASTContext::eTypeIsArray))
2073                    {
2074                        ValueObjectSP child_valobj_sp = root->GetChildAtIndex(index, true);
2075                        if (!child_valobj_sp)
2076                            child_valobj_sp = root->GetSyntheticArrayMemberFromArray(index, true);
2077                        if (child_valobj_sp)
2078                        {
2079                            root = child_valobj_sp;
2080                            *first_unparsed = end+1; // skip ]
2081                            *final_result = ValueObject::ePlain;
2082                            continue;
2083                        }
2084                        else
2085                        {
2086                            *first_unparsed = expression_cstr;
2087                            *reason_to_stop = ValueObject::eNoSuchChild;
2088                            *final_result = ValueObject::eInvalid;
2089                            return ValueObjectSP();
2090                        }
2091                    }
2092                    else if (root_clang_type_info.Test(ClangASTContext::eTypeIsPointer))
2093                    {
2094                        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
2095                            pointee_clang_type_info.Test(ClangASTContext::eTypeIsScalar))
2096                        {
2097                            Error error;
2098                            root = root->Dereference(error);
2099                            if (error.Fail() || !root.get())
2100                            {
2101                                *first_unparsed = expression_cstr;
2102                                *reason_to_stop = ValueObject::eDereferencingFailed;
2103                                *final_result = ValueObject::eInvalid;
2104                                return ValueObjectSP();
2105                            }
2106                            else
2107                            {
2108                                *what_next = eNothing;
2109                                continue;
2110                            }
2111                        }
2112                        else
2113                        {
2114                            root = root->GetSyntheticArrayMemberFromPointer(index, true);
2115                            if (!root.get())
2116                            {
2117                                *first_unparsed = expression_cstr;
2118                                *reason_to_stop = ValueObject::eNoSuchChild;
2119                                *final_result = ValueObject::eInvalid;
2120                                return ValueObjectSP();
2121                            }
2122                            else
2123                            {
2124                                *first_unparsed = end+1; // skip ]
2125                                *final_result = ValueObject::ePlain;
2126                                continue;
2127                            }
2128                        }
2129                    }
2130                    else /*if (ClangASTContext::IsScalarType(root_clang_type))*/
2131                    {
2132                        root = root->GetSyntheticBitFieldChild(index, index, true);
2133                        if (!root.get())
2134                        {
2135                            *first_unparsed = expression_cstr;
2136                            *reason_to_stop = ValueObject::eNoSuchChild;
2137                            *final_result = ValueObject::eInvalid;
2138                            return ValueObjectSP();
2139                        }
2140                        else // we do not know how to expand members of bitfields, so we just return and let the caller do any further processing
2141                        {
2142                            *first_unparsed = end+1; // skip ]
2143                            *reason_to_stop = ValueObject::eBitfieldRangeOperatorMet;
2144                            *final_result = ValueObject::eBitfield;
2145                            return root;
2146                        }
2147                    }
2148                }
2149                else // we have a low and a high index
2150                {
2151                    char *end = NULL;
2152                    unsigned long index_lower = ::strtoul (expression_cstr+1, &end, 0);
2153                    if (!end || end != separator_position) // if something weird is in our way return an error
2154                    {
2155                        *first_unparsed = expression_cstr;
2156                        *reason_to_stop = ValueObject::eUnexpectedSymbol;
2157                        *final_result = ValueObject::eInvalid;
2158                        return ValueObjectSP();
2159                    }
2160                    unsigned long index_higher = ::strtoul (separator_position+1, &end, 0);
2161                    if (!end || end != close_bracket_position) // if something weird is in our way return an error
2162                    {
2163                        *first_unparsed = expression_cstr;
2164                        *reason_to_stop = ValueObject::eUnexpectedSymbol;
2165                        *final_result = ValueObject::eInvalid;
2166                        return ValueObjectSP();
2167                    }
2168                    if (index_lower > index_higher) // swap indices if required
2169                    {
2170                        unsigned long temp = index_lower;
2171                        index_lower = index_higher;
2172                        index_higher = temp;
2173                    }
2174                    if (root_clang_type_info.Test(ClangASTContext::eTypeIsScalar)) // expansion only works for scalars
2175                    {
2176                        root = root->GetSyntheticBitFieldChild(index_lower, index_higher, true);
2177                        if (!root.get())
2178                        {
2179                            *first_unparsed = expression_cstr;
2180                            *reason_to_stop = ValueObject::eNoSuchChild;
2181                            *final_result = ValueObject::eInvalid;
2182                            return ValueObjectSP();
2183                        }
2184                        else
2185                        {
2186                            *first_unparsed = end+1; // skip ]
2187                            *reason_to_stop = ValueObject::eBitfieldRangeOperatorMet;
2188                            *final_result = ValueObject::eBitfield;
2189                            return root;
2190                        }
2191                    }
2192                    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
2193                             *what_next == ValueObject::eDereference &&
2194                             pointee_clang_type_info.Test(ClangASTContext::eTypeIsScalar))
2195                    {
2196                        Error error;
2197                        root = root->Dereference(error);
2198                        if (error.Fail() || !root.get())
2199                        {
2200                            *first_unparsed = expression_cstr;
2201                            *reason_to_stop = ValueObject::eDereferencingFailed;
2202                            *final_result = ValueObject::eInvalid;
2203                            return ValueObjectSP();
2204                        }
2205                        else
2206                        {
2207                            *what_next = ValueObject::eNothing;
2208                            continue;
2209                        }
2210                    }
2211                    else
2212                    {
2213                        *first_unparsed = expression_cstr;
2214                        *reason_to_stop = ValueObject::eArrayRangeOperatorMet;
2215                        *final_result = ValueObject::eBoundedRange;
2216                        return root;
2217                    }
2218                }
2219                break;
2220            }
2221            default: // some non-separator is in the way
2222            {
2223                *first_unparsed = expression_cstr;
2224                *reason_to_stop = ValueObject::eUnexpectedSymbol;
2225                *final_result = ValueObject::eInvalid;
2226                return ValueObjectSP();
2227                break;
2228            }
2229        }
2230    }
2231}
2232
2233int
2234ValueObject::ExpandArraySliceExpression(const char* expression_cstr,
2235                                        const char** first_unparsed,
2236                                        lldb::ValueObjectSP root,
2237                                        lldb::ValueObjectListSP& list,
2238                                        ExpressionPathScanEndReason* reason_to_stop,
2239                                        ExpressionPathEndResultType* final_result,
2240                                        const GetValueForExpressionPathOptions& options,
2241                                        ExpressionPathAftermath* what_next)
2242{
2243    if (!root.get())
2244        return 0;
2245
2246    *first_unparsed = expression_cstr;
2247
2248    while (true)
2249    {
2250
2251        const char* expression_cstr = *first_unparsed; // hide the top level expression_cstr
2252
2253        lldb::clang_type_t root_clang_type = root->GetClangType();
2254        lldb::clang_type_t pointee_clang_type;
2255        Flags root_clang_type_info,pointee_clang_type_info;
2256
2257        root_clang_type_info = Flags(ClangASTContext::GetTypeInfo(root_clang_type, GetClangAST(), &pointee_clang_type));
2258        if (pointee_clang_type)
2259            pointee_clang_type_info = Flags(ClangASTContext::GetTypeInfo(pointee_clang_type, GetClangAST(), NULL));
2260
2261        if (!expression_cstr || *expression_cstr == '\0')
2262        {
2263            *reason_to_stop = ValueObject::eEndOfString;
2264            list->Append(root);
2265            return 1;
2266        }
2267
2268        switch (*expression_cstr)
2269        {
2270            case '[':
2271            {
2272                if (!root_clang_type_info.Test(ClangASTContext::eTypeIsArray) && !root_clang_type_info.Test(ClangASTContext::eTypeIsPointer)) // if this is not a T[] nor a T*
2273                {
2274                    if (!root_clang_type_info.Test(ClangASTContext::eTypeIsScalar)) // if this is not even a scalar, this syntax is just plain wrong!
2275                    {
2276                        *first_unparsed = expression_cstr;
2277                        *reason_to_stop = ValueObject::eRangeOperatorInvalid;
2278                        *final_result = ValueObject::eInvalid;
2279                        return 0;
2280                    }
2281                    else if (!options.m_allow_bitfields_syntax) // if this is a scalar, check that we can expand bitfields
2282                    {
2283                        *first_unparsed = expression_cstr;
2284                        *reason_to_stop = ValueObject::eRangeOperatorNotAllowed;
2285                        *final_result = ValueObject::eInvalid;
2286                        return 0;
2287                    }
2288                }
2289                if (*(expression_cstr+1) == ']') // if this is an unbounded range it only works for arrays
2290                {
2291                    if (!root_clang_type_info.Test(ClangASTContext::eTypeIsArray))
2292                    {
2293                        *first_unparsed = expression_cstr;
2294                        *reason_to_stop = ValueObject::eEmptyRangeNotAllowed;
2295                        *final_result = ValueObject::eInvalid;
2296                        return 0;
2297                    }
2298                    else // expand this into list
2299                    {
2300                        int max_index = root->GetNumChildren() - 1;
2301                        for (int index = 0; index < max_index; index++)
2302                        {
2303                            ValueObjectSP child =
2304                                root->GetChildAtIndex(index, true);
2305                            list->Append(child);
2306                        }
2307                        *first_unparsed = expression_cstr+2;
2308                        *reason_to_stop = ValueObject::eRangeOperatorExpanded;
2309                        *final_result = ValueObject::eValueObjectList;
2310                        return max_index; // tell me number of items I added to the VOList
2311                    }
2312                }
2313                const char *separator_position = ::strchr(expression_cstr+1,'-');
2314                const char *close_bracket_position = ::strchr(expression_cstr+1,']');
2315                if (!close_bracket_position) // if there is no ], this is a syntax error
2316                {
2317                    *first_unparsed = expression_cstr;
2318                    *reason_to_stop = ValueObject::eUnexpectedSymbol;
2319                    *final_result = ValueObject::eInvalid;
2320                    return 0;
2321                }
2322                if (!separator_position || separator_position > close_bracket_position) // if no separator, this is either [] or [N]
2323                {
2324                    char *end = NULL;
2325                    unsigned long index = ::strtoul (expression_cstr+1, &end, 0);
2326                    if (!end || end != close_bracket_position) // if something weird is in our way return an error
2327                    {
2328                        *first_unparsed = expression_cstr;
2329                        *reason_to_stop = ValueObject::eUnexpectedSymbol;
2330                        *final_result = ValueObject::eInvalid;
2331                        return 0;
2332                    }
2333                    if (end - expression_cstr == 1) // if this is [], only return a valid value for arrays
2334                    {
2335                        if (root_clang_type_info.Test(ClangASTContext::eTypeIsArray))
2336                        {
2337                            int max_index = root->GetNumChildren() - 1;
2338                            for (int index = 0; index < max_index; index++)
2339                            {
2340                                ValueObjectSP child =
2341                                root->GetChildAtIndex(index, true);
2342                                list->Append(child);
2343                            }
2344                            *first_unparsed = expression_cstr+2;
2345                            *reason_to_stop = ValueObject::eRangeOperatorExpanded;
2346                            *final_result = ValueObject::eValueObjectList;
2347                            return max_index; // tell me number of items I added to the VOList
2348                        }
2349                        else
2350                        {
2351                            *first_unparsed = expression_cstr;
2352                            *reason_to_stop = ValueObject::eEmptyRangeNotAllowed;
2353                            *final_result = ValueObject::eInvalid;
2354                            return 0;
2355                        }
2356                    }
2357                    // from here on we do have a valid index
2358                    if (root_clang_type_info.Test(ClangASTContext::eTypeIsArray))
2359                    {
2360                        root = root->GetChildAtIndex(index, true);
2361                        if (!root.get())
2362                        {
2363                            *first_unparsed = expression_cstr;
2364                            *reason_to_stop = ValueObject::eNoSuchChild;
2365                            *final_result = ValueObject::eInvalid;
2366                            return 0;
2367                        }
2368                        else
2369                        {
2370                            list->Append(root);
2371                            *first_unparsed = end+1; // skip ]
2372                            *reason_to_stop = ValueObject::eRangeOperatorExpanded;
2373                            *final_result = ValueObject::eValueObjectList;
2374                            return 1;
2375                        }
2376                    }
2377                    else if (root_clang_type_info.Test(ClangASTContext::eTypeIsPointer))
2378                    {
2379                        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
2380                            pointee_clang_type_info.Test(ClangASTContext::eTypeIsScalar))
2381                        {
2382                            Error error;
2383                            root = root->Dereference(error);
2384                            if (error.Fail() || !root.get())
2385                            {
2386                                *first_unparsed = expression_cstr;
2387                                *reason_to_stop = ValueObject::eDereferencingFailed;
2388                                *final_result = ValueObject::eInvalid;
2389                                return 0;
2390                            }
2391                            else
2392                            {
2393                                *what_next = eNothing;
2394                                continue;
2395                            }
2396                        }
2397                        else
2398                        {
2399                            root = root->GetSyntheticArrayMemberFromPointer(index, true);
2400                            if (!root.get())
2401                            {
2402                                *first_unparsed = expression_cstr;
2403                                *reason_to_stop = ValueObject::eNoSuchChild;
2404                                *final_result = ValueObject::eInvalid;
2405                                return 0;
2406                            }
2407                            else
2408                            {
2409                                list->Append(root);
2410                                *first_unparsed = end+1; // skip ]
2411                                *reason_to_stop = ValueObject::eRangeOperatorExpanded;
2412                                *final_result = ValueObject::eValueObjectList;
2413                                return 1;
2414                            }
2415                        }
2416                    }
2417                    else /*if (ClangASTContext::IsScalarType(root_clang_type))*/
2418                    {
2419                        root = root->GetSyntheticBitFieldChild(index, index, true);
2420                        if (!root.get())
2421                        {
2422                            *first_unparsed = expression_cstr;
2423                            *reason_to_stop = ValueObject::eNoSuchChild;
2424                            *final_result = ValueObject::eInvalid;
2425                            return 0;
2426                        }
2427                        else // we do not know how to expand members of bitfields, so we just return and let the caller do any further processing
2428                        {
2429                            list->Append(root);
2430                            *first_unparsed = end+1; // skip ]
2431                            *reason_to_stop = ValueObject::eRangeOperatorExpanded;
2432                            *final_result = ValueObject::eValueObjectList;
2433                            return 1;
2434                        }
2435                    }
2436                }
2437                else // we have a low and a high index
2438                {
2439                    char *end = NULL;
2440                    unsigned long index_lower = ::strtoul (expression_cstr+1, &end, 0);
2441                    if (!end || end != separator_position) // if something weird is in our way return an error
2442                    {
2443                        *first_unparsed = expression_cstr;
2444                        *reason_to_stop = ValueObject::eUnexpectedSymbol;
2445                        *final_result = ValueObject::eInvalid;
2446                        return 0;
2447                    }
2448                    unsigned long index_higher = ::strtoul (separator_position+1, &end, 0);
2449                    if (!end || end != close_bracket_position) // if something weird is in our way return an error
2450                    {
2451                        *first_unparsed = expression_cstr;
2452                        *reason_to_stop = ValueObject::eUnexpectedSymbol;
2453                        *final_result = ValueObject::eInvalid;
2454                        return 0;
2455                    }
2456                    if (index_lower > index_higher) // swap indices if required
2457                    {
2458                        unsigned long temp = index_lower;
2459                        index_lower = index_higher;
2460                        index_higher = temp;
2461                    }
2462                    if (root_clang_type_info.Test(ClangASTContext::eTypeIsScalar)) // expansion only works for scalars
2463                    {
2464                        root = root->GetSyntheticBitFieldChild(index_lower, index_higher, true);
2465                        if (!root.get())
2466                        {
2467                            *first_unparsed = expression_cstr;
2468                            *reason_to_stop = ValueObject::eNoSuchChild;
2469                            *final_result = ValueObject::eInvalid;
2470                            return 0;
2471                        }
2472                        else
2473                        {
2474                            list->Append(root);
2475                            *first_unparsed = end+1; // skip ]
2476                            *reason_to_stop = ValueObject::eRangeOperatorExpanded;
2477                            *final_result = ValueObject::eValueObjectList;
2478                            return 1;
2479                        }
2480                    }
2481                    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
2482                             *what_next == ValueObject::eDereference &&
2483                             pointee_clang_type_info.Test(ClangASTContext::eTypeIsScalar))
2484                    {
2485                        Error error;
2486                        root = root->Dereference(error);
2487                        if (error.Fail() || !root.get())
2488                        {
2489                            *first_unparsed = expression_cstr;
2490                            *reason_to_stop = ValueObject::eDereferencingFailed;
2491                            *final_result = ValueObject::eInvalid;
2492                            return 0;
2493                        }
2494                        else
2495                        {
2496                            *what_next = ValueObject::eNothing;
2497                            continue;
2498                        }
2499                    }
2500                    else
2501                    {
2502                        for (int index = index_lower;
2503                             index <= index_higher; index++)
2504                        {
2505                            ValueObjectSP child =
2506                                root->GetChildAtIndex(index, true);
2507                            list->Append(child);
2508                        }
2509                        *first_unparsed = end+1;
2510                        *reason_to_stop = ValueObject::eRangeOperatorExpanded;
2511                        *final_result = ValueObject::eValueObjectList;
2512                        return index_higher-index_lower+1; // tell me number of items I added to the VOList
2513                    }
2514                }
2515                break;
2516            }
2517            default: // some non-[ separator, or something entirely wrong, is in the way
2518            {
2519                *first_unparsed = expression_cstr;
2520                *reason_to_stop = ValueObject::eUnexpectedSymbol;
2521                *final_result = ValueObject::eInvalid;
2522                return 0;
2523                break;
2524            }
2525        }
2526    }
2527}
2528
2529void
2530ValueObject::DumpValueObject
2531(
2532    Stream &s,
2533    ValueObject *valobj,
2534    const char *root_valobj_name,
2535    uint32_t ptr_depth,
2536    uint32_t curr_depth,
2537    uint32_t max_depth,
2538    bool show_types,
2539    bool show_location,
2540    bool use_objc,
2541    lldb::DynamicValueType use_dynamic,
2542    bool scope_already_checked,
2543    bool flat_output
2544)
2545{
2546    if (valobj)
2547    {
2548        bool update_success = valobj->UpdateValueIfNeeded ();
2549
2550        if (update_success && use_dynamic != lldb::eNoDynamicValues)
2551        {
2552            ValueObject *dynamic_value = valobj->GetDynamicValue(use_dynamic).get();
2553            if (dynamic_value)
2554                valobj = dynamic_value;
2555        }
2556
2557        clang_type_t clang_type = valobj->GetClangType();
2558
2559        const Flags type_flags (ClangASTContext::GetTypeInfo (clang_type, NULL, NULL));
2560        const char *err_cstr = NULL;
2561        const bool has_children = type_flags.Test (ClangASTContext::eTypeHasChildren);
2562        const bool has_value = type_flags.Test (ClangASTContext::eTypeHasValue);
2563
2564        const bool print_valobj = flat_output == false || has_value;
2565
2566        if (print_valobj)
2567        {
2568            if (show_location)
2569            {
2570                s.Printf("%s: ", valobj->GetLocationAsCString());
2571            }
2572
2573            s.Indent();
2574
2575            // Always show the type for the top level items.
2576            if (show_types || (curr_depth == 0 && !flat_output))
2577                s.Printf("(%s) ", valobj->GetTypeName().AsCString("<invalid type>"));
2578
2579
2580            if (flat_output)
2581            {
2582                // If we are showing types, also qualify the C++ base classes
2583                const bool qualify_cxx_base_classes = show_types;
2584                valobj->GetExpressionPath(s, qualify_cxx_base_classes);
2585                s.PutCString(" =");
2586            }
2587            else
2588            {
2589                const char *name_cstr = root_valobj_name ? root_valobj_name : valobj->GetName().AsCString("");
2590                s.Printf ("%s =", name_cstr);
2591            }
2592
2593            if (!scope_already_checked && !valobj->IsInScope())
2594            {
2595                err_cstr = "out of scope";
2596            }
2597        }
2598
2599        const char *val_cstr = NULL;
2600        const char *sum_cstr = NULL;
2601        SummaryFormat* entry = valobj->GetSummaryFormat().get();
2602
2603        if (err_cstr == NULL)
2604        {
2605            val_cstr = valobj->GetValueAsCString();
2606            err_cstr = valobj->GetError().AsCString();
2607        }
2608
2609        if (err_cstr)
2610        {
2611            s.Printf (" <%s>\n", err_cstr);
2612        }
2613        else
2614        {
2615            const bool is_ref = type_flags.Test (ClangASTContext::eTypeIsReference);
2616            if (print_valobj)
2617            {
2618
2619                sum_cstr = valobj->GetSummaryAsCString();
2620
2621                // We must calculate this value in realtime because entry might alter this variable's value
2622                // (e.g. by saying ${var%fmt}) and render precached values useless
2623                if (val_cstr && (!entry || entry->DoesPrintValue() || !sum_cstr))
2624                    s.Printf(" %s", valobj->GetValueAsCString());
2625
2626                if(sum_cstr)
2627                {
2628                    // for some reason, using %@ (ObjC description) in a summary string, makes
2629                    // us believe we need to reset ourselves, thus invalidating the content of
2630                    // sum_cstr. Thus, IF we had a valid sum_cstr before, but it is now empty
2631                    // let us recalculate it!
2632                    if (sum_cstr[0] == '\0')
2633                        s.Printf(" %s", valobj->GetSummaryAsCString());
2634                    else
2635                        s.Printf(" %s", sum_cstr);
2636                }
2637
2638                if (use_objc)
2639                {
2640                    const char *object_desc = valobj->GetObjectDescription();
2641                    if (object_desc)
2642                        s.Printf(" %s\n", object_desc);
2643                    else
2644                        s.Printf (" [no Objective-C description available]\n");
2645                    return;
2646                }
2647            }
2648
2649            if (curr_depth < max_depth)
2650            {
2651                // We will show children for all concrete types. We won't show
2652                // pointer contents unless a pointer depth has been specified.
2653                // We won't reference contents unless the reference is the
2654                // root object (depth of zero).
2655                bool print_children = true;
2656
2657                // Use a new temporary pointer depth in case we override the
2658                // current pointer depth below...
2659                uint32_t curr_ptr_depth = ptr_depth;
2660
2661                const bool is_ptr = type_flags.Test (ClangASTContext::eTypeIsPointer);
2662                if (is_ptr || is_ref)
2663                {
2664                    // We have a pointer or reference whose value is an address.
2665                    // Make sure that address is not NULL
2666                    AddressType ptr_address_type;
2667                    if (valobj->GetPointerValue (ptr_address_type, true) == 0)
2668                        print_children = false;
2669
2670                    else if (is_ref && curr_depth == 0)
2671                    {
2672                        // If this is the root object (depth is zero) that we are showing
2673                        // and it is a reference, and no pointer depth has been supplied
2674                        // print out what it references. Don't do this at deeper depths
2675                        // otherwise we can end up with infinite recursion...
2676                        curr_ptr_depth = 1;
2677                    }
2678
2679                    if (curr_ptr_depth == 0)
2680                        print_children = false;
2681                }
2682
2683                if (print_children && (!entry || entry->DoesPrintChildren() || !sum_cstr))
2684                {
2685                    const uint32_t num_children = valobj->GetNumChildren();
2686                    if (num_children)
2687                    {
2688                        if (flat_output)
2689                        {
2690                            if (print_valobj)
2691                                s.EOL();
2692                        }
2693                        else
2694                        {
2695                            if (print_valobj)
2696                                s.PutCString(is_ref ? ": {\n" : " {\n");
2697                            s.IndentMore();
2698                        }
2699
2700                        for (uint32_t idx=0; idx<num_children; ++idx)
2701                        {
2702                            ValueObjectSP child_sp(valobj->GetChildAtIndex(idx, true));
2703                            if (child_sp.get())
2704                            {
2705                                DumpValueObject (s,
2706                                                 child_sp.get(),
2707                                                 NULL,
2708                                                 (is_ptr || is_ref) ? curr_ptr_depth - 1 : curr_ptr_depth,
2709                                                 curr_depth + 1,
2710                                                 max_depth,
2711                                                 show_types,
2712                                                 show_location,
2713                                                 false,
2714                                                 use_dynamic,
2715                                                 true,
2716                                                 flat_output);
2717                            }
2718                        }
2719
2720                        if (!flat_output)
2721                        {
2722                            s.IndentLess();
2723                            s.Indent("}\n");
2724                        }
2725                    }
2726                    else if (has_children)
2727                    {
2728                        // Aggregate, no children...
2729                        if (print_valobj)
2730                            s.PutCString(" {}\n");
2731                    }
2732                    else
2733                    {
2734                        if (print_valobj)
2735                            s.EOL();
2736                    }
2737
2738                }
2739                else
2740                {
2741                    s.EOL();
2742                }
2743            }
2744            else
2745            {
2746                if (has_children && print_valobj)
2747                {
2748                    s.PutCString("{...}\n");
2749                }
2750            }
2751        }
2752    }
2753}
2754
2755
2756ValueObjectSP
2757ValueObject::CreateConstantValue (const ConstString &name)
2758{
2759    ValueObjectSP valobj_sp;
2760
2761    if (UpdateValueIfNeeded() && m_error.Success())
2762    {
2763        ExecutionContextScope *exe_scope = GetExecutionContextScope();
2764        if (exe_scope)
2765        {
2766            ExecutionContext exe_ctx;
2767            exe_scope->CalculateExecutionContext(exe_ctx);
2768
2769            clang::ASTContext *ast = GetClangAST ();
2770
2771            DataExtractor data;
2772            data.SetByteOrder (m_data.GetByteOrder());
2773            data.SetAddressByteSize(m_data.GetAddressByteSize());
2774
2775            m_error = m_value.GetValueAsData (&exe_ctx, ast, data, 0, GetModule());
2776
2777            valobj_sp = ValueObjectConstResult::Create (exe_scope,
2778                                                        ast,
2779                                                        GetClangType(),
2780                                                        name,
2781                                                        data);
2782        }
2783    }
2784
2785    if (!valobj_sp)
2786    {
2787        valobj_sp = ValueObjectConstResult::Create (NULL, m_error);
2788    }
2789    return valobj_sp;
2790}
2791
2792lldb::ValueObjectSP
2793ValueObject::Dereference (Error &error)
2794{
2795    if (m_deref_valobj)
2796        return m_deref_valobj->GetSP();
2797
2798    const bool is_pointer_type = IsPointerType();
2799    if (is_pointer_type)
2800    {
2801        bool omit_empty_base_classes = true;
2802        bool ignore_array_bounds = false;
2803
2804        std::string child_name_str;
2805        uint32_t child_byte_size = 0;
2806        int32_t child_byte_offset = 0;
2807        uint32_t child_bitfield_bit_size = 0;
2808        uint32_t child_bitfield_bit_offset = 0;
2809        bool child_is_base_class = false;
2810        bool child_is_deref_of_parent = false;
2811        const bool transparent_pointers = false;
2812        clang::ASTContext *clang_ast = GetClangAST();
2813        clang_type_t clang_type = GetClangType();
2814        clang_type_t child_clang_type;
2815
2816        ExecutionContext exe_ctx;
2817        GetExecutionContextScope()->CalculateExecutionContext (exe_ctx);
2818
2819        child_clang_type = ClangASTContext::GetChildClangTypeAtIndex (&exe_ctx,
2820                                                                      clang_ast,
2821                                                                      GetName().GetCString(),
2822                                                                      clang_type,
2823                                                                      0,
2824                                                                      transparent_pointers,
2825                                                                      omit_empty_base_classes,
2826                                                                      ignore_array_bounds,
2827                                                                      child_name_str,
2828                                                                      child_byte_size,
2829                                                                      child_byte_offset,
2830                                                                      child_bitfield_bit_size,
2831                                                                      child_bitfield_bit_offset,
2832                                                                      child_is_base_class,
2833                                                                      child_is_deref_of_parent);
2834        if (child_clang_type && child_byte_size)
2835        {
2836            ConstString child_name;
2837            if (!child_name_str.empty())
2838                child_name.SetCString (child_name_str.c_str());
2839
2840            m_deref_valobj = new ValueObjectChild (*this,
2841                                                   clang_ast,
2842                                                   child_clang_type,
2843                                                   child_name,
2844                                                   child_byte_size,
2845                                                   child_byte_offset,
2846                                                   child_bitfield_bit_size,
2847                                                   child_bitfield_bit_offset,
2848                                                   child_is_base_class,
2849                                                   child_is_deref_of_parent);
2850        }
2851    }
2852
2853    if (m_deref_valobj)
2854    {
2855        error.Clear();
2856        return m_deref_valobj->GetSP();
2857    }
2858    else
2859    {
2860        StreamString strm;
2861        GetExpressionPath(strm, true);
2862
2863        if (is_pointer_type)
2864            error.SetErrorStringWithFormat("dereference failed: (%s) %s", GetTypeName().AsCString("<invalid type>"), strm.GetString().c_str());
2865        else
2866            error.SetErrorStringWithFormat("not a pointer type: (%s) %s", GetTypeName().AsCString("<invalid type>"), strm.GetString().c_str());
2867        return ValueObjectSP();
2868    }
2869}
2870
2871lldb::ValueObjectSP
2872ValueObject::AddressOf (Error &error)
2873{
2874    if (m_addr_of_valobj_sp)
2875        return m_addr_of_valobj_sp;
2876
2877    AddressType address_type = eAddressTypeInvalid;
2878    const bool scalar_is_load_address = false;
2879    lldb::addr_t addr = GetAddressOf (address_type, scalar_is_load_address);
2880    error.Clear();
2881    if (addr != LLDB_INVALID_ADDRESS)
2882    {
2883        switch (address_type)
2884        {
2885        default:
2886        case eAddressTypeInvalid:
2887            {
2888                StreamString expr_path_strm;
2889                GetExpressionPath(expr_path_strm, true);
2890                error.SetErrorStringWithFormat("'%s' is not in memory", expr_path_strm.GetString().c_str());
2891            }
2892            break;
2893
2894        case eAddressTypeFile:
2895        case eAddressTypeLoad:
2896        case eAddressTypeHost:
2897            {
2898                clang::ASTContext *ast = GetClangAST();
2899                clang_type_t clang_type = GetClangType();
2900                if (ast && clang_type)
2901                {
2902                    std::string name (1, '&');
2903                    name.append (m_name.AsCString(""));
2904                    m_addr_of_valobj_sp = ValueObjectConstResult::Create (GetExecutionContextScope(),
2905                                                                          ast,
2906                                                                          ClangASTContext::CreatePointerType (ast, clang_type),
2907                                                                          ConstString (name.c_str()),
2908                                                                          addr,
2909                                                                          eAddressTypeInvalid,
2910                                                                          m_data.GetAddressByteSize());
2911                }
2912            }
2913            break;
2914        }
2915    }
2916    return m_addr_of_valobj_sp;
2917}
2918
2919
2920lldb::ValueObjectSP
2921ValueObject::CastPointerType (const char *name, ClangASTType &clang_ast_type)
2922{
2923    lldb::ValueObjectSP valobj_sp;
2924    AddressType address_type;
2925    const bool scalar_is_load_address = true;
2926    lldb::addr_t ptr_value = GetPointerValue (address_type, scalar_is_load_address);
2927
2928    if (ptr_value != LLDB_INVALID_ADDRESS)
2929    {
2930        Address ptr_addr (NULL, ptr_value);
2931
2932        valobj_sp = ValueObjectMemory::Create (GetExecutionContextScope(),
2933                                               name,
2934                                               ptr_addr,
2935                                               clang_ast_type);
2936    }
2937    return valobj_sp;
2938}
2939
2940lldb::ValueObjectSP
2941ValueObject::CastPointerType (const char *name, TypeSP &type_sp)
2942{
2943    lldb::ValueObjectSP valobj_sp;
2944    AddressType address_type;
2945    const bool scalar_is_load_address = true;
2946    lldb::addr_t ptr_value = GetPointerValue (address_type, scalar_is_load_address);
2947
2948    if (ptr_value != LLDB_INVALID_ADDRESS)
2949    {
2950        Address ptr_addr (NULL, ptr_value);
2951
2952        valobj_sp = ValueObjectMemory::Create (GetExecutionContextScope(),
2953                                               name,
2954                                               ptr_addr,
2955                                               type_sp);
2956    }
2957    return valobj_sp;
2958}
2959
2960
2961ValueObject::EvaluationPoint::EvaluationPoint () :
2962    m_thread_id (LLDB_INVALID_UID),
2963    m_stop_id (0)
2964{
2965}
2966
2967ValueObject::EvaluationPoint::EvaluationPoint (ExecutionContextScope *exe_scope, bool use_selected):
2968    m_needs_update (true),
2969    m_first_update (true),
2970    m_thread_id (LLDB_INVALID_THREAD_ID),
2971    m_stop_id (0)
2972
2973{
2974    ExecutionContext exe_ctx;
2975    ExecutionContextScope *computed_exe_scope = exe_scope;  // If use_selected is true, we may find a better scope,
2976                                                            // and if so we want to cache that not the original.
2977    if (exe_scope)
2978        exe_scope->CalculateExecutionContext(exe_ctx);
2979    if (exe_ctx.target != NULL)
2980    {
2981        m_target_sp = exe_ctx.target->GetSP();
2982
2983        if (exe_ctx.process == NULL)
2984            m_process_sp = exe_ctx.target->GetProcessSP();
2985        else
2986            m_process_sp = exe_ctx.process->GetSP();
2987
2988        if (m_process_sp != NULL)
2989        {
2990            m_stop_id = m_process_sp->GetStopID();
2991            Thread *thread = NULL;
2992
2993            if (exe_ctx.thread == NULL)
2994            {
2995                if (use_selected)
2996                {
2997                    thread = m_process_sp->GetThreadList().GetSelectedThread().get();
2998                    if (thread)
2999                        computed_exe_scope = thread;
3000                }
3001            }
3002            else
3003                thread = exe_ctx.thread;
3004
3005            if (thread != NULL)
3006            {
3007                m_thread_id = thread->GetIndexID();
3008                if (exe_ctx.frame == NULL)
3009                {
3010                    if (use_selected)
3011                    {
3012                        StackFrame *frame = exe_ctx.thread->GetSelectedFrame().get();
3013                        if (frame)
3014                        {
3015                            m_stack_id = frame->GetStackID();
3016                            computed_exe_scope = frame;
3017                        }
3018                    }
3019                }
3020                else
3021                    m_stack_id = exe_ctx.frame->GetStackID();
3022            }
3023        }
3024    }
3025    m_exe_scope = computed_exe_scope;
3026}
3027
3028ValueObject::EvaluationPoint::EvaluationPoint (const ValueObject::EvaluationPoint &rhs) :
3029    m_exe_scope (rhs.m_exe_scope),
3030    m_needs_update(true),
3031    m_first_update(true),
3032    m_target_sp (rhs.m_target_sp),
3033    m_process_sp (rhs.m_process_sp),
3034    m_thread_id (rhs.m_thread_id),
3035    m_stack_id (rhs.m_stack_id),
3036    m_stop_id (0)
3037{
3038}
3039
3040ValueObject::EvaluationPoint::~EvaluationPoint ()
3041{
3042}
3043
3044ExecutionContextScope *
3045ValueObject::EvaluationPoint::GetExecutionContextScope ()
3046{
3047    // We have to update before giving out the scope, or we could be handing out stale pointers.
3048    SyncWithProcessState();
3049
3050    return m_exe_scope;
3051}
3052
3053// This function checks the EvaluationPoint against the current process state.  If the current
3054// state matches the evaluation point, or the evaluation point is already invalid, then we return
3055// false, meaning "no change".  If the current state is different, we update our state, and return
3056// true meaning "yes, change".  If we did see a change, we also set m_needs_update to true, so
3057// future calls to NeedsUpdate will return true.
3058
3059bool
3060ValueObject::EvaluationPoint::SyncWithProcessState()
3061{
3062    // If we're already invalid, we don't need to do anything, and nothing has changed:
3063    if (m_stop_id == LLDB_INVALID_UID)
3064    {
3065        // Can't update with an invalid state.
3066        m_needs_update = false;
3067        return false;
3068    }
3069
3070    // If we don't have a process nothing can change.
3071    if (!m_process_sp)
3072        return false;
3073
3074    // If our stop id is the current stop ID, nothing has changed:
3075    uint32_t cur_stop_id = m_process_sp->GetStopID();
3076    if (m_stop_id == cur_stop_id)
3077        return false;
3078
3079    // If the current stop id is 0, either we haven't run yet, or the process state has been cleared.
3080    // In either case, we aren't going to be able to sync with the process state.
3081    if (cur_stop_id == 0)
3082        return false;
3083
3084    m_stop_id = cur_stop_id;
3085    m_needs_update = true;
3086    m_exe_scope = m_process_sp.get();
3087
3088    // Something has changed, so we will return true.  Now make sure the thread & frame still exist, and if either
3089    // doesn't, mark ourselves as invalid.
3090
3091    if (m_thread_id != LLDB_INVALID_THREAD_ID)
3092    {
3093        Thread *our_thread = m_process_sp->GetThreadList().FindThreadByIndexID (m_thread_id).get();
3094        if (our_thread == NULL)
3095        {
3096            SetInvalid();
3097        }
3098        else
3099        {
3100            m_exe_scope = our_thread;
3101
3102            if (m_stack_id.IsValid())
3103            {
3104                StackFrame *our_frame = our_thread->GetFrameWithStackID (m_stack_id).get();
3105                if (our_frame == NULL)
3106                    SetInvalid();
3107                else
3108                    m_exe_scope = our_frame;
3109            }
3110        }
3111    }
3112    return true;
3113}
3114
3115void
3116ValueObject::EvaluationPoint::SetUpdated ()
3117{
3118    m_first_update = false;
3119    m_needs_update = false;
3120    if (m_process_sp)
3121        m_stop_id = m_process_sp->GetStopID();
3122}
3123
3124
3125bool
3126ValueObject::EvaluationPoint::SetContext (ExecutionContextScope *exe_scope)
3127{
3128    if (!IsValid())
3129        return false;
3130
3131    bool needs_update = false;
3132    m_exe_scope = NULL;
3133
3134    // The target has to be non-null, and the
3135    Target *target = exe_scope->CalculateTarget();
3136    if (target != NULL)
3137    {
3138        Target *old_target = m_target_sp.get();
3139        assert (target == old_target);
3140        Process *process = exe_scope->CalculateProcess();
3141        if (process != NULL)
3142        {
3143            // FOR NOW - assume you can't update variable objects across process boundaries.
3144            Process *old_process = m_process_sp.get();
3145            assert (process == old_process);
3146
3147            lldb::user_id_t stop_id = process->GetStopID();
3148            if (stop_id != m_stop_id)
3149            {
3150                needs_update = true;
3151                m_stop_id = stop_id;
3152            }
3153            // See if we're switching the thread or stack context.  If no thread is given, this is
3154            // being evaluated in a global context.
3155            Thread *thread = exe_scope->CalculateThread();
3156            if (thread != NULL)
3157            {
3158                lldb::user_id_t new_thread_index = thread->GetIndexID();
3159                if (new_thread_index != m_thread_id)
3160                {
3161                    needs_update = true;
3162                    m_thread_id = new_thread_index;
3163                    m_stack_id.Clear();
3164                }
3165
3166                StackFrame *new_frame = exe_scope->CalculateStackFrame();
3167                if (new_frame != NULL)
3168                {
3169                    if (new_frame->GetStackID() != m_stack_id)
3170                    {
3171                        needs_update = true;
3172                        m_stack_id = new_frame->GetStackID();
3173                    }
3174                }
3175                else
3176                {
3177                    m_stack_id.Clear();
3178                    needs_update = true;
3179                }
3180            }
3181            else
3182            {
3183                // If this had been given a thread, and now there is none, we should update.
3184                // Otherwise we don't have to do anything.
3185                if (m_thread_id != LLDB_INVALID_UID)
3186                {
3187                    m_thread_id = LLDB_INVALID_UID;
3188                    m_stack_id.Clear();
3189                    needs_update = true;
3190                }
3191            }
3192        }
3193        else
3194        {
3195            // If there is no process, then we don't need to update anything.
3196            // But if we're switching from having a process to not, we should try to update.
3197            if (m_process_sp.get() != NULL)
3198            {
3199                needs_update = true;
3200                m_process_sp.reset();
3201                m_thread_id = LLDB_INVALID_UID;
3202                m_stack_id.Clear();
3203            }
3204        }
3205    }
3206    else
3207    {
3208        // If there's no target, nothing can change so we don't need to update anything.
3209        // But if we're switching from having a target to not, we should try to update.
3210        if (m_target_sp.get() != NULL)
3211        {
3212            needs_update = true;
3213            m_target_sp.reset();
3214            m_process_sp.reset();
3215            m_thread_id = LLDB_INVALID_UID;
3216            m_stack_id.Clear();
3217        }
3218    }
3219    if (!m_needs_update)
3220        m_needs_update = needs_update;
3221
3222    return needs_update;
3223}
3224