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"
25#include "lldb/Target/Process.h"
27#include "lldb/Target/Target.h"
30#include "lldb/Utility/Scalar.h"
31#include "lldb/Utility/Status.h"
33#include "lldb/lldb-types.h"
34
35#include "llvm/ADT/StringRef.h"
36#include "llvm/Support/Error.h"
37
38#include <cassert>
39#include <memory>
40#include <optional>
41
42namespace lldb_private {
44}
45namespace lldb_private {
46class StackFrame;
47}
48namespace lldb_private {
49struct RegisterInfo;
50}
51using namespace lldb_private;
52
55 const lldb::VariableSP &var_sp) {
56 auto manager_sp = ValueObjectManager::Create();
57 return (new ValueObjectVariable(exe_scope, *manager_sp, var_sp))->GetSP();
58}
59
61 ValueObjectManager &manager,
62 const lldb::VariableSP &var_sp)
63 : ValueObject(exe_scope, manager), m_variable_sp(var_sp) {
64 // Do not attempt to construct one of these objects with no variable!
65 assert(m_variable_sp.get() != nullptr);
66 m_name = var_sp->GetName();
67}
68
70
72 Type *var_type = m_variable_sp->GetType();
73 if (var_type)
74 return var_type->GetForwardCompilerType();
75 return CompilerType();
76}
77
79 Type *var_type = m_variable_sp->GetType();
80 if (var_type)
81 return var_type->GetName();
82 return ConstString();
83}
84
86 Type *var_type = m_variable_sp->GetType();
87 if (var_type)
88 return var_type->GetForwardCompilerType().GetDisplayTypeName();
89 return ConstString();
90}
91
93 Type *var_type = m_variable_sp->GetType();
94 if (var_type)
95 return var_type->GetQualifiedName();
96 return ConstString();
97}
98
99llvm::Expected<uint32_t>
102
103 if (!type.IsValid())
104 return llvm::createStringError("invalid type");
105
107 const bool omit_empty_base_classes = true;
108 auto child_count = type.GetNumChildren(omit_empty_base_classes, &exe_ctx);
109 if (!child_count)
110 return child_count;
111 return *child_count <= max ? *child_count : max;
112}
113
114llvm::Expected<uint64_t> ValueObjectVariable::GetByteSize() {
116
118 return type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
119}
120
126
128 SetValueIsValid(false);
129 m_error.Clear();
130
131 Variable *variable = m_variable_sp.get();
132 DWARFExpressionList &expr_list = variable->LocationExpressionList();
133
134 if (variable->GetLocationIsConstantValueData()) {
135 // expr doesn't contain DWARF bytes, it contains the constant variable
136 // value bytes themselves...
137 if (expr_list.GetExpressionData(m_data)) {
138 if (m_data.GetDataStart() && m_data.GetByteSize())
139 m_value.SetBytes(m_data.GetDataStart(), m_data.GetByteSize());
140 m_value.SetContext(Value::ContextType::Variable, variable);
141 } else if (HasNoStorage()) {
142 m_value.SetCompilerType(GetCompilerType());
143 } else
144 m_error = Status::FromErrorString("empty constant data");
145 // 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) {
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);
161 if (sc.function)
162 loclist_base_load_addr =
163 sc.function->GetAddress().GetLoadAddress(target);
164 }
165 Value old_value(m_value);
166 llvm::Expected<Value> maybe_value = expr_list.Evaluate(
167 &exe_ctx, nullptr, loclist_base_load_addr, nullptr, nullptr);
168
169 if (maybe_value) {
170 m_value = *maybe_value;
173 expr_list.IsImplicit(&exe_ctx, nullptr, loclist_base_load_addr);
174 m_value.SetContext(Value::ContextType::Variable, variable);
175
176 CompilerType compiler_type = GetCompilerType();
177 if (compiler_type.IsValid()) {
178 m_value.SetCompilerType(compiler_type);
179
180 if (lldb::ProcessSP process_sp = GetProcessSP())
181 if (LanguageRuntime *runtime = process_sp->GetLanguageRuntime(
182 compiler_type.GetMinimumLanguage()))
183 if (llvm::Error err =
184 runtime->FixupVariableLocation(*variable, m_value)) {
185 m_error = Status::FromError(std::move(err));
186 return false;
187 }
188 }
189
190 Value::ValueType value_type = m_value.GetValueType();
191
192 // The size of the buffer within m_value can be less than the size
193 // prescribed by its type. E.g. this can happen when an expression only
194 // partially describes an object (say, because it contains DW_OP_piece).
195 //
196 // In this case, grow m_value to the expected size. An alternative way to
197 // handle this is to teach Value::GetValueAsData() and ValueObjectChild
198 // not to read past the end of a host buffer, but this gets impractically
199 // complicated as a Value's host buffer may be shared with a distant
200 // ancestor or sibling in the ValueObject hierarchy.
201 //
202 // FIXME: When we grow m_value, we should represent the added bits as
203 // undefined somehow instead of as 0's.
204 if (value_type == Value::ValueType::HostAddress &&
205 compiler_type.IsValid()) {
206 if (size_t value_buf_size = m_value.GetBuffer().GetByteSize()) {
207 size_t value_size = m_value.GetValueByteSize(&m_error, &exe_ctx);
208 if (m_error.Success() && value_buf_size < value_size)
209 m_value.ResizeData(value_size);
210 }
211 }
212
213 Process *process = exe_ctx.GetProcessPtr();
214 const bool process_is_alive = process && process->IsAlive();
215
216 switch (value_type) {
218 m_error = Status::FromErrorString("invalid value");
219 break;
221 // The variable value is in the Scalar value inside the m_value. We can
222 // point our m_data right to it.
223 m_error = m_value.GetValueAsData(&exe_ctx, m_data, GetModule().get());
224 break;
225
229 // The DWARF expression result was an address in the inferior process.
230 // If this variable is an aggregate type, we just need the address as
231 // the main value as all child variable objects will rely upon this
232 // location and add an offset and then read their own values as needed.
233 // If this variable is a simple type, we read all data for it into
234 // m_data. Make sure this type has a value before we try and read it
235
236 // If we have a file address, convert it to a load address if we can.
237 if (value_type == Value::ValueType::FileAddress && process_is_alive)
238 m_value.ConvertToLoadAddress(GetModule().get(), target);
239
240 if (!CanProvideValue()) {
241 // this value object represents an aggregate type whose children have
242 // values, but this object does not. So we say we are changed if our
243 // location has changed.
244 SetValueDidChange(value_type != old_value.GetValueType() ||
245 m_value.GetScalar() != old_value.GetScalar());
246 } else {
247 // Copy the Value and set the context to use our Variable so it can
248 // extract read its value into m_data appropriately
249 Value value(m_value);
251 m_error = value.GetValueAsData(&exe_ctx, m_data, GetModule().get());
252
253 SetValueDidChange(value_type != old_value.GetValueType() ||
254 m_value.GetScalar() != old_value.GetScalar());
255 }
256 break;
257 }
258
259 SetValueIsValid(m_error.Success());
260 } else if (HasNoStorage()) {
261 // A variable whose type occupies no memory needs no location.
262 llvm::consumeError(maybe_value.takeError());
263 m_value.SetCompilerType(GetCompilerType());
266 } else {
267 m_error = Status::FromError(maybe_value.takeError());
268 // could not find location, won't allow editing
271 }
272 }
273
274 return m_error.Success();
275}
276
278 Value::ValueType value_type = valobj.GetValue().GetValueType();
280 Process *process = exe_ctx.GetProcessPtr();
281 const bool process_is_alive = process && process->IsAlive();
282 const uint32_t type_info = valobj.GetCompilerType().GetTypeInfo();
283 const bool is_pointer_or_ref =
284 (type_info & (lldb::eTypeIsPointer | lldb::eTypeIsReference)) != 0;
285
286 switch (value_type) {
288 break;
290 // If this type is a pointer, then its children will be considered load
291 // addresses if the pointer or reference is dereferenced, but only if
292 // the process is alive.
293 //
294 // There could be global variables like in the following code:
295 // struct LinkedListNode { Foo* foo; LinkedListNode* next; };
296 // Foo g_foo1;
297 // Foo g_foo2;
298 // LinkedListNode g_second_node = { &g_foo2, NULL };
299 // LinkedListNode g_first_node = { &g_foo1, &g_second_node };
300 //
301 // When we aren't running, we should be able to look at these variables
302 // using the "target variable" command. Children of the "g_first_node"
303 // always will be of the same address type as the parent. But children
304 // of the "next" member of LinkedListNode will become load addresses if
305 // we have a live process, or remain a file address if it was a file
306 // address.
307 if (process_is_alive && is_pointer_or_ref)
309 else
311 break;
313 // Same as above for load addresses, except children of pointer or refs
314 // are always load addresses. Host addresses are used to store freeze
315 // dried variables. If this type is a struct, the entire struct
316 // contents will be copied into the heap of the
317 // LLDB process, but we do not currently follow any pointers.
318 if (is_pointer_or_ref)
320 else
322 break;
326 break;
327 }
328}
329
331 const ExecutionContextRef &exe_ctx_ref = GetExecutionContextRef();
332 if (exe_ctx_ref.HasFrameRef()) {
333 ExecutionContext exe_ctx(exe_ctx_ref);
334 StackFrame *frame = exe_ctx.GetFramePtr();
335 if (frame) {
336 return m_variable_sp->IsInScope(frame);
337 } else {
338 // This ValueObject had a frame at one time, but now we can't locate it,
339 // so return false since we probably aren't in scope.
340 return false;
341 }
342 }
343 // We have a variable that wasn't tied to a frame, which means it is a global
344 // and is always in scope.
345 return true;
346}
347
349 if (m_variable_sp) {
350 SymbolContextScope *sc_scope = m_variable_sp->GetSymbolContextScope();
351 if (sc_scope) {
352 return sc_scope->CalculateSymbolContextModule();
353 }
354 }
355 return lldb::ModuleSP();
356}
357
359 if (m_variable_sp)
360 return m_variable_sp->GetSymbolContextScope();
361 return nullptr;
362}
363
365 if (m_variable_sp) {
366 decl = m_variable_sp->GetDeclaration();
367 return true;
368 }
369 return false;
370}
371
378
380 // Refresh the resolved location so m_resolved_value_is_implicit is current.
383 return llvm::createStringError("variable is not in a writable location");
385}
386
388 Status &error) {
389 if (!UpdateValueIfNeeded()) {
390 error = Status::FromErrorString("unable to update value before writing");
391 return false;
392 }
393
394 if (llvm::Error err = CanSetValue()) {
395 error = Status::FromError(std::move(err));
396 return false;
397 }
398
399 if (m_resolved_value.GetContextType() == Value::ContextType::RegisterInfo) {
400 RegisterInfo *reg_info = m_resolved_value.GetRegisterInfo();
402 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
403 RegisterValue reg_value;
404 if (!reg_info || !reg_ctx) {
405 error = Status::FromErrorString("unable to retrieve register info");
406 return false;
407 }
408 error = reg_value.SetValueFromString(reg_info, llvm::StringRef(value_str));
409 if (error.Fail())
410 return false;
411 if (reg_ctx->WriteRegister(reg_info, reg_value)) {
413 return true;
414 } else {
415 error = Status::FromErrorString("unable to write back to register");
416 return false;
417 }
418 } else
419 return ValueObject::SetValueFromCString(value_str, error);
420}
421
423 if (!UpdateValueIfNeeded()) {
424 error = Status::FromErrorString("unable to update value before writing");
425 return false;
426 }
427
428 if (llvm::Error err = CanSetValue()) {
429 error = Status::FromError(std::move(err));
430 return false;
431 }
432
433 if (m_resolved_value.GetContextType() == Value::ContextType::RegisterInfo) {
434 RegisterInfo *reg_info = m_resolved_value.GetRegisterInfo();
436 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
437 RegisterValue reg_value;
438 if (!reg_info || !reg_ctx) {
439 error = Status::FromErrorString("unable to retrieve register info");
440 return false;
441 }
442 error = reg_value.SetValueFromData(*reg_info, data, 0, true);
443 if (error.Fail())
444 return false;
445 if (reg_ctx->WriteRegister(reg_info, reg_value)) {
447 return true;
448 } else {
449 error = Status::FromErrorString("unable to write back to register");
450 return false;
451 }
452 } else
453 return ValueObject::SetData(data, error);
454}
static llvm::raw_ostream & error(Stream &strm)
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:303
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition ArchSpec.cpp:710
lldb::ByteOrder GetByteOrder() const
Returns the byte order for the architecture specification.
Definition ArchSpec.cpp:759
static std::shared_ptr< ClusterManager > Create()
Generic representation of a type in a programming language.
lldb::LanguageType GetMinimumLanguage()
ConstString GetDisplayTypeName() const
llvm::Expected< uint64_t > GetByteSize(ExecutionContextScope *exe_scope) const
Return the size of the type in bytes.
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 ...
bool IsImplicit(ExecutionContext *exe_ctx, RegisterContext *reg_ctx, lldb::addr_t func_load_addr) const
Return true if the expression in scope at the current PC produces an implicit location,...
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.
An data extractor class.
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 Address & GetAddress() const
Return the address of the function (its entry point).
Definition Function.h:439
A plug-in interface definition class for debugging a process.
Definition Process.h:370
virtual bool IsAlive()
Check if a process is still alive.
Definition Process.cpp:1143
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:118
static Status FromErrorString(const char *str)
Definition Status.h:141
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
"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.
Function * function
The Function for a given query.
const ArchSpec & GetArchitecture() const
Definition Target.h:1337
CompilerType GetForwardCompilerType()
ConstString GetName()
ConstString GetQualifiedName()
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
bool SetData(DataExtractor &data, Status &error) override
const char * GetLocationAsCString() override
bool m_resolved_value_is_implicit
True when the resolved value has no writable storage in the inferior (an implicit location,...
static lldb::ValueObjectSP Create(ExecutionContextScope *exe_scope, const lldb::VariableSP &var_sp)
Value m_resolved_value
The value that DWARFExpression resolves this variable to before we patch it up.
llvm::Error CanSetValue() override
Check if the value may be writable.
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().
llvm::Expected< uint64_t > GetByteSize() override
bool GetDeclaration(Declaration &decl) override
CompilerType GetCompilerTypeImpl() override
void SetValueIsValid(bool valid)
ClusterManager< ValueObject > ValueObjectManager
ValueObject(ExecutionContextScope *exe_scope, ValueObjectManager &manager, AddressType child_ptr_or_ref_addr_type=eAddressTypeLoad)
Use this constructor to create a "root variable object".
virtual llvm::Error CanSetValue()
Check if the value may be writable.
Status m_error
An error object that can describe any errors that occur when updating values.
lldb::ProcessSP GetProcessSP() const
DataExtractor m_data
A data extractor that can be used to extract the value.
bool HasNoStorage()
Returns whether objects of the type of this value occupy no memory, so that the value has no data and...
void SetValueDidChange(bool value_changed)
bool UpdateValueIfNeeded(bool update_format=true)
CompilerType GetCompilerType()
virtual const char * GetLocationAsCString()
virtual bool SetValueFromCString(const char *value_str, Status &error)
virtual bool SetData(DataExtractor &data, Status &error)
ConstString m_name
The name of this object.
const char * GetLocationAsCStringImpl(const Value &value, const DataExtractor &data)
const ExecutionContextRef & GetExecutionContextRef() const
const Value & GetValue() const
void SetAddressTypeOfChildren(AddressType at)
const Scalar & GetScalar() const
See comment on m_scalar to understand what GetScalar returns.
Definition Value.h:114
Status GetValueAsData(ExecutionContext *exe_ctx, DataExtractor &data, Module *module)
Definition Value.cpp:324
ValueType
Type that describes Value::m_value.
Definition Value.h:42
@ HostAddress
A host address value (for memory in the process that < A is using liblldb).
Definition Value.h:53
@ FileAddress
A file address value.
Definition Value.h:48
@ LoadAddress
A load address value.
Definition Value.h:50
@ Scalar
A raw scalar value.
Definition Value.h:46
ValueType GetValueType() const
Definition Value.cpp:112
void SetContext(ContextType context_type, void *p)
Definition Value.h:97
@ Variable
lldb_private::Variable *.
Definition Value.h:66
@ RegisterInfo
RegisterInfo * (can be a scalar or a vector register).
Definition Value.h:62
DWARFExpressionList & LocationExpressionList()
Definition Variable.h:79
void CalculateSymbolContext(SymbolContext *sc)
Definition Variable.cpp:220
bool GetLocationIsConstantValueData() const
Definition Variable.h:104
#define LLDB_INVALID_ADDRESS
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
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::Variable > VariableSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Module > ModuleSP
Every register is described in detail including its name, alternate name (optional),...