• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2021 Code Intelligence GmbH
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  *      http://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 #pragma once
18 
19 #include <jni.h>
20 
21 #include <string>
22 #include <vector>
23 
24 #include "jvm_tooling.h"
25 
26 namespace jazzer {
27 
28 enum class RunResult {
29   kOk,
30   kException,
31   kDumpAndContinue,
32 };
33 
34 // Invokes the following static methods in the java fuzz target class:
35 // 1. On construction:
36 //    - `public static void fuzzerInitialize()`
37 //    OR
38 //    - `public static void fuzzerInitialize(String[] args)`
39 // 2. On every call of Run():
40 //    - `public static void fuzzerTestOneInput(FuzzedDataProvider data)`
41 //    OR
42 //    - `public static void fuzzerTestOneInput(byte[] input)`
43 // 3. On destruction:
44 //    - `public static void fuzzerTearDown()`
45 class FuzzTargetRunner : public ExceptionPrinter {
46  private:
47   const JVM &jvm_;
48   jclass jclass_;
49   jmethodID fuzzer_initialize_;
50   jmethodID fuzzer_initialize_with_args_;
51   jmethodID fuzzer_test_one_input_bytes_;
52   jmethodID fuzzer_test_one_input_data_;
53   jmethodID fuzzer_tear_down_;
54   jclass jazzer_;
55   jfieldID last_finding_;
56   std::vector<jlong> ignore_tokens_;
57 
58   [[nodiscard]] std::string DetectFuzzTargetClass() const;
59   [[nodiscard]] jthrowable GetFinding() const;
60 
61  public:
62   // Initializes the java fuzz target by calling `void fuzzerInitialize(...)`.
63   explicit FuzzTargetRunner(
64       JVM &jvm, const std::vector<std::string> &additional_target_args = {});
65 
66   // Calls the fuzz target tear down function. This can be useful to join any
67   // Threads so that the JVM shuts down correctly.
68   virtual ~FuzzTargetRunner();
69 
70   // Propagate the fuzzer input to the java fuzz target.
71   RunResult Run(const uint8_t *data, std::size_t size);
72 
73   void DumpReproducer(const uint8_t *data, std::size_t size);
74 };
75 
76 }  // namespace jazzer
77