LLDB mainline
ValueObjectVariable.cpp
Go to the documentation of this file.
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
10
11#include "lldb/Core/Address.h"
14#include "lldb/Core/Module.h"
15#include "lldb/Core/Value.h"
21#include "lldb/Symbol/Type.h"
24#include "lldb/Target/Process.h"
26#include "lldb/Target/Target.h"
29#include "lldb/Utility/Scalar.h"
30#include "lldb/Utility/Status.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 {
42}
43namespace lldb_private {
44class StackFrame;
45}
46namespace lldb_private {
47struct RegisterInfo;
48}
49using namespace lldb_private;
50
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
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
68
70 Type *var_type = m_variable_sp->GetType();
71 if (var_type)
72 return var_type->GetForwardCompilerType();
73 return CompilerType();
74}
75
77 Type *var_type = m_variable_sp->GetType();
78 if (var_type)
79 return var_type->GetName();
80 return ConstString();
81}
82
84 Type *var_type = m_variable_sp->GetType();
85 if (var_type)
86 return var_type->GetForwardCompilerType().GetDisplayTypeName();
87 return ConstString();
88}
89
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>
100
101 if (!type.IsValid())
102 return llvm::make_error<llvm::StringError>("invalid type",
103 llvm::inconvertibleErrorCode());
104
106 const bool omit_empty_base_classes = true;
107 auto child_count = type.GetNumChildren(omit_empty_base_classes, &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() {
115
117
118 if (!type.IsValid())
119 return {};
120
121 return type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
122}
123
125 if (m_variable_sp)
126 return m_variable_sp->GetScope();
128}
129
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(m_data)) {
144 } else
145 m_error = Status::FromErrorString("empty constant data");
146 // constant bytes can't be edited - sorry
148 } else {
149 lldb::addr_t loclist_base_load_addr = LLDB_INVALID_ADDRESS;
151
152 Target *target = exe_ctx.GetTargetPtr();
153 if (target) {
156 }
157
158 if (!expr_list.IsAlwaysValidSingleExpr()) {
159 SymbolContext sc;
160 variable->CalculateSymbolContext(&sc);
161 if (sc.function)
162 loclist_base_load_addr =
164 target);
165 }
166 Value old_value(m_value);
167 llvm::Expected<Value> maybe_value = expr_list.Evaluate(
168 &exe_ctx, nullptr, loclist_base_load_addr, nullptr, nullptr);
169
170 if (maybe_value) {
171 m_value = *maybe_value;
174
175 CompilerType compiler_type = GetCompilerType();
176 if (compiler_type.IsValid())
177 m_value.SetCompilerType(compiler_type);
178
180
181 // The size of the buffer within m_value can be less than the size
182 // prescribed by its type. E.g. this can happen when an expression only
183 // partially describes an object (say, because it contains DW_OP_piece).
184 //
185 // In this case, grow m_value to the expected size. An alternative way to
186 // handle this is to teach Value::GetValueAsData() and ValueObjectChild
187 // not to read past the end of a host buffer, but this gets impractically
188 // complicated as a Value's host buffer may be shared with a distant
189 // ancestor or sibling in the ValueObject hierarchy.
190 //
191 // FIXME: When we grow m_value, we should represent the added bits as
192 // undefined somehow instead of as 0's.
193 if (value_type == Value::ValueType::HostAddress &&
194 compiler_type.IsValid()) {
195 if (size_t value_buf_size = m_value.GetBuffer().GetByteSize()) {
196 size_t value_size = m_value.GetValueByteSize(&m_error, &exe_ctx);
197 if (m_error.Success() && value_buf_size < value_size)
198 m_value.ResizeData(value_size);
199 }
200 }
201
202 Process *process = exe_ctx.GetProcessPtr();
203 const bool process_is_alive = process && process->IsAlive();
204
205 switch (value_type) {
207 m_error = Status::FromErrorString("invalid value");
208 break;
210 // The variable value is in the Scalar value inside the m_value. We can
211 // point our m_data right to it.
212 m_error = m_value.GetValueAsData(&exe_ctx, m_data, GetModule().get());
213 break;
214
218 // The DWARF expression result was an address in the inferior process.
219 // If this variable is an aggregate type, we just need the address as
220 // the main value as all child variable objects will rely upon this
221 // location and add an offset and then read their own values as needed.
222 // If this variable is a simple type, we read all data for it into
223 // m_data. Make sure this type has a value before we try and read it
224
225 // If we have a file address, convert it to a load address if we can.
226 if (value_type == Value::ValueType::FileAddress && process_is_alive)
227 m_value.ConvertToLoadAddress(GetModule().get(), target);
228
229 if (!CanProvideValue()) {
230 // this value object represents an aggregate type whose children have
231 // values, but this object does not. So we say we are changed if our
232 // location has changed.
233 SetValueDidChange(value_type != old_value.GetValueType() ||
234 m_value.GetScalar() != old_value.GetScalar());
235 } else {
236 // Copy the Value and set the context to use our Variable so it can
237 // extract read its value into m_data appropriately
238 Value value(m_value);
240 m_error = value.GetValueAsData(&exe_ctx, m_data, GetModule().get());
241
242 SetValueDidChange(value_type != old_value.GetValueType() ||
243 m_value.GetScalar() != old_value.GetScalar());
244 }
245 break;
246 }
247
249 } else {
250 m_error = Status::FromError(maybe_value.takeError());
251 // could not find location, won't allow editing
253 }
254 }
255
256 return m_error.Success();
257}
258
260 Value::ValueType value_type = valobj.GetValue().GetValueType();
262 Process *process = exe_ctx.GetProcessPtr();
263 const bool process_is_alive = process && process->IsAlive();
264 const uint32_t type_info = valobj.GetCompilerType().GetTypeInfo();
265 const bool is_pointer_or_ref =
266 (type_info & (lldb::eTypeIsPointer | lldb::eTypeIsReference)) != 0;
267
268 switch (value_type) {
270 break;
272 // If this type is a pointer, then its children will be considered load
273 // addresses if the pointer or reference is dereferenced, but only if
274 // the process is alive.
275 //
276 // There could be global variables like in the following code:
277 // struct LinkedListNode { Foo* foo; LinkedListNode* next; };
278 // Foo g_foo1;
279 // Foo g_foo2;
280 // LinkedListNode g_second_node = { &g_foo2, NULL };
281 // LinkedListNode g_first_node = { &g_foo1, &g_second_node };
282 //
283 // When we aren't running, we should be able to look at these variables
284 // using the "target variable" command. Children of the "g_first_node"
285 // always will be of the same address type as the parent. But children
286 // of the "next" member of LinkedListNode will become load addresses if
287 // we have a live process, or remain a file address if it was a file
288 // address.
289 if (process_is_alive && is_pointer_or_ref)
291 else
293 break;
295 // Same as above for load addresses, except children of pointer or refs
296 // are always load addresses. Host addresses are used to store freeze
297 // dried variables. If this type is a struct, the entire struct
298 // contents will be copied into the heap of the
299 // LLDB process, but we do not currently follow any pointers.
300 if (is_pointer_or_ref)
302 else
304 break;
308 break;
309 }
310}
311
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
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
341 if (m_variable_sp)
342 return m_variable_sp->GetSymbolContextScope();
343 return nullptr;
344}
345
347 if (m_variable_sp) {
348 decl = m_variable_sp->GetDeclaration();
349 return true;
350 }
351 return false;
352}
353
357 else
359}
360
362 Status &error) {
363 if (!UpdateValueIfNeeded()) {
364 error = Status::FromErrorString("unable to update value before writing");
365 return false;
366 }
367
371 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
372 RegisterValue reg_value;
373 if (!reg_info || !reg_ctx) {
374 error = Status::FromErrorString("unable to retrieve register info");
375 return false;
376 }
377 error = reg_value.SetValueFromString(reg_info, llvm::StringRef(value_str));
378 if (error.Fail())
379 return false;
380 if (reg_ctx->WriteRegister(reg_info, reg_value)) {
382 return true;
383 } else {
384 error = Status::FromErrorString("unable to write back to register");
385 return false;
386 }
387 } else
388 return ValueObject::SetValueFromCString(value_str, error);
389}
390
392 if (!UpdateValueIfNeeded()) {
393 error = Status::FromErrorString("unable to update value before writing");
394 return false;
395 }
396
400 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
401 RegisterValue reg_value;
402 if (!reg_info || !reg_ctx) {
403 error = Status::FromErrorString("unable to retrieve register info");
404 return false;
405 }
406 error = reg_value.SetValueFromData(*reg_info, data, 0, true);
407 if (error.Fail())
408 return false;
409 if (reg_ctx->WriteRegister(reg_info, reg_value)) {
411 return true;
412 } else {
413 error = Status::FromErrorString("unable to write back to register");
414 return false;
415 }
416 } else
417 return ValueObject::SetData(data, error);
418}
static llvm::raw_ostream & error(Stream &strm)
Address & GetBaseAddress()
Get accessor for the base address of the range.
Definition: AddressRange.h:211
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition: Address.cpp:313
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition: ArchSpec.cpp:709
lldb::ByteOrder GetByteOrder() const
Returns the byte order for the architecture specification.
Definition: ArchSpec.cpp:756
static std::shared_ptr< ClusterManager > Create()
Definition: SharedCluster.h:24
Generic representation of a type in a programming language.
Definition: CompilerType.h:36
std::optional< uint64_t > GetByteSize(ExecutionContextScope *exe_scope) const
Return the size of the type in bytes.
ConstString GetDisplayTypeName() const
uint32_t GetTypeInfo(CompilerType *pointee_or_element_compiler_type=nullptr) const
llvm::Expected< uint32_t > GetNumChildren(bool omit_empty_base_classes, const ExecutionContext *exe_ctx) const
A uniqued constant string class.
Definition: ConstString.h:40
"lldb/Expression/DWARFExpressionList.h" Encapsulates a range map from file address range to a single ...
llvm::Expected< Value > Evaluate(ExecutionContext *exe_ctx, RegisterContext *reg_ctx, lldb::addr_t func_load_addr, const Value *initial_value_ptr, const Value *object_address_ptr) const
bool GetExpressionData(DataExtractor &data, lldb::addr_t func_load_addr=LLDB_INVALID_ADDRESS, lldb::addr_t file_addr=0) const
Get the expression data at the file address.
lldb::offset_t GetByteSize() const override
Get the number of bytes in the data buffer.
An data extractor class.
Definition: DataExtractor.h:48
void SetByteOrder(lldb::ByteOrder byte_order)
Set the byte_order value.
uint64_t GetByteSize() const
Get the number of bytes contained in this object.
const uint8_t * GetDataStart() const
Get the data start pointer.
void SetAddressByteSize(uint32_t addr_size)
Set the address byte size.
A class that describes the declaration location of a lldb object.
Definition: Declaration.h:24
Execution context objects refer to objects in the execution of the program that is being debugged.
bool HasFrameRef() const
Returns true if this object has a weak reference to a frame.
"lldb/Target/ExecutionContextScope.h" Inherit from this if your object can reconstruct its execution ...
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
ExecutionContextScope * GetBestExecutionContextScope() const
StackFrame * GetFramePtr() const
Returns a pointer to the frame object.
Target * GetTargetPtr() const
Returns a pointer to the target object.
Process * GetProcessPtr() const
Returns a pointer to the process object.
RegisterContext * GetRegisterContext() const
const AddressRange & GetAddressRange()
DEPRECATED: Use GetAddressRanges instead.
Definition: Function.h:448
A plug-in interface definition class for debugging a process.
Definition: Process.h:343
virtual bool IsAlive()
Check if a process is still alive.
Definition: Process.cpp:1100
virtual bool WriteRegister(const RegisterInfo *reg_info, const RegisterValue &reg_value)=0
Status SetValueFromString(const RegisterInfo *reg_info, llvm::StringRef value_str)
Status SetValueFromData(const RegisterInfo &reg_info, DataExtractor &data, lldb::offset_t offset, bool partial_data_ok)
This base class provides an interface to stack frames.
Definition: StackFrame.h:44
An error handling class.
Definition: Status.h:115
void Clear()
Clear the object state.
Definition: Status.cpp:215
static Status FromErrorString(const char *str)
Definition: Status.h:138
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition: Status.cpp:137
bool Success() const
Test for success condition.
Definition: Status.cpp:280
"lldb/Symbol/SymbolContextScope.h" Inherit from this if your object is part of a symbol context and c...
virtual lldb::ModuleSP CalculateSymbolContextModule()
Defines a symbol context baton that can be handed other debug core functions.
Definition: SymbolContext.h:34
Function * function
The Function for a given query.
const ArchSpec & GetArchitecture() const
Definition: Target.h:1039
CompilerType GetForwardCompilerType()
Definition: Type.cpp:774
ConstString GetName()
Definition: Type.cpp:440
ConstString GetQualifiedName()
Definition: Type.cpp:779
A ValueObject that contains a root variable that may or may not have children.
ValueObjectVariable(ExecutionContextScope *exe_scope, ValueObjectManager &manager, const lldb::VariableSP &var_sp)
lldb::ValueType GetValueType() const override
SymbolContextScope * GetSymbolContextScope() override
lldb::ModuleSP GetModule() override
Return the module associated with this value object in case the value is from an executable file and ...
void DoUpdateChildrenAddressType(ValueObject &valobj) override
ConstString GetDisplayTypeName() override
bool SetData(DataExtractor &data, Status &error) override
const char * GetLocationAsCString() override
static lldb::ValueObjectSP Create(ExecutionContextScope *exe_scope, const lldb::VariableSP &var_sp)
std::optional< uint64_t > GetByteSize() override
ConstString GetQualifiedTypeName() override
bool SetValueFromCString(const char *value_str, Status &error) override
lldb::VariableSP m_variable_sp
The variable that this value object is based upon.
llvm::Expected< uint32_t > CalculateNumChildren(uint32_t max) override
Should only be called by ValueObject::GetNumChildren().
bool GetDeclaration(Declaration &decl) override
CompilerType GetCompilerTypeImpl() override
void SetValueIsValid(bool valid)
Definition: ValueObject.h:1059
CompilerType GetCompilerType()
Definition: ValueObject.h:352
Status m_error
An error object that can describe any errors that occur when updating values.
Definition: ValueObject.h:930
DataExtractor m_data
A data extractor that can be used to extract the value.
Definition: ValueObject.h:926
void SetValueDidChange(bool value_changed)
Definition: ValueObject.h:1055
bool UpdateValueIfNeeded(bool update_format=true)
virtual const char * GetLocationAsCString()
Definition: ValueObject.h:522
virtual bool SetValueFromCString(const char *value_str, Status &error)
virtual bool SetData(DataExtractor &data, Status &error)
ConstString m_name
The name of this object.
Definition: ValueObject.h:924
const char * GetLocationAsCStringImpl(const Value &value, const DataExtractor &data)
const ExecutionContextRef & GetExecutionContextRef() const
Definition: ValueObject.h:330
virtual bool CanProvideValue()
const Value & GetValue() const
Definition: ValueObject.h:511
void SetAddressTypeOfChildren(AddressType at)
Definition: ValueObject.h:834
const Scalar & GetScalar() const
Definition: Value.h:112
Status GetValueAsData(ExecutionContext *exe_ctx, DataExtractor &data, Module *module)
Definition: Value.cpp:315
RegisterInfo * GetRegisterInfo() const
Definition: Value.cpp:140
ValueType
Type that describes Value::m_value.
Definition: Value.h:41
@ HostAddress
A host address value (for memory in the process that < A is using liblldb).
@ FileAddress
A file address value.
@ LoadAddress
A load address value.
@ Scalar
A raw scalar value.
ValueType GetValueType() const
Definition: Value.cpp:109
void SetCompilerType(const CompilerType &compiler_type)
Definition: Value.cpp:268
void SetContext(ContextType context_type, void *p)
Definition: Value.h:96
DataBufferHeap & GetBuffer()
Definition: Value.h:120
uint64_t GetValueByteSize(Status *error_ptr, ExecutionContext *exe_ctx)
Definition: Value.cpp:211
@ Variable
lldb_private::Variable *.
@ RegisterInfo
RegisterInfo * (can be a scalar or a vector register).
ContextType GetContextType() const
Definition: Value.h:87
void ConvertToLoadAddress(Module *module, Target *target)
Convert this value's file address to a load address, if possible.
Definition: Value.cpp:668
size_t ResizeData(size_t len)
Definition: Value.cpp:190
void SetBytes(const void *bytes, int len)
Definition: Value.cpp:88
DWARFExpressionList & LocationExpressionList()
Definition: Variable.h:76
void CalculateSymbolContext(SymbolContext *sc)
Definition: Variable.cpp:208
bool GetLocationIsConstantValueData() const
Definition: Variable.h:96
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:82
A class that represents a running process on the host machine.
@ eAddressTypeFile
Address is an address as found in an object or symbol file.
@ eAddressTypeLoad
Address is an address as in the current target inferior process.
@ eAddressTypeHost
Address is an address in the process that is running this code.
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
Definition: lldb-forward.h:484
std::shared_ptr< lldb_private::Variable > VariableSP
Definition: lldb-forward.h:486
uint64_t addr_t
Definition: lldb-types.h:80
std::shared_ptr< lldb_private::Module > ModuleSP
Definition: lldb-forward.h:373
@ eValueTypeInvalid
Every register is described in detail including its name, alternate name (optional),...