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