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.c_str()));
491 const size_t hash(ComputeModifiedUtf8Hash(descriptor.c_str()));
492 for (auto& dex_file : dex_files) {
493 const dex::ClassDef* dex_class_def =
494 OatDexFile::FindClassDef(*dex_file, descriptor.c_str(), hash);
495 if (dex_class_def != nullptr) {
496 ScopedObjectAccess soa(env);
497 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
498 StackHandleScope<1> hs(soa.Self());
499 Handle<mirror::ClassLoader> class_loader(
500 hs.NewHandle(soa.Decode<mirror::ClassLoader>(javaLoader)));
501 ObjPtr<mirror::DexCache> dex_cache =
502 class_linker->RegisterDexFile(*dex_file, class_loader.Get());
503 if (dex_cache == nullptr) {
504 // OOME or InternalError (dexFile already registered with a different class loader).
505 soa.Self()->AssertPendingException();
506 return nullptr;
507 }
508 ObjPtr<mirror::Class> result = class_linker->DefineClass(soa.Self(),
509 descriptor.c_str(),
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
DexFile_getDexFileStatus(JNIEnv * env,jclass,jstring javaFilename,jstring javaInstructionSet)631 static jstring DexFile_getDexFileStatus(JNIEnv* env,
632 jclass,
633 jstring javaFilename,
634 jstring javaInstructionSet) {
635 ScopedUtfChars filename(env, javaFilename);
636 if (env->ExceptionCheck()) {
637 return nullptr;
638 }
639
640 ScopedUtfChars instruction_set(env, javaInstructionSet);
641 if (env->ExceptionCheck()) {
642 return nullptr;
643 }
644
645 const InstructionSet target_instruction_set = GetInstructionSetFromString(
646 instruction_set.c_str());
647 if (target_instruction_set == InstructionSet::kNone) {
648 ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException"));
649 std::string message(StringPrintf("Instruction set %s is invalid.", instruction_set.c_str()));
650 env->ThrowNew(iae.get(), message.c_str());
651 return nullptr;
652 }
653
654 // The API doesn't support passing a class loader context, so skip the class loader context check
655 // and assume that it's OK.
656 OatFileAssistant oat_file_assistant(filename.c_str(),
657 target_instruction_set,
658 /* context= */ nullptr,
659 /* load_executable= */ false);
660 return env->NewStringUTF(oat_file_assistant.GetStatusDump().c_str());
661 }
662
663 // Return an array specifying the optimization status of the given file.
664 // The array specification is [compiler_filter, compiler_reason].
DexFile_getDexFileOptimizationStatus(JNIEnv * env,jclass,jstring javaFilename,jstring javaInstructionSet)665 static jobjectArray DexFile_getDexFileOptimizationStatus(JNIEnv* env,
666 jclass,
667 jstring javaFilename,
668 jstring javaInstructionSet) {
669 ScopedUtfChars filename(env, javaFilename);
670 if (env->ExceptionCheck()) {
671 return nullptr;
672 }
673
674 ScopedUtfChars instruction_set(env, javaInstructionSet);
675 if (env->ExceptionCheck()) {
676 return nullptr;
677 }
678
679 const InstructionSet target_instruction_set = GetInstructionSetFromString(
680 instruction_set.c_str());
681 if (target_instruction_set == InstructionSet::kNone) {
682 ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException"));
683 std::string message(StringPrintf("Instruction set %s is invalid.", instruction_set.c_str()));
684 env->ThrowNew(iae.get(), message.c_str());
685 return nullptr;
686 }
687
688 std::string compilation_filter;
689 std::string compilation_reason;
690 OatFileAssistant::GetOptimizationStatus(
691 filename.c_str(), target_instruction_set, &compilation_filter, &compilation_reason);
692
693 ScopedObjectAccess soa(Thread::ForEnv(env));
694 return soa.AddLocalReference<jobjectArray>(CreateStringArray(soa.Self(), {
695 compilation_filter.c_str(),
696 compilation_reason.c_str()
697 }));
698 }
699
DexFile_getDexOptNeeded(JNIEnv * env,jclass,jstring javaFilename,jstring javaInstructionSet,jstring javaTargetCompilerFilter,jstring javaClassLoaderContext,jboolean newProfile,jboolean downgrade)700 static jint DexFile_getDexOptNeeded(JNIEnv* env,
701 jclass,
702 jstring javaFilename,
703 jstring javaInstructionSet,
704 jstring javaTargetCompilerFilter,
705 jstring javaClassLoaderContext,
706 jboolean newProfile,
707 jboolean downgrade) {
708 ScopedUtfChars filename(env, javaFilename);
709 if (env->ExceptionCheck()) {
710 return -1;
711 }
712
713 ScopedUtfChars instruction_set(env, javaInstructionSet);
714 if (env->ExceptionCheck()) {
715 return -1;
716 }
717
718 ScopedUtfChars target_compiler_filter(env, javaTargetCompilerFilter);
719 if (env->ExceptionCheck()) {
720 return -1;
721 }
722
723 NullableScopedUtfChars class_loader_context(env, javaClassLoaderContext);
724 if (env->ExceptionCheck()) {
725 return -1;
726 }
727
728 return GetDexOptNeeded(env,
729 filename.c_str(),
730 instruction_set.c_str(),
731 target_compiler_filter.c_str(),
732 class_loader_context.c_str(),
733 newProfile == JNI_TRUE,
734 downgrade == JNI_TRUE);
735 }
736
737 // public API
DexFile_isDexOptNeeded(JNIEnv * env,jclass,jstring javaFilename)738 static jboolean DexFile_isDexOptNeeded(JNIEnv* env, jclass, jstring javaFilename) {
739 ScopedUtfChars filename_utf(env, javaFilename);
740 if (env->ExceptionCheck()) {
741 return JNI_FALSE;
742 }
743
744 const char* filename = filename_utf.c_str();
745 if ((filename == nullptr) || !OS::FileExists(filename)) {
746 LOG(ERROR) << "DexFile_isDexOptNeeded file '" << filename << "' does not exist";
747 ScopedLocalRef<jclass> fnfe(env, env->FindClass("java/io/FileNotFoundException"));
748 const char* message = (filename == nullptr) ? "<empty file name>" : filename;
749 env->ThrowNew(fnfe.get(), message);
750 return JNI_FALSE;
751 }
752
753 OatFileAssistant oat_file_assistant(filename,
754 kRuntimeISA,
755 /* context= */ nullptr,
756 /* load_executable= */ false);
757 return oat_file_assistant.IsUpToDate() ? JNI_FALSE : JNI_TRUE;
758 }
759
DexFile_isValidCompilerFilter(JNIEnv * env,jclass javaDexFileClass,jstring javaCompilerFilter)760 static jboolean DexFile_isValidCompilerFilter(JNIEnv* env,
761 [[maybe_unused]] jclass javaDexFileClass,
762 jstring javaCompilerFilter) {
763 ScopedUtfChars compiler_filter(env, javaCompilerFilter);
764 if (env->ExceptionCheck()) {
765 return -1;
766 }
767
768 CompilerFilter::Filter filter;
769 return CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)
770 ? JNI_TRUE : JNI_FALSE;
771 }
772
DexFile_isProfileGuidedCompilerFilter(JNIEnv * env,jclass javaDexFileClass,jstring javaCompilerFilter)773 static jboolean DexFile_isProfileGuidedCompilerFilter(JNIEnv* env,
774 [[maybe_unused]] jclass javaDexFileClass,
775 jstring javaCompilerFilter) {
776 ScopedUtfChars compiler_filter(env, javaCompilerFilter);
777 if (env->ExceptionCheck()) {
778 return -1;
779 }
780
781 CompilerFilter::Filter filter;
782 if (!CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)) {
783 return JNI_FALSE;
784 }
785 return CompilerFilter::DependsOnProfile(filter) ? JNI_TRUE : JNI_FALSE;
786 }
787
DexFile_isVerifiedCompilerFilter(JNIEnv * env,jclass javaDexFileClass,jstring javaCompilerFilter)788 static jboolean DexFile_isVerifiedCompilerFilter(JNIEnv* env,
789 [[maybe_unused]] jclass javaDexFileClass,
790 jstring javaCompilerFilter) {
791 ScopedUtfChars compiler_filter(env, javaCompilerFilter);
792 if (env->ExceptionCheck()) {
793 return -1;
794 }
795
796 CompilerFilter::Filter filter;
797 if (!CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)) {
798 return JNI_FALSE;
799 }
800 return CompilerFilter::IsVerificationEnabled(filter) ? JNI_TRUE : JNI_FALSE;
801 }
802
DexFile_isOptimizedCompilerFilter(JNIEnv * env,jclass javaDexFileClass,jstring javaCompilerFilter)803 static jboolean DexFile_isOptimizedCompilerFilter(JNIEnv* env,
804 [[maybe_unused]] jclass javaDexFileClass,
805 jstring javaCompilerFilter) {
806 ScopedUtfChars compiler_filter(env, javaCompilerFilter);
807 if (env->ExceptionCheck()) {
808 return -1;
809 }
810
811 CompilerFilter::Filter filter;
812 if (!CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)) {
813 return JNI_FALSE;
814 }
815 return CompilerFilter::IsAotCompilationEnabled(filter) ? JNI_TRUE : JNI_FALSE;
816 }
817
DexFile_isReadOnlyJavaDclEnforced(JNIEnv * env,jclass javaDexFileClass)818 static jboolean DexFile_isReadOnlyJavaDclEnforced(JNIEnv* env,
819 [[maybe_unused]] jclass javaDexFileClass) {
820 return (isReadOnlyJavaDclChecked() && isReadOnlyJavaDclEnforced(env)) ? JNI_TRUE : JNI_FALSE;
821 }
822
DexFile_getNonProfileGuidedCompilerFilter(JNIEnv * env,jclass javaDexFileClass,jstring javaCompilerFilter)823 static jstring DexFile_getNonProfileGuidedCompilerFilter(JNIEnv* env,
824 [[maybe_unused]] jclass javaDexFileClass,
825 jstring javaCompilerFilter) {
826 ScopedUtfChars compiler_filter(env, javaCompilerFilter);
827 if (env->ExceptionCheck()) {
828 return nullptr;
829 }
830
831 CompilerFilter::Filter filter;
832 if (!CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)) {
833 return javaCompilerFilter;
834 }
835
836 CompilerFilter::Filter new_filter = CompilerFilter::GetNonProfileDependentFilterFrom(filter);
837
838 // Filter stayed the same, return input.
839 if (filter == new_filter) {
840 return javaCompilerFilter;
841 }
842
843 // Create a new string object and return.
844 std::string new_filter_str = CompilerFilter::NameOfFilter(new_filter);
845 return env->NewStringUTF(new_filter_str.c_str());
846 }
847
DexFile_getSafeModeCompilerFilter(JNIEnv * env,jclass javaDexFileClass,jstring javaCompilerFilter)848 static jstring DexFile_getSafeModeCompilerFilter(JNIEnv* env,
849 [[maybe_unused]] jclass javaDexFileClass,
850 jstring javaCompilerFilter) {
851 ScopedUtfChars compiler_filter(env, javaCompilerFilter);
852 if (env->ExceptionCheck()) {
853 return nullptr;
854 }
855
856 CompilerFilter::Filter filter;
857 if (!CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)) {
858 return javaCompilerFilter;
859 }
860
861 CompilerFilter::Filter new_filter = CompilerFilter::GetSafeModeFilterFrom(filter);
862
863 // Filter stayed the same, return input.
864 if (filter == new_filter) {
865 return javaCompilerFilter;
866 }
867
868 // Create a new string object and return.
869 std::string new_filter_str = CompilerFilter::NameOfFilter(new_filter);
870 return env->NewStringUTF(new_filter_str.c_str());
871 }
872
DexFile_isBackedByOatFile(JNIEnv * env,jclass,jobject cookie)873 static jboolean DexFile_isBackedByOatFile(JNIEnv* env, jclass, jobject cookie) {
874 const OatFile* oat_file = nullptr;
875 std::vector<const DexFile*> dex_files;
876 if (!ConvertJavaArrayToDexFiles(env, cookie, /*out */ dex_files, /* out */ oat_file)) {
877 DCHECK(env->ExceptionCheck());
878 return false;
879 }
880 return oat_file != nullptr;
881 }
882
DexFile_getDexFileOutputPaths(JNIEnv * env,jclass,jstring javaFilename,jstring javaInstructionSet)883 static jobjectArray DexFile_getDexFileOutputPaths(JNIEnv* env,
884 jclass,
885 jstring javaFilename,
886 jstring javaInstructionSet) {
887 ScopedUtfChars filename(env, javaFilename);
888 if (env->ExceptionCheck()) {
889 return nullptr;
890 }
891
892 ScopedUtfChars instruction_set(env, javaInstructionSet);
893 if (env->ExceptionCheck()) {
894 return nullptr;
895 }
896
897 const InstructionSet target_instruction_set = GetInstructionSetFromString(
898 instruction_set.c_str());
899 if (target_instruction_set == InstructionSet::kNone) {
900 ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException"));
901 std::string message(StringPrintf("Instruction set %s is invalid.", instruction_set.c_str()));
902 env->ThrowNew(iae.get(), message.c_str());
903 return nullptr;
904 }
905
906 std::string oat_filename;
907 std::string vdex_filename;
908 // Check if the file is in the boot classpath by looking at image spaces which
909 // have oat files.
910 bool is_vdex_only = false;
911 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
912 const OatFile* oat_file = space->GetOatFile();
913 if (oat_file != nullptr) {
914 const std::vector<const OatDexFile*>& oat_dex_files = oat_file->GetOatDexFiles();
915 for (const OatDexFile* oat_dex_file : oat_dex_files) {
916 if (DexFileLoader::GetBaseLocation(oat_dex_file->GetDexFileLocation()) ==
917 filename.c_str()) {
918 oat_filename = GetSystemImageFilename(oat_file->GetLocation().c_str(),
919 target_instruction_set);
920 is_vdex_only = oat_file->IsBackedByVdexOnly();
921 break;
922 }
923 }
924 if (!oat_filename.empty()) {
925 break;
926 }
927 }
928 }
929
930 // If we did not find a boot classpath oat file, lookup the oat file for an app.
931 if (oat_filename.empty()) {
932 OatFileAssistant oat_file_assistant(filename.c_str(),
933 target_instruction_set,
934 /* context= */ nullptr,
935 /* load_executable= */ false);
936
937 std::unique_ptr<OatFile> best_oat_file = oat_file_assistant.GetBestOatFile();
938 if (best_oat_file == nullptr) {
939 return nullptr;
940 }
941
942 oat_filename = best_oat_file->GetLocation();
943 is_vdex_only = best_oat_file->IsBackedByVdexOnly();
944 }
945
946 const char* filenames[] = { oat_filename.c_str(), nullptr };
947 ArrayRef<const char* const> used_filenames(filenames, 1u);
948 if (!is_vdex_only) {
949 vdex_filename = GetVdexFilename(oat_filename);
950 filenames[1] = vdex_filename.c_str();
951 used_filenames = ArrayRef<const char* const>(filenames, 2u);
952 }
953 ScopedObjectAccess soa(Thread::ForEnv(env));
954 return soa.AddLocalReference<jobjectArray>(CreateStringArray(soa.Self(), used_filenames));
955 }
956
DexFile_getStaticSizeOfDexFile(JNIEnv * env,jclass,jobject cookie)957 static jlong DexFile_getStaticSizeOfDexFile(JNIEnv* env, jclass, jobject cookie) {
958 const OatFile* oat_file = nullptr;
959 std::vector<const DexFile*> dex_files;
960 if (!ConvertJavaArrayToDexFiles(env, cookie, /*out */ dex_files, /* out */ oat_file)) {
961 DCHECK(env->ExceptionCheck());
962 return 0;
963 }
964
965 uint64_t file_size = 0;
966 for (auto& dex_file : dex_files) {
967 if (dex_file) {
968 file_size += dex_file->GetHeader().file_size_;
969 }
970 }
971 return static_cast<jlong>(file_size);
972 }
973
DexFile_setTrusted(JNIEnv * env,jclass,jobject j_cookie)974 static void DexFile_setTrusted(JNIEnv* env, jclass, jobject j_cookie) {
975 Runtime* runtime = Runtime::Current();
976 ScopedObjectAccess soa(env);
977
978 // Currently only allow this for debuggable apps.
979 if (!runtime->IsJavaDebuggableAtInit()) {
980 ThrowSecurityException("Can't exempt class, process is not debuggable.");
981 return;
982 }
983
984 std::vector<const DexFile*> dex_files;
985 const OatFile* oat_file;
986 if (!ConvertJavaArrayToDexFiles(env, j_cookie, dex_files, oat_file)) {
987 Thread::Current()->AssertPendingException();
988 return;
989 }
990
991 // Assign core platform domain as the dex files are allowed to access all the other domains.
992 for (const DexFile* dex_file : dex_files) {
993 const_cast<DexFile*>(dex_file)->SetHiddenapiDomain(hiddenapi::Domain::kCorePlatform);
994 }
995 }
996
997 static JNINativeMethod gMethods[] = {
998 NATIVE_METHOD(DexFile, closeDexFile, "(Ljava/lang/Object;)Z"),
999 NATIVE_METHOD(DexFile,
1000 defineClassNative,
1001 "(Ljava/lang/String;"
1002 "Ljava/lang/ClassLoader;"
1003 "Ljava/lang/Object;"
1004 "Ldalvik/system/DexFile;"
1005 ")Ljava/lang/Class;"),
1006 NATIVE_METHOD(DexFile, getClassNameList, "(Ljava/lang/Object;)[Ljava/lang/String;"),
1007 NATIVE_METHOD(DexFile, isDexOptNeeded, "(Ljava/lang/String;)Z"),
1008 NATIVE_METHOD(DexFile,
1009 getDexOptNeeded,
1010 "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZ)I"),
1011 NATIVE_METHOD(DexFile,
1012 openDexFileNative,
1013 "(Ljava/lang/String;"
1014 "Ljava/lang/String;"
1015 "I"
1016 "Ljava/lang/ClassLoader;"
1017 "[Ldalvik/system/DexPathList$Element;"
1018 ")Ljava/lang/Object;"),
1019 NATIVE_METHOD(DexFile,
1020 openInMemoryDexFilesNative,
1021 "([Ljava/nio/ByteBuffer;"
1022 "[[B"
1023 "[I"
1024 "[I"
1025 "Ljava/lang/ClassLoader;"
1026 "[Ldalvik/system/DexPathList$Element;"
1027 ")Ljava/lang/Object;"),
1028 NATIVE_METHOD(DexFile,
1029 verifyInBackgroundNative,
1030 "(Ljava/lang/Object;"
1031 "Ljava/lang/ClassLoader;"
1032 ")V"),
1033 NATIVE_METHOD(DexFile, isValidCompilerFilter, "(Ljava/lang/String;)Z"),
1034 NATIVE_METHOD(DexFile, isProfileGuidedCompilerFilter, "(Ljava/lang/String;)Z"),
1035 NATIVE_METHOD(DexFile, isVerifiedCompilerFilter, "(Ljava/lang/String;)Z"),
1036 NATIVE_METHOD(DexFile, isOptimizedCompilerFilter, "(Ljava/lang/String;)Z"),
1037 NATIVE_METHOD(DexFile, isReadOnlyJavaDclEnforced, "()Z"),
1038 NATIVE_METHOD(
1039 DexFile, getNonProfileGuidedCompilerFilter, "(Ljava/lang/String;)Ljava/lang/String;"),
1040 NATIVE_METHOD(DexFile, getSafeModeCompilerFilter, "(Ljava/lang/String;)Ljava/lang/String;"),
1041 NATIVE_METHOD(DexFile, isBackedByOatFile, "(Ljava/lang/Object;)Z"),
1042 NATIVE_METHOD(
1043 DexFile, getDexFileStatus, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"),
1044 NATIVE_METHOD(DexFile,
1045 getDexFileOutputPaths,
1046 "(Ljava/lang/String;Ljava/lang/String;)[Ljava/lang/String;"),
1047 NATIVE_METHOD(DexFile, getStaticSizeOfDexFile, "(Ljava/lang/Object;)J"),
1048 NATIVE_METHOD(DexFile,
1049 getDexFileOptimizationStatus,
1050 "(Ljava/lang/String;Ljava/lang/String;)[Ljava/lang/String;"),
1051 NATIVE_METHOD(DexFile, setTrusted, "(Ljava/lang/Object;)V")};
1052
register_dalvik_system_DexFile(JNIEnv * env)1053 void register_dalvik_system_DexFile(JNIEnv* env) {
1054 REGISTER_NATIVE_METHODS("dalvik/system/DexFile");
1055 }
1056
1057 } // namespace art
1058