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
37#include <cassert>
38#include <memory>
39#include <optional>
40
41namespace lldb_private {
43}
44namespace lldb_private {
45class StackFrame;
46}
47namespace lldb_private {
48struct RegisterInfo;
49}
50using namespace lldb_private;
51
54 const lldb::VariableSP &var_sp) {
55 auto manager_sp = ValueObjectManager::Create();
56 return (new ValueObjectVariable(exe_scope, *manager_sp, var_sp))->GetSP();
57}
58
60 ValueObjectManager &manager,
61 const lldb::VariableSP &var_sp)
62 : ValueObject(exe_scope, manager), m_variable_sp(var_sp) {
63 // Do not attempt to construct one of these objects with no variable!
64 assert(m_variable_sp.get() != nullptr);
65 m_name = var_sp->GetName();
66}
67
69
71 Type *var_type = m_variable_sp->GetType();
72 if (var_type)
73 return var_type->GetForwardCompilerType();
74 return CompilerType();
75}
76
78 Type *var_type = m_variable_sp->GetType();
79 if (var_type)
80 return var_type->GetName();
81 return ConstString();
82}
83
85 Type *var_type = m_variable_sp->GetType();
86 if (var_type)
87 return var_type->GetForwardCompilerType().GetDisplayTypeName();
88 return ConstString();
89}
90
92 Type *var_type = m_variable_sp->GetType();
93 if (var_type)
94 return var_type->GetQualifiedName();
95 return ConstString();
96}
97
98llvm::Expected<uint32_t>
101
102 if (!type.IsValid())
103 return llvm::createStringError("invalid type");
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
113llvm::Expected<uint64_t> ValueObjectVariable::GetByteSize() {
115
117 return type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
118}
119
125
127 SetValueIsValid(false);
128 m_error.Clear();
129
130 Variable *variable = m_variable_sp.get();
131 DWARFExpressionList &expr_list = variable->LocationExpressionList();
132
133 if (variable->GetLocationIsConstantValueData()) {
134 // expr doesn't contain DWARF bytes, it contains the constant variable
135 // value bytes themselves...
136 if (expr_list.GetExpressionData(m_data)) {
137 if (m_data.GetDataStart() && m_data.GetByteSize())
138 m_value.SetBytes(m_data.GetDataStart(), m_data.GetByteSize());
139 m_value.SetContext(Value::ContextType::Variable, variable);
140 } else
141 m_error = Status::FromErrorString("empty constant data");
142 // constant bytes can't be edited - sorry
145 } else {
146 lldb::addr_t loclist_base_load_addr = LLDB_INVALID_ADDRESS;
148
149 Target *target = exe_ctx.GetTargetPtr();
150 if (target) {
151 m_data.SetByteOrder(target->GetArchitecture().GetByteOrder());
152 m_data.SetAddressByteSize(target->GetArchitecture().GetAddressByteSize());
153 }
154
155 if (!expr_list.IsAlwaysValidSingleExpr()) {
156 SymbolContext sc;
157 variable->CalculateSymbolContext(&sc);
158 if (sc.function)
159 loclist_base_load_addr =
160 sc.function->GetAddress().GetLoadAddress(target);
161 }
162 Value old_value(m_value);
163 llvm::Expected<Value> maybe_value = expr_list.Evaluate(
164 &exe_ctx, nullptr, loclist_base_load_addr, nullptr, nullptr);
165
166 if (maybe_value) {
167 m_value = *maybe_value;
170 expr_list.IsImplicit(&exe_ctx, nullptr, loclist_base_load_addr);
171 m_value.SetContext(Value::ContextType::Variable, variable);
172
173 CompilerType compiler_type = GetCompilerType();
174 if (compiler_type.IsValid()) {
175 m_value.SetCompilerType(compiler_type);
176
177 if (lldb::ProcessSP process_sp = GetProcessSP())
178 if (LanguageRuntime *runtime = process_sp->GetLanguageRuntime(
179 compiler_type.GetMinimumLanguage()))
180 if (llvm::Error err =
181 runtime->FixupVariableLocation(*variable, m_value)) {
182 m_error = Status::FromError(std::move(err));
183 return false;
184 }
185 }
186
187 Value::ValueType value_type = m_value.GetValueType();
188
189 // The size of the buffer within m_value can be less than the size
190 // prescribed by its type. E.g. this can happen when an expression only
191 // partially describes an object (say, because it contains DW_OP_piece).
192 //
193 // In this case, grow m_value to the expected size. An alternative way to
194 // handle this is to teach Value::GetValueAsData() and ValueObjectChild
195 // not to read past the end of a host buffer, but this gets impractically
196 // complicated as a Value's host buffer may be shared with a distant
197 // ancestor or sibling in the ValueObject hierarchy.
198 //
199 // FIXME: When we grow m_value, we should represent the added bits as
200 // undefined somehow instead of as 0's.
201 if (value_type == Value::ValueType::HostAddress &&
202 compiler_type.IsValid()) {
203 if (size_t value_buf_size = m_value.GetBuffer().GetByteSize()) {
204 size_t value_size = m_value.GetValueByteSize(&m_error, &exe_ctx);
205 if (m_error.Success() && value_buf_size < value_size)
206 m_value.ResizeData(value_size);
207 }
208 }
209
210 Process *process = exe_ctx.GetProcessPtr();
211 const bool process_is_alive = process && process->IsAlive();
212
213 switch (value_type) {
215 m_error = Status::FromErrorString("invalid value");
216 break;
218 // The variable value is in the Scalar value inside the m_value. We can
219 // point our m_data right to it.
220 m_error = m_value.GetValueAsData(&exe_ctx, m_data, GetModule().get());
221 break;
222
226 // The DWARF expression result was an address in the inferior process.
227 // If this variable is an aggregate type, we just need the address as
228 // the main value as all child variable objects will rely upon this
229 // location and add an offset and then read their own values as needed.
230 // If this variable is a simple type, we read all data for it into
231 // m_data. Make sure this type has a value before we try and read it
232
233 // If we have a file address, convert it to a load address if we can.
234 if (value_type == Value::ValueType::FileAddress && process_is_alive)
235 m_value.ConvertToLoadAddress(GetModule().get(), target);
236
237 if (!CanProvideValue()) {
238 // this value object represents an aggregate type whose children have
239 // values, but this object does not. So we say we are changed if our
240 // location has changed.
241 SetValueDidChange(value_type != old_value.GetValueType() ||
242 m_value.GetScalar() != old_value.GetScalar());
243 } else {
244 // Copy the Value and set the context to use our Variable so it can
245 // extract read its value into m_data appropriately
246 Value value(m_value);
248 m_error = value.GetValueAsData(&exe_ctx, m_data, GetModule().get());
249
250 SetValueDidChange(value_type != old_value.GetValueType() ||
251 m_value.GetScalar() != old_value.GetScalar());
252 }
253 break;
254 }
255
256 SetValueIsValid(m_error.Success());
257 } else {
258 m_error = Status::FromError(maybe_value.takeError());
259 // could not find location, won't allow editing
262 }
263 }
264
265 return m_error.Success();
266}
267
269 Value::ValueType value_type = valobj.GetValue().GetValueType();
271 Process *process = exe_ctx.GetProcessPtr();
272 const bool process_is_alive = process && process->IsAlive();
273 const uint32_t type_info = valobj.GetCompilerType().GetTypeInfo();
274 const bool is_pointer_or_ref =
275 (type_info & (lldb::eTypeIsPointer | lldb::eTypeIsReference)) != 0;
276
277 switch (value_type) {
279 break;
281 // If this type is a pointer, then its children will be considered load
282 // addresses if the pointer or reference is dereferenced, but only if
283 // the process is alive.
284 //
285 // There could be global variables like in the following code:
286 // struct LinkedListNode { Foo* foo; LinkedListNode* next; };
287 // Foo g_foo1;
288 // Foo g_foo2;
289 // LinkedListNode g_second_node = { &g_foo2, NULL };
290 // LinkedListNode g_first_node = { &g_foo1, &g_second_node };
291 //
292 // When we aren't running, we should be able to look at these variables
293 // using the "target variable" command. Children of the "g_first_node"
294 // always will be of the same address type as the parent. But children
295 // of the "next" member of LinkedListNode will become load addresses if
296 // we have a live process, or remain a file address if it was a file
297 // address.
298 if (process_is_alive && is_pointer_or_ref)
300 else
302 break;
304 // Same as above for load addresses, except children of pointer or refs
305 // are always load addresses. Host addresses are used to store freeze
306 // dried variables. If this type is a struct, the entire struct
307 // contents will be copied into the heap of the
308 // LLDB process, but we do not currently follow any pointers.
309 if (is_pointer_or_ref)
311 else
313 break;
317 break;
318 }
319}
320
322 const ExecutionContextRef &exe_ctx_ref = GetExecutionContextRef();
323 if (exe_ctx_ref.HasFrameRef()) {
324 ExecutionContext exe_ctx(exe_ctx_ref);
325 StackFrame *frame = exe_ctx.GetFramePtr();
326 if (frame) {
327 return m_variable_sp->IsInScope(frame);
328 } else {
329 // This ValueObject had a frame at one time, but now we can't locate it,
330 // so return false since we probably aren't in scope.
331 return false;
332 }
333 }
334 // We have a variable that wasn't tied to a frame, which means it is a global
335 // and is always in scope.
336 return true;
337}
338
340 if (m_variable_sp) {
341 SymbolContextScope *sc_scope = m_variable_sp->GetSymbolContextScope();
342 if (sc_scope) {
343 return sc_scope->CalculateSymbolContextModule();
344 }
345 }
346 return lldb::ModuleSP();
347}
348
350 if (m_variable_sp)
351 return m_variable_sp->GetSymbolContextScope();
352 return nullptr;
353}
354
356 if (m_variable_sp) {
357 decl = m_variable_sp->GetDeclaration();
358 return true;
359 }
360 return false;
361}
362
369
371 // Refresh the resolved location so m_resolved_value_is_implicit is current.
374 return llvm::createStringError("variable is not in a writable location");
376}
377
379 Status &error) {
380 if (!UpdateValueIfNeeded()) {
381 error = Status::FromErrorString("unable to update value before writing");
382 return false;
383 }
384
385 if (llvm::Error err = CanSetValue()) {
386 error = Status::FromError(std::move(err));
387 return false;
388 }
389
390 if (m_resolved_value.GetContextType() == Value::ContextType::RegisterInfo) {
391 RegisterInfo *reg_info = m_resolved_value.GetRegisterInfo();
393 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
394 RegisterValue reg_value;
395 if (!reg_info || !reg_ctx) {
396 error = Status::FromErrorString("unable to retrieve register info");
397 return false;
398 }
399 error = reg_value.SetValueFromString(reg_info, llvm::StringRef(value_str));
400 if (error.Fail())
401 return false;
402 if (reg_ctx->WriteRegister(reg_info, reg_value)) {
404 return true;
405 } else {
406 error = Status::FromErrorString("unable to write back to register");
407 return false;
408 }
409 } else
410 return ValueObject::SetValueFromCString(value_str, error);
411}
412
414 if (!UpdateValueIfNeeded()) {
415 error = Status::FromErrorString("unable to update value before writing");
416 return false;
417 }
418
419 if (llvm::Error err = CanSetValue()) {
420 error = Status::FromError(std::move(err));
421 return false;
422 }
423
424 if (m_resolved_value.GetContextType() == Value::ContextType::RegisterInfo) {
425 RegisterInfo *reg_info = m_resolved_value.GetRegisterInfo();
427 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
428 RegisterValue reg_value;
429 if (!reg_info || !reg_ctx) {
430 error = Status::FromErrorString("unable to retrieve register info");
431 return false;
432 }
433 error = reg_value.SetValueFromData(*reg_info, data, 0, true);
434 if (error.Fail())
435 return false;
436 if (reg_ctx->WriteRegister(reg_info, reg_value)) {
438 return true;
439 } else {
440 error = Status::FromErrorString("unable to write back to register");
441 return false;
442 }
443 } else
444 return ValueObject::SetData(data, error);
445}
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:894
lldb::ByteOrder GetByteOrder() const
Returns the byte order for the architecture specification.
Definition ArchSpec.cpp:943
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:369
virtual bool IsAlive()
Check if a process is still alive.
Definition Process.cpp:1142
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:1321
CompilerType GetForwardCompilerType()
Definition Type.cpp:791
ConstString GetName()
Definition Type.cpp:442
ConstString GetQualifiedName()
Definition Type.cpp:796
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.
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:323
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:111
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),...