Handle verifying an empty flatbuffer without crashing
We would before dereference nullptr looking for the start of the message
to verify. Since that question already didn't make sense, don't even
bother starting.
Change-Id: I086a0ea2f0a1858e83406e4c36c51699d8dd344e
diff --git a/aos/BUILD b/aos/BUILD
index 2761cbf..9a62e66 100644
--- a/aos/BUILD
+++ b/aos/BUILD
@@ -547,3 +547,16 @@
"//aos/testing:googletest",
],
)
+
+cc_test(
+ name = "flatbuffers_test",
+ srcs = [
+ "flatbuffers_test.cc",
+ ],
+ deps = [
+ ":flatbuffers",
+ ":json_to_flatbuffer",
+ ":json_to_flatbuffer_flatbuffer",
+ "//aos/testing:googletest",
+ ],
+)
diff --git a/aos/flatbuffers.h b/aos/flatbuffers.h
index adb9769..b751a4e 100644
--- a/aos/flatbuffers.h
+++ b/aos/flatbuffers.h
@@ -117,6 +117,9 @@
void Wipe() { memset(span().data(), 0, span().size()); }
bool Verify() const {
+ if (span().size() < 4u) {
+ return false;
+ }
flatbuffers::Verifier v(span().data(), span().size());
return v.VerifyTable(&message());
}
diff --git a/aos/flatbuffers_test.cc b/aos/flatbuffers_test.cc
new file mode 100644
index 0000000..e3030f1
--- /dev/null
+++ b/aos/flatbuffers_test.cc
@@ -0,0 +1,25 @@
+#include "aos/flatbuffers.h"
+
+#include "gtest/gtest.h"
+
+#include "aos/json_to_flatbuffer.h"
+#include "aos/json_to_flatbuffer_generated.h"
+
+namespace aos {
+namespace testing {
+
+// Tests that Verify works.
+TEST(FlatbufferTest, Verify) {
+ FlatbufferDetachedBuffer<Configuration> fb =
+ JsonToFlatbuffer<Configuration>("{}");
+ FlatbufferSpan<Configuration> fb_span(fb);
+ EXPECT_TRUE(fb.Verify());
+ EXPECT_TRUE(fb_span.Verify());
+
+ // Now confirm it works on an empty flatbuffer.
+ FlatbufferSpan<Configuration> empty(absl::Span<const uint8_t>(nullptr, 0));
+ EXPECT_FALSE(empty.Verify());
+}
+
+} // namespace testing
+} // namespace aos