dalvik_system_DexFile.cc revision cd7e7f78b8e97c1f6419f3f44e0d5fdc6eddfdc6
1/* 2 * Copyright (C) 2008 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 "dalvik_system_DexFile.h" 18 19#include <sstream> 20 21#include "base/logging.h" 22#include "base/stl_util.h" 23#include "base/stringprintf.h" 24#include "class_linker.h" 25#include "common_throws.h" 26#include "compiler_filter.h" 27#include "dex_file-inl.h" 28#include "jni_internal.h" 29#include "mirror/class_loader.h" 30#include "mirror/object-inl.h" 31#include "mirror/string.h" 32#include "oat_file.h" 33#include "oat_file_assistant.h" 34#include "oat_file_manager.h" 35#include "os.h" 36#include "profiler.h" 37#include "runtime.h" 38#include "scoped_thread_state_change.h" 39#include "ScopedLocalRef.h" 40#include "ScopedUtfChars.h" 41#include "utils.h" 42#include "well_known_classes.h" 43#include "zip_archive.h" 44 45namespace art { 46 47static bool ConvertJavaArrayToDexFiles( 48 JNIEnv* env, 49 jobject arrayObject, 50 /*out*/ std::vector<const DexFile*>& dex_files, 51 /*out*/ const OatFile*& oat_file) { 52 jarray array = reinterpret_cast<jarray>(arrayObject); 53 54 jsize array_size = env->GetArrayLength(array); 55 if (env->ExceptionCheck() == JNI_TRUE) { 56 return false; 57 } 58 59 // TODO: Optimize. On 32bit we can use an int array. 60 jboolean is_long_data_copied; 61 jlong* long_data = env->GetLongArrayElements(reinterpret_cast<jlongArray>(array), 62 &is_long_data_copied); 63 if (env->ExceptionCheck() == JNI_TRUE) { 64 return false; 65 } 66 67 oat_file = reinterpret_cast<const OatFile*>(static_cast<uintptr_t>(long_data[kOatFileIndex])); 68 dex_files.reserve(array_size - 1); 69 for (jsize i = kDexFileIndexStart; i < array_size; ++i) { 70 dex_files.push_back(reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(long_data[i]))); 71 } 72 73 env->ReleaseLongArrayElements(reinterpret_cast<jlongArray>(array), long_data, JNI_ABORT); 74 return env->ExceptionCheck() != JNI_TRUE; 75} 76 77static jlongArray ConvertDexFilesToJavaArray(JNIEnv* env, 78 const OatFile* oat_file, 79 std::vector<std::unique_ptr<const DexFile>>& vec) { 80 // Add one for the oat file. 81 jlongArray long_array = env->NewLongArray(static_cast<jsize>(kDexFileIndexStart + vec.size())); 82 if (env->ExceptionCheck() == JNI_TRUE) { 83 return nullptr; 84 } 85 86 jboolean is_long_data_copied; 87 jlong* long_data = env->GetLongArrayElements(long_array, &is_long_data_copied); 88 if (env->ExceptionCheck() == JNI_TRUE) { 89 return nullptr; 90 } 91 92 long_data[kOatFileIndex] = reinterpret_cast<uintptr_t>(oat_file); 93 for (size_t i = 0; i < vec.size(); ++i) { 94 long_data[kDexFileIndexStart + i] = reinterpret_cast<uintptr_t>(vec[i].get()); 95 } 96 97 env->ReleaseLongArrayElements(long_array, long_data, 0); 98 if (env->ExceptionCheck() == JNI_TRUE) { 99 return nullptr; 100 } 101 102 // Now release all the unique_ptrs. 103 for (auto& dex_file : vec) { 104 dex_file.release(); 105 } 106 107 return long_array; 108} 109 110// A smart pointer that provides read-only access to a Java string's UTF chars. 111// Unlike libcore's NullableScopedUtfChars, this will *not* throw NullPointerException if 112// passed a null jstring. The correct idiom is: 113// 114// NullableScopedUtfChars name(env, javaName); 115// if (env->ExceptionCheck()) { 116// return null; 117// } 118// // ... use name.c_str() 119// 120// TODO: rewrite to get rid of this, or change ScopedUtfChars to offer this option. 121class NullableScopedUtfChars { 122 public: 123 NullableScopedUtfChars(JNIEnv* env, jstring s) : mEnv(env), mString(s) { 124 mUtfChars = (s != nullptr) ? env->GetStringUTFChars(s, nullptr) : nullptr; 125 } 126 127 ~NullableScopedUtfChars() { 128 if (mUtfChars) { 129 mEnv->ReleaseStringUTFChars(mString, mUtfChars); 130 } 131 } 132 133 const char* c_str() const { 134 return mUtfChars; 135 } 136 137 size_t size() const { 138 return strlen(mUtfChars); 139 } 140 141 // Element access. 142 const char& operator[](size_t n) const { 143 return mUtfChars[n]; 144 } 145 146 private: 147 JNIEnv* mEnv; 148 jstring mString; 149 const char* mUtfChars; 150 151 // Disallow copy and assignment. 152 NullableScopedUtfChars(const NullableScopedUtfChars&); 153 void operator=(const NullableScopedUtfChars&); 154}; 155 156static jobject DexFile_openDexFileNative(JNIEnv* env, 157 jclass, 158 jstring javaSourceName, 159 jstring javaOutputName, 160 jint flags ATTRIBUTE_UNUSED, 161 jobject class_loader, 162 jobjectArray dex_elements) { 163 ScopedUtfChars sourceName(env, javaSourceName); 164 if (sourceName.c_str() == nullptr) { 165 return 0; 166 } 167 NullableScopedUtfChars outputName(env, javaOutputName); 168 if (env->ExceptionCheck()) { 169 return 0; 170 } 171 Runtime* const runtime = Runtime::Current(); 172 ClassLinker* linker = runtime->GetClassLinker(); 173 std::vector<std::unique_ptr<const DexFile>> dex_files; 174 std::vector<std::string> error_msgs; 175 const OatFile* oat_file = nullptr; 176 177 dex_files = runtime->GetOatFileManager().OpenDexFilesFromOat(sourceName.c_str(), 178 outputName.c_str(), 179 class_loader, 180 dex_elements, 181 /*out*/ &oat_file, 182 /*out*/ &error_msgs); 183 184 if (!dex_files.empty()) { 185 jlongArray array = ConvertDexFilesToJavaArray(env, oat_file, dex_files); 186 if (array == nullptr) { 187 ScopedObjectAccess soa(env); 188 for (auto& dex_file : dex_files) { 189 if (linker->FindDexCache(soa.Self(), *dex_file, true) != nullptr) { 190 dex_file.release(); 191 } 192 } 193 } 194 return array; 195 } else { 196 ScopedObjectAccess soa(env); 197 CHECK(!error_msgs.empty()); 198 // The most important message is at the end. So set up nesting by going forward, which will 199 // wrap the existing exception as a cause for the following one. 200 auto it = error_msgs.begin(); 201 auto itEnd = error_msgs.end(); 202 for ( ; it != itEnd; ++it) { 203 ThrowWrappedIOException("%s", it->c_str()); 204 } 205 206 return nullptr; 207 } 208} 209 210static jboolean DexFile_closeDexFile(JNIEnv* env, jclass, jobject cookie) { 211 std::vector<const DexFile*> dex_files; 212 const OatFile* oat_file; 213 if (!ConvertJavaArrayToDexFiles(env, cookie, dex_files, oat_file)) { 214 Thread::Current()->AssertPendingException(); 215 return JNI_FALSE; 216 } 217 Runtime* const runtime = Runtime::Current(); 218 bool all_deleted = true; 219 { 220 ScopedObjectAccess soa(env); 221 mirror::Object* dex_files_object = soa.Decode<mirror::Object*>(cookie); 222 mirror::LongArray* long_dex_files = dex_files_object->AsLongArray(); 223 // Delete dex files associated with this dalvik.system.DexFile since there should not be running 224 // code using it. dex_files is a vector due to multidex. 225 ClassLinker* const class_linker = runtime->GetClassLinker(); 226 int32_t i = kDexFileIndexStart; // Oat file is at index 0. 227 for (const DexFile* dex_file : dex_files) { 228 if (dex_file != nullptr) { 229 // Only delete the dex file if the dex cache is not found to prevent runtime crashes if there 230 // are calls to DexFile.close while the ART DexFile is still in use. 231 if (class_linker->FindDexCache(soa.Self(), *dex_file, true) == nullptr) { 232 // Clear the element in the array so that we can call close again. 233 long_dex_files->Set(i, 0); 234 delete dex_file; 235 } else { 236 all_deleted = false; 237 } 238 } 239 ++i; 240 } 241 } 242 243 // oat_file can be null if we are running without dex2oat. 244 if (all_deleted && oat_file != nullptr) { 245 // If all of the dex files are no longer in use we can unmap the corresponding oat file. 246 VLOG(class_linker) << "Unregistering " << oat_file; 247 runtime->GetOatFileManager().UnRegisterAndDeleteOatFile(oat_file); 248 } 249 return all_deleted ? JNI_TRUE : JNI_FALSE; 250} 251 252static jclass DexFile_defineClassNative(JNIEnv* env, 253 jclass, 254 jstring javaName, 255 jobject javaLoader, 256 jobject cookie, 257 jobject dexFile) { 258 std::vector<const DexFile*> dex_files; 259 const OatFile* oat_file; 260 if (!ConvertJavaArrayToDexFiles(env, cookie, /*out*/ dex_files, /*out*/ oat_file)) { 261 VLOG(class_linker) << "Failed to find dex_file"; 262 DCHECK(env->ExceptionCheck()); 263 return nullptr; 264 } 265 266 ScopedUtfChars class_name(env, javaName); 267 if (class_name.c_str() == nullptr) { 268 VLOG(class_linker) << "Failed to find class_name"; 269 return nullptr; 270 } 271 const std::string descriptor(DotToDescriptor(class_name.c_str())); 272 const size_t hash(ComputeModifiedUtf8Hash(descriptor.c_str())); 273 for (auto& dex_file : dex_files) { 274 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor.c_str(), hash); 275 if (dex_class_def != nullptr) { 276 ScopedObjectAccess soa(env); 277 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 278 StackHandleScope<1> hs(soa.Self()); 279 Handle<mirror::ClassLoader> class_loader( 280 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(javaLoader))); 281 class_linker->RegisterDexFile( 282 *dex_file, 283 class_linker->GetOrCreateAllocatorForClassLoader(class_loader.Get())); 284 mirror::Class* result = class_linker->DefineClass(soa.Self(), 285 descriptor.c_str(), 286 hash, 287 class_loader, 288 *dex_file, 289 *dex_class_def); 290 // Add the used dex file. This only required for the DexFile.loadClass API since normal 291 // class loaders already keep their dex files live. 292 class_linker->InsertDexFileInToClassLoader(soa.Decode<mirror::Object*>(dexFile), 293 class_loader.Get()); 294 if (result != nullptr) { 295 VLOG(class_linker) << "DexFile_defineClassNative returning " << result 296 << " for " << class_name.c_str(); 297 return soa.AddLocalReference<jclass>(result); 298 } 299 } 300 } 301 VLOG(class_linker) << "Failed to find dex_class_def " << class_name.c_str(); 302 return nullptr; 303} 304 305// Needed as a compare functor for sets of const char 306struct CharPointerComparator { 307 bool operator()(const char *str1, const char *str2) const { 308 return strcmp(str1, str2) < 0; 309 } 310}; 311 312// Note: this can be an expensive call, as we sort out duplicates in MultiDex files. 313static jobjectArray DexFile_getClassNameList(JNIEnv* env, jclass, jobject cookie) { 314 const OatFile* oat_file = nullptr; 315 std::vector<const DexFile*> dex_files; 316 if (!ConvertJavaArrayToDexFiles(env, cookie, /*out */ dex_files, /* out */ oat_file)) { 317 DCHECK(env->ExceptionCheck()); 318 return nullptr; 319 } 320 321 // Push all class descriptors into a set. Use set instead of unordered_set as we want to 322 // retrieve all in the end. 323 std::set<const char*, CharPointerComparator> descriptors; 324 for (auto& dex_file : dex_files) { 325 for (size_t i = 0; i < dex_file->NumClassDefs(); ++i) { 326 const DexFile::ClassDef& class_def = dex_file->GetClassDef(i); 327 const char* descriptor = dex_file->GetClassDescriptor(class_def); 328 descriptors.insert(descriptor); 329 } 330 } 331 332 // Now create output array and copy the set into it. 333 jobjectArray result = env->NewObjectArray(descriptors.size(), 334 WellKnownClasses::java_lang_String, 335 nullptr); 336 if (result != nullptr) { 337 auto it = descriptors.begin(); 338 auto it_end = descriptors.end(); 339 jsize i = 0; 340 for (; it != it_end; it++, ++i) { 341 std::string descriptor(DescriptorToDot(*it)); 342 ScopedLocalRef<jstring> jdescriptor(env, env->NewStringUTF(descriptor.c_str())); 343 if (jdescriptor.get() == nullptr) { 344 return nullptr; 345 } 346 env->SetObjectArrayElement(result, i, jdescriptor.get()); 347 } 348 } 349 return result; 350} 351 352static jint GetDexOptNeeded(JNIEnv* env, 353 const char* filename, 354 const char* instruction_set, 355 const char* compiler_filter_name, 356 bool profile_changed) { 357 if ((filename == nullptr) || !OS::FileExists(filename)) { 358 LOG(ERROR) << "DexFile_getDexOptNeeded file '" << filename << "' does not exist"; 359 ScopedLocalRef<jclass> fnfe(env, env->FindClass("java/io/FileNotFoundException")); 360 const char* message = (filename == nullptr) ? "<empty file name>" : filename; 361 env->ThrowNew(fnfe.get(), message); 362 return -1; 363 } 364 365 const InstructionSet target_instruction_set = GetInstructionSetFromString(instruction_set); 366 if (target_instruction_set == kNone) { 367 ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException")); 368 std::string message(StringPrintf("Instruction set %s is invalid.", instruction_set)); 369 env->ThrowNew(iae.get(), message.c_str()); 370 return -1; 371 } 372 373 CompilerFilter::Filter filter; 374 if (!CompilerFilter::ParseCompilerFilter(compiler_filter_name, &filter)) { 375 ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException")); 376 std::string message(StringPrintf("Compiler filter %s is invalid.", compiler_filter_name)); 377 env->ThrowNew(iae.get(), message.c_str()); 378 return -1; 379 } 380 381 // TODO: Verify the dex location is well formed, and throw an IOException if 382 // not? 383 384 OatFileAssistant oat_file_assistant(filename, target_instruction_set, profile_changed, false); 385 386 // Always treat elements of the bootclasspath as up-to-date. 387 if (oat_file_assistant.IsInBootClassPath()) { 388 return OatFileAssistant::kNoDexOptNeeded; 389 } 390 return oat_file_assistant.GetDexOptNeeded(filter); 391} 392 393static jstring DexFile_getDexFileStatus(JNIEnv* env, 394 jclass, 395 jstring javaFilename, 396 jstring javaInstructionSet) { 397 ScopedUtfChars filename(env, javaFilename); 398 if (env->ExceptionCheck()) { 399 return nullptr; 400 } 401 402 ScopedUtfChars instruction_set(env, javaInstructionSet); 403 if (env->ExceptionCheck()) { 404 return nullptr; 405 } 406 407 const InstructionSet target_instruction_set = GetInstructionSetFromString( 408 instruction_set.c_str()); 409 if (target_instruction_set == kNone) { 410 ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException")); 411 std::string message(StringPrintf("Instruction set %s is invalid.", instruction_set.c_str())); 412 env->ThrowNew(iae.get(), message.c_str()); 413 return nullptr; 414 } 415 416 OatFileAssistant oat_file_assistant(filename.c_str(), target_instruction_set, 417 false /* profile_changed */, 418 false /* load_executable */); 419 420 std::ostringstream status; 421 bool oat_file_exists = false; 422 bool odex_file_exists = false; 423 if (oat_file_assistant.OatFileExists()) { 424 oat_file_exists = true; 425 status << *oat_file_assistant.OatFileName() << " [compilation_filter="; 426 status << CompilerFilter::NameOfFilter(oat_file_assistant.OatFileCompilerFilter()); 427 status << ", status=" << oat_file_assistant.OatFileStatus(); 428 } 429 430 if (oat_file_assistant.OdexFileExists()) { 431 odex_file_exists = true; 432 if (oat_file_exists) { 433 status << "] "; 434 } 435 status << *oat_file_assistant.OdexFileName() << " [compilation_filter="; 436 status << CompilerFilter::NameOfFilter(oat_file_assistant.OdexFileCompilerFilter()); 437 status << ", status=" << oat_file_assistant.OdexFileStatus(); 438 } 439 440 if (!oat_file_exists && !odex_file_exists) { 441 status << "invalid["; 442 } 443 444 status << "]"; 445 return env->NewStringUTF(status.str().c_str()); 446} 447 448static jint DexFile_getDexOptNeeded(JNIEnv* env, 449 jclass, 450 jstring javaFilename, 451 jstring javaInstructionSet, 452 jstring javaTargetCompilerFilter, 453 jboolean newProfile) { 454 ScopedUtfChars filename(env, javaFilename); 455 if (env->ExceptionCheck()) { 456 return -1; 457 } 458 459 ScopedUtfChars instruction_set(env, javaInstructionSet); 460 if (env->ExceptionCheck()) { 461 return -1; 462 } 463 464 ScopedUtfChars target_compiler_filter(env, javaTargetCompilerFilter); 465 if (env->ExceptionCheck()) { 466 return -1; 467 } 468 469 return GetDexOptNeeded(env, 470 filename.c_str(), 471 instruction_set.c_str(), 472 target_compiler_filter.c_str(), 473 newProfile == JNI_TRUE); 474} 475 476// public API 477static jboolean DexFile_isDexOptNeeded(JNIEnv* env, jclass, jstring javaFilename) { 478 const char* instruction_set = GetInstructionSetString(kRuntimeISA); 479 ScopedUtfChars filename(env, javaFilename); 480 jint status = GetDexOptNeeded( 481 env, 482 filename.c_str(), 483 instruction_set, 484 "speed-profile", 485 /*profile_changed*/false); 486 return (status != OatFileAssistant::kNoDexOptNeeded) ? JNI_TRUE : JNI_FALSE; 487} 488 489static jboolean DexFile_isValidCompilerFilter(JNIEnv* env, 490 jclass javeDexFileClass ATTRIBUTE_UNUSED, 491 jstring javaCompilerFilter) { 492 ScopedUtfChars compiler_filter(env, javaCompilerFilter); 493 if (env->ExceptionCheck()) { 494 return -1; 495 } 496 497 CompilerFilter::Filter filter; 498 return CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter) 499 ? JNI_TRUE : JNI_FALSE; 500} 501 502static jboolean DexFile_isProfileGuidedCompilerFilter(JNIEnv* env, 503 jclass javeDexFileClass ATTRIBUTE_UNUSED, 504 jstring javaCompilerFilter) { 505 ScopedUtfChars compiler_filter(env, javaCompilerFilter); 506 if (env->ExceptionCheck()) { 507 return -1; 508 } 509 510 CompilerFilter::Filter filter; 511 if (!CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)) { 512 return JNI_FALSE; 513 } 514 return CompilerFilter::DependsOnProfile(filter) ? JNI_TRUE : JNI_FALSE; 515} 516 517static jstring DexFile_getNonProfileGuidedCompilerFilter(JNIEnv* env, 518 jclass javeDexFileClass ATTRIBUTE_UNUSED, 519 jstring javaCompilerFilter) { 520 ScopedUtfChars compiler_filter(env, javaCompilerFilter); 521 if (env->ExceptionCheck()) { 522 return nullptr; 523 } 524 525 CompilerFilter::Filter filter; 526 if (!CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)) { 527 return javaCompilerFilter; 528 } 529 530 CompilerFilter::Filter new_filter = CompilerFilter::GetNonProfileDependentFilterFrom(filter); 531 532 // Filter stayed the same, return input. 533 if (filter == new_filter) { 534 return javaCompilerFilter; 535 } 536 537 // Create a new string object and return. 538 std::string new_filter_str = CompilerFilter::NameOfFilter(new_filter); 539 return env->NewStringUTF(new_filter_str.c_str()); 540} 541 542static jboolean DexFile_isBackedByOatFile(JNIEnv* env, jclass, jobject cookie) { 543 const OatFile* oat_file = nullptr; 544 std::vector<const DexFile*> dex_files; 545 if (!ConvertJavaArrayToDexFiles(env, cookie, /*out */ dex_files, /* out */ oat_file)) { 546 DCHECK(env->ExceptionCheck()); 547 return false; 548 } 549 return oat_file != nullptr; 550} 551 552static JNINativeMethod gMethods[] = { 553 NATIVE_METHOD(DexFile, closeDexFile, "(Ljava/lang/Object;)Z"), 554 NATIVE_METHOD(DexFile, 555 defineClassNative, 556 "(Ljava/lang/String;" 557 "Ljava/lang/ClassLoader;" 558 "Ljava/lang/Object;" 559 "Ldalvik/system/DexFile;" 560 ")Ljava/lang/Class;"), 561 NATIVE_METHOD(DexFile, getClassNameList, "(Ljava/lang/Object;)[Ljava/lang/String;"), 562 NATIVE_METHOD(DexFile, isDexOptNeeded, "(Ljava/lang/String;)Z"), 563 NATIVE_METHOD(DexFile, getDexOptNeeded, 564 "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)I"), 565 NATIVE_METHOD(DexFile, openDexFileNative, 566 "(Ljava/lang/String;" 567 "Ljava/lang/String;" 568 "I" 569 "Ljava/lang/ClassLoader;" 570 "[Ldalvik/system/DexPathList$Element;" 571 ")Ljava/lang/Object;"), 572 NATIVE_METHOD(DexFile, isValidCompilerFilter, "(Ljava/lang/String;)Z"), 573 NATIVE_METHOD(DexFile, isProfileGuidedCompilerFilter, "(Ljava/lang/String;)Z"), 574 NATIVE_METHOD(DexFile, 575 getNonProfileGuidedCompilerFilter, 576 "(Ljava/lang/String;)Ljava/lang/String;"), 577 NATIVE_METHOD(DexFile, isBackedByOatFile, "(Ljava/lang/Object;)Z"), 578 NATIVE_METHOD(DexFile, getDexFileStatus, 579 "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;") 580}; 581 582void register_dalvik_system_DexFile(JNIEnv* env) { 583 REGISTER_NATIVE_METHODS("dalvik/system/DexFile"); 584} 585 586} // namespace art 587