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