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