1 //===-- ValueObjectVariable.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/ValueObjectVariable.h"
11 
12 #include "lldb/Core/Address.h"      // for Address
13 #include "lldb/Core/AddressRange.h" // for AddressRange
14 #include "lldb/Core/ArchSpec.h"     // for ArchSpec
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/RegisterValue.h"
17 #include "lldb/Core/Scalar.h" // for Scalar, operator!=
18 #include "lldb/Core/Value.h"
19 #include "lldb/Expression/DWARFExpression.h" // for DWARFExpression
20 #include "lldb/Symbol/Declaration.h"         // for Declaration
21 #include "lldb/Symbol/Function.h"
22 #include "lldb/Symbol/ObjectFile.h"
23 #include "lldb/Symbol/SymbolContext.h"
24 #include "lldb/Symbol/SymbolContextScope.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/RegisterContext.h"
30 #include "lldb/Target/Target.h"
31 #include "lldb/Utility/DataExtractor.h"     // for DataExtractor
32 #include "lldb/Utility/Status.h"            // for Status
33 #include "lldb/lldb-private-enumerations.h" // for AddressType::eAddressTy...
34 #include "lldb/lldb-types.h"                // for addr_t
35 
36 #include "llvm/ADT/StringRef.h" // for StringRef
37 
38 #include <assert.h> // for assert
39 #include <memory>   // for shared_ptr
40 
41 namespace lldb_private {
42 class ExecutionContextScope;
43 }
44 namespace lldb_private {
45 class StackFrame;
46 }
47 namespace lldb_private {
48 struct RegisterInfo;
49 }
50 using namespace lldb_private;
51 
52 lldb::ValueObjectSP
53 ValueObjectVariable::Create(ExecutionContextScope *exe_scope,
54                             const lldb::VariableSP &var_sp) {
55   return (new ValueObjectVariable(exe_scope, var_sp))->GetSP();
56 }
57 
58 ValueObjectVariable::ValueObjectVariable(ExecutionContextScope *exe_scope,
59                                          const lldb::VariableSP &var_sp)
60     : ValueObject(exe_scope), m_variable_sp(var_sp) {
61   // Do not attempt to construct one of these objects with no variable!
62   assert(m_variable_sp.get() != NULL);
63   m_name = var_sp->GetName();
64 }
65 
66 ValueObjectVariable::~ValueObjectVariable() {}
67 
68 CompilerType ValueObjectVariable::GetCompilerTypeImpl() {
69   Type *var_type = m_variable_sp->GetType();
70   if (var_type)
71     return var_type->GetForwardCompilerType();
72   return CompilerType();
73 }
74 
75 ConstString ValueObjectVariable::GetTypeName() {
76   Type *var_type = m_variable_sp->GetType();
77   if (var_type)
78     return var_type->GetName();
79   return ConstString();
80 }
81 
82 ConstString ValueObjectVariable::GetDisplayTypeName() {
83   Type *var_type = m_variable_sp->GetType();
84   if (var_type)
85     return var_type->GetForwardCompilerType().GetDisplayTypeName();
86   return ConstString();
87 }
88 
89 ConstString ValueObjectVariable::GetQualifiedTypeName() {
90   Type *var_type = m_variable_sp->GetType();
91   if (var_type)
92     return var_type->GetQualifiedName();
93   return ConstString();
94 }
95 
96 size_t ValueObjectVariable::CalculateNumChildren(uint32_t max) {
97   CompilerType type(GetCompilerType());
98 
99   if (!type.IsValid())
100     return 0;
101 
102   const bool omit_empty_base_classes = true;
103   auto child_count = type.GetNumChildren(omit_empty_base_classes);
104   return child_count <= max ? child_count : max;
105 }
106 
107 uint64_t ValueObjectVariable::GetByteSize() {
108   ExecutionContext exe_ctx(GetExecutionContextRef());
109 
110   CompilerType type(GetCompilerType());
111 
112   if (!type.IsValid())
113     return 0;
114 
115   return type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
116 }
117 
118 lldb::ValueType ValueObjectVariable::GetValueType() const {
119   if (m_variable_sp)
120     return m_variable_sp->GetScope();
121   return lldb::eValueTypeInvalid;
122 }
123 
124 bool ValueObjectVariable::UpdateValue() {
125   SetValueIsValid(false);
126   m_error.Clear();
127 
128   Variable *variable = m_variable_sp.get();
129   DWARFExpression &expr = variable->LocationExpression();
130 
131   if (variable->GetLocationIsConstantValueData()) {
132     // expr doesn't contain DWARF bytes, it contains the constant variable
133     // value bytes themselves...
134     if (expr.GetExpressionData(m_data))
135       m_value.SetContext(Value::eContextTypeVariable, variable);
136     else
137       m_error.SetErrorString("empty constant data");
138     // constant bytes can't be edited - sorry
139     m_resolved_value.SetContext(Value::eContextTypeInvalid, NULL);
140   } else {
141     lldb::addr_t loclist_base_load_addr = LLDB_INVALID_ADDRESS;
142     ExecutionContext exe_ctx(GetExecutionContextRef());
143 
144     Target *target = exe_ctx.GetTargetPtr();
145     if (target) {
146       m_data.SetByteOrder(target->GetArchitecture().GetByteOrder());
147       m_data.SetAddressByteSize(target->GetArchitecture().GetAddressByteSize());
148     }
149 
150     if (expr.IsLocationList()) {
151       SymbolContext sc;
152       variable->CalculateSymbolContext(&sc);
153       if (sc.function)
154         loclist_base_load_addr =
155             sc.function->GetAddressRange().GetBaseAddress().GetLoadAddress(
156                 target);
157     }
158     Value old_value(m_value);
159     if (expr.Evaluate(&exe_ctx, nullptr, loclist_base_load_addr, nullptr,
160                       nullptr, m_value, &m_error)) {
161       m_resolved_value = m_value;
162       m_value.SetContext(Value::eContextTypeVariable, variable);
163 
164       CompilerType compiler_type = GetCompilerType();
165       if (compiler_type.IsValid())
166         m_value.SetCompilerType(compiler_type);
167 
168       Value::ValueType value_type = m_value.GetValueType();
169 
170       Process *process = exe_ctx.GetProcessPtr();
171       const bool process_is_alive = process && process->IsAlive();
172       const uint32_t type_info = compiler_type.GetTypeInfo();
173       const bool is_pointer_or_ref =
174           (type_info & (lldb::eTypeIsPointer | lldb::eTypeIsReference)) != 0;
175 
176       switch (value_type) {
177       case Value::eValueTypeFileAddress:
178         // If this type is a pointer, then its children will be considered load
179         // addresses
180         // if the pointer or reference is dereferenced, but only if the process
181         // is alive.
182         //
183         // There could be global variables like in the following code:
184         // struct LinkedListNode { Foo* foo; LinkedListNode* next; };
185         // Foo g_foo1;
186         // Foo g_foo2;
187         // LinkedListNode g_second_node = { &g_foo2, NULL };
188         // LinkedListNode g_first_node = { &g_foo1, &g_second_node };
189         //
190         // When we aren't running, we should be able to look at these variables
191         // using
192         // the "target variable" command. Children of the "g_first_node" always
193         // will
194         // be of the same address type as the parent. But children of the "next"
195         // member of
196         // LinkedListNode will become load addresses if we have a live process,
197         // or remain
198         // what a file address if it what a file address.
199         if (process_is_alive && is_pointer_or_ref)
200           SetAddressTypeOfChildren(eAddressTypeLoad);
201         else
202           SetAddressTypeOfChildren(eAddressTypeFile);
203         break;
204       case Value::eValueTypeHostAddress:
205         // Same as above for load addresses, except children of pointer or refs
206         // are always
207         // load addresses. Host addresses are used to store freeze dried
208         // variables. If this
209         // type is a struct, the entire struct contents will be copied into the
210         // heap of the
211         // LLDB process, but we do not currrently follow any pointers.
212         if (is_pointer_or_ref)
213           SetAddressTypeOfChildren(eAddressTypeLoad);
214         else
215           SetAddressTypeOfChildren(eAddressTypeHost);
216         break;
217       case Value::eValueTypeLoadAddress:
218       case Value::eValueTypeScalar:
219       case Value::eValueTypeVector:
220         SetAddressTypeOfChildren(eAddressTypeLoad);
221         break;
222       }
223 
224       switch (value_type) {
225       case Value::eValueTypeVector:
226       // fall through
227       case Value::eValueTypeScalar:
228         // The variable value is in the Scalar value inside the m_value.
229         // We can point our m_data right to it.
230         m_error =
231             m_value.GetValueAsData(&exe_ctx, m_data, 0, GetModule().get());
232         break;
233 
234       case Value::eValueTypeFileAddress:
235       case Value::eValueTypeLoadAddress:
236       case Value::eValueTypeHostAddress:
237         // The DWARF expression result was an address in the inferior
238         // process. If this variable is an aggregate type, we just need
239         // the address as the main value as all child variable objects
240         // will rely upon this location and add an offset and then read
241         // their own values as needed. If this variable is a simple
242         // type, we read all data for it into m_data.
243         // Make sure this type has a value before we try and read it
244 
245         // If we have a file address, convert it to a load address if we can.
246         if (value_type == Value::eValueTypeFileAddress && process_is_alive) {
247           lldb::addr_t file_addr =
248               m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
249           if (file_addr != LLDB_INVALID_ADDRESS) {
250             SymbolContext var_sc;
251             variable->CalculateSymbolContext(&var_sc);
252             if (var_sc.module_sp) {
253               ObjectFile *objfile = var_sc.module_sp->GetObjectFile();
254               if (objfile) {
255                 Address so_addr(file_addr, objfile->GetSectionList());
256                 lldb::addr_t load_addr = so_addr.GetLoadAddress(target);
257                 if (load_addr != LLDB_INVALID_ADDRESS) {
258                   m_value.SetValueType(Value::eValueTypeLoadAddress);
259                   m_value.GetScalar() = load_addr;
260                 }
261               }
262             }
263           }
264         }
265 
266         if (!CanProvideValue()) {
267           // this value object represents an aggregate type whose
268           // children have values, but this object does not. So we
269           // say we are changed if our location has changed.
270           SetValueDidChange(value_type != old_value.GetValueType() ||
271                             m_value.GetScalar() != old_value.GetScalar());
272         } else {
273           // Copy the Value and set the context to use our Variable
274           // so it can extract read its value into m_data appropriately
275           Value value(m_value);
276           value.SetContext(Value::eContextTypeVariable, variable);
277           m_error =
278               value.GetValueAsData(&exe_ctx, m_data, 0, GetModule().get());
279 
280           SetValueDidChange(value_type != old_value.GetValueType() ||
281                             m_value.GetScalar() != old_value.GetScalar());
282         }
283         break;
284       }
285 
286       SetValueIsValid(m_error.Success());
287     } else {
288       // could not find location, won't allow editing
289       m_resolved_value.SetContext(Value::eContextTypeInvalid, NULL);
290     }
291   }
292   return m_error.Success();
293 }
294 
295 bool ValueObjectVariable::IsInScope() {
296   const ExecutionContextRef &exe_ctx_ref = GetExecutionContextRef();
297   if (exe_ctx_ref.HasFrameRef()) {
298     ExecutionContext exe_ctx(exe_ctx_ref);
299     StackFrame *frame = exe_ctx.GetFramePtr();
300     if (frame) {
301       return m_variable_sp->IsInScope(frame);
302     } else {
303       // This ValueObject had a frame at one time, but now we
304       // can't locate it, so return false since we probably aren't
305       // in scope.
306       return false;
307     }
308   }
309   // We have a variable that wasn't tied to a frame, which
310   // means it is a global and is always in scope.
311   return true;
312 }
313 
314 lldb::ModuleSP ValueObjectVariable::GetModule() {
315   if (m_variable_sp) {
316     SymbolContextScope *sc_scope = m_variable_sp->GetSymbolContextScope();
317     if (sc_scope) {
318       return sc_scope->CalculateSymbolContextModule();
319     }
320   }
321   return lldb::ModuleSP();
322 }
323 
324 SymbolContextScope *ValueObjectVariable::GetSymbolContextScope() {
325   if (m_variable_sp)
326     return m_variable_sp->GetSymbolContextScope();
327   return NULL;
328 }
329 
330 bool ValueObjectVariable::GetDeclaration(Declaration &decl) {
331   if (m_variable_sp) {
332     decl = m_variable_sp->GetDeclaration();
333     return true;
334   }
335   return false;
336 }
337 
338 const char *ValueObjectVariable::GetLocationAsCString() {
339   if (m_resolved_value.GetContextType() == Value::eContextTypeRegisterInfo)
340     return GetLocationAsCStringImpl(m_resolved_value, m_data);
341   else
342     return ValueObject::GetLocationAsCString();
343 }
344 
345 bool ValueObjectVariable::SetValueFromCString(const char *value_str,
346                                               Status &error) {
347   if (!UpdateValueIfNeeded()) {
348     error.SetErrorString("unable to update value before writing");
349     return false;
350   }
351 
352   if (m_resolved_value.GetContextType() == Value::eContextTypeRegisterInfo) {
353     RegisterInfo *reg_info = m_resolved_value.GetRegisterInfo();
354     ExecutionContext exe_ctx(GetExecutionContextRef());
355     RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
356     RegisterValue reg_value;
357     if (!reg_info || !reg_ctx) {
358       error.SetErrorString("unable to retrieve register info");
359       return false;
360     }
361     error = reg_value.SetValueFromString(reg_info, llvm::StringRef(value_str));
362     if (error.Fail())
363       return false;
364     if (reg_ctx->WriteRegister(reg_info, reg_value)) {
365       SetNeedsUpdate();
366       return true;
367     } else {
368       error.SetErrorString("unable to write back to register");
369       return false;
370     }
371   } else
372     return ValueObject::SetValueFromCString(value_str, error);
373 }
374 
375 bool ValueObjectVariable::SetData(DataExtractor &data, Status &error) {
376   if (!UpdateValueIfNeeded()) {
377     error.SetErrorString("unable to update value before writing");
378     return false;
379   }
380 
381   if (m_resolved_value.GetContextType() == Value::eContextTypeRegisterInfo) {
382     RegisterInfo *reg_info = m_resolved_value.GetRegisterInfo();
383     ExecutionContext exe_ctx(GetExecutionContextRef());
384     RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
385     RegisterValue reg_value;
386     if (!reg_info || !reg_ctx) {
387       error.SetErrorString("unable to retrieve register info");
388       return false;
389     }
390     error = reg_value.SetValueFromData(reg_info, data, 0, true);
391     if (error.Fail())
392       return false;
393     if (reg_ctx->WriteRegister(reg_info, reg_value)) {
394       SetNeedsUpdate();
395       return true;
396     } else {
397       error.SetErrorString("unable to write back to register");
398       return false;
399     }
400   } else
401     return ValueObject::SetData(data, error);
402 }
403