1 //===-- LibCxxList.cpp ------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // C Includes
11 // C++ Includes
12 // Other libraries and framework includes
13 // Project includes
14 #include "LibCxx.h"
15 
16 #include "lldb/Core/DataBufferHeap.h"
17 #include "lldb/Core/Error.h"
18 #include "lldb/Core/Stream.h"
19 #include "lldb/Core/ValueObject.h"
20 #include "lldb/Core/ValueObjectConstResult.h"
21 #include "lldb/DataFormatters/FormattersHelpers.h"
22 #include "lldb/Host/Endian.h"
23 #include "lldb/Symbol/ClangASTContext.h"
24 #include "lldb/Target/Target.h"
25 
26 using namespace lldb;
27 using namespace lldb_private;
28 using namespace lldb_private::formatters;
29 
30 class MapEntry {
31 public:
32   MapEntry() = default;
33   explicit MapEntry(ValueObjectSP entry_sp) : m_entry_sp(entry_sp) {}
34   MapEntry(const MapEntry &rhs) = default;
35   explicit MapEntry(ValueObject *entry)
36       : m_entry_sp(entry ? entry->GetSP() : ValueObjectSP()) {}
37 
38   ValueObjectSP left() const {
39     static ConstString g_left("__left_");
40     if (!m_entry_sp)
41       return m_entry_sp;
42     return m_entry_sp->GetSyntheticChildAtOffset(
43         0, m_entry_sp->GetCompilerType(), true);
44   }
45 
46   ValueObjectSP right() const {
47     static ConstString g_right("__right_");
48     if (!m_entry_sp)
49       return m_entry_sp;
50     return m_entry_sp->GetSyntheticChildAtOffset(
51         m_entry_sp->GetProcessSP()->GetAddressByteSize(),
52         m_entry_sp->GetCompilerType(), true);
53   }
54 
55   ValueObjectSP parent() const {
56     static ConstString g_parent("__parent_");
57     if (!m_entry_sp)
58       return m_entry_sp;
59     return m_entry_sp->GetSyntheticChildAtOffset(
60         2 * m_entry_sp->GetProcessSP()->GetAddressByteSize(),
61         m_entry_sp->GetCompilerType(), true);
62   }
63 
64   uint64_t value() const {
65     if (!m_entry_sp)
66       return 0;
67     return m_entry_sp->GetValueAsUnsigned(0);
68   }
69 
70   bool error() const {
71     if (!m_entry_sp)
72       return true;
73     return m_entry_sp->GetError().Fail();
74   }
75 
76   bool null() const { return (value() == 0); }
77 
78   ValueObjectSP GetEntry() const { return m_entry_sp; }
79 
80   void SetEntry(ValueObjectSP entry) { m_entry_sp = entry; }
81 
82   bool operator==(const MapEntry &rhs) const {
83     return (rhs.m_entry_sp.get() == m_entry_sp.get());
84   }
85 
86 private:
87   ValueObjectSP m_entry_sp;
88 };
89 
90 class MapIterator {
91 public:
92   MapIterator() = default;
93   MapIterator(MapEntry entry, size_t depth = 0)
94       : m_entry(entry), m_max_depth(depth), m_error(false) {}
95   MapIterator(ValueObjectSP entry, size_t depth = 0)
96       : m_entry(entry), m_max_depth(depth), m_error(false) {}
97   MapIterator(const MapIterator &rhs)
98       : m_entry(rhs.m_entry), m_max_depth(rhs.m_max_depth), m_error(false) {}
99   MapIterator(ValueObject *entry, size_t depth = 0)
100       : m_entry(entry), m_max_depth(depth), m_error(false) {}
101 
102   ValueObjectSP value() { return m_entry.GetEntry(); }
103 
104   ValueObjectSP advance(size_t count) {
105     ValueObjectSP fail;
106     if (m_error)
107       return fail;
108     size_t steps = 0;
109     while (count > 0) {
110       next();
111       count--, steps++;
112       if (m_error || m_entry.null() || (steps > m_max_depth))
113         return fail;
114     }
115     return m_entry.GetEntry();
116   }
117 
118 protected:
119   void next() {
120     if (m_entry.null())
121       return;
122     MapEntry right(m_entry.right());
123     if (!right.null()) {
124       m_entry = tree_min(std::move(right));
125       return;
126     }
127     size_t steps = 0;
128     while (!is_left_child(m_entry)) {
129       if (m_entry.error()) {
130         m_error = true;
131         return;
132       }
133       m_entry.SetEntry(m_entry.parent());
134       steps++;
135       if (steps > m_max_depth) {
136         m_entry = MapEntry();
137         return;
138       }
139     }
140     m_entry = MapEntry(m_entry.parent());
141   }
142 
143 private:
144   MapEntry tree_min(MapEntry &&x) {
145     if (x.null())
146       return MapEntry();
147     MapEntry left(x.left());
148     size_t steps = 0;
149     while (!left.null()) {
150       if (left.error()) {
151         m_error = true;
152         return MapEntry();
153       }
154       x = left;
155       left.SetEntry(x.left());
156       steps++;
157       if (steps > m_max_depth)
158         return MapEntry();
159     }
160     return x;
161   }
162 
163   bool is_left_child(const MapEntry &x) {
164     if (x.null())
165       return false;
166     MapEntry rhs(x.parent());
167     rhs.SetEntry(rhs.left());
168     return x.value() == rhs.value();
169   }
170 
171   MapEntry m_entry;
172   size_t m_max_depth;
173   bool m_error;
174 };
175 
176 namespace lldb_private {
177 namespace formatters {
178 class LibcxxStdMapSyntheticFrontEnd : public SyntheticChildrenFrontEnd {
179 public:
180   LibcxxStdMapSyntheticFrontEnd(lldb::ValueObjectSP valobj_sp);
181 
182   ~LibcxxStdMapSyntheticFrontEnd() override = default;
183 
184   size_t CalculateNumChildren() override;
185 
186   lldb::ValueObjectSP GetChildAtIndex(size_t idx) override;
187 
188   bool Update() override;
189 
190   bool MightHaveChildren() override;
191 
192   size_t GetIndexOfChildWithName(const ConstString &name) override;
193 
194 private:
195   bool GetDataType();
196 
197   void GetValueOffset(const lldb::ValueObjectSP &node);
198 
199   ValueObject *m_tree;
200   ValueObject *m_root_node;
201   CompilerType m_element_type;
202   uint32_t m_skip_size;
203   size_t m_count;
204   std::map<size_t, MapIterator> m_iterators;
205 };
206 } // namespace formatters
207 } // namespace lldb_private
208 
209 lldb_private::formatters::LibcxxStdMapSyntheticFrontEnd::
210     LibcxxStdMapSyntheticFrontEnd(lldb::ValueObjectSP valobj_sp)
211     : SyntheticChildrenFrontEnd(*valobj_sp), m_tree(nullptr),
212       m_root_node(nullptr), m_element_type(), m_skip_size(UINT32_MAX),
213       m_count(UINT32_MAX), m_iterators() {
214   if (valobj_sp)
215     Update();
216 }
217 
218 size_t lldb_private::formatters::LibcxxStdMapSyntheticFrontEnd::
219     CalculateNumChildren() {
220   static ConstString g___pair3_("__pair3_");
221   static ConstString g___first_("__first_");
222 
223   if (m_count != UINT32_MAX)
224     return m_count;
225   if (m_tree == nullptr)
226     return 0;
227   ValueObjectSP m_item(m_tree->GetChildMemberWithName(g___pair3_, true));
228   if (!m_item)
229     return 0;
230   m_item = m_item->GetChildMemberWithName(g___first_, true);
231   if (!m_item)
232     return 0;
233   m_count = m_item->GetValueAsUnsigned(0);
234   return m_count;
235 }
236 
237 bool lldb_private::formatters::LibcxxStdMapSyntheticFrontEnd::GetDataType() {
238   static ConstString g___value_("__value_");
239   static ConstString g_tree_("__tree_");
240   static ConstString g_pair3("__pair3_");
241 
242   if (m_element_type.GetOpaqueQualType() && m_element_type.GetTypeSystem())
243     return true;
244   m_element_type.Clear();
245   ValueObjectSP deref;
246   Error error;
247   deref = m_root_node->Dereference(error);
248   if (!deref || error.Fail())
249     return false;
250   deref = deref->GetChildMemberWithName(g___value_, true);
251   if (deref) {
252     m_element_type = deref->GetCompilerType();
253     return true;
254   }
255   lldb::TemplateArgumentKind kind;
256   deref = m_backend.GetChildAtNamePath({g_tree_, g_pair3});
257   if (!deref)
258     return false;
259   m_element_type =
260       deref->GetCompilerType().GetTemplateArgument(1, kind).GetTemplateArgument(
261           1, kind);
262   if (m_element_type) {
263     std::string name;
264     uint64_t bit_offset_ptr;
265     uint32_t bitfield_bit_size_ptr;
266     bool is_bitfield_ptr;
267     m_element_type = m_element_type.GetFieldAtIndex(
268         0, name, &bit_offset_ptr, &bitfield_bit_size_ptr, &is_bitfield_ptr);
269     m_element_type = m_element_type.GetTypedefedType();
270     return m_element_type.IsValid();
271   } else {
272     m_element_type = m_backend.GetCompilerType().GetTemplateArgument(0, kind);
273     return m_element_type.IsValid();
274   }
275 }
276 
277 void lldb_private::formatters::LibcxxStdMapSyntheticFrontEnd::GetValueOffset(
278     const lldb::ValueObjectSP &node) {
279   if (m_skip_size != UINT32_MAX)
280     return;
281   if (!node)
282     return;
283   CompilerType node_type(node->GetCompilerType());
284   uint64_t bit_offset;
285   if (node_type.GetIndexOfFieldWithName("__value_", nullptr, &bit_offset) !=
286       UINT32_MAX) {
287     m_skip_size = bit_offset / 8u;
288   } else {
289     ClangASTContext *ast_ctx =
290         llvm::dyn_cast_or_null<ClangASTContext>(node_type.GetTypeSystem());
291     if (!ast_ctx)
292       return;
293     CompilerType tree_node_type = ast_ctx->CreateStructForIdentifier(
294         ConstString(),
295         {{"ptr0", ast_ctx->GetBasicType(lldb::eBasicTypeVoid).GetPointerType()},
296          {"ptr1", ast_ctx->GetBasicType(lldb::eBasicTypeVoid).GetPointerType()},
297          {"ptr2", ast_ctx->GetBasicType(lldb::eBasicTypeVoid).GetPointerType()},
298          {"cw", ast_ctx->GetBasicType(lldb::eBasicTypeBool)},
299          {"payload", (m_element_type.GetCompleteType(), m_element_type)}});
300     std::string child_name;
301     uint32_t child_byte_size;
302     int32_t child_byte_offset = 0;
303     uint32_t child_bitfield_bit_size;
304     uint32_t child_bitfield_bit_offset;
305     bool child_is_base_class;
306     bool child_is_deref_of_parent;
307     uint64_t language_flags;
308     if (tree_node_type
309             .GetChildCompilerTypeAtIndex(
310                 nullptr, 4, true, true, true, child_name, child_byte_size,
311                 child_byte_offset, child_bitfield_bit_size,
312                 child_bitfield_bit_offset, child_is_base_class,
313                 child_is_deref_of_parent, nullptr, language_flags)
314             .IsValid())
315       m_skip_size = (uint32_t)child_byte_offset;
316   }
317 }
318 
319 lldb::ValueObjectSP
320 lldb_private::formatters::LibcxxStdMapSyntheticFrontEnd::GetChildAtIndex(
321     size_t idx) {
322   static ConstString g___cc("__cc");
323   static ConstString g___nc("__nc");
324   static ConstString g___value_("__value_");
325 
326   if (idx >= CalculateNumChildren())
327     return lldb::ValueObjectSP();
328   if (m_tree == nullptr || m_root_node == nullptr)
329     return lldb::ValueObjectSP();
330 
331   MapIterator iterator(m_root_node, CalculateNumChildren());
332 
333   const bool need_to_skip = (idx > 0);
334   size_t actual_advancde = idx;
335   if (need_to_skip) {
336     auto cached_iterator = m_iterators.find(idx - 1);
337     if (cached_iterator != m_iterators.end()) {
338       iterator = cached_iterator->second;
339       actual_advancde = 1;
340     }
341   }
342 
343   ValueObjectSP iterated_sp(iterator.advance(actual_advancde));
344   if (!iterated_sp) {
345     // this tree is garbage - stop
346     m_tree =
347         nullptr; // this will stop all future searches until an Update() happens
348     return iterated_sp;
349   }
350   if (GetDataType()) {
351     if (!need_to_skip) {
352       Error error;
353       iterated_sp = iterated_sp->Dereference(error);
354       if (!iterated_sp || error.Fail()) {
355         m_tree = nullptr;
356         return lldb::ValueObjectSP();
357       }
358       GetValueOffset(iterated_sp);
359       auto child_sp = iterated_sp->GetChildMemberWithName(g___value_, true);
360       if (child_sp)
361         iterated_sp = child_sp;
362       else
363         iterated_sp = iterated_sp->GetSyntheticChildAtOffset(
364             m_skip_size, m_element_type, true);
365       if (!iterated_sp) {
366         m_tree = nullptr;
367         return lldb::ValueObjectSP();
368       }
369     } else {
370       // because of the way our debug info is made, we need to read item 0 first
371       // so that we can cache information used to generate other elements
372       if (m_skip_size == UINT32_MAX)
373         GetChildAtIndex(0);
374       if (m_skip_size == UINT32_MAX) {
375         m_tree = nullptr;
376         return lldb::ValueObjectSP();
377       }
378       iterated_sp = iterated_sp->GetSyntheticChildAtOffset(
379           m_skip_size, m_element_type, true);
380       if (!iterated_sp) {
381         m_tree = nullptr;
382         return lldb::ValueObjectSP();
383       }
384     }
385   } else {
386     m_tree = nullptr;
387     return lldb::ValueObjectSP();
388   }
389   // at this point we have a valid
390   // we need to copy current_sp into a new object otherwise we will end up with
391   // all items named __value_
392   DataExtractor data;
393   Error error;
394   iterated_sp->GetData(data, error);
395   if (error.Fail()) {
396     m_tree = nullptr;
397     return lldb::ValueObjectSP();
398   }
399   StreamString name;
400   name.Printf("[%" PRIu64 "]", (uint64_t)idx);
401   auto potential_child_sp = CreateValueObjectFromData(
402       name.GetData(), data, m_backend.GetExecutionContextRef(), m_element_type);
403   if (potential_child_sp) {
404     switch (potential_child_sp->GetNumChildren()) {
405     case 1: {
406       auto child0_sp = potential_child_sp->GetChildAtIndex(0, true);
407       if (child0_sp && child0_sp->GetName() == g___cc)
408         potential_child_sp = child0_sp;
409       break;
410     }
411     case 2: {
412       auto child0_sp = potential_child_sp->GetChildAtIndex(0, true);
413       auto child1_sp = potential_child_sp->GetChildAtIndex(1, true);
414       if (child0_sp && child0_sp->GetName() == g___cc && child1_sp &&
415           child1_sp->GetName() == g___nc)
416         potential_child_sp = child0_sp;
417       break;
418     }
419     }
420     potential_child_sp->SetName(ConstString(name.GetData()));
421   }
422   m_iterators[idx] = iterator;
423   return potential_child_sp;
424 }
425 
426 bool lldb_private::formatters::LibcxxStdMapSyntheticFrontEnd::Update() {
427   static ConstString g___tree_("__tree_");
428   static ConstString g___begin_node_("__begin_node_");
429   m_count = UINT32_MAX;
430   m_tree = m_root_node = nullptr;
431   m_iterators.clear();
432   m_tree = m_backend.GetChildMemberWithName(g___tree_, true).get();
433   if (!m_tree)
434     return false;
435   m_root_node = m_tree->GetChildMemberWithName(g___begin_node_, true).get();
436   return false;
437 }
438 
439 bool lldb_private::formatters::LibcxxStdMapSyntheticFrontEnd::
440     MightHaveChildren() {
441   return true;
442 }
443 
444 size_t lldb_private::formatters::LibcxxStdMapSyntheticFrontEnd::
445     GetIndexOfChildWithName(const ConstString &name) {
446   return ExtractIndexFromString(name.GetCString());
447 }
448 
449 SyntheticChildrenFrontEnd *
450 lldb_private::formatters::LibcxxStdMapSyntheticFrontEndCreator(
451     CXXSyntheticChildren *, lldb::ValueObjectSP valobj_sp) {
452   return (valobj_sp ? new LibcxxStdMapSyntheticFrontEnd(valobj_sp) : nullptr);
453 }
454