blob: 40157c48087cab9f9a4e84375b9f440766d23d0c [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"
Mathieu Chartierfc58af42015-04-16 18:00:39 -070032#include "method.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070033#include "object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080034#include "object-refvisitor-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070035#include "object_array-inl.h"
Alex Lightd6251582016-10-31 11:12:30 -070036#include "object_lock.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070037#include "runtime.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080038#include "thread.h"
39#include "throwable.h"
40#include "utils.h"
41#include "well_known_classes.h"
42
43namespace art {
44namespace mirror {
45
Andreas Gampe46ee31b2016-12-14 10:11:49 -080046using android::base::StringPrintf;
47
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070048GcRoot<Class> Class::java_lang_Class_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080049
Andreas Gampeee5303f2017-08-31 15:34:42 -070050constexpr Class::Status Class::kStatusRetired;
51constexpr Class::Status Class::kStatusErrorResolved;
52constexpr Class::Status Class::kStatusErrorUnresolved;
53constexpr Class::Status Class::kStatusNotReady;
54constexpr Class::Status Class::kStatusIdx;
55constexpr Class::Status Class::kStatusLoaded;
56constexpr Class::Status Class::kStatusResolving;
57constexpr Class::Status Class::kStatusResolved;
58constexpr Class::Status Class::kStatusVerifying;
59constexpr Class::Status Class::kStatusRetryVerificationAtRuntime;
60constexpr Class::Status Class::kStatusVerifyingAtRuntime;
61constexpr Class::Status Class::kStatusVerified;
62constexpr Class::Status Class::kStatusSuperclassValidated;
63constexpr Class::Status Class::kStatusInitializing;
64constexpr Class::Status Class::kStatusInitialized;
65constexpr Class::Status Class::kStatusMax;
66
Mathieu Chartier28bd2e42016-10-04 13:54:57 -070067void Class::SetClassClass(ObjPtr<Class> java_lang_Class) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070068 CHECK(java_lang_Class_.IsNull())
69 << java_lang_Class_.Read()
Hiroshi Yamauchi4f1ebc22014-06-25 14:30:41 -070070 << " " << java_lang_Class;
Brian Carlstrom004644f2014-06-18 08:34:01 -070071 CHECK(java_lang_Class != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -070072 java_lang_Class->SetClassFlags(kClassFlagClass);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070073 java_lang_Class_ = GcRoot<Class>(java_lang_Class);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080074}
75
76void Class::ResetClass() {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070077 CHECK(!java_lang_Class_.IsNull());
78 java_lang_Class_ = GcRoot<Class>(nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080079}
80
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -070081void Class::VisitRoots(RootVisitor* visitor) {
82 java_lang_Class_.VisitRootIfNonNull(visitor, RootInfo(kRootStickyClass));
Mathieu Chartierc528dba2013-11-26 12:00:11 -080083}
84
Alex Light0273ad12016-11-02 11:19:31 -070085ClassExt* Class::EnsureExtDataPresent(Thread* self) {
86 ObjPtr<ClassExt> existing(GetExtData());
87 if (!existing.IsNull()) {
88 return existing.Ptr();
89 }
90 StackHandleScope<3> hs(self);
91 // Handlerize 'this' since we are allocating here.
92 Handle<Class> h_this(hs.NewHandle(this));
93 // Clear exception so we can allocate.
94 Handle<Throwable> throwable(hs.NewHandle(self->GetException()));
95 self->ClearException();
96 // Allocate the ClassExt
97 Handle<ClassExt> new_ext(hs.NewHandle(ClassExt::Alloc(self)));
Andreas Gampefa4333d2017-02-14 11:10:34 -080098 if (new_ext == nullptr) {
Alex Light0273ad12016-11-02 11:19:31 -070099 // OOM allocating the classExt.
100 // TODO Should we restore the suppressed exception?
101 self->AssertPendingOOMException();
102 return nullptr;
Andreas Gampe99babb62015-11-02 16:20:00 -0800103 } else {
Alex Light0273ad12016-11-02 11:19:31 -0700104 MemberOffset ext_offset(OFFSET_OF_OBJECT_MEMBER(Class, ext_data_));
105 bool set;
106 // Set the ext_data_ field using CAS semantics.
107 if (Runtime::Current()->IsActiveTransaction()) {
108 set = h_this->CasFieldStrongSequentiallyConsistentObject<true>(ext_offset,
109 ObjPtr<ClassExt>(nullptr),
110 new_ext.Get());
111 } else {
112 set = h_this->CasFieldStrongSequentiallyConsistentObject<false>(ext_offset,
113 ObjPtr<ClassExt>(nullptr),
114 new_ext.Get());
115 }
116 ObjPtr<ClassExt> ret(set ? new_ext.Get() : h_this->GetExtData());
117 DCHECK(!set || h_this->GetExtData() == new_ext.Get());
118 CHECK(!ret.IsNull());
119 // Restore the exception if there was one.
Andreas Gampefa4333d2017-02-14 11:10:34 -0800120 if (throwable != nullptr) {
Alex Light0273ad12016-11-02 11:19:31 -0700121 self->SetException(throwable.Get());
122 }
123 return ret.Ptr();
Andreas Gampe99babb62015-11-02 16:20:00 -0800124 }
125}
126
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700127void Class::SetStatus(Handle<Class> h_this, Status new_status, Thread* self) {
128 Status old_status = h_this->GetStatus();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700129 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
130 bool class_linker_initialized = class_linker != nullptr && class_linker->IsInitialized();
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700131 if (LIKELY(class_linker_initialized)) {
Vladimir Marko72ab6842017-01-20 19:32:50 +0000132 if (UNLIKELY(new_status <= old_status &&
133 new_status != kStatusErrorUnresolved &&
134 new_status != kStatusErrorResolved &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700135 new_status != kStatusRetired)) {
David Sehr709b0702016-10-13 09:12:37 -0700136 LOG(FATAL) << "Unexpected change back of class status for " << h_this->PrettyClass()
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700137 << " " << old_status << " -> " << new_status;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -0700138 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700139 if (new_status >= kStatusResolved || old_status >= kStatusResolved) {
140 // When classes are being resolved the resolution code should hold the lock.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700141 CHECK_EQ(h_this->GetLockOwnerThreadId(), self->GetThreadId())
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700142 << "Attempt to change status of class while not holding its lock: "
David Sehr709b0702016-10-13 09:12:37 -0700143 << h_this->PrettyClass() << " " << old_status << " -> " << new_status;
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700144 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800145 }
Vladimir Marko72ab6842017-01-20 19:32:50 +0000146 if (UNLIKELY(IsErroneous(new_status))) {
147 CHECK(!h_this->IsErroneous())
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700148 << "Attempt to set as erroneous an already erroneous class "
Vladimir Marko72ab6842017-01-20 19:32:50 +0000149 << h_this->PrettyClass()
150 << " old_status: " << old_status << " new_status: " << new_status;
151 CHECK_EQ(new_status == kStatusErrorResolved, old_status >= kStatusResolved);
Andreas Gampe31decb12015-08-24 21:09:05 -0700152 if (VLOG_IS_ON(class_linker)) {
David Sehr709b0702016-10-13 09:12:37 -0700153 LOG(ERROR) << "Setting " << h_this->PrettyDescriptor() << " to erroneous.";
Andreas Gampe31decb12015-08-24 21:09:05 -0700154 if (self->IsExceptionPending()) {
155 LOG(ERROR) << "Exception: " << self->GetException()->Dump();
156 }
157 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800158
Alex Light0273ad12016-11-02 11:19:31 -0700159 ObjPtr<ClassExt> ext(h_this->EnsureExtDataPresent(self));
160 if (!ext.IsNull()) {
161 self->AssertPendingException();
162 ext->SetVerifyError(self->GetException());
163 } else {
164 self->AssertPendingOOMException();
Alex Lightd6251582016-10-31 11:12:30 -0700165 }
166 self->AssertPendingException();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800167 }
Alex Light0273ad12016-11-02 11:19:31 -0700168
Andreas Gampe575e78c2014-11-03 23:41:03 -0800169 static_assert(sizeof(Status) == sizeof(uint32_t), "Size of status not equal to uint32");
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100170 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier93bbee02016-08-31 09:38:40 -0700171 h_this->SetField32Volatile<true>(StatusOffset(), new_status);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100172 } else {
Mathieu Chartier93bbee02016-08-31 09:38:40 -0700173 h_this->SetField32Volatile<false>(StatusOffset(), new_status);
174 }
175
176 // Setting the object size alloc fast path needs to be after the status write so that if the
177 // alloc path sees a valid object size, we would know that it's initialized as long as it has a
178 // load-acquire/fake dependency.
179 if (new_status == kStatusInitialized && !h_this->IsVariableSize()) {
Mathieu Chartier161db1d2016-09-01 14:06:54 -0700180 DCHECK_EQ(h_this->GetObjectSizeAllocFastPath(), std::numeric_limits<uint32_t>::max());
181 // Finalizable objects must always go slow path.
182 if (!h_this->IsFinalizable()) {
183 h_this->SetObjectSizeAllocFastPath(RoundUp(h_this->GetObjectSize(), kObjectAlignment));
Mathieu Chartier93bbee02016-08-31 09:38:40 -0700184 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100185 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700186
187 if (!class_linker_initialized) {
188 // When the class linker is being initialized its single threaded and by definition there can be
189 // no waiters. During initialization classes may appear temporary but won't be retired as their
190 // size was statically computed.
191 } else {
192 // Classes that are being resolved or initialized need to notify waiters that the class status
193 // changed. See ClassLinker::EnsureResolved and ClassLinker::WaitForInitializeClass.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700194 if (h_this->IsTemp()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700195 // Class is a temporary one, ensure that waiters for resolution get notified of retirement
196 // so that they can grab the new version of the class from the class linker's table.
David Sehr709b0702016-10-13 09:12:37 -0700197 CHECK_LT(new_status, kStatusResolved) << h_this->PrettyDescriptor();
Vladimir Marko72ab6842017-01-20 19:32:50 +0000198 if (new_status == kStatusRetired || new_status == kStatusErrorUnresolved) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700199 h_this->NotifyAll(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700200 }
201 } else {
202 CHECK_NE(new_status, kStatusRetired);
203 if (old_status >= kStatusResolved || new_status >= kStatusResolved) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700204 h_this->NotifyAll(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700205 }
206 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700207 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800208}
209
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700210void Class::SetDexCache(ObjPtr<DexCache> new_dex_cache) {
Chang Xing6d3e7682017-07-11 10:31:29 -0700211 SetFieldObjectTransaction(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), new_dex_cache);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800212}
213
Ian Rogersef7d42f2014-01-06 12:55:46 -0800214void Class::SetClassSize(uint32_t new_class_size) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700215 if (kIsDebugBuild && new_class_size < GetClassSize()) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700216 DumpClass(LOG_STREAM(FATAL_WITHOUT_ABORT), kDumpClassFullDetail);
217 LOG(FATAL_WITHOUT_ABORT) << new_class_size << " vs " << GetClassSize();
David Sehr709b0702016-10-13 09:12:37 -0700218 LOG(FATAL) << "class=" << PrettyTypeOf();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700219 }
Chang Xing6d3e7682017-07-11 10:31:29 -0700220 SetField32Transaction(OFFSET_OF_OBJECT_MEMBER(Class, class_size_), new_class_size);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800221}
222
223// Return the class' name. The exact format is bizarre, but it's the specified behavior for
224// Class.getName: keywords for primitive types, regular "[I" form for primitive arrays (so "int"
225// but "[I"), and arrays of reference types written between "L" and ";" but with dots rather than
226// slashes (so "java.lang.String" but "[Ljava.lang.String;"). Madness.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700227String* Class::ComputeName(Handle<Class> h_this) {
228 String* name = h_this->GetName();
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800229 if (name != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800230 return name;
231 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700232 std::string temp;
233 const char* descriptor = h_this->GetDescriptor(&temp);
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800234 Thread* self = Thread::Current();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800235 if ((descriptor[0] != 'L') && (descriptor[0] != '[')) {
236 // The descriptor indicates that this is the class for
237 // a primitive type; special-case the return value.
Brian Carlstrom004644f2014-06-18 08:34:01 -0700238 const char* c_name = nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800239 switch (descriptor[0]) {
240 case 'Z': c_name = "boolean"; break;
241 case 'B': c_name = "byte"; break;
242 case 'C': c_name = "char"; break;
243 case 'S': c_name = "short"; break;
244 case 'I': c_name = "int"; break;
245 case 'J': c_name = "long"; break;
246 case 'F': c_name = "float"; break;
247 case 'D': c_name = "double"; break;
248 case 'V': c_name = "void"; break;
249 default:
250 LOG(FATAL) << "Unknown primitive type: " << PrintableChar(descriptor[0]);
251 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800252 name = String::AllocFromModifiedUtf8(self, c_name);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800253 } else {
254 // Convert the UTF-8 name to a java.lang.String. The name must use '.' to separate package
255 // components.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700256 name = String::AllocFromModifiedUtf8(self, DescriptorToDot(descriptor).c_str());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800257 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700258 h_this->SetName(name);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800259 return name;
260}
261
Ian Rogersef7d42f2014-01-06 12:55:46 -0800262void Class::DumpClass(std::ostream& os, int flags) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800263 if ((flags & kDumpClassFullDetail) == 0) {
David Sehr709b0702016-10-13 09:12:37 -0700264 os << PrettyClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800265 if ((flags & kDumpClassClassLoader) != 0) {
266 os << ' ' << GetClassLoader();
267 }
268 if ((flags & kDumpClassInitialized) != 0) {
269 os << ' ' << GetStatus();
270 }
271 os << "\n";
272 return;
273 }
274
Mathieu Chartiere401d142015-04-22 13:56:20 -0700275 Thread* const self = Thread::Current();
Mathieu Chartierf8322842014-05-16 10:59:25 -0700276 StackHandleScope<2> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700277 Handle<Class> h_this(hs.NewHandle(this));
278 Handle<Class> h_super(hs.NewHandle(GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700279 auto image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Mathieu Chartierf8322842014-05-16 10:59:25 -0700280
Ian Rogers1ff3c982014-08-12 02:30:58 -0700281 std::string temp;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800282 os << "----- " << (IsInterface() ? "interface" : "class") << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -0700283 << "'" << GetDescriptor(&temp) << "' cl=" << GetClassLoader() << " -----\n",
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800284 os << " objectSize=" << SizeOf() << " "
Andreas Gampefa4333d2017-02-14 11:10:34 -0800285 << "(" << (h_super != nullptr ? h_super->SizeOf() : -1) << " from super)\n",
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800286 os << StringPrintf(" access=0x%04x.%04x\n",
287 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
Andreas Gampefa4333d2017-02-14 11:10:34 -0800288 if (h_super != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700289 os << " super='" << h_super->PrettyClass() << "' (cl=" << h_super->GetClassLoader()
Mathieu Chartierf8322842014-05-16 10:59:25 -0700290 << ")\n";
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800291 }
292 if (IsArrayClass()) {
293 os << " componentType=" << PrettyClass(GetComponentType()) << "\n";
294 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700295 const size_t num_direct_interfaces = NumDirectInterfaces();
296 if (num_direct_interfaces > 0) {
297 os << " interfaces (" << num_direct_interfaces << "):\n";
298 for (size_t i = 0; i < num_direct_interfaces; ++i) {
Vladimir Marko19a4d372016-12-08 14:41:46 +0000299 ObjPtr<Class> interface = GetDirectInterface(self, h_this.Get(), i);
Andreas Gampe16f149c2015-03-23 10:10:20 -0700300 if (interface == nullptr) {
301 os << StringPrintf(" %2zd: nullptr!\n", i);
302 } else {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700303 ObjPtr<ClassLoader> cl = interface->GetClassLoader();
304 os << StringPrintf(" %2zd: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl.Ptr());
Andreas Gampe16f149c2015-03-23 10:10:20 -0700305 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800306 }
307 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700308 if (!IsLoaded()) {
309 os << " class not yet loaded";
310 } else {
311 // After this point, this may have moved due to GetDirectInterface.
312 os << " vtable (" << h_this->NumVirtualMethods() << " entries, "
Andreas Gampefa4333d2017-02-14 11:10:34 -0800313 << (h_super != nullptr ? h_super->NumVirtualMethods() : 0) << " in super):\n";
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700314 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
David Sehr709b0702016-10-13 09:12:37 -0700315 os << StringPrintf(" %2zd: %s\n", i, ArtMethod::PrettyMethod(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700316 h_this->GetVirtualMethodDuringLinking(i, image_pointer_size)).c_str());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800317 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700318 os << " direct methods (" << h_this->NumDirectMethods() << " entries):\n";
319 for (size_t i = 0; i < h_this->NumDirectMethods(); ++i) {
David Sehr709b0702016-10-13 09:12:37 -0700320 os << StringPrintf(" %2zd: %s\n", i, ArtMethod::PrettyMethod(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700321 h_this->GetDirectMethod(i, image_pointer_size)).c_str());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700322 }
323 if (h_this->NumStaticFields() > 0) {
324 os << " static fields (" << h_this->NumStaticFields() << " entries):\n";
Vladimir Marko72ab6842017-01-20 19:32:50 +0000325 if (h_this->IsResolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700326 for (size_t i = 0; i < h_this->NumStaticFields(); ++i) {
David Sehr709b0702016-10-13 09:12:37 -0700327 os << StringPrintf(" %2zd: %s\n", i,
328 ArtField::PrettyField(h_this->GetStaticField(i)).c_str());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700329 }
330 } else {
331 os << " <not yet available>";
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800332 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700333 }
334 if (h_this->NumInstanceFields() > 0) {
335 os << " instance fields (" << h_this->NumInstanceFields() << " entries):\n";
Vladimir Marko72ab6842017-01-20 19:32:50 +0000336 if (h_this->IsResolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700337 for (size_t i = 0; i < h_this->NumInstanceFields(); ++i) {
David Sehr709b0702016-10-13 09:12:37 -0700338 os << StringPrintf(" %2zd: %s\n", i,
339 ArtField::PrettyField(h_this->GetInstanceField(i)).c_str());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700340 }
341 } else {
342 os << " <not yet available>";
343 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800344 }
345 }
346}
347
348void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700349 if (kIsDebugBuild && new_reference_offsets != kClassWalkSuper) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800350 // Sanity check that the number of bits set in the reference offset bitmap
351 // agrees with the number of references
Ian Rogerscdc1aaf2014-10-09 13:21:38 -0700352 uint32_t count = 0;
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700353 for (ObjPtr<Class> c = this; c != nullptr; c = c->GetSuperClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800354 count += c->NumReferenceInstanceFieldsDuringLinking();
355 }
Ian Rogerscdc1aaf2014-10-09 13:21:38 -0700356 // +1 for the Class in Object.
357 CHECK_EQ(static_cast<uint32_t>(POPCOUNT(new_reference_offsets)) + 1, count);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800358 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100359 // Not called within a transaction.
360 SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700361 new_reference_offsets);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800362}
363
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800364bool Class::IsInSamePackage(const StringPiece& descriptor1, const StringPiece& descriptor2) {
365 size_t i = 0;
Ian Rogers6b604a12014-09-25 15:35:37 -0700366 size_t min_length = std::min(descriptor1.size(), descriptor2.size());
367 while (i < min_length && descriptor1[i] == descriptor2[i]) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800368 ++i;
369 }
370 if (descriptor1.find('/', i) != StringPiece::npos ||
371 descriptor2.find('/', i) != StringPiece::npos) {
372 return false;
373 } else {
374 return true;
375 }
376}
377
Mathieu Chartier3398c782016-09-30 10:27:43 -0700378bool Class::IsInSamePackage(ObjPtr<Class> that) {
379 ObjPtr<Class> klass1 = this;
380 ObjPtr<Class> klass2 = that;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800381 if (klass1 == klass2) {
382 return true;
383 }
384 // Class loaders must match.
385 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
386 return false;
387 }
388 // Arrays are in the same package when their element classes are.
389 while (klass1->IsArrayClass()) {
390 klass1 = klass1->GetComponentType();
391 }
392 while (klass2->IsArrayClass()) {
393 klass2 = klass2->GetComponentType();
394 }
Anwar Ghuloum9fa3f202013-03-26 14:32:54 -0700395 // trivial check again for array types
396 if (klass1 == klass2) {
397 return true;
398 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800399 // Compare the package part of the descriptor string.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700400 std::string temp1, temp2;
401 return IsInSamePackage(klass1->GetDescriptor(&temp1), klass2->GetDescriptor(&temp2));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800402}
403
Ian Rogersef7d42f2014-01-06 12:55:46 -0800404bool Class::IsThrowableClass() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800405 return WellKnownClasses::ToClass(WellKnownClasses::java_lang_Throwable)->IsAssignableFrom(this);
406}
407
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700408void Class::SetClassLoader(ObjPtr<ClassLoader> new_class_loader) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100409 if (Runtime::Current()->IsActiveTransaction()) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700410 SetFieldObject<true>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100411 } else {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700412 SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100413 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800414}
415
Vladimir Markoba118822017-06-12 15:41:56 +0100416template <typename SignatureType>
417static inline ArtMethod* FindInterfaceMethodWithSignature(ObjPtr<Class> klass,
418 const StringPiece& name,
419 const SignatureType& signature,
420 PointerSize pointer_size)
421 REQUIRES_SHARED(Locks::mutator_lock_) {
422 // If the current class is not an interface, skip the search of its declared methods;
423 // such lookup is used only to distinguish between IncompatibleClassChangeError and
424 // NoSuchMethodError and the caller has already tried to search methods in the class.
425 if (LIKELY(klass->IsInterface())) {
426 // Search declared methods, both direct and virtual.
427 // (This lookup is used also for invoke-static on interface classes.)
428 for (ArtMethod& method : klass->GetDeclaredMethodsSlice(pointer_size)) {
429 if (method.GetName() == name && method.GetSignature() == signature) {
430 return &method;
431 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800432 }
433 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700434
Vladimir Markoba118822017-06-12 15:41:56 +0100435 // TODO: If there is a unique maximally-specific non-abstract superinterface method,
436 // we should return it, otherwise an arbitrary one can be returned.
437 ObjPtr<IfTable> iftable = klass->GetIfTable();
438 for (int32_t i = 0, iftable_count = iftable->Count(); i < iftable_count; ++i) {
439 ObjPtr<Class> iface = iftable->GetInterface(i);
440 for (ArtMethod& method : iface->GetVirtualMethodsSlice(pointer_size)) {
441 if (method.GetName() == name && method.GetSignature() == signature) {
442 return &method;
443 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700444 }
445 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800446
Vladimir Markoba118822017-06-12 15:41:56 +0100447 // Then search for public non-static methods in the java.lang.Object.
448 if (LIKELY(klass->IsInterface())) {
449 ObjPtr<Class> object_class = klass->GetSuperClass();
450 DCHECK(object_class->IsObjectClass());
451 for (ArtMethod& method : object_class->GetDeclaredMethodsSlice(pointer_size)) {
452 if (method.IsPublic() && !method.IsStatic() &&
453 method.GetName() == name && method.GetSignature() == signature) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700454 return &method;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800455 }
456 }
457 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700458 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800459}
460
Vladimir Markoba118822017-06-12 15:41:56 +0100461ArtMethod* Class::FindInterfaceMethod(const StringPiece& name,
462 const StringPiece& signature,
463 PointerSize pointer_size) {
464 return FindInterfaceMethodWithSignature(this, name, signature, pointer_size);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800465}
466
Vladimir Markoba118822017-06-12 15:41:56 +0100467ArtMethod* Class::FindInterfaceMethod(const StringPiece& name,
468 const Signature& signature,
469 PointerSize pointer_size) {
470 return FindInterfaceMethodWithSignature(this, name, signature, pointer_size);
Ian Rogersd91d6d62013-09-25 20:26:14 -0700471}
472
Vladimir Markoba118822017-06-12 15:41:56 +0100473ArtMethod* Class::FindInterfaceMethod(ObjPtr<DexCache> dex_cache,
474 uint32_t dex_method_idx,
475 PointerSize pointer_size) {
476 // We always search by name and signature, ignoring the type index in the MethodId.
477 const DexFile& dex_file = *dex_cache->GetDexFile();
478 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
479 StringPiece name = dex_file.StringDataByIdx(method_id.name_idx_);
480 const Signature signature = dex_file.GetMethodSignature(method_id);
481 return FindInterfaceMethod(name, signature, pointer_size);
482}
483
Alex Lightafb66472017-08-01 09:54:49 -0700484static inline bool IsValidInheritanceCheck(ObjPtr<mirror::Class> klass,
485 ObjPtr<mirror::Class> declaring_class)
486 REQUIRES_SHARED(Locks::mutator_lock_) {
487 if (klass->IsArrayClass()) {
488 return declaring_class->IsObjectClass();
489 } else if (klass->IsInterface()) {
490 return declaring_class->IsObjectClass() || declaring_class == klass;
491 } else {
492 return klass->IsSubClass(declaring_class);
493 }
494}
495
Vladimir Markoba118822017-06-12 15:41:56 +0100496static inline bool IsInheritedMethod(ObjPtr<mirror::Class> klass,
497 ObjPtr<mirror::Class> declaring_class,
498 ArtMethod& method)
499 REQUIRES_SHARED(Locks::mutator_lock_) {
500 DCHECK_EQ(declaring_class, method.GetDeclaringClass());
501 DCHECK_NE(klass, declaring_class);
Alex Lightafb66472017-08-01 09:54:49 -0700502 DCHECK(IsValidInheritanceCheck(klass, declaring_class));
Vladimir Markoba118822017-06-12 15:41:56 +0100503 uint32_t access_flags = method.GetAccessFlags();
504 if ((access_flags & (kAccPublic | kAccProtected)) != 0) {
505 return true;
506 }
507 if ((access_flags & kAccPrivate) != 0) {
508 return false;
509 }
510 for (; klass != declaring_class; klass = klass->GetSuperClass()) {
511 if (!klass->IsInSamePackage(declaring_class)) {
512 return false;
513 }
514 }
515 return true;
516}
517
518template <typename SignatureType>
519static inline ArtMethod* FindClassMethodWithSignature(ObjPtr<Class> this_klass,
520 const StringPiece& name,
521 const SignatureType& signature,
522 PointerSize pointer_size)
523 REQUIRES_SHARED(Locks::mutator_lock_) {
524 // Search declared methods first.
525 for (ArtMethod& method : this_klass->GetDeclaredMethodsSlice(pointer_size)) {
526 ArtMethod* np_method = method.GetInterfaceMethodIfProxy(pointer_size);
527 if (np_method->GetName() == name && np_method->GetSignature() == signature) {
528 return &method;
529 }
530 }
531
532 // Then search the superclass chain. If we find an inherited method, return it.
533 // If we find a method that's not inherited because of access restrictions,
534 // try to find a method inherited from an interface in copied methods.
535 ObjPtr<Class> klass = this_klass->GetSuperClass();
536 ArtMethod* uninherited_method = nullptr;
537 for (; klass != nullptr; klass = klass->GetSuperClass()) {
538 DCHECK(!klass->IsProxyClass());
539 for (ArtMethod& method : klass->GetDeclaredMethodsSlice(pointer_size)) {
540 if (method.GetName() == name && method.GetSignature() == signature) {
541 if (IsInheritedMethod(this_klass, klass, method)) {
542 return &method;
543 }
544 uninherited_method = &method;
545 break;
546 }
547 }
548 if (uninherited_method != nullptr) {
549 break;
550 }
551 }
552
553 // Then search copied methods.
554 // If we found a method that's not inherited, stop the search in its declaring class.
555 ObjPtr<Class> end_klass = klass;
556 DCHECK_EQ(uninherited_method != nullptr, end_klass != nullptr);
557 klass = this_klass;
558 if (UNLIKELY(klass->IsProxyClass())) {
559 DCHECK(klass->GetCopiedMethodsSlice(pointer_size).empty());
560 klass = klass->GetSuperClass();
561 }
562 for (; klass != end_klass; klass = klass->GetSuperClass()) {
563 DCHECK(!klass->IsProxyClass());
564 for (ArtMethod& method : klass->GetCopiedMethodsSlice(pointer_size)) {
565 if (method.GetName() == name && method.GetSignature() == signature) {
566 return &method; // No further check needed, copied methods are inherited by definition.
567 }
568 }
569 }
570 return uninherited_method; // Return the `uninherited_method` if any.
571}
572
573
574ArtMethod* Class::FindClassMethod(const StringPiece& name,
575 const StringPiece& signature,
576 PointerSize pointer_size) {
577 return FindClassMethodWithSignature(this, name, signature, pointer_size);
578}
579
580ArtMethod* Class::FindClassMethod(const StringPiece& name,
581 const Signature& signature,
582 PointerSize pointer_size) {
583 return FindClassMethodWithSignature(this, name, signature, pointer_size);
584}
585
586ArtMethod* Class::FindClassMethod(ObjPtr<DexCache> dex_cache,
587 uint32_t dex_method_idx,
588 PointerSize pointer_size) {
589 // FIXME: Hijacking a proxy class by a custom class loader can break this assumption.
590 DCHECK(!IsProxyClass());
591
592 // First try to find a declared method by dex_method_idx if we have a dex_cache match.
593 ObjPtr<DexCache> this_dex_cache = GetDexCache();
594 if (this_dex_cache == dex_cache) {
595 // Lookup is always performed in the class referenced by the MethodId.
596 DCHECK_EQ(dex_type_idx_, GetDexFile().GetMethodId(dex_method_idx).class_idx_.index_);
597 for (ArtMethod& method : GetDeclaredMethodsSlice(pointer_size)) {
598 if (method.GetDexMethodIndex() == dex_method_idx) {
599 return &method;
600 }
601 }
602 }
603 // If not found, we need to search by name and signature.
604 const DexFile& dex_file = *dex_cache->GetDexFile();
605 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
606 const Signature signature = dex_file.GetMethodSignature(method_id);
607 StringPiece name; // Delay strlen() until actually needed.
608 // If we do not have a dex_cache match, try to find the declared method in this class now.
609 if (this_dex_cache != dex_cache && !GetDeclaredMethodsSlice(pointer_size).empty()) {
610 DCHECK(name.empty());
611 name = dex_file.StringDataByIdx(method_id.name_idx_);
612 for (ArtMethod& method : GetDeclaredMethodsSlice(pointer_size)) {
613 if (method.GetName() == name && method.GetSignature() == signature) {
614 return &method;
615 }
616 }
617 }
618
619 // Then search the superclass chain. If we find an inherited method, return it.
620 // If we find a method that's not inherited because of access restrictions,
621 // try to find a method inherited from an interface in copied methods.
622 ArtMethod* uninherited_method = nullptr;
623 ObjPtr<Class> klass = GetSuperClass();
624 for (; klass != nullptr; klass = klass->GetSuperClass()) {
625 ArtMethod* candidate_method = nullptr;
626 ArraySlice<ArtMethod> declared_methods = klass->GetDeclaredMethodsSlice(pointer_size);
627 if (klass->GetDexCache() == dex_cache) {
628 // Matching dex_cache. We cannot compare the `dex_method_idx` anymore because
629 // the type index differs, so compare the name index and proto index.
630 for (ArtMethod& method : declared_methods) {
631 const DexFile::MethodId& cmp_method_id = dex_file.GetMethodId(method.GetDexMethodIndex());
632 if (cmp_method_id.name_idx_ == method_id.name_idx_ &&
633 cmp_method_id.proto_idx_ == method_id.proto_idx_) {
634 candidate_method = &method;
635 break;
636 }
637 }
638 } else {
639 if (!declared_methods.empty() && name.empty()) {
640 name = dex_file.StringDataByIdx(method_id.name_idx_);
641 }
642 for (ArtMethod& method : declared_methods) {
643 if (method.GetName() == name && method.GetSignature() == signature) {
644 candidate_method = &method;
645 break;
646 }
647 }
648 }
649 if (candidate_method != nullptr) {
650 if (IsInheritedMethod(this, klass, *candidate_method)) {
651 return candidate_method;
652 } else {
653 uninherited_method = candidate_method;
654 break;
655 }
656 }
657 }
658
659 // Then search copied methods.
660 // If we found a method that's not inherited, stop the search in its declaring class.
661 ObjPtr<Class> end_klass = klass;
662 DCHECK_EQ(uninherited_method != nullptr, end_klass != nullptr);
663 // After we have searched the declared methods of the super-class chain,
664 // search copied methods which can contain methods from interfaces.
665 for (klass = this; klass != end_klass; klass = klass->GetSuperClass()) {
666 ArraySlice<ArtMethod> copied_methods = klass->GetCopiedMethodsSlice(pointer_size);
667 if (!copied_methods.empty() && name.empty()) {
668 name = dex_file.StringDataByIdx(method_id.name_idx_);
669 }
670 for (ArtMethod& method : copied_methods) {
671 if (method.GetName() == name && method.GetSignature() == signature) {
672 return &method; // No further check needed, copied methods are inherited by definition.
673 }
674 }
675 }
676 return uninherited_method; // Return the `uninherited_method` if any.
677}
678
679ArtMethod* Class::FindConstructor(const StringPiece& signature, PointerSize pointer_size) {
680 // Internal helper, never called on proxy classes. We can skip GetInterfaceMethodIfProxy().
681 DCHECK(!IsProxyClass());
682 StringPiece name("<init>");
683 for (ArtMethod& method : GetDirectMethodsSliceUnchecked(pointer_size)) {
684 if (method.GetName() == name && method.GetSignature() == signature) {
685 return &method;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800686 }
687 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700688 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800689}
690
Andreas Gampe542451c2016-07-26 09:02:02 -0700691ArtMethod* Class::FindDeclaredDirectMethodByName(const StringPiece& name,
692 PointerSize pointer_size) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000693 for (auto& method : GetDirectMethods(pointer_size)) {
694 ArtMethod* const np_method = method.GetInterfaceMethodIfProxy(pointer_size);
695 if (name == np_method->GetName()) {
696 return &method;
697 }
698 }
699 return nullptr;
700}
701
Andreas Gampe542451c2016-07-26 09:02:02 -0700702ArtMethod* Class::FindDeclaredVirtualMethodByName(const StringPiece& name,
703 PointerSize pointer_size) {
Jeff Hao13e748b2015-08-25 20:44:19 +0000704 for (auto& method : GetVirtualMethods(pointer_size)) {
705 ArtMethod* const np_method = method.GetInterfaceMethodIfProxy(pointer_size);
706 if (name == np_method->GetName()) {
707 return &method;
708 }
709 }
710 return nullptr;
711}
712
Andreas Gampe542451c2016-07-26 09:02:02 -0700713ArtMethod* Class::FindVirtualMethodForInterfaceSuper(ArtMethod* method, PointerSize pointer_size) {
Alex Light705ad492015-09-21 11:36:30 -0700714 DCHECK(method->GetDeclaringClass()->IsInterface());
715 DCHECK(IsInterface()) << "Should only be called on a interface class";
716 // Check if we have one defined on this interface first. This includes searching copied ones to
717 // get any conflict methods. Conflict methods are copied into each subtype from the supertype. We
718 // don't do any indirect method checks here.
719 for (ArtMethod& iface_method : GetVirtualMethods(pointer_size)) {
720 if (method->HasSameNameAndSignature(&iface_method)) {
721 return &iface_method;
722 }
723 }
724
725 std::vector<ArtMethod*> abstract_methods;
726 // Search through the IFTable for a working version. We don't need to check for conflicts
727 // because if there was one it would appear in this classes virtual_methods_ above.
728
729 Thread* self = Thread::Current();
730 StackHandleScope<2> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700731 MutableHandle<IfTable> iftable(hs.NewHandle(GetIfTable()));
732 MutableHandle<Class> iface(hs.NewHandle<Class>(nullptr));
Alex Light705ad492015-09-21 11:36:30 -0700733 size_t iftable_count = GetIfTableCount();
734 // Find the method. We don't need to check for conflicts because they would have been in the
735 // copied virtuals of this interface. Order matters, traverse in reverse topological order; most
736 // subtypiest interfaces get visited first.
737 for (size_t k = iftable_count; k != 0;) {
738 k--;
739 DCHECK_LT(k, iftable->Count());
740 iface.Assign(iftable->GetInterface(k));
741 // Iterate through every declared method on this interface. Each direct method's name/signature
742 // is unique so the order of the inner loop doesn't matter.
743 for (auto& method_iter : iface->GetDeclaredVirtualMethods(pointer_size)) {
744 ArtMethod* current_method = &method_iter;
745 if (current_method->HasSameNameAndSignature(method)) {
746 if (current_method->IsDefault()) {
747 // Handle JLS soft errors, a default method from another superinterface tree can
748 // "override" an abstract method(s) from another superinterface tree(s). To do this,
749 // ignore any [default] method which are dominated by the abstract methods we've seen so
750 // far. Check if overridden by any in abstract_methods. We do not need to check for
751 // default_conflicts because we would hit those before we get to this loop.
752 bool overridden = false;
753 for (ArtMethod* possible_override : abstract_methods) {
754 DCHECK(possible_override->HasSameNameAndSignature(current_method));
755 if (iface->IsAssignableFrom(possible_override->GetDeclaringClass())) {
756 overridden = true;
757 break;
758 }
759 }
760 if (!overridden) {
761 return current_method;
762 }
763 } else {
764 // Is not default.
765 // This might override another default method. Just stash it for now.
766 abstract_methods.push_back(current_method);
767 }
768 }
769 }
770 }
771 // If we reach here we either never found any declaration of the method (in which case
772 // 'abstract_methods' is empty or we found no non-overriden default methods in which case
773 // 'abstract_methods' contains a number of abstract implementations of the methods. We choose one
774 // of these arbitrarily.
775 return abstract_methods.empty() ? nullptr : abstract_methods[0];
776}
777
Andreas Gampe542451c2016-07-26 09:02:02 -0700778ArtMethod* Class::FindClassInitializer(PointerSize pointer_size) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700779 for (ArtMethod& method : GetDirectMethods(pointer_size)) {
780 if (method.IsClassInitializer()) {
781 DCHECK_STREQ(method.GetName(), "<clinit>");
782 DCHECK_STREQ(method.GetSignature().ToString().c_str(), "()V");
783 return &method;
Ian Rogersd91d6d62013-09-25 20:26:14 -0700784 }
785 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700786 return nullptr;
Ian Rogersd91d6d62013-09-25 20:26:14 -0700787}
788
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700789// Custom binary search to avoid double comparisons from std::binary_search.
790static ArtField* FindFieldByNameAndType(LengthPrefixedArray<ArtField>* fields,
791 const StringPiece& name,
792 const StringPiece& type)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700793 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700794 if (fields == nullptr) {
795 return nullptr;
796 }
797 size_t low = 0;
Vladimir Marko35831e82015-09-11 11:59:18 +0100798 size_t high = fields->size();
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700799 ArtField* ret = nullptr;
800 while (low < high) {
801 size_t mid = (low + high) / 2;
802 ArtField& field = fields->At(mid);
803 // Fields are sorted by class, then name, then type descriptor. This is verified in dex file
804 // verifier. There can be multiple fields with the same in the same class name due to proguard.
805 int result = StringPiece(field.GetName()).Compare(name);
806 if (result == 0) {
807 result = StringPiece(field.GetTypeDescriptor()).Compare(type);
808 }
809 if (result < 0) {
810 low = mid + 1;
811 } else if (result > 0) {
812 high = mid;
813 } else {
814 ret = &field;
815 break;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800816 }
817 }
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700818 if (kIsDebugBuild) {
819 ArtField* found = nullptr;
820 for (ArtField& field : MakeIterationRangeFromLengthPrefixedArray(fields)) {
821 if (name == field.GetName() && type == field.GetTypeDescriptor()) {
822 found = &field;
823 break;
824 }
825 }
David Sehr709b0702016-10-13 09:12:37 -0700826 CHECK_EQ(found, ret) << "Found " << found->PrettyField() << " vs " << ret->PrettyField();
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700827 }
828 return ret;
829}
830
831ArtField* Class::FindDeclaredInstanceField(const StringPiece& name, const StringPiece& type) {
832 // Binary search by name. Interfaces are not relevant because they can't contain instance fields.
833 return FindFieldByNameAndType(GetIFieldsPtr(), name, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800834}
835
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700836ArtField* Class::FindDeclaredInstanceField(ObjPtr<DexCache> dex_cache, uint32_t dex_field_idx) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800837 if (GetDexCache() == dex_cache) {
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700838 for (ArtField& field : GetIFields()) {
839 if (field.GetDexFieldIndex() == dex_field_idx) {
840 return &field;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800841 }
842 }
843 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700844 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800845}
846
Brian Carlstromea46f952013-07-30 01:26:50 -0700847ArtField* Class::FindInstanceField(const StringPiece& name, const StringPiece& type) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800848 // Is the field in this class, or any of its superclasses?
849 // Interfaces are not relevant because they can't contain instance fields.
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700850 for (ObjPtr<Class> c = this; c != nullptr; c = c->GetSuperClass()) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700851 ArtField* f = c->FindDeclaredInstanceField(name, type);
Brian Carlstrom004644f2014-06-18 08:34:01 -0700852 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800853 return f;
854 }
855 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700856 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800857}
858
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700859ArtField* Class::FindInstanceField(ObjPtr<DexCache> dex_cache, uint32_t dex_field_idx) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800860 // Is the field in this class, or any of its superclasses?
861 // Interfaces are not relevant because they can't contain instance fields.
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700862 for (ObjPtr<Class> c = this; c != nullptr; c = c->GetSuperClass()) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700863 ArtField* f = c->FindDeclaredInstanceField(dex_cache, dex_field_idx);
Brian Carlstrom004644f2014-06-18 08:34:01 -0700864 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800865 return f;
866 }
867 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700868 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800869}
870
Brian Carlstromea46f952013-07-30 01:26:50 -0700871ArtField* Class::FindDeclaredStaticField(const StringPiece& name, const StringPiece& type) {
Brian Carlstrom004644f2014-06-18 08:34:01 -0700872 DCHECK(type != nullptr);
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700873 return FindFieldByNameAndType(GetSFieldsPtr(), name, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800874}
875
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700876ArtField* Class::FindDeclaredStaticField(ObjPtr<DexCache> dex_cache, uint32_t dex_field_idx) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800877 if (dex_cache == GetDexCache()) {
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700878 for (ArtField& field : GetSFields()) {
879 if (field.GetDexFieldIndex() == dex_field_idx) {
880 return &field;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800881 }
882 }
883 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700884 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800885}
886
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700887ArtField* Class::FindStaticField(Thread* self,
Vladimir Marko19a4d372016-12-08 14:41:46 +0000888 ObjPtr<Class> klass,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700889 const StringPiece& name,
Mathieu Chartierf8322842014-05-16 10:59:25 -0700890 const StringPiece& type) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800891 // Is the field in this class (or its interfaces), or any of its
892 // superclasses (or their interfaces)?
Vladimir Marko19a4d372016-12-08 14:41:46 +0000893 for (ObjPtr<Class> k = klass; k != nullptr; k = k->GetSuperClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800894 // Is the field in this class?
Brian Carlstromea46f952013-07-30 01:26:50 -0700895 ArtField* f = k->FindDeclaredStaticField(name, type);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700896 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800897 return f;
898 }
899 // Is this field in any of this class' interfaces?
Vladimir Marko19a4d372016-12-08 14:41:46 +0000900 for (uint32_t i = 0, num_interfaces = k->NumDirectInterfaces(); i != num_interfaces; ++i) {
901 ObjPtr<Class> interface = GetDirectInterface(self, k, i);
902 DCHECK(interface != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700903 f = FindStaticField(self, interface, name, type);
904 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800905 return f;
906 }
907 }
908 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700909 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800910}
911
Vladimir Markobb268b12016-06-30 15:52:56 +0100912ArtField* Class::FindStaticField(Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700913 ObjPtr<Class> klass,
914 ObjPtr<DexCache> dex_cache,
Mathieu Chartierf8322842014-05-16 10:59:25 -0700915 uint32_t dex_field_idx) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700916 for (ObjPtr<Class> k = klass; k != nullptr; k = k->GetSuperClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800917 // Is the field in this class?
Brian Carlstromea46f952013-07-30 01:26:50 -0700918 ArtField* f = k->FindDeclaredStaticField(dex_cache, dex_field_idx);
Brian Carlstrom004644f2014-06-18 08:34:01 -0700919 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800920 return f;
921 }
Vladimir Markobb268b12016-06-30 15:52:56 +0100922 // Though GetDirectInterface() should not cause thread suspension when called
923 // from here, it takes a Handle as an argument, so we need to wrap `k`.
Mathieu Chartier268764d2016-09-13 12:09:38 -0700924 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800925 // Is this field in any of this class' interfaces?
Vladimir Marko19a4d372016-12-08 14:41:46 +0000926 for (uint32_t i = 0, num_interfaces = k->NumDirectInterfaces(); i != num_interfaces; ++i) {
927 ObjPtr<Class> interface = GetDirectInterface(self, k, i);
928 DCHECK(interface != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700929 f = FindStaticField(self, interface, dex_cache, dex_field_idx);
930 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800931 return f;
932 }
933 }
934 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700935 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800936}
937
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700938ArtField* Class::FindField(Thread* self,
Vladimir Marko19a4d372016-12-08 14:41:46 +0000939 ObjPtr<Class> klass,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700940 const StringPiece& name,
Mathieu Chartierf8322842014-05-16 10:59:25 -0700941 const StringPiece& type) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800942 // Find a field using the JLS field resolution order
Vladimir Marko19a4d372016-12-08 14:41:46 +0000943 for (ObjPtr<Class> k = klass; k != nullptr; k = k->GetSuperClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800944 // Is the field in this class?
Brian Carlstromea46f952013-07-30 01:26:50 -0700945 ArtField* f = k->FindDeclaredInstanceField(name, type);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700946 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800947 return f;
948 }
949 f = k->FindDeclaredStaticField(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 // Is this field in any of this class' interfaces?
Vladimir Marko19a4d372016-12-08 14:41:46 +0000954 for (uint32_t i = 0, num_interfaces = k->NumDirectInterfaces(); i != num_interfaces; ++i) {
955 ObjPtr<Class> interface = GetDirectInterface(self, k, i);
956 DCHECK(interface != nullptr);
957 f = FindStaticField(self, interface, name, type);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700958 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800959 return f;
960 }
961 }
962 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700963 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800964}
965
Andreas Gampe542451c2016-07-26 09:02:02 -0700966void Class::SetSkipAccessChecksFlagOnAllMethods(PointerSize pointer_size) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700967 DCHECK(IsVerified());
Alex Lighte64300b2015-12-15 15:02:47 -0800968 for (auto& m : GetMethods(pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -0700969 if (!m.IsNative() && m.IsInvokable()) {
Igor Murashkindf707e42016-02-02 16:56:50 -0800970 m.SetSkipAccessChecks();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700971 }
972 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +0200973}
974
Ian Rogers1ff3c982014-08-12 02:30:58 -0700975const char* Class::GetDescriptor(std::string* storage) {
976 if (IsPrimitive()) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700977 return Primitive::Descriptor(GetPrimitiveType());
Ian Rogers1ff3c982014-08-12 02:30:58 -0700978 } else if (IsArrayClass()) {
979 return GetArrayDescriptor(storage);
Nicolas Geoffray3a090922015-11-24 09:17:30 +0000980 } else if (IsProxyClass()) {
981 *storage = Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(this);
Ian Rogers1ff3c982014-08-12 02:30:58 -0700982 return storage->c_str();
Mathieu Chartierf8322842014-05-16 10:59:25 -0700983 } else {
984 const DexFile& dex_file = GetDexFile();
985 const DexFile::TypeId& type_id = dex_file.GetTypeId(GetClassDef()->class_idx_);
986 return dex_file.GetTypeDescriptor(type_id);
987 }
988}
989
Ian Rogers1ff3c982014-08-12 02:30:58 -0700990const char* Class::GetArrayDescriptor(std::string* storage) {
991 std::string temp;
992 const char* elem_desc = GetComponentType()->GetDescriptor(&temp);
993 *storage = "[";
994 *storage += elem_desc;
995 return storage->c_str();
Mathieu Chartierf8322842014-05-16 10:59:25 -0700996}
997
998const DexFile::ClassDef* Class::GetClassDef() {
999 uint16_t class_def_idx = GetDexClassDefIndex();
1000 if (class_def_idx == DexFile::kDexNoIndex16) {
1001 return nullptr;
1002 }
1003 return &GetDexFile().GetClassDef(class_def_idx);
1004}
1005
Andreas Gampea5b09a62016-11-17 15:21:22 -08001006dex::TypeIndex Class::GetDirectInterfaceTypeIdx(uint32_t idx) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001007 DCHECK(!IsPrimitive());
1008 DCHECK(!IsArrayClass());
1009 return GetInterfaceTypeList()->GetTypeItem(idx).type_idx_;
1010}
1011
Vladimir Marko19a4d372016-12-08 14:41:46 +00001012ObjPtr<Class> Class::GetDirectInterface(Thread* self, ObjPtr<Class> klass, uint32_t idx) {
1013 DCHECK(klass != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07001014 DCHECK(!klass->IsPrimitive());
1015 if (klass->IsArrayClass()) {
1016 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Vladimir Marko19a4d372016-12-08 14:41:46 +00001017 // Use ClassLinker::LookupClass(); avoid poisoning ObjPtr<>s by ClassLinker::FindSystemClass().
1018 ObjPtr<Class> interface;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001019 if (idx == 0) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001020 interface = class_linker->LookupClass(self, "Ljava/lang/Cloneable;", nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07001021 } else {
1022 DCHECK_EQ(1U, idx);
Vladimir Marko19a4d372016-12-08 14:41:46 +00001023 interface = class_linker->LookupClass(self, "Ljava/io/Serializable;", nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07001024 }
Vladimir Marko19a4d372016-12-08 14:41:46 +00001025 DCHECK(interface != nullptr);
1026 return interface;
Nicolas Geoffray3a090922015-11-24 09:17:30 +00001027 } else if (klass->IsProxyClass()) {
Narayan Kamath6b2dc312017-03-14 13:26:12 +00001028 ObjPtr<ObjectArray<Class>> interfaces = klass->GetProxyInterfaces();
Mathieu Chartierf8322842014-05-16 10:59:25 -07001029 DCHECK(interfaces != nullptr);
1030 return interfaces->Get(idx);
1031 } else {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001032 dex::TypeIndex type_idx = klass->GetDirectInterfaceTypeIdx(idx);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001033 ObjPtr<Class> interface = ClassLinker::LookupResolvedType(
1034 type_idx, klass->GetDexCache(), klass->GetClassLoader());
Mathieu Chartierf8322842014-05-16 10:59:25 -07001035 return interface;
1036 }
1037}
1038
Vladimir Marko19a4d372016-12-08 14:41:46 +00001039ObjPtr<Class> Class::ResolveDirectInterface(Thread* self, Handle<Class> klass, uint32_t idx) {
1040 ObjPtr<Class> interface = GetDirectInterface(self, klass.Get(), idx);
1041 if (interface == nullptr) {
1042 DCHECK(!klass->IsArrayClass());
1043 DCHECK(!klass->IsProxyClass());
1044 dex::TypeIndex type_idx = klass->GetDirectInterfaceTypeIdx(idx);
1045 interface = Runtime::Current()->GetClassLinker()->ResolveType(klass->GetDexFile(),
1046 type_idx,
1047 klass.Get());
1048 CHECK(interface != nullptr || self->IsExceptionPending());
1049 }
1050 return interface;
1051}
1052
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001053ObjPtr<Class> Class::GetCommonSuperClass(Handle<Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08001054 DCHECK(klass != nullptr);
Calin Juravle52503d82015-11-11 16:58:31 +00001055 DCHECK(!klass->IsInterface());
1056 DCHECK(!IsInterface());
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001057 ObjPtr<Class> common_super_class = this;
Calin Juravle52503d82015-11-11 16:58:31 +00001058 while (!common_super_class->IsAssignableFrom(klass.Get())) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001059 ObjPtr<Class> old_common = common_super_class;
Aart Bik22deed02016-04-04 14:19:01 -07001060 common_super_class = old_common->GetSuperClass();
David Sehr709b0702016-10-13 09:12:37 -07001061 DCHECK(common_super_class != nullptr) << old_common->PrettyClass();
Calin Juravle52503d82015-11-11 16:58:31 +00001062 }
Calin Juravle52503d82015-11-11 16:58:31 +00001063 return common_super_class;
1064}
1065
Mathieu Chartierf8322842014-05-16 10:59:25 -07001066const char* Class::GetSourceFile() {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001067 const DexFile& dex_file = GetDexFile();
1068 const DexFile::ClassDef* dex_class_def = GetClassDef();
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001069 if (dex_class_def == nullptr) {
1070 // Generated classes have no class def.
1071 return nullptr;
1072 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001073 return dex_file.GetSourceFile(*dex_class_def);
1074}
1075
1076std::string Class::GetLocation() {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001077 ObjPtr<DexCache> dex_cache = GetDexCache();
Nicolas Geoffray3a090922015-11-24 09:17:30 +00001078 if (dex_cache != nullptr && !IsProxyClass()) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001079 return dex_cache->GetLocation()->ToModifiedUtf8();
1080 }
1081 // Arrays and proxies are generated and have no corresponding dex file location.
1082 return "generated class";
1083}
1084
1085const DexFile::TypeList* Class::GetInterfaceTypeList() {
1086 const DexFile::ClassDef* class_def = GetClassDef();
1087 if (class_def == nullptr) {
1088 return nullptr;
1089 }
1090 return GetDexFile().GetInterfacesList(*class_def);
1091}
1092
Andreas Gampe542451c2016-07-26 09:02:02 -07001093void Class::PopulateEmbeddedVTable(PointerSize pointer_size) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001094 PointerArray* table = GetVTableDuringLinking();
David Sehr709b0702016-10-13 09:12:37 -07001095 CHECK(table != nullptr) << PrettyClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001096 const size_t table_length = table->GetLength();
1097 SetEmbeddedVTableLength(table_length);
1098 for (size_t i = 0; i < table_length; i++) {
1099 SetEmbeddedVTableEntry(i, table->GetElementPtrSize<ArtMethod*>(i, pointer_size), pointer_size);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001100 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07001101 // Keep java.lang.Object class's vtable around for since it's easier
1102 // to be reused by array classes during their linking.
1103 if (!IsObjectClass()) {
1104 SetVTable(nullptr);
1105 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001106}
1107
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001108class ReadBarrierOnNativeRootsVisitor {
1109 public:
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001110 void operator()(ObjPtr<Object> obj ATTRIBUTE_UNUSED,
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001111 MemberOffset offset ATTRIBUTE_UNUSED,
1112 bool is_static ATTRIBUTE_UNUSED) const {}
1113
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001114 void VisitRootIfNonNull(CompressedReference<Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001115 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001116 if (!root->IsNull()) {
1117 VisitRoot(root);
1118 }
1119 }
1120
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001121 void VisitRoot(CompressedReference<Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001122 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001123 ObjPtr<Object> old_ref = root->AsMirrorPtr();
1124 ObjPtr<Object> new_ref = ReadBarrier::BarrierForRoot(root);
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001125 if (old_ref != new_ref) {
1126 // Update the field atomically. This may fail if mutator updates before us, but it's ok.
1127 auto* atomic_root =
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001128 reinterpret_cast<Atomic<CompressedReference<Object>>*>(root);
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001129 atomic_root->CompareExchangeStrongSequentiallyConsistent(
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001130 CompressedReference<Object>::FromMirrorPtr(old_ref.Ptr()),
1131 CompressedReference<Object>::FromMirrorPtr(new_ref.Ptr()));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001132 }
1133 }
1134};
1135
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001136// The pre-fence visitor for Class::CopyOf().
1137class CopyClassVisitor {
1138 public:
Andreas Gampe542451c2016-07-26 09:02:02 -07001139 CopyClassVisitor(Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001140 Handle<Class>* orig,
Andreas Gampe542451c2016-07-26 09:02:02 -07001141 size_t new_length,
1142 size_t copy_bytes,
1143 ImTable* imt,
1144 PointerSize pointer_size)
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001145 : self_(self), orig_(orig), new_length_(new_length),
Mathieu Chartiere401d142015-04-22 13:56:20 -07001146 copy_bytes_(copy_bytes), imt_(imt), pointer_size_(pointer_size) {
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001147 }
1148
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001149 void operator()(ObjPtr<Object> obj, size_t usable_size ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001150 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001151 StackHandleScope<1> hs(self_);
1152 Handle<mirror::Class> h_new_class_obj(hs.NewHandle(obj->AsClass()));
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001153 Object::CopyObject(h_new_class_obj.Get(), orig_->Get(), copy_bytes_);
1154 Class::SetStatus(h_new_class_obj, Class::kStatusResolving, self_);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001155 h_new_class_obj->PopulateEmbeddedVTable(pointer_size_);
1156 h_new_class_obj->SetImt(imt_, pointer_size_);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001157 h_new_class_obj->SetClassSize(new_length_);
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001158 // Visit all of the references to make sure there is no from space references in the native
1159 // roots.
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001160 ObjPtr<Object>(h_new_class_obj.Get())->VisitReferences(
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001161 ReadBarrierOnNativeRootsVisitor(), VoidFunctor());
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001162 }
1163
1164 private:
1165 Thread* const self_;
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001166 Handle<Class>* const orig_;
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001167 const size_t new_length_;
1168 const size_t copy_bytes_;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001169 ImTable* imt_;
Andreas Gampe542451c2016-07-26 09:02:02 -07001170 const PointerSize pointer_size_;
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001171 DISALLOW_COPY_AND_ASSIGN(CopyClassVisitor);
1172};
1173
Andreas Gampe542451c2016-07-26 09:02:02 -07001174Class* Class::CopyOf(Thread* self, int32_t new_length, ImTable* imt, PointerSize pointer_size) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001175 DCHECK_GE(new_length, static_cast<int32_t>(sizeof(Class)));
1176 // We may get copied by a compacting GC.
1177 StackHandleScope<1> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001178 Handle<Class> h_this(hs.NewHandle(this));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001179 gc::Heap* heap = Runtime::Current()->GetHeap();
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001180 // The num_bytes (3rd param) is sizeof(Class) as opposed to SizeOf()
1181 // to skip copying the tail part that we will overwrite here.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001182 CopyClassVisitor visitor(self, &h_this, new_length, sizeof(Class), imt, pointer_size);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001183 ObjPtr<Object> new_class = kMovingClasses ?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001184 heap->AllocObject<true>(self, java_lang_Class_.Read(), new_length, visitor) :
1185 heap->AllocNonMovableObject<true>(self, java_lang_Class_.Read(), new_length, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001186 if (UNLIKELY(new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001187 self->AssertPendingOOMException();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001188 return nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001189 }
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001190 return new_class->AsClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001191}
1192
Nicolas Geoffray3a090922015-11-24 09:17:30 +00001193bool Class::ProxyDescriptorEquals(const char* match) {
1194 DCHECK(IsProxyClass());
1195 return Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(this) == match;
Vladimir Marko3481ba22015-04-13 12:22:36 +01001196}
1197
Mathieu Chartiere401d142015-04-22 13:56:20 -07001198// TODO: Move this to java_lang_Class.cc?
1199ArtMethod* Class::GetDeclaredConstructor(
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001200 Thread* self, Handle<ObjectArray<Class>> args, PointerSize pointer_size) {
Andreas Gampe6039e562016-04-05 18:18:43 -07001201 for (auto& m : GetDirectMethods(pointer_size)) {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001202 // Skip <clinit> which is a static constructor, as well as non constructors.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001203 if (m.IsStatic() || !m.IsConstructor()) {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001204 continue;
1205 }
1206 // May cause thread suspension and exceptions.
Andreas Gampe542451c2016-07-26 09:02:02 -07001207 if (m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->EqualParameters(args)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001208 return &m;
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001209 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001210 if (UNLIKELY(self->IsExceptionPending())) {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001211 return nullptr;
1212 }
1213 }
1214 return nullptr;
1215}
1216
Mathieu Chartiere401d142015-04-22 13:56:20 -07001217uint32_t Class::Depth() {
1218 uint32_t depth = 0;
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001219 for (ObjPtr<Class> klass = this; klass->GetSuperClass() != nullptr; klass = klass->GetSuperClass()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001220 depth++;
1221 }
1222 return depth;
1223}
1224
Andreas Gampea5b09a62016-11-17 15:21:22 -08001225dex::TypeIndex Class::FindTypeIndexInOtherDexFile(const DexFile& dex_file) {
Nicolas Geoffraye4084a52016-02-18 14:43:42 +00001226 std::string temp;
1227 const DexFile::TypeId* type_id = dex_file.FindTypeId(GetDescriptor(&temp));
Andreas Gampe2722f382017-06-08 18:03:25 -07001228 return (type_id == nullptr) ? dex::TypeIndex() : dex_file.GetIndexForTypeId(*type_id);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +00001229}
1230
Andreas Gampe542451c2016-07-26 09:02:02 -07001231template <PointerSize kPointerSize, bool kTransactionActive>
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001232ObjPtr<Method> Class::GetDeclaredMethodInternal(
1233 Thread* self,
1234 ObjPtr<Class> klass,
1235 ObjPtr<String> name,
1236 ObjPtr<ObjectArray<Class>> args) {
Andreas Gampebc4d2182016-02-22 10:03:12 -08001237 // Covariant return types permit the class to define multiple
1238 // methods with the same name and parameter types. Prefer to
1239 // return a non-synthetic method in such situations. We may
1240 // still return a synthetic method to handle situations like
1241 // escalated visibility. We never return miranda methods that
1242 // were synthesized by the runtime.
1243 constexpr uint32_t kSkipModifiers = kAccMiranda | kAccSynthetic;
1244 StackHandleScope<3> hs(self);
1245 auto h_method_name = hs.NewHandle(name);
Andreas Gampefa4333d2017-02-14 11:10:34 -08001246 if (UNLIKELY(h_method_name == nullptr)) {
Andreas Gampebc4d2182016-02-22 10:03:12 -08001247 ThrowNullPointerException("name == null");
1248 return nullptr;
1249 }
1250 auto h_args = hs.NewHandle(args);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001251 Handle<Class> h_klass = hs.NewHandle(klass);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001252 ArtMethod* result = nullptr;
Andreas Gampee01e3642016-07-25 13:06:04 -07001253 for (auto& m : h_klass->GetDeclaredVirtualMethods(kPointerSize)) {
1254 auto* np_method = m.GetInterfaceMethodIfProxy(kPointerSize);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001255 // May cause thread suspension.
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001256 ObjPtr<String> np_name = np_method->GetNameAsString(self);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001257 if (!np_name->Equals(h_method_name.Get()) || !np_method->EqualParameters(h_args)) {
1258 if (UNLIKELY(self->IsExceptionPending())) {
1259 return nullptr;
1260 }
1261 continue;
1262 }
1263 auto modifiers = m.GetAccessFlags();
1264 if ((modifiers & kSkipModifiers) == 0) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001265 return Method::CreateFromArtMethod<kPointerSize, kTransactionActive>(self, &m);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001266 }
1267 if ((modifiers & kAccMiranda) == 0) {
1268 result = &m; // Remember as potential result if it's not a miranda method.
1269 }
1270 }
1271 if (result == nullptr) {
Andreas Gampee01e3642016-07-25 13:06:04 -07001272 for (auto& m : h_klass->GetDirectMethods(kPointerSize)) {
Andreas Gampebc4d2182016-02-22 10:03:12 -08001273 auto modifiers = m.GetAccessFlags();
1274 if ((modifiers & kAccConstructor) != 0) {
1275 continue;
1276 }
Andreas Gampee01e3642016-07-25 13:06:04 -07001277 auto* np_method = m.GetInterfaceMethodIfProxy(kPointerSize);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001278 // May cause thread suspension.
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001279 ObjPtr<String> np_name = np_method->GetNameAsString(self);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001280 if (np_name == nullptr) {
1281 self->AssertPendingException();
1282 return nullptr;
1283 }
1284 if (!np_name->Equals(h_method_name.Get()) || !np_method->EqualParameters(h_args)) {
1285 if (UNLIKELY(self->IsExceptionPending())) {
1286 return nullptr;
1287 }
1288 continue;
1289 }
1290 if ((modifiers & kSkipModifiers) == 0) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001291 return Method::CreateFromArtMethod<kPointerSize, kTransactionActive>(self, &m);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001292 }
1293 // Direct methods cannot be miranda methods, so this potential result must be synthetic.
1294 result = &m;
1295 }
1296 }
1297 return result != nullptr
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001298 ? Method::CreateFromArtMethod<kPointerSize, kTransactionActive>(self, result)
Andreas Gampebc4d2182016-02-22 10:03:12 -08001299 : nullptr;
1300}
1301
1302template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001303ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k32, false>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001304 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001305 ObjPtr<Class> klass,
1306 ObjPtr<String> name,
1307 ObjPtr<ObjectArray<Class>> args);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001308template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001309ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k32, true>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001310 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001311 ObjPtr<Class> klass,
1312 ObjPtr<String> name,
1313 ObjPtr<ObjectArray<Class>> args);
Andreas Gampee01e3642016-07-25 13:06:04 -07001314template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001315ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k64, false>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001316 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001317 ObjPtr<Class> klass,
1318 ObjPtr<String> name,
1319 ObjPtr<ObjectArray<Class>> args);
Andreas Gampee01e3642016-07-25 13:06:04 -07001320template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001321ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k64, true>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001322 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001323 ObjPtr<Class> klass,
1324 ObjPtr<String> name,
1325 ObjPtr<ObjectArray<Class>> args);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001326
Andreas Gampe542451c2016-07-26 09:02:02 -07001327template <PointerSize kPointerSize, bool kTransactionActive>
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001328ObjPtr<Constructor> Class::GetDeclaredConstructorInternal(
Andreas Gampe6039e562016-04-05 18:18:43 -07001329 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001330 ObjPtr<Class> klass,
1331 ObjPtr<ObjectArray<Class>> args) {
Andreas Gampe6039e562016-04-05 18:18:43 -07001332 StackHandleScope<1> hs(self);
Andreas Gampee01e3642016-07-25 13:06:04 -07001333 ArtMethod* result = klass->GetDeclaredConstructor(self, hs.NewHandle(args), kPointerSize);
Andreas Gampe6039e562016-04-05 18:18:43 -07001334 return result != nullptr
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001335 ? Constructor::CreateFromArtMethod<kPointerSize, kTransactionActive>(self, result)
Andreas Gampe6039e562016-04-05 18:18:43 -07001336 : nullptr;
1337}
1338
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001339// Constructor::CreateFromArtMethod<kTransactionActive>(self, result)
Andreas Gampe6039e562016-04-05 18:18:43 -07001340
Andreas Gampe542451c2016-07-26 09:02:02 -07001341template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001342ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k32, false>(
Andreas Gampe6039e562016-04-05 18:18:43 -07001343 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001344 ObjPtr<Class> klass,
1345 ObjPtr<ObjectArray<Class>> args);
Andreas Gampe542451c2016-07-26 09:02:02 -07001346template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001347ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k32, true>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001348 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001349 ObjPtr<Class> klass,
1350 ObjPtr<ObjectArray<Class>> args);
Andreas Gampe542451c2016-07-26 09:02:02 -07001351template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001352ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k64, false>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001353 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001354 ObjPtr<Class> klass,
1355 ObjPtr<ObjectArray<Class>> args);
Andreas Gampe542451c2016-07-26 09:02:02 -07001356template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001357ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k64, true>(
Andreas Gampe6039e562016-04-05 18:18:43 -07001358 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001359 ObjPtr<Class> klass,
1360 ObjPtr<ObjectArray<Class>> args);
Andreas Gampe6039e562016-04-05 18:18:43 -07001361
Andreas Gampe715fdc22016-04-18 17:07:30 -07001362int32_t Class::GetInnerClassFlags(Handle<Class> h_this, int32_t default_value) {
1363 if (h_this->IsProxyClass() || h_this->GetDexCache() == nullptr) {
1364 return default_value;
1365 }
1366 uint32_t flags;
David Sehr9323e6e2016-09-13 08:58:35 -07001367 if (!annotations::GetInnerClassFlags(h_this, &flags)) {
Andreas Gampe715fdc22016-04-18 17:07:30 -07001368 return default_value;
1369 }
1370 return flags;
1371}
1372
Mathieu Chartier93bbee02016-08-31 09:38:40 -07001373void Class::SetObjectSizeAllocFastPath(uint32_t new_object_size) {
1374 if (Runtime::Current()->IsActiveTransaction()) {
1375 SetField32Volatile<true>(ObjectSizeAllocFastPathOffset(), new_object_size);
1376 } else {
1377 SetField32Volatile<false>(ObjectSizeAllocFastPathOffset(), new_object_size);
1378 }
1379}
1380
David Sehr709b0702016-10-13 09:12:37 -07001381std::string Class::PrettyDescriptor(ObjPtr<mirror::Class> klass) {
1382 if (klass == nullptr) {
1383 return "null";
1384 }
1385 return klass->PrettyDescriptor();
1386}
1387
1388std::string Class::PrettyDescriptor() {
1389 std::string temp;
1390 return art::PrettyDescriptor(GetDescriptor(&temp));
1391}
1392
1393std::string Class::PrettyClass(ObjPtr<mirror::Class> c) {
1394 if (c == nullptr) {
1395 return "null";
1396 }
1397 return c->PrettyClass();
1398}
1399
1400std::string Class::PrettyClass() {
1401 std::string result;
1402 result += "java.lang.Class<";
1403 result += PrettyDescriptor();
1404 result += ">";
1405 return result;
1406}
1407
1408std::string Class::PrettyClassAndClassLoader(ObjPtr<mirror::Class> c) {
1409 if (c == nullptr) {
1410 return "null";
1411 }
1412 return c->PrettyClassAndClassLoader();
1413}
1414
1415std::string Class::PrettyClassAndClassLoader() {
1416 std::string result;
1417 result += "java.lang.Class<";
1418 result += PrettyDescriptor();
1419 result += ",";
1420 result += mirror::Object::PrettyTypeOf(GetClassLoader());
1421 // TODO: add an identifying hash value for the loader
1422 result += ">";
1423 return result;
1424}
1425
Andreas Gampe90b936d2017-01-31 08:58:55 -08001426template<VerifyObjectFlags kVerifyFlags> void Class::GetAccessFlagsDCheck() {
1427 // Check class is loaded/retired or this is java.lang.String that has a
1428 // circularity issue during loading the names of its members
1429 DCHECK(IsIdxLoaded<kVerifyFlags>() || IsRetired<kVerifyFlags>() ||
1430 IsErroneous<static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis)>() ||
1431 this == String::GetJavaLangString())
1432 << "IsIdxLoaded=" << IsIdxLoaded<kVerifyFlags>()
1433 << " IsRetired=" << IsRetired<kVerifyFlags>()
1434 << " IsErroneous=" <<
1435 IsErroneous<static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis)>()
1436 << " IsString=" << (this == String::GetJavaLangString())
1437 << " status= " << GetStatus<kVerifyFlags>()
1438 << " descriptor=" << PrettyDescriptor();
1439}
1440// Instantiate the common cases.
1441template void Class::GetAccessFlagsDCheck<kVerifyNone>();
1442template void Class::GetAccessFlagsDCheck<kVerifyThis>();
1443template void Class::GetAccessFlagsDCheck<kVerifyReads>();
1444template void Class::GetAccessFlagsDCheck<kVerifyWrites>();
1445template void Class::GetAccessFlagsDCheck<kVerifyAll>();
1446
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001447} // namespace mirror
1448} // namespace art