ValueObject.cpp revision 4ae519666628cca07c194bf677163009cc2e5a8b
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// C++ Includes
14// Other libraries and framework includes
15#include "llvm/Support/raw_ostream.h"
16
17// Project includes
18#include "lldb/Core/DataBufferHeap.h"
19#include "lldb/Core/StreamString.h"
20#include "lldb/Core/ValueObjectChild.h"
21#include "lldb/Core/ValueObjectList.h"
22
23#include "lldb/Symbol/ClangASTType.h"
24#include "lldb/Symbol/ClangASTContext.h"
25#include "lldb/Symbol/Type.h"
26
27#include "lldb/Target/ExecutionContext.h"
28#include "lldb/Target/Process.h"
29#include "lldb/Target/RegisterContext.h"
30#include "lldb/Target/Thread.h"
31#include <stdlib.h>
32
33using namespace lldb;
34using namespace lldb_private;
35
36static lldb::user_id_t g_value_obj_uid = 0;
37
38//----------------------------------------------------------------------
39// ValueObject constructor
40//----------------------------------------------------------------------
41ValueObject::ValueObject () :
42    UserID (++g_value_obj_uid), // Unique identifier for every value object
43    m_update_id (0),    // Value object lists always start at 1, value objects start at zero
44    m_name (),
45    m_data (),
46    m_value (),
47    m_error (),
48    m_value_str (),
49    m_old_value_str (),
50    m_location_str (),
51    m_summary_str (),
52    m_object_desc_str (),
53    m_children (),
54    m_synthetic_children (),
55    m_value_is_valid (false),
56    m_value_did_change (false),
57    m_children_count_valid (false),
58    m_old_value_valid (false)
59{
60}
61
62//----------------------------------------------------------------------
63// Destructor
64//----------------------------------------------------------------------
65ValueObject::~ValueObject ()
66{
67}
68
69user_id_t
70ValueObject::GetUpdateID() const
71{
72    return m_update_id;
73}
74
75bool
76ValueObject::UpdateValueIfNeeded (ExecutionContextScope *exe_scope)
77{
78    if (exe_scope)
79    {
80        Process *process = exe_scope->CalculateProcess();
81        if (process)
82        {
83            const user_id_t stop_id = process->GetStopID();
84            if (m_update_id != stop_id)
85            {
86                bool first_update = m_update_id == 0;
87                // Save the old value using swap to avoid a string copy which
88                // also will clear our m_value_str
89                if (m_value_str.empty())
90                {
91                    m_old_value_valid = false;
92                }
93                else
94                {
95                    m_old_value_valid = true;
96                    m_old_value_str.swap (m_value_str);
97                    m_value_str.clear();
98                }
99                m_location_str.clear();
100                m_summary_str.clear();
101                m_object_desc_str.clear();
102
103                const bool value_was_valid = GetValueIsValid();
104                SetValueDidChange (false);
105
106                m_error.Clear();
107
108                // Call the pure virtual function to update the value
109                UpdateValue (exe_scope);
110
111                // Update the fact that we tried to update the value for this
112                // value object wether or not we succeed
113                m_update_id = stop_id;
114                bool success = m_error.Success();
115                SetValueIsValid (success);
116
117                if (first_update)
118                    SetValueDidChange (false);
119                else if (!m_value_did_change && success == false)
120                {
121                    // The value wasn't gotten successfully, so we mark this
122                    // as changed if the value used to be valid and now isn't
123                    SetValueDidChange (value_was_valid);
124                }
125            }
126        }
127    }
128    return m_error.Success();
129}
130
131const DataExtractor &
132ValueObject::GetDataExtractor () const
133{
134    return m_data;
135}
136
137DataExtractor &
138ValueObject::GetDataExtractor ()
139{
140    return m_data;
141}
142
143const Error &
144ValueObject::GetError() const
145{
146    return m_error;
147}
148
149const ConstString &
150ValueObject::GetName() const
151{
152    return m_name;
153}
154
155const char *
156ValueObject::GetLocationAsCString (ExecutionContextScope *exe_scope)
157{
158    if (UpdateValueIfNeeded(exe_scope))
159    {
160        if (m_location_str.empty())
161        {
162            StreamString sstr;
163
164            switch (m_value.GetValueType())
165            {
166            default:
167                break;
168
169            case Value::eValueTypeScalar:
170                if (m_value.GetContextType() == Value::eContextTypeDCRegisterInfo)
171                {
172                    RegisterInfo *reg_info = m_value.GetRegisterInfo();
173                    if (reg_info)
174                    {
175                        if (reg_info->name)
176                            m_location_str = reg_info->name;
177                        else if (reg_info->alt_name)
178                            m_location_str = reg_info->alt_name;
179                        break;
180                    }
181                }
182                m_location_str = "scalar";
183                break;
184
185            case Value::eValueTypeLoadAddress:
186            case Value::eValueTypeFileAddress:
187            case Value::eValueTypeHostAddress:
188                {
189                    uint32_t addr_nibble_size = m_data.GetAddressByteSize() * 2;
190                    sstr.Printf("0x%*.*llx", addr_nibble_size, addr_nibble_size, m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS));
191                    m_location_str.swap(sstr.GetString());
192                }
193                break;
194            }
195        }
196    }
197    return m_location_str.c_str();
198}
199
200Value &
201ValueObject::GetValue()
202{
203    return m_value;
204}
205
206const Value &
207ValueObject::GetValue() const
208{
209    return m_value;
210}
211
212bool
213ValueObject::GetValueIsValid () const
214{
215    return m_value_is_valid;
216}
217
218
219void
220ValueObject::SetValueIsValid (bool b)
221{
222    m_value_is_valid = b;
223}
224
225bool
226ValueObject::GetValueDidChange (ExecutionContextScope *exe_scope)
227{
228    GetValueAsCString (exe_scope);
229    return m_value_did_change;
230}
231
232void
233ValueObject::SetValueDidChange (bool value_changed)
234{
235    m_value_did_change = value_changed;
236}
237
238ValueObjectSP
239ValueObject::GetChildAtIndex (uint32_t idx, bool can_create)
240{
241    ValueObjectSP child_sp;
242    if (idx < GetNumChildren())
243    {
244        // Check if we have already made the child value object?
245        if (can_create && m_children[idx].get() == NULL)
246        {
247            // No we haven't created the child at this index, so lets have our
248            // subclass do it and cache the result for quick future access.
249            m_children[idx] = CreateChildAtIndex (idx, false, 0);
250        }
251
252        child_sp = m_children[idx];
253    }
254    return child_sp;
255}
256
257uint32_t
258ValueObject::GetIndexOfChildWithName (const ConstString &name)
259{
260    bool omit_empty_base_classes = true;
261    return ClangASTContext::GetIndexOfChildWithName (GetClangAST(),
262                                                     GetOpaqueClangQualType(),
263                                                     name.AsCString(),
264                                                     omit_empty_base_classes);
265}
266
267ValueObjectSP
268ValueObject::GetChildMemberWithName (const ConstString &name, bool can_create)
269{
270    // when getting a child by name, it could be burried inside some base
271    // classes (which really aren't part of the expression path), so we
272    // need a vector of indexes that can get us down to the correct child
273    std::vector<uint32_t> child_indexes;
274    clang::ASTContext *clang_ast = GetClangAST();
275    void *clang_type = GetOpaqueClangQualType();
276    bool omit_empty_base_classes = true;
277    const size_t num_child_indexes =  ClangASTContext::GetIndexOfChildMemberWithName (clang_ast,
278                                                                                      clang_type,
279                                                                                      name.AsCString(),
280                                                                                      omit_empty_base_classes,
281                                                                                      child_indexes);
282    ValueObjectSP child_sp;
283    if (num_child_indexes > 0)
284    {
285        std::vector<uint32_t>::const_iterator pos = child_indexes.begin ();
286        std::vector<uint32_t>::const_iterator end = child_indexes.end ();
287
288        child_sp = GetChildAtIndex(*pos, can_create);
289        for (++pos; pos != end; ++pos)
290        {
291            if (child_sp)
292            {
293                ValueObjectSP new_child_sp(child_sp->GetChildAtIndex (*pos, can_create));
294                child_sp = new_child_sp;
295            }
296            else
297            {
298                child_sp.reset();
299            }
300
301        }
302    }
303    return child_sp;
304}
305
306
307uint32_t
308ValueObject::GetNumChildren ()
309{
310    if (!m_children_count_valid)
311    {
312        SetNumChildren (CalculateNumChildren());
313    }
314    return m_children.size();
315}
316void
317ValueObject::SetNumChildren (uint32_t num_children)
318{
319    m_children_count_valid = true;
320    m_children.resize(num_children);
321}
322
323void
324ValueObject::SetName (const char *name)
325{
326    m_name.SetCString(name);
327}
328
329void
330ValueObject::SetName (const ConstString &name)
331{
332    m_name = name;
333}
334
335ValueObjectSP
336ValueObject::CreateChildAtIndex (uint32_t idx, bool synthetic_array_member, int32_t synthetic_index)
337{
338    ValueObjectSP valobj_sp;
339    bool omit_empty_base_classes = true;
340
341    std::string child_name_str;
342    uint32_t child_byte_size = 0;
343    int32_t child_byte_offset = 0;
344    uint32_t child_bitfield_bit_size = 0;
345    uint32_t child_bitfield_bit_offset = 0;
346    const bool transparent_pointers = synthetic_array_member == false;
347    clang::ASTContext *clang_ast = GetClangAST();
348    void *clang_type = GetOpaqueClangQualType();
349    void *child_clang_type;
350    child_clang_type = ClangASTContext::GetChildClangTypeAtIndex (clang_ast,
351                                                                  GetName().AsCString(),
352                                                                  clang_type,
353                                                                  idx,
354                                                                  transparent_pointers,
355                                                                  omit_empty_base_classes,
356                                                                  child_name_str,
357                                                                  child_byte_size,
358                                                                  child_byte_offset,
359                                                                  child_bitfield_bit_size,
360                                                                  child_bitfield_bit_offset);
361    if (child_clang_type)
362    {
363        if (synthetic_index)
364            child_byte_offset += child_byte_size * synthetic_index;
365
366        ConstString child_name;
367        if (!child_name_str.empty())
368            child_name.SetCString (child_name_str.c_str());
369
370        valobj_sp.reset (new ValueObjectChild (this,
371                                               clang_ast,
372                                               child_clang_type,
373                                               child_name,
374                                               child_byte_size,
375                                               child_byte_offset,
376                                               child_bitfield_bit_size,
377                                               child_bitfield_bit_offset));
378    }
379    return valobj_sp;
380}
381
382const char *
383ValueObject::GetSummaryAsCString (ExecutionContextScope *exe_scope)
384{
385    if (UpdateValueIfNeeded (exe_scope))
386    {
387        if (m_summary_str.empty())
388        {
389            void *clang_type = GetOpaqueClangQualType();
390
391            // See if this is a pointer to a C string?
392            uint32_t fixed_length = 0;
393            if (clang_type && ClangASTContext::IsCStringType (clang_type, fixed_length))
394            {
395                Process *process = exe_scope->CalculateProcess();
396                if (process != NULL)
397                {
398                    StreamString sstr;
399                    lldb::addr_t cstr_address = LLDB_INVALID_ADDRESS;
400                    lldb::AddressType cstr_address_type = eAddressTypeInvalid;
401                    switch (GetValue().GetValueType())
402                    {
403                    case Value::eValueTypeScalar:
404                        cstr_address = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
405                        cstr_address_type = eAddressTypeLoad;
406                        break;
407
408                    case Value::eValueTypeLoadAddress:
409                    case Value::eValueTypeFileAddress:
410                    case Value::eValueTypeHostAddress:
411                        {
412                            uint32_t data_offset = 0;
413                            cstr_address = m_data.GetPointer(&data_offset);
414                            cstr_address_type = m_value.GetValueAddressType();
415                            if (cstr_address_type == eAddressTypeInvalid)
416                                cstr_address_type = eAddressTypeLoad;
417                        }
418                        break;
419                    }
420
421                    if (cstr_address != LLDB_INVALID_ADDRESS)
422                    {
423                        DataExtractor data;
424                        size_t bytes_read = 0;
425                        std::vector<char> data_buffer;
426                        std::vector<char> cstr_buffer;
427                        size_t cstr_length;
428                        Error error;
429                        if (fixed_length > 0)
430                        {
431                            data_buffer.resize(fixed_length);
432                            // Resize the formatted buffer in case every character
433                            // uses the "\xXX" format and one extra byte for a NULL
434                            cstr_buffer.resize(data_buffer.size() * 4 + 1);
435                            data.SetData (&data_buffer.front(), data_buffer.size(), eByteOrderHost);
436                            bytes_read = process->ReadMemory (cstr_address, &data_buffer.front(), fixed_length, error);
437                            if (bytes_read > 0)
438                            {
439                                sstr << '"';
440                                cstr_length = data.Dump (&sstr,
441                                                         0,                 // Start offset in "data"
442                                                         eFormatChar,       // Print as characters
443                                                         1,                 // Size of item (1 byte for a char!)
444                                                         bytes_read,        // How many bytes to print?
445                                                         UINT32_MAX,        // num per line
446                                                         LLDB_INVALID_ADDRESS,// base address
447                                                         0,                 // bitfield bit size
448                                                         0);                // bitfield bit offset
449                                sstr << '"';
450                            }
451                        }
452                        else
453                        {
454                            const size_t k_max_buf_size = 256;
455                            data_buffer.resize (k_max_buf_size + 1);
456                            // NULL terminate in case we don't get the entire C string
457                            data_buffer.back() = '\0';
458                            // Make a formatted buffer that can contain take 4
459                            // bytes per character in case each byte uses the
460                            // "\xXX" format and one extra byte for a NULL
461                            cstr_buffer.resize (k_max_buf_size * 4 + 1);
462
463                            data.SetData (&data_buffer.front(), data_buffer.size(), eByteOrderHost);
464                            size_t total_cstr_len = 0;
465                            while ((bytes_read = process->ReadMemory (cstr_address, &data_buffer.front(), k_max_buf_size, error)) > 0)
466                            {
467                                size_t len = strlen(&data_buffer.front());
468                                if (len == 0)
469                                    break;
470                                if (len > bytes_read)
471                                    len = bytes_read;
472                                if (sstr.GetSize() == 0)
473                                    sstr << '"';
474
475                                cstr_length = data.Dump (&sstr,
476                                                         0,                 // Start offset in "data"
477                                                         eFormatChar,       // Print as characters
478                                                         1,                 // Size of item (1 byte for a char!)
479                                                         len,               // How many bytes to print?
480                                                         UINT32_MAX,        // num per line
481                                                         LLDB_INVALID_ADDRESS,// base address
482                                                         0,                 // bitfield bit size
483                                                         0);                // bitfield bit offset
484
485                                if (len < k_max_buf_size)
486                                    break;
487                                cstr_address += total_cstr_len;
488                            }
489                            if (sstr.GetSize() > 0)
490                                sstr << '"';
491                        }
492
493                        if (sstr.GetSize() > 0)
494                            m_summary_str.assign (sstr.GetData(), sstr.GetSize());
495                    }
496                }
497            }
498        }
499    }
500    if (m_summary_str.empty())
501        return NULL;
502    return m_summary_str.c_str();
503}
504
505const char *
506ValueObject::GetObjectDescription (ExecutionContextScope *exe_scope)
507{
508    if (!m_object_desc_str.empty())
509        return m_object_desc_str.c_str();
510
511    if (!ClangASTContext::IsPointerType (GetOpaqueClangQualType()))
512        return NULL;
513
514    if (!GetValueIsValid())
515        return NULL;
516
517    Process *process = exe_scope->CalculateProcess();
518
519    if (!process)
520        return NULL;
521
522    Scalar scalar;
523
524    if (!ClangASTType::GetValueAsScalar (GetClangAST(),
525                                        GetOpaqueClangQualType(),
526                                        GetDataExtractor(),
527                                        0,
528                                        GetByteSize(),
529                                        scalar))
530        return NULL;
531
532    ExecutionContext exe_ctx;
533    exe_scope->Calculate(exe_ctx);
534
535    Value val(scalar);
536    val.SetContext(Value::eContextTypeOpaqueClangQualType,
537                   ClangASTContext::GetVoidPtrType(GetClangAST(), false));
538
539    StreamString s;
540    // FIXME: Check the runtime this object belongs to and get the appropriate object printer for the object kind.
541    if (process->GetObjCObjectPrinter().PrintObject(s, val, exe_ctx))
542    {
543        m_object_desc_str.append (s.GetData());
544    }
545    return m_object_desc_str.c_str();
546}
547
548const char *
549ValueObject::GetValueAsCString (ExecutionContextScope *exe_scope)
550{
551    // If our byte size is zero this is an aggregate type that has children
552    if (ClangASTContext::IsAggregateType (GetOpaqueClangQualType()) == false)
553    {
554        if (UpdateValueIfNeeded(exe_scope))
555        {
556            if (m_value_str.empty())
557            {
558                const Value::ContextType context_type = m_value.GetContextType();
559
560                switch (context_type)
561                {
562                case Value::eContextTypeOpaqueClangQualType:
563                case Value::eContextTypeDCType:
564                case Value::eContextTypeDCVariable:
565                    {
566                        void *clang_type = GetOpaqueClangQualType ();
567                        if (clang_type)
568                        {
569                            StreamString sstr;
570                            lldb::Format format = ClangASTType::GetFormat(clang_type);
571                            if (ClangASTType::DumpTypeValue(GetClangAST(),            // The clang AST
572                                                                clang_type,               // The clang type to display
573                                                                &sstr,
574                                                                format,                   // Format to display this type with
575                                                                m_data,                   // Data to extract from
576                                                                0,                        // Byte offset into "m_data"
577                                                                GetByteSize(),            // Byte size of item in "m_data"
578                                                                GetBitfieldBitSize(),     // Bitfield bit size
579                                                                GetBitfieldBitOffset()))  // Bitfield bit offset
580                                m_value_str.swap(sstr.GetString());
581                            else
582                                m_value_str.clear();
583                        }
584                    }
585                    break;
586
587                case Value::eContextTypeDCRegisterInfo:
588                    {
589                        const RegisterInfo *reg_info = m_value.GetRegisterInfo();
590                        if (reg_info)
591                        {
592                            StreamString reg_sstr;
593                            m_data.Dump(&reg_sstr, 0, reg_info->format, reg_info->byte_size, 1, UINT32_MAX, LLDB_INVALID_ADDRESS, 0, 0);
594                            m_value_str.swap(reg_sstr.GetString());
595                        }
596                    }
597                    break;
598
599                default:
600                    break;
601                }
602            }
603
604            if (!m_value_did_change && m_old_value_valid)
605            {
606                // The value was gotten successfully, so we consider the
607                // value as changed if the value string differs
608                SetValueDidChange (m_old_value_str != m_value_str);
609            }
610        }
611    }
612    if (m_value_str.empty())
613        return NULL;
614    return m_value_str.c_str();
615}
616
617bool
618ValueObject::SetValueFromCString (ExecutionContextScope *exe_scope, const char *value_str)
619{
620    // Make sure our value is up to date first so that our location and location
621    // type is valid.
622    if (!UpdateValueIfNeeded(exe_scope))
623        return false;
624
625    uint32_t count = 0;
626    lldb::Encoding encoding = ClangASTType::GetEncoding (GetOpaqueClangQualType(), count);
627
628    char *end = NULL;
629    const size_t byte_size = GetByteSize();
630    switch (encoding)
631    {
632    case eEncodingInvalid:
633        return false;
634
635    case eEncodingUint:
636        if (byte_size > sizeof(unsigned long long))
637        {
638            return false;
639        }
640        else
641        {
642            unsigned long long ull_val = strtoull(value_str, &end, 0);
643            if (end && *end != '\0')
644                return false;
645            m_value = ull_val;
646            // Limit the bytes in our m_data appropriately.
647            m_value.GetScalar().GetData (m_data, byte_size);
648        }
649        break;
650
651    case eEncodingSint:
652        if (byte_size > sizeof(long long))
653        {
654            return false;
655        }
656        else
657        {
658            long long sll_val = strtoll(value_str, &end, 0);
659            if (end && *end != '\0')
660                return false;
661            m_value = sll_val;
662            // Limit the bytes in our m_data appropriately.
663            m_value.GetScalar().GetData (m_data, byte_size);
664        }
665        break;
666
667    case eEncodingIEEE754:
668        {
669            const off_t byte_offset = GetByteOffset();
670            uint8_t *dst = const_cast<uint8_t *>(m_data.PeekData(byte_offset, byte_size));
671            if (dst != NULL)
672            {
673                // We are decoding a float into host byte order below, so make
674                // sure m_data knows what it contains.
675                m_data.SetByteOrder(eByteOrderHost);
676                const size_t converted_byte_size = ClangASTContext::ConvertStringToFloatValue (
677                                                        GetClangAST(),
678                                                        GetOpaqueClangQualType(),
679                                                        value_str,
680                                                        dst,
681                                                        byte_size);
682
683                if (converted_byte_size == byte_size)
684                {
685                }
686            }
687        }
688        break;
689
690    case eEncodingVector:
691        return false;
692
693    default:
694        return false;
695    }
696
697    // If we have made it here the value is in m_data and we should write it
698    // out to the target
699    return Write ();
700}
701
702bool
703ValueObject::Write ()
704{
705    // Clear the update ID so the next time we try and read the value
706    // we try and read it again.
707    m_update_id = 0;
708
709    // TODO: when Value has a method to write a value back, call it from here.
710    return false;
711
712}
713
714void
715ValueObject::AddSyntheticChild (const ConstString &key, ValueObjectSP& valobj_sp)
716{
717    m_synthetic_children[key] = valobj_sp;
718}
719
720ValueObjectSP
721ValueObject::GetSyntheticChild (const ConstString &key) const
722{
723    ValueObjectSP synthetic_child_sp;
724    std::map<ConstString, ValueObjectSP>::const_iterator pos = m_synthetic_children.find (key);
725    if (pos != m_synthetic_children.end())
726        synthetic_child_sp = pos->second;
727    return synthetic_child_sp;
728}
729
730bool
731ValueObject::IsPointerType ()
732{
733    return ClangASTContext::IsPointerType (GetOpaqueClangQualType());
734}
735
736bool
737ValueObject::IsPointerOrReferenceType ()
738{
739    return ClangASTContext::IsPointerOrReferenceType(GetOpaqueClangQualType());
740}
741
742ValueObjectSP
743ValueObject::GetSyntheticArrayMemberFromPointer (int32_t index, bool can_create)
744{
745    ValueObjectSP synthetic_child_sp;
746    if (IsPointerType ())
747    {
748        char index_str[64];
749        snprintf(index_str, sizeof(index_str), "[%i]", index);
750        ConstString index_const_str(index_str);
751        // Check if we have already created a synthetic array member in this
752        // valid object. If we have we will re-use it.
753        synthetic_child_sp = GetSyntheticChild (index_const_str);
754        if (!synthetic_child_sp)
755        {
756            // We haven't made a synthetic array member for INDEX yet, so
757            // lets make one and cache it for any future reference.
758            synthetic_child_sp = CreateChildAtIndex(0, true, index);
759
760            // Cache the value if we got one back...
761            if (synthetic_child_sp)
762                AddSyntheticChild(index_const_str, synthetic_child_sp);
763        }
764    }
765    return synthetic_child_sp;
766}
767