1 /*
2 * Copyright (C) 2024 The Android Open Source Project
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 #include <iostream>
18
19 #include "android-base/file.h"
20 #include "android-base/strings.h"
21 #include "base/file_utils.h"
22 #include "base/mem_map.h"
23 #include "dex/class_accessor-inl.h"
24 #include "dex/dex_file_verifier.h"
25 #include "dex/standard_dex_file.h"
26 #include "handle_scope-inl.h"
27 #include "interpreter/unstarted_runtime.h"
28 #include "jni/java_vm_ext.h"
29 #include "noop_compiler_callbacks.h"
30 #include "runtime.h"
31 #include "scoped_thread_state_change-inl.h"
32 #include "verifier/class_verifier.h"
33 #include "well_known_classes.h"
34
35 // Global variable to count how many DEX files passed DEX file verification and they were
36 // registered, since these are the cases for which we would be running the GC. In case of
37 // scheduling multiple fuzzer jobs, using the ‘-jobs’ flag, this is not shared among the threads.
38 int skipped_gc_iterations = 0;
39 // Global variable to call the GC once every maximum number of iterations.
40 // TODO: These values were obtained from local experimenting. They can be changed after
41 // further investigation.
42 static constexpr int kMaxSkipGCIterations = 100;
43 // Global variable to signal LSAN that we are not leaking memory.
44 uint8_t* allocated_signal_stack = nullptr;
45
46 namespace art {
47 // A class to be friends with ClassLinker and access the internal FindDexCacheDataLocked method.
48 class VerifyClassesFuzzerHelper {
49 public:
GetDexCacheData(Runtime * runtime,const DexFile * dex_file)50 static const ClassLinker::DexCacheData* GetDexCacheData(Runtime* runtime, const DexFile* dex_file)
51 REQUIRES_SHARED(Locks::mutator_lock_) {
52 Thread* self = Thread::Current();
53 ReaderMutexLock mu(self, *Locks::dex_lock_);
54 ClassLinker* class_linker = runtime->GetClassLinker();
55 const ClassLinker::DexCacheData* cached_data = class_linker->FindDexCacheDataLocked(*dex_file);
56 return cached_data;
57 }
58 };
59 } // namespace art
60
GetDexFileName(const std::string & jar_name)61 std::string GetDexFileName(const std::string& jar_name) {
62 // The jar files are located in the data directory within the directory of the fuzzer's binary.
63 std::string executable_dir = android::base::GetExecutableDirectory();
64
65 std::string result =
66 android::base::StringPrintf("%s/data/%s.jar", executable_dir.c_str(), jar_name.c_str());
67
68 return result;
69 }
70
GetLibCoreDexFileNames()71 std::vector<std::string> GetLibCoreDexFileNames() {
72 std::vector<std::string> result;
73 const std::vector<std::string> modules = {
74 "core-oj",
75 "core-libart",
76 "okhttp",
77 "bouncycastle",
78 "apache-xml",
79 "core-icu4j",
80 "conscrypt",
81 };
82 result.reserve(modules.size());
83 for (const std::string& module : modules) {
84 result.push_back(GetDexFileName(module));
85 }
86 return result;
87 }
88
GetClassPathOption(const char * option,const std::vector<std::string> & class_path)89 std::string GetClassPathOption(const char* option, const std::vector<std::string>& class_path) {
90 return option + android::base::Join(class_path, ':');
91 }
92
RegisterDexFileAndGetClassLoader(art::Runtime * runtime,art::StandardDexFile * dex_file)93 jobject RegisterDexFileAndGetClassLoader(art::Runtime* runtime, art::StandardDexFile* dex_file)
94 REQUIRES_SHARED(art::Locks::mutator_lock_) {
95 art::Thread* self = art::Thread::Current();
96 art::ClassLinker* class_linker = runtime->GetClassLinker();
97 const std::vector<const art::DexFile*> dex_files = {dex_file};
98 jobject class_loader = class_linker->CreatePathClassLoader(self, dex_files);
99 art::ObjPtr<art::mirror::ClassLoader> cl = self->DecodeJObject(class_loader)->AsClassLoader();
100 class_linker->RegisterDexFile(*dex_file, cl);
101 return class_loader;
102 }
103
LLVMFuzzerInitialize(int * argc,char *** argv)104 extern "C" int LLVMFuzzerInitialize([[maybe_unused]] int* argc, [[maybe_unused]] char*** argv) {
105 // Set logging to error and above to avoid warnings about unexpected checksums.
106 android::base::SetMinimumLogSeverity(android::base::ERROR);
107
108 // Create runtime.
109 art::RuntimeOptions options;
110 {
111 static art::NoopCompilerCallbacks callbacks;
112 options.push_back(std::make_pair("compilercallbacks", &callbacks));
113 }
114
115 std::string boot_class_path_string =
116 GetClassPathOption("-Xbootclasspath:", GetLibCoreDexFileNames());
117 options.push_back(std::make_pair(boot_class_path_string, nullptr));
118
119 // Instruction set.
120 options.push_back(
121 std::make_pair("imageinstructionset",
122 reinterpret_cast<const void*>(GetInstructionSetString(art::kRuntimeISA))));
123
124 // No need for sig chain.
125 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
126
127 if (!art::Runtime::Create(options, false)) {
128 LOG(FATAL) << "We should always be able to create the runtime";
129 UNREACHABLE();
130 }
131
132 // Need well-known-classes.
133 art::WellKnownClasses::Init(art::Thread::Current()->GetJniEnv());
134 // Need a class loader. Fake that we're a compiler.
135 // Note: this will run initializers through the unstarted runtime, so make sure it's
136 // initialized.
137 art::interpreter::UnstartedRuntime::Initialize();
138
139 art::Thread::Current()->TransitionFromRunnableToSuspended(art::ThreadState::kNative);
140
141 // Query the current stack and add it to the global variable. Otherwise LSAN complains about a
142 // non-existing leak.
143 stack_t ss;
144 if (sigaltstack(nullptr, &ss) == -1) {
145 PLOG(FATAL) << "sigaltstack failed";
146 }
147 allocated_signal_stack = reinterpret_cast<uint8_t*>(ss.ss_sp);
148
149 return 0;
150 }
151
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)152 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
153 // Do not verify the checksum as we only care about the DEX file contents,
154 // and know that the checksum would probably be erroneous (i.e. random).
155 constexpr bool kVerify = false;
156
157 auto container = std::make_shared<art::MemoryDexFileContainer>(data, size);
158 art::StandardDexFile dex_file(data,
159 /*location=*/"fuzz.dex",
160 /*location_checksum=*/0,
161 /*oat_dex_file=*/nullptr,
162 container);
163 std::string error_msg;
164 const bool verify_result =
165 art::dex::Verify(&dex_file, dex_file.GetLocation().c_str(), kVerify, &error_msg);
166
167 if (!verify_result) {
168 // DEX file couldn't be verified, don't save it in the corpus.
169 return -1;
170 }
171
172 art::Runtime* runtime = art::Runtime::Current();
173 CHECK(runtime != nullptr);
174
175 art::ScopedObjectAccess soa(art::Thread::Current());
176 art::ClassLinker* class_linker = runtime->GetClassLinker();
177 jobject class_loader = RegisterDexFileAndGetClassLoader(runtime, &dex_file);
178
179 // Scope for the handles
180 {
181 art::StackHandleScope<3> scope(soa.Self());
182 art::Handle<art::mirror::ClassLoader> h_loader =
183 scope.NewHandle(soa.Decode<art::mirror::ClassLoader>(class_loader));
184 art::MutableHandle<art::mirror::Class> h_klass(scope.NewHandle<art::mirror::Class>(nullptr));
185 art::MutableHandle<art::mirror::DexCache> h_dex_cache(
186 scope.NewHandle<art::mirror::DexCache>(nullptr));
187
188 for (art::ClassAccessor accessor : dex_file.GetClasses()) {
189 h_klass.Assign(
190 class_linker->FindClass(soa.Self(), dex_file, accessor.GetClassIdx(), h_loader));
191 // Ignore classes that couldn't be loaded since we are looking for crashes during
192 // class/method verification.
193 if (h_klass == nullptr || h_klass->IsErroneous()) {
194 soa.Self()->ClearException();
195 continue;
196 }
197 h_dex_cache.Assign(h_klass->GetDexCache());
198 art::verifier::ClassVerifier::VerifyClass(soa.Self(),
199 /* verifier_deps= */ nullptr,
200 h_dex_cache->GetDexFile(),
201 h_klass,
202 h_dex_cache,
203 h_loader,
204 *h_klass->GetClassDef(),
205 runtime->GetCompilerCallbacks(),
206 art::verifier::HardFailLogMode::kLogWarning,
207 /* api_level= */ 0,
208 &error_msg);
209 }
210 }
211
212 skipped_gc_iterations++;
213
214 // Delete weak root to the DexCache before removing a DEX file from the cache. This is usually
215 // handled by the GC, but since we are not calling it every iteration, we need to delete them
216 // manually.
217 const art::ClassLinker::DexCacheData* dex_cache_data =
218 art::VerifyClassesFuzzerHelper::GetDexCacheData(runtime, &dex_file);
219 soa.Env()->GetVm()->DeleteWeakGlobalRef(soa.Self(), dex_cache_data->weak_root);
220
221 class_linker->RemoveDexFromCaches(dex_file);
222
223 // Delete global ref and unload class loader to free RAM.
224 soa.Env()->GetVm()->DeleteGlobalRef(soa.Self(), class_loader);
225
226 if (skipped_gc_iterations == kMaxSkipGCIterations) {
227 runtime->GetHeap()->CollectGarbage(/* clear_soft_references */ true);
228 skipped_gc_iterations = 0;
229 }
230
231 return 0;
232 }
233