1 //===-- Value.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/Value.h"
11 
12 // C Includes
13 // C++ Includes
14 // Other libraries and framework includes
15 // Project includes
16 #include "lldb/Core/DataExtractor.h"
17 #include "lldb/Core/DataBufferHeap.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/State.h"
20 #include "lldb/Core/Stream.h"
21 #include "lldb/Symbol/ClangASTType.h"
22 #include "lldb/Symbol/ClangASTContext.h"
23 #include "lldb/Symbol/ObjectFile.h"
24 #include "lldb/Symbol/SymbolContext.h"
25 #include "lldb/Symbol/Type.h"
26 #include "lldb/Symbol/Variable.h"
27 #include "lldb/Target/ExecutionContext.h"
28 #include "lldb/Target/Process.h"
29 #include "lldb/Target/Target.h"
30 
31 using namespace lldb;
32 using namespace lldb_private;
33 
34 Value::Value() :
35     m_value (),
36     m_value_type (eValueTypeScalar),
37     m_context (NULL),
38     m_context_type (eContextTypeInvalid),
39     m_data_buffer ()
40 {
41 }
42 
43 Value::Value(const Scalar& scalar) :
44     m_value (scalar),
45     m_value_type (eValueTypeScalar),
46     m_context (NULL),
47     m_context_type (eContextTypeInvalid),
48     m_data_buffer ()
49 {
50 }
51 
52 
53 Value::Value(const uint8_t *bytes, int len) :
54     m_value (),
55     m_value_type (eValueTypeHostAddress),
56     m_context (NULL),
57     m_context_type (eContextTypeInvalid),
58     m_data_buffer ()
59 {
60     m_data_buffer.CopyData(bytes, len);
61     m_value = (uintptr_t)m_data_buffer.GetBytes();
62 }
63 
64 Value::Value(const Value &v) :
65     m_value(v.m_value),
66     m_value_type(v.m_value_type),
67     m_context(v.m_context),
68     m_context_type(v.m_context_type)
69 {
70     if ((uintptr_t)v.m_value.ULongLong(LLDB_INVALID_ADDRESS) == (uintptr_t)v.m_data_buffer.GetBytes())
71     {
72         m_data_buffer.CopyData(v.m_data_buffer.GetBytes(),
73                                v.m_data_buffer.GetByteSize());
74 
75         m_value = (uintptr_t)m_data_buffer.GetBytes();
76     }
77 }
78 
79 Value &
80 Value::operator=(const Value &rhs)
81 {
82     if (this != &rhs)
83     {
84         m_value = rhs.m_value;
85         m_value_type = rhs.m_value_type;
86         m_context = rhs.m_context;
87         m_context_type = rhs.m_context_type;
88         if ((uintptr_t)rhs.m_value.ULongLong(LLDB_INVALID_ADDRESS) == (uintptr_t)rhs.m_data_buffer.GetBytes())
89         {
90             m_data_buffer.CopyData(rhs.m_data_buffer.GetBytes(),
91                                    rhs.m_data_buffer.GetByteSize());
92 
93             m_value = (uintptr_t)m_data_buffer.GetBytes();
94         }
95     }
96     return *this;
97 }
98 
99 void
100 Value::Dump (Stream* strm)
101 {
102     m_value.GetValue (strm, true);
103     strm->Printf(", value_type = %s, context = %p, context_type = %s",
104                 Value::GetValueTypeAsCString(m_value_type),
105                 m_context,
106                 Value::GetContextTypeAsCString(m_context_type));
107 }
108 
109 Value::ValueType
110 Value::GetValueType() const
111 {
112     return m_value_type;
113 }
114 
115 AddressType
116 Value::GetValueAddressType () const
117 {
118     switch (m_value_type)
119     {
120     default:
121     case eValueTypeScalar:
122         break;
123     case eValueTypeLoadAddress: return eAddressTypeLoad;
124     case eValueTypeFileAddress: return eAddressTypeFile;
125     case eValueTypeHostAddress: return eAddressTypeHost;
126     }
127     return eAddressTypeInvalid;
128 }
129 
130 RegisterInfo *
131 Value::GetRegisterInfo()
132 {
133     if (m_context_type == eContextTypeRegisterInfo)
134         return static_cast<RegisterInfo *> (m_context);
135     return NULL;
136 }
137 
138 Type *
139 Value::GetType()
140 {
141     if (m_context_type == eContextTypeLLDBType)
142         return static_cast<Type *> (m_context);
143     return NULL;
144 }
145 
146 void
147 Value::ResizeData(int len)
148 {
149     m_value_type = eValueTypeHostAddress;
150     m_data_buffer.SetByteSize(len);
151     m_value = (uintptr_t)m_data_buffer.GetBytes();
152 }
153 
154 bool
155 Value::ValueOf(ExecutionContext *exe_ctx, clang::ASTContext *ast_context)
156 {
157     switch (m_context_type)
158     {
159     case eContextTypeInvalid:
160     case eContextTypeClangType:         // clang::Type *
161     case eContextTypeRegisterInfo:      // RegisterInfo *
162     case eContextTypeLLDBType:          // Type *
163         break;
164 
165     case eContextTypeVariable:          // Variable *
166         ResolveValue(exe_ctx, ast_context);
167         return true;
168     }
169     return false;
170 }
171 
172 size_t
173 Value::GetValueByteSize (clang::ASTContext *ast_context, Error *error_ptr)
174 {
175     size_t byte_size = 0;
176 
177     switch (m_context_type)
178     {
179     case eContextTypeInvalid:
180         // If we have no context, there is no way to know how much memory to read
181         if (error_ptr)
182             error_ptr->SetErrorString ("Invalid context type, there is no way to know how much memory to read.");
183         break;
184 
185     case eContextTypeClangType:
186         if (ast_context == NULL)
187         {
188             if (error_ptr)
189                 error_ptr->SetErrorString ("Can't determine size of opaque clang type with NULL ASTContext *.");
190         }
191         else
192         {
193             uint64_t bit_width = ClangASTType::GetClangTypeBitWidth (ast_context, m_context);
194             byte_size = (bit_width + 7 ) / 8;
195         }
196         break;
197 
198     case eContextTypeRegisterInfo:     // RegisterInfo *
199         if (GetRegisterInfo())
200             byte_size = GetRegisterInfo()->byte_size;
201         else if (error_ptr)
202             error_ptr->SetErrorString ("Can't determine byte size with NULL RegisterInfo *.");
203         break;
204 
205     case eContextTypeLLDBType:             // Type *
206         if (GetType())
207             byte_size = GetType()->GetByteSize();
208         else if (error_ptr)
209             error_ptr->SetErrorString ("Can't determine byte size with NULL Type *.");
210         break;
211 
212     case eContextTypeVariable:         // Variable *
213         if (GetVariable())
214         {
215             if (GetVariable()->GetType())
216                 byte_size = GetVariable()->GetType()->GetByteSize();
217             else if (error_ptr)
218                 error_ptr->SetErrorString ("Can't determine byte size with NULL Type *.");
219         }
220         else if (error_ptr)
221             error_ptr->SetErrorString ("Can't determine byte size with NULL Variable *.");
222         break;
223     }
224 
225     if (error_ptr)
226     {
227         if (byte_size == 0)
228         {
229             if (error_ptr->Success())
230                 error_ptr->SetErrorString("Unable to determine byte size.");
231         }
232         else
233         {
234             error_ptr->Clear();
235         }
236     }
237     return byte_size;
238 }
239 
240 clang_type_t
241 Value::GetClangType ()
242 {
243     switch (m_context_type)
244     {
245     case eContextTypeInvalid:
246         break;
247 
248     case eContextTypeClangType:
249         return m_context;
250 
251     case eContextTypeRegisterInfo:
252         break;    // TODO: Eventually convert into a clang type?
253 
254     case eContextTypeLLDBType:
255         if (GetType())
256             return GetType()->GetClangForwardType();
257         break;
258 
259     case eContextTypeVariable:
260         if (GetVariable())
261             return GetVariable()->GetType()->GetClangForwardType();
262         break;
263     }
264 
265     return NULL;
266 }
267 
268 lldb::Format
269 Value::GetValueDefaultFormat ()
270 {
271     switch (m_context_type)
272     {
273     case eContextTypeInvalid:
274         break;
275 
276     case eContextTypeClangType:
277         return ClangASTType::GetFormat (m_context);
278 
279     case eContextTypeRegisterInfo:
280         if (GetRegisterInfo())
281             return GetRegisterInfo()->format;
282         break;
283 
284     case eContextTypeLLDBType:
285         if (GetType())
286             return GetType()->GetFormat();
287         break;
288 
289     case eContextTypeVariable:
290         if (GetVariable())
291             return GetVariable()->GetType()->GetFormat();
292         break;
293 
294     }
295 
296     // Return a good default in case we can't figure anything out
297     return eFormatHex;
298 }
299 
300 bool
301 Value::GetData (DataExtractor &data)
302 {
303     switch (m_value_type)
304     {
305     default:
306         break;
307 
308     case eValueTypeScalar:
309         if (m_value.GetData (data))
310             return true;
311         break;
312 
313     case eValueTypeLoadAddress:
314     case eValueTypeFileAddress:
315     case eValueTypeHostAddress:
316         if (m_data_buffer.GetByteSize())
317         {
318             data.SetData(m_data_buffer.GetBytes(), m_data_buffer.GetByteSize(), data.GetByteOrder());
319             return true;
320         }
321         break;
322     }
323 
324     return false;
325 
326 }
327 
328 Error
329 Value::GetValueAsData (ExecutionContext *exe_ctx,
330                        clang::ASTContext *ast_context,
331                        DataExtractor &data,
332                        uint32_t data_offset,
333                        Module *module)
334 {
335     data.Clear();
336 
337     Error error;
338     lldb::addr_t address = LLDB_INVALID_ADDRESS;
339     AddressType address_type = eAddressTypeFile;
340     Address file_so_addr;
341     switch (m_value_type)
342     {
343     default:
344         error.SetErrorStringWithFormat("invalid value type %i", m_value_type);
345         break;
346 
347     case eValueTypeScalar:
348         data.SetByteOrder (lldb::endian::InlHostByteOrder());
349         if (m_context_type == eContextTypeClangType && ast_context)
350         {
351             uint32_t ptr_bit_width = ClangASTType::GetClangTypeBitWidth (ast_context,
352                                                                      ClangASTContext::GetVoidPtrType(ast_context, false));
353             uint32_t ptr_byte_size = (ptr_bit_width + 7) / 8;
354             data.SetAddressByteSize (ptr_byte_size);
355         }
356         else
357             data.SetAddressByteSize(sizeof(void *));
358         if (m_value.GetData (data))
359             return error;   // Success;
360         error.SetErrorStringWithFormat("extracting data from value failed");
361         break;
362 
363     case eValueTypeLoadAddress:
364         if (exe_ctx == NULL)
365         {
366             error.SetErrorString ("can't read load address (no execution context)");
367         }
368         else
369         {
370             Process *process = exe_ctx->GetProcessPtr();
371             if (process == NULL)
372             {
373                 error.SetErrorString ("can't read load address (invalid process)");
374             }
375             else
376             {
377                 address = m_value.ULongLong(LLDB_INVALID_ADDRESS);
378                 address_type = eAddressTypeLoad;
379                 data.SetByteOrder(process->GetTarget().GetArchitecture().GetByteOrder());
380                 data.SetAddressByteSize(process->GetTarget().GetArchitecture().GetAddressByteSize());
381             }
382         }
383         break;
384 
385     case eValueTypeFileAddress:
386         if (exe_ctx == NULL)
387         {
388             error.SetErrorString ("can't read file address (no execution context)");
389         }
390         else if (exe_ctx->GetTargetPtr() == NULL)
391         {
392             error.SetErrorString ("can't read file address (invalid target)");
393         }
394         else
395         {
396             address = m_value.ULongLong(LLDB_INVALID_ADDRESS);
397             if (address == LLDB_INVALID_ADDRESS)
398             {
399                 error.SetErrorString ("invalid file address");
400             }
401             else
402             {
403                 if (module == NULL)
404                 {
405                     // The only thing we can currently lock down to a module so that
406                     // we can resolve a file address, is a variable.
407                     Variable *variable = GetVariable();
408                     if (variable)
409                     {
410                         SymbolContext var_sc;
411                         variable->CalculateSymbolContext(&var_sc);
412                         module = var_sc.module_sp.get();
413                     }
414                 }
415 
416                 if (module)
417                 {
418                     bool resolved = false;
419                     ObjectFile *objfile = module->GetObjectFile();
420                     if (objfile)
421                     {
422                         Address so_addr(address, objfile->GetSectionList());
423                         addr_t load_address = so_addr.GetLoadAddress (exe_ctx->GetTargetPtr());
424                         bool process_launched_and_stopped = exe_ctx->GetProcessPtr()
425                             ? StateIsStoppedState(exe_ctx->GetProcessPtr()->GetState(), true /* must_exist */)
426                             : false;
427                         // Don't use the load address if the process has exited.
428                         if (load_address != LLDB_INVALID_ADDRESS && process_launched_and_stopped)
429                         {
430                             resolved = true;
431                             address = load_address;
432                             address_type = eAddressTypeLoad;
433                             data.SetByteOrder(exe_ctx->GetTargetRef().GetArchitecture().GetByteOrder());
434                             data.SetAddressByteSize(exe_ctx->GetTargetRef().GetArchitecture().GetAddressByteSize());
435                         }
436                         else
437                         {
438                             if (so_addr.IsSectionOffset())
439                             {
440                                 resolved = true;
441                                 file_so_addr = so_addr;
442                                 data.SetByteOrder(objfile->GetByteOrder());
443                                 data.SetAddressByteSize(objfile->GetAddressByteSize());
444                             }
445                         }
446                     }
447                     if (!resolved)
448                     {
449                         Variable *variable = GetVariable();
450 
451                         if (module)
452                         {
453                             if (variable)
454                                 error.SetErrorStringWithFormat ("unable to resolve the module for file address 0x%" PRIx64 " for variable '%s' in %s%s%s",
455                                                                 address,
456                                                                 variable->GetName().AsCString(""),
457                                                                 module->GetFileSpec().GetDirectory().GetCString(),
458                                                                 module->GetFileSpec().GetDirectory() ? "/" : "",
459                                                                 module->GetFileSpec().GetFilename().GetCString());
460                             else
461                                 error.SetErrorStringWithFormat ("unable to resolve the module for file address 0x%" PRIx64 " in %s%s%s",
462                                                                 address,
463                                                                 module->GetFileSpec().GetDirectory().GetCString(),
464                                                                 module->GetFileSpec().GetDirectory() ? "/" : "",
465                                                                 module->GetFileSpec().GetFilename().GetCString());
466                         }
467                         else
468                         {
469                             if (variable)
470                                 error.SetErrorStringWithFormat ("unable to resolve the module for file address 0x%" PRIx64 " for variable '%s'",
471                                                                 address,
472                                                                 variable->GetName().AsCString(""));
473                             else
474                                 error.SetErrorStringWithFormat ("unable to resolve the module for file address 0x%" PRIx64, address);
475                         }
476                     }
477                 }
478                 else
479                 {
480                     // Can't convert a file address to anything valid without more
481                     // context (which Module it came from)
482                     error.SetErrorString ("can't read memory from file address without more context");
483                 }
484             }
485         }
486         break;
487 
488     case eValueTypeHostAddress:
489         address = m_value.ULongLong(LLDB_INVALID_ADDRESS);
490         address_type = eAddressTypeHost;
491         if (exe_ctx)
492         {
493             Target *target = exe_ctx->GetTargetPtr();
494             if (target)
495             {
496                 data.SetByteOrder(target->GetArchitecture().GetByteOrder());
497                 data.SetAddressByteSize(target->GetArchitecture().GetAddressByteSize());
498                 break;
499             }
500         }
501         // fallback to host settings
502         data.SetByteOrder(lldb::endian::InlHostByteOrder());
503         data.SetAddressByteSize(sizeof(void *));
504         break;
505     }
506 
507     // Bail if we encountered any errors
508     if (error.Fail())
509         return error;
510 
511     if (address == LLDB_INVALID_ADDRESS)
512     {
513         error.SetErrorStringWithFormat ("invalid %s address", address_type == eAddressTypeHost ? "host" : "load");
514         return error;
515     }
516 
517     // If we got here, we need to read the value from memory
518     uint32_t byte_size = GetValueByteSize (ast_context, &error);
519 
520     // Bail if we encountered any errors getting the byte size
521     if (error.Fail())
522         return error;
523 
524     // Make sure we have enough room within "data", and if we don't make
525     // something large enough that does
526     if (!data.ValidOffsetForDataOfSize (data_offset, byte_size))
527     {
528         DataBufferSP data_sp(new DataBufferHeap (data_offset + byte_size, '\0'));
529         data.SetData(data_sp);
530     }
531 
532     uint8_t* dst = const_cast<uint8_t*>(data.PeekData (data_offset, byte_size));
533     if (dst != NULL)
534     {
535         if (address_type == eAddressTypeHost)
536         {
537             // The address is an address in this process, so just copy it
538             memcpy (dst, (uint8_t*)NULL + address, byte_size);
539         }
540         else if ((address_type == eAddressTypeLoad) || (address_type == eAddressTypeFile))
541         {
542             if (file_so_addr.IsValid())
543             {
544                 // We have a file address that we were able to translate into a
545                 // section offset address so we might be able to read this from
546                 // the object files if we don't have a live process. Lets always
547                 // try and read from the process if we have one though since we
548                 // want to read the actual value by setting "prefer_file_cache"
549                 // to false.
550                 const bool prefer_file_cache = false;
551                 if (exe_ctx->GetTargetRef().ReadMemory(file_so_addr, prefer_file_cache, dst, byte_size, error) != byte_size)
552                 {
553                     error.SetErrorStringWithFormat("read memory from 0x%" PRIx64 " failed", (uint64_t)address);
554                 }
555             }
556             else
557             {
558                 // The execution context might have a NULL process, but it
559                 // might have a valid process in the exe_ctx->target, so use
560                 // the ExecutionContext::GetProcess accessor to ensure we
561                 // get the process if there is one.
562                 Process *process = exe_ctx->GetProcessPtr();
563 
564                 if (process)
565                 {
566                     const size_t bytes_read = process->ReadMemory(address, dst, byte_size, error);
567                     if (bytes_read != byte_size)
568                         error.SetErrorStringWithFormat("read memory from 0x%" PRIx64 " failed (%u of %u bytes read)",
569                                                        (uint64_t)address,
570                                                        (uint32_t)bytes_read,
571                                                        (uint32_t)byte_size);
572                 }
573                 else
574                 {
575                     error.SetErrorStringWithFormat("read memory from 0x%" PRIx64 " failed (invalid process)", (uint64_t)address);
576                 }
577             }
578         }
579         else
580         {
581             error.SetErrorStringWithFormat ("unsupported AddressType value (%i)", address_type);
582         }
583     }
584     else
585     {
586         error.SetErrorStringWithFormat ("out of memory");
587     }
588 
589     return error;
590 }
591 
592 Scalar &
593 Value::ResolveValue(ExecutionContext *exe_ctx, clang::ASTContext *ast_context)
594 {
595     void *opaque_clang_qual_type = GetClangType();
596     if (opaque_clang_qual_type)
597     {
598         switch (m_value_type)
599         {
600         case eValueTypeScalar:               // raw scalar value
601             break;
602 
603         default:
604         case eValueTypeFileAddress:
605             m_value.Clear();
606             break;
607 
608         case eValueTypeLoadAddress:          // load address value
609         case eValueTypeHostAddress:          // host address value (for memory in the process that is using liblldb)
610             {
611                 AddressType address_type = m_value_type == eValueTypeLoadAddress ? eAddressTypeLoad : eAddressTypeHost;
612                 lldb::addr_t addr = m_value.ULongLong(LLDB_INVALID_ADDRESS);
613                 DataExtractor data;
614                 if (ClangASTType::ReadFromMemory (ast_context, opaque_clang_qual_type, exe_ctx, addr, address_type, data))
615                 {
616                     Scalar scalar;
617                     if (ClangASTType::GetValueAsScalar (ast_context, opaque_clang_qual_type, data, 0, data.GetByteSize(), scalar))
618                     {
619                         m_value = scalar;
620                         m_value_type = eValueTypeScalar;
621                     }
622                     else
623                     {
624                         if ((uintptr_t)addr != (uintptr_t)m_data_buffer.GetBytes())
625                         {
626                             m_value.Clear();
627                             m_value_type = eValueTypeScalar;
628                         }
629                     }
630                 }
631                 else
632                 {
633                     if ((uintptr_t)addr != (uintptr_t)m_data_buffer.GetBytes())
634                     {
635                         m_value.Clear();
636                         m_value_type = eValueTypeScalar;
637                     }
638                 }
639             }
640             break;
641         }
642     }
643     return m_value;
644 }
645 
646 Variable *
647 Value::GetVariable()
648 {
649     if (m_context_type == eContextTypeVariable)
650         return static_cast<Variable *> (m_context);
651     return NULL;
652 }
653 
654 const char *
655 Value::GetValueTypeAsCString (ValueType value_type)
656 {
657     switch (value_type)
658     {
659     case eValueTypeScalar:      return "scalar";
660     case eValueTypeVector:      return "vector";
661     case eValueTypeFileAddress: return "file address";
662     case eValueTypeLoadAddress: return "load address";
663     case eValueTypeHostAddress: return "host address";
664     };
665     return "???";
666 }
667 
668 const char *
669 Value::GetContextTypeAsCString (ContextType context_type)
670 {
671     switch (context_type)
672     {
673     case eContextTypeInvalid:       return "invalid";
674     case eContextTypeClangType:     return "clang::Type *";
675     case eContextTypeRegisterInfo:  return "RegisterInfo *";
676     case eContextTypeLLDBType:      return "Type *";
677     case eContextTypeVariable:      return "Variable *";
678     };
679     return "???";
680 }
681 
682 ValueList::ValueList (const ValueList &rhs)
683 {
684     m_values = rhs.m_values;
685 }
686 
687 const ValueList &
688 ValueList::operator= (const ValueList &rhs)
689 {
690     m_values = rhs.m_values;
691     return *this;
692 }
693 
694 void
695 ValueList::PushValue (const Value &value)
696 {
697     m_values.push_back (value);
698 }
699 
700 size_t
701 ValueList::GetSize()
702 {
703     return m_values.size();
704 }
705 
706 Value *
707 ValueList::GetValueAtIndex (size_t idx)
708 {
709     if (idx < GetSize())
710     {
711         return &(m_values[idx]);
712     }
713     else
714         return NULL;
715 }
716 
717 void
718 ValueList::Clear ()
719 {
720     m_values.clear();
721 }
722