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