blob: 4d810dbce01bdb92479928a6f5f96bf732b1bdd8 [file] [log] [blame]
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001/*
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
Andreas Gampe46ee31b2016-12-14 10:11:49 -080019#include "android-base/stringprintf.h"
20
Brian Carlstromea46f952013-07-30 01:26:50 -070021#include "art_field-inl.h"
22#include "art_method-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070023#include "class-inl.h"
Alex Lightd6251582016-10-31 11:12:30 -070024#include "class_ext.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010025#include "class_linker-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080026#include "class_loader.h"
27#include "dex_cache.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070028#include "dex_file-inl.h"
David Sehr9323e6e2016-09-13 08:58:35 -070029#include "dex_file_annotations.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070030#include "gc/accounting/card_table-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070031#include "handle_scope-inl.h"
Igor Murashkin86083f72017-10-27 10:59:04 -070032#include "subtype_check.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -070033#include "method.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070034#include "object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080035#include "object-refvisitor-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070036#include "object_array-inl.h"
Alex Lightd6251582016-10-31 11:12:30 -070037#include "object_lock.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070038#include "runtime.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080039#include "thread.h"
40#include "throwable.h"
41#include "utils.h"
42#include "well_known_classes.h"
43
44namespace art {
Igor Murashkin86083f72017-10-27 10:59:04 -070045
46// TODO: move to own CC file?
47constexpr size_t BitString::kBitSizeAtPosition[BitString::kCapacity];
48constexpr size_t BitString::kCapacity;
49
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080050namespace mirror {
51
Andreas Gampe46ee31b2016-12-14 10:11:49 -080052using android::base::StringPrintf;
53
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070054GcRoot<Class> Class::java_lang_Class_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080055
Andreas Gampeee5303f2017-08-31 15:34:42 -070056constexpr Class::Status Class::kStatusRetired;
57constexpr Class::Status Class::kStatusErrorResolved;
58constexpr Class::Status Class::kStatusErrorUnresolved;
59constexpr Class::Status Class::kStatusNotReady;
60constexpr Class::Status Class::kStatusIdx;
61constexpr Class::Status Class::kStatusLoaded;
62constexpr Class::Status Class::kStatusResolving;
63constexpr Class::Status Class::kStatusResolved;
64constexpr Class::Status Class::kStatusVerifying;
65constexpr Class::Status Class::kStatusRetryVerificationAtRuntime;
66constexpr Class::Status Class::kStatusVerifyingAtRuntime;
67constexpr Class::Status Class::kStatusVerified;
68constexpr Class::Status Class::kStatusSuperclassValidated;
69constexpr Class::Status Class::kStatusInitializing;
70constexpr Class::Status Class::kStatusInitialized;
71constexpr Class::Status Class::kStatusMax;
72
Mathieu Chartier28bd2e42016-10-04 13:54:57 -070073void Class::SetClassClass(ObjPtr<Class> java_lang_Class) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070074 CHECK(java_lang_Class_.IsNull())
75 << java_lang_Class_.Read()
Hiroshi Yamauchi4f1ebc22014-06-25 14:30:41 -070076 << " " << java_lang_Class;
Brian Carlstrom004644f2014-06-18 08:34:01 -070077 CHECK(java_lang_Class != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -070078 java_lang_Class->SetClassFlags(kClassFlagClass);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070079 java_lang_Class_ = GcRoot<Class>(java_lang_Class);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080080}
81
82void Class::ResetClass() {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070083 CHECK(!java_lang_Class_.IsNull());
84 java_lang_Class_ = GcRoot<Class>(nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080085}
86
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -070087void Class::VisitRoots(RootVisitor* visitor) {
88 java_lang_Class_.VisitRootIfNonNull(visitor, RootInfo(kRootStickyClass));
Mathieu Chartierc528dba2013-11-26 12:00:11 -080089}
90
Alex Light0273ad12016-11-02 11:19:31 -070091ClassExt* Class::EnsureExtDataPresent(Thread* self) {
92 ObjPtr<ClassExt> existing(GetExtData());
93 if (!existing.IsNull()) {
94 return existing.Ptr();
95 }
96 StackHandleScope<3> hs(self);
97 // Handlerize 'this' since we are allocating here.
98 Handle<Class> h_this(hs.NewHandle(this));
99 // Clear exception so we can allocate.
100 Handle<Throwable> throwable(hs.NewHandle(self->GetException()));
101 self->ClearException();
102 // Allocate the ClassExt
103 Handle<ClassExt> new_ext(hs.NewHandle(ClassExt::Alloc(self)));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800104 if (new_ext == nullptr) {
Alex Light0273ad12016-11-02 11:19:31 -0700105 // OOM allocating the classExt.
106 // TODO Should we restore the suppressed exception?
107 self->AssertPendingOOMException();
108 return nullptr;
Andreas Gampe99babb62015-11-02 16:20:00 -0800109 } else {
Alex Light0273ad12016-11-02 11:19:31 -0700110 MemberOffset ext_offset(OFFSET_OF_OBJECT_MEMBER(Class, ext_data_));
111 bool set;
112 // Set the ext_data_ field using CAS semantics.
113 if (Runtime::Current()->IsActiveTransaction()) {
114 set = h_this->CasFieldStrongSequentiallyConsistentObject<true>(ext_offset,
115 ObjPtr<ClassExt>(nullptr),
116 new_ext.Get());
117 } else {
118 set = h_this->CasFieldStrongSequentiallyConsistentObject<false>(ext_offset,
119 ObjPtr<ClassExt>(nullptr),
120 new_ext.Get());
121 }
122 ObjPtr<ClassExt> ret(set ? new_ext.Get() : h_this->GetExtData());
123 DCHECK(!set || h_this->GetExtData() == new_ext.Get());
124 CHECK(!ret.IsNull());
125 // Restore the exception if there was one.
Andreas Gampefa4333d2017-02-14 11:10:34 -0800126 if (throwable != nullptr) {
Alex Light0273ad12016-11-02 11:19:31 -0700127 self->SetException(throwable.Get());
128 }
129 return ret.Ptr();
Andreas Gampe99babb62015-11-02 16:20:00 -0800130 }
131}
132
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700133void Class::SetStatus(Handle<Class> h_this, Status new_status, Thread* self) {
134 Status old_status = h_this->GetStatus();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700135 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
136 bool class_linker_initialized = class_linker != nullptr && class_linker->IsInitialized();
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700137 if (LIKELY(class_linker_initialized)) {
Vladimir Marko72ab6842017-01-20 19:32:50 +0000138 if (UNLIKELY(new_status <= old_status &&
139 new_status != kStatusErrorUnresolved &&
140 new_status != kStatusErrorResolved &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700141 new_status != kStatusRetired)) {
David Sehr709b0702016-10-13 09:12:37 -0700142 LOG(FATAL) << "Unexpected change back of class status for " << h_this->PrettyClass()
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700143 << " " << old_status << " -> " << new_status;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -0700144 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700145 if (new_status >= kStatusResolved || old_status >= kStatusResolved) {
146 // When classes are being resolved the resolution code should hold the lock.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700147 CHECK_EQ(h_this->GetLockOwnerThreadId(), self->GetThreadId())
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700148 << "Attempt to change status of class while not holding its lock: "
David Sehr709b0702016-10-13 09:12:37 -0700149 << h_this->PrettyClass() << " " << old_status << " -> " << new_status;
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700150 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800151 }
Vladimir Marko72ab6842017-01-20 19:32:50 +0000152 if (UNLIKELY(IsErroneous(new_status))) {
153 CHECK(!h_this->IsErroneous())
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700154 << "Attempt to set as erroneous an already erroneous class "
Vladimir Marko72ab6842017-01-20 19:32:50 +0000155 << h_this->PrettyClass()
156 << " old_status: " << old_status << " new_status: " << new_status;
157 CHECK_EQ(new_status == kStatusErrorResolved, old_status >= kStatusResolved);
Andreas Gampe31decb12015-08-24 21:09:05 -0700158 if (VLOG_IS_ON(class_linker)) {
David Sehr709b0702016-10-13 09:12:37 -0700159 LOG(ERROR) << "Setting " << h_this->PrettyDescriptor() << " to erroneous.";
Andreas Gampe31decb12015-08-24 21:09:05 -0700160 if (self->IsExceptionPending()) {
161 LOG(ERROR) << "Exception: " << self->GetException()->Dump();
162 }
163 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800164
Alex Light0273ad12016-11-02 11:19:31 -0700165 ObjPtr<ClassExt> ext(h_this->EnsureExtDataPresent(self));
166 if (!ext.IsNull()) {
167 self->AssertPendingException();
168 ext->SetVerifyError(self->GetException());
169 } else {
170 self->AssertPendingOOMException();
Alex Lightd6251582016-10-31 11:12:30 -0700171 }
172 self->AssertPendingException();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800173 }
Alex Light0273ad12016-11-02 11:19:31 -0700174
Igor Murashkin86083f72017-10-27 10:59:04 -0700175 {
176 ObjPtr<mirror::Class> h_this_ptr = h_this.Get();
177 SubtypeCheck<ObjPtr<mirror::Class>>::WriteStatus(h_this_ptr, new_status);
Mathieu Chartier93bbee02016-08-31 09:38:40 -0700178 }
179
180 // Setting the object size alloc fast path needs to be after the status write so that if the
181 // alloc path sees a valid object size, we would know that it's initialized as long as it has a
182 // load-acquire/fake dependency.
183 if (new_status == kStatusInitialized && !h_this->IsVariableSize()) {
Mathieu Chartier161db1d2016-09-01 14:06:54 -0700184 DCHECK_EQ(h_this->GetObjectSizeAllocFastPath(), std::numeric_limits<uint32_t>::max());
185 // Finalizable objects must always go slow path.
186 if (!h_this->IsFinalizable()) {
187 h_this->SetObjectSizeAllocFastPath(RoundUp(h_this->GetObjectSize(), kObjectAlignment));
Mathieu Chartier93bbee02016-08-31 09:38:40 -0700188 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100189 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700190
191 if (!class_linker_initialized) {
192 // When the class linker is being initialized its single threaded and by definition there can be
193 // no waiters. During initialization classes may appear temporary but won't be retired as their
194 // size was statically computed.
195 } else {
196 // Classes that are being resolved or initialized need to notify waiters that the class status
197 // changed. See ClassLinker::EnsureResolved and ClassLinker::WaitForInitializeClass.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700198 if (h_this->IsTemp()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700199 // Class is a temporary one, ensure that waiters for resolution get notified of retirement
200 // so that they can grab the new version of the class from the class linker's table.
David Sehr709b0702016-10-13 09:12:37 -0700201 CHECK_LT(new_status, kStatusResolved) << h_this->PrettyDescriptor();
Vladimir Marko72ab6842017-01-20 19:32:50 +0000202 if (new_status == kStatusRetired || new_status == kStatusErrorUnresolved) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700203 h_this->NotifyAll(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700204 }
205 } else {
206 CHECK_NE(new_status, kStatusRetired);
207 if (old_status >= kStatusResolved || new_status >= kStatusResolved) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700208 h_this->NotifyAll(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700209 }
210 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700211 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800212}
213
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700214void Class::SetDexCache(ObjPtr<DexCache> new_dex_cache) {
Chang Xing6d3e7682017-07-11 10:31:29 -0700215 SetFieldObjectTransaction(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), new_dex_cache);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800216}
217
Ian Rogersef7d42f2014-01-06 12:55:46 -0800218void Class::SetClassSize(uint32_t new_class_size) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700219 if (kIsDebugBuild && new_class_size < GetClassSize()) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700220 DumpClass(LOG_STREAM(FATAL_WITHOUT_ABORT), kDumpClassFullDetail);
221 LOG(FATAL_WITHOUT_ABORT) << new_class_size << " vs " << GetClassSize();
David Sehr709b0702016-10-13 09:12:37 -0700222 LOG(FATAL) << "class=" << PrettyTypeOf();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700223 }
Chang Xing6d3e7682017-07-11 10:31:29 -0700224 SetField32Transaction(OFFSET_OF_OBJECT_MEMBER(Class, class_size_), new_class_size);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800225}
226
227// Return the class' name. The exact format is bizarre, but it's the specified behavior for
228// Class.getName: keywords for primitive types, regular "[I" form for primitive arrays (so "int"
229// but "[I"), and arrays of reference types written between "L" and ";" but with dots rather than
230// slashes (so "java.lang.String" but "[Ljava.lang.String;"). Madness.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700231String* Class::ComputeName(Handle<Class> h_this) {
232 String* name = h_this->GetName();
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800233 if (name != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800234 return name;
235 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700236 std::string temp;
237 const char* descriptor = h_this->GetDescriptor(&temp);
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800238 Thread* self = Thread::Current();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800239 if ((descriptor[0] != 'L') && (descriptor[0] != '[')) {
240 // The descriptor indicates that this is the class for
241 // a primitive type; special-case the return value.
Brian Carlstrom004644f2014-06-18 08:34:01 -0700242 const char* c_name = nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800243 switch (descriptor[0]) {
244 case 'Z': c_name = "boolean"; break;
245 case 'B': c_name = "byte"; break;
246 case 'C': c_name = "char"; break;
247 case 'S': c_name = "short"; break;
248 case 'I': c_name = "int"; break;
249 case 'J': c_name = "long"; break;
250 case 'F': c_name = "float"; break;
251 case 'D': c_name = "double"; break;
252 case 'V': c_name = "void"; break;
253 default:
254 LOG(FATAL) << "Unknown primitive type: " << PrintableChar(descriptor[0]);
255 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800256 name = String::AllocFromModifiedUtf8(self, c_name);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800257 } else {
258 // Convert the UTF-8 name to a java.lang.String. The name must use '.' to separate package
259 // components.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700260 name = String::AllocFromModifiedUtf8(self, DescriptorToDot(descriptor).c_str());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800261 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700262 h_this->SetName(name);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800263 return name;
264}
265
Ian Rogersef7d42f2014-01-06 12:55:46 -0800266void Class::DumpClass(std::ostream& os, int flags) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800267 if ((flags & kDumpClassFullDetail) == 0) {
David Sehr709b0702016-10-13 09:12:37 -0700268 os << PrettyClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800269 if ((flags & kDumpClassClassLoader) != 0) {
270 os << ' ' << GetClassLoader();
271 }
272 if ((flags & kDumpClassInitialized) != 0) {
273 os << ' ' << GetStatus();
274 }
275 os << "\n";
276 return;
277 }
278
Mathieu Chartiere401d142015-04-22 13:56:20 -0700279 Thread* const self = Thread::Current();
Mathieu Chartierf8322842014-05-16 10:59:25 -0700280 StackHandleScope<2> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700281 Handle<Class> h_this(hs.NewHandle(this));
282 Handle<Class> h_super(hs.NewHandle(GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700283 auto image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Mathieu Chartierf8322842014-05-16 10:59:25 -0700284
Ian Rogers1ff3c982014-08-12 02:30:58 -0700285 std::string temp;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800286 os << "----- " << (IsInterface() ? "interface" : "class") << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -0700287 << "'" << GetDescriptor(&temp) << "' cl=" << GetClassLoader() << " -----\n",
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800288 os << " objectSize=" << SizeOf() << " "
Andreas Gampefa4333d2017-02-14 11:10:34 -0800289 << "(" << (h_super != nullptr ? h_super->SizeOf() : -1) << " from super)\n",
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800290 os << StringPrintf(" access=0x%04x.%04x\n",
291 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
Andreas Gampefa4333d2017-02-14 11:10:34 -0800292 if (h_super != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700293 os << " super='" << h_super->PrettyClass() << "' (cl=" << h_super->GetClassLoader()
Mathieu Chartierf8322842014-05-16 10:59:25 -0700294 << ")\n";
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800295 }
296 if (IsArrayClass()) {
297 os << " componentType=" << PrettyClass(GetComponentType()) << "\n";
298 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700299 const size_t num_direct_interfaces = NumDirectInterfaces();
300 if (num_direct_interfaces > 0) {
301 os << " interfaces (" << num_direct_interfaces << "):\n";
302 for (size_t i = 0; i < num_direct_interfaces; ++i) {
Vladimir Marko19a4d372016-12-08 14:41:46 +0000303 ObjPtr<Class> interface = GetDirectInterface(self, h_this.Get(), i);
Andreas Gampe16f149c2015-03-23 10:10:20 -0700304 if (interface == nullptr) {
305 os << StringPrintf(" %2zd: nullptr!\n", i);
306 } else {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700307 ObjPtr<ClassLoader> cl = interface->GetClassLoader();
308 os << StringPrintf(" %2zd: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl.Ptr());
Andreas Gampe16f149c2015-03-23 10:10:20 -0700309 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800310 }
311 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700312 if (!IsLoaded()) {
313 os << " class not yet loaded";
314 } else {
315 // After this point, this may have moved due to GetDirectInterface.
316 os << " vtable (" << h_this->NumVirtualMethods() << " entries, "
Andreas Gampefa4333d2017-02-14 11:10:34 -0800317 << (h_super != nullptr ? h_super->NumVirtualMethods() : 0) << " in super):\n";
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700318 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
David Sehr709b0702016-10-13 09:12:37 -0700319 os << StringPrintf(" %2zd: %s\n", i, ArtMethod::PrettyMethod(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700320 h_this->GetVirtualMethodDuringLinking(i, image_pointer_size)).c_str());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800321 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700322 os << " direct methods (" << h_this->NumDirectMethods() << " entries):\n";
323 for (size_t i = 0; i < h_this->NumDirectMethods(); ++i) {
David Sehr709b0702016-10-13 09:12:37 -0700324 os << StringPrintf(" %2zd: %s\n", i, ArtMethod::PrettyMethod(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700325 h_this->GetDirectMethod(i, image_pointer_size)).c_str());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700326 }
327 if (h_this->NumStaticFields() > 0) {
328 os << " static fields (" << h_this->NumStaticFields() << " entries):\n";
Vladimir Marko72ab6842017-01-20 19:32:50 +0000329 if (h_this->IsResolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700330 for (size_t i = 0; i < h_this->NumStaticFields(); ++i) {
David Sehr709b0702016-10-13 09:12:37 -0700331 os << StringPrintf(" %2zd: %s\n", i,
332 ArtField::PrettyField(h_this->GetStaticField(i)).c_str());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700333 }
334 } else {
335 os << " <not yet available>";
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800336 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700337 }
338 if (h_this->NumInstanceFields() > 0) {
339 os << " instance fields (" << h_this->NumInstanceFields() << " entries):\n";
Vladimir Marko72ab6842017-01-20 19:32:50 +0000340 if (h_this->IsResolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700341 for (size_t i = 0; i < h_this->NumInstanceFields(); ++i) {
David Sehr709b0702016-10-13 09:12:37 -0700342 os << StringPrintf(" %2zd: %s\n", i,
343 ArtField::PrettyField(h_this->GetInstanceField(i)).c_str());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700344 }
345 } else {
346 os << " <not yet available>";
347 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800348 }
349 }
350}
351
352void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700353 if (kIsDebugBuild && new_reference_offsets != kClassWalkSuper) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800354 // Sanity check that the number of bits set in the reference offset bitmap
355 // agrees with the number of references
Ian Rogerscdc1aaf2014-10-09 13:21:38 -0700356 uint32_t count = 0;
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700357 for (ObjPtr<Class> c = this; c != nullptr; c = c->GetSuperClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800358 count += c->NumReferenceInstanceFieldsDuringLinking();
359 }
Ian Rogerscdc1aaf2014-10-09 13:21:38 -0700360 // +1 for the Class in Object.
361 CHECK_EQ(static_cast<uint32_t>(POPCOUNT(new_reference_offsets)) + 1, count);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800362 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100363 // Not called within a transaction.
364 SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700365 new_reference_offsets);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800366}
367
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800368bool Class::IsInSamePackage(const StringPiece& descriptor1, const StringPiece& descriptor2) {
369 size_t i = 0;
Ian Rogers6b604a12014-09-25 15:35:37 -0700370 size_t min_length = std::min(descriptor1.size(), descriptor2.size());
371 while (i < min_length && descriptor1[i] == descriptor2[i]) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800372 ++i;
373 }
374 if (descriptor1.find('/', i) != StringPiece::npos ||
375 descriptor2.find('/', i) != StringPiece::npos) {
376 return false;
377 } else {
378 return true;
379 }
380}
381
Mathieu Chartier3398c782016-09-30 10:27:43 -0700382bool Class::IsInSamePackage(ObjPtr<Class> that) {
383 ObjPtr<Class> klass1 = this;
384 ObjPtr<Class> klass2 = that;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800385 if (klass1 == klass2) {
386 return true;
387 }
388 // Class loaders must match.
389 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
390 return false;
391 }
392 // Arrays are in the same package when their element classes are.
393 while (klass1->IsArrayClass()) {
394 klass1 = klass1->GetComponentType();
395 }
396 while (klass2->IsArrayClass()) {
397 klass2 = klass2->GetComponentType();
398 }
Anwar Ghuloum9fa3f202013-03-26 14:32:54 -0700399 // trivial check again for array types
400 if (klass1 == klass2) {
401 return true;
402 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800403 // Compare the package part of the descriptor string.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700404 std::string temp1, temp2;
405 return IsInSamePackage(klass1->GetDescriptor(&temp1), klass2->GetDescriptor(&temp2));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800406}
407
Ian Rogersef7d42f2014-01-06 12:55:46 -0800408bool Class::IsThrowableClass() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800409 return WellKnownClasses::ToClass(WellKnownClasses::java_lang_Throwable)->IsAssignableFrom(this);
410}
411
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700412void Class::SetClassLoader(ObjPtr<ClassLoader> new_class_loader) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100413 if (Runtime::Current()->IsActiveTransaction()) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700414 SetFieldObject<true>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100415 } else {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700416 SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100417 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800418}
419
Vladimir Markoba118822017-06-12 15:41:56 +0100420template <typename SignatureType>
421static inline ArtMethod* FindInterfaceMethodWithSignature(ObjPtr<Class> klass,
422 const StringPiece& name,
423 const SignatureType& signature,
424 PointerSize pointer_size)
425 REQUIRES_SHARED(Locks::mutator_lock_) {
426 // If the current class is not an interface, skip the search of its declared methods;
427 // such lookup is used only to distinguish between IncompatibleClassChangeError and
428 // NoSuchMethodError and the caller has already tried to search methods in the class.
429 if (LIKELY(klass->IsInterface())) {
430 // Search declared methods, both direct and virtual.
431 // (This lookup is used also for invoke-static on interface classes.)
432 for (ArtMethod& method : klass->GetDeclaredMethodsSlice(pointer_size)) {
433 if (method.GetName() == name && method.GetSignature() == signature) {
434 return &method;
435 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800436 }
437 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700438
Vladimir Markoba118822017-06-12 15:41:56 +0100439 // TODO: If there is a unique maximally-specific non-abstract superinterface method,
440 // we should return it, otherwise an arbitrary one can be returned.
441 ObjPtr<IfTable> iftable = klass->GetIfTable();
442 for (int32_t i = 0, iftable_count = iftable->Count(); i < iftable_count; ++i) {
443 ObjPtr<Class> iface = iftable->GetInterface(i);
444 for (ArtMethod& method : iface->GetVirtualMethodsSlice(pointer_size)) {
445 if (method.GetName() == name && method.GetSignature() == signature) {
446 return &method;
447 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700448 }
449 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800450
Vladimir Markoba118822017-06-12 15:41:56 +0100451 // Then search for public non-static methods in the java.lang.Object.
452 if (LIKELY(klass->IsInterface())) {
453 ObjPtr<Class> object_class = klass->GetSuperClass();
454 DCHECK(object_class->IsObjectClass());
455 for (ArtMethod& method : object_class->GetDeclaredMethodsSlice(pointer_size)) {
456 if (method.IsPublic() && !method.IsStatic() &&
457 method.GetName() == name && method.GetSignature() == signature) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700458 return &method;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800459 }
460 }
461 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700462 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800463}
464
Vladimir Markoba118822017-06-12 15:41:56 +0100465ArtMethod* Class::FindInterfaceMethod(const StringPiece& name,
466 const StringPiece& signature,
467 PointerSize pointer_size) {
468 return FindInterfaceMethodWithSignature(this, name, signature, pointer_size);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800469}
470
Vladimir Markoba118822017-06-12 15:41:56 +0100471ArtMethod* Class::FindInterfaceMethod(const StringPiece& name,
472 const Signature& signature,
473 PointerSize pointer_size) {
474 return FindInterfaceMethodWithSignature(this, name, signature, pointer_size);
Ian Rogersd91d6d62013-09-25 20:26:14 -0700475}
476
Vladimir Markoba118822017-06-12 15:41:56 +0100477ArtMethod* Class::FindInterfaceMethod(ObjPtr<DexCache> dex_cache,
478 uint32_t dex_method_idx,
479 PointerSize pointer_size) {
480 // We always search by name and signature, ignoring the type index in the MethodId.
481 const DexFile& dex_file = *dex_cache->GetDexFile();
482 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
483 StringPiece name = dex_file.StringDataByIdx(method_id.name_idx_);
484 const Signature signature = dex_file.GetMethodSignature(method_id);
485 return FindInterfaceMethod(name, signature, pointer_size);
486}
487
Alex Lightafb66472017-08-01 09:54:49 -0700488static inline bool IsValidInheritanceCheck(ObjPtr<mirror::Class> klass,
489 ObjPtr<mirror::Class> declaring_class)
490 REQUIRES_SHARED(Locks::mutator_lock_) {
491 if (klass->IsArrayClass()) {
492 return declaring_class->IsObjectClass();
493 } else if (klass->IsInterface()) {
494 return declaring_class->IsObjectClass() || declaring_class == klass;
495 } else {
496 return klass->IsSubClass(declaring_class);
497 }
498}
499
Vladimir Markoba118822017-06-12 15:41:56 +0100500static inline bool IsInheritedMethod(ObjPtr<mirror::Class> klass,
501 ObjPtr<mirror::Class> declaring_class,
502 ArtMethod& method)
503 REQUIRES_SHARED(Locks::mutator_lock_) {
504 DCHECK_EQ(declaring_class, method.GetDeclaringClass());
505 DCHECK_NE(klass, declaring_class);
Alex Lightafb66472017-08-01 09:54:49 -0700506 DCHECK(IsValidInheritanceCheck(klass, declaring_class));
Vladimir Markoba118822017-06-12 15:41:56 +0100507 uint32_t access_flags = method.GetAccessFlags();
508 if ((access_flags & (kAccPublic | kAccProtected)) != 0) {
509 return true;
510 }
511 if ((access_flags & kAccPrivate) != 0) {
512 return false;
513 }
514 for (; klass != declaring_class; klass = klass->GetSuperClass()) {
515 if (!klass->IsInSamePackage(declaring_class)) {
516 return false;
517 }
518 }
519 return true;
520}
521
522template <typename SignatureType>
523static inline ArtMethod* FindClassMethodWithSignature(ObjPtr<Class> this_klass,
524 const StringPiece& name,
525 const SignatureType& signature,
526 PointerSize pointer_size)
527 REQUIRES_SHARED(Locks::mutator_lock_) {
528 // Search declared methods first.
529 for (ArtMethod& method : this_klass->GetDeclaredMethodsSlice(pointer_size)) {
530 ArtMethod* np_method = method.GetInterfaceMethodIfProxy(pointer_size);
531 if (np_method->GetName() == name && np_method->GetSignature() == signature) {
532 return &method;
533 }
534 }
535
536 // Then search the superclass chain. If we find an inherited method, return it.
537 // If we find a method that's not inherited because of access restrictions,
538 // try to find a method inherited from an interface in copied methods.
539 ObjPtr<Class> klass = this_klass->GetSuperClass();
540 ArtMethod* uninherited_method = nullptr;
541 for (; klass != nullptr; klass = klass->GetSuperClass()) {
542 DCHECK(!klass->IsProxyClass());
543 for (ArtMethod& method : klass->GetDeclaredMethodsSlice(pointer_size)) {
544 if (method.GetName() == name && method.GetSignature() == signature) {
545 if (IsInheritedMethod(this_klass, klass, method)) {
546 return &method;
547 }
548 uninherited_method = &method;
549 break;
550 }
551 }
552 if (uninherited_method != nullptr) {
553 break;
554 }
555 }
556
557 // Then search copied methods.
558 // If we found a method that's not inherited, stop the search in its declaring class.
559 ObjPtr<Class> end_klass = klass;
560 DCHECK_EQ(uninherited_method != nullptr, end_klass != nullptr);
561 klass = this_klass;
562 if (UNLIKELY(klass->IsProxyClass())) {
563 DCHECK(klass->GetCopiedMethodsSlice(pointer_size).empty());
564 klass = klass->GetSuperClass();
565 }
566 for (; klass != end_klass; klass = klass->GetSuperClass()) {
567 DCHECK(!klass->IsProxyClass());
568 for (ArtMethod& method : klass->GetCopiedMethodsSlice(pointer_size)) {
569 if (method.GetName() == name && method.GetSignature() == signature) {
570 return &method; // No further check needed, copied methods are inherited by definition.
571 }
572 }
573 }
574 return uninherited_method; // Return the `uninherited_method` if any.
575}
576
577
578ArtMethod* Class::FindClassMethod(const StringPiece& name,
579 const StringPiece& signature,
580 PointerSize pointer_size) {
581 return FindClassMethodWithSignature(this, name, signature, pointer_size);
582}
583
584ArtMethod* Class::FindClassMethod(const StringPiece& name,
585 const Signature& signature,
586 PointerSize pointer_size) {
587 return FindClassMethodWithSignature(this, name, signature, pointer_size);
588}
589
590ArtMethod* Class::FindClassMethod(ObjPtr<DexCache> dex_cache,
591 uint32_t dex_method_idx,
592 PointerSize pointer_size) {
593 // FIXME: Hijacking a proxy class by a custom class loader can break this assumption.
594 DCHECK(!IsProxyClass());
595
596 // First try to find a declared method by dex_method_idx if we have a dex_cache match.
597 ObjPtr<DexCache> this_dex_cache = GetDexCache();
598 if (this_dex_cache == dex_cache) {
599 // Lookup is always performed in the class referenced by the MethodId.
600 DCHECK_EQ(dex_type_idx_, GetDexFile().GetMethodId(dex_method_idx).class_idx_.index_);
601 for (ArtMethod& method : GetDeclaredMethodsSlice(pointer_size)) {
602 if (method.GetDexMethodIndex() == dex_method_idx) {
603 return &method;
604 }
605 }
606 }
607 // If not found, we need to search by name and signature.
608 const DexFile& dex_file = *dex_cache->GetDexFile();
609 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
610 const Signature signature = dex_file.GetMethodSignature(method_id);
611 StringPiece name; // Delay strlen() until actually needed.
612 // If we do not have a dex_cache match, try to find the declared method in this class now.
613 if (this_dex_cache != dex_cache && !GetDeclaredMethodsSlice(pointer_size).empty()) {
614 DCHECK(name.empty());
615 name = dex_file.StringDataByIdx(method_id.name_idx_);
616 for (ArtMethod& method : GetDeclaredMethodsSlice(pointer_size)) {
617 if (method.GetName() == name && method.GetSignature() == signature) {
618 return &method;
619 }
620 }
621 }
622
623 // Then search the superclass chain. If we find an inherited method, return it.
624 // If we find a method that's not inherited because of access restrictions,
625 // try to find a method inherited from an interface in copied methods.
626 ArtMethod* uninherited_method = nullptr;
627 ObjPtr<Class> klass = GetSuperClass();
628 for (; klass != nullptr; klass = klass->GetSuperClass()) {
629 ArtMethod* candidate_method = nullptr;
630 ArraySlice<ArtMethod> declared_methods = klass->GetDeclaredMethodsSlice(pointer_size);
631 if (klass->GetDexCache() == dex_cache) {
632 // Matching dex_cache. We cannot compare the `dex_method_idx` anymore because
633 // the type index differs, so compare the name index and proto index.
634 for (ArtMethod& method : declared_methods) {
635 const DexFile::MethodId& cmp_method_id = dex_file.GetMethodId(method.GetDexMethodIndex());
636 if (cmp_method_id.name_idx_ == method_id.name_idx_ &&
637 cmp_method_id.proto_idx_ == method_id.proto_idx_) {
638 candidate_method = &method;
639 break;
640 }
641 }
642 } else {
643 if (!declared_methods.empty() && name.empty()) {
644 name = dex_file.StringDataByIdx(method_id.name_idx_);
645 }
646 for (ArtMethod& method : declared_methods) {
647 if (method.GetName() == name && method.GetSignature() == signature) {
648 candidate_method = &method;
649 break;
650 }
651 }
652 }
653 if (candidate_method != nullptr) {
654 if (IsInheritedMethod(this, klass, *candidate_method)) {
655 return candidate_method;
656 } else {
657 uninherited_method = candidate_method;
658 break;
659 }
660 }
661 }
662
663 // Then search copied methods.
664 // If we found a method that's not inherited, stop the search in its declaring class.
665 ObjPtr<Class> end_klass = klass;
666 DCHECK_EQ(uninherited_method != nullptr, end_klass != nullptr);
667 // After we have searched the declared methods of the super-class chain,
668 // search copied methods which can contain methods from interfaces.
669 for (klass = this; klass != end_klass; klass = klass->GetSuperClass()) {
670 ArraySlice<ArtMethod> copied_methods = klass->GetCopiedMethodsSlice(pointer_size);
671 if (!copied_methods.empty() && name.empty()) {
672 name = dex_file.StringDataByIdx(method_id.name_idx_);
673 }
674 for (ArtMethod& method : copied_methods) {
675 if (method.GetName() == name && method.GetSignature() == signature) {
676 return &method; // No further check needed, copied methods are inherited by definition.
677 }
678 }
679 }
680 return uninherited_method; // Return the `uninherited_method` if any.
681}
682
683ArtMethod* Class::FindConstructor(const StringPiece& signature, PointerSize pointer_size) {
684 // Internal helper, never called on proxy classes. We can skip GetInterfaceMethodIfProxy().
685 DCHECK(!IsProxyClass());
686 StringPiece name("<init>");
687 for (ArtMethod& method : GetDirectMethodsSliceUnchecked(pointer_size)) {
688 if (method.GetName() == name && method.GetSignature() == signature) {
689 return &method;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800690 }
691 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700692 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800693}
694
Andreas Gampe542451c2016-07-26 09:02:02 -0700695ArtMethod* Class::FindDeclaredDirectMethodByName(const StringPiece& name,
696 PointerSize pointer_size) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000697 for (auto& method : GetDirectMethods(pointer_size)) {
698 ArtMethod* const np_method = method.GetInterfaceMethodIfProxy(pointer_size);
699 if (name == np_method->GetName()) {
700 return &method;
701 }
702 }
703 return nullptr;
704}
705
Andreas Gampe542451c2016-07-26 09:02:02 -0700706ArtMethod* Class::FindDeclaredVirtualMethodByName(const StringPiece& name,
707 PointerSize pointer_size) {
Jeff Hao13e748b2015-08-25 20:44:19 +0000708 for (auto& method : GetVirtualMethods(pointer_size)) {
709 ArtMethod* const np_method = method.GetInterfaceMethodIfProxy(pointer_size);
710 if (name == np_method->GetName()) {
711 return &method;
712 }
713 }
714 return nullptr;
715}
716
Andreas Gampe542451c2016-07-26 09:02:02 -0700717ArtMethod* Class::FindVirtualMethodForInterfaceSuper(ArtMethod* method, PointerSize pointer_size) {
Alex Light705ad492015-09-21 11:36:30 -0700718 DCHECK(method->GetDeclaringClass()->IsInterface());
719 DCHECK(IsInterface()) << "Should only be called on a interface class";
720 // Check if we have one defined on this interface first. This includes searching copied ones to
721 // get any conflict methods. Conflict methods are copied into each subtype from the supertype. We
722 // don't do any indirect method checks here.
723 for (ArtMethod& iface_method : GetVirtualMethods(pointer_size)) {
724 if (method->HasSameNameAndSignature(&iface_method)) {
725 return &iface_method;
726 }
727 }
728
729 std::vector<ArtMethod*> abstract_methods;
730 // Search through the IFTable for a working version. We don't need to check for conflicts
731 // because if there was one it would appear in this classes virtual_methods_ above.
732
733 Thread* self = Thread::Current();
734 StackHandleScope<2> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700735 MutableHandle<IfTable> iftable(hs.NewHandle(GetIfTable()));
736 MutableHandle<Class> iface(hs.NewHandle<Class>(nullptr));
Alex Light705ad492015-09-21 11:36:30 -0700737 size_t iftable_count = GetIfTableCount();
738 // Find the method. We don't need to check for conflicts because they would have been in the
739 // copied virtuals of this interface. Order matters, traverse in reverse topological order; most
740 // subtypiest interfaces get visited first.
741 for (size_t k = iftable_count; k != 0;) {
742 k--;
743 DCHECK_LT(k, iftable->Count());
744 iface.Assign(iftable->GetInterface(k));
745 // Iterate through every declared method on this interface. Each direct method's name/signature
746 // is unique so the order of the inner loop doesn't matter.
747 for (auto& method_iter : iface->GetDeclaredVirtualMethods(pointer_size)) {
748 ArtMethod* current_method = &method_iter;
749 if (current_method->HasSameNameAndSignature(method)) {
750 if (current_method->IsDefault()) {
751 // Handle JLS soft errors, a default method from another superinterface tree can
752 // "override" an abstract method(s) from another superinterface tree(s). To do this,
753 // ignore any [default] method which are dominated by the abstract methods we've seen so
754 // far. Check if overridden by any in abstract_methods. We do not need to check for
755 // default_conflicts because we would hit those before we get to this loop.
756 bool overridden = false;
757 for (ArtMethod* possible_override : abstract_methods) {
758 DCHECK(possible_override->HasSameNameAndSignature(current_method));
759 if (iface->IsAssignableFrom(possible_override->GetDeclaringClass())) {
760 overridden = true;
761 break;
762 }
763 }
764 if (!overridden) {
765 return current_method;
766 }
767 } else {
768 // Is not default.
769 // This might override another default method. Just stash it for now.
770 abstract_methods.push_back(current_method);
771 }
772 }
773 }
774 }
775 // If we reach here we either never found any declaration of the method (in which case
776 // 'abstract_methods' is empty or we found no non-overriden default methods in which case
777 // 'abstract_methods' contains a number of abstract implementations of the methods. We choose one
778 // of these arbitrarily.
779 return abstract_methods.empty() ? nullptr : abstract_methods[0];
780}
781
Andreas Gampe542451c2016-07-26 09:02:02 -0700782ArtMethod* Class::FindClassInitializer(PointerSize pointer_size) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700783 for (ArtMethod& method : GetDirectMethods(pointer_size)) {
784 if (method.IsClassInitializer()) {
785 DCHECK_STREQ(method.GetName(), "<clinit>");
786 DCHECK_STREQ(method.GetSignature().ToString().c_str(), "()V");
787 return &method;
Ian Rogersd91d6d62013-09-25 20:26:14 -0700788 }
789 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700790 return nullptr;
Ian Rogersd91d6d62013-09-25 20:26:14 -0700791}
792
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700793// Custom binary search to avoid double comparisons from std::binary_search.
794static ArtField* FindFieldByNameAndType(LengthPrefixedArray<ArtField>* fields,
795 const StringPiece& name,
796 const StringPiece& type)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700797 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700798 if (fields == nullptr) {
799 return nullptr;
800 }
801 size_t low = 0;
Vladimir Marko35831e82015-09-11 11:59:18 +0100802 size_t high = fields->size();
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700803 ArtField* ret = nullptr;
804 while (low < high) {
805 size_t mid = (low + high) / 2;
806 ArtField& field = fields->At(mid);
807 // Fields are sorted by class, then name, then type descriptor. This is verified in dex file
808 // verifier. There can be multiple fields with the same in the same class name due to proguard.
809 int result = StringPiece(field.GetName()).Compare(name);
810 if (result == 0) {
811 result = StringPiece(field.GetTypeDescriptor()).Compare(type);
812 }
813 if (result < 0) {
814 low = mid + 1;
815 } else if (result > 0) {
816 high = mid;
817 } else {
818 ret = &field;
819 break;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800820 }
821 }
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700822 if (kIsDebugBuild) {
823 ArtField* found = nullptr;
824 for (ArtField& field : MakeIterationRangeFromLengthPrefixedArray(fields)) {
825 if (name == field.GetName() && type == field.GetTypeDescriptor()) {
826 found = &field;
827 break;
828 }
829 }
David Sehr709b0702016-10-13 09:12:37 -0700830 CHECK_EQ(found, ret) << "Found " << found->PrettyField() << " vs " << ret->PrettyField();
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700831 }
832 return ret;
833}
834
835ArtField* Class::FindDeclaredInstanceField(const StringPiece& name, const StringPiece& type) {
836 // Binary search by name. Interfaces are not relevant because they can't contain instance fields.
837 return FindFieldByNameAndType(GetIFieldsPtr(), name, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800838}
839
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700840ArtField* Class::FindDeclaredInstanceField(ObjPtr<DexCache> dex_cache, uint32_t dex_field_idx) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800841 if (GetDexCache() == dex_cache) {
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700842 for (ArtField& field : GetIFields()) {
843 if (field.GetDexFieldIndex() == dex_field_idx) {
844 return &field;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800845 }
846 }
847 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700848 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800849}
850
Brian Carlstromea46f952013-07-30 01:26:50 -0700851ArtField* Class::FindInstanceField(const StringPiece& name, const StringPiece& type) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800852 // Is the field in this class, or any of its superclasses?
853 // Interfaces are not relevant because they can't contain instance fields.
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700854 for (ObjPtr<Class> c = this; c != nullptr; c = c->GetSuperClass()) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700855 ArtField* f = c->FindDeclaredInstanceField(name, type);
Brian Carlstrom004644f2014-06-18 08:34:01 -0700856 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800857 return f;
858 }
859 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700860 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800861}
862
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700863ArtField* Class::FindInstanceField(ObjPtr<DexCache> dex_cache, uint32_t dex_field_idx) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800864 // Is the field in this class, or any of its superclasses?
865 // Interfaces are not relevant because they can't contain instance fields.
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700866 for (ObjPtr<Class> c = this; c != nullptr; c = c->GetSuperClass()) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700867 ArtField* f = c->FindDeclaredInstanceField(dex_cache, dex_field_idx);
Brian Carlstrom004644f2014-06-18 08:34:01 -0700868 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800869 return f;
870 }
871 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700872 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800873}
874
Brian Carlstromea46f952013-07-30 01:26:50 -0700875ArtField* Class::FindDeclaredStaticField(const StringPiece& name, const StringPiece& type) {
Brian Carlstrom004644f2014-06-18 08:34:01 -0700876 DCHECK(type != nullptr);
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700877 return FindFieldByNameAndType(GetSFieldsPtr(), name, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800878}
879
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700880ArtField* Class::FindDeclaredStaticField(ObjPtr<DexCache> dex_cache, uint32_t dex_field_idx) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800881 if (dex_cache == GetDexCache()) {
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700882 for (ArtField& field : GetSFields()) {
883 if (field.GetDexFieldIndex() == dex_field_idx) {
884 return &field;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800885 }
886 }
887 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700888 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800889}
890
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700891ArtField* Class::FindStaticField(Thread* self,
Vladimir Marko19a4d372016-12-08 14:41:46 +0000892 ObjPtr<Class> klass,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700893 const StringPiece& name,
Mathieu Chartierf8322842014-05-16 10:59:25 -0700894 const StringPiece& type) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800895 // Is the field in this class (or its interfaces), or any of its
896 // superclasses (or their interfaces)?
Vladimir Marko19a4d372016-12-08 14:41:46 +0000897 for (ObjPtr<Class> k = klass; k != nullptr; k = k->GetSuperClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800898 // Is the field in this class?
Brian Carlstromea46f952013-07-30 01:26:50 -0700899 ArtField* f = k->FindDeclaredStaticField(name, type);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700900 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800901 return f;
902 }
903 // Is this field in any of this class' interfaces?
Vladimir Marko19a4d372016-12-08 14:41:46 +0000904 for (uint32_t i = 0, num_interfaces = k->NumDirectInterfaces(); i != num_interfaces; ++i) {
905 ObjPtr<Class> interface = GetDirectInterface(self, k, i);
906 DCHECK(interface != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700907 f = FindStaticField(self, interface, name, type);
908 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800909 return f;
910 }
911 }
912 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700913 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800914}
915
Vladimir Markobb268b12016-06-30 15:52:56 +0100916ArtField* Class::FindStaticField(Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700917 ObjPtr<Class> klass,
918 ObjPtr<DexCache> dex_cache,
Mathieu Chartierf8322842014-05-16 10:59:25 -0700919 uint32_t dex_field_idx) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700920 for (ObjPtr<Class> k = klass; k != nullptr; k = k->GetSuperClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800921 // Is the field in this class?
Brian Carlstromea46f952013-07-30 01:26:50 -0700922 ArtField* f = k->FindDeclaredStaticField(dex_cache, dex_field_idx);
Brian Carlstrom004644f2014-06-18 08:34:01 -0700923 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800924 return f;
925 }
Vladimir Markobb268b12016-06-30 15:52:56 +0100926 // Though GetDirectInterface() should not cause thread suspension when called
927 // from here, it takes a Handle as an argument, so we need to wrap `k`.
Mathieu Chartier268764d2016-09-13 12:09:38 -0700928 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800929 // Is this field in any of this class' interfaces?
Vladimir Marko19a4d372016-12-08 14:41:46 +0000930 for (uint32_t i = 0, num_interfaces = k->NumDirectInterfaces(); i != num_interfaces; ++i) {
931 ObjPtr<Class> interface = GetDirectInterface(self, k, i);
932 DCHECK(interface != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700933 f = FindStaticField(self, interface, dex_cache, dex_field_idx);
934 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800935 return f;
936 }
937 }
938 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700939 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800940}
941
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700942ArtField* Class::FindField(Thread* self,
Vladimir Marko19a4d372016-12-08 14:41:46 +0000943 ObjPtr<Class> klass,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700944 const StringPiece& name,
Mathieu Chartierf8322842014-05-16 10:59:25 -0700945 const StringPiece& type) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800946 // Find a field using the JLS field resolution order
Vladimir Marko19a4d372016-12-08 14:41:46 +0000947 for (ObjPtr<Class> k = klass; k != nullptr; k = k->GetSuperClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800948 // Is the field in this class?
Brian Carlstromea46f952013-07-30 01:26:50 -0700949 ArtField* f = k->FindDeclaredInstanceField(name, type);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700950 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800951 return f;
952 }
953 f = k->FindDeclaredStaticField(name, type);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700954 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800955 return f;
956 }
957 // Is this field in any of this class' interfaces?
Vladimir Marko19a4d372016-12-08 14:41:46 +0000958 for (uint32_t i = 0, num_interfaces = k->NumDirectInterfaces(); i != num_interfaces; ++i) {
959 ObjPtr<Class> interface = GetDirectInterface(self, k, i);
960 DCHECK(interface != nullptr);
961 f = FindStaticField(self, interface, name, type);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700962 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800963 return f;
964 }
965 }
966 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700967 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800968}
969
Andreas Gampe542451c2016-07-26 09:02:02 -0700970void Class::SetSkipAccessChecksFlagOnAllMethods(PointerSize pointer_size) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700971 DCHECK(IsVerified());
Alex Lighte64300b2015-12-15 15:02:47 -0800972 for (auto& m : GetMethods(pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -0700973 if (!m.IsNative() && m.IsInvokable()) {
Igor Murashkindf707e42016-02-02 16:56:50 -0800974 m.SetSkipAccessChecks();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700975 }
976 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +0200977}
978
Ian Rogers1ff3c982014-08-12 02:30:58 -0700979const char* Class::GetDescriptor(std::string* storage) {
980 if (IsPrimitive()) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700981 return Primitive::Descriptor(GetPrimitiveType());
Ian Rogers1ff3c982014-08-12 02:30:58 -0700982 } else if (IsArrayClass()) {
983 return GetArrayDescriptor(storage);
Nicolas Geoffray3a090922015-11-24 09:17:30 +0000984 } else if (IsProxyClass()) {
985 *storage = Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(this);
Ian Rogers1ff3c982014-08-12 02:30:58 -0700986 return storage->c_str();
Mathieu Chartierf8322842014-05-16 10:59:25 -0700987 } else {
988 const DexFile& dex_file = GetDexFile();
989 const DexFile::TypeId& type_id = dex_file.GetTypeId(GetClassDef()->class_idx_);
990 return dex_file.GetTypeDescriptor(type_id);
991 }
992}
993
Ian Rogers1ff3c982014-08-12 02:30:58 -0700994const char* Class::GetArrayDescriptor(std::string* storage) {
995 std::string temp;
996 const char* elem_desc = GetComponentType()->GetDescriptor(&temp);
997 *storage = "[";
998 *storage += elem_desc;
999 return storage->c_str();
Mathieu Chartierf8322842014-05-16 10:59:25 -07001000}
1001
1002const DexFile::ClassDef* Class::GetClassDef() {
1003 uint16_t class_def_idx = GetDexClassDefIndex();
1004 if (class_def_idx == DexFile::kDexNoIndex16) {
1005 return nullptr;
1006 }
1007 return &GetDexFile().GetClassDef(class_def_idx);
1008}
1009
Andreas Gampea5b09a62016-11-17 15:21:22 -08001010dex::TypeIndex Class::GetDirectInterfaceTypeIdx(uint32_t idx) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001011 DCHECK(!IsPrimitive());
1012 DCHECK(!IsArrayClass());
1013 return GetInterfaceTypeList()->GetTypeItem(idx).type_idx_;
1014}
1015
Vladimir Marko19a4d372016-12-08 14:41:46 +00001016ObjPtr<Class> Class::GetDirectInterface(Thread* self, ObjPtr<Class> klass, uint32_t idx) {
1017 DCHECK(klass != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07001018 DCHECK(!klass->IsPrimitive());
1019 if (klass->IsArrayClass()) {
1020 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Vladimir Marko19a4d372016-12-08 14:41:46 +00001021 // Use ClassLinker::LookupClass(); avoid poisoning ObjPtr<>s by ClassLinker::FindSystemClass().
1022 ObjPtr<Class> interface;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001023 if (idx == 0) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001024 interface = class_linker->LookupClass(self, "Ljava/lang/Cloneable;", nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07001025 } else {
1026 DCHECK_EQ(1U, idx);
Vladimir Marko19a4d372016-12-08 14:41:46 +00001027 interface = class_linker->LookupClass(self, "Ljava/io/Serializable;", nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07001028 }
Vladimir Marko19a4d372016-12-08 14:41:46 +00001029 DCHECK(interface != nullptr);
1030 return interface;
Nicolas Geoffray3a090922015-11-24 09:17:30 +00001031 } else if (klass->IsProxyClass()) {
Narayan Kamath6b2dc312017-03-14 13:26:12 +00001032 ObjPtr<ObjectArray<Class>> interfaces = klass->GetProxyInterfaces();
Mathieu Chartierf8322842014-05-16 10:59:25 -07001033 DCHECK(interfaces != nullptr);
1034 return interfaces->Get(idx);
1035 } else {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001036 dex::TypeIndex type_idx = klass->GetDirectInterfaceTypeIdx(idx);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001037 ObjPtr<Class> interface = ClassLinker::LookupResolvedType(
1038 type_idx, klass->GetDexCache(), klass->GetClassLoader());
Mathieu Chartierf8322842014-05-16 10:59:25 -07001039 return interface;
1040 }
1041}
1042
Vladimir Marko19a4d372016-12-08 14:41:46 +00001043ObjPtr<Class> Class::ResolveDirectInterface(Thread* self, Handle<Class> klass, uint32_t idx) {
1044 ObjPtr<Class> interface = GetDirectInterface(self, klass.Get(), idx);
1045 if (interface == nullptr) {
1046 DCHECK(!klass->IsArrayClass());
1047 DCHECK(!klass->IsProxyClass());
1048 dex::TypeIndex type_idx = klass->GetDirectInterfaceTypeIdx(idx);
1049 interface = Runtime::Current()->GetClassLinker()->ResolveType(klass->GetDexFile(),
1050 type_idx,
1051 klass.Get());
1052 CHECK(interface != nullptr || self->IsExceptionPending());
1053 }
1054 return interface;
1055}
1056
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001057ObjPtr<Class> Class::GetCommonSuperClass(Handle<Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08001058 DCHECK(klass != nullptr);
Calin Juravle52503d82015-11-11 16:58:31 +00001059 DCHECK(!klass->IsInterface());
1060 DCHECK(!IsInterface());
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001061 ObjPtr<Class> common_super_class = this;
Calin Juravle52503d82015-11-11 16:58:31 +00001062 while (!common_super_class->IsAssignableFrom(klass.Get())) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001063 ObjPtr<Class> old_common = common_super_class;
Aart Bik22deed02016-04-04 14:19:01 -07001064 common_super_class = old_common->GetSuperClass();
David Sehr709b0702016-10-13 09:12:37 -07001065 DCHECK(common_super_class != nullptr) << old_common->PrettyClass();
Calin Juravle52503d82015-11-11 16:58:31 +00001066 }
Calin Juravle52503d82015-11-11 16:58:31 +00001067 return common_super_class;
1068}
1069
Mathieu Chartierf8322842014-05-16 10:59:25 -07001070const char* Class::GetSourceFile() {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001071 const DexFile& dex_file = GetDexFile();
1072 const DexFile::ClassDef* dex_class_def = GetClassDef();
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001073 if (dex_class_def == nullptr) {
1074 // Generated classes have no class def.
1075 return nullptr;
1076 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001077 return dex_file.GetSourceFile(*dex_class_def);
1078}
1079
1080std::string Class::GetLocation() {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001081 ObjPtr<DexCache> dex_cache = GetDexCache();
Nicolas Geoffray3a090922015-11-24 09:17:30 +00001082 if (dex_cache != nullptr && !IsProxyClass()) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001083 return dex_cache->GetLocation()->ToModifiedUtf8();
1084 }
1085 // Arrays and proxies are generated and have no corresponding dex file location.
1086 return "generated class";
1087}
1088
1089const DexFile::TypeList* Class::GetInterfaceTypeList() {
1090 const DexFile::ClassDef* class_def = GetClassDef();
1091 if (class_def == nullptr) {
1092 return nullptr;
1093 }
1094 return GetDexFile().GetInterfacesList(*class_def);
1095}
1096
Andreas Gampe542451c2016-07-26 09:02:02 -07001097void Class::PopulateEmbeddedVTable(PointerSize pointer_size) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001098 PointerArray* table = GetVTableDuringLinking();
David Sehr709b0702016-10-13 09:12:37 -07001099 CHECK(table != nullptr) << PrettyClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001100 const size_t table_length = table->GetLength();
1101 SetEmbeddedVTableLength(table_length);
1102 for (size_t i = 0; i < table_length; i++) {
1103 SetEmbeddedVTableEntry(i, table->GetElementPtrSize<ArtMethod*>(i, pointer_size), pointer_size);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001104 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07001105 // Keep java.lang.Object class's vtable around for since it's easier
1106 // to be reused by array classes during their linking.
1107 if (!IsObjectClass()) {
1108 SetVTable(nullptr);
1109 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001110}
1111
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001112class ReadBarrierOnNativeRootsVisitor {
1113 public:
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001114 void operator()(ObjPtr<Object> obj ATTRIBUTE_UNUSED,
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001115 MemberOffset offset ATTRIBUTE_UNUSED,
1116 bool is_static ATTRIBUTE_UNUSED) const {}
1117
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001118 void VisitRootIfNonNull(CompressedReference<Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001119 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001120 if (!root->IsNull()) {
1121 VisitRoot(root);
1122 }
1123 }
1124
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001125 void VisitRoot(CompressedReference<Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001126 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001127 ObjPtr<Object> old_ref = root->AsMirrorPtr();
1128 ObjPtr<Object> new_ref = ReadBarrier::BarrierForRoot(root);
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001129 if (old_ref != new_ref) {
1130 // Update the field atomically. This may fail if mutator updates before us, but it's ok.
1131 auto* atomic_root =
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001132 reinterpret_cast<Atomic<CompressedReference<Object>>*>(root);
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001133 atomic_root->CompareExchangeStrongSequentiallyConsistent(
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001134 CompressedReference<Object>::FromMirrorPtr(old_ref.Ptr()),
1135 CompressedReference<Object>::FromMirrorPtr(new_ref.Ptr()));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001136 }
1137 }
1138};
1139
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001140// The pre-fence visitor for Class::CopyOf().
1141class CopyClassVisitor {
1142 public:
Andreas Gampe542451c2016-07-26 09:02:02 -07001143 CopyClassVisitor(Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001144 Handle<Class>* orig,
Andreas Gampe542451c2016-07-26 09:02:02 -07001145 size_t new_length,
1146 size_t copy_bytes,
1147 ImTable* imt,
1148 PointerSize pointer_size)
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001149 : self_(self), orig_(orig), new_length_(new_length),
Mathieu Chartiere401d142015-04-22 13:56:20 -07001150 copy_bytes_(copy_bytes), imt_(imt), pointer_size_(pointer_size) {
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001151 }
1152
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001153 void operator()(ObjPtr<Object> obj, size_t usable_size ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001154 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001155 StackHandleScope<1> hs(self_);
1156 Handle<mirror::Class> h_new_class_obj(hs.NewHandle(obj->AsClass()));
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001157 Object::CopyObject(h_new_class_obj.Get(), orig_->Get(), copy_bytes_);
1158 Class::SetStatus(h_new_class_obj, Class::kStatusResolving, self_);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001159 h_new_class_obj->PopulateEmbeddedVTable(pointer_size_);
1160 h_new_class_obj->SetImt(imt_, pointer_size_);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001161 h_new_class_obj->SetClassSize(new_length_);
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001162 // Visit all of the references to make sure there is no from space references in the native
1163 // roots.
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001164 ObjPtr<Object>(h_new_class_obj.Get())->VisitReferences(
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001165 ReadBarrierOnNativeRootsVisitor(), VoidFunctor());
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001166 }
1167
1168 private:
1169 Thread* const self_;
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001170 Handle<Class>* const orig_;
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001171 const size_t new_length_;
1172 const size_t copy_bytes_;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001173 ImTable* imt_;
Andreas Gampe542451c2016-07-26 09:02:02 -07001174 const PointerSize pointer_size_;
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001175 DISALLOW_COPY_AND_ASSIGN(CopyClassVisitor);
1176};
1177
Andreas Gampe542451c2016-07-26 09:02:02 -07001178Class* Class::CopyOf(Thread* self, int32_t new_length, ImTable* imt, PointerSize pointer_size) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001179 DCHECK_GE(new_length, static_cast<int32_t>(sizeof(Class)));
1180 // We may get copied by a compacting GC.
1181 StackHandleScope<1> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001182 Handle<Class> h_this(hs.NewHandle(this));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001183 gc::Heap* heap = Runtime::Current()->GetHeap();
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001184 // The num_bytes (3rd param) is sizeof(Class) as opposed to SizeOf()
1185 // to skip copying the tail part that we will overwrite here.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001186 CopyClassVisitor visitor(self, &h_this, new_length, sizeof(Class), imt, pointer_size);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001187 ObjPtr<Object> new_class = kMovingClasses ?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001188 heap->AllocObject<true>(self, java_lang_Class_.Read(), new_length, visitor) :
1189 heap->AllocNonMovableObject<true>(self, java_lang_Class_.Read(), new_length, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001190 if (UNLIKELY(new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001191 self->AssertPendingOOMException();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001192 return nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001193 }
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001194 return new_class->AsClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001195}
1196
Nicolas Geoffray3a090922015-11-24 09:17:30 +00001197bool Class::ProxyDescriptorEquals(const char* match) {
1198 DCHECK(IsProxyClass());
1199 return Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(this) == match;
Vladimir Marko3481ba22015-04-13 12:22:36 +01001200}
1201
Mathieu Chartiere401d142015-04-22 13:56:20 -07001202// TODO: Move this to java_lang_Class.cc?
1203ArtMethod* Class::GetDeclaredConstructor(
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001204 Thread* self, Handle<ObjectArray<Class>> args, PointerSize pointer_size) {
Andreas Gampe6039e562016-04-05 18:18:43 -07001205 for (auto& m : GetDirectMethods(pointer_size)) {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001206 // Skip <clinit> which is a static constructor, as well as non constructors.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001207 if (m.IsStatic() || !m.IsConstructor()) {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001208 continue;
1209 }
1210 // May cause thread suspension and exceptions.
Andreas Gampe542451c2016-07-26 09:02:02 -07001211 if (m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->EqualParameters(args)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001212 return &m;
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001213 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001214 if (UNLIKELY(self->IsExceptionPending())) {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001215 return nullptr;
1216 }
1217 }
1218 return nullptr;
1219}
1220
Mathieu Chartiere401d142015-04-22 13:56:20 -07001221uint32_t Class::Depth() {
1222 uint32_t depth = 0;
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001223 for (ObjPtr<Class> klass = this; klass->GetSuperClass() != nullptr; klass = klass->GetSuperClass()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001224 depth++;
1225 }
1226 return depth;
1227}
1228
Andreas Gampea5b09a62016-11-17 15:21:22 -08001229dex::TypeIndex Class::FindTypeIndexInOtherDexFile(const DexFile& dex_file) {
Nicolas Geoffraye4084a52016-02-18 14:43:42 +00001230 std::string temp;
1231 const DexFile::TypeId* type_id = dex_file.FindTypeId(GetDescriptor(&temp));
Andreas Gampe2722f382017-06-08 18:03:25 -07001232 return (type_id == nullptr) ? dex::TypeIndex() : dex_file.GetIndexForTypeId(*type_id);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +00001233}
1234
Andreas Gampe542451c2016-07-26 09:02:02 -07001235template <PointerSize kPointerSize, bool kTransactionActive>
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001236ObjPtr<Method> Class::GetDeclaredMethodInternal(
1237 Thread* self,
1238 ObjPtr<Class> klass,
1239 ObjPtr<String> name,
1240 ObjPtr<ObjectArray<Class>> args) {
Andreas Gampebc4d2182016-02-22 10:03:12 -08001241 // Covariant return types permit the class to define multiple
1242 // methods with the same name and parameter types. Prefer to
1243 // return a non-synthetic method in such situations. We may
1244 // still return a synthetic method to handle situations like
1245 // escalated visibility. We never return miranda methods that
1246 // were synthesized by the runtime.
1247 constexpr uint32_t kSkipModifiers = kAccMiranda | kAccSynthetic;
1248 StackHandleScope<3> hs(self);
1249 auto h_method_name = hs.NewHandle(name);
Andreas Gampefa4333d2017-02-14 11:10:34 -08001250 if (UNLIKELY(h_method_name == nullptr)) {
Andreas Gampebc4d2182016-02-22 10:03:12 -08001251 ThrowNullPointerException("name == null");
1252 return nullptr;
1253 }
1254 auto h_args = hs.NewHandle(args);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001255 Handle<Class> h_klass = hs.NewHandle(klass);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001256 ArtMethod* result = nullptr;
Andreas Gampee01e3642016-07-25 13:06:04 -07001257 for (auto& m : h_klass->GetDeclaredVirtualMethods(kPointerSize)) {
1258 auto* np_method = m.GetInterfaceMethodIfProxy(kPointerSize);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001259 // May cause thread suspension.
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001260 ObjPtr<String> np_name = np_method->GetNameAsString(self);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001261 if (!np_name->Equals(h_method_name.Get()) || !np_method->EqualParameters(h_args)) {
1262 if (UNLIKELY(self->IsExceptionPending())) {
1263 return nullptr;
1264 }
1265 continue;
1266 }
1267 auto modifiers = m.GetAccessFlags();
1268 if ((modifiers & kSkipModifiers) == 0) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001269 return Method::CreateFromArtMethod<kPointerSize, kTransactionActive>(self, &m);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001270 }
1271 if ((modifiers & kAccMiranda) == 0) {
1272 result = &m; // Remember as potential result if it's not a miranda method.
1273 }
1274 }
1275 if (result == nullptr) {
Andreas Gampee01e3642016-07-25 13:06:04 -07001276 for (auto& m : h_klass->GetDirectMethods(kPointerSize)) {
Andreas Gampebc4d2182016-02-22 10:03:12 -08001277 auto modifiers = m.GetAccessFlags();
1278 if ((modifiers & kAccConstructor) != 0) {
1279 continue;
1280 }
Andreas Gampee01e3642016-07-25 13:06:04 -07001281 auto* np_method = m.GetInterfaceMethodIfProxy(kPointerSize);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001282 // May cause thread suspension.
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001283 ObjPtr<String> np_name = np_method->GetNameAsString(self);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001284 if (np_name == nullptr) {
1285 self->AssertPendingException();
1286 return nullptr;
1287 }
1288 if (!np_name->Equals(h_method_name.Get()) || !np_method->EqualParameters(h_args)) {
1289 if (UNLIKELY(self->IsExceptionPending())) {
1290 return nullptr;
1291 }
1292 continue;
1293 }
1294 if ((modifiers & kSkipModifiers) == 0) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001295 return Method::CreateFromArtMethod<kPointerSize, kTransactionActive>(self, &m);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001296 }
1297 // Direct methods cannot be miranda methods, so this potential result must be synthetic.
1298 result = &m;
1299 }
1300 }
1301 return result != nullptr
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001302 ? Method::CreateFromArtMethod<kPointerSize, kTransactionActive>(self, result)
Andreas Gampebc4d2182016-02-22 10:03:12 -08001303 : nullptr;
1304}
1305
1306template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001307ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k32, false>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001308 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001309 ObjPtr<Class> klass,
1310 ObjPtr<String> name,
1311 ObjPtr<ObjectArray<Class>> args);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001312template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001313ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k32, true>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001314 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001315 ObjPtr<Class> klass,
1316 ObjPtr<String> name,
1317 ObjPtr<ObjectArray<Class>> args);
Andreas Gampee01e3642016-07-25 13:06:04 -07001318template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001319ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k64, false>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001320 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001321 ObjPtr<Class> klass,
1322 ObjPtr<String> name,
1323 ObjPtr<ObjectArray<Class>> args);
Andreas Gampee01e3642016-07-25 13:06:04 -07001324template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001325ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k64, true>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001326 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001327 ObjPtr<Class> klass,
1328 ObjPtr<String> name,
1329 ObjPtr<ObjectArray<Class>> args);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001330
Andreas Gampe542451c2016-07-26 09:02:02 -07001331template <PointerSize kPointerSize, bool kTransactionActive>
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001332ObjPtr<Constructor> Class::GetDeclaredConstructorInternal(
Andreas Gampe6039e562016-04-05 18:18:43 -07001333 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001334 ObjPtr<Class> klass,
1335 ObjPtr<ObjectArray<Class>> args) {
Andreas Gampe6039e562016-04-05 18:18:43 -07001336 StackHandleScope<1> hs(self);
Andreas Gampee01e3642016-07-25 13:06:04 -07001337 ArtMethod* result = klass->GetDeclaredConstructor(self, hs.NewHandle(args), kPointerSize);
Andreas Gampe6039e562016-04-05 18:18:43 -07001338 return result != nullptr
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001339 ? Constructor::CreateFromArtMethod<kPointerSize, kTransactionActive>(self, result)
Andreas Gampe6039e562016-04-05 18:18:43 -07001340 : nullptr;
1341}
1342
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001343// Constructor::CreateFromArtMethod<kTransactionActive>(self, result)
Andreas Gampe6039e562016-04-05 18:18:43 -07001344
Andreas Gampe542451c2016-07-26 09:02:02 -07001345template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001346ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k32, false>(
Andreas Gampe6039e562016-04-05 18:18:43 -07001347 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001348 ObjPtr<Class> klass,
1349 ObjPtr<ObjectArray<Class>> args);
Andreas Gampe542451c2016-07-26 09:02:02 -07001350template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001351ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k32, true>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001352 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001353 ObjPtr<Class> klass,
1354 ObjPtr<ObjectArray<Class>> args);
Andreas Gampe542451c2016-07-26 09:02:02 -07001355template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001356ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k64, false>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001357 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001358 ObjPtr<Class> klass,
1359 ObjPtr<ObjectArray<Class>> args);
Andreas Gampe542451c2016-07-26 09:02:02 -07001360template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001361ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k64, true>(
Andreas Gampe6039e562016-04-05 18:18:43 -07001362 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001363 ObjPtr<Class> klass,
1364 ObjPtr<ObjectArray<Class>> args);
Andreas Gampe6039e562016-04-05 18:18:43 -07001365
Andreas Gampe715fdc22016-04-18 17:07:30 -07001366int32_t Class::GetInnerClassFlags(Handle<Class> h_this, int32_t default_value) {
1367 if (h_this->IsProxyClass() || h_this->GetDexCache() == nullptr) {
1368 return default_value;
1369 }
1370 uint32_t flags;
David Sehr9323e6e2016-09-13 08:58:35 -07001371 if (!annotations::GetInnerClassFlags(h_this, &flags)) {
Andreas Gampe715fdc22016-04-18 17:07:30 -07001372 return default_value;
1373 }
1374 return flags;
1375}
1376
Mathieu Chartier93bbee02016-08-31 09:38:40 -07001377void Class::SetObjectSizeAllocFastPath(uint32_t new_object_size) {
1378 if (Runtime::Current()->IsActiveTransaction()) {
1379 SetField32Volatile<true>(ObjectSizeAllocFastPathOffset(), new_object_size);
1380 } else {
1381 SetField32Volatile<false>(ObjectSizeAllocFastPathOffset(), new_object_size);
1382 }
1383}
1384
David Sehr709b0702016-10-13 09:12:37 -07001385std::string Class::PrettyDescriptor(ObjPtr<mirror::Class> klass) {
1386 if (klass == nullptr) {
1387 return "null";
1388 }
1389 return klass->PrettyDescriptor();
1390}
1391
1392std::string Class::PrettyDescriptor() {
1393 std::string temp;
1394 return art::PrettyDescriptor(GetDescriptor(&temp));
1395}
1396
1397std::string Class::PrettyClass(ObjPtr<mirror::Class> c) {
1398 if (c == nullptr) {
1399 return "null";
1400 }
1401 return c->PrettyClass();
1402}
1403
1404std::string Class::PrettyClass() {
1405 std::string result;
1406 result += "java.lang.Class<";
1407 result += PrettyDescriptor();
1408 result += ">";
1409 return result;
1410}
1411
1412std::string Class::PrettyClassAndClassLoader(ObjPtr<mirror::Class> c) {
1413 if (c == nullptr) {
1414 return "null";
1415 }
1416 return c->PrettyClassAndClassLoader();
1417}
1418
1419std::string Class::PrettyClassAndClassLoader() {
1420 std::string result;
1421 result += "java.lang.Class<";
1422 result += PrettyDescriptor();
1423 result += ",";
1424 result += mirror::Object::PrettyTypeOf(GetClassLoader());
1425 // TODO: add an identifying hash value for the loader
1426 result += ">";
1427 return result;
1428}
1429
Andreas Gampe90b936d2017-01-31 08:58:55 -08001430template<VerifyObjectFlags kVerifyFlags> void Class::GetAccessFlagsDCheck() {
1431 // Check class is loaded/retired or this is java.lang.String that has a
1432 // circularity issue during loading the names of its members
1433 DCHECK(IsIdxLoaded<kVerifyFlags>() || IsRetired<kVerifyFlags>() ||
1434 IsErroneous<static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis)>() ||
1435 this == String::GetJavaLangString())
1436 << "IsIdxLoaded=" << IsIdxLoaded<kVerifyFlags>()
1437 << " IsRetired=" << IsRetired<kVerifyFlags>()
1438 << " IsErroneous=" <<
1439 IsErroneous<static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis)>()
1440 << " IsString=" << (this == String::GetJavaLangString())
1441 << " status= " << GetStatus<kVerifyFlags>()
1442 << " descriptor=" << PrettyDescriptor();
1443}
1444// Instantiate the common cases.
1445template void Class::GetAccessFlagsDCheck<kVerifyNone>();
1446template void Class::GetAccessFlagsDCheck<kVerifyThis>();
1447template void Class::GetAccessFlagsDCheck<kVerifyReads>();
1448template void Class::GetAccessFlagsDCheck<kVerifyWrites>();
1449template void Class::GetAccessFlagsDCheck<kVerifyAll>();
1450
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001451} // namespace mirror
1452} // namespace art