LLDB mainline
ValueObjectSynthetic.cpp
Go to the documentation of this file.
1//===-- ValueObjectSynthetic.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/Debugger.h"
12#include "lldb/Core/Value.h"
16#include "lldb/Target/Target.h"
19#include "lldb/Utility/Log.h"
20#include "lldb/Utility/Status.h"
22
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/Support/Error.h"
25#include "llvm/Support/ErrorExtras.h"
26#include <mutex>
27#include <optional>
28
29namespace lldb_private {
30class Declaration;
31}
32
33using namespace lldb_private;
34
36public:
39
40 llvm::Expected<uint32_t> CalculateNumChildren() override {
41 return m_backend.GetNumChildren();
42 }
43
44 lldb::ValueObjectSP GetChildAtIndex(uint32_t idx) override {
45 return m_backend.GetChildAtIndex(idx);
46 }
47
48 llvm::Expected<size_t>
49 GetIndexOfChildWithName(llvm::StringRef name) override {
50 return m_backend.GetIndexOfChildWithName(name);
51 }
52
53 bool MightHaveChildren() override { return m_backend.MightHaveChildren(); }
54
58};
59
62 : ValueObject(parent), m_synth_sp(std::move(filter)), m_children_byindex(),
68 SetName(parent.GetName());
69 // Copying the data of an incomplete type won't work as it has no byte size.
70 if (m_parent->GetCompilerType().IsCompleteType())
73}
74
76
80
82 return m_parent->GetTypeName();
83}
84
86 return m_parent->GetQualifiedTypeName();
87}
88
90 const std::string synth_name = m_synth_filter_up->GetSyntheticTypeName();
91 if (!synth_name.empty())
92 return ConstString(synth_name);
93
94 return m_parent->GetDisplayTypeName();
95}
96
97llvm::Expected<uint32_t>
100
104
105 if (max < UINT32_MAX) {
106 auto num_children = m_synth_filter_up->CalculateNumChildren(max);
107 LLDB_LOG(log,
108 "[ValueObjectSynthetic::CalculateNumChildren] for VO of name "
109 "{0} and type {1}, the filter returned {2} child values",
110 GetName(), GetTypeName(), num_children ? *num_children : 0);
111 return num_children;
112 } else {
113 auto num_children_or_err = m_synth_filter_up->CalculateNumChildren(max);
114 if (!num_children_or_err) {
116 return num_children_or_err;
117 }
118 auto num_children = (m_synthetic_children_count = *num_children_or_err);
119 LLDB_LOG(log,
120 "[ValueObjectSynthetic::CalculateNumChildren] for VO of name "
121 "{0} and type {1}, the filter returned {2} child values",
122 GetName(), GetTypeName(), num_children);
123 return num_children;
124 }
125}
126
129 if (!m_parent)
130 return lldb::ValueObjectSP();
131 if (IsDynamic() && GetDynamicValueType() == valueType)
132 return GetSP();
133 return m_parent->GetDynamicValue(valueType);
134}
135
142
143llvm::Expected<uint64_t> ValueObjectSynthetic::GetByteSize() {
144 return m_parent->GetByteSize();
145}
146
148 return m_parent->GetValueType();
149}
150
152 ValueObject *valobj_for_frontend = m_parent;
153 if (m_synth_sp->WantsDereference()) {
154 CompilerType type = m_parent->GetCompilerType();
155 if (type.IsValid() && type.IsPointerOrReferenceType()) {
157 lldb::ValueObjectSP deref_sp = m_parent->Dereference(error);
158 if (error.Success())
159 valobj_for_frontend = deref_sp.get();
160 }
161 }
162 m_synth_filter_up = (m_synth_sp->GetFrontEnd(*valobj_for_frontend));
164 m_synth_filter_up = std::make_unique<DummySyntheticFrontEnd>(*m_parent);
165}
166
169
170 SetValueIsValid(false);
171 m_error.Clear();
172
173 if (!m_parent->UpdateValueIfNeeded(false)) {
174 // our parent could not update.. as we are meaningless without a parent,
175 // just stop
176 if (m_parent->GetError().Fail())
177 m_error = m_parent->GetError().Clone();
178 return false;
179 }
180
181 // Regenerate the synthetic filter if our typename changes. When the (dynamic)
182 // type of an object changes, so does their synthetic filter of choice.
183 ConstString new_parent_type_name = m_parent->GetTypeName();
184 if (new_parent_type_name != m_parent_type_name) {
185 LLDB_LOG(log,
186 "[ValueObjectSynthetic::UpdateValue] name={0}, type changed "
187 "from {1} to {2}, recomputing synthetic filter",
188 GetName(), m_parent_type_name, new_parent_type_name);
189 m_parent_type_name = new_parent_type_name;
191 }
192
193 // let our backend do its update
195 LLDB_LOG(log,
196 "[ValueObjectSynthetic::UpdateValue] name={0}, synthetic "
197 "filter said caches are stale - clearing",
198 GetName());
199 // filter said that cached values are stale
200 {
201 std::lock_guard<std::mutex> guard(m_child_mutex);
202 m_children_byindex.clear();
203 m_name_toindex.clear();
204 }
205 // usually, an object's value can change but this does not alter its
206 // children count for a synthetic VO that might indeed happen, so we need
207 // to tell the upper echelons that they need to come back to us asking for
208 // children
209 m_flags.m_children_count_valid = false;
210 {
211 std::lock_guard<std::mutex> guard(m_child_mutex);
213 }
216 } else {
217 LLDB_LOG(log,
218 "[ValueObjectSynthetic::UpdateValue] name={0}, synthetic "
219 "filter said caches are still valid",
220 GetName());
221 }
222
224
225 lldb::ValueObjectSP synth_val(m_synth_filter_up->GetSyntheticValue());
226
227 if (synth_val && synth_val->CanProvideValue()) {
228 LLDB_LOG(log,
229 "[ValueObjectSynthetic::UpdateValue] name={0}, synthetic "
230 "filter said it can provide a value",
231 GetName());
232
234 CopyValueData(synth_val.get());
235 } else {
236 LLDB_LOG(log,
237 "[ValueObjectSynthetic::UpdateValue] name={0}, synthetic "
238 "filter said it will not provide a value",
239 GetName());
240
242 // Copying the data of an incomplete type won't work as it has no byte size.
243 if (m_parent->GetCompilerType().IsCompleteType())
245 }
246
247 SetValueIsValid(true);
248 return true;
249}
250
251/// Whether \p valobj, apart from any dynamic or synthetic wrappers, has no
252/// parent.
253static bool IsRootValue(ValueObject &valobj) {
254 ValueObject *base = valobj.FollowParentChain([](ValueObject *vo) {
255 return vo->GetParent() && (vo->IsSynthetic() || vo->IsDynamic());
256 });
257 return base && !base->GetParent();
258}
259
261 bool is_root) {
262 static std::once_flag g_foreign_root_warning;
263 static std::once_flag g_foreign_non_root_warning;
264 std::optional<lldb::user_id_t> debugger_id;
265 if (lldb::TargetSP target_sp = GetTargetSP())
266 debugger_id = target_sp->GetDebugger().GetID();
267 std::string message = llvm::formatv(
268 "the synthetic child provider for '{0}' returned '{1}', which {2}. "
269 "Create synthetic children with the CreateValueFrom* methods of the "
270 "SBValue being formatted instead",
271 GetTypeName(), child.GetName(),
272 is_root ? "is not owned by its parent"
273 : "is a child of another value. LLDB does not keep it alive, "
274 "so it may be freed while it is still in use");
275 Debugger::ReportWarning(std::move(message), debugger_id,
276 is_root ? &g_foreign_root_warning
277 : &g_foreign_non_root_warning);
278}
279
281 bool can_create) {
283
284 LLDB_LOG(log,
285 "[ValueObjectSynthetic::GetChildAtIndex] name={0}, retrieving "
286 "child at index {1}",
287 GetName(), idx);
288
290
291 ValueObject *valobj;
292 bool child_is_cached;
293 {
294 std::lock_guard<std::mutex> guard(m_child_mutex);
295 auto cached_child_it = m_children_byindex.find(idx);
296 child_is_cached = cached_child_it != m_children_byindex.end();
297 if (child_is_cached)
298 valobj = cached_child_it->second;
299 }
300
301 if (!child_is_cached) {
302 if (can_create && m_synth_filter_up != nullptr) {
303 LLDB_LOG(log,
304 "[ValueObjectSynthetic::GetChildAtIndex] name={0}, child at "
305 "index {1} not cached and will be created",
306 GetName(), idx);
307
308 lldb::ValueObjectSP synth_guy = m_synth_filter_up->GetChildAtIndex(idx);
309
310 LLDB_LOG(
311 log,
312 "[ValueObjectSynthetic::GetChildAtIndex] name={0}, child at index "
313 "{1} created as {2} (is "
314 "synthetic: {3})",
315 GetName(), idx, static_cast<void *>(synth_guy.get()),
316 synth_guy.get()
317 ? (synth_guy->IsSyntheticChildrenGenerated() ? "yes" : "no")
318 : "no");
319
320 if (!synth_guy)
321 return synth_guy;
322
323 if (synth_guy->IsSyntheticChildrenGenerated())
324 synth_guy->SetLogicalParent(this);
325
326 // m_children_byindex holds raw pointers, so a child that our
327 // ClusterManager does not own has to be kept alive here. Only do that
328 // for a root value, which the provider made for this child. A child of
329 // another value could hold a reference back to us.
330 const bool is_foreign = synth_guy->GetManager() != GetManager();
331 const bool is_foreign_root = is_foreign && IsRootValue(*synth_guy);
332 {
333 std::lock_guard<std::mutex> guard(m_child_mutex);
334 if (synth_guy->IsSyntheticChildrenGenerated() || is_foreign_root)
335 m_synthetic_children_cache.push_back(synth_guy);
336 m_children_byindex[idx] = synth_guy.get();
337 }
338 if (is_foreign)
339 WarnAboutForeignChild(*synth_guy, is_foreign_root);
340 synth_guy->SetPreferredDisplayLanguageIfNeeded(
342
343 if (lldb::ValueObjectSP check_sp =
344 CheckValueObjectOwnership(synth_guy.get()))
345 return check_sp;
346 return synth_guy;
347 } else {
348 LLDB_LOG(log,
349 "[ValueObjectSynthetic::GetChildAtIndex] name={0}, child at "
350 "index {1} not cached and cannot "
351 "be created (can_create = {2}, synth_filter = {3})",
352 GetName(), idx, can_create ? "yes" : "no",
353 static_cast<void *>(m_synth_filter_up.get()));
354
355 return lldb::ValueObjectSP();
356 }
357 } else {
358 LLDB_LOG(log,
359 "[ValueObjectSynthetic::GetChildAtIndex] name={0}, child at "
360 "index {1} cached as {2}",
361 GetName(), idx, static_cast<void *>(valobj));
363 if (check_sp)
364 return check_sp;
365 return valobj->GetSP();
366 }
367}
368
371 bool can_create) {
373
374 auto index_or_err = GetIndexOfChildWithName(name);
375
376 if (!index_or_err) {
377 LLDB_LOG_ERROR(GetLog(LLDBLog::DataFormatters), index_or_err.takeError(),
378 "{0}");
379 return lldb::ValueObjectSP();
380 }
381
382 return GetChildAtIndex(*index_or_err, can_create);
383}
384
385llvm::Expected<size_t>
388
389 ConstString name(name_ref);
390
391 {
392 std::lock_guard<std::mutex> guard(m_child_mutex);
393 auto name_to_index = m_name_toindex.find(name.GetCString());
394 if (name_to_index != m_name_toindex.end())
395 return name_to_index->second;
396 }
397
399 return llvm::createStringErrorV("type has no child named '{0}'", name);
400
401 size_t index;
402 auto index_or_err = m_synth_filter_up->GetIndexOfChildWithName(name);
403 if (index_or_err) {
404 index = *index_or_err;
405 } else {
406 // The front-end does its own subscripting, so its answer is final.
407 if (m_synth_sp->CustomSubscripting())
408 return index_or_err.takeError();
409
410 // Provide automatic support for subscript child names ("[N]").
411 auto maybe_index = formatters::ExtractIndexFromString(name.GetCString());
412 if (!maybe_index)
413 // The child name was not of the form "[N]", return the original error.
414 return index_or_err.takeError();
415
416 // Subscripting succeeded, ignore the original error.
417 llvm::consumeError(index_or_err.takeError());
418 index = *maybe_index;
419
420 // Prevent unnecessary work by limiting max to one past the index.
421 uint32_t max = index + 1;
422 auto num_children = GetNumChildren(max);
423 if (!num_children)
424 return num_children.takeError();
425 if (index >= *num_children)
426 return llvm::createStringErrorV("subscript index out of range: {0}",
427 index);
428 }
429
430 std::lock_guard<std::mutex> guard(m_child_mutex);
431 m_name_toindex[name.GetCString()] = index;
432 return index;
433}
434
435bool ValueObjectSynthetic::IsInScope() { return m_parent->IsInScope(); }
436
440
442 if (!source->UpdateValueIfNeeded())
443 return;
444 m_value = source->GetValue();
446 m_error = m_value.GetValueAsData(&exe_ctx, m_data, GetModule().get());
447}
448
450 if (!UpdateValueIfNeeded())
451 return false;
453 return true;
454 return m_parent->CanProvideValue();
455}
456
458 Status &error) {
459 return m_parent->SetValueFromCString(value_str, error);
460}
461
463 if (m_parent) {
464 m_parent->ClearUserVisibleData(eClearUserVisibleDataItemsAll);
465 m_parent->SetFormat(format);
466 }
467 this->ValueObject::SetFormat(format);
469}
470
472 lldb::LanguageType lang) {
474 if (m_parent)
475 m_parent->SetPreferredDisplayLanguage(lang);
476}
477
486
488 if (m_parent)
489 return m_parent->IsSyntheticChildrenGenerated();
490 return false;
491}
492
494 if (m_parent)
495 m_parent->SetSyntheticChildrenGenerated(b);
497}
498
500 if (m_parent)
501 return m_parent->GetDeclaration(decl);
502
503 return ValueObject::GetDeclaration(decl);
504}
505
507 if (m_parent)
508 return m_parent->GetLanguageFlags();
509 return this->ValueObject::GetLanguageFlags();
510}
511
513 if (m_parent)
514 m_parent->SetLanguageFlags(flags);
515 else
517}
518
520 GetExpressionPathFormat epformat) {
521 // A synthetic ValueObject may wrap an underlying Register or RegisterSet
522 // ValueObject, which requires a different approach to generating the
523 // expression path. In such cases, delegate to the non-synthetic value object.
524 if (const lldb::ValueType obj_value_type = GetValueType();
525 IsSynthetic() && (obj_value_type == lldb::eValueTypeRegister ||
526 obj_value_type == lldb::eValueTypeRegisterSet)) {
527
528 if (const lldb::ValueObjectSP raw_value = GetNonSyntheticValue())
529 return raw_value->GetExpressionPath(stream, epformat);
530 }
531 return ValueObject::GetExpressionPath(stream, epformat);
532}
533
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
static bool IsRootValue(ValueObject &valobj)
Whether valobj, apart from any dynamic or synthetic wrappers, has no parent.
llvm::Expected< uint32_t > CalculateNumChildren() override
lldb::ChildCacheState Update() override
This function is assumed to always succeed and if it fails, the front-end should know to deal with it...
lldb::ValueObjectSP GetChildAtIndex(uint32_t idx) override
llvm::Expected< size_t > GetIndexOfChildWithName(llvm::StringRef name) override
Determine the index of a named child.
DummySyntheticFrontEnd(ValueObject &backend)
Generic representation of a type in a programming language.
bool IsPointerOrReferenceType(CompilerType *pointee_type=nullptr) const
A uniqued constant string class.
Definition ConstString.h:40
const char * GetCString() const
Get the string value as a C string.
static void ReportWarning(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report warning events.
A class that describes the declaration location of a lldb object.
Definition Declaration.h:24
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
An error handling class.
Definition Status.h:118
A stream class that can stream formatted output to a file.
Definition Stream.h:28
SyntheticChildrenFrontEnd(ValueObject &backend)
virtual lldb::DynamicValueType GetDynamicValueType()
lldb::ValueObjectSP GetChildAtIndex(uint32_t idx, bool can_create=true) override
bool SetValueFromCString(const char *value_str, Status &error) override
lldb::ValueType GetValueType() const override
lldb::LanguageType GetPreferredDisplayLanguage() override
void GetExpressionPath(Stream &stream, GetExpressionPathFormat epformat=eGetExpressionPathFormatDereferencePointers) override
void SetFormat(lldb::Format format) override
NameToIndexMap m_name_toindex
Guarded by m_child_mutex;.
ByIndexMap m_children_byindex
Guarded by m_child_mutex;.
std::unique_ptr< SyntheticChildrenFrontEnd > m_synth_filter_up
lldb::ValueObjectSP GetDynamicValue(lldb::DynamicValueType valueType) override
void SetSyntheticChildrenGenerated(bool b) override
void SetPreferredDisplayLanguage(lldb::LanguageType)
lldb::ValueObjectSP GetNonSyntheticValue() override
SyntheticChildrenCache m_synthetic_children_cache
Guarded by m_child_mutex;.
void WarnAboutForeignChild(ValueObject &child, bool is_root)
Warn, once per session, that the provider returned a child that our ClusterManager does not own.
llvm::Expected< size_t > GetIndexOfChildWithName(llvm::StringRef name) override
Return the index of the child named name.
bool GetDeclaration(Declaration &decl) override
bool MightHaveChildren() override
Find out if a ValueObject might have children.
lldb::ValueObjectSP GetChildMemberWithName(llvm::StringRef name, bool can_create=true) override
llvm::Expected< uint64_t > GetByteSize() override
ValueObjectSynthetic(ValueObject &parent, lldb::SyntheticChildrenSP filter)
void SetLanguageFlags(uint64_t flags) override
SyntheticChildrenFrontEnd * GetSyntheticChildrenFrontEnd() override
llvm::Expected< uint32_t > CalculateNumChildren(uint32_t max) override
Should only be called by ValueObject::GetNumChildren().
void SetValueIsValid(bool valid)
lldb::ValueObjectSP CheckValueObjectOwnership(ValueObject *child)
void ClearUserVisibleData(uint32_t items=ValueObject::eClearUserVisibleDataItemsAllStrings)
ValueObject * FollowParentChain(std::function< bool(ValueObject *)>)
Given a ValueObject, loop over itself and its parent, and its parent's parent, .
void SetPreferredDisplayLanguage(lldb::LanguageType lt)
struct lldb_private::ValueObject::Bitflags m_flags
lldb::ValueObjectSP GetSP()
virtual void SetLanguageFlags(uint64_t flags)
Status m_error
An error object that can describe any errors that occur when updating values.
virtual uint64_t GetLanguageFlags()
virtual void SetSyntheticChildrenGenerated(bool b)
DataExtractor m_data
A data extractor that can be used to extract the value.
llvm::Expected< uint32_t > GetNumChildren(uint32_t max=UINT32_MAX)
virtual void GetExpressionPath(Stream &s, GetExpressionPathFormat=eGetExpressionPathFormatDereferencePointers)
ValueObjectManager * GetManager()
virtual lldb::ModuleSP GetModule()
Return the module associated with this value object in case the value is from an executable file and ...
lldb::LanguageType m_preferred_display_language
ValueObject * m_parent
The parent value object, or nullptr if this has no parent.
virtual bool GetDeclaration(Declaration &decl)
void SetName(llvm::StringRef name)
Change the name of the current ValueObject.
bool UpdateValueIfNeeded(bool update_format=true)
lldb::TargetSP GetTargetSP() const
ConstString GetName() const
virtual ValueObject * GetParent()
virtual void SetFormat(lldb::Format format)
virtual bool IsSynthetic()
const ExecutionContextRef & GetExecutionContextRef() const
const Value & GetValue() const
#define UINT32_MAX
std::optional< size_t > ExtractIndexFromString(llvm::StringRef item_name)
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
ChildCacheState
Specifies if children need to be re-computed after a call to SyntheticChildrenFrontEnd::Update.
@ eRefetch
Children need to be recomputed dynamically.
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
Format
Display format definitions.
LanguageType
Programming language type.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eValueTypeRegister
stack frame register value
@ eValueTypeRegisterSet
A collection of stack frame register values.
std::shared_ptr< lldb_private::SyntheticChildren > SyntheticChildrenSP
std::shared_ptr< lldb_private::Target > TargetSP