Upgrade to 1.46.0
[platform/upstream/nghttp2.git] / third-party / mruby / oss-fuzz / mruby_proto_fuzzer.cpp
1 #include <string>
2 #include <iostream>
3 #include <fstream>
4
5 #include <mruby.h>
6 #include <mruby/compile.h>
7
8 #include "libprotobuf-mutator/src/libfuzzer/libfuzzer_macro.h"
9 #include "ruby.pb.h"
10 #include "proto_to_ruby.h"
11
12 using namespace ruby_fuzzer;
13 using namespace std;
14
15 int FuzzRB(const uint8_t *Data, size_t size) {
16         mrb_value v;
17         mrb_state *mrb = mrb_open();
18         if (!mrb)
19                 return 0;
20
21         char *code = (char *)malloc(size+1);
22         if (!code)
23                 return 0;
24         memcpy(code, Data, size);
25         code[size] = '\0';
26
27         if (const char *dump_path = getenv("PROTO_FUZZER_DUMP_PATH")) {
28                 // With libFuzzer binary run this to generate an RB file x.rb:
29                 // PROTO_FUZZER_DUMP_PATH=x.rb ./a.out proto-input
30                 std::ofstream of(dump_path);
31                 of.write(code, size);
32         }
33         v = mrb_load_string(mrb, code);
34         mrb_close(mrb);
35
36         free(code);
37         return 0;
38 }
39
40 DEFINE_PROTO_FUZZER(const Function &function) {
41         protoConverter converter;
42         auto s = converter.FunctionToString(function);
43         (void)FuzzRB((const uint8_t*)s.data(), s.size());
44 }