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   auto manager_sp = ValueObjectManager::Create();
54   return (new ValueObjectVariable(exe_scope, *manager_sp, var_sp))->GetSP();
55 }
56 
57 ValueObjectVariable::ValueObjectVariable(ExecutionContextScope *exe_scope,
58                                          ValueObjectManager &manager,
59                                          const lldb::VariableSP &var_sp)
60     : ValueObject(exe_scope, manager), m_variable_sp(var_sp) {
61   // Do not attempt to construct one of these objects with no variable!
62   assert(m_variable_sp.get() != nullptr);
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   ExecutionContext exe_ctx(GetExecutionContextRef());
103   const bool omit_empty_base_classes = true;
104   auto child_count = type.GetNumChildren(omit_empty_base_classes, &exe_ctx);
105   return child_count <= max ? child_count : max;
106 }
107 
108 uint64_t ValueObjectVariable::GetByteSize() {
109   ExecutionContext exe_ctx(GetExecutionContextRef());
110 
111   CompilerType type(GetCompilerType());
112 
113   if (!type.IsValid())
114     return 0;
115 
116   return type.GetByteSize(exe_ctx.GetBestExecutionContextScope()).getValueOr(0);
117 }
118 
119 lldb::ValueType ValueObjectVariable::GetValueType() const {
120   if (m_variable_sp)
121     return m_variable_sp->GetScope();
122   return lldb::eValueTypeInvalid;
123 }
124 
125 bool ValueObjectVariable::UpdateValue() {
126   SetValueIsValid(false);
127   m_error.Clear();
128 
129   Variable *variable = m_variable_sp.get();
130   DWARFExpression &expr = variable->LocationExpression();
131 
132   if (variable->GetLocationIsConstantValueData()) {
133     // expr doesn't contain DWARF bytes, it contains the constant variable
134     // value bytes themselves...
135     if (expr.GetExpressionData(m_data))
136       m_value.SetContext(Value::eContextTypeVariable, variable);
137     else
138       m_error.SetErrorString("empty constant data");
139     // constant bytes can't be edited - sorry
140     m_resolved_value.SetContext(Value::eContextTypeInvalid, nullptr);
141   } else {
142     lldb::addr_t loclist_base_load_addr = LLDB_INVALID_ADDRESS;
143     ExecutionContext exe_ctx(GetExecutionContextRef());
144 
145     Target *target = exe_ctx.GetTargetPtr();
146     if (target) {
147       m_data.SetByteOrder(target->GetArchitecture().GetByteOrder());
148       m_data.SetAddressByteSize(target->GetArchitecture().GetAddressByteSize());
149     }
150 
151     if (expr.IsLocationList()) {
152       SymbolContext sc;
153       variable->CalculateSymbolContext(&sc);
154       if (sc.function)
155         loclist_base_load_addr =
156             sc.function->GetAddressRange().GetBaseAddress().GetLoadAddress(
157                 target);
158     }
159     Value old_value(m_value);
160     if (expr.Evaluate(&exe_ctx, nullptr, loclist_base_load_addr, nullptr,
161                       nullptr, m_value, &m_error)) {
162       m_resolved_value = m_value;
163       m_value.SetContext(Value::eContextTypeVariable, variable);
164 
165       CompilerType compiler_type = GetCompilerType();
166       if (compiler_type.IsValid())
167         m_value.SetCompilerType(compiler_type);
168 
169       Value::ValueType value_type = m_value.GetValueType();
170 
171       // The size of the buffer within m_value can be less than the size
172       // prescribed by its type. E.g. this can happen when an expression only
173       // partially describes an object (say, because it contains DW_OP_piece).
174       //
175       // In this case, grow m_value to the expected size. An alternative way to
176       // handle this is to teach Value::GetValueAsData() and ValueObjectChild
177       // not to read past the end of a host buffer, but this gets impractically
178       // complicated as a Value's host buffer may be shared with a distant
179       // ancestor or sibling in the ValueObject hierarchy.
180       //
181       // FIXME: When we grow m_value, we should represent the added bits as
182       // undefined somehow instead of as 0's.
183       if (value_type == Value::eValueTypeHostAddress &&
184           compiler_type.IsValid()) {
185         if (size_t value_buf_size = m_value.GetBuffer().GetByteSize()) {
186           size_t value_size = m_value.GetValueByteSize(&m_error, &exe_ctx);
187           if (m_error.Success() && value_buf_size < value_size)
188             m_value.ResizeData(value_size);
189         }
190       }
191 
192       Process *process = exe_ctx.GetProcessPtr();
193       const bool process_is_alive = process && process->IsAlive();
194 
195       switch (value_type) {
196       case Value::eValueTypeVector:
197       // fall through
198       case Value::eValueTypeScalar:
199         // The variable value is in the Scalar value inside the m_value. We can
200         // point our m_data right to it.
201         m_error =
202             m_value.GetValueAsData(&exe_ctx, m_data, GetModule().get());
203         break;
204 
205       case Value::eValueTypeFileAddress:
206       case Value::eValueTypeLoadAddress:
207       case Value::eValueTypeHostAddress:
208         // The DWARF expression result was an address in the inferior process.
209         // If this variable is an aggregate type, we just need the address as
210         // the main value as all child variable objects will rely upon this
211         // location and add an offset and then read their own values as needed.
212         // If this variable is a simple type, we read all data for it into
213         // m_data. Make sure this type has a value before we try and read it
214 
215         // If we have a file address, convert it to a load address if we can.
216         if (value_type == Value::eValueTypeFileAddress && process_is_alive)
217           m_value.ConvertToLoadAddress(GetModule().get(), target);
218 
219         if (!CanProvideValue()) {
220           // this value object represents an aggregate type whose children have
221           // values, but this object does not. So we say we are changed if our
222           // location has changed.
223           SetValueDidChange(value_type != old_value.GetValueType() ||
224                             m_value.GetScalar() != old_value.GetScalar());
225         } else {
226           // Copy the Value and set the context to use our Variable so it can
227           // extract read its value into m_data appropriately
228           Value value(m_value);
229           value.SetContext(Value::eContextTypeVariable, variable);
230           m_error =
231               value.GetValueAsData(&exe_ctx, m_data, GetModule().get());
232 
233           SetValueDidChange(value_type != old_value.GetValueType() ||
234                             m_value.GetScalar() != old_value.GetScalar());
235         }
236         break;
237       }
238 
239       SetValueIsValid(m_error.Success());
240     } else {
241       // could not find location, won't allow editing
242       m_resolved_value.SetContext(Value::eContextTypeInvalid, nullptr);
243     }
244   }
245   return m_error.Success();
246 }
247 
248 bool ValueObjectVariable::IsInScope() {
249   const ExecutionContextRef &exe_ctx_ref = GetExecutionContextRef();
250   if (exe_ctx_ref.HasFrameRef()) {
251     ExecutionContext exe_ctx(exe_ctx_ref);
252     StackFrame *frame = exe_ctx.GetFramePtr();
253     if (frame) {
254       return m_variable_sp->IsInScope(frame);
255     } else {
256       // This ValueObject had a frame at one time, but now we can't locate it,
257       // so return false since we probably aren't in scope.
258       return false;
259     }
260   }
261   // We have a variable that wasn't tied to a frame, which means it is a global
262   // and is always in scope.
263   return true;
264 }
265 
266 lldb::ModuleSP ValueObjectVariable::GetModule() {
267   if (m_variable_sp) {
268     SymbolContextScope *sc_scope = m_variable_sp->GetSymbolContextScope();
269     if (sc_scope) {
270       return sc_scope->CalculateSymbolContextModule();
271     }
272   }
273   return lldb::ModuleSP();
274 }
275 
276 SymbolContextScope *ValueObjectVariable::GetSymbolContextScope() {
277   if (m_variable_sp)
278     return m_variable_sp->GetSymbolContextScope();
279   return nullptr;
280 }
281 
282 bool ValueObjectVariable::GetDeclaration(Declaration &decl) {
283   if (m_variable_sp) {
284     decl = m_variable_sp->GetDeclaration();
285     return true;
286   }
287   return false;
288 }
289 
290 const char *ValueObjectVariable::GetLocationAsCString() {
291   if (m_resolved_value.GetContextType() == Value::eContextTypeRegisterInfo)
292     return GetLocationAsCStringImpl(m_resolved_value, m_data);
293   else
294     return ValueObject::GetLocationAsCString();
295 }
296 
297 bool ValueObjectVariable::SetValueFromCString(const char *value_str,
298                                               Status &error) {
299   if (!UpdateValueIfNeeded()) {
300     error.SetErrorString("unable to update value before writing");
301     return false;
302   }
303 
304   if (m_resolved_value.GetContextType() == Value::eContextTypeRegisterInfo) {
305     RegisterInfo *reg_info = m_resolved_value.GetRegisterInfo();
306     ExecutionContext exe_ctx(GetExecutionContextRef());
307     RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
308     RegisterValue reg_value;
309     if (!reg_info || !reg_ctx) {
310       error.SetErrorString("unable to retrieve register info");
311       return false;
312     }
313     error = reg_value.SetValueFromString(reg_info, llvm::StringRef(value_str));
314     if (error.Fail())
315       return false;
316     if (reg_ctx->WriteRegister(reg_info, reg_value)) {
317       SetNeedsUpdate();
318       return true;
319     } else {
320       error.SetErrorString("unable to write back to register");
321       return false;
322     }
323   } else
324     return ValueObject::SetValueFromCString(value_str, error);
325 }
326 
327 bool ValueObjectVariable::SetData(DataExtractor &data, Status &error) {
328   if (!UpdateValueIfNeeded()) {
329     error.SetErrorString("unable to update value before writing");
330     return false;
331   }
332 
333   if (m_resolved_value.GetContextType() == Value::eContextTypeRegisterInfo) {
334     RegisterInfo *reg_info = m_resolved_value.GetRegisterInfo();
335     ExecutionContext exe_ctx(GetExecutionContextRef());
336     RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
337     RegisterValue reg_value;
338     if (!reg_info || !reg_ctx) {
339       error.SetErrorString("unable to retrieve register info");
340       return false;
341     }
342     error = reg_value.SetValueFromData(reg_info, data, 0, true);
343     if (error.Fail())
344       return false;
345     if (reg_ctx->WriteRegister(reg_info, reg_value)) {
346       SetNeedsUpdate();
347       return true;
348     } else {
349       error.SetErrorString("unable to write back to register");
350       return false;
351     }
352   } else
353     return ValueObject::SetData(data, error);
354 }
355