1 //===-- ValueObjectVariable.cpp -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Core/ValueObjectVariable.h"
10 
11 #include "lldb/Core/Address.h"
12 #include "lldb/Core/AddressRange.h"
13 #include "lldb/Core/Module.h"
14 #include "lldb/Core/Value.h"
15 #include "lldb/Expression/DWARFExpression.h"
16 #include "lldb/Symbol/Declaration.h"
17 #include "lldb/Symbol/Function.h"
18 #include "lldb/Symbol/ObjectFile.h"
19 #include "lldb/Symbol/SymbolContext.h"
20 #include "lldb/Symbol/SymbolContextScope.h"
21 #include "lldb/Symbol/Type.h"
22 #include "lldb/Symbol/Variable.h"
23 #include "lldb/Target/ExecutionContext.h"
24 #include "lldb/Target/Process.h"
25 #include "lldb/Target/RegisterContext.h"
26 #include "lldb/Target/Target.h"
27 #include "lldb/Utility/DataExtractor.h"
28 #include "lldb/Utility/RegisterValue.h"
29 #include "lldb/Utility/Scalar.h"
30 #include "lldb/Utility/Status.h"
31 #include "lldb/lldb-private-enumerations.h"
32 #include "lldb/lldb-types.h"
33 
34 #include "llvm/ADT/StringRef.h"
35 
36 #include <assert.h>
37 #include <memory>
38 
39 namespace lldb_private {
40 class ExecutionContextScope;
41 }
42 namespace lldb_private {
43 class StackFrame;
44 }
45 namespace lldb_private {
46 struct RegisterInfo;
47 }
48 using namespace lldb_private;
49 
50 lldb::ValueObjectSP
51 ValueObjectVariable::Create(ExecutionContextScope *exe_scope,
52                             const lldb::VariableSP &var_sp) {
53   return (new ValueObjectVariable(exe_scope, var_sp))->GetSP();
54 }
55 
56 ValueObjectVariable::ValueObjectVariable(ExecutionContextScope *exe_scope,
57                                          const lldb::VariableSP &var_sp)
58     : ValueObject(exe_scope), m_variable_sp(var_sp) {
59   // Do not attempt to construct one of these objects with no variable!
60   assert(m_variable_sp.get() != nullptr);
61   m_name = var_sp->GetName();
62 }
63 
64 ValueObjectVariable::~ValueObjectVariable() {}
65 
66 CompilerType ValueObjectVariable::GetCompilerTypeImpl() {
67   Type *var_type = m_variable_sp->GetType();
68   if (var_type)
69     return var_type->GetForwardCompilerType();
70   return CompilerType();
71 }
72 
73 ConstString ValueObjectVariable::GetTypeName() {
74   Type *var_type = m_variable_sp->GetType();
75   if (var_type)
76     return var_type->GetName();
77   return ConstString();
78 }
79 
80 ConstString ValueObjectVariable::GetDisplayTypeName() {
81   Type *var_type = m_variable_sp->GetType();
82   if (var_type)
83     return var_type->GetForwardCompilerType().GetDisplayTypeName();
84   return ConstString();
85 }
86 
87 ConstString ValueObjectVariable::GetQualifiedTypeName() {
88   Type *var_type = m_variable_sp->GetType();
89   if (var_type)
90     return var_type->GetQualifiedName();
91   return ConstString();
92 }
93 
94 size_t ValueObjectVariable::CalculateNumChildren(uint32_t max) {
95   CompilerType type(GetCompilerType());
96 
97   if (!type.IsValid())
98     return 0;
99 
100   ExecutionContext exe_ctx(GetExecutionContextRef());
101   const bool omit_empty_base_classes = true;
102   auto child_count = type.GetNumChildren(omit_empty_base_classes, &exe_ctx);
103   return child_count <= max ? child_count : max;
104 }
105 
106 uint64_t ValueObjectVariable::GetByteSize() {
107   ExecutionContext exe_ctx(GetExecutionContextRef());
108 
109   CompilerType type(GetCompilerType());
110 
111   if (!type.IsValid())
112     return 0;
113 
114   return type.GetByteSize(exe_ctx.GetBestExecutionContextScope()).getValueOr(0);
115 }
116 
117 lldb::ValueType ValueObjectVariable::GetValueType() const {
118   if (m_variable_sp)
119     return m_variable_sp->GetScope();
120   return lldb::eValueTypeInvalid;
121 }
122 
123 bool ValueObjectVariable::UpdateValue() {
124   SetValueIsValid(false);
125   m_error.Clear();
126 
127   Variable *variable = m_variable_sp.get();
128   DWARFExpression &expr = variable->LocationExpression();
129 
130   if (variable->GetLocationIsConstantValueData()) {
131     // expr doesn't contain DWARF bytes, it contains the constant variable
132     // value bytes themselves...
133     if (expr.GetExpressionData(m_data))
134       m_value.SetContext(Value::eContextTypeVariable, variable);
135     else
136       m_error.SetErrorString("empty constant data");
137     // constant bytes can't be edited - sorry
138     m_resolved_value.SetContext(Value::eContextTypeInvalid, nullptr);
139   } else {
140     lldb::addr_t loclist_base_load_addr = LLDB_INVALID_ADDRESS;
141     ExecutionContext exe_ctx(GetExecutionContextRef());
142 
143     Target *target = exe_ctx.GetTargetPtr();
144     if (target) {
145       m_data.SetByteOrder(target->GetArchitecture().GetByteOrder());
146       m_data.SetAddressByteSize(target->GetArchitecture().GetAddressByteSize());
147     }
148 
149     if (expr.IsLocationList()) {
150       SymbolContext sc;
151       variable->CalculateSymbolContext(&sc);
152       if (sc.function)
153         loclist_base_load_addr =
154             sc.function->GetAddressRange().GetBaseAddress().GetLoadAddress(
155                 target);
156     }
157     Value old_value(m_value);
158     if (expr.Evaluate(&exe_ctx, nullptr, loclist_base_load_addr, nullptr,
159                       nullptr, m_value, &m_error)) {
160       m_resolved_value = m_value;
161       m_value.SetContext(Value::eContextTypeVariable, variable);
162 
163       CompilerType compiler_type = GetCompilerType();
164       if (compiler_type.IsValid())
165         m_value.SetCompilerType(compiler_type);
166 
167       Value::ValueType value_type = m_value.GetValueType();
168 
169       // The size of the buffer within m_value can be less than the size
170       // prescribed by its type. E.g. this can happen when an expression only
171       // partially describes an object (say, because it contains DW_OP_piece).
172       //
173       // In this case, grow m_value to the expected size. An alternative way to
174       // handle this is to teach Value::GetValueAsData() and ValueObjectChild
175       // not to read past the end of a host buffer, but this gets impractically
176       // complicated as a Value's host buffer may be shared with a distant
177       // ancestor or sibling in the ValueObject hierarchy.
178       //
179       // FIXME: When we grow m_value, we should represent the added bits as
180       // undefined somehow instead of as 0's.
181       if (value_type == Value::eValueTypeHostAddress &&
182           compiler_type.IsValid()) {
183         if (size_t value_buf_size = m_value.GetBuffer().GetByteSize()) {
184           size_t value_size = m_value.GetValueByteSize(&m_error, &exe_ctx);
185           if (m_error.Success() && value_buf_size < value_size)
186             m_value.ResizeData(value_size);
187         }
188       }
189 
190       Process *process = exe_ctx.GetProcessPtr();
191       const bool process_is_alive = process && process->IsAlive();
192 
193       switch (value_type) {
194       case Value::eValueTypeVector:
195       // fall through
196       case Value::eValueTypeScalar:
197         // The variable value is in the Scalar value inside the m_value. We can
198         // point our m_data right to it.
199         m_error =
200             m_value.GetValueAsData(&exe_ctx, m_data, GetModule().get());
201         break;
202 
203       case Value::eValueTypeFileAddress:
204       case Value::eValueTypeLoadAddress:
205       case Value::eValueTypeHostAddress:
206         // The DWARF expression result was an address in the inferior process.
207         // If this variable is an aggregate type, we just need the address as
208         // the main value as all child variable objects will rely upon this
209         // location and add an offset and then read their own values as needed.
210         // If this variable is a simple type, we read all data for it into
211         // m_data. Make sure this type has a value before we try and read it
212 
213         // If we have a file address, convert it to a load address if we can.
214         if (value_type == Value::eValueTypeFileAddress && process_is_alive)
215           m_value.ConvertToLoadAddress(GetModule().get(), target);
216 
217         if (!CanProvideValue()) {
218           // this value object represents an aggregate type whose children have
219           // values, but this object does not. So we say we are changed if our
220           // location has changed.
221           SetValueDidChange(value_type != old_value.GetValueType() ||
222                             m_value.GetScalar() != old_value.GetScalar());
223         } else {
224           // Copy the Value and set the context to use our Variable so it can
225           // extract read its value into m_data appropriately
226           Value value(m_value);
227           value.SetContext(Value::eContextTypeVariable, variable);
228           m_error =
229               value.GetValueAsData(&exe_ctx, m_data, GetModule().get());
230 
231           SetValueDidChange(value_type != old_value.GetValueType() ||
232                             m_value.GetScalar() != old_value.GetScalar());
233         }
234         break;
235       }
236 
237       SetValueIsValid(m_error.Success());
238     } else {
239       // could not find location, won't allow editing
240       m_resolved_value.SetContext(Value::eContextTypeInvalid, nullptr);
241     }
242   }
243   return m_error.Success();
244 }
245 
246 bool ValueObjectVariable::IsInScope() {
247   const ExecutionContextRef &exe_ctx_ref = GetExecutionContextRef();
248   if (exe_ctx_ref.HasFrameRef()) {
249     ExecutionContext exe_ctx(exe_ctx_ref);
250     StackFrame *frame = exe_ctx.GetFramePtr();
251     if (frame) {
252       return m_variable_sp->IsInScope(frame);
253     } else {
254       // This ValueObject had a frame at one time, but now we can't locate it,
255       // so return false since we probably aren't in scope.
256       return false;
257     }
258   }
259   // We have a variable that wasn't tied to a frame, which means it is a global
260   // and is always in scope.
261   return true;
262 }
263 
264 lldb::ModuleSP ValueObjectVariable::GetModule() {
265   if (m_variable_sp) {
266     SymbolContextScope *sc_scope = m_variable_sp->GetSymbolContextScope();
267     if (sc_scope) {
268       return sc_scope->CalculateSymbolContextModule();
269     }
270   }
271   return lldb::ModuleSP();
272 }
273 
274 SymbolContextScope *ValueObjectVariable::GetSymbolContextScope() {
275   if (m_variable_sp)
276     return m_variable_sp->GetSymbolContextScope();
277   return nullptr;
278 }
279 
280 bool ValueObjectVariable::GetDeclaration(Declaration &decl) {
281   if (m_variable_sp) {
282     decl = m_variable_sp->GetDeclaration();
283     return true;
284   }
285   return false;
286 }
287 
288 const char *ValueObjectVariable::GetLocationAsCString() {
289   if (m_resolved_value.GetContextType() == Value::eContextTypeRegisterInfo)
290     return GetLocationAsCStringImpl(m_resolved_value, m_data);
291   else
292     return ValueObject::GetLocationAsCString();
293 }
294 
295 bool ValueObjectVariable::SetValueFromCString(const char *value_str,
296                                               Status &error) {
297   if (!UpdateValueIfNeeded()) {
298     error.SetErrorString("unable to update value before writing");
299     return false;
300   }
301 
302   if (m_resolved_value.GetContextType() == Value::eContextTypeRegisterInfo) {
303     RegisterInfo *reg_info = m_resolved_value.GetRegisterInfo();
304     ExecutionContext exe_ctx(GetExecutionContextRef());
305     RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
306     RegisterValue reg_value;
307     if (!reg_info || !reg_ctx) {
308       error.SetErrorString("unable to retrieve register info");
309       return false;
310     }
311     error = reg_value.SetValueFromString(reg_info, llvm::StringRef(value_str));
312     if (error.Fail())
313       return false;
314     if (reg_ctx->WriteRegister(reg_info, reg_value)) {
315       SetNeedsUpdate();
316       return true;
317     } else {
318       error.SetErrorString("unable to write back to register");
319       return false;
320     }
321   } else
322     return ValueObject::SetValueFromCString(value_str, error);
323 }
324 
325 bool ValueObjectVariable::SetData(DataExtractor &data, Status &error) {
326   if (!UpdateValueIfNeeded()) {
327     error.SetErrorString("unable to update value before writing");
328     return false;
329   }
330 
331   if (m_resolved_value.GetContextType() == Value::eContextTypeRegisterInfo) {
332     RegisterInfo *reg_info = m_resolved_value.GetRegisterInfo();
333     ExecutionContext exe_ctx(GetExecutionContextRef());
334     RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
335     RegisterValue reg_value;
336     if (!reg_info || !reg_ctx) {
337       error.SetErrorString("unable to retrieve register info");
338       return false;
339     }
340     error = reg_value.SetValueFromData(reg_info, data, 0, true);
341     if (error.Fail())
342       return false;
343     if (reg_ctx->WriteRegister(reg_info, reg_value)) {
344       SetNeedsUpdate();
345       return true;
346     } else {
347       error.SetErrorString("unable to write back to register");
348       return false;
349     }
350   } else
351     return ValueObject::SetData(data, error);
352 }
353