Home | History | Annotate | Download | only in runtime
      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 
     23 #include "android-base/stringprintf.h"
     24 #include "android-base/strings.h"
     25 
     26 #include "art_field-inl.h"
     27 #include "base/bit_vector-inl.h"
     28 #include "base/file_utils.h"
     29 #include "base/logging.h"  // For VLOG.
     30 #include "base/stl_util.h"
     31 #include "base/systrace.h"
     32 #include "class_linker.h"
     33 #include "class_loader_context.h"
     34 #include "dex/art_dex_file_loader.h"
     35 #include "dex/dex_file-inl.h"
     36 #include "dex/dex_file_loader.h"
     37 #include "dex/dex_file_tracking_registrar.h"
     38 #include "gc/scoped_gc_critical_section.h"
     39 #include "gc/space/image_space.h"
     40 #include "handle_scope-inl.h"
     41 #include "jni_internal.h"
     42 #include "mirror/class_loader.h"
     43 #include "mirror/object-inl.h"
     44 #include "oat_file.h"
     45 #include "oat_file_assistant.h"
     46 #include "obj_ptr-inl.h"
     47 #include "scoped_thread_state_change-inl.h"
     48 #include "thread-current-inl.h"
     49 #include "thread_list.h"
     50 #include "well_known_classes.h"
     51 
     52 namespace art {
     53 
     54 using android::base::StringPrintf;
     55 
     56 // If true, we attempt to load the application image if it exists.
     57 static constexpr bool kEnableAppImage = true;
     58 
     59 const OatFile* OatFileManager::RegisterOatFile(std::unique_ptr<const OatFile> oat_file) {
     60   WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
     61   CHECK(!only_use_system_oat_files_ ||
     62         LocationIsOnSystem(oat_file->GetLocation().c_str()) ||
     63         !oat_file->IsExecutable())
     64       << "Registering a non /system oat file: " << oat_file->GetLocation();
     65   DCHECK(oat_file != nullptr);
     66   if (kIsDebugBuild) {
     67     CHECK(oat_files_.find(oat_file) == oat_files_.end());
     68     for (const std::unique_ptr<const OatFile>& existing : oat_files_) {
     69       CHECK_NE(oat_file.get(), existing.get()) << oat_file->GetLocation();
     70       // Check that we don't have an oat file with the same address. Copies of the same oat file
     71       // should be loaded at different addresses.
     72       CHECK_NE(oat_file->Begin(), existing->Begin()) << "Oat file already mapped at that location";
     73     }
     74   }
     75   have_non_pic_oat_file_ = have_non_pic_oat_file_ || !oat_file->IsPic();
     76   const OatFile* ret = oat_file.get();
     77   oat_files_.insert(std::move(oat_file));
     78   return ret;
     79 }
     80 
     81 void OatFileManager::UnRegisterAndDeleteOatFile(const OatFile* oat_file) {
     82   WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
     83   DCHECK(oat_file != nullptr);
     84   std::unique_ptr<const OatFile> compare(oat_file);
     85   auto it = oat_files_.find(compare);
     86   CHECK(it != oat_files_.end());
     87   oat_files_.erase(it);
     88   compare.release();
     89 }
     90 
     91 const OatFile* OatFileManager::FindOpenedOatFileFromDexLocation(
     92     const std::string& dex_base_location) const {
     93   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
     94   for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
     95     const std::vector<const OatDexFile*>& oat_dex_files = oat_file->GetOatDexFiles();
     96     for (const OatDexFile* oat_dex_file : oat_dex_files) {
     97       if (DexFileLoader::GetBaseLocation(oat_dex_file->GetDexFileLocation()) == dex_base_location) {
     98         return oat_file.get();
     99       }
    100     }
    101   }
    102   return nullptr;
    103 }
    104 
    105 const OatFile* OatFileManager::FindOpenedOatFileFromOatLocation(const std::string& oat_location)
    106     const {
    107   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
    108   return FindOpenedOatFileFromOatLocationLocked(oat_location);
    109 }
    110 
    111 const OatFile* OatFileManager::FindOpenedOatFileFromOatLocationLocked(
    112     const std::string& oat_location) const {
    113   for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
    114     if (oat_file->GetLocation() == oat_location) {
    115       return oat_file.get();
    116     }
    117   }
    118   return nullptr;
    119 }
    120 
    121 std::vector<const OatFile*> OatFileManager::GetBootOatFiles() const {
    122   std::vector<const OatFile*> oat_files;
    123   std::vector<gc::space::ImageSpace*> image_spaces =
    124       Runtime::Current()->GetHeap()->GetBootImageSpaces();
    125   for (gc::space::ImageSpace* image_space : image_spaces) {
    126     oat_files.push_back(image_space->GetOatFile());
    127   }
    128   return oat_files;
    129 }
    130 
    131 const OatFile* OatFileManager::GetPrimaryOatFile() const {
    132   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
    133   std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
    134   if (!boot_oat_files.empty()) {
    135     for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
    136       if (std::find(boot_oat_files.begin(), boot_oat_files.end(), oat_file.get()) ==
    137           boot_oat_files.end()) {
    138         return oat_file.get();
    139       }
    140     }
    141   }
    142   return nullptr;
    143 }
    144 
    145 OatFileManager::OatFileManager()
    146     : have_non_pic_oat_file_(false), only_use_system_oat_files_(false) {}
    147 
    148 OatFileManager::~OatFileManager() {
    149   // Explicitly clear oat_files_ since the OatFile destructor calls back into OatFileManager for
    150   // UnRegisterOatFileLocation.
    151   oat_files_.clear();
    152 }
    153 
    154 std::vector<const OatFile*> OatFileManager::RegisterImageOatFiles(
    155     std::vector<gc::space::ImageSpace*> spaces) {
    156   std::vector<const OatFile*> oat_files;
    157   for (gc::space::ImageSpace* space : spaces) {
    158     oat_files.push_back(RegisterOatFile(space->ReleaseOatFile()));
    159   }
    160   return oat_files;
    161 }
    162 
    163 class TypeIndexInfo {
    164  public:
    165   explicit TypeIndexInfo(const DexFile* dex_file)
    166       : type_indexes_(GenerateTypeIndexes(dex_file)),
    167         iter_(type_indexes_.Indexes().begin()),
    168         end_(type_indexes_.Indexes().end()) { }
    169 
    170   BitVector& GetTypeIndexes() {
    171     return type_indexes_;
    172   }
    173   BitVector::IndexIterator& GetIterator() {
    174     return iter_;
    175   }
    176   BitVector::IndexIterator& GetIteratorEnd() {
    177     return end_;
    178   }
    179   void AdvanceIterator() {
    180     iter_++;
    181   }
    182 
    183  private:
    184   static BitVector GenerateTypeIndexes(const DexFile* dex_file) {
    185     BitVector type_indexes(/*start_bits*/0, /*expandable*/true, Allocator::GetMallocAllocator());
    186     for (uint16_t i = 0; i < dex_file->NumClassDefs(); ++i) {
    187       const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
    188       uint16_t type_idx = class_def.class_idx_.index_;
    189       type_indexes.SetBit(type_idx);
    190     }
    191     return type_indexes;
    192   }
    193 
    194   // BitVector with bits set for the type indexes of all classes in the input dex file.
    195   BitVector type_indexes_;
    196   BitVector::IndexIterator iter_;
    197   BitVector::IndexIterator end_;
    198 };
    199 
    200 class DexFileAndClassPair : ValueObject {
    201  public:
    202   DexFileAndClassPair(const DexFile* dex_file, TypeIndexInfo* type_info, bool from_loaded_oat)
    203      : type_info_(type_info),
    204        dex_file_(dex_file),
    205        cached_descriptor_(dex_file_->StringByTypeIdx(dex::TypeIndex(*type_info->GetIterator()))),
    206        from_loaded_oat_(from_loaded_oat) {
    207     type_info_->AdvanceIterator();
    208   }
    209 
    210   DexFileAndClassPair(const DexFileAndClassPair& rhs) = default;
    211 
    212   DexFileAndClassPair& operator=(const DexFileAndClassPair& rhs) = default;
    213 
    214   const char* GetCachedDescriptor() const {
    215     return cached_descriptor_;
    216   }
    217 
    218   bool operator<(const DexFileAndClassPair& rhs) const {
    219     const int cmp = strcmp(cached_descriptor_, rhs.cached_descriptor_);
    220     if (cmp != 0) {
    221       // Note that the order must be reversed. We want to iterate over the classes in dex files.
    222       // They are sorted lexicographically. Thus, the priority-queue must be a min-queue.
    223       return cmp > 0;
    224     }
    225     return dex_file_ < rhs.dex_file_;
    226   }
    227 
    228   bool DexFileHasMoreClasses() const {
    229     return type_info_->GetIterator() != type_info_->GetIteratorEnd();
    230   }
    231 
    232   void Next() {
    233     cached_descriptor_ = dex_file_->StringByTypeIdx(dex::TypeIndex(*type_info_->GetIterator()));
    234     type_info_->AdvanceIterator();
    235   }
    236 
    237   bool FromLoadedOat() const {
    238     return from_loaded_oat_;
    239   }
    240 
    241   const DexFile* GetDexFile() const {
    242     return dex_file_;
    243   }
    244 
    245  private:
    246   TypeIndexInfo* type_info_;
    247   const DexFile* dex_file_;
    248   const char* cached_descriptor_;
    249   bool from_loaded_oat_;  // We only need to compare mismatches between what we load now
    250                           // and what was loaded before. Any old duplicates must have been
    251                           // OK, and any new "internal" duplicates are as well (they must
    252                           // be from multidex, which resolves correctly).
    253 };
    254 
    255 static void AddDexFilesFromOat(
    256     const OatFile* oat_file,
    257     /*out*/std::vector<const DexFile*>* dex_files,
    258     std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
    259   for (const OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
    260     std::string error;
    261     std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error);
    262     if (dex_file == nullptr) {
    263       LOG(WARNING) << "Could not create dex file from oat file: " << error;
    264     } else if (dex_file->NumClassDefs() > 0U) {
    265       dex_files->push_back(dex_file.get());
    266       opened_dex_files->push_back(std::move(dex_file));
    267     }
    268   }
    269 }
    270 
    271 static void AddNext(/*inout*/DexFileAndClassPair& original,
    272                     /*inout*/std::priority_queue<DexFileAndClassPair>& heap) {
    273   if (original.DexFileHasMoreClasses()) {
    274     original.Next();
    275     heap.push(std::move(original));
    276   }
    277 }
    278 
    279 static bool CollisionCheck(std::vector<const DexFile*>& dex_files_loaded,
    280                            std::vector<const DexFile*>& dex_files_unloaded,
    281                            std::string* error_msg /*out*/) {
    282   // Generate type index information for each dex file.
    283   std::vector<TypeIndexInfo> loaded_types;
    284   for (const DexFile* dex_file : dex_files_loaded) {
    285     loaded_types.push_back(TypeIndexInfo(dex_file));
    286   }
    287   std::vector<TypeIndexInfo> unloaded_types;
    288   for (const DexFile* dex_file : dex_files_unloaded) {
    289     unloaded_types.push_back(TypeIndexInfo(dex_file));
    290   }
    291 
    292   // Populate the queue of dex file and class pairs with the loaded and unloaded dex files.
    293   std::priority_queue<DexFileAndClassPair> queue;
    294   for (size_t i = 0; i < dex_files_loaded.size(); ++i) {
    295     if (loaded_types[i].GetIterator() != loaded_types[i].GetIteratorEnd()) {
    296       queue.emplace(dex_files_loaded[i], &loaded_types[i], /*from_loaded_oat*/true);
    297     }
    298   }
    299   for (size_t i = 0; i < dex_files_unloaded.size(); ++i) {
    300     if (unloaded_types[i].GetIterator() != unloaded_types[i].GetIteratorEnd()) {
    301       queue.emplace(dex_files_unloaded[i], &unloaded_types[i], /*from_loaded_oat*/false);
    302     }
    303   }
    304 
    305   // Now drain the queue.
    306   bool has_duplicates = false;
    307   error_msg->clear();
    308   while (!queue.empty()) {
    309     // Modifying the top element is only safe if we pop right after.
    310     DexFileAndClassPair compare_pop(queue.top());
    311     queue.pop();
    312 
    313     // Compare against the following elements.
    314     while (!queue.empty()) {
    315       DexFileAndClassPair top(queue.top());
    316       if (strcmp(compare_pop.GetCachedDescriptor(), top.GetCachedDescriptor()) == 0) {
    317         // Same descriptor. Check whether it's crossing old-oat-files to new-oat-files.
    318         if (compare_pop.FromLoadedOat() != top.FromLoadedOat()) {
    319           error_msg->append(
    320               StringPrintf("Found duplicated class when checking oat files: '%s' in %s and %s\n",
    321                            compare_pop.GetCachedDescriptor(),
    322                            compare_pop.GetDexFile()->GetLocation().c_str(),
    323                            top.GetDexFile()->GetLocation().c_str()));
    324           if (!VLOG_IS_ON(oat)) {
    325             return true;
    326           }
    327           has_duplicates = true;
    328         }
    329         queue.pop();
    330         AddNext(top, queue);
    331       } else {
    332         // Something else. Done here.
    333         break;
    334       }
    335     }
    336     AddNext(compare_pop, queue);
    337   }
    338 
    339   return has_duplicates;
    340 }
    341 
    342 // Check for class-def collisions in dex files.
    343 //
    344 // This first walks the class loader chain present in the given context, getting all the dex files
    345 // from the class loader.
    346 //
    347 // If the context is null (which means the initial class loader was null or unsupported)
    348 // this returns false. b/37777332.
    349 //
    350 // This first checks whether all class loaders in the context have the same type and
    351 // classpath. If so, we exit early. Otherwise, we do the collision check.
    352 //
    353 // The collision check works by maintaining a heap with one class from each dex file, sorted by the
    354 // class descriptor. Then a dex-file/class pair is continually removed from the heap and compared
    355 // against the following top element. If the descriptor is the same, it is now checked whether
    356 // the two elements agree on whether their dex file was from an already-loaded oat-file or the
    357 // new oat file. Any disagreement indicates a collision.
    358 bool OatFileManager::HasCollisions(const OatFile* oat_file,
    359                                    const ClassLoaderContext* context,
    360                                    std::string* error_msg /*out*/) const {
    361   DCHECK(oat_file != nullptr);
    362   DCHECK(error_msg != nullptr);
    363 
    364   // The context might be null if there are unrecognized class loaders in the chain or they
    365   // don't meet sensible sanity conditions. In this case we assume that the app knows what it's
    366   // doing and accept the oat file.
    367   // Note that this has correctness implications as we cannot guarantee that the class resolution
    368   // used during compilation is OK (b/37777332).
    369   if (context == nullptr) {
    370       LOG(WARNING) << "Skipping duplicate class check due to unsupported classloader";
    371       return false;
    372   }
    373 
    374   // If the pat file loading context matches the context used during compilation then we accept
    375   // the oat file without addition checks
    376   if (context->VerifyClassLoaderContextMatch(oat_file->GetClassLoaderContext())) {
    377     return false;
    378   }
    379 
    380   // The class loader context does not match. Perform a full duplicate classes check.
    381 
    382   std::vector<const DexFile*> dex_files_loaded = context->FlattenOpenedDexFiles();
    383 
    384   // Vector that holds the newly opened dex files live, this is done to prevent leaks.
    385   std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
    386 
    387   ScopedTrace st("Collision check");
    388   // Add dex files from the oat file to check.
    389   std::vector<const DexFile*> dex_files_unloaded;
    390   AddDexFilesFromOat(oat_file, &dex_files_unloaded, &opened_dex_files);
    391   return CollisionCheck(dex_files_loaded, dex_files_unloaded, error_msg);
    392 }
    393 
    394 std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat(
    395     const char* dex_location,
    396     jobject class_loader,
    397     jobjectArray dex_elements,
    398     const OatFile** out_oat_file,
    399     std::vector<std::string>* error_msgs) {
    400   ScopedTrace trace(__FUNCTION__);
    401   CHECK(dex_location != nullptr);
    402   CHECK(error_msgs != nullptr);
    403 
    404   // Verify we aren't holding the mutator lock, which could starve GC if we
    405   // have to generate or relocate an oat file.
    406   Thread* const self = Thread::Current();
    407   Locks::mutator_lock_->AssertNotHeld(self);
    408   Runtime* const runtime = Runtime::Current();
    409 
    410   std::unique_ptr<ClassLoaderContext> context;
    411   // If the class_loader is null there's not much we can do. This happens if a dex files is loaded
    412   // directly with DexFile APIs instead of using class loaders.
    413   if (class_loader == nullptr) {
    414     LOG(WARNING) << "Opening an oat file without a class loader. "
    415                  << "Are you using the deprecated DexFile APIs?";
    416     context = nullptr;
    417   } else {
    418     context = ClassLoaderContext::CreateContextForClassLoader(class_loader, dex_elements);
    419   }
    420 
    421   OatFileAssistant oat_file_assistant(dex_location,
    422                                       kRuntimeISA,
    423                                       !runtime->IsAotCompiler(),
    424                                       only_use_system_oat_files_);
    425 
    426   // Lock the target oat location to avoid races generating and loading the
    427   // oat file.
    428   std::string error_msg;
    429   if (!oat_file_assistant.Lock(/*out*/&error_msg)) {
    430     // Don't worry too much if this fails. If it does fail, it's unlikely we
    431     // can generate an oat file anyway.
    432     VLOG(class_linker) << "OatFileAssistant::Lock: " << error_msg;
    433   }
    434 
    435   const OatFile* source_oat_file = nullptr;
    436 
    437   if (!oat_file_assistant.IsUpToDate()) {
    438     // Update the oat file on disk if we can, based on the --compiler-filter
    439     // option derived from the current runtime options.
    440     // This may fail, but that's okay. Best effort is all that matters here.
    441     // TODO(calin): b/64530081 b/66984396. Pass a null context to verify and compile
    442     // secondary dex files in isolation (and avoid to extract/verify the main apk
    443     // if it's in the class path). Note this trades correctness for performance
    444     // since the resulting slow down is unacceptable in some cases until b/64530081
    445     // is fixed.
    446     // We still pass the class loader context when the classpath string of the runtime
    447     // is not empty, which is the situation when ART is invoked standalone.
    448     ClassLoaderContext* actual_context = Runtime::Current()->GetClassPathString().empty()
    449         ? nullptr
    450         : context.get();
    451     switch (oat_file_assistant.MakeUpToDate(/*profile_changed*/ false,
    452                                             actual_context,
    453                                             /*out*/ &error_msg)) {
    454       case OatFileAssistant::kUpdateFailed:
    455         LOG(WARNING) << error_msg;
    456         break;
    457 
    458       case OatFileAssistant::kUpdateNotAttempted:
    459         // Avoid spamming the logs if we decided not to attempt making the oat
    460         // file up to date.
    461         VLOG(oat) << error_msg;
    462         break;
    463 
    464       case OatFileAssistant::kUpdateSucceeded:
    465         // Nothing to do.
    466         break;
    467     }
    468   }
    469 
    470   // Get the oat file on disk.
    471   std::unique_ptr<const OatFile> oat_file(oat_file_assistant.GetBestOatFile().release());
    472   VLOG(oat) << "OatFileAssistant(" << dex_location << ").GetBestOatFile()="
    473             << reinterpret_cast<uintptr_t>(oat_file.get())
    474             << " (executable=" << (oat_file != nullptr ? oat_file->IsExecutable() : false) << ")";
    475 
    476   if ((class_loader != nullptr || dex_elements != nullptr) && oat_file != nullptr) {
    477     // Prevent oat files from being loaded if no class_loader or dex_elements are provided.
    478     // This can happen when the deprecated DexFile.<init>(String) is called directly, and it
    479     // could load oat files without checking the classpath, which would be incorrect.
    480     // Take the file only if it has no collisions, or we must take it because of preopting.
    481     bool accept_oat_file =
    482         !HasCollisions(oat_file.get(), context.get(), /*out*/ &error_msg);
    483     if (!accept_oat_file) {
    484       // Failed the collision check. Print warning.
    485       if (Runtime::Current()->IsDexFileFallbackEnabled()) {
    486         if (!oat_file_assistant.HasOriginalDexFiles()) {
    487           // We need to fallback but don't have original dex files. We have to
    488           // fallback to opening the existing oat file. This is potentially
    489           // unsafe so we warn about it.
    490           accept_oat_file = true;
    491 
    492           LOG(WARNING) << "Dex location " << dex_location << " does not seem to include dex file. "
    493                        << "Allow oat file use. This is potentially dangerous.";
    494         } else {
    495           // We have to fallback and found original dex files - extract them from an APK.
    496           // Also warn about this operation because it's potentially wasteful.
    497           LOG(WARNING) << "Found duplicate classes, falling back to extracting from APK : "
    498                        << dex_location;
    499           LOG(WARNING) << "NOTE: This wastes RAM and hurts startup performance.";
    500         }
    501       } else {
    502         // TODO: We should remove this. The fact that we're here implies -Xno-dex-file-fallback
    503         // was set, which means that we should never fallback. If we don't have original dex
    504         // files, we should just fail resolution as the flag intended.
    505         if (!oat_file_assistant.HasOriginalDexFiles()) {
    506           accept_oat_file = true;
    507         }
    508 
    509         LOG(WARNING) << "Found duplicate classes, dex-file-fallback disabled, will be failing to "
    510                         " load classes for " << dex_location;
    511       }
    512 
    513       LOG(WARNING) << error_msg;
    514     }
    515 
    516     if (accept_oat_file) {
    517       VLOG(class_linker) << "Registering " << oat_file->GetLocation();
    518       source_oat_file = RegisterOatFile(std::move(oat_file));
    519       *out_oat_file = source_oat_file;
    520     }
    521   }
    522 
    523   std::vector<std::unique_ptr<const DexFile>> dex_files;
    524 
    525   // Load the dex files from the oat file.
    526   if (source_oat_file != nullptr) {
    527     bool added_image_space = false;
    528     if (source_oat_file->IsExecutable()) {
    529       // We need to throw away the image space if we are debuggable but the oat-file source of the
    530       // image is not otherwise we might get classes with inlined methods or other such things.
    531       std::unique_ptr<gc::space::ImageSpace> image_space;
    532       if (kEnableAppImage && (!runtime->IsJavaDebuggable() || source_oat_file->IsDebuggable())) {
    533         image_space = oat_file_assistant.OpenImageSpace(source_oat_file);
    534       } else {
    535         image_space = nullptr;
    536       }
    537       if (image_space != nullptr) {
    538         ScopedObjectAccess soa(self);
    539         StackHandleScope<1> hs(self);
    540         Handle<mirror::ClassLoader> h_loader(
    541             hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader)));
    542         // Can not load app image without class loader.
    543         if (h_loader != nullptr) {
    544           std::string temp_error_msg;
    545           // Add image space has a race condition since other threads could be reading from the
    546           // spaces array.
    547           {
    548             ScopedThreadSuspension sts(self, kSuspended);
    549             gc::ScopedGCCriticalSection gcs(self,
    550                                             gc::kGcCauseAddRemoveAppImageSpace,
    551                                             gc::kCollectorTypeAddRemoveAppImageSpace);
    552             ScopedSuspendAll ssa("Add image space");
    553             runtime->GetHeap()->AddSpace(image_space.get());
    554           }
    555           {
    556             ScopedTrace trace2(StringPrintf("Adding image space for location %s", dex_location));
    557             added_image_space = runtime->GetClassLinker()->AddImageSpace(image_space.get(),
    558                                                                          h_loader,
    559                                                                          dex_elements,
    560                                                                          dex_location,
    561                                                                          /*out*/&dex_files,
    562                                                                          /*out*/&temp_error_msg);
    563           }
    564           if (added_image_space) {
    565             // Successfully added image space to heap, release the map so that it does not get
    566             // freed.
    567             image_space.release();
    568 
    569             // Register for tracking.
    570             for (const auto& dex_file : dex_files) {
    571               dex::tracking::RegisterDexFile(dex_file.get());
    572             }
    573           } else {
    574             LOG(INFO) << "Failed to add image file " << temp_error_msg;
    575             dex_files.clear();
    576             {
    577               ScopedThreadSuspension sts(self, kSuspended);
    578               gc::ScopedGCCriticalSection gcs(self,
    579                                               gc::kGcCauseAddRemoveAppImageSpace,
    580                                               gc::kCollectorTypeAddRemoveAppImageSpace);
    581               ScopedSuspendAll ssa("Remove image space");
    582               runtime->GetHeap()->RemoveSpace(image_space.get());
    583             }
    584             // Non-fatal, don't update error_msg.
    585           }
    586         }
    587       }
    588     }
    589     if (!added_image_space) {
    590       DCHECK(dex_files.empty());
    591       dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
    592 
    593       // Register for tracking.
    594       for (const auto& dex_file : dex_files) {
    595         dex::tracking::RegisterDexFile(dex_file.get());
    596       }
    597     }
    598     if (dex_files.empty()) {
    599       error_msgs->push_back("Failed to open dex files from " + source_oat_file->GetLocation());
    600     } else {
    601       // Opened dex files from an oat file, madvise them to their loaded state.
    602        for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
    603          OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
    604        }
    605     }
    606   }
    607 
    608   // Fall back to running out of the original dex file if we couldn't load any
    609   // dex_files from the oat file.
    610   if (dex_files.empty()) {
    611     if (oat_file_assistant.HasOriginalDexFiles()) {
    612       if (Runtime::Current()->IsDexFileFallbackEnabled()) {
    613         static constexpr bool kVerifyChecksum = true;
    614         const ArtDexFileLoader dex_file_loader;
    615         if (!dex_file_loader.Open(dex_location,
    616                                   dex_location,
    617                                   Runtime::Current()->IsVerificationEnabled(),
    618                                   kVerifyChecksum,
    619                                   /*out*/ &error_msg,
    620                                   &dex_files)) {
    621           LOG(WARNING) << error_msg;
    622           error_msgs->push_back("Failed to open dex files from " + std::string(dex_location)
    623                                 + " because: " + error_msg);
    624         }
    625       } else {
    626         error_msgs->push_back("Fallback mode disabled, skipping dex files.");
    627       }
    628     } else {
    629       error_msgs->push_back("No original dex files found for dex location "
    630           + std::string(dex_location));
    631     }
    632   }
    633 
    634   return dex_files;
    635 }
    636 
    637 void OatFileManager::SetOnlyUseSystemOatFiles() {
    638   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
    639   CHECK_EQ(oat_files_.size(), GetBootOatFiles().size());
    640   only_use_system_oat_files_ = true;
    641 }
    642 
    643 void OatFileManager::DumpForSigQuit(std::ostream& os) {
    644   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
    645   std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
    646   for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
    647     if (ContainsElement(boot_oat_files, oat_file.get())) {
    648       continue;
    649     }
    650     os << oat_file->GetLocation() << ": " << oat_file->GetCompilerFilter() << "\n";
    651   }
    652 }
    653 
    654 }  // namespace art
    655