Don't immediately abort for large maps and arrays am: 84292b6e8f am: b6c3c49c05 am: a7f5ed58d3 am: 2448b24d91

Original change: https://android-review.googlesource.com/c/platform/system/libcppbor/+/2494034

Change-Id: I052000fbbe9623068cf2c42f83f4aed73f0be520
Signed-off-by: Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>
diff --git a/src/cppbor_parse.cpp b/src/cppbor_parse.cpp
index a9a9b7d..2614c4e 100644
--- a/src/cppbor_parse.cpp
+++ b/src/cppbor_parse.cpp
@@ -128,7 +128,6 @@
     size_t size() const override { return mSize; }
 
     void add(std::unique_ptr<Item> item) override {
-        mEntries.reserve(mSize);
         mEntries.push_back(std::move(item));
     }
 
@@ -151,7 +150,6 @@
 
     void add(std::unique_ptr<Item> item) override {
         if (mKeyHeldForAdding) {
-            mEntries.reserve(mSize);
             mEntries.push_back({std::move(mKeyHeldForAdding), std::move(item)});
         } else {
             mKeyHeldForAdding = std::move(item);
diff --git a/tests/cppbor_test.cpp b/tests/cppbor_test.cpp
index 3c4d97f..aaa8bc5 100644
--- a/tests/cppbor_test.cpp
+++ b/tests/cppbor_test.cpp
@@ -1642,6 +1642,21 @@
     EXPECT_EQ(arr[0]->asTstr()->value(), "hello");
 }
 
+TEST(FullParserTest, ArrayTooBigForMemory) {
+    vector<uint8_t> encoded = {
+      // Array with 2^64 - 1 data items.
+      0x9B, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+      // First item.
+      0x01,
+      // Rest of the items are missing.
+    };
+
+    auto [item, pos, message] = parse(encoded);
+    EXPECT_THAT(item, IsNull());
+    EXPECT_EQ(pos, encoded.data());
+    EXPECT_EQ(message, "Not enough entries for array.");
+}
+
 TEST(FullParserTest, MutableOutput) {
     Array nestedArray("pizza", 31415);
     Map nestedMap("array", std::move(nestedArray));
@@ -1682,6 +1697,21 @@
     EXPECT_THAT(item, MatchesItem(ByRef(val)));
 }
 
+TEST(FullParserTest, MapTooBigForMemory) {
+    vector<uint8_t> encoded = {
+      // Map with 2^64 - 1 pairs of data items.
+      0xBB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+      // First pair.
+      0x01, 0x01,
+      // Rest of the pairs are missing.
+    };
+
+    auto [item, pos, message] = parse(encoded);
+    EXPECT_THAT(item, IsNull());
+    EXPECT_EQ(pos, encoded.data());
+    EXPECT_EQ(message, "Not enough entries for map.");
+}
+
 TEST(FullParserTest, SemanticTag) {
     SemanticTag val(99, "Salem");