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 "android-base/file.h"
22 #include "android-base/stringprintf.h"
23
24 #include "base/casts.h"
25 #include "base/compiler_filter.h"
26 #include "base/file_utils.h"
27 #include "base/hiddenapi_domain.h"
28 #include "base/logging.h"
29 #include "base/os.h"
30 #include "base/stl_util.h"
31 #include "base/transform_iterator.h"
32 #include "base/utils.h"
33 #include "base/zip_archive.h"
34 #include "class_linker.h"
35 #include "class_loader_context.h"
36 #include "common_throws.h"
37 #include "dex/art_dex_file_loader.h"
38 #include "dex/descriptors_names.h"
39 #include "dex/dex_file-inl.h"
40 #include "dex/dex_file_loader.h"
41 #include "gc/space/image_space.h"
42 #include "handle_scope-inl.h"
43 #include "jit/debugger_interface.h"
44 #include "jni/jni_internal.h"
45 #include "mirror/class_loader.h"
46 #include "mirror/object-inl.h"
47 #include "mirror/string.h"
48 #include "native_util.h"
49 #include "nativehelper/jni_macros.h"
50 #include "nativehelper/scoped_local_ref.h"
51 #include "nativehelper/scoped_utf_chars.h"
52 #include "oat/oat_file.h"
53 #include "oat/oat_file_assistant.h"
54 #include "oat/oat_file_manager.h"
55 #include "runtime.h"
56 #include "scoped_thread_state_change-inl.h"
57 #include "string_array_utils.h"
58 #include "thread-current-inl.h"
59
60 #ifdef ART_TARGET_ANDROID
61 #include <android/api-level.h>
62 #include <sys/system_properties.h>
63 #endif // ART_TARGET_ANDROID
64
65 namespace art HIDDEN {
66
67 // Should be the same as dalvik.system.DexFile.ENFORCE_READ_ONLY_JAVA_DCL
68 static constexpr uint64_t kEnforceReadOnlyJavaDcl = 218865702;
69
70 using android::base::StringPrintf;
71
ConvertJavaArrayToDexFiles(JNIEnv * env,jobject arrayObject,std::vector<const DexFile * > & dex_files,const OatFile * & oat_file)72 static bool ConvertJavaArrayToDexFiles(
73 JNIEnv* env,
74 jobject arrayObject,
75 /*out*/ std::vector<const DexFile*>& dex_files,
76 /*out*/ const OatFile*& oat_file) {
77 jarray array = reinterpret_cast<jarray>(arrayObject);
78
79 jsize array_size = env->GetArrayLength(array);
80 if (env->ExceptionCheck() == JNI_TRUE) {
81 return false;
82 }
83
84 // TODO: Optimize. On 32bit we can use an int array.
85 jboolean is_long_data_copied;
86 jlong* long_data = env->GetLongArrayElements(reinterpret_cast<jlongArray>(array),
87 &is_long_data_copied);
88 if (env->ExceptionCheck() == JNI_TRUE) {
89 return false;
90 }
91
92 oat_file = reinterpret_cast64<const OatFile*>(long_data[kOatFileIndex]);
93 dex_files.reserve(array_size - 1);
94 for (jsize i = kDexFileIndexStart; i < array_size; ++i) {
95 dex_files.push_back(reinterpret_cast64<const DexFile*>(long_data[i]));
96 }
97
98 env->ReleaseLongArrayElements(reinterpret_cast<jlongArray>(array), long_data, JNI_ABORT);
99 return env->ExceptionCheck() != JNI_TRUE;
100 }
101
ConvertDexFilesToJavaArray(JNIEnv * env,const OatFile * oat_file,std::vector<std::unique_ptr<const DexFile>> & vec)102 static jlongArray ConvertDexFilesToJavaArray(JNIEnv* env,
103 const OatFile* oat_file,
104 std::vector<std::unique_ptr<const DexFile>>& vec) {
105 // Add one for the oat file.
106 jlongArray long_array = env->NewLongArray(static_cast<jsize>(kDexFileIndexStart + vec.size()));
107 if (env->ExceptionCheck() == JNI_TRUE) {
108 return nullptr;
109 }
110
111 jboolean is_long_data_copied;
112 jlong* long_data = env->GetLongArrayElements(long_array, &is_long_data_copied);
113 if (env->ExceptionCheck() == JNI_TRUE) {
114 return nullptr;
115 }
116
117 long_data[kOatFileIndex] = reinterpret_cast64<jlong>(oat_file);
118 for (size_t i = 0; i < vec.size(); ++i) {
119 long_data[kDexFileIndexStart + i] = reinterpret_cast64<jlong>(vec[i].get());
120 }
121
122 env->ReleaseLongArrayElements(long_array, long_data, 0);
123 if (env->ExceptionCheck() == JNI_TRUE) {
124 return nullptr;
125 }
126
127 // Now release all the unique_ptrs.
128 for (auto& dex_file : vec) {
129 dex_file.release(); // NOLINT
130 }
131
132 return long_array;
133 }
134
135 // A smart pointer that provides read-only access to a Java string's UTF chars.
136 // Unlike libcore's NullableScopedUtfChars, this will *not* throw NullPointerException if
137 // passed a null jstring. The correct idiom is:
138 //
139 // NullableScopedUtfChars name(env, javaName);
140 // if (env->ExceptionCheck()) {
141 // return null;
142 // }
143 // // ... use name.c_str()
144 //
145 // TODO: rewrite to get rid of this, or change ScopedUtfChars to offer this option.
146 class NullableScopedUtfChars {
147 public:
NullableScopedUtfChars(JNIEnv * env,jstring s)148 NullableScopedUtfChars(JNIEnv* env, jstring s) : mEnv(env), mString(s) {
149 mUtfChars = (s != nullptr) ? env->GetStringUTFChars(s, nullptr) : nullptr;
150 }
151
~NullableScopedUtfChars()152 ~NullableScopedUtfChars() {
153 if (mUtfChars) {
154 mEnv->ReleaseStringUTFChars(mString, mUtfChars);
155 }
156 }
157
c_str() const158 const char* c_str() const {
159 return mUtfChars;
160 }
161
size() const162 size_t size() const {
163 return strlen(mUtfChars);
164 }
165
166 // Element access.
operator [](size_t n) const167 const char& operator[](size_t n) const {
168 return mUtfChars[n];
169 }
170
171 private:
172 JNIEnv* mEnv;
173 jstring mString;
174 const char* mUtfChars;
175
176 // Disallow copy and assignment.
177 NullableScopedUtfChars(const NullableScopedUtfChars&);
178 void operator=(const NullableScopedUtfChars&);
179 };
180
CreateCookieFromOatFileManagerResult(JNIEnv * env,std::vector<std::unique_ptr<const DexFile>> & dex_files,const OatFile * oat_file,const std::vector<std::string> & error_msgs)181 static jobject CreateCookieFromOatFileManagerResult(
182 JNIEnv* env,
183 std::vector<std::unique_ptr<const DexFile>>& dex_files,
184 const OatFile* oat_file,
185 const std::vector<std::string>& error_msgs) {
186 ClassLinker* linker = Runtime::Current()->GetClassLinker();
187 if (dex_files.empty()) {
188 ScopedObjectAccess soa(env);
189 CHECK(!error_msgs.empty());
190 // The most important message is at the end. So set up nesting by going forward, which will
191 // wrap the existing exception as a cause for the following one.
192 auto it = error_msgs.begin();
193 auto itEnd = error_msgs.end();
194 for ( ; it != itEnd; ++it) {
195 ThrowWrappedIOException("%s", it->c_str());
196 }
197 return nullptr;
198 }
199
200 jlongArray array = ConvertDexFilesToJavaArray(env, oat_file, dex_files);
201 if (array == nullptr) {
202 ScopedObjectAccess soa(env);
203 for (auto& dex_file : dex_files) {
204 if (linker->IsDexFileRegistered(soa.Self(), *dex_file)) {
205 dex_file.release(); // NOLINT
206 }
207 }
208 }
209 return array;
210 }
211
AllocateDexMemoryMap(JNIEnv * env,jint start,jint end)212 static MemMap AllocateDexMemoryMap(JNIEnv* env, jint start, jint end) {
213 if (end <= start) {
214 ScopedObjectAccess soa(env);
215 ThrowWrappedIOException("Bad range");
216 return MemMap::Invalid();
217 }
218
219 std::string error_message;
220 size_t length = static_cast<size_t>(end - start);
221 MemMap dex_mem_map = MemMap::MapAnonymous("DEX data",
222 length,
223 PROT_READ | PROT_WRITE,
224 /*low_4gb=*/ false,
225 &error_message);
226 if (!dex_mem_map.IsValid()) {
227 ScopedObjectAccess soa(env);
228 ThrowWrappedIOException("%s", error_message.c_str());
229 return MemMap::Invalid();
230 }
231 return dex_mem_map;
232 }
233
234 struct ScopedIntArrayAccessor {
235 public:
ScopedIntArrayAccessorart::ScopedIntArrayAccessor236 ScopedIntArrayAccessor(JNIEnv* env, jintArray arr) : env_(env), array_(arr) {
237 elements_ = env_->GetIntArrayElements(array_, /* isCopy= */ nullptr);
238 CHECK(elements_ != nullptr);
239 }
240
~ScopedIntArrayAccessorart::ScopedIntArrayAccessor241 ~ScopedIntArrayAccessor() {
242 env_->ReleaseIntArrayElements(array_, elements_, JNI_ABORT);
243 }
244
Getart::ScopedIntArrayAccessor245 jint Get(jsize index) const { return elements_[index]; }
246
247 private:
248 JNIEnv* env_;
249 jintArray array_;
250 jint* elements_;
251 };
252
DexFile_openInMemoryDexFilesNative(JNIEnv * env,jclass,jobjectArray buffers,jobjectArray arrays,jintArray jstarts,jintArray jends,jobject class_loader,jobjectArray dex_elements)253 static jobject DexFile_openInMemoryDexFilesNative(JNIEnv* env,
254 jclass,
255 jobjectArray buffers,
256 jobjectArray arrays,
257 jintArray jstarts,
258 jintArray jends,
259 jobject class_loader,
260 jobjectArray dex_elements) {
261 jsize buffers_length = env->GetArrayLength(buffers);
262 CHECK_EQ(buffers_length, env->GetArrayLength(arrays));
263 CHECK_EQ(buffers_length, env->GetArrayLength(jstarts));
264 CHECK_EQ(buffers_length, env->GetArrayLength(jends));
265
266 ScopedIntArrayAccessor starts(env, jstarts);
267 ScopedIntArrayAccessor ends(env, jends);
268
269 // Allocate memory for dex files and copy data from ByteBuffers.
270 std::vector<MemMap> dex_mem_maps;
271 dex_mem_maps.reserve(buffers_length);
272 for (jsize i = 0; i < buffers_length; ++i) {
273 jobject buffer = env->GetObjectArrayElement(buffers, i);
274 jbyteArray array = reinterpret_cast<jbyteArray>(env->GetObjectArrayElement(arrays, i));
275 jint start = starts.Get(i);
276 jint end = ends.Get(i);
277
278 MemMap dex_data = AllocateDexMemoryMap(env, start, end);
279 if (!dex_data.IsValid()) {
280 DCHECK(Thread::Current()->IsExceptionPending());
281 return nullptr;
282 }
283
284 if (array == nullptr) {
285 // Direct ByteBuffer
286 uint8_t* base_address = reinterpret_cast<uint8_t*>(env->GetDirectBufferAddress(buffer));
287 if (base_address == nullptr) {
288 ScopedObjectAccess soa(env);
289 ThrowWrappedIOException("dexFileBuffer not direct");
290 return nullptr;
291 }
292 size_t length = static_cast<size_t>(end - start);
293 memcpy(dex_data.Begin(), base_address + start, length);
294 } else {
295 // ByteBuffer backed by a byte array
296 jbyte* destination = reinterpret_cast<jbyte*>(dex_data.Begin());
297 env->GetByteArrayRegion(array, start, end - start, destination);
298 }
299
300 dex_mem_maps.push_back(std::move(dex_data));
301 }
302
303 // Hand MemMaps over to OatFileManager to open the dex files and potentially
304 // create a backing OatFile instance from an anonymous vdex.
305 std::vector<std::string> error_msgs;
306 const OatFile* oat_file = nullptr;
307 std::vector<std::unique_ptr<const DexFile>> dex_files =
308 Runtime::Current()->GetOatFileManager().OpenDexFilesFromOat(std::move(dex_mem_maps),
309 class_loader,
310 dex_elements,
311 /*out*/ &oat_file,
312 /*out*/ &error_msgs);
313 return CreateCookieFromOatFileManagerResult(env, dex_files, oat_file, error_msgs);
314 }
315
316 #ifdef ART_TARGET_ANDROID
isReadOnlyJavaDclEnforced(JNIEnv * env)317 static bool isReadOnlyJavaDclEnforced(JNIEnv* env) {
318 static bool is_at_least_u = [] {
319 const int api_level = android_get_device_api_level();
320 if (api_level > __ANDROID_API_T__) {
321 return true;
322 } else if (api_level == __ANDROID_API_T__) {
323 // Check if running U preview
324 char value[92] = {0};
325 if (__system_property_get("ro.build.version.preview_sdk", value) >= 0 && atoi(value) > 0) {
326 return true;
327 }
328 }
329 return false;
330 }();
331 if (is_at_least_u) {
332 // The reason why we are calling the AppCompat framework through JVM
333 // instead of directly using the CompatFramework C++ API is because feature
334 // overrides only apply to the Java API.
335 // CtsLibcoreTestCases is part of mainline modules, which requires the same test
336 // to run on older Android versions; the target SDK of CtsLibcoreTestCases is locked
337 // to the lowest supported API level (at the time of writing, it's API 31).
338 // We would need to be able to manually enable the compat change in CTS tests.
339 ScopedLocalRef<jclass> compat(env, env->FindClass("android/compat/Compatibility"));
340 jmethodID mId = env->GetStaticMethodID(compat.get(), "isChangeEnabled", "(J)Z");
341 return env->CallStaticBooleanMethod(compat.get(), mId, kEnforceReadOnlyJavaDcl) == JNI_TRUE;
342 } else {
343 return false;
344 }
345 }
346 #else // ART_TARGET_ANDROID
isReadOnlyJavaDclEnforced(JNIEnv *)347 constexpr static bool isReadOnlyJavaDclEnforced(JNIEnv*) {
348 (void)kEnforceReadOnlyJavaDcl;
349 return false;
350 }
351 #endif // ART_TARGET_ANDROID
352
isReadOnlyJavaDclChecked()353 static bool isReadOnlyJavaDclChecked() {
354 if (!kIsTargetAndroid) {
355 return false;
356 }
357 const int uid = getuid();
358 // The following UIDs are exempted:
359 // * Root (0): root processes always have write access to files.
360 // * System (1000): /data/app/**.apk are owned by AID_SYSTEM;
361 // loading installed APKs in system_server is allowed.
362 // * Shell (2000): directly calling dalvikvm/app_process in ADB shell
363 // to run JARs with CLI is allowed.
364 return uid != 0 && uid != 1000 && uid != 2000;
365 }
366
367 // TODO(calin): clean up the unused parameters (here and in libcore).
DexFile_openDexFileNative(JNIEnv * env,jclass,jstring javaSourceName,jstring javaOutputName,jint flags,jobject class_loader,jobjectArray dex_elements)368 static jobject DexFile_openDexFileNative(JNIEnv* env,
369 jclass,
370 jstring javaSourceName,
371 [[maybe_unused]] jstring javaOutputName,
372 [[maybe_unused]] jint flags,
373 jobject class_loader,
374 jobjectArray dex_elements) {
375 ScopedUtfChars sourceName(env, javaSourceName);
376 if (sourceName.c_str() == nullptr) {
377 return nullptr;
378 }
379
380 if (isReadOnlyJavaDclChecked() && access(sourceName.c_str(), W_OK) == 0) {
381 LOG(ERROR) << "Attempt to load writable dex file: " << sourceName.c_str();
382 if (isReadOnlyJavaDclEnforced(env)) {
383 ScopedLocalRef<jclass> se(env, env->FindClass("java/lang/SecurityException"));
384 std::string message(
385 StringPrintf("Writable dex file '%s' is not allowed.", sourceName.c_str()));
386 env->ThrowNew(se.get(), message.c_str());
387 return nullptr;
388 }
389 }
390
391 std::vector<std::string> error_msgs;
392 const OatFile* oat_file = nullptr;
393 std::vector<std::unique_ptr<const DexFile>> dex_files =
394 Runtime::Current()->GetOatFileManager().OpenDexFilesFromOat(sourceName.c_str(),
395 class_loader,
396 dex_elements,
397 /*out*/ &oat_file,
398 /*out*/ &error_msgs);
399 return CreateCookieFromOatFileManagerResult(env, dex_files, oat_file, error_msgs);
400 }
401
DexFile_verifyInBackgroundNative(JNIEnv * env,jclass,jobject cookie,jobject class_loader)402 static void DexFile_verifyInBackgroundNative(JNIEnv* env,
403 jclass,
404 jobject cookie,
405 jobject class_loader) {
406 CHECK(cookie != nullptr);
407 CHECK(class_loader != nullptr);
408
409 // Extract list of dex files from the cookie.
410 std::vector<const DexFile*> dex_files;
411 const OatFile* oat_file;
412 if (!ConvertJavaArrayToDexFiles(env, cookie, dex_files, oat_file)) {
413 Thread::Current()->AssertPendingException();
414 return;
415 }
416 CHECK(oat_file == nullptr) << "Called verifyInBackground on a dex file backed by oat";
417
418 // Hand over to OatFileManager to spawn a verification thread.
419 Runtime::Current()->GetOatFileManager().RunBackgroundVerification(
420 dex_files,
421 class_loader);
422 }
423
DexFile_closeDexFile(JNIEnv * env,jclass,jobject cookie)424 static jboolean DexFile_closeDexFile(JNIEnv* env, jclass, jobject cookie) {
425 std::vector<const DexFile*> dex_files;
426 const OatFile* oat_file;
427 if (!ConvertJavaArrayToDexFiles(env, cookie, dex_files, oat_file)) {
428 Thread::Current()->AssertPendingException();
429 return JNI_FALSE;
430 }
431 Runtime* const runtime = Runtime::Current();
432 bool all_deleted = true;
433 // We need to clear the caches since they may contain pointers to the dex instructions.
434 // Different dex file can be loaded at the same memory location later by chance.
435 Thread::ClearAllInterpreterCaches();
436 {
437 ScopedObjectAccess soa(env);
438 ObjPtr<mirror::Object> dex_files_object = soa.Decode<mirror::Object>(cookie);
439 ObjPtr<mirror::LongArray> long_dex_files = dex_files_object->AsLongArray();
440 // Delete dex files associated with this dalvik.system.DexFile since there should not be running
441 // code using it. dex_files is a vector due to multidex.
442 ClassLinker* const class_linker = runtime->GetClassLinker();
443 int32_t i = kDexFileIndexStart; // Oat file is at index 0.
444 for (const DexFile* dex_file : dex_files) {
445 if (dex_file != nullptr) {
446 RemoveNativeDebugInfoForDex(soa.Self(), dex_file);
447 // Only delete the dex file if the dex cache is not found to prevent runtime crashes
448 // if there are calls to DexFile.close while the ART DexFile is still in use.
449 if (!class_linker->IsDexFileRegistered(soa.Self(), *dex_file)) {
450 // Clear the element in the array so that we can call close again.
451 long_dex_files->Set(i, 0);
452 class_linker->RemoveDexFromCaches(*dex_file);
453 delete dex_file;
454 } else {
455 all_deleted = false;
456 }
457 }
458 ++i;
459 }
460 }
461
462 // oat_file can be null if we are running without dex2oat.
463 if (all_deleted && oat_file != nullptr) {
464 // If all of the dex files are no longer in use we can unmap the corresponding oat file.
465 VLOG(class_linker) << "Unregistering " << oat_file;
466 runtime->GetOatFileManager().UnRegisterAndDeleteOatFile(oat_file);
467 }
468 return all_deleted ? JNI_TRUE : JNI_FALSE;
469 }
470
DexFile_defineClassNative(JNIEnv * env,jclass,jstring javaName,jobject javaLoader,jobject cookie,jobject dexFile)471 static jclass DexFile_defineClassNative(JNIEnv* env,
472 jclass,
473 jstring javaName,
474 jobject javaLoader,
475 jobject cookie,
476 jobject dexFile) {
477 std::vector<const DexFile*> dex_files;
478 const OatFile* oat_file;
479 if (!ConvertJavaArrayToDexFiles(env, cookie, /*out*/ dex_files, /*out*/ oat_file)) {
480 VLOG(class_linker) << "Failed to find dex_file";
481 DCHECK(env->ExceptionCheck());
482 return nullptr;
483 }
484
485 ScopedUtfChars class_name(env, javaName);
486 if (class_name.c_str() == nullptr) {
487 VLOG(class_linker) << "Failed to find class_name";
488 return nullptr;
489 }
490 const std::string descriptor = DotToDescriptor(class_name);
491 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
492 for (auto& dex_file : dex_files) {
493 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
494 if (dex_class_def != nullptr) {
495 ScopedObjectAccess soa(env);
496 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
497 StackHandleScope<1> hs(soa.Self());
498 Handle<mirror::ClassLoader> class_loader(
499 hs.NewHandle(soa.Decode<mirror::ClassLoader>(javaLoader)));
500 ObjPtr<mirror::DexCache> dex_cache =
501 class_linker->RegisterDexFile(*dex_file, class_loader.Get());
502 if (dex_cache == nullptr) {
503 // OOME or InternalError (dexFile already registered with a different class loader).
504 soa.Self()->AssertPendingException();
505 return nullptr;
506 }
507 ObjPtr<mirror::Class> result = class_linker->DefineClass(soa.Self(),
508 descriptor.c_str(),
509 descriptor.length(),
510 hash,
511 class_loader,
512 *dex_file,
513 *dex_class_def);
514 // Add the used dex file. This only required for the DexFile.loadClass API since normal
515 // class loaders already keep their dex files live.
516 class_linker->InsertDexFileInToClassLoader(soa.Decode<mirror::Object>(dexFile),
517 class_loader.Get());
518 if (result != nullptr) {
519 VLOG(class_linker) << "DexFile_defineClassNative returning " << result
520 << " for " << class_name.c_str();
521 return soa.AddLocalReference<jclass>(result);
522 }
523 }
524 }
525 VLOG(class_linker) << "Failed to find dex_class_def " << class_name.c_str();
526 return nullptr;
527 }
528
529 // Needed as a compare functor for sets of const char
530 struct CharPointerComparator {
operator ()art::CharPointerComparator531 bool operator()(const char *str1, const char *str2) const {
532 return strcmp(str1, str2) < 0;
533 }
534 };
535
536 // Note: this can be an expensive call, as we sort out duplicates in MultiDex files.
DexFile_getClassNameList(JNIEnv * env,jclass,jobject cookie)537 static jobjectArray DexFile_getClassNameList(JNIEnv* env, jclass, jobject cookie) {
538 const OatFile* oat_file = nullptr;
539 std::vector<const DexFile*> dex_files;
540 if (!ConvertJavaArrayToDexFiles(env, cookie, /*out */ dex_files, /* out */ oat_file)) {
541 DCHECK(env->ExceptionCheck());
542 return nullptr;
543 }
544
545 // Push all class descriptors into a set. Use set instead of unordered_set as we want to
546 // retrieve all in the end.
547 std::set<const char*, CharPointerComparator> descriptors;
548 for (auto& dex_file : dex_files) {
549 for (size_t i = 0; i < dex_file->NumClassDefs(); ++i) {
550 const dex::ClassDef& class_def = dex_file->GetClassDef(i);
551 const char* descriptor = dex_file->GetClassDescriptor(class_def);
552 descriptors.insert(descriptor);
553 }
554 }
555
556 // Now create output array and copy the set into it.
557 ScopedObjectAccess soa(Thread::ForEnv(env));
558 auto descriptor_to_dot = [](const char* descriptor) { return DescriptorToDot(descriptor); };
559 return soa.AddLocalReference<jobjectArray>(CreateStringArray(
560 soa.Self(),
561 descriptors.size(),
562 MakeTransformRange(descriptors, descriptor_to_dot)));
563 }
564
GetDexOptNeeded(JNIEnv * env,const char * filename,const char * instruction_set,const char * compiler_filter_name,const char * class_loader_context,bool profile_changed,bool downgrade)565 static jint GetDexOptNeeded(JNIEnv* env,
566 const char* filename,
567 const char* instruction_set,
568 const char* compiler_filter_name,
569 const char* class_loader_context,
570 bool profile_changed,
571 bool downgrade) {
572 if ((filename == nullptr) || !OS::FileExists(filename)) {
573 LOG(ERROR) << "DexFile_getDexOptNeeded file '" << filename << "' does not exist";
574 ScopedLocalRef<jclass> fnfe(env, env->FindClass("java/io/FileNotFoundException"));
575 const char* message = (filename == nullptr) ? "<empty file name>" : filename;
576 env->ThrowNew(fnfe.get(), message);
577 return -1;
578 }
579
580 const InstructionSet target_instruction_set = GetInstructionSetFromString(instruction_set);
581 if (target_instruction_set == InstructionSet::kNone) {
582 ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException"));
583 std::string message(StringPrintf("Instruction set %s is invalid.", instruction_set));
584 env->ThrowNew(iae.get(), message.c_str());
585 return -1;
586 }
587
588 CompilerFilter::Filter filter;
589 if (!CompilerFilter::ParseCompilerFilter(compiler_filter_name, &filter)) {
590 ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException"));
591 std::string message(StringPrintf("Compiler filter %s is invalid.", compiler_filter_name));
592 env->ThrowNew(iae.get(), message.c_str());
593 return -1;
594 }
595
596 std::unique_ptr<ClassLoaderContext> context = nullptr;
597 if (class_loader_context != nullptr) {
598 context = ClassLoaderContext::Create(class_loader_context);
599
600 if (context == nullptr) {
601 ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException"));
602 std::string message(StringPrintf("Class loader context '%s' is invalid.",
603 class_loader_context));
604 env->ThrowNew(iae.get(), message.c_str());
605 return -1;
606 }
607 std::vector<int> context_fds;
608 context->OpenDexFiles(android::base::Dirname(filename),
609 context_fds,
610 /*only_read_checksums*/ true);
611 }
612
613 // TODO: Verify the dex location is well formed, and throw an IOException if
614 // not?
615
616 OatFileAssistant oat_file_assistant(filename,
617 target_instruction_set,
618 context.get(),
619 /* load_executable= */ false);
620
621 // Always treat elements of the bootclasspath as up-to-date.
622 if (oat_file_assistant.IsInBootClassPath()) {
623 return OatFileAssistant::kNoDexOptNeeded;
624 }
625
626 return oat_file_assistant.GetDexOptNeeded(filter,
627 profile_changed,
628 downgrade);
629 }
630
631 // Return an array specifying the optimization status of the given file.
632 // The array specification is [compiler_filter, compiler_reason].
DexFile_getDexFileOptimizationStatus(JNIEnv * env,jclass,jstring javaFilename,jstring javaInstructionSet)633 static jobjectArray DexFile_getDexFileOptimizationStatus(JNIEnv* env,
634 jclass,
635 jstring javaFilename,
636 jstring javaInstructionSet) {
637 ScopedUtfChars filename(env, javaFilename);
638 if (env->ExceptionCheck()) {
639 return nullptr;
640 }
641
642 ScopedUtfChars instruction_set(env, javaInstructionSet);
643 if (env->ExceptionCheck()) {
644 return nullptr;
645 }
646
647 const InstructionSet target_instruction_set = GetInstructionSetFromString(
648 instruction_set.c_str());
649 if (target_instruction_set == InstructionSet::kNone) {
650 ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException"));
651 std::string message(StringPrintf("Instruction set %s is invalid.", instruction_set.c_str()));
652 env->ThrowNew(iae.get(), message.c_str());
653 return nullptr;
654 }
655
656 std::string compilation_filter;
657 std::string compilation_reason;
658 OatFileAssistant::GetOptimizationStatus(
659 filename.c_str(), target_instruction_set, &compilation_filter, &compilation_reason);
660
661 ScopedObjectAccess soa(Thread::ForEnv(env));
662 return soa.AddLocalReference<jobjectArray>(CreateStringArray(soa.Self(), {
663 compilation_filter.c_str(),
664 compilation_reason.c_str()
665 }));
666 }
667
DexFile_getDexOptNeeded(JNIEnv * env,jclass,jstring javaFilename,jstring javaInstructionSet,jstring javaTargetCompilerFilter,jstring javaClassLoaderContext,jboolean newProfile,jboolean downgrade)668 static jint DexFile_getDexOptNeeded(JNIEnv* env,
669 jclass,
670 jstring javaFilename,
671 jstring javaInstructionSet,
672 jstring javaTargetCompilerFilter,
673 jstring javaClassLoaderContext,
674 jboolean newProfile,
675 jboolean downgrade) {
676 ScopedUtfChars filename(env, javaFilename);
677 if (env->ExceptionCheck()) {
678 return -1;
679 }
680
681 ScopedUtfChars instruction_set(env, javaInstructionSet);
682 if (env->ExceptionCheck()) {
683 return -1;
684 }
685
686 ScopedUtfChars target_compiler_filter(env, javaTargetCompilerFilter);
687 if (env->ExceptionCheck()) {
688 return -1;
689 }
690
691 NullableScopedUtfChars class_loader_context(env, javaClassLoaderContext);
692 if (env->ExceptionCheck()) {
693 return -1;
694 }
695
696 return GetDexOptNeeded(env,
697 filename.c_str(),
698 instruction_set.c_str(),
699 target_compiler_filter.c_str(),
700 class_loader_context.c_str(),
701 newProfile == JNI_TRUE,
702 downgrade == JNI_TRUE);
703 }
704
705 // public API
DexFile_isDexOptNeeded(JNIEnv * env,jclass,jstring javaFilename)706 static jboolean DexFile_isDexOptNeeded(JNIEnv* env, jclass, jstring javaFilename) {
707 ScopedUtfChars filename_utf(env, javaFilename);
708 if (env->ExceptionCheck()) {
709 return JNI_FALSE;
710 }
711
712 const char* filename = filename_utf.c_str();
713 if ((filename == nullptr) || !OS::FileExists(filename)) {
714 LOG(ERROR) << "DexFile_isDexOptNeeded file '" << filename << "' does not exist";
715 ScopedLocalRef<jclass> fnfe(env, env->FindClass("java/io/FileNotFoundException"));
716 const char* message = (filename == nullptr) ? "<empty file name>" : filename;
717 env->ThrowNew(fnfe.get(), message);
718 return JNI_FALSE;
719 }
720
721 OatFileAssistant oat_file_assistant(filename,
722 kRuntimeISA,
723 /* context= */ nullptr,
724 /* load_executable= */ false);
725 return oat_file_assistant.IsUpToDate() ? JNI_FALSE : JNI_TRUE;
726 }
727
DexFile_isValidCompilerFilter(JNIEnv * env,jclass javaDexFileClass,jstring javaCompilerFilter)728 static jboolean DexFile_isValidCompilerFilter(JNIEnv* env,
729 [[maybe_unused]] jclass javaDexFileClass,
730 jstring javaCompilerFilter) {
731 ScopedUtfChars compiler_filter(env, javaCompilerFilter);
732 if (env->ExceptionCheck()) {
733 return -1;
734 }
735
736 CompilerFilter::Filter filter;
737 return CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)
738 ? JNI_TRUE : JNI_FALSE;
739 }
740
DexFile_isProfileGuidedCompilerFilter(JNIEnv * env,jclass javaDexFileClass,jstring javaCompilerFilter)741 static jboolean DexFile_isProfileGuidedCompilerFilter(JNIEnv* env,
742 [[maybe_unused]] jclass javaDexFileClass,
743 jstring javaCompilerFilter) {
744 ScopedUtfChars compiler_filter(env, javaCompilerFilter);
745 if (env->ExceptionCheck()) {
746 return -1;
747 }
748
749 CompilerFilter::Filter filter;
750 if (!CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)) {
751 return JNI_FALSE;
752 }
753 return CompilerFilter::DependsOnProfile(filter) ? JNI_TRUE : JNI_FALSE;
754 }
755
DexFile_isVerifiedCompilerFilter(JNIEnv * env,jclass javaDexFileClass,jstring javaCompilerFilter)756 static jboolean DexFile_isVerifiedCompilerFilter(JNIEnv* env,
757 [[maybe_unused]] jclass javaDexFileClass,
758 jstring javaCompilerFilter) {
759 ScopedUtfChars compiler_filter(env, javaCompilerFilter);
760 if (env->ExceptionCheck()) {
761 return -1;
762 }
763
764 CompilerFilter::Filter filter;
765 if (!CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)) {
766 return JNI_FALSE;
767 }
768 return CompilerFilter::IsVerificationEnabled(filter) ? JNI_TRUE : JNI_FALSE;
769 }
770
DexFile_isOptimizedCompilerFilter(JNIEnv * env,jclass javaDexFileClass,jstring javaCompilerFilter)771 static jboolean DexFile_isOptimizedCompilerFilter(JNIEnv* env,
772 [[maybe_unused]] jclass javaDexFileClass,
773 jstring javaCompilerFilter) {
774 ScopedUtfChars compiler_filter(env, javaCompilerFilter);
775 if (env->ExceptionCheck()) {
776 return -1;
777 }
778
779 CompilerFilter::Filter filter;
780 if (!CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)) {
781 return JNI_FALSE;
782 }
783 return CompilerFilter::IsAotCompilationEnabled(filter) ? JNI_TRUE : JNI_FALSE;
784 }
785
DexFile_isReadOnlyJavaDclEnforced(JNIEnv * env,jclass javaDexFileClass)786 static jboolean DexFile_isReadOnlyJavaDclEnforced(JNIEnv* env,
787 [[maybe_unused]] jclass javaDexFileClass) {
788 return (isReadOnlyJavaDclChecked() && isReadOnlyJavaDclEnforced(env)) ? JNI_TRUE : JNI_FALSE;
789 }
790
DexFile_getNonProfileGuidedCompilerFilter(JNIEnv * env,jclass javaDexFileClass,jstring javaCompilerFilter)791 static jstring DexFile_getNonProfileGuidedCompilerFilter(JNIEnv* env,
792 [[maybe_unused]] jclass javaDexFileClass,
793 jstring javaCompilerFilter) {
794 ScopedUtfChars compiler_filter(env, javaCompilerFilter);
795 if (env->ExceptionCheck()) {
796 return nullptr;
797 }
798
799 CompilerFilter::Filter filter;
800 if (!CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)) {
801 return javaCompilerFilter;
802 }
803
804 CompilerFilter::Filter new_filter = CompilerFilter::GetNonProfileDependentFilterFrom(filter);
805
806 // Filter stayed the same, return input.
807 if (filter == new_filter) {
808 return javaCompilerFilter;
809 }
810
811 // Create a new string object and return.
812 std::string new_filter_str = CompilerFilter::NameOfFilter(new_filter);
813 return env->NewStringUTF(new_filter_str.c_str());
814 }
815
DexFile_getSafeModeCompilerFilter(JNIEnv * env,jclass javaDexFileClass,jstring javaCompilerFilter)816 static jstring DexFile_getSafeModeCompilerFilter(JNIEnv* env,
817 [[maybe_unused]] jclass javaDexFileClass,
818 jstring javaCompilerFilter) {
819 ScopedUtfChars compiler_filter(env, javaCompilerFilter);
820 if (env->ExceptionCheck()) {
821 return nullptr;
822 }
823
824 CompilerFilter::Filter filter;
825 if (!CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)) {
826 return javaCompilerFilter;
827 }
828
829 CompilerFilter::Filter new_filter = CompilerFilter::GetSafeModeFilterFrom(filter);
830
831 // Filter stayed the same, return input.
832 if (filter == new_filter) {
833 return javaCompilerFilter;
834 }
835
836 // Create a new string object and return.
837 std::string new_filter_str = CompilerFilter::NameOfFilter(new_filter);
838 return env->NewStringUTF(new_filter_str.c_str());
839 }
840
DexFile_isBackedByOatFile(JNIEnv * env,jclass,jobject cookie)841 static jboolean DexFile_isBackedByOatFile(JNIEnv* env, jclass, jobject cookie) {
842 const OatFile* oat_file = nullptr;
843 std::vector<const DexFile*> dex_files;
844 if (!ConvertJavaArrayToDexFiles(env, cookie, /*out */ dex_files, /* out */ oat_file)) {
845 DCHECK(env->ExceptionCheck());
846 return false;
847 }
848 return oat_file != nullptr;
849 }
850
DexFile_getDexFileOutputPaths(JNIEnv * env,jclass,jstring javaFilename,jstring javaInstructionSet)851 static jobjectArray DexFile_getDexFileOutputPaths(JNIEnv* env,
852 jclass,
853 jstring javaFilename,
854 jstring javaInstructionSet) {
855 ScopedUtfChars filename(env, javaFilename);
856 if (env->ExceptionCheck()) {
857 return nullptr;
858 }
859
860 ScopedUtfChars instruction_set(env, javaInstructionSet);
861 if (env->ExceptionCheck()) {
862 return nullptr;
863 }
864
865 const InstructionSet target_instruction_set = GetInstructionSetFromString(
866 instruction_set.c_str());
867 if (target_instruction_set == InstructionSet::kNone) {
868 ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException"));
869 std::string message(StringPrintf("Instruction set %s is invalid.", instruction_set.c_str()));
870 env->ThrowNew(iae.get(), message.c_str());
871 return nullptr;
872 }
873
874 std::string oat_filename;
875 std::string vdex_filename;
876 // Check if the file is in the boot classpath by looking at image spaces which
877 // have oat files.
878 bool is_vdex_only = false;
879 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
880 const OatFile* oat_file = space->GetOatFile();
881 if (oat_file != nullptr) {
882 const std::vector<const OatDexFile*>& oat_dex_files = oat_file->GetOatDexFiles();
883 for (const OatDexFile* oat_dex_file : oat_dex_files) {
884 if (DexFileLoader::GetBaseLocation(oat_dex_file->GetDexFileLocation()) ==
885 filename.c_str()) {
886 oat_filename = oat_file->GetLocation();
887 is_vdex_only = oat_file->IsBackedByVdexOnly();
888 break;
889 }
890 }
891 if (!oat_filename.empty()) {
892 break;
893 }
894 }
895 }
896
897 // If we did not find a boot classpath oat file, lookup the oat file for an app.
898 if (oat_filename.empty()) {
899 OatFileAssistant oat_file_assistant(filename.c_str(),
900 target_instruction_set,
901 /* context= */ nullptr,
902 /* load_executable= */ false);
903
904 std::unique_ptr<OatFile> best_oat_file = oat_file_assistant.GetBestOatFile();
905 if (best_oat_file == nullptr) {
906 return nullptr;
907 }
908
909 oat_filename = best_oat_file->GetLocation();
910 is_vdex_only = best_oat_file->IsBackedByVdexOnly();
911 }
912
913 const char* filenames[] = { oat_filename.c_str(), nullptr };
914 ArrayRef<const char* const> used_filenames(filenames, 1u);
915 if (!is_vdex_only) {
916 vdex_filename = GetVdexFilename(oat_filename);
917 filenames[1] = vdex_filename.c_str();
918 used_filenames = ArrayRef<const char* const>(filenames, 2u);
919 }
920 ScopedObjectAccess soa(Thread::ForEnv(env));
921 return soa.AddLocalReference<jobjectArray>(CreateStringArray(soa.Self(), used_filenames));
922 }
923
DexFile_getStaticSizeOfDexFile(JNIEnv * env,jclass,jobject cookie)924 static jlong DexFile_getStaticSizeOfDexFile(JNIEnv* env, jclass, jobject cookie) {
925 const OatFile* oat_file = nullptr;
926 std::vector<const DexFile*> dex_files;
927 if (!ConvertJavaArrayToDexFiles(env, cookie, /*out */ dex_files, /* out */ oat_file)) {
928 DCHECK(env->ExceptionCheck());
929 return 0;
930 }
931
932 uint64_t file_size = 0;
933 for (auto& dex_file : dex_files) {
934 if (dex_file) {
935 file_size += dex_file->GetHeader().file_size_;
936 }
937 }
938 return static_cast<jlong>(file_size);
939 }
940
DexFile_setTrusted(JNIEnv * env,jclass,jobject j_cookie)941 static void DexFile_setTrusted(JNIEnv* env, jclass, jobject j_cookie) {
942 Runtime* runtime = Runtime::Current();
943 ScopedObjectAccess soa(env);
944
945 // Currently only allow this for debuggable apps.
946 if (!runtime->IsJavaDebuggableAtInit()) {
947 ThrowSecurityException("Can't exempt class, process is not debuggable.");
948 return;
949 }
950
951 std::vector<const DexFile*> dex_files;
952 const OatFile* oat_file;
953 if (!ConvertJavaArrayToDexFiles(env, j_cookie, dex_files, oat_file)) {
954 Thread::Current()->AssertPendingException();
955 return;
956 }
957
958 // Assign core platform domain as the dex files are allowed to access all the other domains.
959 for (const DexFile* dex_file : dex_files) {
960 const_cast<DexFile*>(dex_file)->SetHiddenapiDomain(hiddenapi::Domain::kCorePlatform);
961 }
962 }
963
964 static JNINativeMethod gMethods[] = {
965 NATIVE_METHOD(DexFile, closeDexFile, "(Ljava/lang/Object;)Z"),
966 NATIVE_METHOD(DexFile,
967 defineClassNative,
968 "(Ljava/lang/String;"
969 "Ljava/lang/ClassLoader;"
970 "Ljava/lang/Object;"
971 "Ldalvik/system/DexFile;"
972 ")Ljava/lang/Class;"),
973 NATIVE_METHOD(DexFile, getClassNameList, "(Ljava/lang/Object;)[Ljava/lang/String;"),
974 NATIVE_METHOD(DexFile, isDexOptNeeded, "(Ljava/lang/String;)Z"),
975 NATIVE_METHOD(DexFile,
976 getDexOptNeeded,
977 "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZ)I"),
978 NATIVE_METHOD(DexFile,
979 openDexFileNative,
980 "(Ljava/lang/String;"
981 "Ljava/lang/String;"
982 "I"
983 "Ljava/lang/ClassLoader;"
984 "[Ldalvik/system/DexPathList$Element;"
985 ")Ljava/lang/Object;"),
986 NATIVE_METHOD(DexFile,
987 openInMemoryDexFilesNative,
988 "([Ljava/nio/ByteBuffer;"
989 "[[B"
990 "[I"
991 "[I"
992 "Ljava/lang/ClassLoader;"
993 "[Ldalvik/system/DexPathList$Element;"
994 ")Ljava/lang/Object;"),
995 NATIVE_METHOD(DexFile,
996 verifyInBackgroundNative,
997 "(Ljava/lang/Object;"
998 "Ljava/lang/ClassLoader;"
999 ")V"),
1000 NATIVE_METHOD(DexFile, isValidCompilerFilter, "(Ljava/lang/String;)Z"),
1001 NATIVE_METHOD(DexFile, isProfileGuidedCompilerFilter, "(Ljava/lang/String;)Z"),
1002 NATIVE_METHOD(DexFile, isVerifiedCompilerFilter, "(Ljava/lang/String;)Z"),
1003 NATIVE_METHOD(DexFile, isOptimizedCompilerFilter, "(Ljava/lang/String;)Z"),
1004 NATIVE_METHOD(DexFile, isReadOnlyJavaDclEnforced, "()Z"),
1005 NATIVE_METHOD(
1006 DexFile, getNonProfileGuidedCompilerFilter, "(Ljava/lang/String;)Ljava/lang/String;"),
1007 NATIVE_METHOD(DexFile, getSafeModeCompilerFilter, "(Ljava/lang/String;)Ljava/lang/String;"),
1008 NATIVE_METHOD(DexFile, isBackedByOatFile, "(Ljava/lang/Object;)Z"),
1009 NATIVE_METHOD(DexFile,
1010 getDexFileOutputPaths,
1011 "(Ljava/lang/String;Ljava/lang/String;)[Ljava/lang/String;"),
1012 NATIVE_METHOD(DexFile, getStaticSizeOfDexFile, "(Ljava/lang/Object;)J"),
1013 NATIVE_METHOD(DexFile,
1014 getDexFileOptimizationStatus,
1015 "(Ljava/lang/String;Ljava/lang/String;)[Ljava/lang/String;"),
1016 NATIVE_METHOD(DexFile, setTrusted, "(Ljava/lang/Object;)V")};
1017
register_dalvik_system_DexFile(JNIEnv * env)1018 void register_dalvik_system_DexFile(JNIEnv* env) {
1019 REGISTER_NATIVE_METHODS("dalvik/system/DexFile");
1020 }
1021
1022 } // namespace art
1023