dalvik_system_DexFile.cc revision 04302dbb106d590ff72c0dfecda23d85b6565059
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 "base/logging.h"
20#include "base/stl_util.h"
21#include "base/stringprintf.h"
22#include "class_linker.h"
23#include "common_throws.h"
24#include "dex_file-inl.h"
25#include "jni_internal.h"
26#include "mirror/class_loader.h"
27#include "mirror/object-inl.h"
28#include "mirror/string.h"
29#include "oat_file_assistant.h"
30#include "oat_file_manager.h"
31#include "os.h"
32#include "profiler.h"
33#include "runtime.h"
34#include "scoped_thread_state_change.h"
35#include "ScopedLocalRef.h"
36#include "ScopedUtfChars.h"
37#include "utils.h"
38#include "well_known_classes.h"
39#include "zip_archive.h"
40
41namespace art {
42
43static bool ConvertJavaArrayToDexFiles(
44    JNIEnv* env,
45    jobject arrayObject,
46    /*out*/ std::vector<const DexFile*>& dex_files,
47    /*out*/ const OatFile*& oat_file) {
48  jarray array = reinterpret_cast<jarray>(arrayObject);
49
50  jsize array_size = env->GetArrayLength(array);
51  if (env->ExceptionCheck() == JNI_TRUE) {
52    return false;
53  }
54
55  // TODO: Optimize. On 32bit we can use an int array.
56  jboolean is_long_data_copied;
57  jlong* long_data = env->GetLongArrayElements(reinterpret_cast<jlongArray>(array),
58                                               &is_long_data_copied);
59  if (env->ExceptionCheck() == JNI_TRUE) {
60    return false;
61  }
62
63  oat_file = reinterpret_cast<const OatFile*>(static_cast<uintptr_t>(long_data[kOatFileIndex]));
64  dex_files.reserve(array_size - 1);
65  for (jsize i = kDexFileIndexStart; i < array_size; ++i) {
66    dex_files.push_back(reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(long_data[i])));
67  }
68
69  env->ReleaseLongArrayElements(reinterpret_cast<jlongArray>(array), long_data, JNI_ABORT);
70  return env->ExceptionCheck() != JNI_TRUE;
71}
72
73static jlongArray ConvertDexFilesToJavaArray(JNIEnv* env,
74                                             const OatFile* oat_file,
75                                             std::vector<std::unique_ptr<const DexFile>>& vec) {
76  // Add one for the oat file.
77  jlongArray long_array = env->NewLongArray(static_cast<jsize>(kDexFileIndexStart + vec.size()));
78  if (env->ExceptionCheck() == JNI_TRUE) {
79    return nullptr;
80  }
81
82  jboolean is_long_data_copied;
83  jlong* long_data = env->GetLongArrayElements(long_array, &is_long_data_copied);
84  if (env->ExceptionCheck() == JNI_TRUE) {
85    return nullptr;
86  }
87
88  long_data[kOatFileIndex] = reinterpret_cast<uintptr_t>(oat_file);
89  for (size_t i = 0; i < vec.size(); ++i) {
90    long_data[kDexFileIndexStart + i] = reinterpret_cast<uintptr_t>(vec[i].get());
91  }
92
93  env->ReleaseLongArrayElements(long_array, long_data, 0);
94  if (env->ExceptionCheck() == JNI_TRUE) {
95    return nullptr;
96  }
97
98  // Now release all the unique_ptrs.
99  for (auto& dex_file : vec) {
100    dex_file.release();
101  }
102
103  return long_array;
104}
105
106// A smart pointer that provides read-only access to a Java string's UTF chars.
107// Unlike libcore's NullableScopedUtfChars, this will *not* throw NullPointerException if
108// passed a null jstring. The correct idiom is:
109//
110//   NullableScopedUtfChars name(env, javaName);
111//   if (env->ExceptionCheck()) {
112//       return null;
113//   }
114//   // ... use name.c_str()
115//
116// TODO: rewrite to get rid of this, or change ScopedUtfChars to offer this option.
117class NullableScopedUtfChars {
118 public:
119  NullableScopedUtfChars(JNIEnv* env, jstring s) : mEnv(env), mString(s) {
120    mUtfChars = (s != nullptr) ? env->GetStringUTFChars(s, nullptr) : nullptr;
121  }
122
123  ~NullableScopedUtfChars() {
124    if (mUtfChars) {
125      mEnv->ReleaseStringUTFChars(mString, mUtfChars);
126    }
127  }
128
129  const char* c_str() const {
130    return mUtfChars;
131  }
132
133  size_t size() const {
134    return strlen(mUtfChars);
135  }
136
137  // Element access.
138  const char& operator[](size_t n) const {
139    return mUtfChars[n];
140  }
141
142 private:
143  JNIEnv* mEnv;
144  jstring mString;
145  const char* mUtfChars;
146
147  // Disallow copy and assignment.
148  NullableScopedUtfChars(const NullableScopedUtfChars&);
149  void operator=(const NullableScopedUtfChars&);
150};
151
152static jobject DexFile_openDexFileNative(JNIEnv* env,
153                                         jclass,
154                                         jstring javaSourceName,
155                                         jstring javaOutputName,
156                                         jint flags ATTRIBUTE_UNUSED,
157                                         // class_loader will be used for app images.
158                                         jobject class_loader ATTRIBUTE_UNUSED) {
159  ScopedUtfChars sourceName(env, javaSourceName);
160  if (sourceName.c_str() == nullptr) {
161    return 0;
162  }
163  NullableScopedUtfChars outputName(env, javaOutputName);
164  if (env->ExceptionCheck()) {
165    return 0;
166  }
167  Runtime* const runtime = Runtime::Current();
168  ClassLinker* linker = runtime->GetClassLinker();
169  std::vector<std::unique_ptr<const DexFile>> dex_files;
170  std::vector<std::string> error_msgs;
171  const OatFile* oat_file = nullptr;
172
173  dex_files = runtime->GetOatFileManager().OpenDexFilesFromOat(sourceName.c_str(),
174                                                               outputName.c_str(),
175                                                               /*out*/ &oat_file,
176                                                               /*out*/ &error_msgs);
177
178  if (!dex_files.empty()) {
179    jlongArray array = ConvertDexFilesToJavaArray(env, oat_file, dex_files);
180    if (array == nullptr) {
181      ScopedObjectAccess soa(env);
182      for (auto& dex_file : dex_files) {
183        if (linker->FindDexCache(soa.Self(), *dex_file, true) != nullptr) {
184          dex_file.release();
185        }
186      }
187    }
188    return array;
189  } else {
190    ScopedObjectAccess soa(env);
191    CHECK(!error_msgs.empty());
192    // The most important message is at the end. So set up nesting by going forward, which will
193    // wrap the existing exception as a cause for the following one.
194    auto it = error_msgs.begin();
195    auto itEnd = error_msgs.end();
196    for ( ; it != itEnd; ++it) {
197      ThrowWrappedIOException("%s", it->c_str());
198    }
199
200    return nullptr;
201  }
202}
203
204static jboolean DexFile_closeDexFile(JNIEnv* env, jclass, jobject cookie) {
205  std::vector<const DexFile*> dex_files;
206  const OatFile* oat_file;
207  if (!ConvertJavaArrayToDexFiles(env, cookie, dex_files, oat_file)) {
208    Thread::Current()->AssertPendingException();
209    return JNI_FALSE;
210  }
211  Runtime* const runtime = Runtime::Current();
212  bool all_deleted = true;
213  {
214    ScopedObjectAccess soa(env);
215    mirror::Object* dex_files_object = soa.Decode<mirror::Object*>(cookie);
216    mirror::LongArray* long_dex_files = dex_files_object->AsLongArray();
217    // Delete dex files associated with this dalvik.system.DexFile since there should not be running
218    // code using it. dex_files is a vector due to multidex.
219    ClassLinker* const class_linker = runtime->GetClassLinker();
220    int32_t i = kDexFileIndexStart;  // Oat file is at index 0.
221    for (const DexFile* dex_file : dex_files) {
222      if (dex_file != nullptr) {
223        // Only delete the dex file if the dex cache is not found to prevent runtime crashes if there
224        // are calls to DexFile.close while the ART DexFile is still in use.
225        if (class_linker->FindDexCache(soa.Self(), *dex_file, true) == nullptr) {
226          // Clear the element in the array so that we can call close again.
227          long_dex_files->Set(i, 0);
228          delete dex_file;
229        } else {
230          all_deleted = false;
231        }
232      }
233      ++i;
234    }
235  }
236
237  // oat_file can be null if we are running without dex2oat.
238  if (all_deleted && oat_file != nullptr) {
239    // If all of the dex files are no longer in use we can unmap the corresponding oat file.
240    VLOG(class_linker) << "Unregistering " << oat_file;
241    runtime->GetOatFileManager().UnRegisterAndDeleteOatFile(oat_file);
242  }
243  return all_deleted ? JNI_TRUE : JNI_FALSE;
244}
245
246static jclass DexFile_defineClassNative(JNIEnv* env,
247                                        jclass,
248                                        jstring javaName,
249                                        jobject javaLoader,
250                                        jobject cookie,
251                                        jobject dexFile) {
252  std::vector<const DexFile*> dex_files;
253  const OatFile* oat_file;
254  if (!ConvertJavaArrayToDexFiles(env, cookie, /*out*/ dex_files, /*out*/ oat_file)) {
255    VLOG(class_linker) << "Failed to find dex_file";
256    DCHECK(env->ExceptionCheck());
257    return nullptr;
258  }
259
260  ScopedUtfChars class_name(env, javaName);
261  if (class_name.c_str() == nullptr) {
262    VLOG(class_linker) << "Failed to find class_name";
263    return nullptr;
264  }
265  const std::string descriptor(DotToDescriptor(class_name.c_str()));
266  const size_t hash(ComputeModifiedUtf8Hash(descriptor.c_str()));
267  for (auto& dex_file : dex_files) {
268    const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor.c_str(), hash);
269    if (dex_class_def != nullptr) {
270      ScopedObjectAccess soa(env);
271      ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
272      StackHandleScope<1> hs(soa.Self());
273      Handle<mirror::ClassLoader> class_loader(
274          hs.NewHandle(soa.Decode<mirror::ClassLoader*>(javaLoader)));
275      class_linker->RegisterDexFile(
276          *dex_file,
277          class_linker->GetOrCreateAllocatorForClassLoader(class_loader.Get()));
278      mirror::Class* result = class_linker->DefineClass(soa.Self(),
279                                                        descriptor.c_str(),
280                                                        hash,
281                                                        class_loader,
282                                                        *dex_file,
283                                                        *dex_class_def);
284      // Add the used dex file. This only required for the DexFile.loadClass API since normal
285      // class loaders already keep their dex files live.
286      class_linker->InsertDexFileInToClassLoader(soa.Decode<mirror::Object*>(dexFile),
287                                                 class_loader.Get());
288      if (result != nullptr) {
289        VLOG(class_linker) << "DexFile_defineClassNative returning " << result
290                           << " for " << class_name.c_str();
291        return soa.AddLocalReference<jclass>(result);
292      }
293    }
294  }
295  VLOG(class_linker) << "Failed to find dex_class_def " << class_name.c_str();
296  return nullptr;
297}
298
299// Needed as a compare functor for sets of const char
300struct CharPointerComparator {
301  bool operator()(const char *str1, const char *str2) const {
302    return strcmp(str1, str2) < 0;
303  }
304};
305
306// Note: this can be an expensive call, as we sort out duplicates in MultiDex files.
307static jobjectArray DexFile_getClassNameList(JNIEnv* env, jclass, jobject cookie) {
308  const OatFile* oat_file = nullptr;
309  std::vector<const DexFile*> dex_files;
310  if (!ConvertJavaArrayToDexFiles(env, cookie, /*out */ dex_files, /* out */ oat_file)) {
311    DCHECK(env->ExceptionCheck());
312    return nullptr;
313  }
314
315  // Push all class descriptors into a set. Use set instead of unordered_set as we want to
316  // retrieve all in the end.
317  std::set<const char*, CharPointerComparator> descriptors;
318  for (auto& dex_file : dex_files) {
319    for (size_t i = 0; i < dex_file->NumClassDefs(); ++i) {
320      const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
321      const char* descriptor = dex_file->GetClassDescriptor(class_def);
322      descriptors.insert(descriptor);
323    }
324  }
325
326  // Now create output array and copy the set into it.
327  jobjectArray result = env->NewObjectArray(descriptors.size(),
328                                            WellKnownClasses::java_lang_String,
329                                            nullptr);
330  if (result != nullptr) {
331    auto it = descriptors.begin();
332    auto it_end = descriptors.end();
333    jsize i = 0;
334    for (; it != it_end; it++, ++i) {
335      std::string descriptor(DescriptorToDot(*it));
336      ScopedLocalRef<jstring> jdescriptor(env, env->NewStringUTF(descriptor.c_str()));
337      if (jdescriptor.get() == nullptr) {
338        return nullptr;
339      }
340      env->SetObjectArrayElement(result, i, jdescriptor.get());
341    }
342  }
343  return result;
344}
345
346static jint GetDexOptNeeded(JNIEnv* env,
347                            const char* filename,
348                            const char* pkgname,
349                            const char* instruction_set,
350                            const jboolean defer) {
351  if ((filename == nullptr) || !OS::FileExists(filename)) {
352    LOG(ERROR) << "DexFile_getDexOptNeeded file '" << filename << "' does not exist";
353    ScopedLocalRef<jclass> fnfe(env, env->FindClass("java/io/FileNotFoundException"));
354    const char* message = (filename == nullptr) ? "<empty file name>" : filename;
355    env->ThrowNew(fnfe.get(), message);
356    return OatFileAssistant::kNoDexOptNeeded;
357  }
358
359  const InstructionSet target_instruction_set = GetInstructionSetFromString(instruction_set);
360  if (target_instruction_set == kNone) {
361    ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException"));
362    std::string message(StringPrintf("Instruction set %s is invalid.", instruction_set));
363    env->ThrowNew(iae.get(), message.c_str());
364    return 0;
365  }
366
367  // TODO: Verify the dex location is well formed, and throw an IOException if
368  // not?
369
370  OatFileAssistant oat_file_assistant(filename, target_instruction_set, false, pkgname);
371
372  // Always treat elements of the bootclasspath as up-to-date.
373  if (oat_file_assistant.IsInBootClassPath()) {
374    return OatFileAssistant::kNoDexOptNeeded;
375  }
376
377  // TODO: Checking the profile should probably be done in the GetStatus()
378  // function. We have it here because GetStatus() should not be copying
379  // profile files. But who should be copying profile files?
380  if (oat_file_assistant.OdexFileIsOutOfDate()) {
381    // Needs recompile if profile has changed significantly.
382    if (Runtime::Current()->GetProfilerOptions().IsEnabled()) {
383      if (oat_file_assistant.IsProfileChangeSignificant()) {
384        if (!defer) {
385          oat_file_assistant.CopyProfileFile();
386        }
387        return OatFileAssistant::kDex2OatNeeded;
388      } else if (oat_file_assistant.ProfileExists()
389          && !oat_file_assistant.OldProfileExists()) {
390        if (!defer) {
391          oat_file_assistant.CopyProfileFile();
392        }
393      }
394    }
395  }
396
397  return oat_file_assistant.GetDexOptNeeded();
398}
399
400static jint DexFile_getDexOptNeeded(JNIEnv* env,
401                                    jclass,
402                                    jstring javaFilename,
403                                    jstring javaPkgname,
404                                    jstring javaInstructionSet,
405                                    jboolean defer) {
406  ScopedUtfChars filename(env, javaFilename);
407  if (env->ExceptionCheck()) {
408    return 0;
409  }
410
411  NullableScopedUtfChars pkgname(env, javaPkgname);
412
413  ScopedUtfChars instruction_set(env, javaInstructionSet);
414  if (env->ExceptionCheck()) {
415    return 0;
416  }
417
418  return GetDexOptNeeded(env,
419                         filename.c_str(),
420                         pkgname.c_str(),
421                         instruction_set.c_str(),
422                         defer);
423}
424
425// public API, null pkgname
426static jboolean DexFile_isDexOptNeeded(JNIEnv* env, jclass, jstring javaFilename) {
427  const char* instruction_set = GetInstructionSetString(kRuntimeISA);
428  ScopedUtfChars filename(env, javaFilename);
429  jint status = GetDexOptNeeded(env, filename.c_str(), nullptr /* pkgname */,
430                                instruction_set, false /* defer */);
431  return (status != OatFileAssistant::kNoDexOptNeeded) ? JNI_TRUE : JNI_FALSE;
432}
433
434static JNINativeMethod gMethods[] = {
435  NATIVE_METHOD(DexFile, closeDexFile, "(Ljava/lang/Object;)Z"),
436  NATIVE_METHOD(DexFile,
437                defineClassNative,
438                "(Ljava/lang/String;"
439                "Ljava/lang/ClassLoader;"
440                "Ljava/lang/Object;"
441                "Ldalvik/system/DexFile;"
442                ")Ljava/lang/Class;"),
443  NATIVE_METHOD(DexFile, getClassNameList, "(Ljava/lang/Object;)[Ljava/lang/String;"),
444  NATIVE_METHOD(DexFile, isDexOptNeeded, "(Ljava/lang/String;)Z"),
445  NATIVE_METHOD(DexFile, getDexOptNeeded,
446                "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)I"),
447  NATIVE_METHOD(DexFile, openDexFileNative,
448                "(Ljava/lang/String;Ljava/lang/String;ILjava/lang/ClassLoader;)Ljava/lang/Object;"),
449};
450
451void register_dalvik_system_DexFile(JNIEnv* env) {
452  REGISTER_NATIVE_METHODS("dalvik/system/DexFile");
453}
454
455}  // namespace art
456