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

source code of lldb/source/Core/ValueObjectVariable.cpp