1 /*
2  * Copyright (C) 2015 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 "oat_file_manager.h"
18 
19 #include <memory>
20 #include <queue>
21 #include <vector>
22 #include <sys/stat.h>
23 
24 #include "android-base/stringprintf.h"
25 #include "android-base/strings.h"
26 
27 #include "art_field-inl.h"
28 #include "base/bit_vector-inl.h"
29 #include "base/file_utils.h"
30 #include "base/logging.h"  // For VLOG.
31 #include "base/mutex-inl.h"
32 #include "base/sdk_version.h"
33 #include "base/stl_util.h"
34 #include "base/systrace.h"
35 #include "class_linker.h"
36 #include "class_loader_context.h"
37 #include "dex/art_dex_file_loader.h"
38 #include "dex/dex_file-inl.h"
39 #include "dex/dex_file_loader.h"
40 #include "dex/dex_file_tracking_registrar.h"
41 #include "gc/scoped_gc_critical_section.h"
42 #include "gc/space/image_space.h"
43 #include "handle_scope-inl.h"
44 #include "jit/jit.h"
45 #include "jni/java_vm_ext.h"
46 #include "jni/jni_internal.h"
47 #include "mirror/class_loader.h"
48 #include "mirror/object-inl.h"
49 #include "oat_file.h"
50 #include "oat_file_assistant.h"
51 #include "obj_ptr-inl.h"
52 #include "scoped_thread_state_change-inl.h"
53 #include "thread-current-inl.h"
54 #include "thread_list.h"
55 #include "thread_pool.h"
56 #include "vdex_file.h"
57 #include "verifier/verifier_deps.h"
58 #include "well_known_classes.h"
59 
60 namespace art {
61 
62 using android::base::StringPrintf;
63 
64 // If true, we attempt to load the application image if it exists.
65 static constexpr bool kEnableAppImage = true;
66 
RegisterOatFile(std::unique_ptr<const OatFile> oat_file)67 const OatFile* OatFileManager::RegisterOatFile(std::unique_ptr<const OatFile> oat_file) {
68   WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
69   CHECK(!only_use_system_oat_files_ ||
70         LocationIsOnSystem(oat_file->GetLocation().c_str()) ||
71         !oat_file->IsExecutable())
72       << "Registering a non /system oat file: " << oat_file->GetLocation();
73   DCHECK(oat_file != nullptr);
74   if (kIsDebugBuild) {
75     CHECK(oat_files_.find(oat_file) == oat_files_.end());
76     for (const std::unique_ptr<const OatFile>& existing : oat_files_) {
77       CHECK_NE(oat_file.get(), existing.get()) << oat_file->GetLocation();
78       // Check that we don't have an oat file with the same address. Copies of the same oat file
79       // should be loaded at different addresses.
80       CHECK_NE(oat_file->Begin(), existing->Begin()) << "Oat file already mapped at that location";
81     }
82   }
83   const OatFile* ret = oat_file.get();
84   oat_files_.insert(std::move(oat_file));
85   return ret;
86 }
87 
UnRegisterAndDeleteOatFile(const OatFile * oat_file)88 void OatFileManager::UnRegisterAndDeleteOatFile(const OatFile* oat_file) {
89   WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
90   DCHECK(oat_file != nullptr);
91   std::unique_ptr<const OatFile> compare(oat_file);
92   auto it = oat_files_.find(compare);
93   CHECK(it != oat_files_.end());
94   oat_files_.erase(it);
95   compare.release();  // NOLINT b/117926937
96 }
97 
FindOpenedOatFileFromDexLocation(const std::string & dex_base_location) const98 const OatFile* OatFileManager::FindOpenedOatFileFromDexLocation(
99     const std::string& dex_base_location) const {
100   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
101   for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
102     const std::vector<const OatDexFile*>& oat_dex_files = oat_file->GetOatDexFiles();
103     for (const OatDexFile* oat_dex_file : oat_dex_files) {
104       if (DexFileLoader::GetBaseLocation(oat_dex_file->GetDexFileLocation()) == dex_base_location) {
105         return oat_file.get();
106       }
107     }
108   }
109   return nullptr;
110 }
111 
FindOpenedOatFileFromOatLocation(const std::string & oat_location) const112 const OatFile* OatFileManager::FindOpenedOatFileFromOatLocation(const std::string& oat_location)
113     const {
114   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
115   return FindOpenedOatFileFromOatLocationLocked(oat_location);
116 }
117 
FindOpenedOatFileFromOatLocationLocked(const std::string & oat_location) const118 const OatFile* OatFileManager::FindOpenedOatFileFromOatLocationLocked(
119     const std::string& oat_location) const {
120   for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
121     if (oat_file->GetLocation() == oat_location) {
122       return oat_file.get();
123     }
124   }
125   return nullptr;
126 }
127 
GetBootOatFiles() const128 std::vector<const OatFile*> OatFileManager::GetBootOatFiles() const {
129   std::vector<gc::space::ImageSpace*> image_spaces =
130       Runtime::Current()->GetHeap()->GetBootImageSpaces();
131   std::vector<const OatFile*> oat_files;
132   oat_files.reserve(image_spaces.size());
133   for (gc::space::ImageSpace* image_space : image_spaces) {
134     oat_files.push_back(image_space->GetOatFile());
135   }
136   return oat_files;
137 }
138 
GetPrimaryOatFile() const139 const OatFile* OatFileManager::GetPrimaryOatFile() const {
140   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
141   std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
142   if (!boot_oat_files.empty()) {
143     for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
144       if (std::find(boot_oat_files.begin(), boot_oat_files.end(), oat_file.get()) ==
145           boot_oat_files.end()) {
146         return oat_file.get();
147       }
148     }
149   }
150   return nullptr;
151 }
152 
OatFileManager()153 OatFileManager::OatFileManager()
154     : only_use_system_oat_files_(false) {}
155 
~OatFileManager()156 OatFileManager::~OatFileManager() {
157   // Explicitly clear oat_files_ since the OatFile destructor calls back into OatFileManager for
158   // UnRegisterOatFileLocation.
159   oat_files_.clear();
160 }
161 
RegisterImageOatFiles(const std::vector<gc::space::ImageSpace * > & spaces)162 std::vector<const OatFile*> OatFileManager::RegisterImageOatFiles(
163     const std::vector<gc::space::ImageSpace*>& spaces) {
164   std::vector<const OatFile*> oat_files;
165   oat_files.reserve(spaces.size());
166   for (gc::space::ImageSpace* space : spaces) {
167     oat_files.push_back(RegisterOatFile(space->ReleaseOatFile()));
168   }
169   return oat_files;
170 }
171 
172 class TypeIndexInfo {
173  public:
TypeIndexInfo(const DexFile * dex_file)174   explicit TypeIndexInfo(const DexFile* dex_file)
175       : type_indexes_(GenerateTypeIndexes(dex_file)),
176         iter_(type_indexes_.Indexes().begin()),
177         end_(type_indexes_.Indexes().end()) { }
178 
GetTypeIndexes()179   BitVector& GetTypeIndexes() {
180     return type_indexes_;
181   }
GetIterator()182   BitVector::IndexIterator& GetIterator() {
183     return iter_;
184   }
GetIteratorEnd()185   BitVector::IndexIterator& GetIteratorEnd() {
186     return end_;
187   }
AdvanceIterator()188   void AdvanceIterator() {
189     iter_++;
190   }
191 
192  private:
GenerateTypeIndexes(const DexFile * dex_file)193   static BitVector GenerateTypeIndexes(const DexFile* dex_file) {
194     BitVector type_indexes(/*start_bits=*/0, /*expandable=*/true, Allocator::GetMallocAllocator());
195     for (uint16_t i = 0; i < dex_file->NumClassDefs(); ++i) {
196       const dex::ClassDef& class_def = dex_file->GetClassDef(i);
197       uint16_t type_idx = class_def.class_idx_.index_;
198       type_indexes.SetBit(type_idx);
199     }
200     return type_indexes;
201   }
202 
203   // BitVector with bits set for the type indexes of all classes in the input dex file.
204   BitVector type_indexes_;
205   BitVector::IndexIterator iter_;
206   BitVector::IndexIterator end_;
207 };
208 
209 class DexFileAndClassPair : ValueObject {
210  public:
DexFileAndClassPair(const DexFile * dex_file,TypeIndexInfo * type_info,bool from_loaded_oat)211   DexFileAndClassPair(const DexFile* dex_file, TypeIndexInfo* type_info, bool from_loaded_oat)
212      : type_info_(type_info),
213        dex_file_(dex_file),
214        cached_descriptor_(dex_file_->StringByTypeIdx(dex::TypeIndex(*type_info->GetIterator()))),
215        from_loaded_oat_(from_loaded_oat) {
216     type_info_->AdvanceIterator();
217   }
218 
219   DexFileAndClassPair(const DexFileAndClassPair& rhs) = default;
220 
221   DexFileAndClassPair& operator=(const DexFileAndClassPair& rhs) = default;
222 
GetCachedDescriptor() const223   const char* GetCachedDescriptor() const {
224     return cached_descriptor_;
225   }
226 
operator <(const DexFileAndClassPair & rhs) const227   bool operator<(const DexFileAndClassPair& rhs) const {
228     const int cmp = strcmp(cached_descriptor_, rhs.cached_descriptor_);
229     if (cmp != 0) {
230       // Note that the order must be reversed. We want to iterate over the classes in dex files.
231       // They are sorted lexicographically. Thus, the priority-queue must be a min-queue.
232       return cmp > 0;
233     }
234     return dex_file_ < rhs.dex_file_;
235   }
236 
DexFileHasMoreClasses() const237   bool DexFileHasMoreClasses() const {
238     return type_info_->GetIterator() != type_info_->GetIteratorEnd();
239   }
240 
Next()241   void Next() {
242     cached_descriptor_ = dex_file_->StringByTypeIdx(dex::TypeIndex(*type_info_->GetIterator()));
243     type_info_->AdvanceIterator();
244   }
245 
FromLoadedOat() const246   bool FromLoadedOat() const {
247     return from_loaded_oat_;
248   }
249 
GetDexFile() const250   const DexFile* GetDexFile() const {
251     return dex_file_;
252   }
253 
254  private:
255   TypeIndexInfo* type_info_;
256   const DexFile* dex_file_;
257   const char* cached_descriptor_;
258   bool from_loaded_oat_;  // We only need to compare mismatches between what we load now
259                           // and what was loaded before. Any old duplicates must have been
260                           // OK, and any new "internal" duplicates are as well (they must
261                           // be from multidex, which resolves correctly).
262 };
263 
AddDexFilesFromOat(const OatFile * oat_file,std::vector<const DexFile * > * dex_files,std::vector<std::unique_ptr<const DexFile>> * opened_dex_files)264 static void AddDexFilesFromOat(
265     const OatFile* oat_file,
266     /*out*/std::vector<const DexFile*>* dex_files,
267     std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
268   for (const OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
269     std::string error;
270     std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error);
271     if (dex_file == nullptr) {
272       LOG(WARNING) << "Could not create dex file from oat file: " << error;
273     } else if (dex_file->NumClassDefs() > 0U) {
274       dex_files->push_back(dex_file.get());
275       opened_dex_files->push_back(std::move(dex_file));
276     }
277   }
278 }
279 
AddNext(DexFileAndClassPair & original,std::priority_queue<DexFileAndClassPair> & heap)280 static void AddNext(/*inout*/DexFileAndClassPair& original,
281                     /*inout*/std::priority_queue<DexFileAndClassPair>& heap) {
282   if (original.DexFileHasMoreClasses()) {
283     original.Next();
284     heap.push(std::move(original));
285   }
286 }
287 
CheckClassCollision(const OatFile * oat_file,const ClassLoaderContext * context,std::string * error_msg)288 static bool CheckClassCollision(const OatFile* oat_file,
289     const ClassLoaderContext* context,
290     std::string* error_msg /*out*/) {
291   std::vector<const DexFile*> dex_files_loaded = context->FlattenOpenedDexFiles();
292 
293   // Vector that holds the newly opened dex files live, this is done to prevent leaks.
294   std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
295 
296   ScopedTrace st("Collision check");
297   // Add dex files from the oat file to check.
298   std::vector<const DexFile*> dex_files_unloaded;
299   AddDexFilesFromOat(oat_file, &dex_files_unloaded, &opened_dex_files);
300 
301   // Generate type index information for each dex file.
302   std::vector<TypeIndexInfo> loaded_types;
303   loaded_types.reserve(dex_files_loaded.size());
304   for (const DexFile* dex_file : dex_files_loaded) {
305     loaded_types.push_back(TypeIndexInfo(dex_file));
306   }
307   std::vector<TypeIndexInfo> unloaded_types;
308   unloaded_types.reserve(dex_files_unloaded.size());
309   for (const DexFile* dex_file : dex_files_unloaded) {
310     unloaded_types.push_back(TypeIndexInfo(dex_file));
311   }
312 
313   // Populate the queue of dex file and class pairs with the loaded and unloaded dex files.
314   std::priority_queue<DexFileAndClassPair> queue;
315   for (size_t i = 0; i < dex_files_loaded.size(); ++i) {
316     if (loaded_types[i].GetIterator() != loaded_types[i].GetIteratorEnd()) {
317       queue.emplace(dex_files_loaded[i], &loaded_types[i], /*from_loaded_oat=*/true);
318     }
319   }
320   for (size_t i = 0; i < dex_files_unloaded.size(); ++i) {
321     if (unloaded_types[i].GetIterator() != unloaded_types[i].GetIteratorEnd()) {
322       queue.emplace(dex_files_unloaded[i], &unloaded_types[i], /*from_loaded_oat=*/false);
323     }
324   }
325 
326   // Now drain the queue.
327   bool has_duplicates = false;
328   error_msg->clear();
329   while (!queue.empty()) {
330     // Modifying the top element is only safe if we pop right after.
331     DexFileAndClassPair compare_pop(queue.top());
332     queue.pop();
333 
334     // Compare against the following elements.
335     while (!queue.empty()) {
336       DexFileAndClassPair top(queue.top());
337       if (strcmp(compare_pop.GetCachedDescriptor(), top.GetCachedDescriptor()) == 0) {
338         // Same descriptor. Check whether it's crossing old-oat-files to new-oat-files.
339         if (compare_pop.FromLoadedOat() != top.FromLoadedOat()) {
340           error_msg->append(
341               StringPrintf("Found duplicated class when checking oat files: '%s' in %s and %s\n",
342                            compare_pop.GetCachedDescriptor(),
343                            compare_pop.GetDexFile()->GetLocation().c_str(),
344                            top.GetDexFile()->GetLocation().c_str()));
345           if (!VLOG_IS_ON(oat)) {
346             return true;
347           }
348           has_duplicates = true;
349         }
350         queue.pop();
351         AddNext(top, queue);
352       } else {
353         // Something else. Done here.
354         break;
355       }
356     }
357     AddNext(compare_pop, queue);
358   }
359 
360   return has_duplicates;
361 }
362 
363 // Check for class-def collisions in dex files.
364 //
365 // This first walks the class loader chain present in the given context, getting all the dex files
366 // from the class loader.
367 //
368 // If the context is null (which means the initial class loader was null or unsupported)
369 // this returns false. b/37777332.
370 //
371 // This first checks whether all class loaders in the context have the same type and
372 // classpath. If so, we exit early. Otherwise, we do the collision check.
373 //
374 // The collision check works by maintaining a heap with one class from each dex file, sorted by the
375 // class descriptor. Then a dex-file/class pair is continually removed from the heap and compared
376 // against the following top element. If the descriptor is the same, it is now checked whether
377 // the two elements agree on whether their dex file was from an already-loaded oat-file or the
378 // new oat file. Any disagreement indicates a collision.
CheckCollision(const OatFile * oat_file,const ClassLoaderContext * context,std::string * error_msg) const379 OatFileManager::CheckCollisionResult OatFileManager::CheckCollision(
380     const OatFile* oat_file,
381     const ClassLoaderContext* context,
382     /*out*/ std::string* error_msg) const {
383   DCHECK(oat_file != nullptr);
384   DCHECK(error_msg != nullptr);
385 
386   // The context might be null if there are unrecognized class loaders in the chain or they
387   // don't meet sensible sanity conditions. In this case we assume that the app knows what it's
388   // doing and accept the oat file.
389   // Note that this has correctness implications as we cannot guarantee that the class resolution
390   // used during compilation is OK (b/37777332).
391   if (context == nullptr) {
392     LOG(WARNING) << "Skipping duplicate class check due to unsupported classloader";
393     return CheckCollisionResult::kSkippedUnsupportedClassLoader;
394   }
395 
396   if (!CompilerFilter::IsVerificationEnabled(oat_file->GetCompilerFilter())) {
397     // If verification is not enabled we don't need to check for collisions as the oat file
398     // is either extracted or assumed verified.
399     return CheckCollisionResult::kSkippedVerificationDisabled;
400   }
401 
402   // If the oat file loading context matches the context used during compilation then we accept
403   // the oat file without addition checks
404   ClassLoaderContext::VerificationResult result = context->VerifyClassLoaderContextMatch(
405       oat_file->GetClassLoaderContext(),
406       /*verify_names=*/ true,
407       /*verify_checksums=*/ true);
408   switch (result) {
409     case ClassLoaderContext::VerificationResult::kForcedToSkipChecks:
410       return CheckCollisionResult::kSkippedClassLoaderContextSharedLibrary;
411     case ClassLoaderContext::VerificationResult::kMismatch:
412       // Mismatched context, do the actual collision check.
413       break;
414     case ClassLoaderContext::VerificationResult::kVerifies:
415       return CheckCollisionResult::kClassLoaderContextMatches;
416   }
417 
418   // The class loader context does not match. Perform a full duplicate classes check.
419   return CheckClassCollision(oat_file, context, error_msg)
420       ? CheckCollisionResult::kPerformedHasCollisions : CheckCollisionResult::kNoCollisions;
421 }
422 
AcceptOatFile(CheckCollisionResult result) const423 bool OatFileManager::AcceptOatFile(CheckCollisionResult result) const {
424   // Take the file only if it has no collisions, or we must take it because of preopting.
425   // Also accept oat files for shared libraries and unsupported class loaders.
426   return result != CheckCollisionResult::kPerformedHasCollisions;
427 }
428 
ShouldLoadAppImage(CheckCollisionResult check_collision_result,const OatFile * source_oat_file,ClassLoaderContext * context,std::string * error_msg)429 bool OatFileManager::ShouldLoadAppImage(CheckCollisionResult check_collision_result,
430                                         const OatFile* source_oat_file,
431                                         ClassLoaderContext* context,
432                                         std::string* error_msg) {
433   Runtime* const runtime = Runtime::Current();
434   if (kEnableAppImage && (!runtime->IsJavaDebuggable() || source_oat_file->IsDebuggable())) {
435     // If we verified the class loader context (skipping due to the special marker doesn't
436     // count), then also avoid the collision check.
437     bool load_image = check_collision_result == CheckCollisionResult::kNoCollisions
438         || check_collision_result == CheckCollisionResult::kClassLoaderContextMatches;
439     // If we skipped the collision check, we need to reverify to be sure its OK to load the
440     // image.
441     if (!load_image &&
442         check_collision_result ==
443             CheckCollisionResult::kSkippedClassLoaderContextSharedLibrary) {
444       // We can load the app image only if there are no collisions. If we know the
445       // class loader but didn't do the full collision check in HasCollisions(),
446       // do it now. b/77342775
447       load_image = !CheckClassCollision(source_oat_file, context, error_msg);
448     }
449     return load_image;
450   }
451   return false;
452 }
453 
OpenDexFilesFromOat(const char * dex_location,jobject class_loader,jobjectArray dex_elements,const OatFile ** out_oat_file,std::vector<std::string> * error_msgs)454 std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat(
455     const char* dex_location,
456     jobject class_loader,
457     jobjectArray dex_elements,
458     const OatFile** out_oat_file,
459     std::vector<std::string>* error_msgs) {
460   ScopedTrace trace(__FUNCTION__);
461   CHECK(dex_location != nullptr);
462   CHECK(error_msgs != nullptr);
463 
464   // Verify we aren't holding the mutator lock, which could starve GC if we
465   // have to generate or relocate an oat file.
466   Thread* const self = Thread::Current();
467   Locks::mutator_lock_->AssertNotHeld(self);
468   Runtime* const runtime = Runtime::Current();
469 
470   std::unique_ptr<ClassLoaderContext> context;
471   // If the class_loader is null there's not much we can do. This happens if a dex files is loaded
472   // directly with DexFile APIs instead of using class loaders.
473   if (class_loader == nullptr) {
474     LOG(WARNING) << "Opening an oat file without a class loader. "
475                  << "Are you using the deprecated DexFile APIs?";
476     context = nullptr;
477   } else {
478     context = ClassLoaderContext::CreateContextForClassLoader(class_loader, dex_elements);
479   }
480 
481   OatFileAssistant oat_file_assistant(dex_location,
482                                       kRuntimeISA,
483                                       runtime->GetOatFilesExecutable(),
484                                       only_use_system_oat_files_);
485 
486   // Get the oat file on disk.
487   std::unique_ptr<const OatFile> oat_file(oat_file_assistant.GetBestOatFile().release());
488   VLOG(oat) << "OatFileAssistant(" << dex_location << ").GetBestOatFile()="
489             << reinterpret_cast<uintptr_t>(oat_file.get())
490             << " (executable=" << (oat_file != nullptr ? oat_file->IsExecutable() : false) << ")";
491 
492   const OatFile* source_oat_file = nullptr;
493   CheckCollisionResult check_collision_result = CheckCollisionResult::kPerformedHasCollisions;
494   std::string error_msg;
495   if ((class_loader != nullptr || dex_elements != nullptr) && oat_file != nullptr) {
496     // Prevent oat files from being loaded if no class_loader or dex_elements are provided.
497     // This can happen when the deprecated DexFile.<init>(String) is called directly, and it
498     // could load oat files without checking the classpath, which would be incorrect.
499     // Take the file only if it has no collisions, or we must take it because of preopting.
500     check_collision_result = CheckCollision(oat_file.get(), context.get(), /*out*/ &error_msg);
501     bool accept_oat_file = AcceptOatFile(check_collision_result);
502     if (!accept_oat_file) {
503       // Failed the collision check. Print warning.
504       if (runtime->IsDexFileFallbackEnabled()) {
505         if (!oat_file_assistant.HasOriginalDexFiles()) {
506           // We need to fallback but don't have original dex files. We have to
507           // fallback to opening the existing oat file. This is potentially
508           // unsafe so we warn about it.
509           accept_oat_file = true;
510 
511           LOG(WARNING) << "Dex location " << dex_location << " does not seem to include dex file. "
512                        << "Allow oat file use. This is potentially dangerous.";
513         } else {
514           // We have to fallback and found original dex files - extract them from an APK.
515           // Also warn about this operation because it's potentially wasteful.
516           LOG(WARNING) << "Found duplicate classes, falling back to extracting from APK : "
517                        << dex_location;
518           LOG(WARNING) << "NOTE: This wastes RAM and hurts startup performance.";
519         }
520       } else {
521         // TODO: We should remove this. The fact that we're here implies -Xno-dex-file-fallback
522         // was set, which means that we should never fallback. If we don't have original dex
523         // files, we should just fail resolution as the flag intended.
524         if (!oat_file_assistant.HasOriginalDexFiles()) {
525           accept_oat_file = true;
526         }
527 
528         LOG(WARNING) << "Found duplicate classes, dex-file-fallback disabled, will be failing to "
529                         " load classes for " << dex_location;
530       }
531 
532       LOG(WARNING) << error_msg;
533     }
534 
535     if (accept_oat_file) {
536       VLOG(class_linker) << "Registering " << oat_file->GetLocation();
537       source_oat_file = RegisterOatFile(std::move(oat_file));
538       *out_oat_file = source_oat_file;
539     }
540   }
541 
542   std::vector<std::unique_ptr<const DexFile>> dex_files;
543 
544   // Load the dex files from the oat file.
545   if (source_oat_file != nullptr) {
546     bool added_image_space = false;
547     if (source_oat_file->IsExecutable()) {
548       ScopedTrace app_image_timing("AppImage:Loading");
549 
550       // We need to throw away the image space if we are debuggable but the oat-file source of the
551       // image is not otherwise we might get classes with inlined methods or other such things.
552       std::unique_ptr<gc::space::ImageSpace> image_space;
553       if (ShouldLoadAppImage(check_collision_result,
554                              source_oat_file,
555                              context.get(),
556                              &error_msg)) {
557         image_space = oat_file_assistant.OpenImageSpace(source_oat_file);
558       }
559       if (image_space != nullptr) {
560         ScopedObjectAccess soa(self);
561         StackHandleScope<1> hs(self);
562         Handle<mirror::ClassLoader> h_loader(
563             hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader)));
564         // Can not load app image without class loader.
565         if (h_loader != nullptr) {
566           std::string temp_error_msg;
567           // Add image space has a race condition since other threads could be reading from the
568           // spaces array.
569           {
570             ScopedThreadSuspension sts(self, kSuspended);
571             gc::ScopedGCCriticalSection gcs(self,
572                                             gc::kGcCauseAddRemoveAppImageSpace,
573                                             gc::kCollectorTypeAddRemoveAppImageSpace);
574             ScopedSuspendAll ssa("Add image space");
575             runtime->GetHeap()->AddSpace(image_space.get());
576           }
577           {
578             ScopedTrace trace2(StringPrintf("Adding image space for location %s", dex_location));
579             added_image_space = runtime->GetClassLinker()->AddImageSpace(image_space.get(),
580                                                                          h_loader,
581                                                                          /*out*/&dex_files,
582                                                                          /*out*/&temp_error_msg);
583           }
584           if (added_image_space) {
585             // Successfully added image space to heap, release the map so that it does not get
586             // freed.
587             image_space.release();  // NOLINT b/117926937
588 
589             // Register for tracking.
590             for (const auto& dex_file : dex_files) {
591               dex::tracking::RegisterDexFile(dex_file.get());
592             }
593           } else {
594             LOG(INFO) << "Failed to add image file " << temp_error_msg;
595             dex_files.clear();
596             {
597               ScopedThreadSuspension sts(self, kSuspended);
598               gc::ScopedGCCriticalSection gcs(self,
599                                               gc::kGcCauseAddRemoveAppImageSpace,
600                                               gc::kCollectorTypeAddRemoveAppImageSpace);
601               ScopedSuspendAll ssa("Remove image space");
602               runtime->GetHeap()->RemoveSpace(image_space.get());
603             }
604             // Non-fatal, don't update error_msg.
605           }
606         }
607       }
608     }
609     if (!added_image_space) {
610       DCHECK(dex_files.empty());
611       dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
612 
613       // Register for tracking.
614       for (const auto& dex_file : dex_files) {
615         dex::tracking::RegisterDexFile(dex_file.get());
616       }
617     }
618     if (dex_files.empty()) {
619       error_msgs->push_back("Failed to open dex files from " + source_oat_file->GetLocation());
620     } else {
621       // Opened dex files from an oat file, madvise them to their loaded state.
622        for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
623          OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
624        }
625     }
626   }
627 
628   // Fall back to running out of the original dex file if we couldn't load any
629   // dex_files from the oat file.
630   if (dex_files.empty()) {
631     if (oat_file_assistant.HasOriginalDexFiles()) {
632       if (Runtime::Current()->IsDexFileFallbackEnabled()) {
633         static constexpr bool kVerifyChecksum = true;
634         const ArtDexFileLoader dex_file_loader;
635         if (!dex_file_loader.Open(dex_location,
636                                   dex_location,
637                                   Runtime::Current()->IsVerificationEnabled(),
638                                   kVerifyChecksum,
639                                   /*out*/ &error_msg,
640                                   &dex_files)) {
641           LOG(WARNING) << error_msg;
642           error_msgs->push_back("Failed to open dex files from " + std::string(dex_location)
643                                 + " because: " + error_msg);
644         }
645       } else {
646         error_msgs->push_back("Fallback mode disabled, skipping dex files.");
647       }
648     } else {
649       std::string msg = StringPrintf("No original dex files found for dex location (%s) %s",
650           GetInstructionSetString(kRuntimeISA), dex_location);
651       error_msgs->push_back(msg);
652     }
653   }
654 
655   if (Runtime::Current()->GetJit() != nullptr) {
656     Runtime::Current()->GetJit()->RegisterDexFiles(dex_files, class_loader);
657   }
658 
659   // Verify if any of the dex files being loaded is already in the class path.
660   // If so, report an error with the current stack trace.
661   // Most likely the developer didn't intend to do this because it will waste
662   // performance and memory.
663   // We perform the check only if the class loader context match failed or did
664   // not run (e.g. not that we do not run the check if we don't have an oat file).
665   if (context != nullptr
666           && check_collision_result != CheckCollisionResult::kClassLoaderContextMatches) {
667     std::set<const DexFile*> already_exists_in_classpath =
668         context->CheckForDuplicateDexFiles(MakeNonOwningPointerVector(dex_files));
669     if (!already_exists_in_classpath.empty()) {
670       auto duplicate_it = already_exists_in_classpath.begin();
671       std::string duplicates = (*duplicate_it)->GetLocation();
672       for (duplicate_it++ ; duplicate_it != already_exists_in_classpath.end(); duplicate_it++) {
673         duplicates += "," + (*duplicate_it)->GetLocation();
674       }
675 
676       std::ostringstream out;
677       out << "Trying to load dex files which is already loaded in the same ClassLoader hierarchy.\n"
678         << "This is a strong indication of bad ClassLoader construct which leads to poor "
679         << "performance and wastes memory.\n"
680         << "The list of duplicate dex files is: " << duplicates << "\n"
681         << "The current class loader context is: " << context->EncodeContextForOatFile("") << "\n"
682         << "Java stack trace:\n";
683 
684       {
685         ScopedObjectAccess soa(self);
686         self->DumpJavaStack(out);
687       }
688 
689       // We log this as an ERROR to stress the fact that this is most likely unintended.
690       // Note that ART cannot do anything about it. It is up to the app to fix their logic.
691       // Here we are trying to give a heads up on why the app might have performance issues.
692       LOG(ERROR) << out.str();
693     }
694   }
695   return dex_files;
696 }
697 
GetDexFileHeaders(const std::vector<MemMap> & maps)698 static std::vector<const DexFile::Header*> GetDexFileHeaders(const std::vector<MemMap>& maps) {
699   std::vector<const DexFile::Header*> headers;
700   headers.reserve(maps.size());
701   for (const MemMap& map : maps) {
702     DCHECK(map.IsValid());
703     headers.push_back(reinterpret_cast<const DexFile::Header*>(map.Begin()));
704   }
705   return headers;
706 }
707 
GetDexFileHeaders(const std::vector<const DexFile * > & dex_files)708 static std::vector<const DexFile::Header*> GetDexFileHeaders(
709     const std::vector<const DexFile*>& dex_files) {
710   std::vector<const DexFile::Header*> headers;
711   headers.reserve(dex_files.size());
712   for (const DexFile* dex_file : dex_files) {
713     headers.push_back(&dex_file->GetHeader());
714   }
715   return headers;
716 }
717 
OpenDexFilesFromOat(std::vector<MemMap> && dex_mem_maps,jobject class_loader,jobjectArray dex_elements,const OatFile ** out_oat_file,std::vector<std::string> * error_msgs)718 std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat(
719     std::vector<MemMap>&& dex_mem_maps,
720     jobject class_loader,
721     jobjectArray dex_elements,
722     const OatFile** out_oat_file,
723     std::vector<std::string>* error_msgs) {
724   std::vector<std::unique_ptr<const DexFile>> dex_files = OpenDexFilesFromOat_Impl(
725       std::move(dex_mem_maps),
726       class_loader,
727       dex_elements,
728       out_oat_file,
729       error_msgs);
730 
731   if (error_msgs->empty()) {
732     // Remove write permission from DexFile pages. We do this at the end because
733     // OatFile assigns OatDexFile pointer in the DexFile objects.
734     for (std::unique_ptr<const DexFile>& dex_file : dex_files) {
735       if (!dex_file->DisableWrite()) {
736         error_msgs->push_back("Failed to make dex file " + dex_file->GetLocation() + " read-only");
737       }
738     }
739   }
740 
741   if (!error_msgs->empty()) {
742     return std::vector<std::unique_ptr<const DexFile>>();
743   }
744 
745   return dex_files;
746 }
747 
OpenDexFilesFromOat_Impl(std::vector<MemMap> && dex_mem_maps,jobject class_loader,jobjectArray dex_elements,const OatFile ** out_oat_file,std::vector<std::string> * error_msgs)748 std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat_Impl(
749     std::vector<MemMap>&& dex_mem_maps,
750     jobject class_loader,
751     jobjectArray dex_elements,
752     const OatFile** out_oat_file,
753     std::vector<std::string>* error_msgs) {
754   ScopedTrace trace(__FUNCTION__);
755   std::string error_msg;
756   DCHECK(error_msgs != nullptr);
757 
758   // Extract dex file headers from `dex_mem_maps`.
759   const std::vector<const DexFile::Header*> dex_headers = GetDexFileHeaders(dex_mem_maps);
760 
761   // Determine dex/vdex locations and the combined location checksum.
762   uint32_t location_checksum;
763   std::string dex_location;
764   std::string vdex_path;
765   bool has_vdex = OatFileAssistant::AnonymousDexVdexLocation(dex_headers,
766                                                              kRuntimeISA,
767                                                              &location_checksum,
768                                                              &dex_location,
769                                                              &vdex_path);
770 
771   // Attempt to open an existing vdex and check dex file checksums match.
772   std::unique_ptr<VdexFile> vdex_file = nullptr;
773   if (has_vdex && OS::FileExists(vdex_path.c_str())) {
774     vdex_file = VdexFile::Open(vdex_path,
775                                /* writable= */ false,
776                                /* low_4gb= */ false,
777                                /* unquicken= */ false,
778                                &error_msg);
779     if (vdex_file == nullptr) {
780       LOG(WARNING) << "Failed to open vdex " << vdex_path << ": " << error_msg;
781     } else if (!vdex_file->MatchesDexFileChecksums(dex_headers)) {
782       LOG(WARNING) << "Failed to open vdex " << vdex_path << ": dex file checksum mismatch";
783       vdex_file.reset(nullptr);
784     }
785   }
786 
787   // Load dex files. Skip structural dex file verification if vdex was found
788   // and dex checksums matched.
789   std::vector<std::unique_ptr<const DexFile>> dex_files;
790   for (size_t i = 0; i < dex_mem_maps.size(); ++i) {
791     static constexpr bool kVerifyChecksum = true;
792     const ArtDexFileLoader dex_file_loader;
793     std::unique_ptr<const DexFile> dex_file(dex_file_loader.Open(
794         DexFileLoader::GetMultiDexLocation(i, dex_location.c_str()),
795         location_checksum,
796         std::move(dex_mem_maps[i]),
797         /* verify= */ (vdex_file == nullptr) && Runtime::Current()->IsVerificationEnabled(),
798         kVerifyChecksum,
799         &error_msg));
800     if (dex_file != nullptr) {
801       dex::tracking::RegisterDexFile(dex_file.get());  // Register for tracking.
802       dex_files.push_back(std::move(dex_file));
803     } else {
804       error_msgs->push_back("Failed to open dex files from memory: " + error_msg);
805     }
806   }
807 
808   // Check if we should proceed to creating an OatFile instance backed by the vdex.
809   // We need: (a) an existing vdex, (b) class loader (can be null if invoked via reflection),
810   // and (c) no errors during dex file loading.
811   if (vdex_file == nullptr || class_loader == nullptr || !error_msgs->empty()) {
812     return dex_files;
813   }
814 
815   // Attempt to create a class loader context, check OpenDexFiles succeeds (prerequisite
816   // for using the context later).
817   std::unique_ptr<ClassLoaderContext> context = ClassLoaderContext::CreateContextForClassLoader(
818       class_loader,
819       dex_elements);
820   if (context == nullptr) {
821     LOG(ERROR) << "Could not create class loader context for " << vdex_path;
822     return dex_files;
823   }
824   DCHECK(context->OpenDexFiles(kRuntimeISA, ""))
825       << "Context created from already opened dex files should not attempt to open again";
826 
827   // Check that we can use the vdex against this boot class path and in this class loader context.
828   // Note 1: We do not need a class loader collision check because there is no compiled code.
829   // Note 2: If these checks fail, we cannot fast-verify because the vdex does not contain
830   //         full VerifierDeps.
831   if (!vdex_file->MatchesBootClassPathChecksums() ||
832       !vdex_file->MatchesClassLoaderContext(*context.get())) {
833     return dex_files;
834   }
835 
836   // Initialize an OatFile instance backed by the loaded vdex.
837   std::unique_ptr<OatFile> oat_file(OatFile::OpenFromVdex(MakeNonOwningPointerVector(dex_files),
838                                                           std::move(vdex_file),
839                                                           dex_location));
840   DCHECK(oat_file != nullptr);
841   VLOG(class_linker) << "Registering " << oat_file->GetLocation();
842   *out_oat_file = RegisterOatFile(std::move(oat_file));
843   return dex_files;
844 }
845 
846 // Check how many vdex files exist in the same directory as the vdex file we are about
847 // to write. If more than or equal to kAnonymousVdexCacheSize, unlink the least
848 // recently used one(s) (according to stat-reported atime).
UnlinkLeastRecentlyUsedVdexIfNeeded(const std::string & vdex_path_to_add,std::string * error_msg)849 static bool UnlinkLeastRecentlyUsedVdexIfNeeded(const std::string& vdex_path_to_add,
850                                                 std::string* error_msg) {
851   if (OS::FileExists(vdex_path_to_add.c_str())) {
852     // File already exists and will be overwritten.
853     // This will not change the number of entries in the cache.
854     return true;
855   }
856 
857   auto last_slash = vdex_path_to_add.rfind('/');
858   CHECK(last_slash != std::string::npos);
859   std::string vdex_dir = vdex_path_to_add.substr(0, last_slash + 1);
860 
861   if (!OS::DirectoryExists(vdex_dir.c_str())) {
862     // Folder does not exist yet. Cache has zero entries.
863     return true;
864   }
865 
866   std::vector<std::pair<time_t, std::string>> cache;
867 
868   DIR* c_dir = opendir(vdex_dir.c_str());
869   if (c_dir == nullptr) {
870     *error_msg = "Unable to open " + vdex_dir + " to delete unused vdex files";
871     return false;
872   }
873   for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
874     if (de->d_type != DT_REG) {
875       continue;
876     }
877     std::string basename = de->d_name;
878     if (!OatFileAssistant::IsAnonymousVdexBasename(basename)) {
879       continue;
880     }
881     std::string fullname = vdex_dir + basename;
882 
883     struct stat s;
884     int rc = TEMP_FAILURE_RETRY(stat(fullname.c_str(), &s));
885     if (rc == -1) {
886       *error_msg = "Failed to stat() anonymous vdex file " + fullname;
887       return false;
888     }
889 
890     cache.push_back(std::make_pair(s.st_atime, fullname));
891   }
892   CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
893 
894   if (cache.size() < OatFileManager::kAnonymousVdexCacheSize) {
895     return true;
896   }
897 
898   std::sort(cache.begin(),
899             cache.end(),
900             [](const auto& a, const auto& b) { return a.first < b.first; });
901   for (size_t i = OatFileManager::kAnonymousVdexCacheSize - 1; i < cache.size(); ++i) {
902     if (unlink(cache[i].second.c_str()) != 0) {
903       *error_msg = "Could not unlink anonymous vdex file " + cache[i].second;
904       return false;
905     }
906   }
907 
908   return true;
909 }
910 
911 class BackgroundVerificationTask final : public Task {
912  public:
BackgroundVerificationTask(const std::vector<const DexFile * > & dex_files,jobject class_loader,const char * class_loader_context,const std::string & vdex_path)913   BackgroundVerificationTask(const std::vector<const DexFile*>& dex_files,
914                              jobject class_loader,
915                              const char* class_loader_context,
916                              const std::string& vdex_path)
917       : dex_files_(dex_files),
918         class_loader_context_(class_loader_context),
919         vdex_path_(vdex_path) {
920     Thread* const self = Thread::Current();
921     ScopedObjectAccess soa(self);
922     // Create a global ref for `class_loader` because it will be accessed from a different thread.
923     class_loader_ = soa.Vm()->AddGlobalRef(self, soa.Decode<mirror::ClassLoader>(class_loader));
924     CHECK(class_loader_ != nullptr);
925   }
926 
~BackgroundVerificationTask()927   ~BackgroundVerificationTask() {
928     Thread* const self = Thread::Current();
929     ScopedObjectAccess soa(self);
930     soa.Vm()->DeleteGlobalRef(self, class_loader_);
931   }
932 
Run(Thread * self)933   void Run(Thread* self) override {
934     std::string error_msg;
935     ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
936     verifier::VerifierDeps verifier_deps(dex_files_);
937 
938     // Iterate over all classes and verify them.
939     for (const DexFile* dex_file : dex_files_) {
940       for (uint32_t cdef_idx = 0; cdef_idx < dex_file->NumClassDefs(); cdef_idx++) {
941         const dex::ClassDef& class_def = dex_file->GetClassDef(cdef_idx);
942 
943         // Take handles inside the loop. The background verification is low priority
944         // and we want to minimize the risk of blocking anyone else.
945         ScopedObjectAccess soa(self);
946         StackHandleScope<2> hs(self);
947         Handle<mirror::ClassLoader> h_loader(hs.NewHandle(
948             soa.Decode<mirror::ClassLoader>(class_loader_)));
949         Handle<mirror::Class> h_class(hs.NewHandle<mirror::Class>(class_linker->FindClass(
950             self,
951             dex_file->GetClassDescriptor(class_def),
952             h_loader)));
953 
954         if (h_class == nullptr) {
955           CHECK(self->IsExceptionPending());
956           self->ClearException();
957           continue;
958         }
959 
960         if (&h_class->GetDexFile() != dex_file) {
961           // There is a different class in the class path or a parent class loader
962           // with the same descriptor. This `h_class` is not resolvable, skip it.
963           continue;
964         }
965 
966         CHECK(h_class->IsResolved()) << h_class->PrettyDescriptor();
967         class_linker->VerifyClass(self, h_class);
968         if (h_class->IsErroneous()) {
969           // ClassLinker::VerifyClass throws, which isn't useful here.
970           CHECK(soa.Self()->IsExceptionPending());
971           soa.Self()->ClearException();
972         }
973 
974         CHECK(h_class->IsVerified() || h_class->IsErroneous())
975             << h_class->PrettyDescriptor() << ": state=" << h_class->GetStatus();
976 
977         if (h_class->IsVerified()) {
978           verifier_deps.RecordClassVerified(*dex_file, class_def);
979         }
980       }
981     }
982 
983     // Delete old vdex files if there are too many in the folder.
984     if (!UnlinkLeastRecentlyUsedVdexIfNeeded(vdex_path_, &error_msg)) {
985       LOG(ERROR) << "Could not unlink old vdex files " << vdex_path_ << ": " << error_msg;
986       return;
987     }
988 
989     // Construct a vdex file and write `verifier_deps` into it.
990     if (!VdexFile::WriteToDisk(vdex_path_,
991                                dex_files_,
992                                verifier_deps,
993                                class_loader_context_,
994                                &error_msg)) {
995       LOG(ERROR) << "Could not write anonymous vdex " << vdex_path_ << ": " << error_msg;
996       return;
997     }
998   }
999 
Finalize()1000   void Finalize() override {
1001     delete this;
1002   }
1003 
1004  private:
1005   const std::vector<const DexFile*> dex_files_;
1006   jobject class_loader_;
1007   const std::string class_loader_context_;
1008   const std::string vdex_path_;
1009 
1010   DISALLOW_COPY_AND_ASSIGN(BackgroundVerificationTask);
1011 };
1012 
RunBackgroundVerification(const std::vector<const DexFile * > & dex_files,jobject class_loader,const char * class_loader_context)1013 void OatFileManager::RunBackgroundVerification(const std::vector<const DexFile*>& dex_files,
1014                                                jobject class_loader,
1015                                                const char* class_loader_context) {
1016   Runtime* const runtime = Runtime::Current();
1017   Thread* const self = Thread::Current();
1018 
1019   if (runtime->IsJavaDebuggable()) {
1020     // Threads created by ThreadPool ("runtime threads") are not allowed to load
1021     // classes when debuggable to match class-initialization semantics
1022     // expectations. Do not verify in the background.
1023     return;
1024   }
1025 
1026   if (!IsSdkVersionSetAndAtLeast(runtime->GetTargetSdkVersion(), SdkVersion::kQ)) {
1027     // Do not run for legacy apps as they may depend on the previous class loader behaviour.
1028     return;
1029   }
1030 
1031   if (runtime->IsShuttingDown(self)) {
1032     // Not allowed to create new threads during runtime shutdown.
1033     return;
1034   }
1035 
1036   uint32_t location_checksum;
1037   std::string dex_location;
1038   std::string vdex_path;
1039   if (OatFileAssistant::AnonymousDexVdexLocation(GetDexFileHeaders(dex_files),
1040                                                  kRuntimeISA,
1041                                                  &location_checksum,
1042                                                  &dex_location,
1043                                                  &vdex_path)) {
1044     if (verification_thread_pool_ == nullptr) {
1045       verification_thread_pool_.reset(
1046           new ThreadPool("Verification thread pool", /* num_threads= */ 1));
1047       verification_thread_pool_->StartWorkers(self);
1048     }
1049     verification_thread_pool_->AddTask(self, new BackgroundVerificationTask(
1050         dex_files,
1051         class_loader,
1052         class_loader_context,
1053         vdex_path));
1054   }
1055 }
1056 
WaitForWorkersToBeCreated()1057 void OatFileManager::WaitForWorkersToBeCreated() {
1058   DCHECK(!Runtime::Current()->IsShuttingDown(Thread::Current()))
1059       << "Cannot create new threads during runtime shutdown";
1060   if (verification_thread_pool_ != nullptr) {
1061     verification_thread_pool_->WaitForWorkersToBeCreated();
1062   }
1063 }
1064 
DeleteThreadPool()1065 void OatFileManager::DeleteThreadPool() {
1066   verification_thread_pool_.reset(nullptr);
1067 }
1068 
WaitForBackgroundVerificationTasks()1069 void OatFileManager::WaitForBackgroundVerificationTasks() {
1070   if (verification_thread_pool_ != nullptr) {
1071     Thread* const self = Thread::Current();
1072     verification_thread_pool_->WaitForWorkersToBeCreated();
1073     verification_thread_pool_->Wait(self, /* do_work= */ true, /* may_hold_locks= */ false);
1074   }
1075 }
1076 
SetOnlyUseSystemOatFiles()1077 void OatFileManager::SetOnlyUseSystemOatFiles() {
1078   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
1079   // Make sure all files that were loaded up to this point are on /system.
1080   // Skip the image files as they can encode locations that don't exist (eg not
1081   // containing the arch in the path, or for JIT zygote /nonx/existent).
1082   std::vector<const OatFile*> boot_vector = GetBootOatFiles();
1083   std::unordered_set<const OatFile*> boot_set(boot_vector.begin(), boot_vector.end());
1084 
1085   for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
1086     if (boot_set.find(oat_file.get()) == boot_set.end()) {
1087       CHECK(LocationIsOnSystem(oat_file->GetLocation().c_str())) << oat_file->GetLocation();
1088     }
1089   }
1090   only_use_system_oat_files_ = true;
1091 }
1092 
DumpForSigQuit(std::ostream & os)1093 void OatFileManager::DumpForSigQuit(std::ostream& os) {
1094   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
1095   std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
1096   for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
1097     if (ContainsElement(boot_oat_files, oat_file.get())) {
1098       continue;
1099     }
1100     os << oat_file->GetLocation() << ": " << oat_file->GetCompilerFilter() << "\n";
1101   }
1102 }
1103 
1104 }  // namespace art
1105