blob: 2736b71151da9e73469f9003d4feb4ff01029eba [file] [log] [blame]
Max Bires44c78812020-04-10 09:38:23 -07001/*
2 * Copyright 2019 Google LLC
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * https://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "cppbor_parse.h"
18
Max Bires44c78812020-04-10 09:38:23 -070019#include <stack>
20
Bram Bonnéf04333a2020-10-20 16:40:52 +020021#ifndef __TRUSTY__
Shawn Willden6ad57322020-11-20 00:31:53 -070022#include <android-base/logging.h>
23#define LOG_TAG "CppBor"
Bram Bonnéf04333a2020-10-20 16:40:52 +020024#else
Shawn Willden6ad57322020-11-20 00:31:53 -070025#define CHECK(x) (void)(x)
Bram Bonnéf04333a2020-10-20 16:40:52 +020026#endif
Max Bires44c78812020-04-10 09:38:23 -070027
28namespace cppbor {
29
30namespace {
31
32std::string insufficientLengthString(size_t bytesNeeded, size_t bytesAvail,
33 const std::string& type) {
Bram Bonnéf04333a2020-10-20 16:40:52 +020034 char buf[1024];
Shawn Willden0f9cd2d2020-11-20 00:35:10 -070035 snprintf(buf, sizeof(buf), "Need %zu byte(s) for %s, have %zu.", bytesNeeded, type.c_str(),
Shawn Willden6ad57322020-11-20 00:31:53 -070036 bytesAvail);
Bram Bonnéf04333a2020-10-20 16:40:52 +020037 return std::string(buf);
Max Bires44c78812020-04-10 09:38:23 -070038}
39
40template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
41std::tuple<bool, uint64_t, const uint8_t*> parseLength(const uint8_t* pos, const uint8_t* end,
42 ParseClient* parseClient) {
43 if (pos + sizeof(T) > end) {
44 parseClient->error(pos - 1, insufficientLengthString(sizeof(T), end - pos, "length field"));
45 return {false, 0, pos};
46 }
47
48 const uint8_t* intEnd = pos + sizeof(T);
49 T result = 0;
50 do {
51 result = static_cast<T>((result << 8) | *pos++);
52 } while (pos < intEnd);
53 return {true, result, pos};
54}
55
56std::tuple<const uint8_t*, ParseClient*> parseRecursively(const uint8_t* begin, const uint8_t* end,
57 ParseClient* parseClient);
58
59std::tuple<const uint8_t*, ParseClient*> handleUint(uint64_t value, const uint8_t* hdrBegin,
60 const uint8_t* hdrEnd,
61 ParseClient* parseClient) {
62 std::unique_ptr<Item> item = std::make_unique<Uint>(value);
63 return {hdrEnd,
64 parseClient->item(item, hdrBegin, hdrEnd /* valueBegin */, hdrEnd /* itemEnd */)};
65}
66
67std::tuple<const uint8_t*, ParseClient*> handleNint(uint64_t value, const uint8_t* hdrBegin,
68 const uint8_t* hdrEnd,
69 ParseClient* parseClient) {
70 if (value > std::numeric_limits<int64_t>::max()) {
71 parseClient->error(hdrBegin, "NINT values that don't fit in int64_t are not supported.");
72 return {hdrBegin, nullptr /* end parsing */};
73 }
74 std::unique_ptr<Item> item = std::make_unique<Nint>(-1 - static_cast<uint64_t>(value));
75 return {hdrEnd,
76 parseClient->item(item, hdrBegin, hdrEnd /* valueBegin */, hdrEnd /* itemEnd */)};
77}
78
79std::tuple<const uint8_t*, ParseClient*> handleBool(uint64_t value, const uint8_t* hdrBegin,
80 const uint8_t* hdrEnd,
81 ParseClient* parseClient) {
82 std::unique_ptr<Item> item = std::make_unique<Bool>(value == TRUE);
83 return {hdrEnd,
84 parseClient->item(item, hdrBegin, hdrEnd /* valueBegin */, hdrEnd /* itemEnd */)};
85}
86
87std::tuple<const uint8_t*, ParseClient*> handleNull(const uint8_t* hdrBegin, const uint8_t* hdrEnd,
88 ParseClient* parseClient) {
89 std::unique_ptr<Item> item = std::make_unique<Null>();
90 return {hdrEnd,
91 parseClient->item(item, hdrBegin, hdrEnd /* valueBegin */, hdrEnd /* itemEnd */)};
92}
93
94template <typename T>
95std::tuple<const uint8_t*, ParseClient*> handleString(uint64_t length, const uint8_t* hdrBegin,
96 const uint8_t* valueBegin, const uint8_t* end,
97 const std::string& errLabel,
98 ParseClient* parseClient) {
99 if (end - valueBegin < static_cast<ssize_t>(length)) {
100 parseClient->error(hdrBegin, insufficientLengthString(length, end - valueBegin, errLabel));
101 return {hdrBegin, nullptr /* end parsing */};
102 }
103
104 std::unique_ptr<Item> item = std::make_unique<T>(valueBegin, valueBegin + length);
105 return {valueBegin + length,
106 parseClient->item(item, hdrBegin, valueBegin, valueBegin + length)};
107}
108
109class IncompleteItem {
110 public:
111 virtual ~IncompleteItem() {}
112 virtual void add(std::unique_ptr<Item> item) = 0;
113};
114
115class IncompleteArray : public Array, public IncompleteItem {
116 public:
Shawn Willden03990c22020-11-24 19:05:09 -0700117 explicit IncompleteArray(size_t size) : mSize(size) {}
Max Bires44c78812020-04-10 09:38:23 -0700118
119 // We return the "complete" size, rather than the actual size.
120 size_t size() const override { return mSize; }
121
122 void add(std::unique_ptr<Item> item) override {
123 mEntries.reserve(mSize);
124 mEntries.push_back(std::move(item));
125 }
126
127 private:
128 size_t mSize;
129};
130
131class IncompleteMap : public Map, public IncompleteItem {
132 public:
Shawn Willden03990c22020-11-24 19:05:09 -0700133 explicit IncompleteMap(size_t size) : mSize(size) {}
Max Bires44c78812020-04-10 09:38:23 -0700134
135 // We return the "complete" size, rather than the actual size.
136 size_t size() const override { return mSize; }
137
138 void add(std::unique_ptr<Item> item) override {
Shawn Willden03990c22020-11-24 19:05:09 -0700139 if (mKeyHeldForAdding) {
140 mEntries.reserve(mSize);
141 mEntries.push_back({std::move(mKeyHeldForAdding), std::move(item)});
142 } else {
143 mKeyHeldForAdding = std::move(item);
144 }
Max Bires44c78812020-04-10 09:38:23 -0700145 }
146
147 private:
Shawn Willden03990c22020-11-24 19:05:09 -0700148 std::unique_ptr<Item> mKeyHeldForAdding;
Max Bires44c78812020-04-10 09:38:23 -0700149 size_t mSize;
150};
151
152class IncompleteSemantic : public Semantic, public IncompleteItem {
153 public:
Shawn Willden03990c22020-11-24 19:05:09 -0700154 explicit IncompleteSemantic(uint64_t value) : Semantic(value) {}
Max Bires44c78812020-04-10 09:38:23 -0700155
156 // We return the "complete" size, rather than the actual size.
157 size_t size() const override { return 1; }
158
159 void add(std::unique_ptr<Item> item) override {
160 mEntries.reserve(1);
161 mEntries.push_back(std::move(item));
162 }
163};
164
165std::tuple<const uint8_t*, ParseClient*> handleEntries(size_t entryCount, const uint8_t* hdrBegin,
166 const uint8_t* pos, const uint8_t* end,
167 const std::string& typeName,
168 ParseClient* parseClient) {
169 while (entryCount > 0) {
170 --entryCount;
171 if (pos == end) {
172 parseClient->error(hdrBegin, "Not enough entries for " + typeName + ".");
173 return {hdrBegin, nullptr /* end parsing */};
174 }
175 std::tie(pos, parseClient) = parseRecursively(pos, end, parseClient);
176 if (!parseClient) return {hdrBegin, nullptr};
177 }
178 return {pos, parseClient};
179}
180
181std::tuple<const uint8_t*, ParseClient*> handleCompound(
182 std::unique_ptr<Item> item, uint64_t entryCount, const uint8_t* hdrBegin,
183 const uint8_t* valueBegin, const uint8_t* end, const std::string& typeName,
184 ParseClient* parseClient) {
185 parseClient =
186 parseClient->item(item, hdrBegin, valueBegin, valueBegin /* don't know the end yet */);
187 if (!parseClient) return {hdrBegin, nullptr};
188
189 const uint8_t* pos;
190 std::tie(pos, parseClient) =
191 handleEntries(entryCount, hdrBegin, valueBegin, end, typeName, parseClient);
192 if (!parseClient) return {hdrBegin, nullptr};
193
194 return {pos, parseClient->itemEnd(item, hdrBegin, valueBegin, pos)};
195}
196
197std::tuple<const uint8_t*, ParseClient*> parseRecursively(const uint8_t* begin, const uint8_t* end,
198 ParseClient* parseClient) {
199 const uint8_t* pos = begin;
200
201 MajorType type = static_cast<MajorType>(*pos & 0xE0);
202 uint8_t tagInt = *pos & 0x1F;
203 ++pos;
204
205 bool success = true;
206 uint64_t addlData;
207 if (tagInt < ONE_BYTE_LENGTH || tagInt > EIGHT_BYTE_LENGTH) {
208 addlData = tagInt;
209 } else {
210 switch (tagInt) {
211 case ONE_BYTE_LENGTH:
212 std::tie(success, addlData, pos) = parseLength<uint8_t>(pos, end, parseClient);
213 break;
214
215 case TWO_BYTE_LENGTH:
216 std::tie(success, addlData, pos) = parseLength<uint16_t>(pos, end, parseClient);
217 break;
218
219 case FOUR_BYTE_LENGTH:
220 std::tie(success, addlData, pos) = parseLength<uint32_t>(pos, end, parseClient);
221 break;
222
223 case EIGHT_BYTE_LENGTH:
224 std::tie(success, addlData, pos) = parseLength<uint64_t>(pos, end, parseClient);
225 break;
226
227 default:
228 CHECK(false); // It's impossible to get here
229 break;
230 }
231 }
232
233 if (!success) return {begin, nullptr};
234
235 switch (type) {
236 case UINT:
237 return handleUint(addlData, begin, pos, parseClient);
238
239 case NINT:
240 return handleNint(addlData, begin, pos, parseClient);
241
242 case BSTR:
243 return handleString<Bstr>(addlData, begin, pos, end, "byte string", parseClient);
244
245 case TSTR:
246 return handleString<Tstr>(addlData, begin, pos, end, "text string", parseClient);
247
248 case ARRAY:
249 return handleCompound(std::make_unique<IncompleteArray>(addlData), addlData, begin, pos,
250 end, "array", parseClient);
251
252 case MAP:
253 return handleCompound(std::make_unique<IncompleteMap>(addlData), addlData * 2, begin,
254 pos, end, "map", parseClient);
255
256 case SEMANTIC:
257 return handleCompound(std::make_unique<IncompleteSemantic>(addlData), 1, begin, pos,
258 end, "semantic", parseClient);
259
260 case SIMPLE:
261 switch (addlData) {
262 case TRUE:
263 case FALSE:
264 return handleBool(addlData, begin, pos, parseClient);
265 case NULL_V:
266 return handleNull(begin, pos, parseClient);
267 }
268 }
269 CHECK(false); // Impossible to get here.
270 return {};
271}
272
273class FullParseClient : public ParseClient {
274 public:
275 virtual ParseClient* item(std::unique_ptr<Item>& item, const uint8_t*, const uint8_t*,
276 const uint8_t* end) override {
277 if (mParentStack.empty() && !item->isCompound()) {
278 // This is the first and only item.
279 mTheItem = std::move(item);
280 mPosition = end;
281 return nullptr; // We're done.
282 }
283
284 if (item->isCompound()) {
285 // Starting a new compound data item, i.e. a new parent. Save it on the parent stack.
286 // It's safe to save a raw pointer because the unique_ptr is guaranteed to stay in
287 // existence until the corresponding itemEnd() call.
Shawn Willdenc5a4a3f2020-12-01 08:14:39 -0700288 mParentStack.push(item.get());
Max Bires44c78812020-04-10 09:38:23 -0700289 return this;
290 } else {
291 appendToLastParent(std::move(item));
292 return this;
293 }
294 }
295
296 virtual ParseClient* itemEnd(std::unique_ptr<Item>& item, const uint8_t*, const uint8_t*,
297 const uint8_t* end) override {
298 CHECK(item->isCompound() && item.get() == mParentStack.top());
299 mParentStack.pop();
300
301 if (mParentStack.empty()) {
302 mTheItem = std::move(item);
303 mPosition = end;
304 return nullptr; // We're done
305 } else {
306 appendToLastParent(std::move(item));
307 return this;
308 }
309 }
310
311 virtual void error(const uint8_t* position, const std::string& errorMessage) override {
312 mPosition = position;
313 mErrorMessage = errorMessage;
314 }
315
316 std::tuple<std::unique_ptr<Item> /* result */, const uint8_t* /* newPos */,
317 std::string /* errMsg */>
318 parseResult() {
319 std::unique_ptr<Item> p = std::move(mTheItem);
320 return {std::move(p), mPosition, std::move(mErrorMessage)};
321 }
322
323 private:
324 void appendToLastParent(std::unique_ptr<Item> item) {
325 auto parent = mParentStack.top();
Shawn Willden6ad57322020-11-20 00:31:53 -0700326#if __has_feature(cxx_rtti)
327 assert(dynamic_cast<IncompleteItem*>(parent));
328#endif
Max Bires44c78812020-04-10 09:38:23 -0700329 if (parent->type() == ARRAY) {
330 static_cast<IncompleteArray*>(parent)->add(std::move(item));
331 } else if (parent->type() == MAP) {
332 static_cast<IncompleteMap*>(parent)->add(std::move(item));
333 } else if (parent->type() == SEMANTIC) {
334 static_cast<IncompleteSemantic*>(parent)->add(std::move(item));
335 } else {
336 CHECK(false); // Impossible to get here.
337 }
338 }
339
340 std::unique_ptr<Item> mTheItem;
Shawn Willdenc5a4a3f2020-12-01 08:14:39 -0700341 std::stack<Item*> mParentStack;
Max Bires44c78812020-04-10 09:38:23 -0700342 const uint8_t* mPosition = nullptr;
343 std::string mErrorMessage;
344};
345
346} // anonymous namespace
347
348void parse(const uint8_t* begin, const uint8_t* end, ParseClient* parseClient) {
349 parseRecursively(begin, end, parseClient);
350}
351
352std::tuple<std::unique_ptr<Item> /* result */, const uint8_t* /* newPos */,
353 std::string /* errMsg */>
354parse(const uint8_t* begin, const uint8_t* end) {
355 FullParseClient parseClient;
356 parse(begin, end, &parseClient);
357 return parseClient.parseResult();
358}
359
360} // namespace cppbor