1 /*
2 * Copyright (C) 2011 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 "class.h"
18
19 #include "art_field-inl.h"
20 #include "art_method-inl.h"
21 #include "class_linker.h"
22 #include "class_loader.h"
23 #include "class-inl.h"
24 #include "dex_cache.h"
25 #include "dex_file-inl.h"
26 #include "gc/accounting/card_table-inl.h"
27 #include "handle_scope-inl.h"
28 #include "object_array-inl.h"
29 #include "object-inl.h"
30 #include "runtime.h"
31 #include "thread.h"
32 #include "throwable.h"
33 #include "utils.h"
34 #include "well_known_classes.h"
35
36 namespace art {
37 namespace mirror {
38
39 GcRoot<Class> Class::java_lang_Class_;
40
SetClassClass(Class * java_lang_Class)41 void Class::SetClassClass(Class* java_lang_Class) {
42 CHECK(java_lang_Class_.IsNull())
43 << java_lang_Class_.Read()
44 << " " << java_lang_Class;
45 CHECK(java_lang_Class != nullptr);
46 java_lang_Class_ = GcRoot<Class>(java_lang_Class);
47 }
48
ResetClass()49 void Class::ResetClass() {
50 CHECK(!java_lang_Class_.IsNull());
51 java_lang_Class_ = GcRoot<Class>(nullptr);
52 }
53
VisitRoots(RootCallback * callback,void * arg)54 void Class::VisitRoots(RootCallback* callback, void* arg) {
55 if (!java_lang_Class_.IsNull()) {
56 java_lang_Class_.VisitRoot(callback, arg, 0, kRootStickyClass);
57 }
58 }
59
SetStatus(Status new_status,Thread * self)60 void Class::SetStatus(Status new_status, Thread* self) {
61 Status old_status = GetStatus();
62 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
63 bool class_linker_initialized = class_linker != nullptr && class_linker->IsInitialized();
64 if (LIKELY(class_linker_initialized)) {
65 if (UNLIKELY(new_status <= old_status && new_status != kStatusError &&
66 new_status != kStatusRetired)) {
67 LOG(FATAL) << "Unexpected change back of class status for " << PrettyClass(this) << " "
68 << old_status << " -> " << new_status;
69 }
70 if (new_status >= kStatusResolved || old_status >= kStatusResolved) {
71 // When classes are being resolved the resolution code should hold the lock.
72 CHECK_EQ(GetLockOwnerThreadId(), self->GetThreadId())
73 << "Attempt to change status of class while not holding its lock: "
74 << PrettyClass(this) << " " << old_status << " -> " << new_status;
75 }
76 }
77 if (UNLIKELY(new_status == kStatusError)) {
78 CHECK_NE(GetStatus(), kStatusError)
79 << "Attempt to set as erroneous an already erroneous class " << PrettyClass(this);
80
81 // Stash current exception.
82 StackHandleScope<3> hs(self);
83 ThrowLocation old_throw_location;
84 Handle<mirror::Throwable> old_exception(hs.NewHandle(self->GetException(&old_throw_location)));
85 CHECK(old_exception.Get() != nullptr);
86 Handle<mirror::Object> old_throw_this_object(hs.NewHandle(old_throw_location.GetThis()));
87 Handle<mirror::ArtMethod> old_throw_method(hs.NewHandle(old_throw_location.GetMethod()));
88 uint32_t old_throw_dex_pc = old_throw_location.GetDexPc();
89 bool is_exception_reported = self->IsExceptionReportedToInstrumentation();
90 Class* eiie_class;
91 // Do't attempt to use FindClass if we have an OOM error since this can try to do more
92 // allocations and may cause infinite loops.
93 bool throw_eiie = (old_exception.Get() == nullptr);
94 if (!throw_eiie) {
95 std::string temp;
96 const char* old_exception_descriptor = old_exception->GetClass()->GetDescriptor(&temp);
97 throw_eiie = (strcmp(old_exception_descriptor, "Ljava/lang/OutOfMemoryError;") != 0);
98 }
99 if (throw_eiie) {
100 // Clear exception to call FindSystemClass.
101 self->ClearException();
102 eiie_class = Runtime::Current()->GetClassLinker()->FindSystemClass(
103 self, "Ljava/lang/ExceptionInInitializerError;");
104 CHECK(!self->IsExceptionPending());
105 // Only verification errors, not initialization problems, should set a verify error.
106 // This is to ensure that ThrowEarlierClassFailure will throw NoClassDefFoundError in that
107 // case.
108 Class* exception_class = old_exception->GetClass();
109 if (!eiie_class->IsAssignableFrom(exception_class)) {
110 SetVerifyErrorClass(exception_class);
111 }
112 }
113
114 // Restore exception.
115 ThrowLocation gc_safe_throw_location(old_throw_this_object.Get(), old_throw_method.Get(),
116 old_throw_dex_pc);
117 self->SetException(gc_safe_throw_location, old_exception.Get());
118 self->SetExceptionReportedToInstrumentation(is_exception_reported);
119 }
120 COMPILE_ASSERT(sizeof(Status) == sizeof(uint32_t), size_of_status_not_uint32);
121 if (Runtime::Current()->IsActiveTransaction()) {
122 SetField32Volatile<true>(OFFSET_OF_OBJECT_MEMBER(Class, status_), new_status);
123 } else {
124 SetField32Volatile<false>(OFFSET_OF_OBJECT_MEMBER(Class, status_), new_status);
125 }
126
127 if (!class_linker_initialized) {
128 // When the class linker is being initialized its single threaded and by definition there can be
129 // no waiters. During initialization classes may appear temporary but won't be retired as their
130 // size was statically computed.
131 } else {
132 // Classes that are being resolved or initialized need to notify waiters that the class status
133 // changed. See ClassLinker::EnsureResolved and ClassLinker::WaitForInitializeClass.
134 if (IsTemp()) {
135 // Class is a temporary one, ensure that waiters for resolution get notified of retirement
136 // so that they can grab the new version of the class from the class linker's table.
137 CHECK_LT(new_status, kStatusResolved) << PrettyDescriptor(this);
138 if (new_status == kStatusRetired || new_status == kStatusError) {
139 NotifyAll(self);
140 }
141 } else {
142 CHECK_NE(new_status, kStatusRetired);
143 if (old_status >= kStatusResolved || new_status >= kStatusResolved) {
144 NotifyAll(self);
145 }
146 }
147 }
148 }
149
SetDexCache(DexCache * new_dex_cache)150 void Class::SetDexCache(DexCache* new_dex_cache) {
151 SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), new_dex_cache);
152 }
153
SetClassSize(uint32_t new_class_size)154 void Class::SetClassSize(uint32_t new_class_size) {
155 if (kIsDebugBuild && (new_class_size < GetClassSize())) {
156 DumpClass(LOG(ERROR), kDumpClassFullDetail);
157 CHECK_GE(new_class_size, GetClassSize()) << " class=" << PrettyTypeOf(this);
158 }
159 // Not called within a transaction.
160 SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, class_size_), new_class_size);
161 }
162
163 // Return the class' name. The exact format is bizarre, but it's the specified behavior for
164 // Class.getName: keywords for primitive types, regular "[I" form for primitive arrays (so "int"
165 // but "[I"), and arrays of reference types written between "L" and ";" but with dots rather than
166 // slashes (so "java.lang.String" but "[Ljava.lang.String;"). Madness.
ComputeName(Handle<Class> h_this)167 String* Class::ComputeName(Handle<Class> h_this) {
168 String* name = h_this->GetName();
169 if (name != nullptr) {
170 return name;
171 }
172 std::string temp;
173 const char* descriptor = h_this->GetDescriptor(&temp);
174 Thread* self = Thread::Current();
175 if ((descriptor[0] != 'L') && (descriptor[0] != '[')) {
176 // The descriptor indicates that this is the class for
177 // a primitive type; special-case the return value.
178 const char* c_name = nullptr;
179 switch (descriptor[0]) {
180 case 'Z': c_name = "boolean"; break;
181 case 'B': c_name = "byte"; break;
182 case 'C': c_name = "char"; break;
183 case 'S': c_name = "short"; break;
184 case 'I': c_name = "int"; break;
185 case 'J': c_name = "long"; break;
186 case 'F': c_name = "float"; break;
187 case 'D': c_name = "double"; break;
188 case 'V': c_name = "void"; break;
189 default:
190 LOG(FATAL) << "Unknown primitive type: " << PrintableChar(descriptor[0]);
191 }
192 name = String::AllocFromModifiedUtf8(self, c_name);
193 } else {
194 // Convert the UTF-8 name to a java.lang.String. The name must use '.' to separate package
195 // components.
196 name = String::AllocFromModifiedUtf8(self, DescriptorToDot(descriptor).c_str());
197 }
198 h_this->SetName(name);
199 return name;
200 }
201
DumpClass(std::ostream & os,int flags)202 void Class::DumpClass(std::ostream& os, int flags) {
203 if ((flags & kDumpClassFullDetail) == 0) {
204 os << PrettyClass(this);
205 if ((flags & kDumpClassClassLoader) != 0) {
206 os << ' ' << GetClassLoader();
207 }
208 if ((flags & kDumpClassInitialized) != 0) {
209 os << ' ' << GetStatus();
210 }
211 os << "\n";
212 return;
213 }
214
215 Thread* self = Thread::Current();
216 StackHandleScope<2> hs(self);
217 Handle<mirror::Class> h_this(hs.NewHandle(this));
218 Handle<mirror::Class> h_super(hs.NewHandle(GetSuperClass()));
219
220 std::string temp;
221 os << "----- " << (IsInterface() ? "interface" : "class") << " "
222 << "'" << GetDescriptor(&temp) << "' cl=" << GetClassLoader() << " -----\n",
223 os << " objectSize=" << SizeOf() << " "
224 << "(" << (h_super.Get() != nullptr ? h_super->SizeOf() : -1) << " from super)\n",
225 os << StringPrintf(" access=0x%04x.%04x\n",
226 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
227 if (h_super.Get() != nullptr) {
228 os << " super='" << PrettyClass(h_super.Get()) << "' (cl=" << h_super->GetClassLoader()
229 << ")\n";
230 }
231 if (IsArrayClass()) {
232 os << " componentType=" << PrettyClass(GetComponentType()) << "\n";
233 }
234 const size_t num_direct_interfaces = NumDirectInterfaces();
235 if (num_direct_interfaces > 0) {
236 os << " interfaces (" << num_direct_interfaces << "):\n";
237 for (size_t i = 0; i < num_direct_interfaces; ++i) {
238 Class* interface = GetDirectInterface(self, h_this, i);
239 const ClassLoader* cl = interface->GetClassLoader();
240 os << StringPrintf(" %2zd: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl);
241 }
242 }
243 if (!IsLoaded()) {
244 os << " class not yet loaded";
245 } else {
246 // After this point, this may have moved due to GetDirectInterface.
247 os << " vtable (" << h_this->NumVirtualMethods() << " entries, "
248 << (h_super.Get() != nullptr ? h_super->NumVirtualMethods() : 0) << " in super):\n";
249 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
250 os << StringPrintf(" %2zd: %s\n", i,
251 PrettyMethod(h_this->GetVirtualMethodDuringLinking(i)).c_str());
252 }
253 os << " direct methods (" << h_this->NumDirectMethods() << " entries):\n";
254 for (size_t i = 0; i < h_this->NumDirectMethods(); ++i) {
255 os << StringPrintf(" %2zd: %s\n", i, PrettyMethod(h_this->GetDirectMethod(i)).c_str());
256 }
257 if (h_this->NumStaticFields() > 0) {
258 os << " static fields (" << h_this->NumStaticFields() << " entries):\n";
259 if (h_this->IsResolved() || h_this->IsErroneous()) {
260 for (size_t i = 0; i < h_this->NumStaticFields(); ++i) {
261 os << StringPrintf(" %2zd: %s\n", i, PrettyField(h_this->GetStaticField(i)).c_str());
262 }
263 } else {
264 os << " <not yet available>";
265 }
266 }
267 if (h_this->NumInstanceFields() > 0) {
268 os << " instance fields (" << h_this->NumInstanceFields() << " entries):\n";
269 if (h_this->IsResolved() || h_this->IsErroneous()) {
270 for (size_t i = 0; i < h_this->NumInstanceFields(); ++i) {
271 os << StringPrintf(" %2zd: %s\n", i, PrettyField(h_this->GetInstanceField(i)).c_str());
272 }
273 } else {
274 os << " <not yet available>";
275 }
276 }
277 }
278 }
279
SetReferenceInstanceOffsets(uint32_t new_reference_offsets)280 void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
281 if (new_reference_offsets != CLASS_WALK_SUPER) {
282 // Sanity check that the number of bits set in the reference offset bitmap
283 // agrees with the number of references
284 size_t count = 0;
285 for (Class* c = this; c != nullptr; c = c->GetSuperClass()) {
286 count += c->NumReferenceInstanceFieldsDuringLinking();
287 }
288 CHECK_EQ((size_t)POPCOUNT(new_reference_offsets), count);
289 }
290 // Not called within a transaction.
291 SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
292 new_reference_offsets);
293 }
294
SetReferenceStaticOffsets(uint32_t new_reference_offsets)295 void Class::SetReferenceStaticOffsets(uint32_t new_reference_offsets) {
296 if (new_reference_offsets != CLASS_WALK_SUPER) {
297 // Sanity check that the number of bits set in the reference offset bitmap
298 // agrees with the number of references
299 CHECK_EQ((size_t)POPCOUNT(new_reference_offsets),
300 NumReferenceStaticFieldsDuringLinking());
301 }
302 // Not called within a transaction.
303 SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, reference_static_offsets_),
304 new_reference_offsets);
305 }
306
IsInSamePackage(const StringPiece & descriptor1,const StringPiece & descriptor2)307 bool Class::IsInSamePackage(const StringPiece& descriptor1, const StringPiece& descriptor2) {
308 size_t i = 0;
309 while (descriptor1[i] != '\0' && descriptor1[i] == descriptor2[i]) {
310 ++i;
311 }
312 if (descriptor1.find('/', i) != StringPiece::npos ||
313 descriptor2.find('/', i) != StringPiece::npos) {
314 return false;
315 } else {
316 return true;
317 }
318 }
319
IsInSamePackage(Class * that)320 bool Class::IsInSamePackage(Class* that) {
321 Class* klass1 = this;
322 Class* klass2 = that;
323 if (klass1 == klass2) {
324 return true;
325 }
326 // Class loaders must match.
327 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
328 return false;
329 }
330 // Arrays are in the same package when their element classes are.
331 while (klass1->IsArrayClass()) {
332 klass1 = klass1->GetComponentType();
333 }
334 while (klass2->IsArrayClass()) {
335 klass2 = klass2->GetComponentType();
336 }
337 // trivial check again for array types
338 if (klass1 == klass2) {
339 return true;
340 }
341 // Compare the package part of the descriptor string.
342 std::string temp1, temp2;
343 return IsInSamePackage(klass1->GetDescriptor(&temp1), klass2->GetDescriptor(&temp2));
344 }
345
IsStringClass() const346 bool Class::IsStringClass() const {
347 return this == String::GetJavaLangString();
348 }
349
IsThrowableClass()350 bool Class::IsThrowableClass() {
351 return WellKnownClasses::ToClass(WellKnownClasses::java_lang_Throwable)->IsAssignableFrom(this);
352 }
353
SetClassLoader(ClassLoader * new_class_loader)354 void Class::SetClassLoader(ClassLoader* new_class_loader) {
355 if (Runtime::Current()->IsActiveTransaction()) {
356 SetFieldObject<true>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader);
357 } else {
358 SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader);
359 }
360 }
361
FindInterfaceMethod(const StringPiece & name,const StringPiece & signature)362 ArtMethod* Class::FindInterfaceMethod(const StringPiece& name, const StringPiece& signature) {
363 // Check the current class before checking the interfaces.
364 ArtMethod* method = FindDeclaredVirtualMethod(name, signature);
365 if (method != nullptr) {
366 return method;
367 }
368
369 int32_t iftable_count = GetIfTableCount();
370 IfTable* iftable = GetIfTable();
371 for (int32_t i = 0; i < iftable_count; ++i) {
372 method = iftable->GetInterface(i)->FindDeclaredVirtualMethod(name, signature);
373 if (method != nullptr) {
374 return method;
375 }
376 }
377 return nullptr;
378 }
379
FindInterfaceMethod(const StringPiece & name,const Signature & signature)380 ArtMethod* Class::FindInterfaceMethod(const StringPiece& name, const Signature& signature) {
381 // Check the current class before checking the interfaces.
382 ArtMethod* method = FindDeclaredVirtualMethod(name, signature);
383 if (method != nullptr) {
384 return method;
385 }
386
387 int32_t iftable_count = GetIfTableCount();
388 IfTable* iftable = GetIfTable();
389 for (int32_t i = 0; i < iftable_count; ++i) {
390 method = iftable->GetInterface(i)->FindDeclaredVirtualMethod(name, signature);
391 if (method != nullptr) {
392 return method;
393 }
394 }
395 return nullptr;
396 }
397
FindInterfaceMethod(const DexCache * dex_cache,uint32_t dex_method_idx)398 ArtMethod* Class::FindInterfaceMethod(const DexCache* dex_cache, uint32_t dex_method_idx) {
399 // Check the current class before checking the interfaces.
400 ArtMethod* method = FindDeclaredVirtualMethod(dex_cache, dex_method_idx);
401 if (method != nullptr) {
402 return method;
403 }
404
405 int32_t iftable_count = GetIfTableCount();
406 IfTable* iftable = GetIfTable();
407 for (int32_t i = 0; i < iftable_count; ++i) {
408 method = iftable->GetInterface(i)->FindDeclaredVirtualMethod(dex_cache, dex_method_idx);
409 if (method != nullptr) {
410 return method;
411 }
412 }
413 return nullptr;
414 }
415
FindDeclaredDirectMethod(const StringPiece & name,const StringPiece & signature)416 ArtMethod* Class::FindDeclaredDirectMethod(const StringPiece& name, const StringPiece& signature) {
417 for (size_t i = 0; i < NumDirectMethods(); ++i) {
418 ArtMethod* method = GetDirectMethod(i);
419 if (name == method->GetName() && method->GetSignature() == signature) {
420 return method;
421 }
422 }
423 return nullptr;
424 }
425
FindDeclaredDirectMethod(const StringPiece & name,const Signature & signature)426 ArtMethod* Class::FindDeclaredDirectMethod(const StringPiece& name, const Signature& signature) {
427 for (size_t i = 0; i < NumDirectMethods(); ++i) {
428 ArtMethod* method = GetDirectMethod(i);
429 if (name == method->GetName() && signature == method->GetSignature()) {
430 return method;
431 }
432 }
433 return nullptr;
434 }
435
FindDeclaredDirectMethod(const DexCache * dex_cache,uint32_t dex_method_idx)436 ArtMethod* Class::FindDeclaredDirectMethod(const DexCache* dex_cache, uint32_t dex_method_idx) {
437 if (GetDexCache() == dex_cache) {
438 for (size_t i = 0; i < NumDirectMethods(); ++i) {
439 ArtMethod* method = GetDirectMethod(i);
440 if (method->GetDexMethodIndex() == dex_method_idx) {
441 return method;
442 }
443 }
444 }
445 return nullptr;
446 }
447
FindDirectMethod(const StringPiece & name,const StringPiece & signature)448 ArtMethod* Class::FindDirectMethod(const StringPiece& name, const StringPiece& signature) {
449 for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) {
450 ArtMethod* method = klass->FindDeclaredDirectMethod(name, signature);
451 if (method != nullptr) {
452 return method;
453 }
454 }
455 return nullptr;
456 }
457
FindDirectMethod(const StringPiece & name,const Signature & signature)458 ArtMethod* Class::FindDirectMethod(const StringPiece& name, const Signature& signature) {
459 for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) {
460 ArtMethod* method = klass->FindDeclaredDirectMethod(name, signature);
461 if (method != nullptr) {
462 return method;
463 }
464 }
465 return nullptr;
466 }
467
FindDirectMethod(const DexCache * dex_cache,uint32_t dex_method_idx)468 ArtMethod* Class::FindDirectMethod(const DexCache* dex_cache, uint32_t dex_method_idx) {
469 for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) {
470 ArtMethod* method = klass->FindDeclaredDirectMethod(dex_cache, dex_method_idx);
471 if (method != nullptr) {
472 return method;
473 }
474 }
475 return nullptr;
476 }
477
FindDeclaredVirtualMethod(const StringPiece & name,const StringPiece & signature)478 ArtMethod* Class::FindDeclaredVirtualMethod(const StringPiece& name, const StringPiece& signature) {
479 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
480 ArtMethod* method = GetVirtualMethod(i);
481 if (name == method->GetName() && method->GetSignature() == signature) {
482 return method;
483 }
484 }
485 return nullptr;
486 }
487
FindDeclaredVirtualMethod(const StringPiece & name,const Signature & signature)488 ArtMethod* Class::FindDeclaredVirtualMethod(const StringPiece& name, const Signature& signature) {
489 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
490 ArtMethod* method = GetVirtualMethod(i);
491 if (name == method->GetName() && signature == method->GetSignature()) {
492 return method;
493 }
494 }
495 return nullptr;
496 }
497
FindDeclaredVirtualMethod(const DexCache * dex_cache,uint32_t dex_method_idx)498 ArtMethod* Class::FindDeclaredVirtualMethod(const DexCache* dex_cache, uint32_t dex_method_idx) {
499 if (GetDexCache() == dex_cache) {
500 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
501 ArtMethod* method = GetVirtualMethod(i);
502 if (method->GetDexMethodIndex() == dex_method_idx &&
503 // A miranda method may have a different DexCache.
504 method->GetDexCache() == dex_cache) {
505 return method;
506 }
507 }
508 }
509 return nullptr;
510 }
511
FindVirtualMethod(const StringPiece & name,const StringPiece & signature)512 ArtMethod* Class::FindVirtualMethod(const StringPiece& name, const StringPiece& signature) {
513 for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) {
514 ArtMethod* method = klass->FindDeclaredVirtualMethod(name, signature);
515 if (method != nullptr) {
516 return method;
517 }
518 }
519 return nullptr;
520 }
521
FindVirtualMethod(const StringPiece & name,const Signature & signature)522 ArtMethod* Class::FindVirtualMethod(const StringPiece& name, const Signature& signature) {
523 for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) {
524 ArtMethod* method = klass->FindDeclaredVirtualMethod(name, signature);
525 if (method != nullptr) {
526 return method;
527 }
528 }
529 return nullptr;
530 }
531
FindVirtualMethod(const DexCache * dex_cache,uint32_t dex_method_idx)532 ArtMethod* Class::FindVirtualMethod(const DexCache* dex_cache, uint32_t dex_method_idx) {
533 for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) {
534 ArtMethod* method = klass->FindDeclaredVirtualMethod(dex_cache, dex_method_idx);
535 if (method != nullptr) {
536 return method;
537 }
538 }
539 return nullptr;
540 }
541
FindClassInitializer()542 ArtMethod* Class::FindClassInitializer() {
543 for (size_t i = 0; i < NumDirectMethods(); ++i) {
544 ArtMethod* method = GetDirectMethod(i);
545 if (method->IsClassInitializer()) {
546 DCHECK_STREQ(method->GetName(), "<clinit>");
547 DCHECK_STREQ(method->GetSignature().ToString().c_str(), "()V");
548 return method;
549 }
550 }
551 return nullptr;
552 }
553
FindDeclaredInstanceField(const StringPiece & name,const StringPiece & type)554 ArtField* Class::FindDeclaredInstanceField(const StringPiece& name, const StringPiece& type) {
555 // Is the field in this class?
556 // Interfaces are not relevant because they can't contain instance fields.
557 for (size_t i = 0; i < NumInstanceFields(); ++i) {
558 ArtField* f = GetInstanceField(i);
559 if (name == f->GetName() && type == f->GetTypeDescriptor()) {
560 return f;
561 }
562 }
563 return nullptr;
564 }
565
FindDeclaredInstanceField(const DexCache * dex_cache,uint32_t dex_field_idx)566 ArtField* Class::FindDeclaredInstanceField(const DexCache* dex_cache, uint32_t dex_field_idx) {
567 if (GetDexCache() == dex_cache) {
568 for (size_t i = 0; i < NumInstanceFields(); ++i) {
569 ArtField* f = GetInstanceField(i);
570 if (f->GetDexFieldIndex() == dex_field_idx) {
571 return f;
572 }
573 }
574 }
575 return nullptr;
576 }
577
FindInstanceField(const StringPiece & name,const StringPiece & type)578 ArtField* Class::FindInstanceField(const StringPiece& name, const StringPiece& type) {
579 // Is the field in this class, or any of its superclasses?
580 // Interfaces are not relevant because they can't contain instance fields.
581 for (Class* c = this; c != nullptr; c = c->GetSuperClass()) {
582 ArtField* f = c->FindDeclaredInstanceField(name, type);
583 if (f != nullptr) {
584 return f;
585 }
586 }
587 return nullptr;
588 }
589
FindInstanceField(const DexCache * dex_cache,uint32_t dex_field_idx)590 ArtField* Class::FindInstanceField(const DexCache* dex_cache, uint32_t dex_field_idx) {
591 // Is the field in this class, or any of its superclasses?
592 // Interfaces are not relevant because they can't contain instance fields.
593 for (Class* c = this; c != nullptr; c = c->GetSuperClass()) {
594 ArtField* f = c->FindDeclaredInstanceField(dex_cache, dex_field_idx);
595 if (f != nullptr) {
596 return f;
597 }
598 }
599 return nullptr;
600 }
601
FindDeclaredStaticField(const StringPiece & name,const StringPiece & type)602 ArtField* Class::FindDeclaredStaticField(const StringPiece& name, const StringPiece& type) {
603 DCHECK(type != nullptr);
604 for (size_t i = 0; i < NumStaticFields(); ++i) {
605 ArtField* f = GetStaticField(i);
606 if (name == f->GetName() && type == f->GetTypeDescriptor()) {
607 return f;
608 }
609 }
610 return nullptr;
611 }
612
FindDeclaredStaticField(const DexCache * dex_cache,uint32_t dex_field_idx)613 ArtField* Class::FindDeclaredStaticField(const DexCache* dex_cache, uint32_t dex_field_idx) {
614 if (dex_cache == GetDexCache()) {
615 for (size_t i = 0; i < NumStaticFields(); ++i) {
616 ArtField* f = GetStaticField(i);
617 if (f->GetDexFieldIndex() == dex_field_idx) {
618 return f;
619 }
620 }
621 }
622 return nullptr;
623 }
624
FindStaticField(Thread * self,Handle<Class> klass,const StringPiece & name,const StringPiece & type)625 ArtField* Class::FindStaticField(Thread* self, Handle<Class> klass, const StringPiece& name,
626 const StringPiece& type) {
627 // Is the field in this class (or its interfaces), or any of its
628 // superclasses (or their interfaces)?
629 for (Class* k = klass.Get(); k != nullptr; k = k->GetSuperClass()) {
630 // Is the field in this class?
631 ArtField* f = k->FindDeclaredStaticField(name, type);
632 if (f != nullptr) {
633 return f;
634 }
635 // Wrap k incase it moves during GetDirectInterface.
636 StackHandleScope<1> hs(self);
637 HandleWrapper<mirror::Class> h_k(hs.NewHandleWrapper(&k));
638 // Is this field in any of this class' interfaces?
639 for (uint32_t i = 0; i < h_k->NumDirectInterfaces(); ++i) {
640 StackHandleScope<1> hs(self);
641 Handle<mirror::Class> interface(hs.NewHandle(GetDirectInterface(self, h_k, i)));
642 f = FindStaticField(self, interface, name, type);
643 if (f != nullptr) {
644 return f;
645 }
646 }
647 }
648 return nullptr;
649 }
650
FindStaticField(Thread * self,Handle<Class> klass,const DexCache * dex_cache,uint32_t dex_field_idx)651 ArtField* Class::FindStaticField(Thread* self, Handle<Class> klass, const DexCache* dex_cache,
652 uint32_t dex_field_idx) {
653 for (Class* k = klass.Get(); k != nullptr; k = k->GetSuperClass()) {
654 // Is the field in this class?
655 ArtField* f = k->FindDeclaredStaticField(dex_cache, dex_field_idx);
656 if (f != nullptr) {
657 return f;
658 }
659 // Wrap k incase it moves during GetDirectInterface.
660 StackHandleScope<1> hs(self);
661 HandleWrapper<mirror::Class> h_k(hs.NewHandleWrapper(&k));
662 // Is this field in any of this class' interfaces?
663 for (uint32_t i = 0; i < h_k->NumDirectInterfaces(); ++i) {
664 StackHandleScope<1> hs(self);
665 Handle<mirror::Class> interface(hs.NewHandle(GetDirectInterface(self, h_k, i)));
666 f = FindStaticField(self, interface, dex_cache, dex_field_idx);
667 if (f != nullptr) {
668 return f;
669 }
670 }
671 }
672 return nullptr;
673 }
674
FindField(Thread * self,Handle<Class> klass,const StringPiece & name,const StringPiece & type)675 ArtField* Class::FindField(Thread* self, Handle<Class> klass, const StringPiece& name,
676 const StringPiece& type) {
677 // Find a field using the JLS field resolution order
678 for (Class* k = klass.Get(); k != nullptr; k = k->GetSuperClass()) {
679 // Is the field in this class?
680 ArtField* f = k->FindDeclaredInstanceField(name, type);
681 if (f != nullptr) {
682 return f;
683 }
684 f = k->FindDeclaredStaticField(name, type);
685 if (f != nullptr) {
686 return f;
687 }
688 // Is this field in any of this class' interfaces?
689 StackHandleScope<1> hs(self);
690 HandleWrapper<mirror::Class> h_k(hs.NewHandleWrapper(&k));
691 for (uint32_t i = 0; i < h_k->NumDirectInterfaces(); ++i) {
692 StackHandleScope<1> hs(self);
693 Handle<mirror::Class> interface(hs.NewHandle(GetDirectInterface(self, h_k, i)));
694 f = interface->FindStaticField(self, interface, name, type);
695 if (f != nullptr) {
696 return f;
697 }
698 }
699 }
700 return nullptr;
701 }
702
SetPreverifiedFlagOnMethods(mirror::ObjectArray<mirror::ArtMethod> * methods)703 static void SetPreverifiedFlagOnMethods(mirror::ObjectArray<mirror::ArtMethod>* methods)
704 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
705 if (methods != nullptr) {
706 for (int32_t index = 0, end = methods->GetLength(); index < end; ++index) {
707 mirror::ArtMethod* method = methods->GetWithoutChecks(index);
708 DCHECK(method != nullptr);
709 if (!method->IsNative() && !method->IsAbstract()) {
710 method->SetPreverified();
711 }
712 }
713 }
714 }
715
SetPreverifiedFlagOnAllMethods()716 void Class::SetPreverifiedFlagOnAllMethods() {
717 DCHECK(IsVerified());
718 SetPreverifiedFlagOnMethods(GetDirectMethods());
719 SetPreverifiedFlagOnMethods(GetVirtualMethods());
720 }
721
GetDescriptor(std::string * storage)722 const char* Class::GetDescriptor(std::string* storage) {
723 if (IsPrimitive()) {
724 return Primitive::Descriptor(GetPrimitiveType());
725 } else if (IsArrayClass()) {
726 return GetArrayDescriptor(storage);
727 } else if (IsProxyClass()) {
728 *storage = Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(this);
729 return storage->c_str();
730 } else {
731 const DexFile& dex_file = GetDexFile();
732 const DexFile::TypeId& type_id = dex_file.GetTypeId(GetClassDef()->class_idx_);
733 return dex_file.GetTypeDescriptor(type_id);
734 }
735 }
736
GetArrayDescriptor(std::string * storage)737 const char* Class::GetArrayDescriptor(std::string* storage) {
738 std::string temp;
739 const char* elem_desc = GetComponentType()->GetDescriptor(&temp);
740 *storage = "[";
741 *storage += elem_desc;
742 return storage->c_str();
743 }
744
GetClassDef()745 const DexFile::ClassDef* Class::GetClassDef() {
746 uint16_t class_def_idx = GetDexClassDefIndex();
747 if (class_def_idx == DexFile::kDexNoIndex16) {
748 return nullptr;
749 }
750 return &GetDexFile().GetClassDef(class_def_idx);
751 }
752
NumDirectInterfaces()753 uint32_t Class::NumDirectInterfaces() {
754 if (IsPrimitive()) {
755 return 0;
756 } else if (IsArrayClass()) {
757 return 2;
758 } else if (IsProxyClass()) {
759 mirror::ObjectArray<mirror::Class>* interfaces = GetInterfaces();
760 return interfaces != nullptr ? interfaces->GetLength() : 0;
761 } else {
762 const DexFile::TypeList* interfaces = GetInterfaceTypeList();
763 if (interfaces == nullptr) {
764 return 0;
765 } else {
766 return interfaces->Size();
767 }
768 }
769 }
770
GetDirectInterfaceTypeIdx(uint32_t idx)771 uint16_t Class::GetDirectInterfaceTypeIdx(uint32_t idx) {
772 DCHECK(!IsPrimitive());
773 DCHECK(!IsArrayClass());
774 return GetInterfaceTypeList()->GetTypeItem(idx).type_idx_;
775 }
776
GetDirectInterface(Thread * self,Handle<mirror::Class> klass,uint32_t idx)777 mirror::Class* Class::GetDirectInterface(Thread* self, Handle<mirror::Class> klass, uint32_t idx) {
778 DCHECK(klass.Get() != nullptr);
779 DCHECK(!klass->IsPrimitive());
780 if (klass->IsArrayClass()) {
781 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
782 if (idx == 0) {
783 return class_linker->FindSystemClass(self, "Ljava/lang/Cloneable;");
784 } else {
785 DCHECK_EQ(1U, idx);
786 return class_linker->FindSystemClass(self, "Ljava/io/Serializable;");
787 }
788 } else if (klass->IsProxyClass()) {
789 mirror::ObjectArray<mirror::Class>* interfaces = klass.Get()->GetInterfaces();
790 DCHECK(interfaces != nullptr);
791 return interfaces->Get(idx);
792 } else {
793 uint16_t type_idx = klass->GetDirectInterfaceTypeIdx(idx);
794 mirror::Class* interface = klass->GetDexCache()->GetResolvedType(type_idx);
795 if (interface == nullptr) {
796 interface = Runtime::Current()->GetClassLinker()->ResolveType(klass->GetDexFile(), type_idx,
797 klass.Get());
798 CHECK(interface != nullptr || self->IsExceptionPending());
799 }
800 return interface;
801 }
802 }
803
GetSourceFile()804 const char* Class::GetSourceFile() {
805 const DexFile& dex_file = GetDexFile();
806 const DexFile::ClassDef* dex_class_def = GetClassDef();
807 if (dex_class_def == nullptr) {
808 // Generated classes have no class def.
809 return nullptr;
810 }
811 return dex_file.GetSourceFile(*dex_class_def);
812 }
813
GetLocation()814 std::string Class::GetLocation() {
815 mirror::DexCache* dex_cache = GetDexCache();
816 if (dex_cache != nullptr && !IsProxyClass()) {
817 return dex_cache->GetLocation()->ToModifiedUtf8();
818 }
819 // Arrays and proxies are generated and have no corresponding dex file location.
820 return "generated class";
821 }
822
GetInterfaceTypeList()823 const DexFile::TypeList* Class::GetInterfaceTypeList() {
824 const DexFile::ClassDef* class_def = GetClassDef();
825 if (class_def == nullptr) {
826 return nullptr;
827 }
828 return GetDexFile().GetInterfacesList(*class_def);
829 }
830
PopulateEmbeddedImtAndVTable()831 void Class::PopulateEmbeddedImtAndVTable() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
832 ObjectArray<ArtMethod>* table = GetImTable();
833 if (table != nullptr) {
834 for (uint32_t i = 0; i < kImtSize; i++) {
835 SetEmbeddedImTableEntry(i, table->Get(i));
836 }
837 }
838
839 table = GetVTableDuringLinking();
840 CHECK(table != nullptr) << PrettyClass(this);
841 SetEmbeddedVTableLength(table->GetLength());
842 for (int32_t i = 0; i < table->GetLength(); i++) {
843 SetEmbeddedVTableEntry(i, table->Get(i));
844 }
845
846 SetImTable(nullptr);
847 // Keep java.lang.Object class's vtable around for since it's easier
848 // to be reused by array classes during their linking.
849 if (!IsObjectClass()) {
850 SetVTable(nullptr);
851 }
852 }
853
854 // The pre-fence visitor for Class::CopyOf().
855 class CopyClassVisitor {
856 public:
CopyClassVisitor(Thread * self,Handle<mirror::Class> * orig,size_t new_length,size_t copy_bytes)857 explicit CopyClassVisitor(Thread* self, Handle<mirror::Class>* orig,
858 size_t new_length, size_t copy_bytes)
859 : self_(self), orig_(orig), new_length_(new_length),
860 copy_bytes_(copy_bytes) {
861 }
862
operator ()(Object * obj,size_t usable_size) const863 void operator()(Object* obj, size_t usable_size) const
864 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
865 UNUSED(usable_size);
866 mirror::Class* new_class_obj = obj->AsClass();
867 mirror::Object::CopyObject(self_, new_class_obj, orig_->Get(), copy_bytes_);
868 new_class_obj->SetStatus(Class::kStatusResolving, self_);
869 new_class_obj->PopulateEmbeddedImtAndVTable();
870 new_class_obj->SetClassSize(new_length_);
871 }
872
873 private:
874 Thread* const self_;
875 Handle<mirror::Class>* const orig_;
876 const size_t new_length_;
877 const size_t copy_bytes_;
878 DISALLOW_COPY_AND_ASSIGN(CopyClassVisitor);
879 };
880
CopyOf(Thread * self,int32_t new_length)881 Class* Class::CopyOf(Thread* self, int32_t new_length) {
882 DCHECK_GE(new_length, static_cast<int32_t>(sizeof(Class)));
883 // We may get copied by a compacting GC.
884 StackHandleScope<1> hs(self);
885 Handle<mirror::Class> h_this(hs.NewHandle(this));
886 gc::Heap* heap = Runtime::Current()->GetHeap();
887 // The num_bytes (3rd param) is sizeof(Class) as opposed to SizeOf()
888 // to skip copying the tail part that we will overwrite here.
889 CopyClassVisitor visitor(self, &h_this, new_length, sizeof(Class));
890
891 mirror::Object* new_class =
892 kMovingClasses
893 ? heap->AllocObject<true>(self, java_lang_Class_.Read(), new_length, visitor)
894 : heap->AllocNonMovableObject<true>(self, java_lang_Class_.Read(), new_length, visitor);
895 if (UNLIKELY(new_class == nullptr)) {
896 CHECK(self->IsExceptionPending()); // Expect an OOME.
897 return NULL;
898 }
899
900 return new_class->AsClass();
901 }
902
903 } // namespace mirror
904 } // namespace art
905