• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/stringprintf.h"
22 
23 #include "base/logging.h"
24 #include "base/stl_util.h"
25 #include "class_linker.h"
26 #include "common_throws.h"
27 #include "compiler_filter.h"
28 #include "dex_file-inl.h"
29 #include "jni_internal.h"
30 #include "mirror/class_loader.h"
31 #include "mirror/object-inl.h"
32 #include "mirror/string.h"
33 #include "native_util.h"
34 #include "nativehelper/jni_macros.h"
35 #include "nativehelper/ScopedLocalRef.h"
36 #include "nativehelper/ScopedUtfChars.h"
37 #include "oat_file.h"
38 #include "oat_file_assistant.h"
39 #include "oat_file_manager.h"
40 #include "os.h"
41 #include "runtime.h"
42 #include "scoped_thread_state_change-inl.h"
43 #include "utils.h"
44 #include "well_known_classes.h"
45 #include "zip_archive.h"
46 
47 namespace art {
48 
49 using android::base::StringPrintf;
50 
ConvertJavaArrayToDexFiles(JNIEnv * env,jobject arrayObject,std::vector<const DexFile * > & dex_files,const OatFile * & oat_file)51 static bool ConvertJavaArrayToDexFiles(
52     JNIEnv* env,
53     jobject arrayObject,
54     /*out*/ std::vector<const DexFile*>& dex_files,
55     /*out*/ const OatFile*& oat_file) {
56   jarray array = reinterpret_cast<jarray>(arrayObject);
57 
58   jsize array_size = env->GetArrayLength(array);
59   if (env->ExceptionCheck() == JNI_TRUE) {
60     return false;
61   }
62 
63   // TODO: Optimize. On 32bit we can use an int array.
64   jboolean is_long_data_copied;
65   jlong* long_data = env->GetLongArrayElements(reinterpret_cast<jlongArray>(array),
66                                                &is_long_data_copied);
67   if (env->ExceptionCheck() == JNI_TRUE) {
68     return false;
69   }
70 
71   oat_file = reinterpret_cast<const OatFile*>(static_cast<uintptr_t>(long_data[kOatFileIndex]));
72   dex_files.reserve(array_size - 1);
73   for (jsize i = kDexFileIndexStart; i < array_size; ++i) {
74     dex_files.push_back(reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(long_data[i])));
75   }
76 
77   env->ReleaseLongArrayElements(reinterpret_cast<jlongArray>(array), long_data, JNI_ABORT);
78   return env->ExceptionCheck() != JNI_TRUE;
79 }
80 
ConvertDexFilesToJavaArray(JNIEnv * env,const OatFile * oat_file,std::vector<std::unique_ptr<const DexFile>> & vec)81 static jlongArray ConvertDexFilesToJavaArray(JNIEnv* env,
82                                              const OatFile* oat_file,
83                                              std::vector<std::unique_ptr<const DexFile>>& vec) {
84   // Add one for the oat file.
85   jlongArray long_array = env->NewLongArray(static_cast<jsize>(kDexFileIndexStart + vec.size()));
86   if (env->ExceptionCheck() == JNI_TRUE) {
87     return nullptr;
88   }
89 
90   jboolean is_long_data_copied;
91   jlong* long_data = env->GetLongArrayElements(long_array, &is_long_data_copied);
92   if (env->ExceptionCheck() == JNI_TRUE) {
93     return nullptr;
94   }
95 
96   long_data[kOatFileIndex] = reinterpret_cast<uintptr_t>(oat_file);
97   for (size_t i = 0; i < vec.size(); ++i) {
98     long_data[kDexFileIndexStart + i] = reinterpret_cast<uintptr_t>(vec[i].get());
99   }
100 
101   env->ReleaseLongArrayElements(long_array, long_data, 0);
102   if (env->ExceptionCheck() == JNI_TRUE) {
103     return nullptr;
104   }
105 
106   // Now release all the unique_ptrs.
107   for (auto& dex_file : vec) {
108     dex_file.release();
109   }
110 
111   return long_array;
112 }
113 
114 // A smart pointer that provides read-only access to a Java string's UTF chars.
115 // Unlike libcore's NullableScopedUtfChars, this will *not* throw NullPointerException if
116 // passed a null jstring. The correct idiom is:
117 //
118 //   NullableScopedUtfChars name(env, javaName);
119 //   if (env->ExceptionCheck()) {
120 //       return null;
121 //   }
122 //   // ... use name.c_str()
123 //
124 // TODO: rewrite to get rid of this, or change ScopedUtfChars to offer this option.
125 class NullableScopedUtfChars {
126  public:
NullableScopedUtfChars(JNIEnv * env,jstring s)127   NullableScopedUtfChars(JNIEnv* env, jstring s) : mEnv(env), mString(s) {
128     mUtfChars = (s != nullptr) ? env->GetStringUTFChars(s, nullptr) : nullptr;
129   }
130 
~NullableScopedUtfChars()131   ~NullableScopedUtfChars() {
132     if (mUtfChars) {
133       mEnv->ReleaseStringUTFChars(mString, mUtfChars);
134     }
135   }
136 
c_str() const137   const char* c_str() const {
138     return mUtfChars;
139   }
140 
size() const141   size_t size() const {
142     return strlen(mUtfChars);
143   }
144 
145   // Element access.
operator [](size_t n) const146   const char& operator[](size_t n) const {
147     return mUtfChars[n];
148   }
149 
150  private:
151   JNIEnv* mEnv;
152   jstring mString;
153   const char* mUtfChars;
154 
155   // Disallow copy and assignment.
156   NullableScopedUtfChars(const NullableScopedUtfChars&);
157   void operator=(const NullableScopedUtfChars&);
158 };
159 
AllocateDexMemoryMap(JNIEnv * env,jint start,jint end)160 static std::unique_ptr<MemMap> AllocateDexMemoryMap(JNIEnv* env, jint start, jint end) {
161   if (end <= start) {
162     ScopedObjectAccess soa(env);
163     ThrowWrappedIOException("Bad range");
164     return nullptr;
165   }
166 
167   std::string error_message;
168   size_t length = static_cast<size_t>(end - start);
169   std::unique_ptr<MemMap> dex_mem_map(MemMap::MapAnonymous("DEX data",
170                                                            nullptr,
171                                                            length,
172                                                            PROT_READ | PROT_WRITE,
173                                                            /* low_4gb */ false,
174                                                            /* reuse */ false,
175                                                            &error_message));
176   if (dex_mem_map == nullptr) {
177     ScopedObjectAccess soa(env);
178     ThrowWrappedIOException("%s", error_message.c_str());
179   }
180   return dex_mem_map;
181 }
182 
CreateDexFile(JNIEnv * env,std::unique_ptr<MemMap> dex_mem_map)183 static const DexFile* CreateDexFile(JNIEnv* env, std::unique_ptr<MemMap> dex_mem_map) {
184   std::string location = StringPrintf("Anonymous-DexFile@%p-%p",
185                                       dex_mem_map->Begin(),
186                                       dex_mem_map->End());
187   std::string error_message;
188   std::unique_ptr<const DexFile> dex_file(DexFile::Open(location,
189                                                         0,
190                                                         std::move(dex_mem_map),
191                                                         /* verify */ true,
192                                                         /* verify_location */ true,
193                                                         &error_message));
194   if (dex_file == nullptr) {
195     ScopedObjectAccess soa(env);
196     ThrowWrappedIOException("%s", error_message.c_str());
197     return nullptr;
198   }
199 
200   if (!dex_file->DisableWrite()) {
201     ScopedObjectAccess soa(env);
202     ThrowWrappedIOException("Failed to make dex file read-only");
203     return nullptr;
204   }
205 
206   return dex_file.release();
207 }
208 
CreateSingleDexFileCookie(JNIEnv * env,std::unique_ptr<MemMap> data)209 static jobject CreateSingleDexFileCookie(JNIEnv* env, std::unique_ptr<MemMap> data) {
210   std::unique_ptr<const DexFile> dex_file(CreateDexFile(env, std::move(data)));
211   if (dex_file.get() == nullptr) {
212     DCHECK(env->ExceptionCheck());
213     return nullptr;
214   }
215   std::vector<std::unique_ptr<const DexFile>> dex_files;
216   dex_files.push_back(std::move(dex_file));
217   return ConvertDexFilesToJavaArray(env, nullptr, dex_files);
218 }
219 
DexFile_createCookieWithDirectBuffer(JNIEnv * env,jclass,jobject buffer,jint start,jint end)220 static jobject DexFile_createCookieWithDirectBuffer(JNIEnv* env,
221                                                     jclass,
222                                                     jobject buffer,
223                                                     jint start,
224                                                     jint end) {
225   uint8_t* base_address = reinterpret_cast<uint8_t*>(env->GetDirectBufferAddress(buffer));
226   if (base_address == nullptr) {
227     ScopedObjectAccess soa(env);
228     ThrowWrappedIOException("dexFileBuffer not direct");
229     return 0;
230   }
231 
232   std::unique_ptr<MemMap> dex_mem_map(AllocateDexMemoryMap(env, start, end));
233   if (dex_mem_map == nullptr) {
234     DCHECK(Thread::Current()->IsExceptionPending());
235     return 0;
236   }
237 
238   size_t length = static_cast<size_t>(end - start);
239   memcpy(dex_mem_map->Begin(), base_address, length);
240   return CreateSingleDexFileCookie(env, std::move(dex_mem_map));
241 }
242 
DexFile_createCookieWithArray(JNIEnv * env,jclass,jbyteArray buffer,jint start,jint end)243 static jobject DexFile_createCookieWithArray(JNIEnv* env,
244                                              jclass,
245                                              jbyteArray buffer,
246                                              jint start,
247                                              jint end) {
248   std::unique_ptr<MemMap> dex_mem_map(AllocateDexMemoryMap(env, start, end));
249   if (dex_mem_map == nullptr) {
250     DCHECK(Thread::Current()->IsExceptionPending());
251     return 0;
252   }
253 
254   auto destination = reinterpret_cast<jbyte*>(dex_mem_map.get()->Begin());
255   env->GetByteArrayRegion(buffer, start, end - start, destination);
256   return CreateSingleDexFileCookie(env, std::move(dex_mem_map));
257 }
258 
259 // TODO(calin): clean up the unused parameters (here and in libcore).
DexFile_openDexFileNative(JNIEnv * env,jclass,jstring javaSourceName,jstring javaOutputName ATTRIBUTE_UNUSED,jint flags ATTRIBUTE_UNUSED,jobject class_loader,jobjectArray dex_elements)260 static jobject DexFile_openDexFileNative(JNIEnv* env,
261                                          jclass,
262                                          jstring javaSourceName,
263                                          jstring javaOutputName ATTRIBUTE_UNUSED,
264                                          jint flags ATTRIBUTE_UNUSED,
265                                          jobject class_loader,
266                                          jobjectArray dex_elements) {
267   ScopedUtfChars sourceName(env, javaSourceName);
268   if (sourceName.c_str() == nullptr) {
269     return 0;
270   }
271 
272   Runtime* const runtime = Runtime::Current();
273   ClassLinker* linker = runtime->GetClassLinker();
274   std::vector<std::unique_ptr<const DexFile>> dex_files;
275   std::vector<std::string> error_msgs;
276   const OatFile* oat_file = nullptr;
277 
278   dex_files = runtime->GetOatFileManager().OpenDexFilesFromOat(sourceName.c_str(),
279                                                                class_loader,
280                                                                dex_elements,
281                                                                /*out*/ &oat_file,
282                                                                /*out*/ &error_msgs);
283 
284   if (!dex_files.empty()) {
285     jlongArray array = ConvertDexFilesToJavaArray(env, oat_file, dex_files);
286     if (array == nullptr) {
287       ScopedObjectAccess soa(env);
288       for (auto& dex_file : dex_files) {
289         if (linker->IsDexFileRegistered(soa.Self(), *dex_file)) {
290           dex_file.release();
291         }
292       }
293     }
294     return array;
295   } else {
296     ScopedObjectAccess soa(env);
297     CHECK(!error_msgs.empty());
298     // The most important message is at the end. So set up nesting by going forward, which will
299     // wrap the existing exception as a cause for the following one.
300     auto it = error_msgs.begin();
301     auto itEnd = error_msgs.end();
302     for ( ; it != itEnd; ++it) {
303       ThrowWrappedIOException("%s", it->c_str());
304     }
305 
306     return nullptr;
307   }
308 }
309 
DexFile_closeDexFile(JNIEnv * env,jclass,jobject cookie)310 static jboolean DexFile_closeDexFile(JNIEnv* env, jclass, jobject cookie) {
311   std::vector<const DexFile*> dex_files;
312   const OatFile* oat_file;
313   if (!ConvertJavaArrayToDexFiles(env, cookie, dex_files, oat_file)) {
314     Thread::Current()->AssertPendingException();
315     return JNI_FALSE;
316   }
317   Runtime* const runtime = Runtime::Current();
318   bool all_deleted = true;
319   {
320     ScopedObjectAccess soa(env);
321     ObjPtr<mirror::Object> dex_files_object = soa.Decode<mirror::Object>(cookie);
322     ObjPtr<mirror::LongArray> long_dex_files = dex_files_object->AsLongArray();
323     // Delete dex files associated with this dalvik.system.DexFile since there should not be running
324     // code using it. dex_files is a vector due to multidex.
325     ClassLinker* const class_linker = runtime->GetClassLinker();
326     int32_t i = kDexFileIndexStart;  // Oat file is at index 0.
327     for (const DexFile* dex_file : dex_files) {
328       if (dex_file != nullptr) {
329         // Only delete the dex file if the dex cache is not found to prevent runtime crashes if there
330         // are calls to DexFile.close while the ART DexFile is still in use.
331         if (!class_linker->IsDexFileRegistered(soa.Self(), *dex_file)) {
332           // Clear the element in the array so that we can call close again.
333           long_dex_files->Set(i, 0);
334           delete dex_file;
335         } else {
336           all_deleted = false;
337         }
338       }
339       ++i;
340     }
341   }
342 
343   // oat_file can be null if we are running without dex2oat.
344   if (all_deleted && oat_file != nullptr) {
345     // If all of the dex files are no longer in use we can unmap the corresponding oat file.
346     VLOG(class_linker) << "Unregistering " << oat_file;
347     runtime->GetOatFileManager().UnRegisterAndDeleteOatFile(oat_file);
348   }
349   return all_deleted ? JNI_TRUE : JNI_FALSE;
350 }
351 
DexFile_defineClassNative(JNIEnv * env,jclass,jstring javaName,jobject javaLoader,jobject cookie,jobject dexFile)352 static jclass DexFile_defineClassNative(JNIEnv* env,
353                                         jclass,
354                                         jstring javaName,
355                                         jobject javaLoader,
356                                         jobject cookie,
357                                         jobject dexFile) {
358   std::vector<const DexFile*> dex_files;
359   const OatFile* oat_file;
360   if (!ConvertJavaArrayToDexFiles(env, cookie, /*out*/ dex_files, /*out*/ oat_file)) {
361     VLOG(class_linker) << "Failed to find dex_file";
362     DCHECK(env->ExceptionCheck());
363     return nullptr;
364   }
365 
366   ScopedUtfChars class_name(env, javaName);
367   if (class_name.c_str() == nullptr) {
368     VLOG(class_linker) << "Failed to find class_name";
369     return nullptr;
370   }
371   const std::string descriptor(DotToDescriptor(class_name.c_str()));
372   const size_t hash(ComputeModifiedUtf8Hash(descriptor.c_str()));
373   for (auto& dex_file : dex_files) {
374     const DexFile::ClassDef* dex_class_def =
375         OatDexFile::FindClassDef(*dex_file, descriptor.c_str(), hash);
376     if (dex_class_def != nullptr) {
377       ScopedObjectAccess soa(env);
378       ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
379       StackHandleScope<1> hs(soa.Self());
380       Handle<mirror::ClassLoader> class_loader(
381           hs.NewHandle(soa.Decode<mirror::ClassLoader>(javaLoader)));
382       ObjPtr<mirror::DexCache> dex_cache =
383           class_linker->RegisterDexFile(*dex_file, class_loader.Get());
384       if (dex_cache == nullptr) {
385         // OOME or InternalError (dexFile already registered with a different class loader).
386         soa.Self()->AssertPendingException();
387         return nullptr;
388       }
389       ObjPtr<mirror::Class> result = class_linker->DefineClass(soa.Self(),
390                                                                descriptor.c_str(),
391                                                                hash,
392                                                                class_loader,
393                                                                *dex_file,
394                                                                *dex_class_def);
395       // Add the used dex file. This only required for the DexFile.loadClass API since normal
396       // class loaders already keep their dex files live.
397       class_linker->InsertDexFileInToClassLoader(soa.Decode<mirror::Object>(dexFile),
398                                                  class_loader.Get());
399       if (result != nullptr) {
400         VLOG(class_linker) << "DexFile_defineClassNative returning " << result
401                            << " for " << class_name.c_str();
402         return soa.AddLocalReference<jclass>(result);
403       }
404     }
405   }
406   VLOG(class_linker) << "Failed to find dex_class_def " << class_name.c_str();
407   return nullptr;
408 }
409 
410 // Needed as a compare functor for sets of const char
411 struct CharPointerComparator {
operator ()art::CharPointerComparator412   bool operator()(const char *str1, const char *str2) const {
413     return strcmp(str1, str2) < 0;
414   }
415 };
416 
417 // Note: this can be an expensive call, as we sort out duplicates in MultiDex files.
DexFile_getClassNameList(JNIEnv * env,jclass,jobject cookie)418 static jobjectArray DexFile_getClassNameList(JNIEnv* env, jclass, jobject cookie) {
419   const OatFile* oat_file = nullptr;
420   std::vector<const DexFile*> dex_files;
421   if (!ConvertJavaArrayToDexFiles(env, cookie, /*out */ dex_files, /* out */ oat_file)) {
422     DCHECK(env->ExceptionCheck());
423     return nullptr;
424   }
425 
426   // Push all class descriptors into a set. Use set instead of unordered_set as we want to
427   // retrieve all in the end.
428   std::set<const char*, CharPointerComparator> descriptors;
429   for (auto& dex_file : dex_files) {
430     for (size_t i = 0; i < dex_file->NumClassDefs(); ++i) {
431       const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
432       const char* descriptor = dex_file->GetClassDescriptor(class_def);
433       descriptors.insert(descriptor);
434     }
435   }
436 
437   // Now create output array and copy the set into it.
438   jobjectArray result = env->NewObjectArray(descriptors.size(),
439                                             WellKnownClasses::java_lang_String,
440                                             nullptr);
441   if (result != nullptr) {
442     auto it = descriptors.begin();
443     auto it_end = descriptors.end();
444     jsize i = 0;
445     for (; it != it_end; it++, ++i) {
446       std::string descriptor(DescriptorToDot(*it));
447       ScopedLocalRef<jstring> jdescriptor(env, env->NewStringUTF(descriptor.c_str()));
448       if (jdescriptor.get() == nullptr) {
449         return nullptr;
450       }
451       env->SetObjectArrayElement(result, i, jdescriptor.get());
452     }
453   }
454   return result;
455 }
456 
GetDexOptNeeded(JNIEnv * env,const char * filename,const char * instruction_set,const char * compiler_filter_name,bool profile_changed,bool downgrade)457 static jint GetDexOptNeeded(JNIEnv* env,
458                             const char* filename,
459                             const char* instruction_set,
460                             const char* compiler_filter_name,
461                             bool profile_changed,
462                             bool downgrade) {
463   if ((filename == nullptr) || !OS::FileExists(filename)) {
464     LOG(ERROR) << "DexFile_getDexOptNeeded file '" << filename << "' does not exist";
465     ScopedLocalRef<jclass> fnfe(env, env->FindClass("java/io/FileNotFoundException"));
466     const char* message = (filename == nullptr) ? "<empty file name>" : filename;
467     env->ThrowNew(fnfe.get(), message);
468     return -1;
469   }
470 
471   const InstructionSet target_instruction_set = GetInstructionSetFromString(instruction_set);
472   if (target_instruction_set == kNone) {
473     ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException"));
474     std::string message(StringPrintf("Instruction set %s is invalid.", instruction_set));
475     env->ThrowNew(iae.get(), message.c_str());
476     return -1;
477   }
478 
479   CompilerFilter::Filter filter;
480   if (!CompilerFilter::ParseCompilerFilter(compiler_filter_name, &filter)) {
481     ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException"));
482     std::string message(StringPrintf("Compiler filter %s is invalid.", compiler_filter_name));
483     env->ThrowNew(iae.get(), message.c_str());
484     return -1;
485   }
486 
487   // TODO: Verify the dex location is well formed, and throw an IOException if
488   // not?
489 
490   OatFileAssistant oat_file_assistant(filename, target_instruction_set, false);
491 
492   // Always treat elements of the bootclasspath as up-to-date.
493   if (oat_file_assistant.IsInBootClassPath()) {
494     return OatFileAssistant::kNoDexOptNeeded;
495   }
496 
497   // TODO(calin): Extend DexFile.getDexOptNeeded to accept the class loader context. b/62269291.
498   return oat_file_assistant.GetDexOptNeeded(filter, profile_changed, downgrade);
499 }
500 
DexFile_getDexFileStatus(JNIEnv * env,jclass,jstring javaFilename,jstring javaInstructionSet)501 static jstring DexFile_getDexFileStatus(JNIEnv* env,
502                                         jclass,
503                                         jstring javaFilename,
504                                         jstring javaInstructionSet) {
505   ScopedUtfChars filename(env, javaFilename);
506   if (env->ExceptionCheck()) {
507     return nullptr;
508   }
509 
510   ScopedUtfChars instruction_set(env, javaInstructionSet);
511   if (env->ExceptionCheck()) {
512     return nullptr;
513   }
514 
515   const InstructionSet target_instruction_set = GetInstructionSetFromString(
516       instruction_set.c_str());
517   if (target_instruction_set == kNone) {
518     ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException"));
519     std::string message(StringPrintf("Instruction set %s is invalid.", instruction_set.c_str()));
520     env->ThrowNew(iae.get(), message.c_str());
521     return nullptr;
522   }
523 
524   OatFileAssistant oat_file_assistant(filename.c_str(), target_instruction_set,
525                                       false /* load_executable */);
526   return env->NewStringUTF(oat_file_assistant.GetStatusDump().c_str());
527 }
528 
DexFile_getDexOptNeeded(JNIEnv * env,jclass,jstring javaFilename,jstring javaInstructionSet,jstring javaTargetCompilerFilter,jboolean newProfile,jboolean downgrade)529 static jint DexFile_getDexOptNeeded(JNIEnv* env,
530                                     jclass,
531                                     jstring javaFilename,
532                                     jstring javaInstructionSet,
533                                     jstring javaTargetCompilerFilter,
534                                     jboolean newProfile,
535                                     jboolean downgrade) {
536   ScopedUtfChars filename(env, javaFilename);
537   if (env->ExceptionCheck()) {
538     return -1;
539   }
540 
541   ScopedUtfChars instruction_set(env, javaInstructionSet);
542   if (env->ExceptionCheck()) {
543     return -1;
544   }
545 
546   ScopedUtfChars target_compiler_filter(env, javaTargetCompilerFilter);
547   if (env->ExceptionCheck()) {
548     return -1;
549   }
550 
551   return GetDexOptNeeded(env,
552                          filename.c_str(),
553                          instruction_set.c_str(),
554                          target_compiler_filter.c_str(),
555                          newProfile == JNI_TRUE,
556                          downgrade == JNI_TRUE);
557 }
558 
559 // public API
DexFile_isDexOptNeeded(JNIEnv * env,jclass,jstring javaFilename)560 static jboolean DexFile_isDexOptNeeded(JNIEnv* env, jclass, jstring javaFilename) {
561   ScopedUtfChars filename_utf(env, javaFilename);
562   if (env->ExceptionCheck()) {
563     return JNI_FALSE;
564   }
565 
566   const char* filename = filename_utf.c_str();
567   if ((filename == nullptr) || !OS::FileExists(filename)) {
568     LOG(ERROR) << "DexFile_isDexOptNeeded file '" << filename << "' does not exist";
569     ScopedLocalRef<jclass> fnfe(env, env->FindClass("java/io/FileNotFoundException"));
570     const char* message = (filename == nullptr) ? "<empty file name>" : filename;
571     env->ThrowNew(fnfe.get(), message);
572     return JNI_FALSE;
573   }
574 
575   OatFileAssistant oat_file_assistant(filename, kRuntimeISA, false);
576   return oat_file_assistant.IsUpToDate() ? JNI_FALSE : JNI_TRUE;
577 }
578 
DexFile_isValidCompilerFilter(JNIEnv * env,jclass javeDexFileClass ATTRIBUTE_UNUSED,jstring javaCompilerFilter)579 static jboolean DexFile_isValidCompilerFilter(JNIEnv* env,
580                                             jclass javeDexFileClass ATTRIBUTE_UNUSED,
581                                             jstring javaCompilerFilter) {
582   ScopedUtfChars compiler_filter(env, javaCompilerFilter);
583   if (env->ExceptionCheck()) {
584     return -1;
585   }
586 
587   CompilerFilter::Filter filter;
588   return CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)
589       ? JNI_TRUE : JNI_FALSE;
590 }
591 
DexFile_isProfileGuidedCompilerFilter(JNIEnv * env,jclass javeDexFileClass ATTRIBUTE_UNUSED,jstring javaCompilerFilter)592 static jboolean DexFile_isProfileGuidedCompilerFilter(JNIEnv* env,
593                                                       jclass javeDexFileClass ATTRIBUTE_UNUSED,
594                                                       jstring javaCompilerFilter) {
595   ScopedUtfChars compiler_filter(env, javaCompilerFilter);
596   if (env->ExceptionCheck()) {
597     return -1;
598   }
599 
600   CompilerFilter::Filter filter;
601   if (!CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)) {
602     return JNI_FALSE;
603   }
604   return CompilerFilter::DependsOnProfile(filter) ? JNI_TRUE : JNI_FALSE;
605 }
606 
DexFile_getNonProfileGuidedCompilerFilter(JNIEnv * env,jclass javeDexFileClass ATTRIBUTE_UNUSED,jstring javaCompilerFilter)607 static jstring DexFile_getNonProfileGuidedCompilerFilter(JNIEnv* env,
608                                                          jclass javeDexFileClass ATTRIBUTE_UNUSED,
609                                                          jstring javaCompilerFilter) {
610   ScopedUtfChars compiler_filter(env, javaCompilerFilter);
611   if (env->ExceptionCheck()) {
612     return nullptr;
613   }
614 
615   CompilerFilter::Filter filter;
616   if (!CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)) {
617     return javaCompilerFilter;
618   }
619 
620   CompilerFilter::Filter new_filter = CompilerFilter::GetNonProfileDependentFilterFrom(filter);
621 
622   // Filter stayed the same, return input.
623   if (filter == new_filter) {
624     return javaCompilerFilter;
625   }
626 
627   // Create a new string object and return.
628   std::string new_filter_str = CompilerFilter::NameOfFilter(new_filter);
629   return env->NewStringUTF(new_filter_str.c_str());
630 }
631 
DexFile_getSafeModeCompilerFilter(JNIEnv * env,jclass javeDexFileClass ATTRIBUTE_UNUSED,jstring javaCompilerFilter)632 static jstring DexFile_getSafeModeCompilerFilter(JNIEnv* env,
633                                                  jclass javeDexFileClass ATTRIBUTE_UNUSED,
634                                                  jstring javaCompilerFilter) {
635   ScopedUtfChars compiler_filter(env, javaCompilerFilter);
636   if (env->ExceptionCheck()) {
637     return nullptr;
638   }
639 
640   CompilerFilter::Filter filter;
641   if (!CompilerFilter::ParseCompilerFilter(compiler_filter.c_str(), &filter)) {
642     return javaCompilerFilter;
643   }
644 
645   CompilerFilter::Filter new_filter = CompilerFilter::GetSafeModeFilterFrom(filter);
646 
647   // Filter stayed the same, return input.
648   if (filter == new_filter) {
649     return javaCompilerFilter;
650   }
651 
652   // Create a new string object and return.
653   std::string new_filter_str = CompilerFilter::NameOfFilter(new_filter);
654   return env->NewStringUTF(new_filter_str.c_str());
655 }
656 
DexFile_isBackedByOatFile(JNIEnv * env,jclass,jobject cookie)657 static jboolean DexFile_isBackedByOatFile(JNIEnv* env, jclass, jobject cookie) {
658   const OatFile* oat_file = nullptr;
659   std::vector<const DexFile*> dex_files;
660   if (!ConvertJavaArrayToDexFiles(env, cookie, /*out */ dex_files, /* out */ oat_file)) {
661     DCHECK(env->ExceptionCheck());
662     return false;
663   }
664   return oat_file != nullptr;
665 }
666 
DexFile_getDexFileOutputPaths(JNIEnv * env,jclass,jstring javaFilename,jstring javaInstructionSet)667 static jobjectArray DexFile_getDexFileOutputPaths(JNIEnv* env,
668                                             jclass,
669                                             jstring javaFilename,
670                                             jstring javaInstructionSet) {
671   ScopedUtfChars filename(env, javaFilename);
672   if (env->ExceptionCheck()) {
673     return nullptr;
674   }
675 
676   ScopedUtfChars instruction_set(env, javaInstructionSet);
677   if (env->ExceptionCheck()) {
678     return nullptr;
679   }
680 
681   const InstructionSet target_instruction_set = GetInstructionSetFromString(
682       instruction_set.c_str());
683   if (target_instruction_set == kNone) {
684     ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException"));
685     std::string message(StringPrintf("Instruction set %s is invalid.", instruction_set.c_str()));
686     env->ThrowNew(iae.get(), message.c_str());
687     return nullptr;
688   }
689 
690   OatFileAssistant oat_file_assistant(filename.c_str(),
691                                       target_instruction_set,
692                                       false /* load_executable */);
693 
694   std::unique_ptr<OatFile> best_oat_file = oat_file_assistant.GetBestOatFile();
695   if (best_oat_file == nullptr) {
696     return nullptr;
697   }
698 
699   std::string oat_filename = best_oat_file->GetLocation();
700   std::string vdex_filename = GetVdexFilename(best_oat_file->GetLocation());
701 
702   ScopedLocalRef<jstring> jvdexFilename(env, env->NewStringUTF(vdex_filename.c_str()));
703   if (jvdexFilename.get() == nullptr) {
704     return nullptr;
705   }
706   ScopedLocalRef<jstring> joatFilename(env, env->NewStringUTF(oat_filename.c_str()));
707   if (joatFilename.get() == nullptr) {
708     return nullptr;
709   }
710 
711   // Now create output array and copy the set into it.
712   jobjectArray result = env->NewObjectArray(2,
713                                             WellKnownClasses::java_lang_String,
714                                             nullptr);
715   env->SetObjectArrayElement(result, 0, jvdexFilename.get());
716   env->SetObjectArrayElement(result, 1, joatFilename.get());
717 
718   return result;
719 }
720 
721 static JNINativeMethod gMethods[] = {
722   NATIVE_METHOD(DexFile, closeDexFile, "(Ljava/lang/Object;)Z"),
723   NATIVE_METHOD(DexFile,
724                 defineClassNative,
725                 "(Ljava/lang/String;"
726                 "Ljava/lang/ClassLoader;"
727                 "Ljava/lang/Object;"
728                 "Ldalvik/system/DexFile;"
729                 ")Ljava/lang/Class;"),
730   NATIVE_METHOD(DexFile, getClassNameList, "(Ljava/lang/Object;)[Ljava/lang/String;"),
731   NATIVE_METHOD(DexFile, isDexOptNeeded, "(Ljava/lang/String;)Z"),
732   NATIVE_METHOD(DexFile, getDexOptNeeded,
733                 "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZ)I"),
734   NATIVE_METHOD(DexFile, openDexFileNative,
735                 "(Ljava/lang/String;"
736                 "Ljava/lang/String;"
737                 "I"
738                 "Ljava/lang/ClassLoader;"
739                 "[Ldalvik/system/DexPathList$Element;"
740                 ")Ljava/lang/Object;"),
741   NATIVE_METHOD(DexFile, createCookieWithDirectBuffer,
742                 "(Ljava/nio/ByteBuffer;II)Ljava/lang/Object;"),
743   NATIVE_METHOD(DexFile, createCookieWithArray, "([BII)Ljava/lang/Object;"),
744   NATIVE_METHOD(DexFile, isValidCompilerFilter, "(Ljava/lang/String;)Z"),
745   NATIVE_METHOD(DexFile, isProfileGuidedCompilerFilter, "(Ljava/lang/String;)Z"),
746   NATIVE_METHOD(DexFile,
747                 getNonProfileGuidedCompilerFilter,
748                 "(Ljava/lang/String;)Ljava/lang/String;"),
749   NATIVE_METHOD(DexFile,
750                 getSafeModeCompilerFilter,
751                 "(Ljava/lang/String;)Ljava/lang/String;"),
752   NATIVE_METHOD(DexFile, isBackedByOatFile, "(Ljava/lang/Object;)Z"),
753   NATIVE_METHOD(DexFile, getDexFileStatus,
754                 "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"),
755   NATIVE_METHOD(DexFile, getDexFileOutputPaths,
756                 "(Ljava/lang/String;Ljava/lang/String;)[Ljava/lang/String;")
757 };
758 
register_dalvik_system_DexFile(JNIEnv * env)759 void register_dalvik_system_DexFile(JNIEnv* env) {
760   REGISTER_NATIVE_METHODS("dalvik/system/DexFile");
761 }
762 
763 }  // namespace art
764