1 //===-- StructuredData.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 
9 #include "lldb/Utility/StructuredData.h"
10 #include "lldb/Utility/FileSpec.h"
11 #include "lldb/Utility/Status.h"
12 #include "llvm/Support/MemoryBuffer.h"
13 #include <cerrno>
14 #include <cinttypes>
15 #include <cstdlib>
16 
17 using namespace lldb_private;
18 using namespace llvm;
19 
20 static StructuredData::ObjectSP ParseJSONValue(json::Value &value);
21 static StructuredData::ObjectSP ParseJSONObject(json::Object *object);
22 static StructuredData::ObjectSP ParseJSONArray(json::Array *array);
23 
24 StructuredData::ObjectSP
25 StructuredData::ParseJSON(const std::string &json_text) {
26   llvm::Expected<json::Value> value = json::parse(json_text);
27   if (!value) {
28     llvm::consumeError(value.takeError());
29     return nullptr;
30   }
31   return ParseJSONValue(*value);
32 }
33 
34 StructuredData::ObjectSP
35 StructuredData::ParseJSONFromFile(const FileSpec &input_spec, Status &error) {
36   StructuredData::ObjectSP return_sp;
37 
38   auto buffer_or_error = llvm::MemoryBuffer::getFile(input_spec.GetPath());
39   if (!buffer_or_error) {
40     error.SetErrorStringWithFormatv("could not open input file: {0} - {1}.",
41                                     input_spec.GetPath(),
42                                     buffer_or_error.getError().message());
43     return return_sp;
44   }
45   llvm::Expected<json::Value> value =
46       json::parse(buffer_or_error.get()->getBuffer().str());
47   if (value)
48     return ParseJSONValue(*value);
49   error.SetErrorString(toString(value.takeError()));
50   return StructuredData::ObjectSP();
51 }
52 
53 bool StructuredData::IsRecordType(const ObjectSP object_sp) {
54   return object_sp->GetType() == lldb::eStructuredDataTypeArray ||
55          object_sp->GetType() == lldb::eStructuredDataTypeDictionary;
56 }
57 
58 static StructuredData::ObjectSP ParseJSONValue(json::Value &value) {
59   if (json::Object *O = value.getAsObject())
60     return ParseJSONObject(O);
61 
62   if (json::Array *A = value.getAsArray())
63     return ParseJSONArray(A);
64 
65   if (auto s = value.getAsString())
66     return std::make_shared<StructuredData::String>(*s);
67 
68   if (auto b = value.getAsBoolean())
69     return std::make_shared<StructuredData::Boolean>(*b);
70 
71   if (auto i = value.getAsInteger())
72     return std::make_shared<StructuredData::Integer>(*i);
73 
74   if (auto d = value.getAsNumber())
75     return std::make_shared<StructuredData::Float>(*d);
76 
77   if (auto n = value.getAsNull())
78     return std::make_shared<StructuredData::Null>();
79 
80   return StructuredData::ObjectSP();
81 }
82 
83 static StructuredData::ObjectSP ParseJSONObject(json::Object *object) {
84   auto dict_up = std::make_unique<StructuredData::Dictionary>();
85   for (auto &KV : *object) {
86     StringRef key = KV.first;
87     json::Value value = KV.second;
88     if (StructuredData::ObjectSP value_sp = ParseJSONValue(value))
89       dict_up->AddItem(key, value_sp);
90   }
91   return std::move(dict_up);
92 }
93 
94 static StructuredData::ObjectSP ParseJSONArray(json::Array *array) {
95   auto array_up = std::make_unique<StructuredData::Array>();
96   for (json::Value &value : *array) {
97     if (StructuredData::ObjectSP value_sp = ParseJSONValue(value))
98       array_up->AddItem(value_sp);
99   }
100   return std::move(array_up);
101 }
102 
103 StructuredData::ObjectSP
104 StructuredData::Object::GetObjectForDotSeparatedPath(llvm::StringRef path) {
105   if (this->GetType() == lldb::eStructuredDataTypeDictionary) {
106     std::pair<llvm::StringRef, llvm::StringRef> match = path.split('.');
107     std::string key = match.first.str();
108     ObjectSP value = this->GetAsDictionary()->GetValueForKey(key);
109     if (value.get()) {
110       // Do we have additional words to descend?  If not, return the value
111       // we're at right now.
112       if (match.second.empty()) {
113         return value;
114       } else {
115         return value->GetObjectForDotSeparatedPath(match.second);
116       }
117     }
118     return ObjectSP();
119   }
120 
121   if (this->GetType() == lldb::eStructuredDataTypeArray) {
122     std::pair<llvm::StringRef, llvm::StringRef> match = path.split('[');
123     if (match.second.empty()) {
124       return this->shared_from_this();
125     }
126     errno = 0;
127     uint64_t val = strtoul(match.second.str().c_str(), nullptr, 10);
128     if (errno == 0) {
129       return this->GetAsArray()->GetItemAtIndex(val);
130     }
131     return ObjectSP();
132   }
133 
134   return this->shared_from_this();
135 }
136 
137 void StructuredData::Object::DumpToStdout(bool pretty_print) const {
138   json::OStream stream(llvm::outs(), pretty_print ? 2 : 0);
139   Serialize(stream);
140 }
141 
142 void StructuredData::Array::Serialize(json::OStream &s) const {
143   s.arrayBegin();
144   for (const auto &item_sp : m_items) {
145     item_sp->Serialize(s);
146   }
147   s.arrayEnd();
148 }
149 
150 void StructuredData::Integer::Serialize(json::OStream &s) const {
151   s.value(static_cast<int64_t>(m_value));
152 }
153 
154 void StructuredData::Float::Serialize(json::OStream &s) const {
155   s.value(m_value);
156 }
157 
158 void StructuredData::Boolean::Serialize(json::OStream &s) const {
159   s.value(m_value);
160 }
161 
162 void StructuredData::String::Serialize(json::OStream &s) const {
163   s.value(m_value);
164 }
165 
166 void StructuredData::Dictionary::Serialize(json::OStream &s) const {
167   s.objectBegin();
168   for (const auto &pair : m_dict) {
169     s.attributeBegin(pair.first.GetStringRef());
170     pair.second->Serialize(s);
171     s.attributeEnd();
172   }
173   s.objectEnd();
174 }
175 
176 void StructuredData::Null::Serialize(json::OStream &s) const {
177   s.value(nullptr);
178 }
179 
180 void StructuredData::Generic::Serialize(json::OStream &s) const {
181   s.value(llvm::formatv("{0:X}", m_object));
182 }
183 
184 void StructuredData::Integer::GetDescription(lldb_private::Stream &s) const {
185   s.Printf("%" PRId64, static_cast<int64_t>(m_value));
186 }
187 
188 void StructuredData::Float::GetDescription(lldb_private::Stream &s) const {
189   s.Printf("%f", m_value);
190 }
191 
192 void StructuredData::Boolean::GetDescription(lldb_private::Stream &s) const {
193   s.Printf(m_value ? "True" : "False");
194 }
195 
196 void StructuredData::String::GetDescription(lldb_private::Stream &s) const {
197   s.Printf("%s", m_value.empty() ? "\"\"" : m_value.c_str());
198 }
199 
200 void StructuredData::Array::GetDescription(lldb_private::Stream &s) const {
201   size_t index = 0;
202   size_t indentation_level = s.GetIndentLevel();
203   for (const auto &item_sp : m_items) {
204     // Sanitize.
205     if (!item_sp)
206       continue;
207 
208     // Reset original indentation level.
209     s.SetIndentLevel(indentation_level);
210     s.Indent();
211 
212     // Print key
213     s.Printf("[%zu]:", index++);
214 
215     // Return to new line and increase indentation if value is record type.
216     // Otherwise add spacing.
217     bool should_indent = IsRecordType(item_sp);
218     if (should_indent) {
219       s.EOL();
220       s.IndentMore();
221     } else {
222       s.PutChar(' ');
223     }
224 
225     // Print value and new line if now last pair.
226     item_sp->GetDescription(s);
227     if (item_sp != *(--m_items.end()))
228       s.EOL();
229 
230     // Reset indentation level if it was incremented previously.
231     if (should_indent)
232       s.IndentLess();
233   }
234 }
235 
236 void StructuredData::Dictionary::GetDescription(lldb_private::Stream &s) const {
237   size_t indentation_level = s.GetIndentLevel();
238   for (const auto &pair : m_dict) {
239     // Sanitize.
240     if (pair.first.IsNull() || pair.first.IsEmpty() || !pair.second)
241       continue;
242 
243     // Reset original indentation level.
244     s.SetIndentLevel(indentation_level);
245     s.Indent();
246 
247     // Print key.
248     s.Printf("%s:", pair.first.AsCString());
249 
250     // Return to new line and increase indentation if value is record type.
251     // Otherwise add spacing.
252     bool should_indent = IsRecordType(pair.second);
253     if (should_indent) {
254       s.EOL();
255       s.IndentMore();
256     } else {
257       s.PutChar(' ');
258     }
259 
260     // Print value and new line if now last pair.
261     pair.second->GetDescription(s);
262     if (pair != *(--m_dict.end()))
263       s.EOL();
264 
265     // Reset indentation level if it was incremented previously.
266     if (should_indent)
267       s.IndentLess();
268   }
269 }
270 
271 void StructuredData::Null::GetDescription(lldb_private::Stream &s) const {
272   s.Printf("NULL");
273 }
274 
275 void StructuredData::Generic::GetDescription(lldb_private::Stream &s) const {
276   s.Printf("%p", m_object);
277 }
278