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 <algorithm>
18 #include <set>
19 #include <fcntl.h>
20 #ifdef __linux__
21 #include <sys/sendfile.h>
22 #else
23 #include <sys/socket.h>
24 #endif
25 #include <sys/stat.h>
26 #include <unistd.h>
27 
28 #include "base/logging.h"
29 #include "base/stl_util.h"
30 #include "base/stringprintf.h"
31 #include "class_linker.h"
32 #include "common_throws.h"
33 #include "dex_file-inl.h"
34 #include "gc/space/image_space.h"
35 #include "gc/space/space-inl.h"
36 #include "image.h"
37 #include "jni_internal.h"
38 #include "mirror/class_loader.h"
39 #include "mirror/object-inl.h"
40 #include "mirror/string.h"
41 #include "oat.h"
42 #include "os.h"
43 #include "profiler.h"
44 #include "runtime.h"
45 #include "scoped_thread_state_change.h"
46 #include "ScopedFd.h"
47 #include "ScopedLocalRef.h"
48 #include "ScopedUtfChars.h"
49 #include "utils.h"
50 #include "well_known_classes.h"
51 #include "zip_archive.h"
52 
53 namespace art {
54 
55 // A smart pointer that provides read-only access to a Java string's UTF chars.
56 // Unlike libcore's NullableScopedUtfChars, this will *not* throw NullPointerException if
57 // passed a null jstring. The correct idiom is:
58 //
59 //   NullableScopedUtfChars name(env, javaName);
60 //   if (env->ExceptionCheck()) {
61 //       return NULL;
62 //   }
63 //   // ... use name.c_str()
64 //
65 // TODO: rewrite to get rid of this, or change ScopedUtfChars to offer this option.
66 class NullableScopedUtfChars {
67  public:
NullableScopedUtfChars(JNIEnv * env,jstring s)68   NullableScopedUtfChars(JNIEnv* env, jstring s) : mEnv(env), mString(s) {
69     mUtfChars = (s != NULL) ? env->GetStringUTFChars(s, NULL) : NULL;
70   }
71 
~NullableScopedUtfChars()72   ~NullableScopedUtfChars() {
73     if (mUtfChars) {
74       mEnv->ReleaseStringUTFChars(mString, mUtfChars);
75     }
76   }
77 
c_str() const78   const char* c_str() const {
79     return mUtfChars;
80   }
81 
size() const82   size_t size() const {
83     return strlen(mUtfChars);
84   }
85 
86   // Element access.
operator [](size_t n) const87   const char& operator[](size_t n) const {
88     return mUtfChars[n];
89   }
90 
91  private:
92   JNIEnv* mEnv;
93   jstring mString;
94   const char* mUtfChars;
95 
96   // Disallow copy and assignment.
97   NullableScopedUtfChars(const NullableScopedUtfChars&);
98   void operator=(const NullableScopedUtfChars&);
99 };
100 
DexFile_openDexFileNative(JNIEnv * env,jclass,jstring javaSourceName,jstring javaOutputName,jint)101 static jlong DexFile_openDexFileNative(JNIEnv* env, jclass, jstring javaSourceName, jstring javaOutputName, jint) {
102   ScopedUtfChars sourceName(env, javaSourceName);
103   if (sourceName.c_str() == NULL) {
104     return 0;
105   }
106   NullableScopedUtfChars outputName(env, javaOutputName);
107   if (env->ExceptionCheck()) {
108     return 0;
109   }
110 
111   ClassLinker* linker = Runtime::Current()->GetClassLinker();
112   std::unique_ptr<std::vector<const DexFile*>> dex_files(new std::vector<const DexFile*>());
113   std::vector<std::string> error_msgs;
114 
115   bool success = linker->OpenDexFilesFromOat(sourceName.c_str(), outputName.c_str(), &error_msgs,
116                                              dex_files.get());
117 
118   if (success || !dex_files->empty()) {
119     // In the case of non-success, we have not found or could not generate the oat file.
120     // But we may still have found a dex file that we can use.
121     return static_cast<jlong>(reinterpret_cast<uintptr_t>(dex_files.release()));
122   } else {
123     // The vector should be empty after a failed loading attempt.
124     DCHECK_EQ(0U, dex_files->size());
125 
126     ScopedObjectAccess soa(env);
127     CHECK(!error_msgs.empty());
128     // The most important message is at the end. So set up nesting by going forward, which will
129     // wrap the existing exception as a cause for the following one.
130     auto it = error_msgs.begin();
131     auto itEnd = error_msgs.end();
132     for ( ; it != itEnd; ++it) {
133       ThrowWrappedIOException("%s", it->c_str());
134     }
135 
136     return 0;
137   }
138 }
139 
toDexFiles(jlong dex_file_address,JNIEnv * env)140 static std::vector<const DexFile*>* toDexFiles(jlong dex_file_address, JNIEnv* env) {
141   std::vector<const DexFile*>* dex_files = reinterpret_cast<std::vector<const DexFile*>*>(
142       static_cast<uintptr_t>(dex_file_address));
143   if (UNLIKELY(dex_files == nullptr)) {
144     ScopedObjectAccess soa(env);
145     ThrowNullPointerException(NULL, "dex_file == null");
146   }
147   return dex_files;
148 }
149 
DexFile_closeDexFile(JNIEnv * env,jclass,jlong cookie)150 static void DexFile_closeDexFile(JNIEnv* env, jclass, jlong cookie) {
151   std::unique_ptr<std::vector<const DexFile*>> dex_files(toDexFiles(cookie, env));
152   if (dex_files.get() == nullptr) {
153     return;
154   }
155   ScopedObjectAccess soa(env);
156 
157   size_t index = 0;
158   for (const DexFile* dex_file : *dex_files) {
159     if (Runtime::Current()->GetClassLinker()->IsDexFileRegistered(*dex_file)) {
160       (*dex_files)[index] = nullptr;
161     }
162     index++;
163   }
164 
165   STLDeleteElements(dex_files.get());
166   // Unique_ptr will delete the vector itself.
167 }
168 
DexFile_defineClassNative(JNIEnv * env,jclass,jstring javaName,jobject javaLoader,jlong cookie)169 static jclass DexFile_defineClassNative(JNIEnv* env, jclass, jstring javaName, jobject javaLoader,
170                                         jlong cookie) {
171   std::vector<const DexFile*>* dex_files = toDexFiles(cookie, env);
172   if (dex_files == NULL) {
173     VLOG(class_linker) << "Failed to find dex_file";
174     return NULL;
175   }
176   ScopedUtfChars class_name(env, javaName);
177   if (class_name.c_str() == NULL) {
178     VLOG(class_linker) << "Failed to find class_name";
179     return NULL;
180   }
181   const std::string descriptor(DotToDescriptor(class_name.c_str()));
182   const size_t hash(ComputeModifiedUtf8Hash(descriptor.c_str()));
183   for (const DexFile* dex_file : *dex_files) {
184     const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor.c_str(), hash);
185     if (dex_class_def != nullptr) {
186       ScopedObjectAccess soa(env);
187       ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
188       class_linker->RegisterDexFile(*dex_file);
189       StackHandleScope<1> hs(soa.Self());
190       Handle<mirror::ClassLoader> class_loader(
191           hs.NewHandle(soa.Decode<mirror::ClassLoader*>(javaLoader)));
192       mirror::Class* result = class_linker->DefineClass(soa.Self(), descriptor.c_str(), hash,
193                                                         class_loader, *dex_file, *dex_class_def);
194       if (result != nullptr) {
195         VLOG(class_linker) << "DexFile_defineClassNative returning " << result;
196         return soa.AddLocalReference<jclass>(result);
197       }
198     }
199   }
200   VLOG(class_linker) << "Failed to find dex_class_def";
201   return nullptr;
202 }
203 
204 // Needed as a compare functor for sets of const char
205 struct CharPointerComparator {
operator ()art::CharPointerComparator206   bool operator()(const char *str1, const char *str2) const {
207     return strcmp(str1, str2) < 0;
208   }
209 };
210 
211 // Note: this can be an expensive call, as we sort out duplicates in MultiDex files.
DexFile_getClassNameList(JNIEnv * env,jclass,jlong cookie)212 static jobjectArray DexFile_getClassNameList(JNIEnv* env, jclass, jlong cookie) {
213   jobjectArray result = nullptr;
214   std::vector<const DexFile*>* dex_files = toDexFiles(cookie, env);
215 
216   if (dex_files != nullptr) {
217     // Push all class descriptors into a set. Use set instead of unordered_set as we want to
218     // retrieve all in the end.
219     std::set<const char*, CharPointerComparator> descriptors;
220     for (const DexFile* dex_file : *dex_files) {
221       for (size_t i = 0; i < dex_file->NumClassDefs(); ++i) {
222         const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
223         const char* descriptor = dex_file->GetClassDescriptor(class_def);
224         descriptors.insert(descriptor);
225       }
226     }
227 
228     // Now create output array and copy the set into it.
229     result = env->NewObjectArray(descriptors.size(), WellKnownClasses::java_lang_String, nullptr);
230     if (result != nullptr) {
231       auto it = descriptors.begin();
232       auto it_end = descriptors.end();
233       jsize i = 0;
234       for (; it != it_end; it++, ++i) {
235         std::string descriptor(DescriptorToDot(*it));
236         ScopedLocalRef<jstring> jdescriptor(env, env->NewStringUTF(descriptor.c_str()));
237         if (jdescriptor.get() == nullptr) {
238           return nullptr;
239         }
240         env->SetObjectArrayElement(result, i, jdescriptor.get());
241       }
242     }
243   }
244   return result;
245 }
246 
CopyProfileFile(const char * oldfile,const char * newfile)247 static void CopyProfileFile(const char* oldfile, const char* newfile) {
248   ScopedFd src(open(oldfile, O_RDONLY));
249   if (src.get() == -1) {
250     PLOG(ERROR) << "Failed to open profile file " << oldfile
251       << ". My uid:gid is " << getuid() << ":" << getgid();
252     return;
253   }
254 
255   struct stat stat_src;
256   if (fstat(src.get(), &stat_src) == -1) {
257     PLOG(ERROR) << "Failed to get stats for profile file  " << oldfile
258       << ". My uid:gid is " << getuid() << ":" << getgid();
259     return;
260   }
261 
262   // Create the copy with rw------- (only accessible by system)
263   ScopedFd dst(open(newfile, O_WRONLY|O_CREAT|O_TRUNC, 0600));
264   if (dst.get()  == -1) {
265     PLOG(ERROR) << "Failed to create/write prev profile file " << newfile
266       << ".  My uid:gid is " << getuid() << ":" << getgid();
267     return;
268   }
269 
270 #ifdef __linux__
271   if (sendfile(dst.get(), src.get(), nullptr, stat_src.st_size) == -1) {
272 #else
273   off_t len;
274   if (sendfile(dst.get(), src.get(), 0, &len, nullptr, 0) == -1) {
275 #endif
276     PLOG(ERROR) << "Failed to copy profile file " << oldfile << " to " << newfile
277       << ". My uid:gid is " << getuid() << ":" << getgid();
278   }
279 }
280 
281 // Java: dalvik.system.DexFile.UP_TO_DATE
282 static const jbyte kUpToDate = 0;
283 // Java: dalvik.system.DexFile.DEXOPT_NEEDED
284 static const jbyte kPatchoatNeeded = 1;
285 // Java: dalvik.system.DexFile.PATCHOAT_NEEDED
286 static const jbyte kDexoptNeeded = 2;
287 
288 template <const bool kVerboseLogging, const bool kReasonLogging>
289 static jbyte IsDexOptNeededForFile(const std::string& oat_filename, const char* filename,
290                                    InstructionSet target_instruction_set,
291                                    bool* oat_is_pic) {
292   std::string error_msg;
293   std::unique_ptr<const OatFile> oat_file(OatFile::Open(oat_filename, oat_filename, nullptr,
294                                                         nullptr,
295                                                         false, &error_msg));
296   if (oat_file.get() == nullptr) {
297     // Note that even though this is kDexoptNeeded, we use
298     // kVerboseLogging instead of the usual kReasonLogging since it is
299     // the common case on first boot and very spammy.
300     if (kVerboseLogging) {
301       LOG(INFO) << "DexFile_isDexOptNeeded failed to open oat file '" << oat_filename
302           << "' for file location '" << filename << "': " << error_msg;
303     }
304     error_msg.clear();
305     return kDexoptNeeded;
306   }
307 
308   // Pass-up the information about if this is PIC.
309   // TODO: Refactor this function to be less complicated.
310   *oat_is_pic = oat_file->IsPic();
311 
312   bool should_relocate_if_possible = Runtime::Current()->ShouldRelocate();
313   uint32_t location_checksum = 0;
314   const art::OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(filename, nullptr,
315                                                                           kReasonLogging);
316   if (oat_dex_file != nullptr) {
317     // If its not possible to read the classes.dex assume up-to-date as we won't be able to
318     // compile it anyway.
319     if (!DexFile::GetChecksum(filename, &location_checksum, &error_msg)) {
320       if (kVerboseLogging) {
321         LOG(INFO) << "DexFile_isDexOptNeeded found precompiled stripped file: "
322             << filename << " for " << oat_filename << ": " << error_msg;
323       }
324       if (ClassLinker::VerifyOatChecksums(oat_file.get(), target_instruction_set, &error_msg)) {
325         if (kVerboseLogging) {
326           LOG(INFO) << "DexFile_isDexOptNeeded file " << oat_filename
327                     << " is up-to-date for " << filename;
328         }
329         return kUpToDate;
330       } else if (should_relocate_if_possible &&
331                   ClassLinker::VerifyOatImageChecksum(oat_file.get(), target_instruction_set)) {
332         if (kReasonLogging) {
333           LOG(INFO) << "DexFile_isDexOptNeeded file " << oat_filename
334                     << " needs to be relocated for " << filename;
335         }
336         return kPatchoatNeeded;
337       } else {
338         if (kReasonLogging) {
339           LOG(INFO) << "DexFile_isDexOptNeeded file " << oat_filename
340                     << " is out of date for " << filename;
341         }
342         return kDexoptNeeded;
343       }
344       // If we get here the file is out of date and we should use the system one to relocate.
345     } else {
346       if (ClassLinker::VerifyOatAndDexFileChecksums(oat_file.get(), filename, location_checksum,
347                                                     target_instruction_set, &error_msg)) {
348         if (kVerboseLogging) {
349           LOG(INFO) << "DexFile_isDexOptNeeded file " << oat_filename
350                     << " is up-to-date for " << filename;
351         }
352         return kUpToDate;
353       } else if (location_checksum == oat_dex_file->GetDexFileLocationChecksum()
354                   && should_relocate_if_possible
355                   && ClassLinker::VerifyOatImageChecksum(oat_file.get(), target_instruction_set)) {
356         if (kReasonLogging) {
357           LOG(INFO) << "DexFile_isDexOptNeeded file " << oat_filename
358                     << " needs to be relocated for " << filename;
359         }
360         return kPatchoatNeeded;
361       } else {
362         if (kReasonLogging) {
363           LOG(INFO) << "DexFile_isDexOptNeeded file " << oat_filename
364                     << " is out of date for " << filename;
365         }
366         return kDexoptNeeded;
367       }
368     }
369   } else {
370     if (kReasonLogging) {
371       LOG(INFO) << "DexFile_isDexOptNeeded file " << oat_filename
372                 << " does not contain " << filename;
373     }
374     return kDexoptNeeded;
375   }
376 }
377 
378 static jbyte IsDexOptNeededInternal(JNIEnv* env, const char* filename,
379     const char* pkgname, const char* instruction_set, const jboolean defer) {
380   // Spammy logging for kUpToDate
381   const bool kVerboseLogging = false;
382   // Logging of reason for returning kDexoptNeeded or kPatchoatNeeded.
383   const bool kReasonLogging = true;
384 
385   if ((filename == nullptr) || !OS::FileExists(filename)) {
386     LOG(ERROR) << "DexFile_isDexOptNeeded file '" << filename << "' does not exist";
387     ScopedLocalRef<jclass> fnfe(env, env->FindClass("java/io/FileNotFoundException"));
388     const char* message = (filename == nullptr) ? "<empty file name>" : filename;
389     env->ThrowNew(fnfe.get(), message);
390     return kUpToDate;
391   }
392 
393   // Always treat elements of the bootclasspath as up-to-date.  The
394   // fact that code is running at all means that this should be true.
395   Runtime* runtime = Runtime::Current();
396   ClassLinker* class_linker = runtime->GetClassLinker();
397   // TODO: We're assuming that the 64 and 32 bit runtimes have identical
398   // class paths. isDexOptNeeded will not necessarily be called on a runtime
399   // that has the same instruction set as the file being dexopted.
400   const std::vector<const DexFile*>& boot_class_path = class_linker->GetBootClassPath();
401   for (size_t i = 0; i < boot_class_path.size(); i++) {
402     if (boot_class_path[i]->GetLocation() == filename) {
403       if (kVerboseLogging) {
404         LOG(INFO) << "DexFile_isDexOptNeeded ignoring boot class path file: " << filename;
405       }
406       return kUpToDate;
407     }
408   }
409 
410   bool force_system_only = false;
411   bool require_system_version = false;
412 
413   // Check the profile file.  We need to rerun dex2oat if the profile has changed significantly
414   // since the last time, or it's new.
415   // If the 'defer' argument is true then this will be retried later.  In this case we
416   // need to make sure that the profile file copy is not made so that we will get the
417   // same result second time.
418   std::string profile_file;
419   std::string prev_profile_file;
420   bool should_copy_profile = false;
421   if (Runtime::Current()->GetProfilerOptions().IsEnabled() && (pkgname != nullptr)) {
422     profile_file = GetDalvikCacheOrDie("profiles", false /* create_if_absent */)
423         + std::string("/") + pkgname;
424     prev_profile_file = profile_file + std::string("@old");
425 
426     struct stat profstat, prevstat;
427     int e1 = stat(profile_file.c_str(), &profstat);
428     int e1_errno = errno;
429     int e2 = stat(prev_profile_file.c_str(), &prevstat);
430     int e2_errno = errno;
431     if (e1 < 0) {
432       if (e1_errno != EACCES) {
433         // No profile file, need to run dex2oat, unless we find a file in system
434         if (kReasonLogging) {
435           LOG(INFO) << "DexFile_isDexOptNeededInternal profile file " << profile_file << " doesn't exist. "
436                     << "Will check odex to see if we can find a working version.";
437         }
438         // Force it to only accept system files/files with versions in system.
439         require_system_version = true;
440       } else {
441         LOG(INFO) << "DexFile_isDexOptNeededInternal recieved EACCES trying to stat profile file "
442                   << profile_file;
443       }
444     } else if (e2 == 0) {
445       // There is a previous profile file.  Check if the profile has changed significantly.
446       // A change in profile is considered significant if X% (change_thr property) of the top K%
447       // (compile_thr property) samples has changed.
448       double top_k_threshold = Runtime::Current()->GetProfilerOptions().GetTopKThreshold();
449       double change_threshold = Runtime::Current()->GetProfilerOptions().GetTopKChangeThreshold();
450       double change_percent = 0.0;
451       ProfileFile new_profile, old_profile;
452       bool new_ok = new_profile.LoadFile(profile_file);
453       bool old_ok = old_profile.LoadFile(prev_profile_file);
454       if (!new_ok || !old_ok) {
455         if (kVerboseLogging) {
456           LOG(INFO) << "DexFile_isDexOptNeededInternal Ignoring invalid profiles: "
457                     << (new_ok ?  "" : profile_file) << " " << (old_ok ? "" : prev_profile_file);
458         }
459       } else {
460         std::set<std::string> new_top_k, old_top_k;
461         new_profile.GetTopKSamples(new_top_k, top_k_threshold);
462         old_profile.GetTopKSamples(old_top_k, top_k_threshold);
463         if (new_top_k.empty()) {
464           if (kVerboseLogging) {
465             LOG(INFO) << "DexFile_isDexOptNeededInternal empty profile: " << profile_file;
466           }
467           // If the new topK is empty we shouldn't optimize so we leave the change_percent at 0.0.
468         } else {
469           std::set<std::string> diff;
470           std::set_difference(new_top_k.begin(), new_top_k.end(), old_top_k.begin(), old_top_k.end(),
471             std::inserter(diff, diff.end()));
472           // TODO: consider using the usedPercentage instead of the plain diff count.
473           change_percent = 100.0 * static_cast<double>(diff.size()) / static_cast<double>(new_top_k.size());
474           if (kVerboseLogging) {
475             std::set<std::string>::iterator end = diff.end();
476             for (std::set<std::string>::iterator it = diff.begin(); it != end; it++) {
477               LOG(INFO) << "DexFile_isDexOptNeededInternal new in topK: " << *it;
478             }
479           }
480         }
481       }
482 
483       if (change_percent > change_threshold) {
484         if (kReasonLogging) {
485           LOG(INFO) << "DexFile_isDexOptNeededInternal size of new profile file " << profile_file <<
486           " is significantly different from old profile file " << prev_profile_file << " (top "
487           << top_k_threshold << "% samples changed in proportion of " << change_percent << "%)";
488         }
489         should_copy_profile = !defer;
490         // Force us to only accept system files.
491         force_system_only = true;
492       }
493     } else if (e2_errno == ENOENT) {
494       // Previous profile does not exist.  Make a copy of the current one.
495       if (kVerboseLogging) {
496         LOG(INFO) << "DexFile_isDexOptNeededInternal previous profile doesn't exist: " << prev_profile_file;
497       }
498       should_copy_profile = !defer;
499     } else {
500       PLOG(INFO) << "Unable to stat previous profile file " << prev_profile_file;
501     }
502   }
503 
504   const InstructionSet target_instruction_set = GetInstructionSetFromString(instruction_set);
505   if (target_instruction_set == kNone) {
506     ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException"));
507     std::string message(StringPrintf("Instruction set %s is invalid.", instruction_set));
508     env->ThrowNew(iae.get(), message.c_str());
509     return 0;
510   }
511 
512   // Get the filename for odex file next to the dex file.
513   std::string odex_filename(DexFilenameToOdexFilename(filename, target_instruction_set));
514   // Get the filename for the dalvik-cache file
515   std::string cache_dir;
516   bool have_android_data = false;
517   bool dalvik_cache_exists = false;
518   bool is_global_cache = false;
519   GetDalvikCache(instruction_set, false, &cache_dir, &have_android_data, &dalvik_cache_exists,
520                  &is_global_cache);
521   std::string cache_filename;  // was cache_location
522   bool have_cache_filename = false;
523   if (dalvik_cache_exists) {
524     std::string error_msg;
525     have_cache_filename = GetDalvikCacheFilename(filename, cache_dir.c_str(), &cache_filename,
526                                                  &error_msg);
527     if (!have_cache_filename && kVerboseLogging) {
528       LOG(INFO) << "DexFile_isDexOptNeededInternal failed to find cache file for dex file " << filename
529                 << ": " << error_msg;
530     }
531   }
532 
533   bool should_relocate_if_possible = Runtime::Current()->ShouldRelocate();
534 
535   jbyte dalvik_cache_decision = -1;
536   // Lets try the cache first (since we want to load from there since thats where the relocated
537   // versions will be).
538   if (have_cache_filename && !force_system_only) {
539     bool oat_is_pic;
540     // We can use the dalvik-cache if we find a good file.
541     dalvik_cache_decision =
542         IsDexOptNeededForFile<kVerboseLogging, kReasonLogging>(cache_filename, filename,
543                                                                target_instruction_set, &oat_is_pic);
544 
545     // Apps that are compiled with --compile-pic never need to be patchoat-d
546     if (oat_is_pic && dalvik_cache_decision == kPatchoatNeeded) {
547       dalvik_cache_decision = kUpToDate;
548     }
549     // We will only return DexOptNeeded if both the cache and system return it.
550     if (dalvik_cache_decision != kDexoptNeeded && !require_system_version) {
551       CHECK(!(dalvik_cache_decision == kPatchoatNeeded && !should_relocate_if_possible))
552           << "May not return PatchoatNeeded when patching is disabled.";
553       return dalvik_cache_decision;
554     }
555     // We couldn't find one thats easy. We should now try the system.
556   }
557 
558   bool oat_is_pic;
559   jbyte system_decision =
560       IsDexOptNeededForFile<kVerboseLogging, kReasonLogging>(odex_filename, filename,
561                                                              target_instruction_set, &oat_is_pic);
562   CHECK(!(system_decision == kPatchoatNeeded && !should_relocate_if_possible))
563       << "May not return PatchoatNeeded when patching is disabled.";
564 
565   // Apps that are compiled with --compile-pic never need to be patchoat-d
566   if (oat_is_pic && system_decision == kPatchoatNeeded) {
567     system_decision = kUpToDate;
568   }
569 
570   if (require_system_version && system_decision == kPatchoatNeeded
571                              && dalvik_cache_decision == kUpToDate) {
572     // We have a version from system relocated to the cache. Return it.
573     return dalvik_cache_decision;
574   }
575 
576   if (should_copy_profile && system_decision == kDexoptNeeded) {
577     CopyProfileFile(profile_file.c_str(), prev_profile_file.c_str());
578   }
579 
580   return system_decision;
581 }
582 
583 static jbyte DexFile_isDexOptNeededInternal(JNIEnv* env, jclass, jstring javaFilename,
584     jstring javaPkgname, jstring javaInstructionSet, jboolean defer) {
585   ScopedUtfChars filename(env, javaFilename);
586   if (env->ExceptionCheck()) {
587     return 0;
588   }
589 
590   NullableScopedUtfChars pkgname(env, javaPkgname);
591 
592   ScopedUtfChars instruction_set(env, javaInstructionSet);
593   if (env->ExceptionCheck()) {
594     return 0;
595   }
596 
597   return IsDexOptNeededInternal(env, filename.c_str(), pkgname.c_str(),
598                                 instruction_set.c_str(), defer);
599 }
600 
601 // public API, NULL pkgname
602 static jboolean DexFile_isDexOptNeeded(JNIEnv* env, jclass, jstring javaFilename) {
603   const char* instruction_set = GetInstructionSetString(kRuntimeISA);
604   ScopedUtfChars filename(env, javaFilename);
605   return kUpToDate != IsDexOptNeededInternal(env, filename.c_str(), nullptr /* pkgname */,
606                                              instruction_set, false /* defer */);
607 }
608 
609 
610 static JNINativeMethod gMethods[] = {
611   NATIVE_METHOD(DexFile, closeDexFile, "(J)V"),
612   NATIVE_METHOD(DexFile, defineClassNative, "(Ljava/lang/String;Ljava/lang/ClassLoader;J)Ljava/lang/Class;"),
613   NATIVE_METHOD(DexFile, getClassNameList, "(J)[Ljava/lang/String;"),
614   NATIVE_METHOD(DexFile, isDexOptNeeded, "(Ljava/lang/String;)Z"),
615   NATIVE_METHOD(DexFile, isDexOptNeededInternal, "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)B"),
616   NATIVE_METHOD(DexFile, openDexFileNative, "(Ljava/lang/String;Ljava/lang/String;I)J"),
617 };
618 
619 void register_dalvik_system_DexFile(JNIEnv* env) {
620   REGISTER_NATIVE_METHODS("dalvik/system/DexFile");
621 }
622 
623 }  // namespace art
624