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 "java_lang_VMClassLoader.h"
18 
19 #include "base/zip_archive.h"
20 #include "class_linker.h"
21 #include "dex/descriptors_names.h"
22 #include "dex/dex_file_loader.h"
23 #include "dex/utf.h"
24 #include "handle_scope-inl.h"
25 #include "jni/jni_internal.h"
26 #include "mirror/class_loader.h"
27 #include "mirror/object-inl.h"
28 #include "native_util.h"
29 #include "nativehelper/jni_macros.h"
30 #include "nativehelper/scoped_local_ref.h"
31 #include "nativehelper/scoped_utf_chars.h"
32 #include "obj_ptr.h"
33 #include "scoped_fast_native_object_access-inl.h"
34 #include "well_known_classes.h"
35 
36 namespace art {
37 
38 // A class so we can be friends with ClassLinker and access internal methods.
39 class VMClassLoader {
40  public:
LookupClass(ClassLinker * cl,Thread * self,const char * descriptor,size_t hash,ObjPtr<mirror::ClassLoader> class_loader)41   static ObjPtr<mirror::Class> LookupClass(ClassLinker* cl,
42                                            Thread* self,
43                                            const char* descriptor,
44                                            size_t hash,
45                                            ObjPtr<mirror::ClassLoader> class_loader)
46       REQUIRES(!Locks::classlinker_classes_lock_)
47       REQUIRES_SHARED(Locks::mutator_lock_) {
48     return cl->LookupClass(self, descriptor, hash, class_loader);
49   }
50 
FindClassInPathClassLoader(ClassLinker * cl,ScopedObjectAccessAlreadyRunnable & soa,Thread * self,const char * descriptor,size_t hash,Handle<mirror::ClassLoader> class_loader)51   static ObjPtr<mirror::Class> FindClassInPathClassLoader(ClassLinker* cl,
52                                                           ScopedObjectAccessAlreadyRunnable& soa,
53                                                           Thread* self,
54                                                           const char* descriptor,
55                                                           size_t hash,
56                                                           Handle<mirror::ClassLoader> class_loader)
57       REQUIRES_SHARED(Locks::mutator_lock_) {
58     ObjPtr<mirror::Class> result;
59     if (cl->FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result)) {
60       DCHECK(!self->IsExceptionPending());
61       return result;
62     }
63     if (self->IsExceptionPending()) {
64       self->ClearException();
65     }
66     return nullptr;
67   }
68 };
69 
VMClassLoader_findLoadedClass(JNIEnv * env,jclass,jobject javaLoader,jstring javaName)70 static jclass VMClassLoader_findLoadedClass(JNIEnv* env, jclass, jobject javaLoader,
71                                             jstring javaName) {
72   ScopedFastNativeObjectAccess soa(env);
73   ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(javaLoader);
74   ScopedUtfChars name(env, javaName);
75   if (name.c_str() == nullptr) {
76     return nullptr;
77   }
78   ClassLinker* cl = Runtime::Current()->GetClassLinker();
79 
80   // Compute hash once.
81   std::string descriptor(DotToDescriptor(name.c_str()));
82   const size_t descriptor_hash = ComputeModifiedUtf8Hash(descriptor.c_str());
83 
84   ObjPtr<mirror::Class> c = VMClassLoader::LookupClass(cl,
85                                                        soa.Self(),
86                                                        descriptor.c_str(),
87                                                        descriptor_hash,
88                                                        loader);
89   if (c != nullptr && c->IsResolved()) {
90     return soa.AddLocalReference<jclass>(c);
91   }
92   // If class is erroneous, throw the earlier failure, wrapped in certain cases. See b/28787733.
93   if (c != nullptr && c->IsErroneous()) {
94     cl->ThrowEarlierClassFailure(c);
95     Thread* self = soa.Self();
96     ObjPtr<mirror::Class> iae_class =
97         self->DecodeJObject(WellKnownClasses::java_lang_IllegalAccessError)->AsClass();
98     ObjPtr<mirror::Class> ncdfe_class =
99         self->DecodeJObject(WellKnownClasses::java_lang_NoClassDefFoundError)->AsClass();
100     ObjPtr<mirror::Class> exception = self->GetException()->GetClass();
101     if (exception == iae_class || exception == ncdfe_class) {
102       self->ThrowNewWrappedException("Ljava/lang/ClassNotFoundException;",
103                                      c->PrettyDescriptor().c_str());
104     }
105     return nullptr;
106   }
107 
108   // Hard-coded performance optimization: We know that all failed libcore calls to findLoadedClass
109   //                                      are followed by a call to the the classloader to actually
110   //                                      load the class.
111   if (loader != nullptr) {
112     // Try the common case.
113     StackHandleScope<1> hs(soa.Self());
114     c = VMClassLoader::FindClassInPathClassLoader(cl,
115                                                   soa,
116                                                   soa.Self(),
117                                                   descriptor.c_str(),
118                                                   descriptor_hash,
119                                                   hs.NewHandle(loader));
120     if (c != nullptr) {
121       return soa.AddLocalReference<jclass>(c);
122     }
123   }
124 
125   // The class wasn't loaded, yet, and our fast-path did not apply (e.g., we didn't understand the
126   // classloader chain).
127   return nullptr;
128 }
129 
130 /*
131  * Returns an array of entries from the boot classpath that could contain resources.
132  */
VMClassLoader_getBootClassPathEntries(JNIEnv * env,jclass)133 static jobjectArray VMClassLoader_getBootClassPathEntries(JNIEnv* env, jclass) {
134   const std::vector<const DexFile*>& path =
135       Runtime::Current()->GetClassLinker()->GetBootClassPath();
136   jobjectArray array =
137       env->NewObjectArray(path.size(), WellKnownClasses::java_lang_String, nullptr);
138   if (array == nullptr) {
139     DCHECK(env->ExceptionCheck());
140     return nullptr;
141   }
142   for (size_t i = 0; i < path.size(); ++i) {
143     const DexFile* dex_file = path[i];
144 
145     // For multidex locations, e.g., x.jar!classes2.dex, we want to look into x.jar.
146     const std::string location(DexFileLoader::GetBaseLocation(dex_file->GetLocation()));
147 
148     ScopedLocalRef<jstring> javaPath(env, env->NewStringUTF(location.c_str()));
149     if (javaPath.get() == nullptr) {
150       DCHECK(env->ExceptionCheck());
151       return nullptr;
152     }
153     env->SetObjectArrayElement(array, i, javaPath.get());
154   }
155   return array;
156 }
157 
158 static JNINativeMethod gMethods[] = {
159   FAST_NATIVE_METHOD(VMClassLoader, findLoadedClass, "(Ljava/lang/ClassLoader;Ljava/lang/String;)Ljava/lang/Class;"),
160   NATIVE_METHOD(VMClassLoader, getBootClassPathEntries, "()[Ljava/lang/String;"),
161 };
162 
register_java_lang_VMClassLoader(JNIEnv * env)163 void register_java_lang_VMClassLoader(JNIEnv* env) {
164   REGISTER_NATIVE_METHODS("java/lang/VMClassLoader");
165 }
166 
167 }  // namespace art
168