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
Create(ExecutionContextScope * exe_scope,const lldb::VariableSP & var_sp)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
ValueObjectVariable(ExecutionContextScope * exe_scope,ValueObjectManager & manager,const lldb::VariableSP & var_sp)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
~ValueObjectVariable()66 ValueObjectVariable::~ValueObjectVariable() {}
67
GetCompilerTypeImpl()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
GetTypeName()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
GetDisplayTypeName()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
GetQualifiedTypeName()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
CalculateNumChildren(uint32_t max)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
GetByteSize()108 llvm::Optional<uint64_t> ValueObjectVariable::GetByteSize() {
109 ExecutionContext exe_ctx(GetExecutionContextRef());
110
111 CompilerType type(GetCompilerType());
112
113 if (!type.IsValid())
114 return {};
115
116 return type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
117 }
118
GetValueType() const119 lldb::ValueType ValueObjectVariable::GetValueType() const {
120 if (m_variable_sp)
121 return m_variable_sp->GetScope();
122 return lldb::eValueTypeInvalid;
123 }
124
UpdateValue()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 if (m_data.GetDataStart() && m_data.GetByteSize())
137 m_value.SetBytes(m_data.GetDataStart(), m_data.GetByteSize());
138 m_value.SetContext(Value::eContextTypeVariable, variable);
139 }
140 else
141 m_error.SetErrorString("empty constant data");
142 // constant bytes can't be edited - sorry
143 m_resolved_value.SetContext(Value::eContextTypeInvalid, nullptr);
144 } else {
145 lldb::addr_t loclist_base_load_addr = LLDB_INVALID_ADDRESS;
146 ExecutionContext exe_ctx(GetExecutionContextRef());
147
148 Target *target = exe_ctx.GetTargetPtr();
149 if (target) {
150 m_data.SetByteOrder(target->GetArchitecture().GetByteOrder());
151 m_data.SetAddressByteSize(target->GetArchitecture().GetAddressByteSize());
152 }
153
154 if (expr.IsLocationList()) {
155 SymbolContext sc;
156 variable->CalculateSymbolContext(&sc);
157 if (sc.function)
158 loclist_base_load_addr =
159 sc.function->GetAddressRange().GetBaseAddress().GetLoadAddress(
160 target);
161 }
162 Value old_value(m_value);
163 if (expr.Evaluate(&exe_ctx, nullptr, loclist_base_load_addr, nullptr,
164 nullptr, m_value, &m_error)) {
165 m_resolved_value = m_value;
166 m_value.SetContext(Value::eContextTypeVariable, variable);
167
168 CompilerType compiler_type = GetCompilerType();
169 if (compiler_type.IsValid())
170 m_value.SetCompilerType(compiler_type);
171
172 Value::ValueType value_type = m_value.GetValueType();
173
174 // The size of the buffer within m_value can be less than the size
175 // prescribed by its type. E.g. this can happen when an expression only
176 // partially describes an object (say, because it contains DW_OP_piece).
177 //
178 // In this case, grow m_value to the expected size. An alternative way to
179 // handle this is to teach Value::GetValueAsData() and ValueObjectChild
180 // not to read past the end of a host buffer, but this gets impractically
181 // complicated as a Value's host buffer may be shared with a distant
182 // ancestor or sibling in the ValueObject hierarchy.
183 //
184 // FIXME: When we grow m_value, we should represent the added bits as
185 // undefined somehow instead of as 0's.
186 if (value_type == Value::eValueTypeHostAddress &&
187 compiler_type.IsValid()) {
188 if (size_t value_buf_size = m_value.GetBuffer().GetByteSize()) {
189 size_t value_size = m_value.GetValueByteSize(&m_error, &exe_ctx);
190 if (m_error.Success() && value_buf_size < value_size)
191 m_value.ResizeData(value_size);
192 }
193 }
194
195 Process *process = exe_ctx.GetProcessPtr();
196 const bool process_is_alive = process && process->IsAlive();
197
198 switch (value_type) {
199 case Value::eValueTypeScalar:
200 // The variable value is in the Scalar value inside the m_value. We can
201 // point our m_data right to it.
202 m_error =
203 m_value.GetValueAsData(&exe_ctx, m_data, GetModule().get());
204 break;
205
206 case Value::eValueTypeFileAddress:
207 case Value::eValueTypeLoadAddress:
208 case Value::eValueTypeHostAddress:
209 // The DWARF expression result was an address in the inferior process.
210 // If this variable is an aggregate type, we just need the address as
211 // the main value as all child variable objects will rely upon this
212 // location and add an offset and then read their own values as needed.
213 // If this variable is a simple type, we read all data for it into
214 // m_data. Make sure this type has a value before we try and read it
215
216 // If we have a file address, convert it to a load address if we can.
217 if (value_type == Value::eValueTypeFileAddress && process_is_alive)
218 m_value.ConvertToLoadAddress(GetModule().get(), target);
219
220 if (!CanProvideValue()) {
221 // this value object represents an aggregate type whose children have
222 // values, but this object does not. So we say we are changed if our
223 // location has changed.
224 SetValueDidChange(value_type != old_value.GetValueType() ||
225 m_value.GetScalar() != old_value.GetScalar());
226 } else {
227 // Copy the Value and set the context to use our Variable so it can
228 // extract read its value into m_data appropriately
229 Value value(m_value);
230 value.SetContext(Value::eContextTypeVariable, variable);
231 m_error =
232 value.GetValueAsData(&exe_ctx, m_data, GetModule().get());
233
234 SetValueDidChange(value_type != old_value.GetValueType() ||
235 m_value.GetScalar() != old_value.GetScalar());
236 }
237 break;
238 }
239
240 SetValueIsValid(m_error.Success());
241 } else {
242 // could not find location, won't allow editing
243 m_resolved_value.SetContext(Value::eContextTypeInvalid, nullptr);
244 }
245 }
246
247 return m_error.Success();
248 }
249
DoUpdateChildrenAddressType(ValueObject & valobj)250 void ValueObjectVariable::DoUpdateChildrenAddressType(ValueObject &valobj) {
251 Value::ValueType value_type = valobj.GetValue().GetValueType();
252 ExecutionContext exe_ctx(GetExecutionContextRef());
253 Process *process = exe_ctx.GetProcessPtr();
254 const bool process_is_alive = process && process->IsAlive();
255 const uint32_t type_info = valobj.GetCompilerType().GetTypeInfo();
256 const bool is_pointer_or_ref =
257 (type_info & (lldb::eTypeIsPointer | lldb::eTypeIsReference)) != 0;
258
259 switch (value_type) {
260 case Value::eValueTypeFileAddress:
261 // If this type is a pointer, then its children will be considered load
262 // addresses if the pointer or reference is dereferenced, but only if
263 // the process is alive.
264 //
265 // There could be global variables like in the following code:
266 // struct LinkedListNode { Foo* foo; LinkedListNode* next; };
267 // Foo g_foo1;
268 // Foo g_foo2;
269 // LinkedListNode g_second_node = { &g_foo2, NULL };
270 // LinkedListNode g_first_node = { &g_foo1, &g_second_node };
271 //
272 // When we aren't running, we should be able to look at these variables
273 // using the "target variable" command. Children of the "g_first_node"
274 // always will be of the same address type as the parent. But children
275 // of the "next" member of LinkedListNode will become load addresses if
276 // we have a live process, or remain a file address if it was a file
277 // address.
278 if (process_is_alive && is_pointer_or_ref)
279 valobj.SetAddressTypeOfChildren(eAddressTypeLoad);
280 else
281 valobj.SetAddressTypeOfChildren(eAddressTypeFile);
282 break;
283 case Value::eValueTypeHostAddress:
284 // Same as above for load addresses, except children of pointer or refs
285 // are always load addresses. Host addresses are used to store freeze
286 // dried variables. If this type is a struct, the entire struct
287 // contents will be copied into the heap of the
288 // LLDB process, but we do not currently follow any pointers.
289 if (is_pointer_or_ref)
290 valobj.SetAddressTypeOfChildren(eAddressTypeLoad);
291 else
292 valobj.SetAddressTypeOfChildren(eAddressTypeHost);
293 break;
294 case Value::eValueTypeLoadAddress:
295 case Value::eValueTypeScalar:
296 valobj.SetAddressTypeOfChildren(eAddressTypeLoad);
297 break;
298 }
299 }
300
301
302
IsInScope()303 bool ValueObjectVariable::IsInScope() {
304 const ExecutionContextRef &exe_ctx_ref = GetExecutionContextRef();
305 if (exe_ctx_ref.HasFrameRef()) {
306 ExecutionContext exe_ctx(exe_ctx_ref);
307 StackFrame *frame = exe_ctx.GetFramePtr();
308 if (frame) {
309 return m_variable_sp->IsInScope(frame);
310 } else {
311 // This ValueObject had a frame at one time, but now we can't locate it,
312 // so return false since we probably aren't in scope.
313 return false;
314 }
315 }
316 // We have a variable that wasn't tied to a frame, which means it is a global
317 // and is always in scope.
318 return true;
319 }
320
GetModule()321 lldb::ModuleSP ValueObjectVariable::GetModule() {
322 if (m_variable_sp) {
323 SymbolContextScope *sc_scope = m_variable_sp->GetSymbolContextScope();
324 if (sc_scope) {
325 return sc_scope->CalculateSymbolContextModule();
326 }
327 }
328 return lldb::ModuleSP();
329 }
330
GetSymbolContextScope()331 SymbolContextScope *ValueObjectVariable::GetSymbolContextScope() {
332 if (m_variable_sp)
333 return m_variable_sp->GetSymbolContextScope();
334 return nullptr;
335 }
336
GetDeclaration(Declaration & decl)337 bool ValueObjectVariable::GetDeclaration(Declaration &decl) {
338 if (m_variable_sp) {
339 decl = m_variable_sp->GetDeclaration();
340 return true;
341 }
342 return false;
343 }
344
GetLocationAsCString()345 const char *ValueObjectVariable::GetLocationAsCString() {
346 if (m_resolved_value.GetContextType() == Value::eContextTypeRegisterInfo)
347 return GetLocationAsCStringImpl(m_resolved_value, m_data);
348 else
349 return ValueObject::GetLocationAsCString();
350 }
351
SetValueFromCString(const char * value_str,Status & error)352 bool ValueObjectVariable::SetValueFromCString(const char *value_str,
353 Status &error) {
354 if (!UpdateValueIfNeeded()) {
355 error.SetErrorString("unable to update value before writing");
356 return false;
357 }
358
359 if (m_resolved_value.GetContextType() == Value::eContextTypeRegisterInfo) {
360 RegisterInfo *reg_info = m_resolved_value.GetRegisterInfo();
361 ExecutionContext exe_ctx(GetExecutionContextRef());
362 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
363 RegisterValue reg_value;
364 if (!reg_info || !reg_ctx) {
365 error.SetErrorString("unable to retrieve register info");
366 return false;
367 }
368 error = reg_value.SetValueFromString(reg_info, llvm::StringRef(value_str));
369 if (error.Fail())
370 return false;
371 if (reg_ctx->WriteRegister(reg_info, reg_value)) {
372 SetNeedsUpdate();
373 return true;
374 } else {
375 error.SetErrorString("unable to write back to register");
376 return false;
377 }
378 } else
379 return ValueObject::SetValueFromCString(value_str, error);
380 }
381
SetData(DataExtractor & data,Status & error)382 bool ValueObjectVariable::SetData(DataExtractor &data, Status &error) {
383 if (!UpdateValueIfNeeded()) {
384 error.SetErrorString("unable to update value before writing");
385 return false;
386 }
387
388 if (m_resolved_value.GetContextType() == Value::eContextTypeRegisterInfo) {
389 RegisterInfo *reg_info = m_resolved_value.GetRegisterInfo();
390 ExecutionContext exe_ctx(GetExecutionContextRef());
391 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
392 RegisterValue reg_value;
393 if (!reg_info || !reg_ctx) {
394 error.SetErrorString("unable to retrieve register info");
395 return false;
396 }
397 error = reg_value.SetValueFromData(reg_info, data, 0, true);
398 if (error.Fail())
399 return false;
400 if (reg_ctx->WriteRegister(reg_info, reg_value)) {
401 SetNeedsUpdate();
402 return true;
403 } else {
404 error.SetErrorString("unable to write back to register");
405 return false;
406 }
407 } else
408 return ValueObject::SetData(data, error);
409 }
410