blob: a0a2f46433a8de1bca40b82d5b7bc3692002dc40 [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 Gampe170331f2017-12-07 18:41:03 -080023#include "base/logging.h" // For VLOG.
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070024#include "class-inl.h"
Alex Lightd6251582016-10-31 11:12:30 -070025#include "class_ext.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010026#include "class_linker-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080027#include "class_loader.h"
28#include "dex_cache.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070029#include "dex_file-inl.h"
David Sehr9323e6e2016-09-13 08:58:35 -070030#include "dex_file_annotations.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070031#include "gc/accounting/card_table-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070032#include "handle_scope-inl.h"
Igor Murashkin86083f72017-10-27 10:59:04 -070033#include "subtype_check.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -070034#include "method.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070035#include "object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080036#include "object-refvisitor-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070037#include "object_array-inl.h"
Alex Lightd6251582016-10-31 11:12:30 -070038#include "object_lock.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070039#include "runtime.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080040#include "thread.h"
41#include "throwable.h"
42#include "utils.h"
43#include "well_known_classes.h"
44
45namespace art {
Igor Murashkin86083f72017-10-27 10:59:04 -070046
47// TODO: move to own CC file?
48constexpr size_t BitString::kBitSizeAtPosition[BitString::kCapacity];
49constexpr size_t BitString::kCapacity;
50
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080051namespace mirror {
52
Andreas Gampe46ee31b2016-12-14 10:11:49 -080053using android::base::StringPrintf;
54
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070055GcRoot<Class> Class::java_lang_Class_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056
Andreas Gampeee5303f2017-08-31 15:34:42 -070057constexpr Class::Status Class::kStatusRetired;
58constexpr Class::Status Class::kStatusErrorResolved;
59constexpr Class::Status Class::kStatusErrorUnresolved;
60constexpr Class::Status Class::kStatusNotReady;
61constexpr Class::Status Class::kStatusIdx;
62constexpr Class::Status Class::kStatusLoaded;
63constexpr Class::Status Class::kStatusResolving;
64constexpr Class::Status Class::kStatusResolved;
65constexpr Class::Status Class::kStatusVerifying;
66constexpr Class::Status Class::kStatusRetryVerificationAtRuntime;
67constexpr Class::Status Class::kStatusVerifyingAtRuntime;
68constexpr Class::Status Class::kStatusVerified;
69constexpr Class::Status Class::kStatusSuperclassValidated;
70constexpr Class::Status Class::kStatusInitializing;
71constexpr Class::Status Class::kStatusInitialized;
72constexpr Class::Status Class::kStatusMax;
73
Mathieu Chartier28bd2e42016-10-04 13:54:57 -070074void Class::SetClassClass(ObjPtr<Class> java_lang_Class) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070075 CHECK(java_lang_Class_.IsNull())
76 << java_lang_Class_.Read()
Hiroshi Yamauchi4f1ebc22014-06-25 14:30:41 -070077 << " " << java_lang_Class;
Brian Carlstrom004644f2014-06-18 08:34:01 -070078 CHECK(java_lang_Class != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -070079 java_lang_Class->SetClassFlags(kClassFlagClass);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070080 java_lang_Class_ = GcRoot<Class>(java_lang_Class);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080081}
82
83void Class::ResetClass() {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070084 CHECK(!java_lang_Class_.IsNull());
85 java_lang_Class_ = GcRoot<Class>(nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080086}
87
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -070088void Class::VisitRoots(RootVisitor* visitor) {
89 java_lang_Class_.VisitRootIfNonNull(visitor, RootInfo(kRootStickyClass));
Mathieu Chartierc528dba2013-11-26 12:00:11 -080090}
91
Alex Light0273ad12016-11-02 11:19:31 -070092ClassExt* Class::EnsureExtDataPresent(Thread* self) {
93 ObjPtr<ClassExt> existing(GetExtData());
94 if (!existing.IsNull()) {
95 return existing.Ptr();
96 }
97 StackHandleScope<3> hs(self);
98 // Handlerize 'this' since we are allocating here.
99 Handle<Class> h_this(hs.NewHandle(this));
100 // Clear exception so we can allocate.
101 Handle<Throwable> throwable(hs.NewHandle(self->GetException()));
102 self->ClearException();
103 // Allocate the ClassExt
104 Handle<ClassExt> new_ext(hs.NewHandle(ClassExt::Alloc(self)));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800105 if (new_ext == nullptr) {
Alex Light0273ad12016-11-02 11:19:31 -0700106 // OOM allocating the classExt.
107 // TODO Should we restore the suppressed exception?
108 self->AssertPendingOOMException();
109 return nullptr;
Andreas Gampe99babb62015-11-02 16:20:00 -0800110 } else {
Alex Light0273ad12016-11-02 11:19:31 -0700111 MemberOffset ext_offset(OFFSET_OF_OBJECT_MEMBER(Class, ext_data_));
112 bool set;
113 // Set the ext_data_ field using CAS semantics.
114 if (Runtime::Current()->IsActiveTransaction()) {
115 set = h_this->CasFieldStrongSequentiallyConsistentObject<true>(ext_offset,
116 ObjPtr<ClassExt>(nullptr),
117 new_ext.Get());
118 } else {
119 set = h_this->CasFieldStrongSequentiallyConsistentObject<false>(ext_offset,
120 ObjPtr<ClassExt>(nullptr),
121 new_ext.Get());
122 }
123 ObjPtr<ClassExt> ret(set ? new_ext.Get() : h_this->GetExtData());
124 DCHECK(!set || h_this->GetExtData() == new_ext.Get());
125 CHECK(!ret.IsNull());
126 // Restore the exception if there was one.
Andreas Gampefa4333d2017-02-14 11:10:34 -0800127 if (throwable != nullptr) {
Alex Light0273ad12016-11-02 11:19:31 -0700128 self->SetException(throwable.Get());
129 }
130 return ret.Ptr();
Andreas Gampe99babb62015-11-02 16:20:00 -0800131 }
132}
133
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700134void Class::SetStatus(Handle<Class> h_this, Status new_status, Thread* self) {
135 Status old_status = h_this->GetStatus();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700136 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
137 bool class_linker_initialized = class_linker != nullptr && class_linker->IsInitialized();
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700138 if (LIKELY(class_linker_initialized)) {
Vladimir Marko72ab6842017-01-20 19:32:50 +0000139 if (UNLIKELY(new_status <= old_status &&
140 new_status != kStatusErrorUnresolved &&
141 new_status != kStatusErrorResolved &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700142 new_status != kStatusRetired)) {
David Sehr709b0702016-10-13 09:12:37 -0700143 LOG(FATAL) << "Unexpected change back of class status for " << h_this->PrettyClass()
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700144 << " " << old_status << " -> " << new_status;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -0700145 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700146 if (new_status >= kStatusResolved || old_status >= kStatusResolved) {
147 // When classes are being resolved the resolution code should hold the lock.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700148 CHECK_EQ(h_this->GetLockOwnerThreadId(), self->GetThreadId())
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700149 << "Attempt to change status of class while not holding its lock: "
David Sehr709b0702016-10-13 09:12:37 -0700150 << h_this->PrettyClass() << " " << old_status << " -> " << new_status;
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700151 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800152 }
Vladimir Marko72ab6842017-01-20 19:32:50 +0000153 if (UNLIKELY(IsErroneous(new_status))) {
154 CHECK(!h_this->IsErroneous())
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700155 << "Attempt to set as erroneous an already erroneous class "
Vladimir Marko72ab6842017-01-20 19:32:50 +0000156 << h_this->PrettyClass()
157 << " old_status: " << old_status << " new_status: " << new_status;
158 CHECK_EQ(new_status == kStatusErrorResolved, old_status >= kStatusResolved);
Andreas Gampe31decb12015-08-24 21:09:05 -0700159 if (VLOG_IS_ON(class_linker)) {
David Sehr709b0702016-10-13 09:12:37 -0700160 LOG(ERROR) << "Setting " << h_this->PrettyDescriptor() << " to erroneous.";
Andreas Gampe31decb12015-08-24 21:09:05 -0700161 if (self->IsExceptionPending()) {
162 LOG(ERROR) << "Exception: " << self->GetException()->Dump();
163 }
164 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800165
Alex Light0273ad12016-11-02 11:19:31 -0700166 ObjPtr<ClassExt> ext(h_this->EnsureExtDataPresent(self));
167 if (!ext.IsNull()) {
168 self->AssertPendingException();
169 ext->SetVerifyError(self->GetException());
170 } else {
171 self->AssertPendingOOMException();
Alex Lightd6251582016-10-31 11:12:30 -0700172 }
173 self->AssertPendingException();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800174 }
Alex Light0273ad12016-11-02 11:19:31 -0700175
Igor Murashkin86083f72017-10-27 10:59:04 -0700176 {
177 ObjPtr<mirror::Class> h_this_ptr = h_this.Get();
178 SubtypeCheck<ObjPtr<mirror::Class>>::WriteStatus(h_this_ptr, new_status);
Mathieu Chartier93bbee02016-08-31 09:38:40 -0700179 }
180
181 // Setting the object size alloc fast path needs to be after the status write so that if the
182 // alloc path sees a valid object size, we would know that it's initialized as long as it has a
183 // load-acquire/fake dependency.
184 if (new_status == kStatusInitialized && !h_this->IsVariableSize()) {
Mathieu Chartier161db1d2016-09-01 14:06:54 -0700185 DCHECK_EQ(h_this->GetObjectSizeAllocFastPath(), std::numeric_limits<uint32_t>::max());
186 // Finalizable objects must always go slow path.
187 if (!h_this->IsFinalizable()) {
188 h_this->SetObjectSizeAllocFastPath(RoundUp(h_this->GetObjectSize(), kObjectAlignment));
Mathieu Chartier93bbee02016-08-31 09:38:40 -0700189 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100190 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700191
192 if (!class_linker_initialized) {
193 // When the class linker is being initialized its single threaded and by definition there can be
194 // no waiters. During initialization classes may appear temporary but won't be retired as their
195 // size was statically computed.
196 } else {
197 // Classes that are being resolved or initialized need to notify waiters that the class status
198 // changed. See ClassLinker::EnsureResolved and ClassLinker::WaitForInitializeClass.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700199 if (h_this->IsTemp()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700200 // Class is a temporary one, ensure that waiters for resolution get notified of retirement
201 // so that they can grab the new version of the class from the class linker's table.
David Sehr709b0702016-10-13 09:12:37 -0700202 CHECK_LT(new_status, kStatusResolved) << h_this->PrettyDescriptor();
Vladimir Marko72ab6842017-01-20 19:32:50 +0000203 if (new_status == kStatusRetired || new_status == kStatusErrorUnresolved) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700204 h_this->NotifyAll(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700205 }
206 } else {
207 CHECK_NE(new_status, kStatusRetired);
208 if (old_status >= kStatusResolved || new_status >= kStatusResolved) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700209 h_this->NotifyAll(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700210 }
211 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700212 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800213}
214
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700215void Class::SetDexCache(ObjPtr<DexCache> new_dex_cache) {
Chang Xing6d3e7682017-07-11 10:31:29 -0700216 SetFieldObjectTransaction(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), new_dex_cache);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800217}
218
Ian Rogersef7d42f2014-01-06 12:55:46 -0800219void Class::SetClassSize(uint32_t new_class_size) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700220 if (kIsDebugBuild && new_class_size < GetClassSize()) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700221 DumpClass(LOG_STREAM(FATAL_WITHOUT_ABORT), kDumpClassFullDetail);
222 LOG(FATAL_WITHOUT_ABORT) << new_class_size << " vs " << GetClassSize();
David Sehr709b0702016-10-13 09:12:37 -0700223 LOG(FATAL) << "class=" << PrettyTypeOf();
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700224 }
Chang Xing6d3e7682017-07-11 10:31:29 -0700225 SetField32Transaction(OFFSET_OF_OBJECT_MEMBER(Class, class_size_), new_class_size);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800226}
227
228// Return the class' name. The exact format is bizarre, but it's the specified behavior for
229// Class.getName: keywords for primitive types, regular "[I" form for primitive arrays (so "int"
230// but "[I"), and arrays of reference types written between "L" and ";" but with dots rather than
231// slashes (so "java.lang.String" but "[Ljava.lang.String;"). Madness.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700232String* Class::ComputeName(Handle<Class> h_this) {
233 String* name = h_this->GetName();
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800234 if (name != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800235 return name;
236 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700237 std::string temp;
238 const char* descriptor = h_this->GetDescriptor(&temp);
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800239 Thread* self = Thread::Current();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800240 if ((descriptor[0] != 'L') && (descriptor[0] != '[')) {
241 // The descriptor indicates that this is the class for
242 // a primitive type; special-case the return value.
Brian Carlstrom004644f2014-06-18 08:34:01 -0700243 const char* c_name = nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800244 switch (descriptor[0]) {
245 case 'Z': c_name = "boolean"; break;
246 case 'B': c_name = "byte"; break;
247 case 'C': c_name = "char"; break;
248 case 'S': c_name = "short"; break;
249 case 'I': c_name = "int"; break;
250 case 'J': c_name = "long"; break;
251 case 'F': c_name = "float"; break;
252 case 'D': c_name = "double"; break;
253 case 'V': c_name = "void"; break;
254 default:
255 LOG(FATAL) << "Unknown primitive type: " << PrintableChar(descriptor[0]);
256 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800257 name = String::AllocFromModifiedUtf8(self, c_name);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800258 } else {
259 // Convert the UTF-8 name to a java.lang.String. The name must use '.' to separate package
260 // components.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700261 name = String::AllocFromModifiedUtf8(self, DescriptorToDot(descriptor).c_str());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800262 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700263 h_this->SetName(name);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800264 return name;
265}
266
Ian Rogersef7d42f2014-01-06 12:55:46 -0800267void Class::DumpClass(std::ostream& os, int flags) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800268 if ((flags & kDumpClassFullDetail) == 0) {
David Sehr709b0702016-10-13 09:12:37 -0700269 os << PrettyClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800270 if ((flags & kDumpClassClassLoader) != 0) {
271 os << ' ' << GetClassLoader();
272 }
273 if ((flags & kDumpClassInitialized) != 0) {
274 os << ' ' << GetStatus();
275 }
276 os << "\n";
277 return;
278 }
279
Mathieu Chartiere401d142015-04-22 13:56:20 -0700280 Thread* const self = Thread::Current();
Mathieu Chartierf8322842014-05-16 10:59:25 -0700281 StackHandleScope<2> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700282 Handle<Class> h_this(hs.NewHandle(this));
283 Handle<Class> h_super(hs.NewHandle(GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700284 auto image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Mathieu Chartierf8322842014-05-16 10:59:25 -0700285
Ian Rogers1ff3c982014-08-12 02:30:58 -0700286 std::string temp;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800287 os << "----- " << (IsInterface() ? "interface" : "class") << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -0700288 << "'" << GetDescriptor(&temp) << "' cl=" << GetClassLoader() << " -----\n",
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800289 os << " objectSize=" << SizeOf() << " "
Andreas Gampefa4333d2017-02-14 11:10:34 -0800290 << "(" << (h_super != nullptr ? h_super->SizeOf() : -1) << " from super)\n",
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800291 os << StringPrintf(" access=0x%04x.%04x\n",
292 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
Andreas Gampefa4333d2017-02-14 11:10:34 -0800293 if (h_super != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700294 os << " super='" << h_super->PrettyClass() << "' (cl=" << h_super->GetClassLoader()
Mathieu Chartierf8322842014-05-16 10:59:25 -0700295 << ")\n";
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800296 }
297 if (IsArrayClass()) {
298 os << " componentType=" << PrettyClass(GetComponentType()) << "\n";
299 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700300 const size_t num_direct_interfaces = NumDirectInterfaces();
301 if (num_direct_interfaces > 0) {
302 os << " interfaces (" << num_direct_interfaces << "):\n";
303 for (size_t i = 0; i < num_direct_interfaces; ++i) {
Vladimir Marko19a4d372016-12-08 14:41:46 +0000304 ObjPtr<Class> interface = GetDirectInterface(self, h_this.Get(), i);
Andreas Gampe16f149c2015-03-23 10:10:20 -0700305 if (interface == nullptr) {
306 os << StringPrintf(" %2zd: nullptr!\n", i);
307 } else {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700308 ObjPtr<ClassLoader> cl = interface->GetClassLoader();
309 os << StringPrintf(" %2zd: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl.Ptr());
Andreas Gampe16f149c2015-03-23 10:10:20 -0700310 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800311 }
312 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700313 if (!IsLoaded()) {
314 os << " class not yet loaded";
315 } else {
316 // After this point, this may have moved due to GetDirectInterface.
317 os << " vtable (" << h_this->NumVirtualMethods() << " entries, "
Andreas Gampefa4333d2017-02-14 11:10:34 -0800318 << (h_super != nullptr ? h_super->NumVirtualMethods() : 0) << " in super):\n";
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700319 for (size_t i = 0; i < NumVirtualMethods(); ++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->GetVirtualMethodDuringLinking(i, image_pointer_size)).c_str());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800322 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700323 os << " direct methods (" << h_this->NumDirectMethods() << " entries):\n";
324 for (size_t i = 0; i < h_this->NumDirectMethods(); ++i) {
David Sehr709b0702016-10-13 09:12:37 -0700325 os << StringPrintf(" %2zd: %s\n", i, ArtMethod::PrettyMethod(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700326 h_this->GetDirectMethod(i, image_pointer_size)).c_str());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700327 }
328 if (h_this->NumStaticFields() > 0) {
329 os << " static fields (" << h_this->NumStaticFields() << " entries):\n";
Vladimir Marko72ab6842017-01-20 19:32:50 +0000330 if (h_this->IsResolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700331 for (size_t i = 0; i < h_this->NumStaticFields(); ++i) {
David Sehr709b0702016-10-13 09:12:37 -0700332 os << StringPrintf(" %2zd: %s\n", i,
333 ArtField::PrettyField(h_this->GetStaticField(i)).c_str());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700334 }
335 } else {
336 os << " <not yet available>";
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800337 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700338 }
339 if (h_this->NumInstanceFields() > 0) {
340 os << " instance fields (" << h_this->NumInstanceFields() << " entries):\n";
Vladimir Marko72ab6842017-01-20 19:32:50 +0000341 if (h_this->IsResolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700342 for (size_t i = 0; i < h_this->NumInstanceFields(); ++i) {
David Sehr709b0702016-10-13 09:12:37 -0700343 os << StringPrintf(" %2zd: %s\n", i,
344 ArtField::PrettyField(h_this->GetInstanceField(i)).c_str());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700345 }
346 } else {
347 os << " <not yet available>";
348 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800349 }
350 }
351}
352
353void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700354 if (kIsDebugBuild && new_reference_offsets != kClassWalkSuper) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800355 // Sanity check that the number of bits set in the reference offset bitmap
356 // agrees with the number of references
Ian Rogerscdc1aaf2014-10-09 13:21:38 -0700357 uint32_t count = 0;
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700358 for (ObjPtr<Class> c = this; c != nullptr; c = c->GetSuperClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800359 count += c->NumReferenceInstanceFieldsDuringLinking();
360 }
Ian Rogerscdc1aaf2014-10-09 13:21:38 -0700361 // +1 for the Class in Object.
362 CHECK_EQ(static_cast<uint32_t>(POPCOUNT(new_reference_offsets)) + 1, count);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800363 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100364 // Not called within a transaction.
365 SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700366 new_reference_offsets);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800367}
368
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800369bool Class::IsInSamePackage(const StringPiece& descriptor1, const StringPiece& descriptor2) {
370 size_t i = 0;
Ian Rogers6b604a12014-09-25 15:35:37 -0700371 size_t min_length = std::min(descriptor1.size(), descriptor2.size());
372 while (i < min_length && descriptor1[i] == descriptor2[i]) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800373 ++i;
374 }
375 if (descriptor1.find('/', i) != StringPiece::npos ||
376 descriptor2.find('/', i) != StringPiece::npos) {
377 return false;
378 } else {
379 return true;
380 }
381}
382
Mathieu Chartier3398c782016-09-30 10:27:43 -0700383bool Class::IsInSamePackage(ObjPtr<Class> that) {
384 ObjPtr<Class> klass1 = this;
385 ObjPtr<Class> klass2 = that;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800386 if (klass1 == klass2) {
387 return true;
388 }
389 // Class loaders must match.
390 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
391 return false;
392 }
393 // Arrays are in the same package when their element classes are.
394 while (klass1->IsArrayClass()) {
395 klass1 = klass1->GetComponentType();
396 }
397 while (klass2->IsArrayClass()) {
398 klass2 = klass2->GetComponentType();
399 }
Anwar Ghuloum9fa3f202013-03-26 14:32:54 -0700400 // trivial check again for array types
401 if (klass1 == klass2) {
402 return true;
403 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800404 // Compare the package part of the descriptor string.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700405 std::string temp1, temp2;
406 return IsInSamePackage(klass1->GetDescriptor(&temp1), klass2->GetDescriptor(&temp2));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800407}
408
Ian Rogersef7d42f2014-01-06 12:55:46 -0800409bool Class::IsThrowableClass() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800410 return WellKnownClasses::ToClass(WellKnownClasses::java_lang_Throwable)->IsAssignableFrom(this);
411}
412
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700413void Class::SetClassLoader(ObjPtr<ClassLoader> new_class_loader) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100414 if (Runtime::Current()->IsActiveTransaction()) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700415 SetFieldObject<true>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100416 } else {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700417 SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100418 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800419}
420
Vladimir Markoba118822017-06-12 15:41:56 +0100421template <typename SignatureType>
422static inline ArtMethod* FindInterfaceMethodWithSignature(ObjPtr<Class> klass,
423 const StringPiece& name,
424 const SignatureType& signature,
425 PointerSize pointer_size)
426 REQUIRES_SHARED(Locks::mutator_lock_) {
427 // If the current class is not an interface, skip the search of its declared methods;
428 // such lookup is used only to distinguish between IncompatibleClassChangeError and
429 // NoSuchMethodError and the caller has already tried to search methods in the class.
430 if (LIKELY(klass->IsInterface())) {
431 // Search declared methods, both direct and virtual.
432 // (This lookup is used also for invoke-static on interface classes.)
433 for (ArtMethod& method : klass->GetDeclaredMethodsSlice(pointer_size)) {
434 if (method.GetName() == name && method.GetSignature() == signature) {
435 return &method;
436 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800437 }
438 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700439
Vladimir Markoba118822017-06-12 15:41:56 +0100440 // TODO: If there is a unique maximally-specific non-abstract superinterface method,
441 // we should return it, otherwise an arbitrary one can be returned.
442 ObjPtr<IfTable> iftable = klass->GetIfTable();
443 for (int32_t i = 0, iftable_count = iftable->Count(); i < iftable_count; ++i) {
444 ObjPtr<Class> iface = iftable->GetInterface(i);
445 for (ArtMethod& method : iface->GetVirtualMethodsSlice(pointer_size)) {
446 if (method.GetName() == name && method.GetSignature() == signature) {
447 return &method;
448 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700449 }
450 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800451
Vladimir Markoba118822017-06-12 15:41:56 +0100452 // Then search for public non-static methods in the java.lang.Object.
453 if (LIKELY(klass->IsInterface())) {
454 ObjPtr<Class> object_class = klass->GetSuperClass();
455 DCHECK(object_class->IsObjectClass());
456 for (ArtMethod& method : object_class->GetDeclaredMethodsSlice(pointer_size)) {
457 if (method.IsPublic() && !method.IsStatic() &&
458 method.GetName() == name && method.GetSignature() == signature) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700459 return &method;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800460 }
461 }
462 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700463 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800464}
465
Vladimir Markoba118822017-06-12 15:41:56 +0100466ArtMethod* Class::FindInterfaceMethod(const StringPiece& name,
467 const StringPiece& signature,
468 PointerSize pointer_size) {
469 return FindInterfaceMethodWithSignature(this, name, signature, pointer_size);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800470}
471
Vladimir Markoba118822017-06-12 15:41:56 +0100472ArtMethod* Class::FindInterfaceMethod(const StringPiece& name,
473 const Signature& signature,
474 PointerSize pointer_size) {
475 return FindInterfaceMethodWithSignature(this, name, signature, pointer_size);
Ian Rogersd91d6d62013-09-25 20:26:14 -0700476}
477
Vladimir Markoba118822017-06-12 15:41:56 +0100478ArtMethod* Class::FindInterfaceMethod(ObjPtr<DexCache> dex_cache,
479 uint32_t dex_method_idx,
480 PointerSize pointer_size) {
481 // We always search by name and signature, ignoring the type index in the MethodId.
482 const DexFile& dex_file = *dex_cache->GetDexFile();
483 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
484 StringPiece name = dex_file.StringDataByIdx(method_id.name_idx_);
485 const Signature signature = dex_file.GetMethodSignature(method_id);
486 return FindInterfaceMethod(name, signature, pointer_size);
487}
488
Alex Lightafb66472017-08-01 09:54:49 -0700489static inline bool IsValidInheritanceCheck(ObjPtr<mirror::Class> klass,
490 ObjPtr<mirror::Class> declaring_class)
491 REQUIRES_SHARED(Locks::mutator_lock_) {
492 if (klass->IsArrayClass()) {
493 return declaring_class->IsObjectClass();
494 } else if (klass->IsInterface()) {
495 return declaring_class->IsObjectClass() || declaring_class == klass;
496 } else {
497 return klass->IsSubClass(declaring_class);
498 }
499}
500
Vladimir Markoba118822017-06-12 15:41:56 +0100501static inline bool IsInheritedMethod(ObjPtr<mirror::Class> klass,
502 ObjPtr<mirror::Class> declaring_class,
503 ArtMethod& method)
504 REQUIRES_SHARED(Locks::mutator_lock_) {
505 DCHECK_EQ(declaring_class, method.GetDeclaringClass());
506 DCHECK_NE(klass, declaring_class);
Alex Lightafb66472017-08-01 09:54:49 -0700507 DCHECK(IsValidInheritanceCheck(klass, declaring_class));
Vladimir Markoba118822017-06-12 15:41:56 +0100508 uint32_t access_flags = method.GetAccessFlags();
509 if ((access_flags & (kAccPublic | kAccProtected)) != 0) {
510 return true;
511 }
512 if ((access_flags & kAccPrivate) != 0) {
513 return false;
514 }
515 for (; klass != declaring_class; klass = klass->GetSuperClass()) {
516 if (!klass->IsInSamePackage(declaring_class)) {
517 return false;
518 }
519 }
520 return true;
521}
522
523template <typename SignatureType>
524static inline ArtMethod* FindClassMethodWithSignature(ObjPtr<Class> this_klass,
525 const StringPiece& name,
526 const SignatureType& signature,
527 PointerSize pointer_size)
528 REQUIRES_SHARED(Locks::mutator_lock_) {
529 // Search declared methods first.
530 for (ArtMethod& method : this_klass->GetDeclaredMethodsSlice(pointer_size)) {
531 ArtMethod* np_method = method.GetInterfaceMethodIfProxy(pointer_size);
532 if (np_method->GetName() == name && np_method->GetSignature() == signature) {
533 return &method;
534 }
535 }
536
537 // Then search the superclass chain. If we find an inherited method, return it.
538 // If we find a method that's not inherited because of access restrictions,
539 // try to find a method inherited from an interface in copied methods.
540 ObjPtr<Class> klass = this_klass->GetSuperClass();
541 ArtMethod* uninherited_method = nullptr;
542 for (; klass != nullptr; klass = klass->GetSuperClass()) {
543 DCHECK(!klass->IsProxyClass());
544 for (ArtMethod& method : klass->GetDeclaredMethodsSlice(pointer_size)) {
545 if (method.GetName() == name && method.GetSignature() == signature) {
546 if (IsInheritedMethod(this_klass, klass, method)) {
547 return &method;
548 }
549 uninherited_method = &method;
550 break;
551 }
552 }
553 if (uninherited_method != nullptr) {
554 break;
555 }
556 }
557
558 // Then search copied methods.
559 // If we found a method that's not inherited, stop the search in its declaring class.
560 ObjPtr<Class> end_klass = klass;
561 DCHECK_EQ(uninherited_method != nullptr, end_klass != nullptr);
562 klass = this_klass;
563 if (UNLIKELY(klass->IsProxyClass())) {
564 DCHECK(klass->GetCopiedMethodsSlice(pointer_size).empty());
565 klass = klass->GetSuperClass();
566 }
567 for (; klass != end_klass; klass = klass->GetSuperClass()) {
568 DCHECK(!klass->IsProxyClass());
569 for (ArtMethod& method : klass->GetCopiedMethodsSlice(pointer_size)) {
570 if (method.GetName() == name && method.GetSignature() == signature) {
571 return &method; // No further check needed, copied methods are inherited by definition.
572 }
573 }
574 }
575 return uninherited_method; // Return the `uninherited_method` if any.
576}
577
578
579ArtMethod* Class::FindClassMethod(const StringPiece& name,
580 const StringPiece& signature,
581 PointerSize pointer_size) {
582 return FindClassMethodWithSignature(this, name, signature, pointer_size);
583}
584
585ArtMethod* Class::FindClassMethod(const StringPiece& name,
586 const Signature& signature,
587 PointerSize pointer_size) {
588 return FindClassMethodWithSignature(this, name, signature, pointer_size);
589}
590
591ArtMethod* Class::FindClassMethod(ObjPtr<DexCache> dex_cache,
592 uint32_t dex_method_idx,
593 PointerSize pointer_size) {
594 // FIXME: Hijacking a proxy class by a custom class loader can break this assumption.
595 DCHECK(!IsProxyClass());
596
597 // First try to find a declared method by dex_method_idx if we have a dex_cache match.
598 ObjPtr<DexCache> this_dex_cache = GetDexCache();
599 if (this_dex_cache == dex_cache) {
600 // Lookup is always performed in the class referenced by the MethodId.
601 DCHECK_EQ(dex_type_idx_, GetDexFile().GetMethodId(dex_method_idx).class_idx_.index_);
602 for (ArtMethod& method : GetDeclaredMethodsSlice(pointer_size)) {
603 if (method.GetDexMethodIndex() == dex_method_idx) {
604 return &method;
605 }
606 }
607 }
608 // If not found, we need to search by name and signature.
609 const DexFile& dex_file = *dex_cache->GetDexFile();
610 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
611 const Signature signature = dex_file.GetMethodSignature(method_id);
612 StringPiece name; // Delay strlen() until actually needed.
613 // If we do not have a dex_cache match, try to find the declared method in this class now.
614 if (this_dex_cache != dex_cache && !GetDeclaredMethodsSlice(pointer_size).empty()) {
615 DCHECK(name.empty());
616 name = dex_file.StringDataByIdx(method_id.name_idx_);
617 for (ArtMethod& method : GetDeclaredMethodsSlice(pointer_size)) {
618 if (method.GetName() == name && method.GetSignature() == signature) {
619 return &method;
620 }
621 }
622 }
623
624 // Then search the superclass chain. If we find an inherited method, return it.
625 // If we find a method that's not inherited because of access restrictions,
626 // try to find a method inherited from an interface in copied methods.
627 ArtMethod* uninherited_method = nullptr;
628 ObjPtr<Class> klass = GetSuperClass();
629 for (; klass != nullptr; klass = klass->GetSuperClass()) {
630 ArtMethod* candidate_method = nullptr;
631 ArraySlice<ArtMethod> declared_methods = klass->GetDeclaredMethodsSlice(pointer_size);
632 if (klass->GetDexCache() == dex_cache) {
633 // Matching dex_cache. We cannot compare the `dex_method_idx` anymore because
634 // the type index differs, so compare the name index and proto index.
635 for (ArtMethod& method : declared_methods) {
636 const DexFile::MethodId& cmp_method_id = dex_file.GetMethodId(method.GetDexMethodIndex());
637 if (cmp_method_id.name_idx_ == method_id.name_idx_ &&
638 cmp_method_id.proto_idx_ == method_id.proto_idx_) {
639 candidate_method = &method;
640 break;
641 }
642 }
643 } else {
644 if (!declared_methods.empty() && name.empty()) {
645 name = dex_file.StringDataByIdx(method_id.name_idx_);
646 }
647 for (ArtMethod& method : declared_methods) {
648 if (method.GetName() == name && method.GetSignature() == signature) {
649 candidate_method = &method;
650 break;
651 }
652 }
653 }
654 if (candidate_method != nullptr) {
655 if (IsInheritedMethod(this, klass, *candidate_method)) {
656 return candidate_method;
657 } else {
658 uninherited_method = candidate_method;
659 break;
660 }
661 }
662 }
663
664 // Then search copied methods.
665 // If we found a method that's not inherited, stop the search in its declaring class.
666 ObjPtr<Class> end_klass = klass;
667 DCHECK_EQ(uninherited_method != nullptr, end_klass != nullptr);
668 // After we have searched the declared methods of the super-class chain,
669 // search copied methods which can contain methods from interfaces.
670 for (klass = this; klass != end_klass; klass = klass->GetSuperClass()) {
671 ArraySlice<ArtMethod> copied_methods = klass->GetCopiedMethodsSlice(pointer_size);
672 if (!copied_methods.empty() && name.empty()) {
673 name = dex_file.StringDataByIdx(method_id.name_idx_);
674 }
675 for (ArtMethod& method : copied_methods) {
676 if (method.GetName() == name && method.GetSignature() == signature) {
677 return &method; // No further check needed, copied methods are inherited by definition.
678 }
679 }
680 }
681 return uninherited_method; // Return the `uninherited_method` if any.
682}
683
684ArtMethod* Class::FindConstructor(const StringPiece& signature, PointerSize pointer_size) {
685 // Internal helper, never called on proxy classes. We can skip GetInterfaceMethodIfProxy().
686 DCHECK(!IsProxyClass());
687 StringPiece name("<init>");
688 for (ArtMethod& method : GetDirectMethodsSliceUnchecked(pointer_size)) {
689 if (method.GetName() == name && method.GetSignature() == signature) {
690 return &method;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800691 }
692 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700693 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800694}
695
Andreas Gampe542451c2016-07-26 09:02:02 -0700696ArtMethod* Class::FindDeclaredDirectMethodByName(const StringPiece& name,
697 PointerSize pointer_size) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000698 for (auto& method : GetDirectMethods(pointer_size)) {
699 ArtMethod* const np_method = method.GetInterfaceMethodIfProxy(pointer_size);
700 if (name == np_method->GetName()) {
701 return &method;
702 }
703 }
704 return nullptr;
705}
706
Andreas Gampe542451c2016-07-26 09:02:02 -0700707ArtMethod* Class::FindDeclaredVirtualMethodByName(const StringPiece& name,
708 PointerSize pointer_size) {
Jeff Hao13e748b2015-08-25 20:44:19 +0000709 for (auto& method : GetVirtualMethods(pointer_size)) {
710 ArtMethod* const np_method = method.GetInterfaceMethodIfProxy(pointer_size);
711 if (name == np_method->GetName()) {
712 return &method;
713 }
714 }
715 return nullptr;
716}
717
Andreas Gampe542451c2016-07-26 09:02:02 -0700718ArtMethod* Class::FindVirtualMethodForInterfaceSuper(ArtMethod* method, PointerSize pointer_size) {
Alex Light705ad492015-09-21 11:36:30 -0700719 DCHECK(method->GetDeclaringClass()->IsInterface());
720 DCHECK(IsInterface()) << "Should only be called on a interface class";
721 // Check if we have one defined on this interface first. This includes searching copied ones to
722 // get any conflict methods. Conflict methods are copied into each subtype from the supertype. We
723 // don't do any indirect method checks here.
724 for (ArtMethod& iface_method : GetVirtualMethods(pointer_size)) {
725 if (method->HasSameNameAndSignature(&iface_method)) {
726 return &iface_method;
727 }
728 }
729
730 std::vector<ArtMethod*> abstract_methods;
731 // Search through the IFTable for a working version. We don't need to check for conflicts
732 // because if there was one it would appear in this classes virtual_methods_ above.
733
734 Thread* self = Thread::Current();
735 StackHandleScope<2> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700736 MutableHandle<IfTable> iftable(hs.NewHandle(GetIfTable()));
737 MutableHandle<Class> iface(hs.NewHandle<Class>(nullptr));
Alex Light705ad492015-09-21 11:36:30 -0700738 size_t iftable_count = GetIfTableCount();
739 // Find the method. We don't need to check for conflicts because they would have been in the
740 // copied virtuals of this interface. Order matters, traverse in reverse topological order; most
741 // subtypiest interfaces get visited first.
742 for (size_t k = iftable_count; k != 0;) {
743 k--;
744 DCHECK_LT(k, iftable->Count());
745 iface.Assign(iftable->GetInterface(k));
746 // Iterate through every declared method on this interface. Each direct method's name/signature
747 // is unique so the order of the inner loop doesn't matter.
748 for (auto& method_iter : iface->GetDeclaredVirtualMethods(pointer_size)) {
749 ArtMethod* current_method = &method_iter;
750 if (current_method->HasSameNameAndSignature(method)) {
751 if (current_method->IsDefault()) {
752 // Handle JLS soft errors, a default method from another superinterface tree can
753 // "override" an abstract method(s) from another superinterface tree(s). To do this,
754 // ignore any [default] method which are dominated by the abstract methods we've seen so
755 // far. Check if overridden by any in abstract_methods. We do not need to check for
756 // default_conflicts because we would hit those before we get to this loop.
757 bool overridden = false;
758 for (ArtMethod* possible_override : abstract_methods) {
759 DCHECK(possible_override->HasSameNameAndSignature(current_method));
760 if (iface->IsAssignableFrom(possible_override->GetDeclaringClass())) {
761 overridden = true;
762 break;
763 }
764 }
765 if (!overridden) {
766 return current_method;
767 }
768 } else {
769 // Is not default.
770 // This might override another default method. Just stash it for now.
771 abstract_methods.push_back(current_method);
772 }
773 }
774 }
775 }
776 // If we reach here we either never found any declaration of the method (in which case
777 // 'abstract_methods' is empty or we found no non-overriden default methods in which case
778 // 'abstract_methods' contains a number of abstract implementations of the methods. We choose one
779 // of these arbitrarily.
780 return abstract_methods.empty() ? nullptr : abstract_methods[0];
781}
782
Andreas Gampe542451c2016-07-26 09:02:02 -0700783ArtMethod* Class::FindClassInitializer(PointerSize pointer_size) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700784 for (ArtMethod& method : GetDirectMethods(pointer_size)) {
785 if (method.IsClassInitializer()) {
786 DCHECK_STREQ(method.GetName(), "<clinit>");
787 DCHECK_STREQ(method.GetSignature().ToString().c_str(), "()V");
788 return &method;
Ian Rogersd91d6d62013-09-25 20:26:14 -0700789 }
790 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700791 return nullptr;
Ian Rogersd91d6d62013-09-25 20:26:14 -0700792}
793
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700794// Custom binary search to avoid double comparisons from std::binary_search.
795static ArtField* FindFieldByNameAndType(LengthPrefixedArray<ArtField>* fields,
796 const StringPiece& name,
797 const StringPiece& type)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700798 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700799 if (fields == nullptr) {
800 return nullptr;
801 }
802 size_t low = 0;
Vladimir Marko35831e82015-09-11 11:59:18 +0100803 size_t high = fields->size();
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700804 ArtField* ret = nullptr;
805 while (low < high) {
806 size_t mid = (low + high) / 2;
807 ArtField& field = fields->At(mid);
808 // Fields are sorted by class, then name, then type descriptor. This is verified in dex file
809 // verifier. There can be multiple fields with the same in the same class name due to proguard.
810 int result = StringPiece(field.GetName()).Compare(name);
811 if (result == 0) {
812 result = StringPiece(field.GetTypeDescriptor()).Compare(type);
813 }
814 if (result < 0) {
815 low = mid + 1;
816 } else if (result > 0) {
817 high = mid;
818 } else {
819 ret = &field;
820 break;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800821 }
822 }
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700823 if (kIsDebugBuild) {
824 ArtField* found = nullptr;
825 for (ArtField& field : MakeIterationRangeFromLengthPrefixedArray(fields)) {
826 if (name == field.GetName() && type == field.GetTypeDescriptor()) {
827 found = &field;
828 break;
829 }
830 }
David Sehr709b0702016-10-13 09:12:37 -0700831 CHECK_EQ(found, ret) << "Found " << found->PrettyField() << " vs " << ret->PrettyField();
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700832 }
833 return ret;
834}
835
836ArtField* Class::FindDeclaredInstanceField(const StringPiece& name, const StringPiece& type) {
837 // Binary search by name. Interfaces are not relevant because they can't contain instance fields.
838 return FindFieldByNameAndType(GetIFieldsPtr(), name, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800839}
840
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700841ArtField* Class::FindDeclaredInstanceField(ObjPtr<DexCache> dex_cache, uint32_t dex_field_idx) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800842 if (GetDexCache() == dex_cache) {
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700843 for (ArtField& field : GetIFields()) {
844 if (field.GetDexFieldIndex() == dex_field_idx) {
845 return &field;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800846 }
847 }
848 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700849 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800850}
851
Brian Carlstromea46f952013-07-30 01:26:50 -0700852ArtField* Class::FindInstanceField(const StringPiece& name, const StringPiece& type) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800853 // Is the field in this class, or any of its superclasses?
854 // Interfaces are not relevant because they can't contain instance fields.
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700855 for (ObjPtr<Class> c = this; c != nullptr; c = c->GetSuperClass()) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700856 ArtField* f = c->FindDeclaredInstanceField(name, type);
Brian Carlstrom004644f2014-06-18 08:34:01 -0700857 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800858 return f;
859 }
860 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700861 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800862}
863
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700864ArtField* Class::FindInstanceField(ObjPtr<DexCache> dex_cache, uint32_t dex_field_idx) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800865 // Is the field in this class, or any of its superclasses?
866 // Interfaces are not relevant because they can't contain instance fields.
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700867 for (ObjPtr<Class> c = this; c != nullptr; c = c->GetSuperClass()) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700868 ArtField* f = c->FindDeclaredInstanceField(dex_cache, dex_field_idx);
Brian Carlstrom004644f2014-06-18 08:34:01 -0700869 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800870 return f;
871 }
872 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700873 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800874}
875
Brian Carlstromea46f952013-07-30 01:26:50 -0700876ArtField* Class::FindDeclaredStaticField(const StringPiece& name, const StringPiece& type) {
Brian Carlstrom004644f2014-06-18 08:34:01 -0700877 DCHECK(type != nullptr);
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700878 return FindFieldByNameAndType(GetSFieldsPtr(), name, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800879}
880
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700881ArtField* Class::FindDeclaredStaticField(ObjPtr<DexCache> dex_cache, uint32_t dex_field_idx) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800882 if (dex_cache == GetDexCache()) {
Mathieu Chartiere2aa3262015-10-20 18:30:03 -0700883 for (ArtField& field : GetSFields()) {
884 if (field.GetDexFieldIndex() == dex_field_idx) {
885 return &field;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800886 }
887 }
888 }
Brian Carlstrom004644f2014-06-18 08:34:01 -0700889 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800890}
891
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700892ArtField* Class::FindStaticField(Thread* self,
Vladimir Marko19a4d372016-12-08 14:41:46 +0000893 ObjPtr<Class> klass,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700894 const StringPiece& name,
Mathieu Chartierf8322842014-05-16 10:59:25 -0700895 const StringPiece& type) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800896 // Is the field in this class (or its interfaces), or any of its
897 // superclasses (or their interfaces)?
Vladimir Marko19a4d372016-12-08 14:41:46 +0000898 for (ObjPtr<Class> k = klass; k != nullptr; k = k->GetSuperClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800899 // Is the field in this class?
Brian Carlstromea46f952013-07-30 01:26:50 -0700900 ArtField* f = k->FindDeclaredStaticField(name, type);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700901 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800902 return f;
903 }
904 // Is this field in any of this class' interfaces?
Vladimir Marko19a4d372016-12-08 14:41:46 +0000905 for (uint32_t i = 0, num_interfaces = k->NumDirectInterfaces(); i != num_interfaces; ++i) {
906 ObjPtr<Class> interface = GetDirectInterface(self, k, i);
907 DCHECK(interface != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700908 f = FindStaticField(self, interface, name, type);
909 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800910 return f;
911 }
912 }
913 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700914 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800915}
916
Vladimir Markobb268b12016-06-30 15:52:56 +0100917ArtField* Class::FindStaticField(Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700918 ObjPtr<Class> klass,
919 ObjPtr<DexCache> dex_cache,
Mathieu Chartierf8322842014-05-16 10:59:25 -0700920 uint32_t dex_field_idx) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700921 for (ObjPtr<Class> k = klass; k != nullptr; k = k->GetSuperClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800922 // Is the field in this class?
Brian Carlstromea46f952013-07-30 01:26:50 -0700923 ArtField* f = k->FindDeclaredStaticField(dex_cache, dex_field_idx);
Brian Carlstrom004644f2014-06-18 08:34:01 -0700924 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800925 return f;
926 }
Vladimir Markobb268b12016-06-30 15:52:56 +0100927 // Though GetDirectInterface() should not cause thread suspension when called
928 // from here, it takes a Handle as an argument, so we need to wrap `k`.
Mathieu Chartier268764d2016-09-13 12:09:38 -0700929 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800930 // Is this field in any of this class' interfaces?
Vladimir Marko19a4d372016-12-08 14:41:46 +0000931 for (uint32_t i = 0, num_interfaces = k->NumDirectInterfaces(); i != num_interfaces; ++i) {
932 ObjPtr<Class> interface = GetDirectInterface(self, k, i);
933 DCHECK(interface != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700934 f = FindStaticField(self, interface, dex_cache, dex_field_idx);
935 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800936 return f;
937 }
938 }
939 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700940 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800941}
942
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700943ArtField* Class::FindField(Thread* self,
Vladimir Marko19a4d372016-12-08 14:41:46 +0000944 ObjPtr<Class> klass,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -0700945 const StringPiece& name,
Mathieu Chartierf8322842014-05-16 10:59:25 -0700946 const StringPiece& type) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800947 // Find a field using the JLS field resolution order
Vladimir Marko19a4d372016-12-08 14:41:46 +0000948 for (ObjPtr<Class> k = klass; k != nullptr; k = k->GetSuperClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800949 // Is the field in this class?
Brian Carlstromea46f952013-07-30 01:26:50 -0700950 ArtField* f = k->FindDeclaredInstanceField(name, type);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700951 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800952 return f;
953 }
954 f = k->FindDeclaredStaticField(name, type);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700955 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800956 return f;
957 }
958 // Is this field in any of this class' interfaces?
Vladimir Marko19a4d372016-12-08 14:41:46 +0000959 for (uint32_t i = 0, num_interfaces = k->NumDirectInterfaces(); i != num_interfaces; ++i) {
960 ObjPtr<Class> interface = GetDirectInterface(self, k, i);
961 DCHECK(interface != nullptr);
962 f = FindStaticField(self, interface, name, type);
Mathieu Chartierf8322842014-05-16 10:59:25 -0700963 if (f != nullptr) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800964 return f;
965 }
966 }
967 }
Mathieu Chartierf8322842014-05-16 10:59:25 -0700968 return nullptr;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800969}
970
Andreas Gampe542451c2016-07-26 09:02:02 -0700971void Class::SetSkipAccessChecksFlagOnAllMethods(PointerSize pointer_size) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700972 DCHECK(IsVerified());
Alex Lighte64300b2015-12-15 15:02:47 -0800973 for (auto& m : GetMethods(pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -0700974 if (!m.IsNative() && m.IsInvokable()) {
Igor Murashkindf707e42016-02-02 16:56:50 -0800975 m.SetSkipAccessChecks();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700976 }
977 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +0200978}
979
Ian Rogers1ff3c982014-08-12 02:30:58 -0700980const char* Class::GetDescriptor(std::string* storage) {
981 if (IsPrimitive()) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700982 return Primitive::Descriptor(GetPrimitiveType());
Ian Rogers1ff3c982014-08-12 02:30:58 -0700983 } else if (IsArrayClass()) {
984 return GetArrayDescriptor(storage);
Nicolas Geoffray3a090922015-11-24 09:17:30 +0000985 } else if (IsProxyClass()) {
986 *storage = Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(this);
Ian Rogers1ff3c982014-08-12 02:30:58 -0700987 return storage->c_str();
Mathieu Chartierf8322842014-05-16 10:59:25 -0700988 } else {
989 const DexFile& dex_file = GetDexFile();
990 const DexFile::TypeId& type_id = dex_file.GetTypeId(GetClassDef()->class_idx_);
991 return dex_file.GetTypeDescriptor(type_id);
992 }
993}
994
Ian Rogers1ff3c982014-08-12 02:30:58 -0700995const char* Class::GetArrayDescriptor(std::string* storage) {
996 std::string temp;
997 const char* elem_desc = GetComponentType()->GetDescriptor(&temp);
998 *storage = "[";
999 *storage += elem_desc;
1000 return storage->c_str();
Mathieu Chartierf8322842014-05-16 10:59:25 -07001001}
1002
1003const DexFile::ClassDef* Class::GetClassDef() {
1004 uint16_t class_def_idx = GetDexClassDefIndex();
1005 if (class_def_idx == DexFile::kDexNoIndex16) {
1006 return nullptr;
1007 }
1008 return &GetDexFile().GetClassDef(class_def_idx);
1009}
1010
Andreas Gampea5b09a62016-11-17 15:21:22 -08001011dex::TypeIndex Class::GetDirectInterfaceTypeIdx(uint32_t idx) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001012 DCHECK(!IsPrimitive());
1013 DCHECK(!IsArrayClass());
1014 return GetInterfaceTypeList()->GetTypeItem(idx).type_idx_;
1015}
1016
Vladimir Marko19a4d372016-12-08 14:41:46 +00001017ObjPtr<Class> Class::GetDirectInterface(Thread* self, ObjPtr<Class> klass, uint32_t idx) {
1018 DCHECK(klass != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07001019 DCHECK(!klass->IsPrimitive());
1020 if (klass->IsArrayClass()) {
1021 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Vladimir Marko19a4d372016-12-08 14:41:46 +00001022 // Use ClassLinker::LookupClass(); avoid poisoning ObjPtr<>s by ClassLinker::FindSystemClass().
1023 ObjPtr<Class> interface;
Mathieu Chartierf8322842014-05-16 10:59:25 -07001024 if (idx == 0) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001025 interface = class_linker->LookupClass(self, "Ljava/lang/Cloneable;", nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07001026 } else {
1027 DCHECK_EQ(1U, idx);
Vladimir Marko19a4d372016-12-08 14:41:46 +00001028 interface = class_linker->LookupClass(self, "Ljava/io/Serializable;", nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07001029 }
Vladimir Marko19a4d372016-12-08 14:41:46 +00001030 DCHECK(interface != nullptr);
1031 return interface;
Nicolas Geoffray3a090922015-11-24 09:17:30 +00001032 } else if (klass->IsProxyClass()) {
Narayan Kamath6b2dc312017-03-14 13:26:12 +00001033 ObjPtr<ObjectArray<Class>> interfaces = klass->GetProxyInterfaces();
Mathieu Chartierf8322842014-05-16 10:59:25 -07001034 DCHECK(interfaces != nullptr);
1035 return interfaces->Get(idx);
1036 } else {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001037 dex::TypeIndex type_idx = klass->GetDirectInterfaceTypeIdx(idx);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001038 ObjPtr<Class> interface = ClassLinker::LookupResolvedType(
1039 type_idx, klass->GetDexCache(), klass->GetClassLoader());
Mathieu Chartierf8322842014-05-16 10:59:25 -07001040 return interface;
1041 }
1042}
1043
Vladimir Marko19a4d372016-12-08 14:41:46 +00001044ObjPtr<Class> Class::ResolveDirectInterface(Thread* self, Handle<Class> klass, uint32_t idx) {
1045 ObjPtr<Class> interface = GetDirectInterface(self, klass.Get(), idx);
1046 if (interface == nullptr) {
1047 DCHECK(!klass->IsArrayClass());
1048 DCHECK(!klass->IsProxyClass());
1049 dex::TypeIndex type_idx = klass->GetDirectInterfaceTypeIdx(idx);
1050 interface = Runtime::Current()->GetClassLinker()->ResolveType(klass->GetDexFile(),
1051 type_idx,
1052 klass.Get());
1053 CHECK(interface != nullptr || self->IsExceptionPending());
1054 }
1055 return interface;
1056}
1057
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001058ObjPtr<Class> Class::GetCommonSuperClass(Handle<Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08001059 DCHECK(klass != nullptr);
Calin Juravle52503d82015-11-11 16:58:31 +00001060 DCHECK(!klass->IsInterface());
1061 DCHECK(!IsInterface());
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001062 ObjPtr<Class> common_super_class = this;
Calin Juravle52503d82015-11-11 16:58:31 +00001063 while (!common_super_class->IsAssignableFrom(klass.Get())) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001064 ObjPtr<Class> old_common = common_super_class;
Aart Bik22deed02016-04-04 14:19:01 -07001065 common_super_class = old_common->GetSuperClass();
David Sehr709b0702016-10-13 09:12:37 -07001066 DCHECK(common_super_class != nullptr) << old_common->PrettyClass();
Calin Juravle52503d82015-11-11 16:58:31 +00001067 }
Calin Juravle52503d82015-11-11 16:58:31 +00001068 return common_super_class;
1069}
1070
Mathieu Chartierf8322842014-05-16 10:59:25 -07001071const char* Class::GetSourceFile() {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001072 const DexFile& dex_file = GetDexFile();
1073 const DexFile::ClassDef* dex_class_def = GetClassDef();
Sebastien Hertz4206eb52014-06-05 10:15:45 +02001074 if (dex_class_def == nullptr) {
1075 // Generated classes have no class def.
1076 return nullptr;
1077 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001078 return dex_file.GetSourceFile(*dex_class_def);
1079}
1080
1081std::string Class::GetLocation() {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001082 ObjPtr<DexCache> dex_cache = GetDexCache();
Nicolas Geoffray3a090922015-11-24 09:17:30 +00001083 if (dex_cache != nullptr && !IsProxyClass()) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001084 return dex_cache->GetLocation()->ToModifiedUtf8();
1085 }
1086 // Arrays and proxies are generated and have no corresponding dex file location.
1087 return "generated class";
1088}
1089
1090const DexFile::TypeList* Class::GetInterfaceTypeList() {
1091 const DexFile::ClassDef* class_def = GetClassDef();
1092 if (class_def == nullptr) {
1093 return nullptr;
1094 }
1095 return GetDexFile().GetInterfacesList(*class_def);
1096}
1097
Andreas Gampe542451c2016-07-26 09:02:02 -07001098void Class::PopulateEmbeddedVTable(PointerSize pointer_size) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001099 PointerArray* table = GetVTableDuringLinking();
David Sehr709b0702016-10-13 09:12:37 -07001100 CHECK(table != nullptr) << PrettyClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001101 const size_t table_length = table->GetLength();
1102 SetEmbeddedVTableLength(table_length);
1103 for (size_t i = 0; i < table_length; i++) {
1104 SetEmbeddedVTableEntry(i, table->GetElementPtrSize<ArtMethod*>(i, pointer_size), pointer_size);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001105 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07001106 // Keep java.lang.Object class's vtable around for since it's easier
1107 // to be reused by array classes during their linking.
1108 if (!IsObjectClass()) {
1109 SetVTable(nullptr);
1110 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001111}
1112
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001113class ReadBarrierOnNativeRootsVisitor {
1114 public:
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001115 void operator()(ObjPtr<Object> obj ATTRIBUTE_UNUSED,
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001116 MemberOffset offset ATTRIBUTE_UNUSED,
1117 bool is_static ATTRIBUTE_UNUSED) const {}
1118
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001119 void VisitRootIfNonNull(CompressedReference<Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001120 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001121 if (!root->IsNull()) {
1122 VisitRoot(root);
1123 }
1124 }
1125
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001126 void VisitRoot(CompressedReference<Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001127 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001128 ObjPtr<Object> old_ref = root->AsMirrorPtr();
1129 ObjPtr<Object> new_ref = ReadBarrier::BarrierForRoot(root);
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001130 if (old_ref != new_ref) {
1131 // Update the field atomically. This may fail if mutator updates before us, but it's ok.
1132 auto* atomic_root =
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001133 reinterpret_cast<Atomic<CompressedReference<Object>>*>(root);
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001134 atomic_root->CompareExchangeStrongSequentiallyConsistent(
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001135 CompressedReference<Object>::FromMirrorPtr(old_ref.Ptr()),
1136 CompressedReference<Object>::FromMirrorPtr(new_ref.Ptr()));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001137 }
1138 }
1139};
1140
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001141// The pre-fence visitor for Class::CopyOf().
1142class CopyClassVisitor {
1143 public:
Andreas Gampe542451c2016-07-26 09:02:02 -07001144 CopyClassVisitor(Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001145 Handle<Class>* orig,
Andreas Gampe542451c2016-07-26 09:02:02 -07001146 size_t new_length,
1147 size_t copy_bytes,
1148 ImTable* imt,
1149 PointerSize pointer_size)
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001150 : self_(self), orig_(orig), new_length_(new_length),
Mathieu Chartiere401d142015-04-22 13:56:20 -07001151 copy_bytes_(copy_bytes), imt_(imt), pointer_size_(pointer_size) {
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001152 }
1153
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001154 void operator()(ObjPtr<Object> obj, size_t usable_size ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001155 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001156 StackHandleScope<1> hs(self_);
1157 Handle<mirror::Class> h_new_class_obj(hs.NewHandle(obj->AsClass()));
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001158 Object::CopyObject(h_new_class_obj.Get(), orig_->Get(), copy_bytes_);
1159 Class::SetStatus(h_new_class_obj, Class::kStatusResolving, self_);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001160 h_new_class_obj->PopulateEmbeddedVTable(pointer_size_);
1161 h_new_class_obj->SetImt(imt_, pointer_size_);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001162 h_new_class_obj->SetClassSize(new_length_);
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07001163 // Visit all of the references to make sure there is no from space references in the native
1164 // roots.
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001165 ObjPtr<Object>(h_new_class_obj.Get())->VisitReferences(
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001166 ReadBarrierOnNativeRootsVisitor(), VoidFunctor());
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001167 }
1168
1169 private:
1170 Thread* const self_;
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001171 Handle<Class>* const orig_;
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001172 const size_t new_length_;
1173 const size_t copy_bytes_;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001174 ImTable* imt_;
Andreas Gampe542451c2016-07-26 09:02:02 -07001175 const PointerSize pointer_size_;
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001176 DISALLOW_COPY_AND_ASSIGN(CopyClassVisitor);
1177};
1178
Andreas Gampe542451c2016-07-26 09:02:02 -07001179Class* Class::CopyOf(Thread* self, int32_t new_length, ImTable* imt, PointerSize pointer_size) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001180 DCHECK_GE(new_length, static_cast<int32_t>(sizeof(Class)));
1181 // We may get copied by a compacting GC.
1182 StackHandleScope<1> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001183 Handle<Class> h_this(hs.NewHandle(this));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001184 gc::Heap* heap = Runtime::Current()->GetHeap();
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001185 // The num_bytes (3rd param) is sizeof(Class) as opposed to SizeOf()
1186 // to skip copying the tail part that we will overwrite here.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001187 CopyClassVisitor visitor(self, &h_this, new_length, sizeof(Class), imt, pointer_size);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001188 ObjPtr<Object> new_class = kMovingClasses ?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001189 heap->AllocObject<true>(self, java_lang_Class_.Read(), new_length, visitor) :
1190 heap->AllocNonMovableObject<true>(self, java_lang_Class_.Read(), new_length, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001191 if (UNLIKELY(new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001192 self->AssertPendingOOMException();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001193 return nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001194 }
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07001195 return new_class->AsClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001196}
1197
Nicolas Geoffray3a090922015-11-24 09:17:30 +00001198bool Class::ProxyDescriptorEquals(const char* match) {
1199 DCHECK(IsProxyClass());
1200 return Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(this) == match;
Vladimir Marko3481ba22015-04-13 12:22:36 +01001201}
1202
Mathieu Chartiere401d142015-04-22 13:56:20 -07001203// TODO: Move this to java_lang_Class.cc?
1204ArtMethod* Class::GetDeclaredConstructor(
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001205 Thread* self, Handle<ObjectArray<Class>> args, PointerSize pointer_size) {
Andreas Gampe6039e562016-04-05 18:18:43 -07001206 for (auto& m : GetDirectMethods(pointer_size)) {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001207 // Skip <clinit> which is a static constructor, as well as non constructors.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001208 if (m.IsStatic() || !m.IsConstructor()) {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001209 continue;
1210 }
1211 // May cause thread suspension and exceptions.
Andreas Gampe542451c2016-07-26 09:02:02 -07001212 if (m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->EqualParameters(args)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001213 return &m;
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001214 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001215 if (UNLIKELY(self->IsExceptionPending())) {
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001216 return nullptr;
1217 }
1218 }
1219 return nullptr;
1220}
1221
Mathieu Chartiere401d142015-04-22 13:56:20 -07001222uint32_t Class::Depth() {
1223 uint32_t depth = 0;
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001224 for (ObjPtr<Class> klass = this; klass->GetSuperClass() != nullptr; klass = klass->GetSuperClass()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001225 depth++;
1226 }
1227 return depth;
1228}
1229
Andreas Gampea5b09a62016-11-17 15:21:22 -08001230dex::TypeIndex Class::FindTypeIndexInOtherDexFile(const DexFile& dex_file) {
Nicolas Geoffraye4084a52016-02-18 14:43:42 +00001231 std::string temp;
1232 const DexFile::TypeId* type_id = dex_file.FindTypeId(GetDescriptor(&temp));
Andreas Gampe2722f382017-06-08 18:03:25 -07001233 return (type_id == nullptr) ? dex::TypeIndex() : dex_file.GetIndexForTypeId(*type_id);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +00001234}
1235
Andreas Gampe542451c2016-07-26 09:02:02 -07001236template <PointerSize kPointerSize, bool kTransactionActive>
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001237ObjPtr<Method> Class::GetDeclaredMethodInternal(
1238 Thread* self,
1239 ObjPtr<Class> klass,
1240 ObjPtr<String> name,
1241 ObjPtr<ObjectArray<Class>> args) {
Andreas Gampebc4d2182016-02-22 10:03:12 -08001242 // Covariant return types permit the class to define multiple
1243 // methods with the same name and parameter types. Prefer to
1244 // return a non-synthetic method in such situations. We may
1245 // still return a synthetic method to handle situations like
1246 // escalated visibility. We never return miranda methods that
1247 // were synthesized by the runtime.
Andreas Gampebc4d2182016-02-22 10:03:12 -08001248 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 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01001267 if (!m.IsMiranda()) {
1268 if (!m.IsSynthetic()) {
1269 return Method::CreateFromArtMethod<kPointerSize, kTransactionActive>(self, &m);
1270 }
Andreas Gampebc4d2182016-02-22 10:03:12 -08001271 result = &m; // Remember as potential result if it's not a miranda method.
1272 }
1273 }
1274 if (result == nullptr) {
Andreas Gampee01e3642016-07-25 13:06:04 -07001275 for (auto& m : h_klass->GetDirectMethods(kPointerSize)) {
Andreas Gampebc4d2182016-02-22 10:03:12 -08001276 auto modifiers = m.GetAccessFlags();
1277 if ((modifiers & kAccConstructor) != 0) {
1278 continue;
1279 }
Andreas Gampee01e3642016-07-25 13:06:04 -07001280 auto* np_method = m.GetInterfaceMethodIfProxy(kPointerSize);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001281 // May cause thread suspension.
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001282 ObjPtr<String> np_name = np_method->GetNameAsString(self);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001283 if (np_name == nullptr) {
1284 self->AssertPendingException();
1285 return nullptr;
1286 }
1287 if (!np_name->Equals(h_method_name.Get()) || !np_method->EqualParameters(h_args)) {
1288 if (UNLIKELY(self->IsExceptionPending())) {
1289 return nullptr;
1290 }
1291 continue;
1292 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01001293 DCHECK(!m.IsMiranda()); // Direct methods cannot be miranda methods.
1294 if ((modifiers & kAccSynthetic) == 0) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001295 return Method::CreateFromArtMethod<kPointerSize, kTransactionActive>(self, &m);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001296 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01001297 result = &m; // Remember as potential result.
Andreas Gampebc4d2182016-02-22 10:03:12 -08001298 }
1299 }
1300 return result != nullptr
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001301 ? Method::CreateFromArtMethod<kPointerSize, kTransactionActive>(self, result)
Andreas Gampebc4d2182016-02-22 10:03:12 -08001302 : nullptr;
1303}
1304
1305template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001306ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k32, false>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001307 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001308 ObjPtr<Class> klass,
1309 ObjPtr<String> name,
1310 ObjPtr<ObjectArray<Class>> args);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001311template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001312ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k32, true>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001313 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001314 ObjPtr<Class> klass,
1315 ObjPtr<String> name,
1316 ObjPtr<ObjectArray<Class>> args);
Andreas Gampee01e3642016-07-25 13:06:04 -07001317template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001318ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k64, false>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001319 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001320 ObjPtr<Class> klass,
1321 ObjPtr<String> name,
1322 ObjPtr<ObjectArray<Class>> args);
Andreas Gampee01e3642016-07-25 13:06:04 -07001323template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001324ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k64, true>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001325 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001326 ObjPtr<Class> klass,
1327 ObjPtr<String> name,
1328 ObjPtr<ObjectArray<Class>> args);
Andreas Gampebc4d2182016-02-22 10:03:12 -08001329
Andreas Gampe542451c2016-07-26 09:02:02 -07001330template <PointerSize kPointerSize, bool kTransactionActive>
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001331ObjPtr<Constructor> Class::GetDeclaredConstructorInternal(
Andreas Gampe6039e562016-04-05 18:18:43 -07001332 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001333 ObjPtr<Class> klass,
1334 ObjPtr<ObjectArray<Class>> args) {
Andreas Gampe6039e562016-04-05 18:18:43 -07001335 StackHandleScope<1> hs(self);
Andreas Gampee01e3642016-07-25 13:06:04 -07001336 ArtMethod* result = klass->GetDeclaredConstructor(self, hs.NewHandle(args), kPointerSize);
Andreas Gampe6039e562016-04-05 18:18:43 -07001337 return result != nullptr
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001338 ? Constructor::CreateFromArtMethod<kPointerSize, kTransactionActive>(self, result)
Andreas Gampe6039e562016-04-05 18:18:43 -07001339 : nullptr;
1340}
1341
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001342// Constructor::CreateFromArtMethod<kTransactionActive>(self, result)
Andreas Gampe6039e562016-04-05 18:18:43 -07001343
Andreas Gampe542451c2016-07-26 09:02:02 -07001344template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001345ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k32, false>(
Andreas Gampe6039e562016-04-05 18:18:43 -07001346 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001347 ObjPtr<Class> klass,
1348 ObjPtr<ObjectArray<Class>> args);
Andreas Gampe542451c2016-07-26 09:02:02 -07001349template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001350ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k32, true>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001351 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001352 ObjPtr<Class> klass,
1353 ObjPtr<ObjectArray<Class>> args);
Andreas Gampe542451c2016-07-26 09:02:02 -07001354template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001355ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k64, false>(
Andreas Gampee01e3642016-07-25 13:06:04 -07001356 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001357 ObjPtr<Class> klass,
1358 ObjPtr<ObjectArray<Class>> args);
Andreas Gampe542451c2016-07-26 09:02:02 -07001359template
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001360ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k64, true>(
Andreas Gampe6039e562016-04-05 18:18:43 -07001361 Thread* self,
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07001362 ObjPtr<Class> klass,
1363 ObjPtr<ObjectArray<Class>> args);
Andreas Gampe6039e562016-04-05 18:18:43 -07001364
Andreas Gampe715fdc22016-04-18 17:07:30 -07001365int32_t Class::GetInnerClassFlags(Handle<Class> h_this, int32_t default_value) {
1366 if (h_this->IsProxyClass() || h_this->GetDexCache() == nullptr) {
1367 return default_value;
1368 }
1369 uint32_t flags;
David Sehr9323e6e2016-09-13 08:58:35 -07001370 if (!annotations::GetInnerClassFlags(h_this, &flags)) {
Andreas Gampe715fdc22016-04-18 17:07:30 -07001371 return default_value;
1372 }
1373 return flags;
1374}
1375
Mathieu Chartier93bbee02016-08-31 09:38:40 -07001376void Class::SetObjectSizeAllocFastPath(uint32_t new_object_size) {
1377 if (Runtime::Current()->IsActiveTransaction()) {
1378 SetField32Volatile<true>(ObjectSizeAllocFastPathOffset(), new_object_size);
1379 } else {
1380 SetField32Volatile<false>(ObjectSizeAllocFastPathOffset(), new_object_size);
1381 }
1382}
1383
David Sehr709b0702016-10-13 09:12:37 -07001384std::string Class::PrettyDescriptor(ObjPtr<mirror::Class> klass) {
1385 if (klass == nullptr) {
1386 return "null";
1387 }
1388 return klass->PrettyDescriptor();
1389}
1390
1391std::string Class::PrettyDescriptor() {
1392 std::string temp;
1393 return art::PrettyDescriptor(GetDescriptor(&temp));
1394}
1395
1396std::string Class::PrettyClass(ObjPtr<mirror::Class> c) {
1397 if (c == nullptr) {
1398 return "null";
1399 }
1400 return c->PrettyClass();
1401}
1402
1403std::string Class::PrettyClass() {
1404 std::string result;
1405 result += "java.lang.Class<";
1406 result += PrettyDescriptor();
1407 result += ">";
1408 return result;
1409}
1410
1411std::string Class::PrettyClassAndClassLoader(ObjPtr<mirror::Class> c) {
1412 if (c == nullptr) {
1413 return "null";
1414 }
1415 return c->PrettyClassAndClassLoader();
1416}
1417
1418std::string Class::PrettyClassAndClassLoader() {
1419 std::string result;
1420 result += "java.lang.Class<";
1421 result += PrettyDescriptor();
1422 result += ",";
1423 result += mirror::Object::PrettyTypeOf(GetClassLoader());
1424 // TODO: add an identifying hash value for the loader
1425 result += ">";
1426 return result;
1427}
1428
Andreas Gampe90b936d2017-01-31 08:58:55 -08001429template<VerifyObjectFlags kVerifyFlags> void Class::GetAccessFlagsDCheck() {
1430 // Check class is loaded/retired or this is java.lang.String that has a
1431 // circularity issue during loading the names of its members
1432 DCHECK(IsIdxLoaded<kVerifyFlags>() || IsRetired<kVerifyFlags>() ||
1433 IsErroneous<static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis)>() ||
1434 this == String::GetJavaLangString())
1435 << "IsIdxLoaded=" << IsIdxLoaded<kVerifyFlags>()
1436 << " IsRetired=" << IsRetired<kVerifyFlags>()
1437 << " IsErroneous=" <<
1438 IsErroneous<static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis)>()
1439 << " IsString=" << (this == String::GetJavaLangString())
1440 << " status= " << GetStatus<kVerifyFlags>()
1441 << " descriptor=" << PrettyDescriptor();
1442}
1443// Instantiate the common cases.
1444template void Class::GetAccessFlagsDCheck<kVerifyNone>();
1445template void Class::GetAccessFlagsDCheck<kVerifyThis>();
1446template void Class::GetAccessFlagsDCheck<kVerifyReads>();
1447template void Class::GetAccessFlagsDCheck<kVerifyWrites>();
1448template void Class::GetAccessFlagsDCheck<kVerifyAll>();
1449
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001450} // namespace mirror
1451} // namespace art