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 "os.h"
31 #include "profiler.h"
32 #include "runtime.h"
33 #include "scoped_thread_state_change.h"
34 #include "ScopedLocalRef.h"
35 #include "ScopedUtfChars.h"
36 #include "utils.h"
37 #include "well_known_classes.h"
38 #include "zip_archive.h"
39 
40 namespace art {
41 
42 static std::unique_ptr<std::vector<const DexFile*>>
ConvertJavaArrayToNative(JNIEnv * env,jobject arrayObject)43 ConvertJavaArrayToNative(JNIEnv* env, jobject arrayObject) {
44   jarray array = reinterpret_cast<jarray>(arrayObject);
45 
46   jsize array_size = env->GetArrayLength(array);
47   if (env->ExceptionCheck() == JNI_TRUE) {
48     return std::unique_ptr<std::vector<const DexFile*>>();
49   }
50 
51   // TODO: Optimize. On 32bit we can use an int array.
52   jboolean is_long_data_copied;
53   jlong* long_data = env->GetLongArrayElements(reinterpret_cast<jlongArray>(array),
54                                                &is_long_data_copied);
55   if (env->ExceptionCheck() == JNI_TRUE) {
56     return std::unique_ptr<std::vector<const DexFile*>>();
57   }
58 
59   std::unique_ptr<std::vector<const DexFile*>> ret(new std::vector<const DexFile*>());
60   ret->reserve(array_size);
61   for (jsize i = 0; i < array_size; ++i) {
62     ret->push_back(reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(*(long_data + i))));
63   }
64 
65   env->ReleaseLongArrayElements(reinterpret_cast<jlongArray>(array), long_data, JNI_ABORT);
66   if (env->ExceptionCheck() == JNI_TRUE) {
67     return std::unique_ptr<std::vector<const DexFile*>>();
68   }
69 
70   return ret;
71 }
72 
ConvertNativeToJavaArray(JNIEnv * env,std::vector<std::unique_ptr<const DexFile>> & vec)73 static jlongArray ConvertNativeToJavaArray(JNIEnv* env,
74                                            std::vector<std::unique_ptr<const DexFile>>& vec) {
75   size_t vec_size = vec.size();
76   jlongArray long_array = env->NewLongArray(static_cast<jsize>(vec_size));
77   if (env->ExceptionCheck() == JNI_TRUE) {
78     return nullptr;
79   }
80 
81   jboolean is_long_data_copied;
82   jlong* long_data = env->GetLongArrayElements(long_array, &is_long_data_copied);
83   if (env->ExceptionCheck() == JNI_TRUE) {
84     return nullptr;
85   }
86 
87   jlong* tmp = long_data;
88   for (auto& dex_file : vec) {
89     *tmp = reinterpret_cast<uintptr_t>(dex_file.get());
90     tmp++;
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.
117 class NullableScopedUtfChars {
118  public:
NullableScopedUtfChars(JNIEnv * env,jstring s)119   NullableScopedUtfChars(JNIEnv* env, jstring s) : mEnv(env), mString(s) {
120     mUtfChars = (s != nullptr) ? env->GetStringUTFChars(s, nullptr) : nullptr;
121   }
122 
~NullableScopedUtfChars()123   ~NullableScopedUtfChars() {
124     if (mUtfChars) {
125       mEnv->ReleaseStringUTFChars(mString, mUtfChars);
126     }
127   }
128 
c_str() const129   const char* c_str() const {
130     return mUtfChars;
131   }
132 
size() const133   size_t size() const {
134     return strlen(mUtfChars);
135   }
136 
137   // Element access.
operator [](size_t n) const138   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 
DexFile_openDexFileNative(JNIEnv * env,jclass,jstring javaSourceName,jstring javaOutputName,jint)152 static jobject DexFile_openDexFileNative(
153     JNIEnv* env, jclass, jstring javaSourceName, jstring javaOutputName, jint) {
154   ScopedUtfChars sourceName(env, javaSourceName);
155   if (sourceName.c_str() == nullptr) {
156     return 0;
157   }
158   NullableScopedUtfChars outputName(env, javaOutputName);
159   if (env->ExceptionCheck()) {
160     return 0;
161   }
162 
163   ClassLinker* linker = Runtime::Current()->GetClassLinker();
164   std::vector<std::unique_ptr<const DexFile>> dex_files;
165   std::vector<std::string> error_msgs;
166 
167   dex_files = linker->OpenDexFilesFromOat(sourceName.c_str(), outputName.c_str(), &error_msgs);
168 
169   if (!dex_files.empty()) {
170     jlongArray array = ConvertNativeToJavaArray(env, dex_files);
171     if (array == nullptr) {
172       ScopedObjectAccess soa(env);
173       for (auto& dex_file : dex_files) {
174         if (Runtime::Current()->GetClassLinker()->IsDexFileRegistered(*dex_file)) {
175           dex_file.release();
176         }
177       }
178     }
179     return array;
180   } else {
181     ScopedObjectAccess soa(env);
182     CHECK(!error_msgs.empty());
183     // The most important message is at the end. So set up nesting by going forward, which will
184     // wrap the existing exception as a cause for the following one.
185     auto it = error_msgs.begin();
186     auto itEnd = error_msgs.end();
187     for ( ; it != itEnd; ++it) {
188       ThrowWrappedIOException("%s", it->c_str());
189     }
190 
191     return nullptr;
192   }
193 }
194 
DexFile_closeDexFile(JNIEnv * env,jclass,jobject cookie)195 static void DexFile_closeDexFile(JNIEnv* env, jclass, jobject cookie) {
196   std::unique_ptr<std::vector<const DexFile*>> dex_files = ConvertJavaArrayToNative(env, cookie);
197   if (dex_files.get() == nullptr) {
198     DCHECK(env->ExceptionCheck());
199     return;
200   }
201 
202   ScopedObjectAccess soa(env);
203 
204   // The Runtime currently never unloads classes, which means any registered
205   // dex files must be kept around forever in case they are used. We
206   // accomplish this here by explicitly leaking those dex files that are
207   // registered.
208   //
209   // TODO: The Runtime should support unloading of classes and freeing of the
210   // dex files for those unloaded classes rather than leaking dex files here.
211   for (auto& dex_file : *dex_files) {
212     if (!Runtime::Current()->GetClassLinker()->IsDexFileRegistered(*dex_file)) {
213       delete dex_file;
214     }
215   }
216 }
217 
DexFile_defineClassNative(JNIEnv * env,jclass,jstring javaName,jobject javaLoader,jobject cookie)218 static jclass DexFile_defineClassNative(JNIEnv* env, jclass, jstring javaName, jobject javaLoader,
219                                         jobject cookie) {
220   std::unique_ptr<std::vector<const DexFile*>> dex_files = ConvertJavaArrayToNative(env, cookie);
221   if (dex_files.get() == nullptr) {
222     VLOG(class_linker) << "Failed to find dex_file";
223     DCHECK(env->ExceptionCheck());
224     return nullptr;
225   }
226 
227   ScopedUtfChars class_name(env, javaName);
228   if (class_name.c_str() == nullptr) {
229     VLOG(class_linker) << "Failed to find class_name";
230     return nullptr;
231   }
232   const std::string descriptor(DotToDescriptor(class_name.c_str()));
233   const size_t hash(ComputeModifiedUtf8Hash(descriptor.c_str()));
234   for (auto& dex_file : *dex_files) {
235     const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor.c_str(), hash);
236     if (dex_class_def != nullptr) {
237       ScopedObjectAccess soa(env);
238       ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
239       class_linker->RegisterDexFile(*dex_file);
240       StackHandleScope<1> hs(soa.Self());
241       Handle<mirror::ClassLoader> class_loader(
242           hs.NewHandle(soa.Decode<mirror::ClassLoader*>(javaLoader)));
243       mirror::Class* result = class_linker->DefineClass(soa.Self(), descriptor.c_str(), hash,
244                                                         class_loader, *dex_file, *dex_class_def);
245       if (result != nullptr) {
246         VLOG(class_linker) << "DexFile_defineClassNative returning " << result
247                            << " for " << class_name.c_str();
248         return soa.AddLocalReference<jclass>(result);
249       }
250     }
251   }
252   VLOG(class_linker) << "Failed to find dex_class_def " << class_name.c_str();
253   return nullptr;
254 }
255 
256 // Needed as a compare functor for sets of const char
257 struct CharPointerComparator {
operator ()art::CharPointerComparator258   bool operator()(const char *str1, const char *str2) const {
259     return strcmp(str1, str2) < 0;
260   }
261 };
262 
263 // Note: this can be an expensive call, as we sort out duplicates in MultiDex files.
DexFile_getClassNameList(JNIEnv * env,jclass,jobject cookie)264 static jobjectArray DexFile_getClassNameList(JNIEnv* env, jclass, jobject cookie) {
265   std::unique_ptr<std::vector<const DexFile*>> dex_files = ConvertJavaArrayToNative(env, cookie);
266   if (dex_files.get() == nullptr) {
267     DCHECK(env->ExceptionCheck());
268     return nullptr;
269   }
270 
271   // Push all class descriptors into a set. Use set instead of unordered_set as we want to
272   // retrieve all in the end.
273   std::set<const char*, CharPointerComparator> descriptors;
274   for (auto& dex_file : *dex_files) {
275     for (size_t i = 0; i < dex_file->NumClassDefs(); ++i) {
276       const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
277       const char* descriptor = dex_file->GetClassDescriptor(class_def);
278       descriptors.insert(descriptor);
279     }
280   }
281 
282   // Now create output array and copy the set into it.
283   jobjectArray result = env->NewObjectArray(descriptors.size(), WellKnownClasses::java_lang_String,
284                                             nullptr);
285   if (result != nullptr) {
286     auto it = descriptors.begin();
287     auto it_end = descriptors.end();
288     jsize i = 0;
289     for (; it != it_end; it++, ++i) {
290       std::string descriptor(DescriptorToDot(*it));
291       ScopedLocalRef<jstring> jdescriptor(env, env->NewStringUTF(descriptor.c_str()));
292       if (jdescriptor.get() == nullptr) {
293         return nullptr;
294       }
295       env->SetObjectArrayElement(result, i, jdescriptor.get());
296     }
297   }
298   return result;
299 }
300 
GetDexOptNeeded(JNIEnv * env,const char * filename,const char * pkgname,const char * instruction_set,const jboolean defer)301 static jint GetDexOptNeeded(JNIEnv* env, const char* filename,
302     const char* pkgname, const char* instruction_set, const jboolean defer) {
303 
304   if ((filename == nullptr) || !OS::FileExists(filename)) {
305     LOG(ERROR) << "DexFile_getDexOptNeeded file '" << filename << "' does not exist";
306     ScopedLocalRef<jclass> fnfe(env, env->FindClass("java/io/FileNotFoundException"));
307     const char* message = (filename == nullptr) ? "<empty file name>" : filename;
308     env->ThrowNew(fnfe.get(), message);
309     return OatFileAssistant::kNoDexOptNeeded;
310   }
311 
312   const InstructionSet target_instruction_set = GetInstructionSetFromString(instruction_set);
313   if (target_instruction_set == kNone) {
314     ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException"));
315     std::string message(StringPrintf("Instruction set %s is invalid.", instruction_set));
316     env->ThrowNew(iae.get(), message.c_str());
317     return 0;
318   }
319 
320   // TODO: Verify the dex location is well formed, and throw an IOException if
321   // not?
322 
323   OatFileAssistant oat_file_assistant(filename, target_instruction_set, false, pkgname);
324 
325   // Always treat elements of the bootclasspath as up-to-date.
326   if (oat_file_assistant.IsInBootClassPath()) {
327     return OatFileAssistant::kNoDexOptNeeded;
328   }
329 
330   // TODO: Checking the profile should probably be done in the GetStatus()
331   // function. We have it here because GetStatus() should not be copying
332   // profile files. But who should be copying profile files?
333   if (oat_file_assistant.OdexFileIsOutOfDate()) {
334     // Needs recompile if profile has changed significantly.
335     if (Runtime::Current()->GetProfilerOptions().IsEnabled()) {
336       if (oat_file_assistant.IsProfileChangeSignificant()) {
337         if (!defer) {
338           oat_file_assistant.CopyProfileFile();
339         }
340         return OatFileAssistant::kDex2OatNeeded;
341       } else if (oat_file_assistant.ProfileExists()
342           && !oat_file_assistant.OldProfileExists()) {
343         if (!defer) {
344           oat_file_assistant.CopyProfileFile();
345         }
346       }
347     }
348   }
349 
350   return oat_file_assistant.GetDexOptNeeded();
351 }
352 
DexFile_getDexOptNeeded(JNIEnv * env,jclass,jstring javaFilename,jstring javaPkgname,jstring javaInstructionSet,jboolean defer)353 static jint DexFile_getDexOptNeeded(JNIEnv* env, jclass, jstring javaFilename,
354     jstring javaPkgname, jstring javaInstructionSet, jboolean defer) {
355   ScopedUtfChars filename(env, javaFilename);
356   if (env->ExceptionCheck()) {
357     return 0;
358   }
359 
360   NullableScopedUtfChars pkgname(env, javaPkgname);
361 
362   ScopedUtfChars instruction_set(env, javaInstructionSet);
363   if (env->ExceptionCheck()) {
364     return 0;
365   }
366 
367   return GetDexOptNeeded(env, filename.c_str(), pkgname.c_str(),
368                          instruction_set.c_str(), defer);
369 }
370 
371 // public API, null pkgname
DexFile_isDexOptNeeded(JNIEnv * env,jclass,jstring javaFilename)372 static jboolean DexFile_isDexOptNeeded(JNIEnv* env, jclass, jstring javaFilename) {
373   const char* instruction_set = GetInstructionSetString(kRuntimeISA);
374   ScopedUtfChars filename(env, javaFilename);
375   jint status = GetDexOptNeeded(env, filename.c_str(), nullptr /* pkgname */,
376                                 instruction_set, false /* defer */);
377   return (status != OatFileAssistant::kNoDexOptNeeded) ? JNI_TRUE : JNI_FALSE;
378 }
379 
380 static JNINativeMethod gMethods[] = {
381   NATIVE_METHOD(DexFile, closeDexFile, "(Ljava/lang/Object;)V"),
382   NATIVE_METHOD(DexFile, defineClassNative,
383                 "(Ljava/lang/String;Ljava/lang/ClassLoader;Ljava/lang/Object;)Ljava/lang/Class;"),
384   NATIVE_METHOD(DexFile, getClassNameList, "(Ljava/lang/Object;)[Ljava/lang/String;"),
385   NATIVE_METHOD(DexFile, isDexOptNeeded, "(Ljava/lang/String;)Z"),
386   NATIVE_METHOD(DexFile, getDexOptNeeded,
387                 "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)I"),
388   NATIVE_METHOD(DexFile, openDexFileNative,
389                 "(Ljava/lang/String;Ljava/lang/String;I)Ljava/lang/Object;"),
390 };
391 
register_dalvik_system_DexFile(JNIEnv * env)392 void register_dalvik_system_DexFile(JNIEnv* env) {
393   REGISTER_NATIVE_METHODS("dalvik/system/DexFile");
394 }
395 
396 }  // namespace art
397