1 /*
2 * Copyright (C) 2017 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 "aot_class_linker.h"
18
19 #include "class_status.h"
20 #include "compiler_callbacks.h"
21 #include "dex/class_reference.h"
22 #include "gc/heap.h"
23 #include "handle_scope-inl.h"
24 #include "mirror/class-inl.h"
25 #include "runtime.h"
26 #include "verifier/verifier_enums.h"
27
28 namespace art {
29
AotClassLinker(InternTable * intern_table)30 AotClassLinker::AotClassLinker(InternTable* intern_table)
31 : ClassLinker(intern_table, /*fast_class_not_found_exceptions=*/ false) {}
32
~AotClassLinker()33 AotClassLinker::~AotClassLinker() {}
34
CanAllocClass()35 bool AotClassLinker::CanAllocClass() {
36 // AllocClass doesn't work under transaction, so we abort.
37 if (Runtime::Current()->IsActiveTransaction()) {
38 Runtime::Current()->AbortTransactionAndThrowAbortError(
39 Thread::Current(), "Can't resolve type within transaction.");
40 return false;
41 }
42 return ClassLinker::CanAllocClass();
43 }
44
45 // Wrap the original InitializeClass with creation of transaction when in strict mode.
InitializeClass(Thread * self,Handle<mirror::Class> klass,bool can_init_statics,bool can_init_parents)46 bool AotClassLinker::InitializeClass(Thread* self,
47 Handle<mirror::Class> klass,
48 bool can_init_statics,
49 bool can_init_parents) {
50 Runtime* const runtime = Runtime::Current();
51 bool strict_mode = runtime->IsActiveStrictTransactionMode();
52
53 DCHECK(klass != nullptr);
54 if (klass->IsInitialized() || klass->IsInitializing()) {
55 return ClassLinker::InitializeClass(self, klass, can_init_statics, can_init_parents);
56 }
57
58 // When compiling a boot image extension, do not initialize a class defined
59 // in a dex file belonging to the boot image we're compiling against.
60 // However, we must allow the initialization of TransactionAbortError,
61 // VerifyError, etc. outside of a transaction.
62 if (!strict_mode && runtime->GetHeap()->ObjectIsInBootImageSpace(klass->GetDexCache())) {
63 if (runtime->IsActiveTransaction()) {
64 runtime->AbortTransactionAndThrowAbortError(self, "Can't initialize " + klass->PrettyTypeOf()
65 + " because it is defined in a boot image dex file.");
66 return false;
67 }
68 CHECK(klass->IsThrowableClass()) << klass->PrettyDescriptor();
69 }
70
71 // When in strict_mode, don't initialize a class if it belongs to boot but not initialized.
72 if (strict_mode && klass->IsBootStrapClassLoaded()) {
73 runtime->AbortTransactionAndThrowAbortError(self, "Can't resolve "
74 + klass->PrettyTypeOf() + " because it is an uninitialized boot class.");
75 return false;
76 }
77
78 // Don't initialize klass if it's superclass is not initialized, because superclass might abort
79 // the transaction and rolled back after klass's change is commited.
80 if (strict_mode && !klass->IsInterface() && klass->HasSuperClass()) {
81 if (klass->GetSuperClass()->GetStatus() == ClassStatus::kInitializing) {
82 runtime->AbortTransactionAndThrowAbortError(self, "Can't resolve "
83 + klass->PrettyTypeOf() + " because it's superclass is not initialized.");
84 return false;
85 }
86 }
87
88 if (strict_mode) {
89 runtime->EnterTransactionMode(/*strict=*/ true, klass.Get());
90 }
91 bool success = ClassLinker::InitializeClass(self, klass, can_init_statics, can_init_parents);
92
93 if (strict_mode) {
94 if (success) {
95 // Exit Transaction if success.
96 runtime->ExitTransactionMode();
97 } else {
98 // If not successfully initialized, don't rollback immediately, leave the cleanup to compiler
99 // driver which needs abort message and exception.
100 DCHECK(self->IsExceptionPending());
101 }
102 }
103 return success;
104 }
105
PerformClassVerification(Thread * self,Handle<mirror::Class> klass,verifier::HardFailLogMode log_level,std::string * error_msg)106 verifier::FailureKind AotClassLinker::PerformClassVerification(Thread* self,
107 Handle<mirror::Class> klass,
108 verifier::HardFailLogMode log_level,
109 std::string* error_msg) {
110 Runtime* const runtime = Runtime::Current();
111 CompilerCallbacks* callbacks = runtime->GetCompilerCallbacks();
112 ClassStatus old_status = callbacks->GetPreviousClassState(
113 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()));
114 // Was it verified? Report no failure.
115 if (old_status >= ClassStatus::kVerified) {
116 return verifier::FailureKind::kNoFailure;
117 }
118 if (old_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
119 return verifier::FailureKind::kAccessChecksFailure;
120 }
121 // Does it need to be verified at runtime? Report soft failure.
122 if (old_status >= ClassStatus::kRetryVerificationAtRuntime) {
123 // Error messages from here are only reported through -verbose:class. It is not worth it to
124 // create a message.
125 return verifier::FailureKind::kSoftFailure;
126 }
127 // Do the actual work.
128 return ClassLinker::PerformClassVerification(self, klass, log_level, error_msg);
129 }
130
CanReferenceInBootImageExtension(ObjPtr<mirror::Class> klass,gc::Heap * heap)131 bool AotClassLinker::CanReferenceInBootImageExtension(ObjPtr<mirror::Class> klass, gc::Heap* heap) {
132 // Do not allow referencing a class or instance of a class defined in a dex file
133 // belonging to the boot image we're compiling against but not itself in the boot image;
134 // or a class referencing such classes as component type, superclass or interface.
135 // Allowing this could yield duplicate class objects from multiple extensions.
136
137 if (heap->ObjectIsInBootImageSpace(klass)) {
138 return true; // Already included in the boot image we're compiling against.
139 }
140
141 // Treat arrays and primitive types specially because they do not have a DexCache that we
142 // can use to check whether the dex file belongs to the boot image we're compiling against.
143 DCHECK(!klass->IsPrimitive()); // Primitive classes must be in the primary boot image.
144 if (klass->IsArrayClass()) {
145 DCHECK(heap->ObjectIsInBootImageSpace(klass->GetIfTable())); // IfTable is OK.
146 // Arrays of all dimensions are tied to the dex file of the non-array component type.
147 do {
148 klass = klass->GetComponentType();
149 } while (klass->IsArrayClass());
150 if (klass->IsPrimitive()) {
151 return false;
152 }
153 // Do not allow arrays of erroneous classes (the array class is not itself erroneous).
154 if (klass->IsErroneous()) {
155 return false;
156 }
157 }
158
159 // Check the class itself.
160 if (heap->ObjectIsInBootImageSpace(klass->GetDexCache())) {
161 return false;
162 }
163
164 // Check superclasses.
165 ObjPtr<mirror::Class> superclass = klass->GetSuperClass();
166 while (!heap->ObjectIsInBootImageSpace(superclass)) {
167 DCHECK(superclass != nullptr); // Cannot skip Object which is in the primary boot image.
168 if (heap->ObjectIsInBootImageSpace(superclass->GetDexCache())) {
169 return false;
170 }
171 superclass = superclass->GetSuperClass();
172 }
173
174 // Check IfTable. This includes direct and indirect interfaces.
175 ObjPtr<mirror::IfTable> if_table = klass->GetIfTable();
176 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
177 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
178 DCHECK(interface != nullptr);
179 if (!heap->ObjectIsInBootImageSpace(interface) &&
180 heap->ObjectIsInBootImageSpace(interface->GetDexCache())) {
181 return false;
182 }
183 }
184
185 if (kIsDebugBuild) {
186 // All virtual methods must come from classes we have already checked above.
187 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
188 ObjPtr<mirror::Class> k = klass;
189 while (!heap->ObjectIsInBootImageSpace(k)) {
190 for (auto& m : k->GetVirtualMethods(pointer_size)) {
191 ObjPtr<mirror::Class> declaring_class = m.GetDeclaringClass();
192 CHECK(heap->ObjectIsInBootImageSpace(declaring_class) ||
193 !heap->ObjectIsInBootImageSpace(declaring_class->GetDexCache()));
194 }
195 k = k->GetSuperClass();
196 }
197 }
198
199 return true;
200 }
201
SetUpdatableBootClassPackages(const std::vector<std::string> & packages)202 bool AotClassLinker::SetUpdatableBootClassPackages(const std::vector<std::string>& packages) {
203 DCHECK(updatable_boot_class_path_descriptor_prefixes_.empty());
204 // Transform package names to descriptor prefixes.
205 std::vector<std::string> prefixes;
206 prefixes.reserve(packages.size());
207 for (const std::string& package : packages) {
208 if (package.empty() || package.find('/') != std::string::npos) {
209 LOG(ERROR) << "Invalid package name: " << package;
210 return false;
211 }
212 std::string prefix = 'L' + package + '/';
213 std::replace(prefix.begin(), prefix.end(), '.', '/');
214 prefixes.push_back(std::move(prefix));
215 }
216 // Sort and remove unnecessary prefixes.
217 std::sort(prefixes.begin(), prefixes.end());
218 std::string last_prefix;
219 auto end_it = std::remove_if(
220 prefixes.begin(),
221 prefixes.end(),
222 [&last_prefix](const std::string& s) {
223 if (!last_prefix.empty() && StartsWith(s, last_prefix)) {
224 return true;
225 } else {
226 last_prefix = s;
227 return false;
228 }
229 });
230 prefixes.resize(std::distance(prefixes.begin(), end_it));
231 prefixes.shrink_to_fit();
232 updatable_boot_class_path_descriptor_prefixes_.swap(prefixes);
233 return true;
234 }
235
IsUpdatableBootClassPathDescriptor(const char * descriptor)236 bool AotClassLinker::IsUpdatableBootClassPathDescriptor(const char* descriptor) {
237 std::string_view descriptor_sv(descriptor);
238 for (const std::string& prefix : updatable_boot_class_path_descriptor_prefixes_) {
239 if (StartsWith(descriptor_sv, prefix)) {
240 return true;
241 }
242 }
243 return false;
244 }
245
246 } // namespace art
247