xref: /aosp_15_r20/external/jazzer-api/src/main/java/com/code_intelligence/jazzer/runtime/JazzerInternal.java (revision 33edd6723662ea34453766bfdca85dbfdd5342b8)
1 // Copyright 2021 Code Intelligence GmbH
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 package com.code_intelligence.jazzer.runtime;
16 
17 import java.util.ArrayList;
18 
19 final public class JazzerInternal {
20   public static Throwable lastFinding;
21   // The value is only relevant when regression testing. Read by the bytecode emitted by
22   // HookMethodVisitor to enable hooks only when invoked from a @FuzzTest.
23   //
24   // Alternatives considered:
25   // Making this thread local rather than global may potentially allow to run fuzz tests in
26   // parallel with regular unit tests, but it is next to impossible to determine which thread is
27   // currently doing work for a fuzz test versus a regular unit test. Instead, @FuzzTest is
28   // annotated with @Isolated.
29   @SuppressWarnings("unused") public static boolean hooksEnabled = true;
30 
31   private static final ArrayList<Runnable> onFuzzTargetReadyCallbacks = new ArrayList<>();
32 
33   // Accessed from api.Jazzer via reflection.
reportFindingFromHook(Throwable finding)34   public static void reportFindingFromHook(Throwable finding) {
35     lastFinding = finding;
36     // Throw an Error that is hard to catch (short of outright ignoring it) in order to quickly
37     // terminate the execution of the fuzz target. The finding will be reported as soon as the fuzz
38     // target returns even if this Error is swallowed.
39     throw new HardToCatchError();
40   }
41 
registerOnFuzzTargetReadyCallback(Runnable callback)42   public static void registerOnFuzzTargetReadyCallback(Runnable callback) {
43     onFuzzTargetReadyCallbacks.add(callback);
44   }
45 
onFuzzTargetReady(String fuzzTargetClass)46   public static void onFuzzTargetReady(String fuzzTargetClass) {
47     onFuzzTargetReadyCallbacks.forEach(Runnable::run);
48     onFuzzTargetReadyCallbacks.clear();
49   }
50 }
51