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