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