xref: /aosp_15_r20/external/flatbuffers/tests/fuzzer/flatbuffers_annotator_fuzzer.cc (revision 890232f25432b36107d06881e0a25aaa6b473652)
1 
2 #include <filesystem>
3 #include <string>
4 
5 #include "binary_annotator.h"
6 #include "test_init.h"
7 
8 static std::filesystem::path exe_path_;
9 static const uint8_t *schema_bfbs_;
10 static size_t schema_bfbs_length_;
11 
TestFileExists(std::filesystem::path file_path)12 bool TestFileExists(std::filesystem::path file_path) {
13   if (file_path.has_filename() && std::filesystem::exists(file_path))
14     return true;
15 
16   TEST_OUTPUT_LINE("@DEBUG: file '%s' not found", file_path.string().c_str());
17   for (const auto &entry :
18        std::filesystem::directory_iterator(file_path.parent_path())) {
19     TEST_OUTPUT_LINE("@DEBUG: parent path entry: '%s'",
20                      entry.path().string().c_str());
21   }
22   return false;
23 }
24 
LoadBinarySchema(const char * file_name)25 std::string LoadBinarySchema(const char *file_name) {
26   const auto file_path = exe_path_.parent_path() / file_name;
27   TEST_EQ(true, TestFileExists(file_path));
28   std::string schemafile;
29   TEST_EQ(true,
30           flatbuffers::LoadFile(file_path.string().c_str(), true, &schemafile));
31 
32   flatbuffers::Verifier verifier(
33       reinterpret_cast<const uint8_t *>(schemafile.c_str()), schemafile.size());
34   TEST_EQ(true, reflection::VerifySchemaBuffer(verifier));
35   return schemafile;
36 }
37 
LLVMFuzzerInitialize(int *,char *** argv)38 extern "C" int LLVMFuzzerInitialize(int *, char ***argv) {
39   exe_path_ = (*argv)[0];
40   static const std::string schema_file =
41       LoadBinarySchema("annotated_binary.bfbs");
42   schema_bfbs_ = reinterpret_cast<const uint8_t *>(schema_file.c_str());
43   schema_bfbs_length_ = schema_file.size();
44   return 0;
45 }
46 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)47 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
48   flatbuffers::BinaryAnnotator annotator(schema_bfbs_, schema_bfbs_length_,
49                                          data, size);
50 
51   annotator.Annotate();
52   return 0;
53 }