xref: /aosp_15_r20/external/jazzer-api/src/main/native/com/code_intelligence/jazzer/driver/fuzz_target_runner.cpp (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 /**
16  * A native wrapper around the FuzzTargetRunner Java class that executes it as a
17  * libFuzzer fuzz target.
18  */
19 
20 #include "fuzz_target_runner.h"
21 
22 #ifndef _WIN32
23 #include <dlfcn.h>
24 #endif
25 #include <jni.h>
26 #include <stdint.h>
27 
28 #include <iostream>
29 #include <limits>
30 #include <string>
31 #include <vector>
32 
33 #include "com_code_intelligence_jazzer_runtime_FuzzTargetRunnerNatives.h"
34 
35 extern "C" int LLVMFuzzerRunDriver(int *argc, char ***argv,
36                                    int (*UserCb)(const uint8_t *Data,
37                                                  size_t Size));
38 extern "C" size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize);
39 
40 namespace {
41 jclass gRunner;
42 jmethodID gRunOneId;
43 jmethodID gMutateOneId;
44 jmethodID gCrossOverId;
45 JavaVM *gJavaVm;
46 JNIEnv *gEnv;
47 jboolean gUseExperimentalMutator;
48 
49 // A libFuzzer-registered callback that outputs the crashing input, but does
50 // not include a stack trace.
51 void (*gLibfuzzerPrintCrashingInput)() = nullptr;
52 
testOneInput(const uint8_t * data,const std::size_t size)53 int testOneInput(const uint8_t *data, const std::size_t size) {
54   JNIEnv &env = *gEnv;
55   jint jsize =
56       std::min(size, static_cast<size_t>(std::numeric_limits<jint>::max()));
57   int res = env.CallStaticIntMethod(gRunner, gRunOneId, data, jsize);
58   if (env.ExceptionCheck()) {
59     env.ExceptionDescribe();
60     _Exit(1);
61   }
62   return res;
63 }
64 }  // namespace
65 
LLVMFuzzerCustomMutator(uint8_t * Data,size_t Size,size_t MaxSize,unsigned int Seed)66 extern "C" size_t LLVMFuzzerCustomMutator(uint8_t *Data, size_t Size,
67                                           size_t MaxSize, unsigned int Seed) {
68   if (gUseExperimentalMutator) {
69     JNIEnv &env = *gEnv;
70     jint jsize =
71         std::min(Size, static_cast<size_t>(std::numeric_limits<jint>::max()));
72     jint jmaxSize = std::min(
73         MaxSize, static_cast<size_t>(std::numeric_limits<jint>::max()));
74     jint jseed = static_cast<jint>(Seed);
75     jint newSize = env.CallStaticLongMethod(gRunner, gMutateOneId, Data, jsize,
76                                             jmaxSize, jseed);
77     if (env.ExceptionCheck()) {
78       env.ExceptionDescribe();
79       _Exit(1);
80     }
81     return static_cast<uint32_t>(newSize);
82   } else {
83     return LLVMFuzzerMutate(Data, Size, MaxSize);
84   }
85 }
86 
LLVMFuzzerCustomCrossOver(const uint8_t * Data1,size_t Size1,const uint8_t * Data2,size_t Size2,uint8_t * Out,size_t MaxOutSize,unsigned int Seed)87 extern "C" size_t LLVMFuzzerCustomCrossOver(const uint8_t *Data1, size_t Size1,
88                                             const uint8_t *Data2, size_t Size2,
89                                             uint8_t *Out, size_t MaxOutSize,
90                                             unsigned int Seed) {
91   if (gUseExperimentalMutator) {
92     JNIEnv &env = *gEnv;
93     jint jsize1 =
94         std::min(Size1, static_cast<size_t>(std::numeric_limits<jint>::max()));
95     jint jsize2 =
96         std::min(Size2, static_cast<size_t>(std::numeric_limits<jint>::max()));
97     jint jMaxOutSize = std::min(
98         MaxOutSize, static_cast<size_t>(std::numeric_limits<jint>::max()));
99     jint jseed = static_cast<jint>(Seed);
100 
101     jint newSize =
102         env.CallStaticLongMethod(gRunner, gCrossOverId, Data1, jsize1, Data2,
103                                  jsize2, Out, jMaxOutSize, jseed);
104     if (env.ExceptionCheck()) {
105       env.ExceptionDescribe();
106       _Exit(1);
107     }
108     return static_cast<uint32_t>(newSize);
109   } else {
110     // No custom cross over supported.
111     return 0;
112   }
113 }
114 
115 namespace jazzer {
DumpJvmStackTraces()116 void DumpJvmStackTraces() {
117   JNIEnv *env = nullptr;
118   if (gJavaVm->AttachCurrentThread(reinterpret_cast<void **>(&env), nullptr) !=
119       JNI_OK) {
120     return;
121   }
122   jmethodID dumpStack =
123       env->GetStaticMethodID(gRunner, "dumpAllStackTraces", "()V");
124   if (env->ExceptionCheck()) {
125     env->ExceptionDescribe();
126     return;
127   }
128   env->CallStaticVoidMethod(gRunner, dumpStack);
129   if (env->ExceptionCheck()) {
130     env->ExceptionDescribe();
131     return;
132   }
133   // Do not detach as we may be the main thread (but the JVM exits anyway).
134 }
135 }  // namespace jazzer
136 
137 [[maybe_unused]] jint
Java_com_code_1intelligence_jazzer_runtime_FuzzTargetRunnerNatives_startLibFuzzer(JNIEnv * env,jclass,jobjectArray args,jclass runner,jboolean useExperimentalMutator)138 Java_com_code_1intelligence_jazzer_runtime_FuzzTargetRunnerNatives_startLibFuzzer(
139     JNIEnv *env, jclass, jobjectArray args, jclass runner,
140     jboolean useExperimentalMutator) {
141   gUseExperimentalMutator = useExperimentalMutator;
142   gEnv = env;
143   env->GetJavaVM(&gJavaVm);
144   gRunner = reinterpret_cast<jclass>(env->NewGlobalRef(runner));
145   gRunOneId = env->GetStaticMethodID(runner, "runOne", "(JI)I");
146   gMutateOneId = env->GetStaticMethodID(runner, "mutateOne", "(JIII)I");
147   gCrossOverId = env->GetStaticMethodID(runner, "crossOver", "(JIJIJII)I");
148   if (gRunOneId == nullptr) {
149     env->ExceptionDescribe();
150     _Exit(1);
151   }
152 
153   int argc = env->GetArrayLength(args);
154   if (env->ExceptionCheck()) {
155     env->ExceptionDescribe();
156     _Exit(1);
157   }
158   std::vector<std::string> argv_strings;
159   std::vector<const char *> argv_c;
160   for (jsize i = 0; i < argc; i++) {
161     auto arg_jni =
162         reinterpret_cast<jbyteArray>(env->GetObjectArrayElement(args, i));
163     if (arg_jni == nullptr) {
164       env->ExceptionDescribe();
165       _Exit(1);
166     }
167     jbyte *arg_c = env->GetByteArrayElements(arg_jni, nullptr);
168     if (arg_c == nullptr) {
169       env->ExceptionDescribe();
170       _Exit(1);
171     }
172     std::size_t arg_size = env->GetArrayLength(arg_jni);
173     if (env->ExceptionCheck()) {
174       env->ExceptionDescribe();
175       _Exit(1);
176     }
177     argv_strings.emplace_back(reinterpret_cast<const char *>(arg_c), arg_size);
178     env->ReleaseByteArrayElements(arg_jni, arg_c, JNI_ABORT);
179     if (env->ExceptionCheck()) {
180       env->ExceptionDescribe();
181       _Exit(1);
182     }
183   }
184   for (jsize i = 0; i < argc; i++) {
185     argv_c.emplace_back(argv_strings[i].c_str());
186   }
187   // Null-terminate argv.
188   argv_c.emplace_back(nullptr);
189 
190   const char **argv = argv_c.data();
191   return LLVMFuzzerRunDriver(&argc, const_cast<char ***>(&argv), testOneInput);
192 }
193 
194 [[maybe_unused]] void
Java_com_code_1intelligence_jazzer_runtime_FuzzTargetRunnerNatives_printCrashingInput(JNIEnv *,jclass)195 Java_com_code_1intelligence_jazzer_runtime_FuzzTargetRunnerNatives_printCrashingInput(
196     JNIEnv *, jclass) {
197   if (gLibfuzzerPrintCrashingInput == nullptr) {
198     std::cerr << "<not available>" << std::endl;
199   } else {
200     gLibfuzzerPrintCrashingInput();
201   }
202 }
203 
204 namespace fuzzer {
205 // Defined in:
206 // https://github.com/llvm/llvm-project/blob/27cc31b64c0491725aa88a6822f0f2a2c18914d7/compiler-rt/lib/fuzzer/FuzzerLoop.cpp#L43
207 // Used here:
208 // https://github.com/llvm/llvm-project/blob/27cc31b64c0491725aa88a6822f0f2a2c18914d7/compiler-rt/lib/fuzzer/FuzzerLoop.cpp#L244
209 extern bool RunningUserCallback;
210 }  // namespace fuzzer
211 
212 [[maybe_unused]] void
Java_com_code_1intelligence_jazzer_runtime_FuzzTargetRunnerNatives_temporarilyDisableLibfuzzerExitHook(JNIEnv *,jclass)213 Java_com_code_1intelligence_jazzer_runtime_FuzzTargetRunnerNatives_temporarilyDisableLibfuzzerExitHook(
214     JNIEnv *, jclass) {
215   ::fuzzer::RunningUserCallback = false;
216 }
217 
218 // We apply a patch to libFuzzer to make it call this function instead of
219 // __sanitizer_set_death_callback to pass us the death callback.
__jazzer_set_death_callback(void (* callback)())220 extern "C" [[maybe_unused]] void __jazzer_set_death_callback(
221     void (*callback)()) {
222   gLibfuzzerPrintCrashingInput = callback;
223 #ifndef _WIN32
224   void *sanitizer_set_death_callback =
225       dlsym(RTLD_DEFAULT, "__sanitizer_set_death_callback");
226   if (sanitizer_set_death_callback != nullptr) {
227     (reinterpret_cast<void (*)(void (*)())>(sanitizer_set_death_callback))(
228         []() {
229           ::jazzer::DumpJvmStackTraces();
230           gLibfuzzerPrintCrashingInput();
231           // Ideally, we would be able to perform a graceful shutdown of the
232           // JVM. However, doing this directly results in a nested bug report by
233           // ASan or UBSan, likely because something about the stack/thread
234           // context in which they generate reports is incompatible with the JVM
235           // shutdown process. use_sigaltstack=0 does not help though, so this
236           // might be on us.
237         });
238   }
239 #endif
240 }
241