Home | History | Annotate | Download | only in runtime
      1 /*
      2  * Copyright (C) 2017 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 "class_loader_context.h"
     18 
     19 #include <stdlib.h>
     20 
     21 #include "android-base/file.h"
     22 #include "art_field-inl.h"
     23 #include "base/dchecked_vector.h"
     24 #include "base/stl_util.h"
     25 #include "class_linker.h"
     26 #include "class_loader_utils.h"
     27 #include "dex_file.h"
     28 #include "handle_scope-inl.h"
     29 #include "jni_internal.h"
     30 #include "oat_file_assistant.h"
     31 #include "obj_ptr-inl.h"
     32 #include "runtime.h"
     33 #include "scoped_thread_state_change-inl.h"
     34 #include "thread.h"
     35 #include "well_known_classes.h"
     36 
     37 namespace art {
     38 
     39 static constexpr char kPathClassLoaderString[] = "PCL";
     40 static constexpr char kDelegateLastClassLoaderString[] = "DLC";
     41 static constexpr char kClassLoaderOpeningMark = '[';
     42 static constexpr char kClassLoaderClosingMark = ']';
     43 static constexpr char kClassLoaderSeparator = ';';
     44 static constexpr char kClasspathSeparator = ':';
     45 static constexpr char kDexFileChecksumSeparator = '*';
     46 
     47 ClassLoaderContext::ClassLoaderContext()
     48     : special_shared_library_(false),
     49       dex_files_open_attempted_(false),
     50       dex_files_open_result_(false),
     51       owns_the_dex_files_(true) {}
     52 
     53 ClassLoaderContext::ClassLoaderContext(bool owns_the_dex_files)
     54     : special_shared_library_(false),
     55       dex_files_open_attempted_(true),
     56       dex_files_open_result_(true),
     57       owns_the_dex_files_(owns_the_dex_files) {}
     58 
     59 ClassLoaderContext::~ClassLoaderContext() {
     60   if (!owns_the_dex_files_) {
     61     // If the context does not own the dex/oat files release the unique pointers to
     62     // make sure we do not de-allocate them.
     63     for (ClassLoaderInfo& info : class_loader_chain_) {
     64       for (std::unique_ptr<OatFile>& oat_file : info.opened_oat_files) {
     65         oat_file.release();
     66       }
     67       for (std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
     68         dex_file.release();
     69       }
     70     }
     71   }
     72 }
     73 
     74 std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Default() {
     75   return Create("");
     76 }
     77 
     78 std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Create(const std::string& spec) {
     79   std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext());
     80   if (result->Parse(spec)) {
     81     return result;
     82   } else {
     83     return nullptr;
     84   }
     85 }
     86 
     87 // The expected format is: "ClassLoaderType1[ClasspathElem1*Checksum1:ClasspathElem2*Checksum2...]".
     88 // The checksum part of the format is expected only if parse_cheksums is true.
     89 bool ClassLoaderContext::ParseClassLoaderSpec(const std::string& class_loader_spec,
     90                                               ClassLoaderType class_loader_type,
     91                                               bool parse_checksums) {
     92   const char* class_loader_type_str = GetClassLoaderTypeName(class_loader_type);
     93   size_t type_str_size = strlen(class_loader_type_str);
     94 
     95   CHECK_EQ(0, class_loader_spec.compare(0, type_str_size, class_loader_type_str));
     96 
     97   // Check the opening and closing markers.
     98   if (class_loader_spec[type_str_size] != kClassLoaderOpeningMark) {
     99     return false;
    100   }
    101   if (class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderClosingMark) {
    102     return false;
    103   }
    104 
    105   // At this point we know the format is ok; continue and extract the classpath.
    106   // Note that class loaders with an empty class path are allowed.
    107   std::string classpath = class_loader_spec.substr(type_str_size + 1,
    108                                                    class_loader_spec.length() - type_str_size - 2);
    109 
    110   class_loader_chain_.push_back(ClassLoaderInfo(class_loader_type));
    111 
    112   if (!parse_checksums) {
    113     Split(classpath, kClasspathSeparator, &class_loader_chain_.back().classpath);
    114   } else {
    115     std::vector<std::string> classpath_elements;
    116     Split(classpath, kClasspathSeparator, &classpath_elements);
    117     for (const std::string& element : classpath_elements) {
    118       std::vector<std::string> dex_file_with_checksum;
    119       Split(element, kDexFileChecksumSeparator, &dex_file_with_checksum);
    120       if (dex_file_with_checksum.size() != 2) {
    121         return false;
    122       }
    123       uint32_t checksum = 0;
    124       if (!ParseInt(dex_file_with_checksum[1].c_str(), &checksum)) {
    125         return false;
    126       }
    127       class_loader_chain_.back().classpath.push_back(dex_file_with_checksum[0]);
    128       class_loader_chain_.back().checksums.push_back(checksum);
    129     }
    130   }
    131 
    132   return true;
    133 }
    134 
    135 // Extracts the class loader type from the given spec.
    136 // Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not
    137 // recognized.
    138 ClassLoaderContext::ClassLoaderType
    139 ClassLoaderContext::ExtractClassLoaderType(const std::string& class_loader_spec) {
    140   const ClassLoaderType kValidTypes[] = {kPathClassLoader, kDelegateLastClassLoader};
    141   for (const ClassLoaderType& type : kValidTypes) {
    142     const char* type_str = GetClassLoaderTypeName(type);
    143     if (class_loader_spec.compare(0, strlen(type_str), type_str) == 0) {
    144       return type;
    145     }
    146   }
    147   return kInvalidClassLoader;
    148 }
    149 
    150 // The format: ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]...
    151 // ClassLoaderType is either "PCL" (PathClassLoader) or "DLC" (DelegateLastClassLoader).
    152 // ClasspathElem is the path of dex/jar/apk file.
    153 bool ClassLoaderContext::Parse(const std::string& spec, bool parse_checksums) {
    154   if (spec.empty()) {
    155     // By default we load the dex files in a PathClassLoader.
    156     // So an empty spec is equivalent to an empty PathClassLoader (this happens when running
    157     // tests)
    158     class_loader_chain_.push_back(ClassLoaderInfo(kPathClassLoader));
    159     return true;
    160   }
    161 
    162   // Stop early if we detect the special shared library, which may be passed as the classpath
    163   // for dex2oat when we want to skip the shared libraries check.
    164   if (spec == OatFile::kSpecialSharedLibrary) {
    165     LOG(INFO) << "The ClassLoaderContext is a special shared library.";
    166     special_shared_library_ = true;
    167     return true;
    168   }
    169 
    170   std::vector<std::string> class_loaders;
    171   Split(spec, kClassLoaderSeparator, &class_loaders);
    172 
    173   for (const std::string& class_loader : class_loaders) {
    174     ClassLoaderType type = ExtractClassLoaderType(class_loader);
    175     if (type == kInvalidClassLoader) {
    176       LOG(ERROR) << "Invalid class loader type: " << class_loader;
    177       return false;
    178     }
    179     if (!ParseClassLoaderSpec(class_loader, type, parse_checksums)) {
    180       LOG(ERROR) << "Invalid class loader spec: " << class_loader;
    181       return false;
    182     }
    183   }
    184   return true;
    185 }
    186 
    187 // Opens requested class path files and appends them to opened_dex_files. If the dex files have
    188 // been stripped, this opens them from their oat files (which get added to opened_oat_files).
    189 bool ClassLoaderContext::OpenDexFiles(InstructionSet isa, const std::string& classpath_dir) {
    190   if (dex_files_open_attempted_) {
    191     // Do not attempt to re-open the files if we already tried.
    192     return dex_files_open_result_;
    193   }
    194 
    195   dex_files_open_attempted_ = true;
    196   // Assume we can open all dex files. If not, we will set this to false as we go.
    197   dex_files_open_result_ = true;
    198 
    199   if (special_shared_library_) {
    200     // Nothing to open if the context is a special shared library.
    201     return true;
    202   }
    203 
    204   // Note that we try to open all dex files even if some fail.
    205   // We may get resource-only apks which we cannot load.
    206   // TODO(calin): Refine the dex opening interface to be able to tell if an archive contains
    207   // no dex files. So that we can distinguish the real failures...
    208   for (ClassLoaderInfo& info : class_loader_chain_) {
    209     size_t opened_dex_files_index = info.opened_dex_files.size();
    210     for (const std::string& cp_elem : info.classpath) {
    211       // If path is relative, append it to the provided base directory.
    212       std::string raw_location = cp_elem;
    213       if (raw_location[0] != '/') {
    214         raw_location = classpath_dir + '/' + raw_location;
    215       }
    216 
    217       std::string location;  // the real location of the class path element.
    218 
    219       if (!android::base::Realpath(raw_location, &location)) {
    220         // If we can't get the realpath of the location there might be something wrong with the
    221         // classpath (maybe the file was deleted).
    222         // Do not continue in this case and return false.
    223         PLOG(ERROR) << "Could not get the realpath of dex location " << raw_location;
    224         return false;
    225       }
    226 
    227       std::string error_msg;
    228       // When opening the dex files from the context we expect their checksum to match their
    229       // contents. So pass true to verify_checksum.
    230       if (!DexFile::Open(location.c_str(),
    231                          location.c_str(),
    232                          /*verify_checksum*/ true,
    233                          &error_msg,
    234                          &info.opened_dex_files)) {
    235         // If we fail to open the dex file because it's been stripped, try to open the dex file
    236         // from its corresponding oat file.
    237         // This could happen when we need to recompile a pre-build whose dex code has been stripped.
    238         // (for example, if the pre-build is only quicken and we want to re-compile it
    239         // speed-profile).
    240         // TODO(calin): Use the vdex directly instead of going through the oat file.
    241         OatFileAssistant oat_file_assistant(location.c_str(), isa, false);
    242         std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
    243         std::vector<std::unique_ptr<const DexFile>> oat_dex_files;
    244         if (oat_file != nullptr &&
    245             OatFileAssistant::LoadDexFiles(*oat_file, location, &oat_dex_files)) {
    246           info.opened_oat_files.push_back(std::move(oat_file));
    247           info.opened_dex_files.insert(info.opened_dex_files.end(),
    248                                        std::make_move_iterator(oat_dex_files.begin()),
    249                                        std::make_move_iterator(oat_dex_files.end()));
    250         } else {
    251           LOG(WARNING) << "Could not open dex files from location: " << location;
    252           dex_files_open_result_ = false;
    253         }
    254       }
    255     }
    256 
    257     // We finished opening the dex files from the classpath.
    258     // Now update the classpath and the checksum with the locations of the dex files.
    259     //
    260     // We do this because initially the classpath contains the paths of the dex files; and
    261     // some of them might be multi-dexes. So in order to have a consistent view we replace all the
    262     // file paths with the actual dex locations being loaded.
    263     // This will allow the context to VerifyClassLoaderContextMatch which expects or multidex
    264     // location in the class paths.
    265     // Note that this will also remove the paths that could not be opened.
    266     info.classpath.clear();
    267     info.checksums.clear();
    268     for (size_t k = opened_dex_files_index; k < info.opened_dex_files.size(); k++) {
    269       std::unique_ptr<const DexFile>& dex = info.opened_dex_files[k];
    270       info.classpath.push_back(dex->GetLocation());
    271       info.checksums.push_back(dex->GetLocationChecksum());
    272     }
    273   }
    274 
    275   return dex_files_open_result_;
    276 }
    277 
    278 bool ClassLoaderContext::RemoveLocationsFromClassPaths(
    279     const dchecked_vector<std::string>& locations) {
    280   CHECK(!dex_files_open_attempted_)
    281       << "RemoveLocationsFromClasspaths cannot be call after OpenDexFiles";
    282 
    283   std::set<std::string> canonical_locations;
    284   for (const std::string& location : locations) {
    285     canonical_locations.insert(DexFile::GetDexCanonicalLocation(location.c_str()));
    286   }
    287   bool removed_locations = false;
    288   for (ClassLoaderInfo& info : class_loader_chain_) {
    289     size_t initial_size = info.classpath.size();
    290     auto kept_it = std::remove_if(
    291         info.classpath.begin(),
    292         info.classpath.end(),
    293         [canonical_locations](const std::string& location) {
    294             return ContainsElement(canonical_locations,
    295                                    DexFile::GetDexCanonicalLocation(location.c_str()));
    296         });
    297     info.classpath.erase(kept_it, info.classpath.end());
    298     if (initial_size != info.classpath.size()) {
    299       removed_locations = true;
    300     }
    301   }
    302   return removed_locations;
    303 }
    304 
    305 std::string ClassLoaderContext::EncodeContextForDex2oat(const std::string& base_dir) const {
    306   return EncodeContext(base_dir, /*for_dex2oat*/ true);
    307 }
    308 
    309 std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir) const {
    310   return EncodeContext(base_dir, /*for_dex2oat*/ false);
    311 }
    312 
    313 std::string ClassLoaderContext::EncodeContext(const std::string& base_dir,
    314                                               bool for_dex2oat) const {
    315   CheckDexFilesOpened("EncodeContextForOatFile");
    316   if (special_shared_library_) {
    317     return OatFile::kSpecialSharedLibrary;
    318   }
    319 
    320   std::ostringstream out;
    321   if (class_loader_chain_.empty()) {
    322     // We can get in this situation if the context was created with a class path containing the
    323     // source dex files which were later removed (happens during run-tests).
    324     out << GetClassLoaderTypeName(kPathClassLoader)
    325         << kClassLoaderOpeningMark
    326         << kClassLoaderClosingMark;
    327     return out.str();
    328   }
    329 
    330   for (size_t i = 0; i < class_loader_chain_.size(); i++) {
    331     const ClassLoaderInfo& info = class_loader_chain_[i];
    332     if (i > 0) {
    333       out << kClassLoaderSeparator;
    334     }
    335     out << GetClassLoaderTypeName(info.type);
    336     out << kClassLoaderOpeningMark;
    337     std::set<std::string> seen_locations;
    338     for (size_t k = 0; k < info.opened_dex_files.size(); k++) {
    339       const std::unique_ptr<const DexFile>& dex_file = info.opened_dex_files[k];
    340       if (for_dex2oat) {
    341         // dex2oat only needs the base location. It cannot accept multidex locations.
    342         // So ensure we only add each file once.
    343         bool new_insert = seen_locations.insert(dex_file->GetBaseLocation()).second;
    344         if (!new_insert) {
    345           continue;
    346         }
    347       }
    348       const std::string& location = dex_file->GetLocation();
    349       if (k > 0) {
    350         out << kClasspathSeparator;
    351       }
    352       // Find paths that were relative and convert them back from absolute.
    353       if (!base_dir.empty() && location.substr(0, base_dir.length()) == base_dir) {
    354         out << location.substr(base_dir.length() + 1).c_str();
    355       } else {
    356         out << dex_file->GetLocation().c_str();
    357       }
    358       // dex2oat does not need the checksums.
    359       if (!for_dex2oat) {
    360         out << kDexFileChecksumSeparator;
    361         out << dex_file->GetLocationChecksum();
    362       }
    363     }
    364     out << kClassLoaderClosingMark;
    365   }
    366   return out.str();
    367 }
    368 
    369 jobject ClassLoaderContext::CreateClassLoader(
    370     const std::vector<const DexFile*>& compilation_sources) const {
    371   CheckDexFilesOpened("CreateClassLoader");
    372 
    373   Thread* self = Thread::Current();
    374   ScopedObjectAccess soa(self);
    375 
    376   ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
    377 
    378   if (class_loader_chain_.empty()) {
    379     return class_linker->CreatePathClassLoader(self, compilation_sources);
    380   }
    381 
    382   // Create the class loaders starting from the top most parent (the one on the last position
    383   // in the chain) but omit the first class loader which will contain the compilation_sources and
    384   // needs special handling.
    385   jobject current_parent = nullptr;  // the starting parent is the BootClassLoader.
    386   for (size_t i = class_loader_chain_.size() - 1; i > 0; i--) {
    387     std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(
    388         class_loader_chain_[i].opened_dex_files);
    389     current_parent = class_linker->CreateWellKnownClassLoader(
    390         self,
    391         class_path_files,
    392         GetClassLoaderClass(class_loader_chain_[i].type),
    393         current_parent);
    394   }
    395 
    396   // We set up all the parents. Move on to create the first class loader.
    397   // Its classpath comes first, followed by compilation sources. This ensures that whenever
    398   // we need to resolve classes from it the classpath elements come first.
    399 
    400   std::vector<const DexFile*> first_class_loader_classpath = MakeNonOwningPointerVector(
    401       class_loader_chain_[0].opened_dex_files);
    402   first_class_loader_classpath.insert(first_class_loader_classpath.end(),
    403                                     compilation_sources.begin(),
    404                                     compilation_sources.end());
    405 
    406   return class_linker->CreateWellKnownClassLoader(
    407       self,
    408       first_class_loader_classpath,
    409       GetClassLoaderClass(class_loader_chain_[0].type),
    410       current_parent);
    411 }
    412 
    413 std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
    414   CheckDexFilesOpened("FlattenOpenedDexFiles");
    415 
    416   std::vector<const DexFile*> result;
    417   for (const ClassLoaderInfo& info : class_loader_chain_) {
    418     for (const std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
    419       result.push_back(dex_file.get());
    420     }
    421   }
    422   return result;
    423 }
    424 
    425 const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
    426   switch (type) {
    427     case kPathClassLoader: return kPathClassLoaderString;
    428     case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
    429     default:
    430       LOG(FATAL) << "Invalid class loader type " << type;
    431       UNREACHABLE();
    432   }
    433 }
    434 
    435 void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
    436   CHECK(dex_files_open_attempted_)
    437       << "Dex files were not successfully opened before the call to " << calling_method
    438       << "attempt=" << dex_files_open_attempted_ << ", result=" << dex_files_open_result_;
    439 }
    440 
    441 // Collects the dex files from the give Java dex_file object. Only the dex files with
    442 // at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
    443 static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
    444                                            ArtField* const cookie_field,
    445                                            std::vector<const DexFile*>* out_dex_files)
    446       REQUIRES_SHARED(Locks::mutator_lock_) {
    447   if (java_dex_file == nullptr) {
    448     return true;
    449   }
    450   // On the Java side, the dex files are stored in the cookie field.
    451   mirror::LongArray* long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
    452   if (long_array == nullptr) {
    453     // This should never happen so log a warning.
    454     LOG(ERROR) << "Unexpected null cookie";
    455     return false;
    456   }
    457   int32_t long_array_size = long_array->GetLength();
    458   // Index 0 from the long array stores the oat file. The dex files start at index 1.
    459   for (int32_t j = 1; j < long_array_size; ++j) {
    460     const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
    461         long_array->GetWithoutChecks(j)));
    462     if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
    463       // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
    464       // cp_dex_file can be null.
    465       out_dex_files->push_back(cp_dex_file);
    466     }
    467   }
    468   return true;
    469 }
    470 
    471 // Collects all the dex files loaded by the given class loader.
    472 // Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
    473 // a null list of dex elements or a null dex element).
    474 static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
    475                                                     Handle<mirror::ClassLoader> class_loader,
    476                                                     std::vector<const DexFile*>* out_dex_files)
    477       REQUIRES_SHARED(Locks::mutator_lock_) {
    478   CHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader));
    479 
    480   // All supported class loaders inherit from BaseDexClassLoader.
    481   // We need to get the DexPathList and loop through it.
    482   ArtField* const cookie_field =
    483       jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
    484   ArtField* const dex_file_field =
    485       jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
    486   ObjPtr<mirror::Object> dex_path_list =
    487       jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
    488           GetObject(class_loader.Get());
    489   CHECK(cookie_field != nullptr);
    490   CHECK(dex_file_field != nullptr);
    491   if (dex_path_list == nullptr) {
    492     // This may be null if the current class loader is under construction and it does not
    493     // have its fields setup yet.
    494     return true;
    495   }
    496   // DexPathList has an array dexElements of Elements[] which each contain a dex file.
    497   ObjPtr<mirror::Object> dex_elements_obj =
    498       jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
    499           GetObject(dex_path_list);
    500   // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
    501   // at the mCookie which is a DexFile vector.
    502   if (dex_elements_obj == nullptr) {
    503     // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
    504     // and assume we have no elements.
    505     return true;
    506   } else {
    507     StackHandleScope<1> hs(soa.Self());
    508     Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
    509         hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
    510     for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
    511       mirror::Object* element = dex_elements->GetWithoutChecks(i);
    512       if (element == nullptr) {
    513         // Should never happen, log an error and break.
    514         // TODO(calin): It's unclear if we should just assert here.
    515         // This code was propagated to oat_file_manager from the class linker where it would
    516         // throw a NPE. For now, return false which will mark this class loader as unsupported.
    517         LOG(ERROR) << "Unexpected null in the dex element list";
    518         return false;
    519       }
    520       ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
    521       if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
    522         return false;
    523       }
    524     }
    525   }
    526 
    527   return true;
    528 }
    529 
    530 static bool GetDexFilesFromDexElementsArray(
    531     ScopedObjectAccessAlreadyRunnable& soa,
    532     Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
    533     std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
    534   DCHECK(dex_elements != nullptr);
    535 
    536   ArtField* const cookie_field =
    537       jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
    538   ArtField* const dex_file_field =
    539       jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
    540   ObjPtr<mirror::Class> const element_class = soa.Decode<mirror::Class>(
    541       WellKnownClasses::dalvik_system_DexPathList__Element);
    542   ObjPtr<mirror::Class> const dexfile_class = soa.Decode<mirror::Class>(
    543       WellKnownClasses::dalvik_system_DexFile);
    544 
    545   for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
    546     mirror::Object* element = dex_elements->GetWithoutChecks(i);
    547     // We can hit a null element here because this is invoked with a partially filled dex_elements
    548     // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
    549     // list of dex files which were opened before.
    550     if (element == nullptr) {
    551       continue;
    552     }
    553 
    554     // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
    555     // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
    556     // a historical glitch. All the java code opens dex files using an array of Elements.
    557     ObjPtr<mirror::Object> dex_file;
    558     if (element_class == element->GetClass()) {
    559       dex_file = dex_file_field->GetObject(element);
    560     } else if (dexfile_class == element->GetClass()) {
    561       dex_file = element;
    562     } else {
    563       LOG(ERROR) << "Unsupported element in dex_elements: "
    564                  << mirror::Class::PrettyClass(element->GetClass());
    565       return false;
    566     }
    567 
    568     if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
    569       return false;
    570     }
    571   }
    572   return true;
    573 }
    574 
    575 // Adds the `class_loader` info to the `context`.
    576 // The dex file present in `dex_elements` array (if not null) will be added at the end of
    577 // the classpath.
    578 // This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
    579 // BootClassLoader. Note that the class loader chain is expected to be short.
    580 bool ClassLoaderContext::AddInfoToContextFromClassLoader(
    581       ScopedObjectAccessAlreadyRunnable& soa,
    582       Handle<mirror::ClassLoader> class_loader,
    583       Handle<mirror::ObjectArray<mirror::Object>> dex_elements)
    584     REQUIRES_SHARED(Locks::mutator_lock_) {
    585   if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
    586     // Nothing to do for the boot class loader as we don't add its dex files to the context.
    587     return true;
    588   }
    589 
    590   ClassLoaderContext::ClassLoaderType type;
    591   if (IsPathOrDexClassLoader(soa, class_loader)) {
    592     type = kPathClassLoader;
    593   } else if (IsDelegateLastClassLoader(soa, class_loader)) {
    594     type = kDelegateLastClassLoader;
    595   } else {
    596     LOG(WARNING) << "Unsupported class loader";
    597     return false;
    598   }
    599 
    600   // Inspect the class loader for its dex files.
    601   std::vector<const DexFile*> dex_files_loaded;
    602   CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
    603 
    604   // If we have a dex_elements array extract its dex elements now.
    605   // This is used in two situations:
    606   //   1) when a new ClassLoader is created DexPathList will open each dex file sequentially
    607   //      passing the list of already open dex files each time. This ensures that we see the
    608   //      correct context even if the ClassLoader under construction is not fully build.
    609   //   2) when apk splits are loaded on the fly, the framework will load their dex files by
    610   //      appending them to the current class loader. When the new code paths are loaded in
    611   //      BaseDexClassLoader, the paths already present in the class loader will be passed
    612   //      in the dex_elements array.
    613   if (dex_elements != nullptr) {
    614     GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
    615   }
    616 
    617   class_loader_chain_.push_back(ClassLoaderContext::ClassLoaderInfo(type));
    618   ClassLoaderInfo& info = class_loader_chain_.back();
    619   for (const DexFile* dex_file : dex_files_loaded) {
    620     info.classpath.push_back(dex_file->GetLocation());
    621     info.checksums.push_back(dex_file->GetLocationChecksum());
    622     info.opened_dex_files.emplace_back(dex_file);
    623   }
    624 
    625   // We created the ClassLoaderInfo for the current loader. Move on to its parent.
    626 
    627   StackHandleScope<1> hs(Thread::Current());
    628   Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
    629 
    630   // Note that dex_elements array is null here. The elements are considered to be part of the
    631   // current class loader and are not passed to the parents.
    632   ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
    633   return AddInfoToContextFromClassLoader(soa, parent, null_dex_elements);
    634 }
    635 
    636 std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
    637     jobject class_loader,
    638     jobjectArray dex_elements) {
    639   CHECK(class_loader != nullptr);
    640 
    641   ScopedObjectAccess soa(Thread::Current());
    642   StackHandleScope<2> hs(soa.Self());
    643   Handle<mirror::ClassLoader> h_class_loader =
    644       hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
    645   Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
    646       hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
    647 
    648   std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files*/ false));
    649   if (result->AddInfoToContextFromClassLoader(soa, h_class_loader, h_dex_elements)) {
    650     return result;
    651   } else {
    652     return nullptr;
    653   }
    654 }
    655 
    656 static bool IsAbsoluteLocation(const std::string& location) {
    657   return !location.empty() && location[0] == '/';
    658 }
    659 
    660 bool ClassLoaderContext::VerifyClassLoaderContextMatch(const std::string& context_spec) const {
    661   DCHECK(dex_files_open_attempted_);
    662   DCHECK(dex_files_open_result_);
    663 
    664   ClassLoaderContext expected_context;
    665   if (!expected_context.Parse(context_spec, /*parse_checksums*/ true)) {
    666     LOG(WARNING) << "Invalid class loader context: " << context_spec;
    667     return false;
    668   }
    669 
    670   // Special shared library contexts always match. They essentially instruct the runtime
    671   // to ignore the class path check because the oat file is known to be loaded in different
    672   // contexts. OatFileManager will further verify if the oat file can be loaded based on the
    673   // collision check.
    674   if (special_shared_library_ || expected_context.special_shared_library_) {
    675     return true;
    676   }
    677 
    678   if (expected_context.class_loader_chain_.size() != class_loader_chain_.size()) {
    679     LOG(WARNING) << "ClassLoaderContext size mismatch. expected="
    680         << expected_context.class_loader_chain_.size()
    681         << ", actual=" << class_loader_chain_.size()
    682         << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
    683     return false;
    684   }
    685 
    686   for (size_t i = 0; i < class_loader_chain_.size(); i++) {
    687     const ClassLoaderInfo& info = class_loader_chain_[i];
    688     const ClassLoaderInfo& expected_info = expected_context.class_loader_chain_[i];
    689     if (info.type != expected_info.type) {
    690       LOG(WARNING) << "ClassLoaderContext type mismatch for position " << i
    691           << ". expected=" << GetClassLoaderTypeName(expected_info.type)
    692           << ", found=" << GetClassLoaderTypeName(info.type)
    693           << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
    694       return false;
    695     }
    696     if (info.classpath.size() != expected_info.classpath.size()) {
    697       LOG(WARNING) << "ClassLoaderContext classpath size mismatch for position " << i
    698             << ". expected=" << expected_info.classpath.size()
    699             << ", found=" << info.classpath.size()
    700             << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
    701       return false;
    702     }
    703 
    704     DCHECK_EQ(info.classpath.size(), info.checksums.size());
    705     DCHECK_EQ(expected_info.classpath.size(), expected_info.checksums.size());
    706 
    707     for (size_t k = 0; k < info.classpath.size(); k++) {
    708       // Compute the dex location that must be compared.
    709       // We shouldn't do a naive comparison `info.classpath[k] == expected_info.classpath[k]`
    710       // because even if they refer to the same file, one could be encoded as a relative location
    711       // and the other as an absolute one.
    712       bool is_dex_name_absolute = IsAbsoluteLocation(info.classpath[k]);
    713       bool is_expected_dex_name_absolute = IsAbsoluteLocation(expected_info.classpath[k]);
    714       std::string dex_name;
    715       std::string expected_dex_name;
    716 
    717       if (is_dex_name_absolute == is_expected_dex_name_absolute) {
    718         // If both locations are absolute or relative then compare them as they are.
    719         // This is usually the case for: shared libraries and secondary dex files.
    720         dex_name = info.classpath[k];
    721         expected_dex_name = expected_info.classpath[k];
    722       } else if (is_dex_name_absolute) {
    723         // The runtime name is absolute but the compiled name (the expected one) is relative.
    724         // This is the case for split apks which depend on base or on other splits.
    725         dex_name = info.classpath[k];
    726         expected_dex_name = OatFile::ResolveRelativeEncodedDexLocation(
    727             info.classpath[k].c_str(), expected_info.classpath[k]);
    728       } else {
    729         // The runtime name is relative but the compiled name is absolute.
    730         // There is no expected use case that would end up here as dex files are always loaded
    731         // with their absolute location. However, be tolerant and do the best effort (in case
    732         // there are unexpected new use case...).
    733         DCHECK(is_expected_dex_name_absolute);
    734         dex_name = OatFile::ResolveRelativeEncodedDexLocation(
    735             expected_info.classpath[k].c_str(), info.classpath[k]);
    736         expected_dex_name = expected_info.classpath[k];
    737       }
    738 
    739       // Compare the locations.
    740       if (dex_name != expected_dex_name) {
    741         LOG(WARNING) << "ClassLoaderContext classpath element mismatch for position " << i
    742             << ". expected=" << expected_info.classpath[k]
    743             << ", found=" << info.classpath[k]
    744             << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
    745         return false;
    746       }
    747 
    748       // Compare the checksums.
    749       if (info.checksums[k] != expected_info.checksums[k]) {
    750         LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch for position " << i
    751                      << ". expected=" << expected_info.checksums[k]
    752                      << ", found=" << info.checksums[k]
    753                      << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
    754         return false;
    755       }
    756     }
    757   }
    758   return true;
    759 }
    760 
    761 jclass ClassLoaderContext::GetClassLoaderClass(ClassLoaderType type) {
    762   switch (type) {
    763     case kPathClassLoader: return WellKnownClasses::dalvik_system_PathClassLoader;
    764     case kDelegateLastClassLoader: return WellKnownClasses::dalvik_system_DelegateLastClassLoader;
    765     case kInvalidClassLoader: break;  // will fail after the switch.
    766   }
    767   LOG(FATAL) << "Invalid class loader type " << type;
    768   UNREACHABLE();
    769 }
    770 
    771 }  // namespace art
    772 
    773